From 09cf295554105a1a1cf0141720b2b3946cc0f6d9 Mon Sep 17 00:00:00 2001 From: Fabian Becker Date: Mon, 22 Jul 2013 15:37:52 +0200 Subject: [PATCH] Reformat all Code. --- src/eva2/gui/AboutDialog.java | 28 +- src/eva2/gui/BeanInspector.java | 29 +- src/eva2/gui/EvAModuleButtonPanelMaker.java | 10 +- src/eva2/gui/EvATabbedFrameMaker.java | 43 +- src/eva2/gui/EvATreeNode.java | 146 +- src/eva2/gui/EvATreeSelectionListener.java | 105 +- src/eva2/gui/Exp.java | 101 +- src/eva2/gui/ExtAction.java | 101 +- src/eva2/gui/ExtActionChangedListener.java | 43 +- src/eva2/gui/ExtDesktopManager.java | 3 +- src/eva2/gui/GOEPanel.java | 19 +- src/eva2/gui/HtmlDemo.java | 111 +- .../gui/InterfaceSelectablePointIcon.java | 19 +- src/eva2/gui/JDocFrame.java | 165 +- src/eva2/gui/JEFrame.java | 152 +- src/eva2/gui/JEFrameRegister.java | 1 + src/eva2/gui/JExtDesktopPane.java | 8 +- src/eva2/gui/JExtDesktopPaneToolBar.java | 22 +- src/eva2/gui/JExtFileChooser.java | 45 +- src/eva2/gui/JExtToolBar.java | 103 +- src/eva2/gui/JParaPanel.java | 20 +- src/eva2/gui/JTextEditorInternalFrame.java | 548 ++-- src/eva2/gui/JTextoutputFrame.java | 1 + src/eva2/gui/LoggingLevelLabel.java | 18 +- src/eva2/gui/LoggingPanel.java | 149 +- src/eva2/gui/Main.java | 40 +- src/eva2/gui/Mnemonic.java | 1 + src/eva2/gui/MultiLineString.java | 28 +- src/eva2/gui/PanelMaker.java | 4 +- src/eva2/gui/PropertyDialog.java | 3 +- src/eva2/gui/PropertyDoubleArray.java | 292 +- src/eva2/gui/PropertyEpsilonConstraint.java | 4 +- src/eva2/gui/PropertyEpsilonThreshold.java | 6 +- src/eva2/gui/PropertyFilePath.java | 51 +- src/eva2/gui/PropertyIntArray.java | 10 +- .../gui/PropertyOptimizationObjectives.java | 43 +- ...opertyOptimizationObjectivesWithParam.java | 91 +- src/eva2/gui/PropertyPanel.java | 107 +- src/eva2/gui/PropertySelectableList.java | 124 +- src/eva2/gui/PropertySheetPanel.java | 446 +-- src/eva2/gui/PropertySheetPanelStat.java | 129 +- src/eva2/gui/PropertySlider.java | 1 + src/eva2/gui/PropertyText.java | 1 - .../gui/PropertyWeightedLPTchebycheff.java | 8 +- src/eva2/gui/SplashScreen.java | 7 +- .../editor/AbstractListSelectionEditor.java | 105 +- src/eva2/gui/editor/BigStringEditor.java | 306 +- src/eva2/gui/editor/ComponentFilter.java | 3 +- src/eva2/gui/editor/EnumEditor.java | 132 +- src/eva2/gui/editor/GenericAreaEditor.java | 72 +- src/eva2/gui/editor/GenericArrayEditor.java | 25 +- .../gui/editor/GenericDoubleArrayEditor.java | 239 +- .../GenericEpsilonConstraintEditor.java | 133 +- .../editor/GenericEpsilonThresholdEditor.java | 143 +- .../gui/editor/GenericFilePathEditor.java | 74 +- .../gui/editor/GenericIntArrayEditor.java | 116 +- src/eva2/gui/editor/GenericObjectEditor.java | 23 +- .../GenericObjectListSelectionEditor.java | 68 +- .../GenericOptimizationObjectivesEditor.java | 232 +- ...OptimizationObjectivesWithParamEditor.java | 271 +- .../GenericWeigthedLPTchebycheffEditor.java | 152 +- .../gui/editor/MultiLineStringEditor.java | 131 +- src/eva2/gui/editor/StatisticsEditor.java | 154 +- .../gui/editor/StringSelectionEditor.java | 132 +- src/eva2/gui/editor/TagEditor.java | 207 +- src/eva2/gui/plot/DPointSetMultiIcon.java | 238 +- src/eva2/gui/plot/DataViewer.java | 5 +- src/eva2/gui/plot/DataViewerInterface.java | 5 +- src/eva2/gui/plot/FunctionArea.java | 176 +- src/eva2/gui/plot/Graph.java | 3 +- src/eva2/gui/plot/GraphPointSet.java | 1029 +++--- src/eva2/gui/plot/GraphPointSetLegend.java | 309 +- src/eva2/gui/plot/GraphWindow.java | 2 +- .../gui/plot/InterfaceDPointWithContent.java | 11 +- src/eva2/gui/plot/Plot.java | 6 +- src/eva2/gui/plot/PlotInterface.java | 50 +- src/eva2/gui/plot/TopoPlot.java | 258 +- src/eva2/gui/utils/CustomTabbedPaneUI.java | 22 +- src/eva2/gui/utils/VerticalButtonUI.java | 61 +- src/eva2/optimization/EvAMainAdapter.java | 4 +- src/eva2/optimization/EvAMainAdapterImpl.java | 6 +- src/eva2/optimization/ModuleServer.java | 6 +- .../OptimizationStateListener.java | 4 +- .../optimization/enums/BOAScoringMethods.java | 10 +- src/eva2/optimization/enums/DETypeEnum.java | 4 +- .../enums/ESMutationInitialSigma.java | 2 +- .../enums/MutateESCrossoverTypeEnum.java | 2 +- .../optimization/enums/PSOTopologyEnum.java | 106 +- .../optimization/enums/PostProcessMethod.java | 2 +- .../optimization/go/GOStandaloneVersion.java | 10 +- .../optimization/go/IndividualInterface.java | 94 +- .../go/InterfaceGOStandalone.java | 1 + .../go/InterfaceNotifyOnInformers.java | 9 +- .../go/InterfaceOptimizationParameters.java | 56 +- ...terfacePopulationChangedEventListener.java | 8 +- .../optimization/go/InterfaceProcessor.java | 1 + .../optimization/go/InterfaceTerminator.java | 28 +- src/eva2/optimization/go/MOCCOStandalone.java | 332 +- src/eva2/optimization/go/SwingWorker.java | 54 +- .../individuals/AbstractEAIndividual.java | 24 +- .../AbstractEAIndividualComparator.java | 373 +-- .../individuals/ESIndividualBinaryData.java | 145 +- .../individuals/ESIndividualDoubleData.java | 228 +- .../individuals/ESIndividualIntegerData.java | 160 +- .../ESIndividualPermutationData.java | 779 ++--- .../GAESIndividualBinaryDoubleData.java | 256 +- .../individuals/GAIndividualBinaryData.java | 138 +- .../individuals/GAIndividualDoubleData.java | 176 +- .../individuals/GAIndividualIntegerData.java | 220 +- .../individuals/GAPIndividualProgramData.java | 235 +- .../individuals/GEIndividualProgramData.java | 394 ++- .../individuals/GIIndividualIntegerData.java | 182 +- ...IOBGAIndividualIntegerPermutationData.java | 251 +- .../individuals/GPIndividualProgramData.java | 271 +- .../IndividualDistanceComparator.java | 62 +- .../IndividualWeightedFitnessComparator.java | 263 +- .../individuals/InterfaceDataTypeBinary.java | 33 +- .../individuals/InterfaceDataTypeDouble.java | 43 +- .../individuals/InterfaceDataTypeInteger.java | 45 +- .../InterfaceDataTypePermutation.java | 53 +- .../individuals/InterfaceDataTypeProgram.java | 45 +- .../individuals/InterfaceESIndividual.java | 17 +- .../individuals/InterfaceGAIndividual.java | 17 +- .../individuals/InterfaceGIIndividual.java | 39 +- .../individuals/InterfaceGPIndividual.java | 26 +- .../individuals/InterfaceOBGAIndividual.java | 28 +- .../OBGAIndividualPermutationData.java | 330 +- .../codings/ga/GAGrayCodingDouble.java | 103 +- .../codings/ga/GAGrayCodingInteger.java | 97 +- .../codings/ga/GAStandardCodingDouble.java | 191 +- .../codings/ga/GAStandardCodingInteger.java | 115 +- .../codings/ga/InterfaceGADoubleCoding.java | 26 +- .../codings/ga/InterfaceGAIntegerCoding.java | 34 +- .../codings/gp/AbstractGPNode.java | 740 +++-- .../individuals/codings/gp/GPArea.java | 133 +- .../individuals/codings/gp/GPNodeAbs.java | 31 +- .../individuals/codings/gp/GPNodeAdd.java | 26 +- .../individuals/codings/gp/GPNodeConst.java | 55 +- .../individuals/codings/gp/GPNodeCos.java | 28 +- .../individuals/codings/gp/GPNodeDiv.java | 48 +- .../individuals/codings/gp/GPNodeExp.java | 26 +- .../codings/gp/GPNodeFlowExec2.java | 28 +- .../codings/gp/GPNodeFlowExec3.java | 26 +- .../individuals/codings/gp/GPNodeInput.java | 64 +- .../individuals/codings/gp/GPNodeMult.java | 31 +- .../individuals/codings/gp/GPNodeNeg.java | 28 +- .../individuals/codings/gp/GPNodeOne.java | 14 +- .../individuals/codings/gp/GPNodeOutput.java | 45 +- .../individuals/codings/gp/GPNodePi.java | 20 +- .../individuals/codings/gp/GPNodePow2.java | 26 +- .../individuals/codings/gp/GPNodePow3.java | 26 +- .../individuals/codings/gp/GPNodeProd.java | 24 +- .../individuals/codings/gp/GPNodeSin.java | 26 +- .../individuals/codings/gp/GPNodeSqrt.java | 28 +- .../individuals/codings/gp/GPNodeSub.java | 28 +- .../individuals/codings/gp/GPNodeSum.java | 36 +- .../codings/gp/InterfaceProgram.java | 8 +- .../mocco/InterfaceProcessElement.java | 8 +- .../mocco/MOCCOChooseMOStrategy.java | 216 +- .../mocco/MOCCOChooseReferencePoint.java | 42 +- .../mocco/MOCCOChooseReferenceSolution.java | 69 +- .../mocco/MOCCOInitialPopulationSize.java | 20 +- .../mocco/MOCCOParameterizeGDF.java | 133 +- .../mocco/MOCCOParameterizeMO.java | 64 +- .../mocco/MOCCOParameterizeRefPoint.java | 137 +- .../mocco/MOCCOParameterizeSO.java | 60 +- .../mocco/MOCCOParameterizeSTEP.java | 200 +- .../mocco/MOCCOParameterizeTchebycheff.java | 182 +- src/eva2/optimization/mocco/MOCCOPhase.java | 54 +- .../mocco/MOCCOProblemInitialization.java | 40 +- .../mocco/MOCCOProblemRedefinition.java | 24 +- src/eva2/optimization/mocco/MOCCOState.java | 141 +- .../InterfaceParetoFrontView.java | 3 +- .../InterfaceRefPointListener.java | 8 +- .../InterfaceRefSolutionListener.java | 6 +- .../mocco/paretofrontviewer/MOCCOViewer.java | 305 +- .../paretofrontviewer/ParetoFrontView2D.java | 162 +- .../ParetoFrontViewParallelAxsis.java | 5 +- .../ParetoFrontViewScatterPlot.java | 174 +- .../modules/AbstractModuleAdapter.java | 14 +- .../AbstractOptimizationParameters.java | 381 +-- .../optimization/modules/DEParameters.java | 58 +- .../optimization/modules/EPParameters.java | 38 +- .../optimization/modules/GAParameters.java | 73 +- .../optimization/modules/GOModuleAdapter.java | 9 +- .../modules/GenericModuleAdapter.java | 74 +- .../optimization/modules/HCModuleAdapter.java | 2 +- .../optimization/modules/HCParameters.java | 24 +- .../optimization/modules/MCModuleAdapter.java | 2 +- .../optimization/modules/MCParameters.java | 32 +- .../modules/MOEAModuleAdapter.java | 2 +- .../optimization/modules/MOEAParameters.java | 82 +- .../optimization/modules/ModuleAdapter.java | 1 + .../modules/OptimizationParameters.java | 30 +- .../modules/PBILModuleAdapter.java | 2 +- .../optimization/modules/PBILParameters.java | 102 +- .../modules/PSOModuleAdapter.java | 2 +- .../optimization/modules/PSOParameters.java | 347 +- src/eva2/optimization/modules/Processor.java | 25 +- .../optimization/modules/SAModuleAdapter.java | 2 +- .../optimization/modules/SAParameters.java | 61 +- .../modules/SSGAModuleAdapter.java | 2 +- .../optimization/modules/SSGAParameters.java | 52 +- .../operator/archiving/AbstractArchiving.java | 102 +- .../archiving/ArchivingAllDominating.java | 30 +- .../operator/archiving/ArchivingMaxiMin.java | 66 +- .../operator/archiving/ArchivingNSGA.java | 42 +- .../operator/archiving/ArchivingNSGAII.java | 83 +- .../archiving/ArchivingNSGAIISMeasure.java | 154 +- .../operator/archiving/ArchivingPESAII.java | 92 +- .../operator/archiving/ArchivingSPEAII.java | 182 +- .../InformationRetrievalInserting.java | 22 +- .../archiving/InformationRetrievalNone.java | 18 +- .../InformationRetrievalReplacing.java | 20 +- .../archiving/InterfaceArchiving.java | 17 +- .../InterfaceInformationRetrieval.java | 13 +- .../InterfaceRemoveSurplusIndividuals.java | 13 +- ...oveSurplusIndividualsDynamicHyperCube.java | 39 +- .../RemoveSurplusIndividualsSMetric.java | 216 +- ...moveSurplusIndividualsStaticHyperCube.java | 31 +- .../ClassificationSelfOrganizingMaps.java | 327 +- .../InterfaceClassification.java | 29 +- .../operator/cluster/ClusterAll.java | 109 +- .../cluster/ClusteringDensityBased.java | 196 +- .../cluster/ClusteringDynPeakIdent.java | 381 +-- .../operator/cluster/ClusteringKMeans.java | 304 +- .../cluster/ClusteringNearestBetter.java | 674 ++-- .../operator/cluster/ClusteringXMeans.java | 225 +- .../operator/cluster/InterfaceClustering.java | 30 +- .../InterfaceClusteringDistanceParam.java | 8 +- .../InterfaceClusteringMetricBased.java | 4 +- .../constraint/AbstractConstraint.java | 438 ++- .../ConstBelongsToDifferentClass.java | 32 +- ...tObjectivesInEqualityBiggerThanLinear.java | 25 +- ...ObjectivesInEqualityBiggerThanSurface.java | 37 +- ...tObjectivesInEqualityLesserThanLinear.java | 25 +- ...bjectivesInEqualitySmallerThanSurface.java | 37 +- .../constraint/ConstraintCollection.java | 127 +- .../constraint/ConstraintHandlingEnum.java | 2 +- .../constraint/ConstraintRelationEnum.java | 2 +- .../operator/constraint/DummyConstraint.java | 32 +- .../constraint/GenericConstraint.java | 205 +- .../constraint/ImplicitConstraint.java | 89 +- .../constraint/InterfaceConstraint.java | 13 +- .../constraint/InterfaceDoubleConstraint.java | 13 +- .../constraint/IntervalConstraint.java | 230 +- .../crossover/AdaptiveCrossoverEAMixer.java | 164 +- .../optimization/operator/crossover/CM1.java | 101 +- .../optimization/operator/crossover/CM2.java | 99 +- .../optimization/operator/crossover/CM3.java | 119 +- .../optimization/operator/crossover/CM4.java | 123 +- .../optimization/operator/crossover/CM5.java | 93 +- .../optimization/operator/crossover/CM6.java | 101 +- .../optimization/operator/crossover/CM7.java | 169 +- .../operator/crossover/CrossoverEAMixer.java | 228 +- .../crossover/CrossoverESArithmetical.java | 84 +- .../crossover/CrossoverESBLXAlpha.java | 94 +- .../crossover/CrossoverESDefault.java | 87 +- .../operator/crossover/CrossoverESFlat.java | 80 +- .../crossover/CrossoverESIntermediate.java | 74 +- .../crossover/CrossoverESNPointDiscrete.java | 87 +- .../CrossoverESNPointDiscreteDislocation.java | 88 +- .../operator/crossover/CrossoverESPCX.java | 145 +- .../operator/crossover/CrossoverESSBX.java | 127 +- .../operator/crossover/CrossoverESSPX.java | 130 +- .../operator/crossover/CrossoverESUNDX.java | 194 +- .../crossover/CrossoverESUniformDiscrete.java | 73 +- .../crossover/CrossoverGABitSimulated.java | 72 +- .../crossover/CrossoverGADefault.java | 254 +- .../crossover/CrossoverGAGINPoint.java | 207 +- .../CrossoverGAGINPointSegmentwise.java | 103 +- .../crossover/CrossoverGAUniform.java | 70 +- .../crossover/CrossoverGIDefault.java | 90 +- .../operator/crossover/CrossoverGINPoint.java | 82 +- .../crossover/CrossoverGINPointVL.java | 121 +- .../crossover/CrossoverGIUniform.java | 69 +- .../crossover/CrossoverGPDefault.java | 138 +- .../operator/crossover/CrossoverOBGAPMX.java | 109 +- .../crossover/CrossoverOBGAPMXUniform.java | 95 +- .../crossover/InterfaceCrossover.java | 30 +- .../InterfaceEvaluatingCrossoverOperator.java | 16 +- .../operator/crossover/NoCrossover.java | 44 +- .../crossover/PropertyCrossoverMixer.java | 88 +- .../PropertyCrossoverMixerEditor.java | 277 +- .../operator/crossover/TestESCrossover.java | 91 +- .../distancemetric/DoubleIntegralMetric.java | 114 +- .../distancemetric/EuclideanMetric.java | 149 +- .../distancemetric/GenotypeMetricBitSet.java | 36 +- .../distancemetric/IndividualDataMetric.java | 146 +- .../InterfaceDistanceMetric.java | 15 +- .../distancemetric/ObjectiveSpaceMetric.java | 24 +- .../distancemetric/PhenotypeMetric.java | 160 +- .../SigmaSingleMetricGlobalMutation.java | 32 +- .../FitnessAdaptiveClustering.java | 40 +- .../fitnessmodifier/FitnessModifierNone.java | 14 +- .../fitnessmodifier/FitnessSharing.java | 44 +- .../InterfaceFitnessModifier.java | 6 +- .../initialization/DefaultInitialization.java | 42 +- .../GAGIInitializeSegmentwise.java | 534 ++-- .../InterfaceInitialization.java | 32 +- .../migration/InterfaceMigration.java | 12 +- .../operator/migration/MOBestMigration.java | 59 +- .../migration/MOClusteringSeparation.java | 126 +- .../operator/migration/MOConeSeparation.java | 374 ++- .../migration/MOXMeansSeparation.java | 116 +- .../operator/migration/SOBestMigration.java | 58 +- .../operator/migration/SOMONoMigration.java | 21 +- .../operator/moso/InterfaceMOSOConverter.java | 33 +- .../moso/MOSODynamicallyWeightedFitness.java | 69 +- .../operator/moso/MOSOEpsilonConstraint.java | 53 +- .../operator/moso/MOSOEpsilonThreshold.java | 53 +- .../operator/moso/MOSOGoalProgramming.java | 58 +- .../operator/moso/MOSOLpMetric.java | 72 +- .../operator/moso/MOSOMOGARankBased.java | 48 +- .../operator/moso/MOSOMaxiMin.java | 70 +- .../operator/moso/MOSONoConvert.java | 42 +- .../operator/moso/MOSORandomChoice.java | 53 +- .../operator/moso/MOSORandomWeight.java | 52 +- .../operator/moso/MOSORankbased.java | 44 +- .../operator/moso/MOSOUtilityFunction.java | 48 +- .../operator/moso/MOSOWeightedFitness.java | 76 +- .../moso/MOSOWeightedLPTchebycheff.java | 75 +- .../operator/mutation/CMAParamSet.java | 397 +-- .../InterfaceAdaptOperatorGenerational.java | 51 +- .../operator/mutation/InterfaceMutation.java | 36 +- .../operator/mutation/MutateDefault.java | 57 +- .../operator/mutation/MutateEAMixer.java | 149 +- .../operator/mutation/MutateESCorrVector.java | 238 +- .../operator/mutation/MutateESCorrolated.java | 241 +- .../MutateESCovarianceMatrixAdaption.java | 264 +- .../MutateESCovarianceMatrixAdaptionPlus.java | 407 ++- .../mutation/MutateESFixedStepSize.java | 79 +- .../operator/mutation/MutateESGlobal.java | 206 +- .../operator/mutation/MutateESLocal.java | 204 +- .../mutation/MutateESMainVectorAdaption.java | 198 +- .../MutateESMutativeStepSizeControl.java | 142 +- .../mutation/MutateESPathLengthAdaption.java | 181 +- .../operator/mutation/MutateESPolynomial.java | 91 +- .../operator/mutation/MutateESRankMuCMA.java | 1366 ++++---- .../mutation/MutateESSuccessRule.java | 112 +- .../operator/mutation/MutateGAAdaptive.java | 99 +- .../operator/mutation/MutateGAGISwapBits.java | 436 +-- .../MutateGAGISwapBitsSegmentwise.java | 122 +- .../operator/mutation/MutateGAInvertBits.java | 15 +- .../operator/mutation/MutateGANBit.java | 12 +- .../mutation/MutateGAShiftSubstring.java | 227 +- .../mutation/MutateGASwapBitsSegmentwise.java | 332 +- .../operator/mutation/MutateGAUniform.java | 169 +- .../mutation/MutateGIInsertDelete.java | 127 +- .../operator/mutation/MutateGIInvert.java | 85 +- .../operator/mutation/MutateGINominal.java | 75 +- .../operator/mutation/MutateGIOrdinal.java | 94 +- .../operator/mutation/MutateGISubset.java | 294 +- .../mutation/MutateGITranslocate.java | 182 +- .../operator/mutation/MutateGPAdaptive.java | 100 +- .../operator/mutation/MutateGPSingleNode.java | 61 +- .../operator/mutation/MutateOBGAFlip.java | 92 +- .../mutation/MutateOBGAInversion.java | 57 +- .../operator/mutation/NoMutation.java | 4 +- .../mutation/PropertyMutationMixer.java | 91 +- .../mutation/PropertyMutationMixerEditor.java | 269 +- .../ConsiderPBestAbsorptionStrategy.java | 69 +- .../EuclideanDiversityAbsorptionStrategy.java | 129 +- .../InterfaceAbsorptionStrategy.java | 46 +- .../StandardAbsorptionStrategy.java | 126 +- .../DummyDeactivationStrategy.java | 23 +- .../ImprovementDeactivationStrategy.java | 273 +- .../InterfaceDeactivationStrategy.java | 34 +- .../StandardDeactivationStrategy.java | 244 +- .../merging/InterfaceMergingStrategy.java | 55 +- .../merging/ScatterMergingStrategy.java | 154 +- .../merging/StandardMergingStrategy.java | 256 +- .../DummySubswarmCreationStrategy.java | 30 +- ...erateNeighborSubswarmCreationStrategy.java | 153 +- .../InterfaceSubswarmCreationStrategy.java | 46 +- .../StandardSubswarmCreationStrategy.java | 198 +- .../AbstractLinearParamAdaption.java | 111 +- .../AbstractParameterControl.java | 145 +- .../CbpsoFitnessThresholdBasedAdaption.java | 298 +- .../paramcontrol/ConstantParameters.java | 55 +- .../paramcontrol/ConstraintBasedAdaption.java | 338 +- .../ExponentialDecayAdaption.java | 184 +- .../paramcontrol/GenericParamAdaption.java | 16 +- .../InterfaceHasUpperDoubleBound.java | 8 +- .../InterfaceParamControllable.java | 13 +- .../InterfaceParameterControl.java | 82 +- .../paramcontrol/LinearParamAdaption.java | 142 +- .../paramcontrol/NoParamAdaption.java | 40 +- .../PSOActivityFeedbackControl.java | 288 +- .../paramcontrol/PSOInertnessAdaption.java | 40 +- .../operator/paramcontrol/ParamAdaption.java | 36 +- .../paramcontrol/ParamChangeListener.java | 2 +- .../paramcontrol/ParameterControlManager.java | 389 ++- .../paramcontrol/SinusoidalParamAdaption.java | 302 +- .../paramcontrol/SuccessBasedAdaption.java | 169 +- .../InterfaceParetoFrontMetric.java | 10 +- .../MetricD1ApproxParetoFront.java | 69 +- .../MetricD1TrueParetoFront.java | 71 +- .../paretofrontmetrics/MetricErrorRatio.java | 83 +- .../MetricMaximumParetoFrontError.java | 67 +- .../MetricOverallNonDominatedVectors.java | 30 +- .../operator/paretofrontmetrics/MetricS.java | 106 +- .../MetricSWithReference.java | 135 +- .../InterfacePostProcessParams.java | 50 +- .../operator/postprocess/PostProcess.java | 2393 +++++++------- .../postprocess/PostProcessParams.java | 377 +-- .../postprocess/SolutionHistogram.java | 338 +- .../selection/InterfaceSelection.java | 39 +- .../selection/MOMultipleSolutions.java | 12 +- .../operator/selection/MOSolution.java | 6 +- .../operator/selection/SelectAll.java | 53 +- .../selection/SelectBestIndividuals.java | 102 +- .../operator/selection/SelectBestSingle.java | 128 +- .../selection/SelectEPTournaments.java | 115 +- .../selection/SelectHomologousMate.java | 54 +- .../SelectMOMAIIDominanceCounter.java | 80 +- .../operator/selection/SelectMOMaxiMin.java | 72 +- .../SelectMONSGAIICrowedTournament.java | 103 +- .../selection/SelectMONonDominated.java | 78 +- .../operator/selection/SelectMOPESA.java | 75 +- .../operator/selection/SelectMOPESAII.java | 103 +- .../operator/selection/SelectMOSPEAII.java | 85 +- .../selection/SelectParticleWheel.java | 204 +- .../operator/selection/SelectRandom.java | 89 +- .../operator/selection/SelectTournament.java | 82 +- .../selection/SelectXProbRouletteWheel.java | 133 +- .../probability/AbstractSelProb.java | 92 +- .../InterfaceSelectionProbability.java | 43 +- .../probability/SelProbBoltzman.java | 162 +- .../probability/SelProbFitnessSharing.java | 78 +- .../probability/SelProbInvertByMax.java | 207 +- .../probability/SelProbLinearRanking.java | 140 +- .../probability/SelProbNonLinearRanking.java | 144 +- .../selection/probability/SelProbRanking.java | 40 +- .../probability/SelProbStandard.java | 55 +- .../probability/SelProbStandardScaling.java | 80 +- .../replacement/InterfaceReplacement.java | 18 +- .../ReplaceDeterministicCrowding.java | 37 +- .../replacement/ReplacePreselection.java | 25 +- .../selection/replacement/ReplaceRandom.java | 27 +- .../selection/replacement/ReplaceWorst.java | 25 +- .../replacement/ReplaceWorstParent.java | 25 +- .../replacement/ReplacementCrowding.java | 54 +- ...ntNondominatedSortingDistanceCrowding.java | 117 +- .../terminators/CombinedTerminator.java | 310 +- .../terminators/DiversityTerminator.java | 127 +- .../terminators/EvaluationTerminator.java | 126 +- .../FitnessConvergenceTerminator.java | 59 +- .../terminators/FitnessValueTerminator.java | 142 +- .../terminators/GenerationTerminator.java | 2 + .../HistoryConvergenceTerminator.java | 230 +- .../KnownOptimaFoundTerminator.java | 128 +- .../terminators/ParetoMetricTerminator.java | 180 +- .../PhenotypeConvergenceTerminator.java | 90 +- .../PopulationArchiveTerminator.java | 79 +- .../PopulationMeasureTerminator.java | 513 +-- .../population/InterfaceSolutionSet.java | 11 +- .../population/PBILPopulation.java | 81 +- .../optimization/population/Population.java | 169 +- .../population/PopulationInitMethod.java | 2 +- .../population/PopulationInterface.java | 9 +- .../optimization/population/SolutionSet.java | 60 +- .../problems/AbstractDynTransProblem.java | 310 +- .../AbstractDynamicOptimizationProblem.java | 469 +-- .../AbstractMultiModalProblemKnown.java | 666 ++-- ...ractMultiObjectiveOptimizationProblem.java | 555 ++-- .../problems/AbstractOptimizationProblem.java | 669 ++-- .../AbstractParallelOptimizationProblem.java | 38 +- .../problems/AbstractProblemBinary.java | 130 +- .../problems/AbstractProblemDouble.java | 1038 +++--- .../problems/AbstractProblemDoubleOffset.java | 55 +- .../problems/AbstractProblemInteger.java | 87 +- ...bstractSynchronousOptimizationProblem.java | 228 +- src/eva2/optimization/problems/B1Problem.java | 67 +- .../problems/BKnapsackProblem.java | 389 ++- .../problems/ConstrHimmelblauProblem.java | 127 +- .../problems/ConstrPressureVessel.java | 189 +- .../optimization/problems/DynJumpProblem.java | 446 +-- .../optimization/problems/ERPStarter.java | 292 +- .../problems/ExternalRuntimeProblem.java | 559 ++-- .../optimization/problems/F10Problem.java | 81 +- .../optimization/problems/F11Problem.java | 52 +- .../optimization/problems/F12Problem.java | 41 +- .../optimization/problems/F13Problem.java | 103 +- .../optimization/problems/F14Problem.java | 72 +- .../optimization/problems/F15Problem.java | 123 +- .../optimization/problems/F16Problem.java | 120 +- .../optimization/problems/F17Problem.java | 114 +- .../optimization/problems/F18Problem.java | 114 +- .../optimization/problems/F19Problem.java | 256 +- src/eva2/optimization/problems/F1Problem.java | 105 +- .../optimization/problems/F20Problem.java | 176 +- .../optimization/problems/F21Problem.java | 182 +- src/eva2/optimization/problems/F2Problem.java | 108 +- src/eva2/optimization/problems/F3Problem.java | 39 +- src/eva2/optimization/problems/F4Problem.java | 41 +- src/eva2/optimization/problems/F5Problem.java | 43 +- src/eva2/optimization/problems/F6Problem.java | 145 +- src/eva2/optimization/problems/F7Problem.java | 94 +- src/eva2/optimization/problems/F8Problem.java | 360 ++- src/eva2/optimization/problems/F9Problem.java | 35 +- .../optimization/problems/FLensProblem.java | 747 +++-- .../optimization/problems/FM0Problem.java | 63 +- .../problems/GPFunctionProblem.java | 244 +- src/eva2/optimization/problems/I1Problem.java | 48 +- .../problems/Interface2DBorderProblem.java | 16 +- ...InterfaceAdditionalPopulationInformer.java | 45 +- .../InterfaceFirstOrderDerivableProblem.java | 20 +- .../problems/InterfaceHasInitRange.java | 21 +- .../problems/InterfaceHasSolutionViewer.java | 5 +- .../InterfaceInterestingHistogram.java | 19 +- .../problems/InterfaceLocalSearchable.java | 25 +- .../InterfaceMultiObjectiveDeNovoProblem.java | 14 +- .../problems/InterfaceMultimodalProblem.java | 1 - .../InterfaceMultimodalProblemKnown.java | 29 +- .../InterfaceOptimizationObjective.java | 27 +- .../InterfaceOptimizationProblem.java | 61 +- .../problems/InterfaceOptimizationTarget.java | 4 +- .../problems/InterfaceProblemDouble.java | 63 +- .../problems/InterfaceProgramProblem.java | 17 +- .../problems/InterfaceSolutionViewer.java | 17 +- .../problems/MatlabEvalMediator.java | 472 +-- .../problems/MatlabProblemDataTypeEnum.java | 2 +- .../problems/PSymbolicRegression.java | 685 ++-- .../problems/SimpleProblemWrapper.java | 437 +-- .../optimization/problems/TF1Problem.java | 228 +- .../problems/WaitForEvARunnable.java | 105 +- .../InterfaceRegressionFunction.java | 10 +- .../problems/regression/RFKoza_GPI_10_1.java | 16 +- .../problems/regression/RFKoza_GPI_10_2.java | 16 +- .../problems/regression/RFKoza_GPI_7_3.java | 16 +- .../regression/RFKoza_GPI_7_3_extended.java | 16 +- .../problems/regression/RFRaidl_F1.java | 14 +- .../problems/regression/RFRaidl_F2.java | 16 +- .../problems/regression/RFRaidl_F3.java | 16 +- .../stat/EvAStatisticalEvaluationParams.java | 96 +- .../optimization/stat/GenericStatistics.java | 2 + .../optimization/stat/GraphSelectionEnum.java | 106 +- .../stat/InterfaceStatistics.java | 54 +- .../stat/InterfaceStatisticsListener.java | 97 +- .../stat/InterfaceStatisticsParameter.java | 96 +- .../stat/InterfaceTextListener.java | 8 +- src/eva2/optimization/stat/MovingAverage.java | 111 +- .../optimization/stat/OptimizationJob.java | 467 +-- .../stat/OptimizationJobList.java | 2 +- .../optimization/stat/StatisticsDummy.java | 197 +- .../stat/StatisticsParameter.java | 11 +- .../stat/StatisticsStandalone.java | 200 +- .../optimization/stat/StatisticsWithGUI.java | 6 +- .../stat/StatsOnSingleDataSetEnum.java | 10 +- .../stat/StatsOnTwoSampledDataEnum.java | 16 +- src/eva2/optimization/strategies/ANPSO.java | 1781 ++++++----- src/eva2/optimization/strategies/BOA.java | 20 +- .../strategies/BinaryScatterSearch.java | 125 +- src/eva2/optimization/strategies/CBNPSO.java | 447 +-- .../CHCAdaptiveSearchAlgorithm.java | 6 +- .../strategies/ClusterBasedNichingEA.java | 71 +- .../strategies/ClusteringHillClimbing.java | 8 +- .../strategies/DifferentialEvolution.java | 26 +- .../DynamicParticleSwarmOptimization.java | 1006 +++--- .../optimization/strategies/EsDpiNiching.java | 47 +- .../strategies/EsDpiNichingCma.java | 80 +- .../strategies/EvolutionStrategies.java | 4 +- .../strategies/EvolutionStrategyIPOP.java | 627 ++-- .../strategies/EvolutionaryProgramming.java | 2 +- .../strategies/GradientDescentAlgorithm.java | 5 +- .../optimization/strategies/HillClimbing.java | 3 +- .../strategies/InterfaceOptimizer.java | 72 +- .../strategies/InterfaceSpeciesAware.java | 42 +- .../strategies/IslandModelEA.java | 8 +- src/eva2/optimization/strategies/LTGA.java | 25 +- src/eva2/optimization/strategies/MLTGA.java | 5 +- .../strategies/MemeticAlgorithm.java | 2 + .../strategies/MonteCarloSearch.java | 4 +- .../strategies/MultiObjectiveCMAES.java | 7 +- .../strategies/MultiObjectiveEA.java | 4 +- .../strategies/NelderMeadSimplex.java | 21 +- .../optimization/strategies/NicheGraph.java | 199 +- .../optimization/strategies/NichePSO.java | 129 +- .../strategies/PDDifferentialEvolution.java | 22 +- .../ParticleFilterOptimization.java | 12 +- .../ParticleSubSwarmOptimization.java | 1366 ++++---- .../strategies/ParticleSwarmOptimization.java | 107 +- .../ParticleSwarmOptimizationGCPSO.java | 474 +-- .../PopulationBasedIncrementalLearning.java | 6 +- .../strategies/ScatterSearch.java | 18 +- .../strategies/SimulatedAnnealing.java | 2 +- src/eva2/optimization/strategies/SqPSO.java | 53 +- .../optimization/strategies/StarANPSO.java | 48 +- .../strategies/ThresholdAlgorithm.java | 2 +- src/eva2/optimization/strategies/Tribes.java | 23 +- .../strategies/WingedMultiObjectiveEA.java | 3 +- .../optimization/strategies/tribes/Tribe.java | 355 +- .../strategies/tribes/TribesExplorer.java | 629 ++-- .../strategies/tribes/TribesMemory.java | 45 +- .../strategies/tribes/TribesParam.java | 18 +- .../strategies/tribes/TribesPosition.java | 156 +- .../strategies/tribes/TribesSwarm.java | 469 +-- .../tools/AbstractObjectEditor.java | 237 +- src/eva2/optimization/tools/DeNovofilter.java | 20 +- .../tools/DoubleArrayComparator.java | 102 +- src/eva2/optimization/tools/FileTools.java | 433 +-- src/eva2/optimization/tools/GONamingBox.java | 124 +- .../optimization/tools/GeneralGEOFaker.java | 66 +- .../tools/GeneralGOEProperty.java | 20 +- .../GeneralGenericObjectEditorPanel.java | 254 +- .../tools/ImpactOfDimensionOnMOEAs.java | 56 +- .../tools/ParetoFrontLocalTester.java | 42 +- .../tools/PortfolioFrontTester.java | 117 +- src/eva2/optimization/tools/TestingDArea.java | 1 + src/eva2/tools/BasicResourceLoader.java | 682 ++-- src/eva2/tools/Cluster.java | 54 +- src/eva2/tools/CubicSpline.java | 372 ++- src/eva2/tools/EVAERROR.java | 93 +- src/eva2/tools/EVAHELP.java | 231 +- src/eva2/tools/JPasswordDialog.java | 61 +- src/eva2/tools/JarResources.java | 294 +- src/eva2/tools/KMEANSJAVA.java | 265 +- src/eva2/tools/MultirunRefiner.java | 330 +- src/eva2/tools/Pair.java | 216 +- src/eva2/tools/PairComparator.java | 77 +- src/eva2/tools/ReflectPackage.java | 1045 +++--- src/eva2/tools/ResourceLoader.java | 13 +- src/eva2/tools/SelectedTag.java | 364 +-- src/eva2/tools/SerializedObject.java | 224 +- src/eva2/tools/Serializer.java | 19 +- src/eva2/tools/StringSelection.java | 14 +- src/eva2/tools/StringTools.java | 704 ++-- src/eva2/tools/TXTFileFilter.java | 25 +- src/eva2/tools/Tag.java | 59 +- src/eva2/tools/ToolBox.java | 213 +- src/eva2/tools/ToolBoxGui.java | 83 +- src/eva2/tools/URLGetter.java | 59 +- .../Chart2DDPointContentSelectable.java | 61 +- .../chart2d/Chart2DDPointIconCircle.java | 14 +- .../chart2d/Chart2DDPointIconContent.java | 30 +- .../tools/chart2d/Chart2DDPointIconCross.java | 8 +- .../tools/chart2d/Chart2DDPointIconPoint.java | 14 +- .../tools/chart2d/Chart2DDPointIconText.java | 24 +- src/eva2/tools/chart2d/DArea.java | 1527 +++++---- src/eva2/tools/chart2d/DArray.java | 494 +-- src/eva2/tools/chart2d/DBorder.java | 68 +- src/eva2/tools/chart2d/DComponent.java | 253 +- src/eva2/tools/chart2d/DContainer.java | 420 +-- src/eva2/tools/chart2d/DElement.java | 35 +- src/eva2/tools/chart2d/DFunction.java | 71 +- src/eva2/tools/chart2d/DGrid.java | 181 +- src/eva2/tools/chart2d/DIntDoubleMap.java | 134 +- src/eva2/tools/chart2d/DLine.java | 100 +- src/eva2/tools/chart2d/DMeasures.java | 474 +-- src/eva2/tools/chart2d/DParent.java | 23 +- src/eva2/tools/chart2d/DPoint.java | 146 +- src/eva2/tools/chart2d/DPointIcon.java | 25 +- src/eva2/tools/chart2d/DPointSet.java | 629 ++-- src/eva2/tools/chart2d/DRectangle.java | 634 ++-- src/eva2/tools/chart2d/ScaledBorder.java | 1214 +++---- src/eva2/tools/chart2d/SlimRect.java | 257 +- .../tools/diagram/ColorBarCalculator.java | 173 +- src/eva2/tools/math/BayNet.java | 1790 ++++++----- src/eva2/tools/math/BayNode.java | 207 +- .../math/Jama/CholeskyDecomposition.java | 297 +- .../math/Jama/EigenvalueDecomposition.java | 1549 ++++----- src/eva2/tools/math/Jama/LUDecomposition.java | 431 +-- src/eva2/tools/math/Jama/Matrix.java | 2603 ++++++++------- src/eva2/tools/math/Jama/QRDecomposition.java | 372 ++- .../math/Jama/SingularValueDecomposition.java | 976 +++--- src/eva2/tools/math/Jama/util/Maths.java | 34 +- src/eva2/tools/math/Mathematics.java | 2668 ++++++++------- src/eva2/tools/math/RNG.java | 15 +- src/eva2/tools/math/SpecialFunction.java | 2219 +++++++------ src/eva2/tools/math/StatisticUtils.java | 1031 +++--- .../interpolation/AbstractDataModifier.java | 31 +- .../math/interpolation/AbstractDataSet.java | 158 +- .../math/interpolation/BasicDataSet.java | 73 +- .../interpolation/InterpolationException.java | 18 +- .../interpolation/LinearInterpolation.java | 950 +++--- .../math/interpolation/PolyInterpolation.java | 787 +++-- .../PolynomialInterpolationResult.java | 29 +- .../interpolation/SplineInterpolation.java | 506 ++- src/eva2/tools/matlab/JMatLink.java | 2847 +++++++++-------- src/eva2/tools/print/PagePrinter.java | 253 +- 681 files changed, 57140 insertions(+), 51465 deletions(-) diff --git a/src/eva2/gui/AboutDialog.java b/src/eva2/gui/AboutDialog.java index 368e0b22..209a9a21 100644 --- a/src/eva2/gui/AboutDialog.java +++ b/src/eva2/gui/AboutDialog.java @@ -5,6 +5,7 @@ package eva2.gui; import eva2.tools.BasicResourceLoader; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -13,24 +14,23 @@ import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; /** - * * @author becker */ public class AboutDialog extends JDialog { private JLabel imageLabel; private JEditorPane infoEditorPane; private JTextArea aboutTextArea; - + public AboutDialog(Frame parent) { super(parent); initComponents(); } - + private void initComponents() { setTitle("About"); setLayout(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); - + setSize(new Dimension(470, 600)); setResizable(false); @@ -41,19 +41,19 @@ public class AboutDialog extends JDialog { /* Create a new JLabel with the image */ imageLabel = new JLabel(imageIcon); - + gbConstraints.gridx = 0; gbConstraints.gridy = 0; gbConstraints.ipady = 10; gbConstraints.insets = new Insets(10, 10, 0, 10); gbConstraints.anchor = GridBagConstraints.PAGE_START; add(imageLabel, gbConstraints); - + String infoMessage = "" - +"

EvA2 (an Evolutionary Algorithms framework, revised version 2) is a comprehensive heuristic optimization framework with emphasis on Evolutionary Algorithms implemented in Java™.

" -+"

For more information, please visit the EvA2 Homepage.

" -+""; - + + "

EvA2 (an Evolutionary Algorithms framework, revised version 2) is a comprehensive heuristic optimization framework with emphasis on Evolutionary Algorithms implemented in Java™.

" + + "

For more information, please visit the EvA2 Homepage.

" + + ""; + infoEditorPane = new JEditorPane("text/html", infoMessage); infoEditorPane.setEditable(false); infoEditorPane.setOpaque(false); @@ -74,10 +74,10 @@ public class AboutDialog extends JDialog { gbConstraints.gridy++; gbConstraints.anchor = GridBagConstraints.CENTER; gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.weightx = 1.0; + gbConstraints.weightx = 1.0; add(infoEditorPane, gbConstraints); - - aboutTextArea = new JTextArea(); + + aboutTextArea = new JTextArea(); aboutTextArea.setEditable(false); aboutTextArea.setRows(8); @@ -93,7 +93,7 @@ public class AboutDialog extends JDialog { public void actionPerformed(ActionEvent e) { AboutDialog.this.dispose(); } - + }); gbConstraints.gridy++; gbConstraints.fill = GridBagConstraints.NONE; diff --git a/src/eva2/gui/BeanInspector.java b/src/eva2/gui/BeanInspector.java index 32bfadc6..cbd43db2 100644 --- a/src/eva2/gui/BeanInspector.java +++ b/src/eva2/gui/BeanInspector.java @@ -6,6 +6,7 @@ import eva2.tools.Pair; import eva2.tools.SelectedTag; import eva2.tools.StringTools; import eva2.tools.Tag; + import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; @@ -23,7 +24,6 @@ import java.util.logging.Logger; * generic display. * * @author mkron, Holger Ulmer, Felix Streichert, Hannes Planatscher - * */ public class BeanInspector { private static final Logger LOGGER = Logger.getLogger(BeanInspector.class.getName()); @@ -108,9 +108,9 @@ public class BeanInspector { /** * Produce a String representation of an arbitrary object. * - * @see #toString(Object, char, boolean, String) * @param obj * @return + * @see #toString(Object, char, boolean, String) */ public static String toString(Object obj) { return toString(obj, ';', false, "", 1, false); @@ -475,7 +475,7 @@ public class BeanInspector { * * @param obj * @param mName the method name - * @param args the arguments, null allowed if the method takes no parameters + * @param args the arguments, null allowed if the method takes no parameters * @return the method or null if it isn't found */ public static Method hasMethod(Object obj, String mName, Object[] args) { @@ -487,9 +487,9 @@ public class BeanInspector { * parameter signature. Return it if found, or null if not. * * @param obj - * @param mName the method name + * @param mName the method name * @param paramTypes the parameter types, null allowed if no parameters are - * expected + * expected * @return the method or null if it isn't found */ public static Method hasMethod(Object obj, String mName, Class[] paramTypes) { @@ -574,7 +574,6 @@ public class BeanInspector { /** * For a Java primitive wrapper class return the corresponding primitive * class. - * */ public static Class getUnboxedType(Class cls) { if (cls == Double.class) { @@ -604,8 +603,8 @@ public class BeanInspector { * Just concatenates getClassDescription(obj) and getMemberDescriptions(obj, * withValues). * - * @param obj target object - * @param withValues if true, member values are displayed as well + * @param obj target object + * @param withValues if true, member values are displayed as well * @return an info string about class and members of the given object */ public static String getDescription(Object obj, boolean withValues) { @@ -651,8 +650,8 @@ public class BeanInspector { * member property is normal or hidden, meaning it may have effect depending * on settings of other members only, for instance. * - * @param obj target object - * @param withValues if true, member values are displayed as well + * @param obj target object + * @param withValues if true, member values are displayed as well * @return an info string about class and members of the given object */ public static String[] getMemberDescriptions(Object obj, boolean withValues) { @@ -741,7 +740,7 @@ public class BeanInspector { System.err.println("Skipping property " + name + " ; exception: " + ex.getMessage()); ex.printStackTrace(); } // end try - } // end for + } // end for return memberInfoList.toArray(new String[1]); } @@ -1018,9 +1017,9 @@ public class BeanInspector { /** * This method simply looks for an appropriate tiptext * - * @param name The name of the property + * @param name The name of the property * @param methods A list of methods to search. - * @param target The target object + * @param target The target object * @return String for the ToolTip. */ public static String getToolTipText(String name, MethodDescriptor[] methods, Object target, boolean stripToolTipToFirstPoint, int toHTMLLen) { @@ -1057,9 +1056,9 @@ public class BeanInspector { /** * This method simply looks for an appropriate tool tip text * - * @param name The name of the property + * @param name The name of the property * @param methods A list of methods to search. - * @param target The target object + * @param target The target object * @return String for the ToolTip. */ public static String getToolTipText(String name, MethodDescriptor[] methods, Object target) { diff --git a/src/eva2/gui/EvAModuleButtonPanelMaker.java b/src/eva2/gui/EvAModuleButtonPanelMaker.java index 189e6ead..c848332d 100644 --- a/src/eva2/gui/EvAModuleButtonPanelMaker.java +++ b/src/eva2/gui/EvAModuleButtonPanelMaker.java @@ -9,10 +9,12 @@ package eva2.gui; * $Date: 2007-11-27 14:37:05 +0100 (Tue, 27 Nov 2007) $ * $Author: mkron $ */ + import eva2.optimization.OptimizationStateListener; import eva2.optimization.modules.ModuleAdapter; import eva2.optimization.stat.OptimizationJob; import eva2.tools.ToolBoxGui; + import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; @@ -53,9 +55,9 @@ public class EvAModuleButtonPanelMaker implements OptimizationStateListener, Ser public JToolBar makePanel() { toolBar = new JToolBar(); toolBar.setFloatable(false); - + moduleAdapter.addOptimizationStateListener((OptimizationStateListener) (this)); - + ////////////////////////////////////////////////////////////// runButton = ToolBoxGui.createIconifiedButton("images/Play24.gif", "Start", true); @@ -111,7 +113,7 @@ public class EvAModuleButtonPanelMaker implements OptimizationStateListener, Ser }); postProcessButton.setEnabled(runningState && moduleAdapter.hasPostProcessing()); toolBar.add(postProcessButton); - + scheduleButton = ToolBoxGui.createIconifiedButton("images/Server24.gif", "Schedule", true); scheduleButton.setToolTipText("Schedule the currently configured optimization as a job."); //scheduleButton.setBorderPainted(false); @@ -139,7 +141,7 @@ public class EvAModuleButtonPanelMaker implements OptimizationStateListener, Ser stopButton.setEnabled(true); runButton.setEnabled(false); postProcessButton.setEnabled(false); - } catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); System.err.print("Error in run: " + ex + " : " + ex.getMessage()); } diff --git a/src/eva2/gui/EvATabbedFrameMaker.java b/src/eva2/gui/EvATabbedFrameMaker.java index 9500c7be..65de4194 100644 --- a/src/eva2/gui/EvATabbedFrameMaker.java +++ b/src/eva2/gui/EvATabbedFrameMaker.java @@ -7,6 +7,7 @@ package eva2.gui; import eva2.optimization.go.InterfaceNotifyOnInformers; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; + import java.awt.*; import java.awt.event.*; import java.io.Serializable; @@ -71,7 +72,7 @@ public class EvATabbedFrameMaker implements Serializable, PanelMaker, InterfaceN tabbedPane.addTab(((JParaPanel) element).getName(), panel); } } - + for (int i = 0; i < tabbedPane.getTabCount(); i++) { tabbedPane.setTabComponentAt(i, new ClosableTabComponent(tabbedPane, tabToolBar)); } @@ -86,8 +87,8 @@ public class EvATabbedFrameMaker implements Serializable, PanelMaker, InterfaceN } /** - * @deprecated * @return The toolbar with control buttons + * @deprecated */ public JExtToolBar getToolBar() { return extToolBar; @@ -151,16 +152,16 @@ public class EvATabbedFrameMaker implements Serializable, PanelMaker, InterfaceN /** * Component to be used as tabComponent; - * Contains a JLabel to show the text and - * a JButton to close the tab it belongs to + * Contains a JLabel to show the text and + * a JButton to close the tab it belongs to */ class ClosableTabComponent extends JPanel { private final JTabbedPane pane; private final JToolBar toolBar; - + public ClosableTabComponent(final JTabbedPane pane, final JToolBar toolBar) { super(new FlowLayout(FlowLayout.LEADING, 0, 0)); - + if (pane == null) { throw new NullPointerException("TabbedPane is null"); } @@ -168,7 +169,7 @@ class ClosableTabComponent extends JPanel { this.toolBar = toolBar; this.toolBar.setVisible(false); setOpaque(false); - + //make JLabel read titles from JTabbedPane JLabel label = new JLabel() { @Override @@ -180,18 +181,18 @@ class ClosableTabComponent extends JPanel { return null; } }; - + add(label); //add more space between the label and the button label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); //tab button JButton button = new TabButton(); - + add(button); //add more space to the top of the component setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0)); } - + private class TabButton extends JButton implements ActionListener { public TabButton() { int size = 17; @@ -212,7 +213,7 @@ class ClosableTabComponent extends JPanel { //Close the proper tab by clicking the button addActionListener(this); } - + @Override public void actionPerformed(ActionEvent e) { int i = pane.indexOfTabComponent(ClosableTabComponent.this); @@ -220,9 +221,9 @@ class ClosableTabComponent extends JPanel { final String tabTitle = pane.getTitleAt(i); final Component tabPane = pane.getComponentAt(i); final int tabPosition = i; - + pane.remove(i); - if(pane.getTabCount() == 0) { + if (pane.getTabCount() == 0) { pane.setVisible(false); } /* Create a button to be shown in the ToolBar */ @@ -233,33 +234,33 @@ class ClosableTabComponent extends JPanel { @Override public void actionPerformed(ActionEvent e) { - /* Add the Tab Panel again */ + /* Add the Tab Panel again */ // ToDo: Fix indexing problem pane.insertTab(tabTitle, null, tabPane, "", tabPosition); /* Set the tab component (closable) */ pane.setTabComponentAt(tabPosition, ClosableTabComponent.this); pane.setVisible(true); /* Remove the Button */ - toolBar.remove((Component)e.getSource()); + toolBar.remove((Component) e.getSource()); /* If the Button was the last one, hide ToolBar again */ - if(toolBar.getComponentCount() == 0) { + if (toolBar.getComponentCount() == 0) { toolBar.setVisible(false); } } }); /* Add it to the ToolBar */ - if(!toolBar.isVisible()) { + if (!toolBar.isVisible()) { toolBar.setVisible(true); } toolBar.add(tabButton); } } - + //we don't want to update UI for this button @Override public void updateUI() { } - + //paint the cross @Override protected void paintComponent(Graphics g) { @@ -277,7 +278,7 @@ class ClosableTabComponent extends JPanel { g2.dispose(); } } - + private final static MouseListener buttonMouseListener = new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { @@ -287,7 +288,7 @@ class ClosableTabComponent extends JPanel { button.setBorderPainted(true); } } - + @Override public void mouseExited(MouseEvent e) { Component component = e.getComponent(); diff --git a/src/eva2/gui/EvATreeNode.java b/src/eva2/gui/EvATreeNode.java index d9564c24..39d00d6a 100644 --- a/src/eva2/gui/EvATreeNode.java +++ b/src/eva2/gui/EvATreeNode.java @@ -8,85 +8,83 @@ import javax.swing.tree.DefaultMutableTreeNode; * OptimizationParameters object, however this is not necessary. * The tree is constructed using the reflection functionality of PropertySheetPanel * which is also used to generate the nested panels for parameter configuration. - * + * + * @author mkron * @see PropertySheetPanel * @see GOParameters - * @author mkron - * */ -public class EvATreeNode extends DefaultMutableTreeNode { - private String[] childrenNames = null; - private Object[] childrenValues = null; - private String myName="EvATreeNode"; - private boolean doListPrimitives=false; +public class EvATreeNode extends DefaultMutableTreeNode { + private String[] childrenNames = null; + private Object[] childrenValues = null; + private String myName = "EvATreeNode"; + private boolean doListPrimitives = false; - /** - * A default constructor setting the name and target object of - * the tree. The children are generated immediately. - * The node label is constructed from the name String and the - * information retrieved from the target object if it implements the getName method. - * - * @param name title of the node - * @param target - */ - public EvATreeNode(String name, Object target) { - super(target); - myName = name; - setObject(target, true); - } + /** + * A default constructor setting the name and target object of + * the tree. The children are generated immediately. + * The node label is constructed from the name String and the + * information retrieved from the target object if it implements the getName method. + * + * @param name title of the node + * @param target + */ + public EvATreeNode(String name, Object target) { + super(target); + myName = name; + setObject(target, true); + } - /** - * Set the target object of the tree. Note that the name is not automatically - * updated and may be out of date if the new target object is incompatible to the - * old name. - * - * @param target the new target object - * @param expand should be true to generate child nodes immediately - */ - public void setObject(Object target, boolean expand) { - super.setUserObject(target); - childrenNames = PropertySheetPanel.getPropertyNames(target); - childrenValues = PropertySheetPanel.getPropertyValues(target, true, true, true); - super.removeAllChildren(); - if (expand) { - initChildren(); + /** + * Set the target object of the tree. Note that the name is not automatically + * updated and may be out of date if the new target object is incompatible to the + * old name. + * + * @param target the new target object + * @param expand should be true to generate child nodes immediately + */ + public void setObject(Object target, boolean expand) { + super.setUserObject(target); + childrenNames = PropertySheetPanel.getPropertyNames(target); + childrenValues = PropertySheetPanel.getPropertyValues(target, true, true, true); + super.removeAllChildren(); + if (expand) { + initChildren(); + } + } + + public void setName(String name) { + myName = name; + } + + public String getName() { + return myName; + } + + /** + * Actually create child nodes. + */ + private void initChildren() { + for (int i = 0; i < childrenValues.length; i++) { + if (childrenValues[i] != null) { + if (doListPrimitives || !(BeanInspector.isJavaPrimitive(childrenValues[i].getClass()))) { + super.add(new EvATreeNode(childrenNames[i], childrenValues[i])); + } } - } + } + } - public void setName(String name) { - myName=name; - } - - public String getName() { - return myName; - } - - /** - * Actually create child nodes. - */ - private void initChildren() { - for (int i=0; i= 0; i--) { + System.out.println("* " + i + " " + tp.getPathComponent(i)); } - TreePath tp = e.getPath(); - if (TRACE) { - for (int i=tp.getPathCount()-1; i>=0; i--) { - System.out.println("* " + i + " " + tp.getPathComponent(i)); - } } - EvATreeNode leafNode = (EvATreeNode)tp.getLastPathComponent(); + } + EvATreeNode leafNode = (EvATreeNode) tp.getLastPathComponent(); // goe.setValue(leafNode.getUserObject()); - Component editComp = goe.getCustomEditor(); - if (editComp instanceof GOEPanel) { - // update the object in the main GOEPanel - ((GOEPanel)editComp).setTarget(leafNode.getUserObject()); - } else { - System.err.println("Error, unable to notify custom editor of type " + editComp.getClass() + ", expected GOEPanel (EvATreeSelectionListener)"); - } - } + Component editComp = goe.getCustomEditor(); + if (editComp instanceof GOEPanel) { + // update the object in the main GOEPanel + ((GOEPanel) editComp).setTarget(leafNode.getUserObject()); + } else { + System.err.println("Error, unable to notify custom editor of type " + editComp.getClass() + ", expected GOEPanel (EvATreeSelectionListener)"); + } + } @Override - public void propertyChange(PropertyChangeEvent evt) { - if (TRACE) { - System.out.println("EvATreeNode received change event " + evt); - } - root.setObject(evt.getNewValue(), true); - if (jtree !=null) { - jtree.setModel(new DefaultTreeModel(root)); - } // TODO this should be done differently so that the tree is not collapsed on each change! - } + public void propertyChange(PropertyChangeEvent evt) { + if (TRACE) { + System.out.println("EvATreeNode received change event " + evt); + } + root.setObject(evt.getNewValue(), true); + if (jtree != null) { + jtree.setModel(new DefaultTreeModel(root)); + } // TODO this should be done differently so that the tree is not collapsed on each change! + } } diff --git a/src/eva2/gui/Exp.java b/src/eva2/gui/Exp.java index c9787979..cd21c802 100644 --- a/src/eva2/gui/Exp.java +++ b/src/eva2/gui/Exp.java @@ -3,67 +3,66 @@ package eva2.gui; import eva2.tools.chart2d.DFunction; /** - * Represents an exponential scaling function. + * Represents an exponential scaling function. * MK: added a guard against undefined values: the smallest positive position can * be stored and used instead of invalid points. - * */ public class Exp extends DFunction { - private double minValue = 1e-10; // think of a minimal value we want to show in case invalid (<=0) values are requested - - public void setMinValue(double v) { - if (v>0) { - minValue = v; - } - else { - System.err.println("Error, minimal value for Exp must be positive!"); - } - } - /* - * (non-Javadoc) - * @see eva2.tools.chart2d.DFunction#isDefinedAt(double) - */ - @Override - public boolean isDefinedAt(double source) { - return true; - } + private double minValue = 1e-10; // think of a minimal value we want to show in case invalid (<=0) values are requested - /* - * (non-Javadoc) - * @see eva2.tools.chart2d.DFunction#isInvertibleAt(double) - */ - @Override - public boolean isInvertibleAt(double image) { - return image > 0; - } + public void setMinValue(double v) { + if (v > 0) { + minValue = v; + } else { + System.err.println("Error, minimal value for Exp must be positive!"); + } + } - /* - * (non-Javadoc) - * @see eva2.tools.chart2d.DFunction#getImageOf(double) - */ + /* + * (non-Javadoc) + * @see eva2.tools.chart2d.DFunction#isDefinedAt(double) + */ @Override - public double getImageOf(double source) { - return Math.exp(source); - } + public boolean isDefinedAt(double source) { + return true; + } - /* - * (non-Javadoc) - * @see eva2.tools.chart2d.DFunction#getSourceOf(double) - */ + /* + * (non-Javadoc) + * @see eva2.tools.chart2d.DFunction#isInvertibleAt(double) + */ @Override - public double getSourceOf(double target) { - if (target <= 0) { - return Math.log(minValue); // think of a minimal value we want to show in case invalid values are requested + public boolean isInvertibleAt(double image) { + return image > 0; + } + + /* + * (non-Javadoc) + * @see eva2.tools.chart2d.DFunction#getImageOf(double) + */ + @Override + public double getImageOf(double source) { + return Math.exp(source); + } + + /* + * (non-Javadoc) + * @see eva2.tools.chart2d.DFunction#getSourceOf(double) + */ + @Override + public double getSourceOf(double target) { + if (target <= 0) { + return Math.log(minValue); // think of a minimal value we want to show in case invalid values are requested // throw new IllegalArgumentException( // "Can not calculate log on values smaller than or equal 0 --> target = " // + target); - } - return Math.log(target); - } - - public void updateMinValue(double y) { - if (y0)) { - minValue=y; - } - } + } + return Math.log(target); + } + + public void updateMinValue(double y) { + if (y < minValue && (y > 0)) { + minValue = y; + } + } } diff --git a/src/eva2/gui/ExtAction.java b/src/eva2/gui/ExtAction.java index db1696df..2d90b374 100644 --- a/src/eva2/gui/ExtAction.java +++ b/src/eva2/gui/ExtAction.java @@ -12,60 +12,67 @@ package eva2.gui; /*==========================================================================* * IMPORTS *==========================================================================*/ + import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.KeyStroke; + /** * */ public abstract class ExtAction extends AbstractAction { - public final static String CAPTION = "Caption"; - public final static String MNEMONIC = "Mnemonic"; - public final static String TOOLTIP = "ToolTip"; - public final static String KEYSTROKE = "KeyStroke"; - /** - * - */ - private void setValues(String s, String toolTip){ - Mnemonic m = new Mnemonic(s); - putValue(MNEMONIC, new Character(m.getMnemonic())); - putValue(Action.NAME, m.getText()); - putValue(TOOLTIP, toolTip); - } - /** - * - */ - public ExtAction(String s, Icon i, String toolTip, KeyStroke key){ - this(s, i, toolTip); - if (i==null) { - System.out.println("Icon == null"); - } - putValue(KEYSTROKE, key); - } - /** - * - */ - public ExtAction(String s, Icon i, String toolTip){ - super(null, i); - if (i==null) { - System.out.println("Icon == null"); - } - setValues(s, toolTip); - } - /** - * - */ - public ExtAction(String s, String toolTip, KeyStroke key){ - this(s, toolTip); - putValue(KEYSTROKE, key); - } - /** - * - */ - public ExtAction(String s, String toolTip){ - super(); - setValues(s, toolTip); - } + public final static String CAPTION = "Caption"; + public final static String MNEMONIC = "Mnemonic"; + public final static String TOOLTIP = "ToolTip"; + public final static String KEYSTROKE = "KeyStroke"; + + /** + * + */ + private void setValues(String s, String toolTip) { + Mnemonic m = new Mnemonic(s); + putValue(MNEMONIC, new Character(m.getMnemonic())); + putValue(Action.NAME, m.getText()); + putValue(TOOLTIP, toolTip); + } + + /** + * + */ + public ExtAction(String s, Icon i, String toolTip, KeyStroke key) { + this(s, i, toolTip); + if (i == null) { + System.out.println("Icon == null"); + } + putValue(KEYSTROKE, key); + } + + /** + * + */ + public ExtAction(String s, Icon i, String toolTip) { + super(null, i); + if (i == null) { + System.out.println("Icon == null"); + } + setValues(s, toolTip); + } + + /** + * + */ + public ExtAction(String s, String toolTip, KeyStroke key) { + this(s, toolTip); + putValue(KEYSTROKE, key); + } + + /** + * + */ + public ExtAction(String s, String toolTip) { + super(); + setValues(s, toolTip); + } } diff --git a/src/eva2/gui/ExtActionChangedListener.java b/src/eva2/gui/ExtActionChangedListener.java index b159680e..632d484c 100644 --- a/src/eva2/gui/ExtActionChangedListener.java +++ b/src/eva2/gui/ExtActionChangedListener.java @@ -12,30 +12,35 @@ package eva2.gui; /*==========================================================================* * IMPORTS *==========================================================================*/ + import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JComponent; + /** * */ -public abstract class ExtActionChangedListener implements PropertyChangeListener{ - protected JComponent component; - /** - * - */ - ExtActionChangedListener(JComponent c){ - super(); - setTarget(c); - } - /** - * - */ +public abstract class ExtActionChangedListener implements PropertyChangeListener { + protected JComponent component; + + /** + * + */ + ExtActionChangedListener(JComponent c) { + super(); + setTarget(c); + } + + /** + * + */ @Override - public abstract void propertyChange(PropertyChangeEvent e); - /** - * - */ - public void setTarget(JComponent c){ - component = c; - } + public abstract void propertyChange(PropertyChangeEvent e); + + /** + * + */ + public void setTarget(JComponent c) { + component = c; + } } diff --git a/src/eva2/gui/ExtDesktopManager.java b/src/eva2/gui/ExtDesktopManager.java index 0e31e9a2..4c336613 100644 --- a/src/eva2/gui/ExtDesktopManager.java +++ b/src/eva2/gui/ExtDesktopManager.java @@ -9,6 +9,7 @@ package eva2.gui; * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ + import java.awt.Component; import java.awt.Event; import java.util.logging.Level; @@ -22,7 +23,7 @@ import javax.swing.KeyStroke; * */ public class ExtDesktopManager extends DefaultDesktopManager { - + private static final Logger LOGGER = Logger.getLogger(ExtDesktopManager.class.getName()); int WINDOW_LIST_START; diff --git a/src/eva2/gui/GOEPanel.java b/src/eva2/gui/GOEPanel.java index ba71a594..8358d3fb 100644 --- a/src/eva2/gui/GOEPanel.java +++ b/src/eva2/gui/GOEPanel.java @@ -5,6 +5,7 @@ import eva2.optimization.tools.FileTools; import eva2.tools.BasicResourceLoader; import eva2.tools.EVAHELP; import eva2.tools.SerializedObject; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -29,7 +30,7 @@ import javax.swing.plaf.basic.BasicComboBoxRenderer; public class GOEPanel extends JPanel implements ItemListener { private Object backupObject; - private PropertyChangeSupport propChangeSupport; + private PropertyChangeSupport propChangeSupport; /** * The chooser component */ @@ -97,11 +98,11 @@ public class GOEPanel extends JPanel implements ItemListener { propertySheetPanel = new PropertySheetPanel(); propertySheetPanel.addPropertyChangeListener( new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent event) { - propChangeSupport.firePropertyChange("", backupObject, genericObjectEditor.getValue()); - } - }); + @Override + public void propertyChange(final PropertyChangeEvent event) { + propChangeSupport.firePropertyChange("", backupObject, genericObjectEditor.getValue()); + } + }); openButton = makeIconButton("images/Open16.gif", "Open"); openButton.setToolTipText("Load a configured object"); openButton.setEnabled(true); @@ -409,8 +410,8 @@ public class GOEPanel extends JPanel implements ItemListener { objectChooser.setSelectedIndex(0); JOptionPane.showMessageDialog(this, "Could not create an example of\n" - + className + "\n" - + "from the current classpath. Is the resource folder at the right place?\nIs the class abstract or the default constructor missing?", + + className + "\n" + + "from the current classpath. Is the resource folder at the right place?\nIs the class abstract or the default constructor missing?", "GenericObjectEditor", JOptionPane.ERROR_MESSAGE); EVAHELP.getSystemPropertyString(); @@ -431,7 +432,7 @@ class ToolTipComboBoxRenderer extends BasicComboBoxRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, - int index, boolean isSelected, boolean cellHasFocus) { + int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); diff --git a/src/eva2/gui/HtmlDemo.java b/src/eva2/gui/HtmlDemo.java index 46120ecf..501bc03d 100644 --- a/src/eva2/gui/HtmlDemo.java +++ b/src/eva2/gui/HtmlDemo.java @@ -9,8 +9,10 @@ package eva2.gui; * $Date: 2007-10-23 16:58:12 +0200 (Tue, 23 Oct 2007) $ * $Author: mkron $ */ + import eva2.EvAInfo; import eva2.tools.BasicResourceLoader; + import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; @@ -25,48 +27,53 @@ import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLFrameHyperlinkEvent; + /** * */ public class HtmlDemo { - private JEditorPane m_html; - private String m_name; - /** - * - */ - public HtmlDemo(String name) { - m_name = name; - } - /** - * - */ - public JEditorPane getPane() { - return m_html; - } + private JEditorPane m_html; + private String m_name; + /** - * - */ + * + */ + public HtmlDemo(String name) { + m_name = name; + } + + /** + * + */ + public JEditorPane getPane() { + return m_html; + } + + /** + * + */ public static void main(String[] args) { HtmlDemo demo = new HtmlDemo("ES.html"); demo.show(); } - + public boolean resourceExists() { - URL url = ClassLoader.getSystemResource("html/"+m_name); - return (url != null); + URL url = ClassLoader.getSystemResource("html/" + m_name); + return (url != null); } - + public static boolean resourceExists(String mname) { - URL url = ClassLoader.getSystemResource("html/"+mname); - return (url != null); + URL url = ClassLoader.getSystemResource("html/" + mname); + return (url != null); } + /** - * - */ + * + */ public void show() { try { URL url = null; - url = this.getClass().getClassLoader().getSystemResource("html/"+m_name); + url = this.getClass().getClassLoader().getSystemResource("html/" + m_name); try { m_html = new JEditorPane(url); @@ -86,39 +93,39 @@ public class HtmlDemo { e.printStackTrace(); return; } - JFrame frame = new JFrame (m_name); - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); + JFrame frame = new JFrame(m_name); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); - JScrollPane scroller = new JScrollPane(); - JViewport vp = scroller.getViewport(); + JScrollPane scroller = new JScrollPane(); + JViewport vp = scroller.getViewport(); vp.add(m_html); - scroller.setPreferredSize( new Dimension(600,500) ); + scroller.setPreferredSize(new Dimension(600, 500)); frame.getContentPane().add(scroller, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } - /** - * - */ - public HyperlinkListener createHyperLinkListener() { - return new HyperlinkListener() { + /** + * + */ + public HyperlinkListener createHyperLinkListener() { + return new HyperlinkListener() { @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - if (e instanceof HTMLFrameHyperlinkEvent) { - ((HTMLDocument)m_html.getDocument()).processHTMLFrameHyperlinkEvent( - (HTMLFrameHyperlinkEvent)e); - } else { - try { - m_html.setPage(e.getURL()); - } catch (IOException ioe) { - System.out.println("IOE: " + ioe); - } - } - } - } - }; -} + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + if (e instanceof HTMLFrameHyperlinkEvent) { + ((HTMLDocument) m_html.getDocument()).processHTMLFrameHyperlinkEvent( + (HTMLFrameHyperlinkEvent) e); + } else { + try { + m_html.setPage(e.getURL()); + } catch (IOException ioe) { + System.out.println("IOE: " + ioe); + } + } + } + } + }; + } } diff --git a/src/eva2/gui/InterfaceSelectablePointIcon.java b/src/eva2/gui/InterfaceSelectablePointIcon.java index 15f66cb5..d01a4c38 100644 --- a/src/eva2/gui/InterfaceSelectablePointIcon.java +++ b/src/eva2/gui/InterfaceSelectablePointIcon.java @@ -12,28 +12,37 @@ import eva2.optimization.mocco.paretofrontviewer.InterfaceRefSolutionListener; */ public interface InterfaceSelectablePointIcon { - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ public void addSelectionListener(InterfaceRefSolutionListener a); - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ public void removeSelectionListeners(); - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfacePointIconSelectionListener */ public InterfaceRefSolutionListener getSelectionListener(); - /** Of course the PointIcon needs a reference to the individual + /** + * Of course the PointIcon needs a reference to the individual * otherwise it can't tell the listener what has been selected. + * * @param indy */ public void setEAIndividual(AbstractEAIndividual indy); - /** This method allows you to get the EAIndividual the icon stands for + /** + * This method allows you to get the EAIndividual the icon stands for + * * @return AbstractEAIndividual */ public AbstractEAIndividual getEAIndividual(); diff --git a/src/eva2/gui/JDocFrame.java b/src/eva2/gui/JDocFrame.java index dd26e779..7dc39225 100644 --- a/src/eva2/gui/JDocFrame.java +++ b/src/eva2/gui/JDocFrame.java @@ -9,89 +9,102 @@ package eva2.gui; * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ + import java.io.File; import javax.swing.JInternalFrame; import javax.swing.JMenu; import javax.swing.JToolBar; + /** * */ -public abstract class JDocFrame extends JInternalFrame{ - private File m_file; - private String titleStr; - protected boolean changed = false; - /** - * - */ - public JDocFrame(String title){ - super(title, true, true /* not closable*/, true, true); - titleStr = title; - } - /** - * - */ - public JDocFrame(File file){ - this(file.getName()); - m_file = file; - } - /** - * - */ - public File getFile(){ - return m_file; - } - /** - * - */ - public String getFileTitle(){ - return titleStr; - } - /** - * - */ - public void save(){ - if(m_file != null) { - save(m_file); - } - } - /** - * - */ - public void save(File f){ - if(!f.equals(m_file)){ - m_file = f; - titleStr = f.getName(); +public abstract class JDocFrame extends JInternalFrame { + private File m_file; + private String titleStr; + protected boolean changed = false; + + /** + * + */ + public JDocFrame(String title) { + super(title, true, true /* not closable*/, true, true); + titleStr = title; } - setChangedImpl(false); - } - /** - * - */ - private void setChangedImpl(boolean value){ - changed = value; - if(changed) { - setTitle(titleStr + " *"); - } - else { - setTitle(titleStr); - } - } - /** - * - */ - protected void setChanged(boolean value){ - if(changed != value) { - setChangedImpl(value); - } - } - /** - * - */ - public boolean isChanged(){ - return changed; - } - public abstract String[] getActionGroups(); - public abstract JMenu getMenu(String group); - public abstract JToolBar getToolBar(String group); + + /** + * + */ + public JDocFrame(File file) { + this(file.getName()); + m_file = file; + } + + /** + * + */ + public File getFile() { + return m_file; + } + + /** + * + */ + public String getFileTitle() { + return titleStr; + } + + /** + * + */ + public void save() { + if (m_file != null) { + save(m_file); + } + } + + /** + * + */ + public void save(File f) { + if (!f.equals(m_file)) { + m_file = f; + titleStr = f.getName(); + } + setChangedImpl(false); + } + + /** + * + */ + private void setChangedImpl(boolean value) { + changed = value; + if (changed) { + setTitle(titleStr + " *"); + } else { + setTitle(titleStr); + } + } + + /** + * + */ + protected void setChanged(boolean value) { + if (changed != value) { + setChangedImpl(value); + } + } + + /** + * + */ + public boolean isChanged() { + return changed; + } + + public abstract String[] getActionGroups(); + + public abstract JMenu getMenu(String group); + + public abstract JToolBar getToolBar(String group); } diff --git a/src/eva2/gui/JEFrame.java b/src/eva2/gui/JEFrame.java index 9233b7ed..5fe07f6a 100644 --- a/src/eva2/gui/JEFrame.java +++ b/src/eva2/gui/JEFrame.java @@ -22,42 +22,42 @@ import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; public class JEFrame extends JInternalFrame { - private boolean closeAllOnClose = false; - - public JEFrame() { - super(); - init(); - } + private boolean closeAllOnClose = false; - public JEFrame(String name) { - super(name); - init(); - } - - /** - * Set to true if all registered JEFrames should be closed if this frame is closed. - * - * @param c - */ - public void setCloseAllOnClosed(boolean c) { - closeAllOnClose = c; - } + public JEFrame() { + super(); + init(); + } - @Override - public void addInternalFrameListener(InternalFrameListener l) { - super.addInternalFrameListener(l); - } + public JEFrame(String name) { + super(name); + init(); + } - private void init() { - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - - this.addInternalFrameListener(new InternalFrameAdapter() { + /** + * Set to true if all registered JEFrames should be closed if this frame is closed. + * + * @param c + */ + public void setCloseAllOnClosed(boolean c) { + closeAllOnClose = c; + } + + @Override + public void addInternalFrameListener(InternalFrameListener l) { + super.addInternalFrameListener(l); + } + + private void init() { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + this.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { super.internalFrameClosed(e); - JEFrameRegister.getInstance().unregister((JEFrame) e.getInternalFrame()); - if (closeAllOnClose) { + JEFrameRegister.getInstance().unregister((JEFrame) e.getInternalFrame()); + if (closeAllOnClose) { JEFrameRegister.getInstance().closeAll(); } } @@ -70,59 +70,59 @@ public class JEFrame extends JInternalFrame { @Override public void internalFrameActivated(InternalFrameEvent e) { - JEFrameRegister.getInstance().register((JEFrame) e.getInternalFrame()); - super.internalFrameActivated(e); + JEFrameRegister.getInstance().register((JEFrame) e.getInternalFrame()); + super.internalFrameActivated(e); } - }); - this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK), - "ctrlFpressed" - ); - this.getRootPane().getActionMap().put( - "ctrlFpressed", - new AbstractAction("ctrlFpressed") { - @Override - public void actionPerformed(ActionEvent actionEvent) { + }); + this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( + KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK), + "ctrlFpressed" + ); + this.getRootPane().getActionMap().put( + "ctrlFpressed", + new AbstractAction("ctrlFpressed") { + @Override + public void actionPerformed(ActionEvent actionEvent) { JEFrameRegister.getInstance().getFrameList().get(0).toFront(); - } - } - ); - this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK), - "ctrlOpressed" - ); - this.getRootPane().getActionMap().put( - "ctrlOpressed", - new AbstractAction("ctrlOpressed") { - @Override - public void actionPerformed(ActionEvent actionEvent) { - java.util.List frameList = JEFrameRegister.getInstance().getFrameList(); - for (JEFrame frame : frameList) { + } + } + ); + this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( + KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK), + "ctrlOpressed" + ); + this.getRootPane().getActionMap().put( + "ctrlOpressed", + new AbstractAction("ctrlOpressed") { + @Override + public void actionPerformed(ActionEvent actionEvent) { + java.util.List frameList = JEFrameRegister.getInstance().getFrameList(); + for (JEFrame frame : frameList) { frame.toFront(); } - } - } - ); - this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke(KeyEvent.VK_LESS , Event.CTRL_MASK), - "ctrlSmallerpressed" - ); - final JEFrame self = this; - this.getRootPane().getActionMap().put( - "ctrlSmallerpressed", - new AbstractAction("ctrlSmallerpressed") { - @Override - public void actionPerformed(ActionEvent actionEvent) { - JEFrameRegister.getInstance().setFocusToNext(self); - } - } - ); - + } + } + ); + this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( + KeyStroke.getKeyStroke(KeyEvent.VK_LESS, Event.CTRL_MASK), + "ctrlSmallerpressed" + ); + final JEFrame self = this; + this.getRootPane().getActionMap().put( + "ctrlSmallerpressed", + new AbstractAction("ctrlSmallerpressed") { + @Override + public void actionPerformed(ActionEvent actionEvent) { + JEFrameRegister.getInstance().setFocusToNext(self); + } + } + ); + this.setMaximizable(true); this.setResizable(true); this.setIconifiable(true); this.setClosable(true); - - - } + + + } } diff --git a/src/eva2/gui/JEFrameRegister.java b/src/eva2/gui/JEFrameRegister.java index a4e942c7..e20a5e47 100644 --- a/src/eva2/gui/JEFrameRegister.java +++ b/src/eva2/gui/JEFrameRegister.java @@ -1,4 +1,5 @@ package eva2.gui; + import java.util.ArrayList; import java.util.List; import javax.swing.JDesktopPane; diff --git a/src/eva2/gui/JExtDesktopPane.java b/src/eva2/gui/JExtDesktopPane.java index 763b8342..63df7e21 100644 --- a/src/eva2/gui/JExtDesktopPane.java +++ b/src/eva2/gui/JExtDesktopPane.java @@ -39,7 +39,7 @@ public class JExtDesktopPane extends JDesktopPane { */ public JExtDesktopPane() { super(); - + windowMenu = new JExtMenu("&Windows"); desktopManager = new ExtDesktopManager(this); setDesktopManager(desktopManager); @@ -65,7 +65,7 @@ public class JExtDesktopPane extends JDesktopPane { } }); - windowMenu.add(actWindowTileHorz = new ExtAction("Tile &Horizontally", "Tiles all windows horizontically", + windowMenu.add(actWindowTileHorz = new ExtAction("Tile &Horizontally", "Tiles all windows horizontically", KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, Event.CTRL_MASK)) { @Override @@ -89,10 +89,10 @@ public class JExtDesktopPane extends JDesktopPane { /** * Method to access the window actions. - * - * @deprecated + * * @param action The desired action (use JExtDesktopPane constants). Default is null * @return The ExtAction + * @deprecated */ public ExtAction getWindowAction(int action) { switch (action) { diff --git a/src/eva2/gui/JExtDesktopPaneToolBar.java b/src/eva2/gui/JExtDesktopPaneToolBar.java index 44058a78..a7ecf326 100644 --- a/src/eva2/gui/JExtDesktopPaneToolBar.java +++ b/src/eva2/gui/JExtDesktopPaneToolBar.java @@ -1,6 +1,7 @@ package eva2.gui; import eva2.tools.ToolBoxGui; + import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; @@ -8,19 +9,18 @@ import javax.swing.JToolBar; import javax.swing.SwingConstants; /** - * * @author becker */ public class JExtDesktopPaneToolBar extends JToolBar { - + private JExtDesktopPane desktopPane; - + public JExtDesktopPaneToolBar(JExtDesktopPane desktopPane) { this.desktopPane = desktopPane; - + initComponents(); } - + private void initComponents() { /* We don't want the ToolBar to be draggable */ setFloatable(false); @@ -33,10 +33,10 @@ public class JExtDesktopPaneToolBar extends JToolBar { public void actionPerformed(ActionEvent e) { desktopPane.tileWindows(SwingConstants.VERTICAL); } - + }); - add(verticalButton); - + add(verticalButton); + JButton horizontalButton = ToolBoxGui.createIconifiedButton("images/TileHorizontal16.png", "Tile horizontally", false); horizontalButton.addActionListener(new ActionListener() { @@ -44,10 +44,10 @@ public class JExtDesktopPaneToolBar extends JToolBar { public void actionPerformed(ActionEvent e) { desktopPane.tileWindows(SwingConstants.HORIZONTAL); } - + }); add(horizontalButton); - + JButton cascadeButton = ToolBoxGui.createIconifiedButton("images/Cascade16.png", "Cascade windows", false); cascadeButton.addActionListener(new ActionListener() { @@ -55,7 +55,7 @@ public class JExtDesktopPaneToolBar extends JToolBar { public void actionPerformed(ActionEvent e) { desktopPane.overlapWindows(); } - + }); add(cascadeButton); } diff --git a/src/eva2/gui/JExtFileChooser.java b/src/eva2/gui/JExtFileChooser.java index 1c2956ae..4eba6952 100644 --- a/src/eva2/gui/JExtFileChooser.java +++ b/src/eva2/gui/JExtFileChooser.java @@ -12,32 +12,33 @@ package eva2.gui; /*==========================================================================* * IMPORTS *==========================================================================*/ + import java.io.File; import javax.swing.*; -public class JExtFileChooser extends JFileChooser{ - private boolean overwriteWarning = true; +public class JExtFileChooser extends JFileChooser { + private boolean overwriteWarning = true; - public void setOverwriteWarning(boolean value){ - overwriteWarning = value; - } - - public boolean getOverwriteWarning(){ - return overwriteWarning; - } - - @Override - public void approveSelection(){ - if(getDialogType() == JFileChooser.SAVE_DIALOG && overwriteWarning){ - File f = getSelectedFile(); - - if(f != null && f.exists()) { - if (JOptionPane.showConfirmDialog(this, "Die Datei " + f.getPath() + " existiert bereits.\nSoll sie �berschrieben werden?", "Achtung", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) { - return; - } - } + public void setOverwriteWarning(boolean value) { + overwriteWarning = value; } - super.approveSelection(); - } + public boolean getOverwriteWarning() { + return overwriteWarning; + } + + @Override + public void approveSelection() { + if (getDialogType() == JFileChooser.SAVE_DIALOG && overwriteWarning) { + File f = getSelectedFile(); + + if (f != null && f.exists()) { + if (JOptionPane.showConfirmDialog(this, "Die Datei " + f.getPath() + " existiert bereits.\nSoll sie �berschrieben werden?", "Achtung", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) { + return; + } + } + } + + super.approveSelection(); + } } diff --git a/src/eva2/gui/JExtToolBar.java b/src/eva2/gui/JExtToolBar.java index 2dfe246c..bdaf4d92 100644 --- a/src/eva2/gui/JExtToolBar.java +++ b/src/eva2/gui/JExtToolBar.java @@ -9,78 +9,77 @@ package eva2.gui; * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ + import java.awt.Insets; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; + /** * */ -public class JExtToolBar extends JToolBar{ +public class JExtToolBar extends JToolBar { @Override - public JButton add(Action a){ - JButton button = super.add(a); - button.setText(null); - button.setMargin(new Insets(0, 0, 0, 0)); + public JButton add(Action a) { + JButton button = super.add(a); + button.setText(null); + button.setMargin(new Insets(0, 0, 0, 0)); - Object o; - o = a.getValue(ExtAction.TOOLTIP); - String toolTip = o != null ? (String)o : ""; + Object o; + o = a.getValue(ExtAction.TOOLTIP); + String toolTip = o != null ? (String) o : ""; - o = a.getValue(ExtAction.KEYSTROKE); - button.setToolTipText(toolTip + getKeyText((KeyStroke)o)); + o = a.getValue(ExtAction.KEYSTROKE); + button.setToolTipText(toolTip + getKeyText((KeyStroke) o)); - return button; - } + return button; + } - private String getKeyText(KeyStroke k){ - StringBuffer result = new StringBuffer(); + private String getKeyText(KeyStroke k) { + StringBuffer result = new StringBuffer(); - if(k != null){ - int modifiers = k.getModifiers(); - if(modifiers > 0) { - result.append(KeyEvent.getKeyModifiersText(modifiers) + "+"); + if (k != null) { + int modifiers = k.getModifiers(); + if (modifiers > 0) { + result.append(KeyEvent.getKeyModifiersText(modifiers) + "+"); + } + result.append(KeyEvent.getKeyText(k.getKeyCode())); + } + if (result.length() > 0) { + result.insert(0, " ["); + result.append("]"); } - result.append(KeyEvent.getKeyText(k.getKeyCode())); - } - if(result.length() > 0){ - result.insert(0, " ["); - result.append("]"); - } - return result.toString(); - } + return result.toString(); + } @Override - protected PropertyChangeListener createActionChangeListener(JButton b){ - return new ExtActionChangedListener(b){ + protected PropertyChangeListener createActionChangeListener(JButton b) { + return new ExtActionChangedListener(b) { @Override - public void propertyChange(PropertyChangeEvent e){ - JButton button = (JButton)component; + public void propertyChange(PropertyChangeEvent e) { + JButton button = (JButton) component; - String propertyName = e.getPropertyName(); - if(propertyName.equals(Action.NAME)){ + String propertyName = e.getPropertyName(); + if (propertyName.equals(Action.NAME)) { /* Nichts tun! */ - } - else if(propertyName.equals("enabled")){ - button.setEnabled(((Boolean)e.getNewValue()).booleanValue()); - button.repaint(); - } - else if(e.getPropertyName().equals(Action.SMALL_ICON)){ - button.setIcon((Icon)e.getNewValue()); - button.invalidate(); - button.repaint(); - } - else if(propertyName.equals(ExtAction.TOOLTIP) || propertyName.equals(ExtAction.KEYSTROKE)){ - Action source = (Action)e.getSource(); + } else if (propertyName.equals("enabled")) { + button.setEnabled(((Boolean) e.getNewValue()).booleanValue()); + button.repaint(); + } else if (e.getPropertyName().equals(Action.SMALL_ICON)) { + button.setIcon((Icon) e.getNewValue()); + button.invalidate(); + button.repaint(); + } else if (propertyName.equals(ExtAction.TOOLTIP) || propertyName.equals(ExtAction.KEYSTROKE)) { + Action source = (Action) e.getSource(); - Object o = source.getValue(ExtAction.TOOLTIP); - String toolTip = o != null ? (String)o : ""; - o = source.getValue(ExtAction.KEYSTROKE); - button.setToolTipText(toolTip + getKeyText((KeyStroke)o)); - } - } - }; - } + Object o = source.getValue(ExtAction.TOOLTIP); + String toolTip = o != null ? (String) o : ""; + o = source.getValue(ExtAction.KEYSTROKE); + button.setToolTipText(toolTip + getKeyText((KeyStroke) o)); + } + } + }; + } } diff --git a/src/eva2/gui/JParaPanel.java b/src/eva2/gui/JParaPanel.java index 417a6a6c..91ae1bd7 100644 --- a/src/eva2/gui/JParaPanel.java +++ b/src/eva2/gui/JParaPanel.java @@ -23,7 +23,7 @@ public class JParaPanel implements Serializable, PanelMaker { protected Object localParameter; protected Object proxyParameter; protected PropertyEditor propertyEditor; - + /** * ToDo: Should be removed in future. */ @@ -49,12 +49,12 @@ public class JParaPanel implements Serializable, PanelMaker { /* ToDo: First parameter is useless and should be removed */ propertyEditor = OptimizationJobList.makeEditor(tempPanel, (OptimizationJobList) localParameter); } else { - propertyEditor = new GenericObjectEditor(); - ((GenericObjectEditor) (propertyEditor)).setClassType(localParameter.getClass()); - ((GenericObjectEditor) (propertyEditor)).setValue(localParameter); - ((GenericObjectEditor) (propertyEditor)).disableOKCancel(); + propertyEditor = new GenericObjectEditor(); + ((GenericObjectEditor) (propertyEditor)).setClassType(localParameter.getClass()); + ((GenericObjectEditor) (propertyEditor)).setValue(localParameter); + ((GenericObjectEditor) (propertyEditor)).disableOKCancel(); } - + return (JComponent) propertyEditor.getCustomEditor(); } @@ -65,10 +65,12 @@ public class JParaPanel implements Serializable, PanelMaker { } public PropertyEditor getEditor() { - return propertyEditor; + return propertyEditor; } - - /** This method will allow you to add a new Editor to a given class + + /** + * This method will allow you to add a new Editor to a given class + * * @param object * @param editor * @return False if failed true else. diff --git a/src/eva2/gui/JTextEditorInternalFrame.java b/src/eva2/gui/JTextEditorInternalFrame.java index 2657e81c..49c01bfa 100644 --- a/src/eva2/gui/JTextEditorInternalFrame.java +++ b/src/eva2/gui/JTextEditorInternalFrame.java @@ -12,6 +12,7 @@ package eva2.gui; /*==========================================================================* * IMPORTS *==========================================================================*/ + import java.awt.Event; import java.awt.event.*; import java.io.*; @@ -22,296 +23,301 @@ import javax.swing.text.*; import javax.swing.undo.*; -public class JTextEditorInternalFrame extends JDocFrame{ - public final static String GROUP_EDIT = "Edit"; - private JTextArea textArea; - private final String[] actionGroups = {GROUP_EDIT}; - protected UndoManager undo = new UndoManager(); - private class UndoAction extends ExtAction{ - public UndoAction(){ - super("R�ckg�ngig", new ImageIcon("images/EditUndo.gif"), "Macht die letzte Aktion r�ckg�ngig", - KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK)); - setEnabled(false); - } +public class JTextEditorInternalFrame extends JDocFrame { + public final static String GROUP_EDIT = "Edit"; + private JTextArea textArea; + private final String[] actionGroups = {GROUP_EDIT}; + protected UndoManager undo = new UndoManager(); - @Override - public void actionPerformed(ActionEvent e){ - try{ - undo.undo(); - } - catch(CannotUndoException exc){} - - update(); - actRedo.update(); - } - - private void update() { - if(undo.canUndo()){ - setEnabled(true); - putValue(Action.NAME, undo.getUndoPresentationName()); - } - else{ - setEnabled(false); - putValue(Action.NAME, "R�ckg�ngig"); - } - } - } // end of inner class UndoAction - /////////////////////////////////////////// - // - /////////////////////////////////////////// - private class RedoAction extends ExtAction{ - public RedoAction(){ - super("Wiederholen", "Wiederholt die letzte Aktion", KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK|Event.SHIFT_MASK)); - setEnabled(false); - } - - @Override - public void actionPerformed(ActionEvent e) { - try{ - undo.redo(); - } - catch(CannotRedoException exc){} - - update(); - actUndo.update(); - } - - private void update() { - if(undo.canRedo()){ - setEnabled(true); - putValue(Action.NAME, undo.getRedoPresentationName()); - } - else{ - setEnabled(false); - putValue(Action.NAME, "Wiederholen"); - } - } - } // end of inner class RedoAction - - private UndoAction actUndo; - private RedoAction actRedo; - public final static String undoAction = "undo"; - public final static String redoAction = "redo"; - /////////////////////////////////////////// - // - ///////////////////////////////////////// - @Override - public String[] getActionGroups(){ - return actionGroups; - } - - private JMenu mnuEdit; - private JToolBar barEdit; - @Override - public JMenu getMenu(String group){ - if(GROUP_EDIT.equals(group)) { - return mnuEdit; - } - else { - return null; - } - } - @Override - public JToolBar getToolBar(String group){ - if(GROUP_EDIT.equals(group)) { - return barEdit; - } - return null; - } - - private Hashtable hashActions = new Hashtable(); - - private Action cloneAction(Action a){ - Action result = null; - - try{ - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(bOut); - out.writeObject(a); - ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); - ObjectInputStream in = new ObjectInputStream(bIn); - result = (Action)in.readObject(); - } - catch(Exception exc){} - - return result; - } - /////////////////////////////////////////////// - // - ////////////////////////////////////////////// - private void createActions(){ - hashActions.put(undoAction, actUndo = new UndoAction()); - hashActions.put(redoAction, actRedo = new RedoAction()); - - Action[] actions = textArea.getActions(); - for(int i = 0; i < actions.length; i++) { - hashActions.put((String)actions[i].getValue(Action.NAME), actions[i]); + private class UndoAction extends ExtAction { + public UndoAction() { + super("R�ckg�ngig", new ImageIcon("images/EditUndo.gif"), "Macht die letzte Aktion r�ckg�ngig", + KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK)); + setEnabled(false); } - mnuEdit = new JExtMenu("&Bearbeiten"); - barEdit = new JExtToolBar(); + @Override + public void actionPerformed(ActionEvent e) { + try { + undo.undo(); + } catch (CannotUndoException exc) { + } - Action a; - Keymap keys = textArea.getKeymap(); - KeyStroke[] keyActions; + update(); + actRedo.update(); + } - mnuEdit.add(actUndo); - barEdit.add(actUndo); - mnuEdit.add(actRedo); - mnuEdit.addSeparator(); + private void update() { + if (undo.canUndo()) { + setEnabled(true); + putValue(Action.NAME, undo.getUndoPresentationName()); + } else { + setEnabled(false); + putValue(Action.NAME, "R�ckg�ngig"); + } + } + } // end of inner class UndoAction - a = (Action)hashActions.get(DefaultEditorKit.cutAction); - keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) { - a.putValue(ExtAction.KEYSTROKE, keyActions[0]); - } - a.putValue(Action.SMALL_ICON, new ImageIcon("images/EditCut.gif")); - a.putValue(ExtAction.CAPTION, "Ausschneiden"); - a.putValue(ExtAction.MNEMONIC, new Character('a')); - a.putValue(ExtAction.TOOLTIP, "Schneidet den markierten Text aus und setzt ihn in die Zwischenablage"); - mnuEdit.add(a); - barEdit.add(a); + /////////////////////////////////////////// + // + /////////////////////////////////////////// + private class RedoAction extends ExtAction { + public RedoAction() { + super("Wiederholen", "Wiederholt die letzte Aktion", KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK | Event.SHIFT_MASK)); + setEnabled(false); + } - a = (Action)hashActions.get(DefaultEditorKit.copyAction); - keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) { - a.putValue(ExtAction.KEYSTROKE, keyActions[0]); - } - a.putValue(Action.SMALL_ICON, new ImageIcon("images/EditCopy.gif")); - a.putValue(ExtAction.CAPTION, "Kopieren"); - a.putValue(ExtAction.MNEMONIC, new Character('k')); - a.putValue(ExtAction.TOOLTIP, "Kopiert den markierten Text in die Zwischenablage"); - mnuEdit.add(a); - barEdit.add(a); + @Override + public void actionPerformed(ActionEvent e) { + try { + undo.redo(); + } catch (CannotRedoException exc) { + } - a = (Action)hashActions.get(DefaultEditorKit.pasteAction); - keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) { - a.putValue(ExtAction.KEYSTROKE, keyActions[0]); - } - a.putValue(Action.SMALL_ICON, new ImageIcon("images/EditPaste.gif")); - a.putValue(ExtAction.CAPTION, "Einf�gen"); - a.putValue(ExtAction.MNEMONIC, new Character('e')); - a.putValue(ExtAction.TOOLTIP, "F�gt Text aus der Zwischenablage ein"); - mnuEdit.add(a); - barEdit.add(a); + update(); + actUndo.update(); + } - mnuEdit.addSeparator(); + private void update() { + if (undo.canRedo()) { + setEnabled(true); + putValue(Action.NAME, undo.getRedoPresentationName()); + } else { + setEnabled(false); + putValue(Action.NAME, "Wiederholen"); + } + } + } // end of inner class RedoAction - a = (Action)hashActions.get(DefaultEditorKit.selectAllAction); - keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) { - a.putValue(ExtAction.KEYSTROKE, keyActions[0]); - } - a.putValue(ExtAction.CAPTION, "Alles markieren"); - a.putValue(ExtAction.MNEMONIC, new Character('m')); - a.putValue(ExtAction.TOOLTIP, "Markiert das ganze Dokument"); - mnuEdit.add(a); - } - ////////////////////////////////////////// - // - ///////////////////////////////////////// - private void createTextArea(){ - textArea = new JTextArea(); - getContentPane().add(new JScrollPane(textArea)); - } - ///////////////////////////////////// - // - ///////////////////////////////////// - private void createListeners(){ - textArea.getDocument().addDocumentListener(new DocumentListener(){ - private void changed(){ - setChanged(true); - } + private UndoAction actUndo; + private RedoAction actRedo; + public final static String undoAction = "undo"; + public final static String redoAction = "redo"; - @Override - public void changedUpdate(DocumentEvent e){ - changed(); - } - - @Override - public void insertUpdate(DocumentEvent e){ - changed(); - } - - @Override - public void removeUpdate(DocumentEvent e){ - changed(); - } - }); - - textArea.getDocument().addUndoableEditListener(new UndoableEditListener(){ - @Override - public void undoableEditHappened(UndoableEditEvent e){ - undo.addEdit(e.getEdit()); - actUndo.update(); - actRedo.update(); - } - }); - } - //////////////////////////////////////////////////// - // - /////////////////////////////////////////////////// - public JTextEditorInternalFrame(String title){ - super(title); - createTextArea(); - createListeners(); - createActions(); - } - ////////////////////////////////////////////////// - // - ///////////////////////////////////////////////// - public JTextEditorInternalFrame(File file){ - super(file); - createTextArea(); - - if(file.exists()){ - FileReader in = null; - try{ - in = new FileReader(file); - textArea.read(in, null); - } - catch(IOException exc){} - finally{ - if(in != null) { - try{ - in.close(); -} -catch(IOException exc){} - } - } + /////////////////////////////////////////// + // + ///////////////////////////////////////// + @Override + public String[] getActionGroups() { + return actionGroups; } - createListeners(); - createActions(); - } + private JMenu mnuEdit; + private JToolBar barEdit; @Override - public void save(File f){ - FileWriter out = null; - try{ - out = new FileWriter(f); - textArea.write(out); - } - catch(IOException exc){} - finally{ - if(out != null) { - try{ -out.close(); -} -catch(IOException exc){} + public JMenu getMenu(String group) { + if (GROUP_EDIT.equals(group)) { + return mnuEdit; + } else { + return null; } } - super.save(f); - } + @Override + public JToolBar getToolBar(String group) { + if (GROUP_EDIT.equals(group)) { + return barEdit; + } + return null; + } + + private Hashtable hashActions = new Hashtable(); + + private Action cloneAction(Action a) { + Action result = null; + + try { + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bOut); + out.writeObject(a); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + ObjectInputStream in = new ObjectInputStream(bIn); + result = (Action) in.readObject(); + } catch (Exception exc) { + } + + return result; + } + + /////////////////////////////////////////////// + // + ////////////////////////////////////////////// + private void createActions() { + hashActions.put(undoAction, actUndo = new UndoAction()); + hashActions.put(redoAction, actRedo = new RedoAction()); + + Action[] actions = textArea.getActions(); + for (int i = 0; i < actions.length; i++) { + hashActions.put((String) actions[i].getValue(Action.NAME), actions[i]); + } + + mnuEdit = new JExtMenu("&Bearbeiten"); + barEdit = new JExtToolBar(); + + Action a; + Keymap keys = textArea.getKeymap(); + KeyStroke[] keyActions; + + mnuEdit.add(actUndo); + barEdit.add(actUndo); + mnuEdit.add(actRedo); + mnuEdit.addSeparator(); + + a = (Action) hashActions.get(DefaultEditorKit.cutAction); + keyActions = keys.getKeyStrokesForAction(a); + if (keyActions != null && keyActions.length > 0) { + a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + } + a.putValue(Action.SMALL_ICON, new ImageIcon("images/EditCut.gif")); + a.putValue(ExtAction.CAPTION, "Ausschneiden"); + a.putValue(ExtAction.MNEMONIC, new Character('a')); + a.putValue(ExtAction.TOOLTIP, "Schneidet den markierten Text aus und setzt ihn in die Zwischenablage"); + mnuEdit.add(a); + barEdit.add(a); + + a = (Action) hashActions.get(DefaultEditorKit.copyAction); + keyActions = keys.getKeyStrokesForAction(a); + if (keyActions != null && keyActions.length > 0) { + a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + } + a.putValue(Action.SMALL_ICON, new ImageIcon("images/EditCopy.gif")); + a.putValue(ExtAction.CAPTION, "Kopieren"); + a.putValue(ExtAction.MNEMONIC, new Character('k')); + a.putValue(ExtAction.TOOLTIP, "Kopiert den markierten Text in die Zwischenablage"); + mnuEdit.add(a); + barEdit.add(a); + + a = (Action) hashActions.get(DefaultEditorKit.pasteAction); + keyActions = keys.getKeyStrokesForAction(a); + if (keyActions != null && keyActions.length > 0) { + a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + } + a.putValue(Action.SMALL_ICON, new ImageIcon("images/EditPaste.gif")); + a.putValue(ExtAction.CAPTION, "Einf�gen"); + a.putValue(ExtAction.MNEMONIC, new Character('e')); + a.putValue(ExtAction.TOOLTIP, "F�gt Text aus der Zwischenablage ein"); + mnuEdit.add(a); + barEdit.add(a); + + mnuEdit.addSeparator(); + + a = (Action) hashActions.get(DefaultEditorKit.selectAllAction); + keyActions = keys.getKeyStrokesForAction(a); + if (keyActions != null && keyActions.length > 0) { + a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + } + a.putValue(ExtAction.CAPTION, "Alles markieren"); + a.putValue(ExtAction.MNEMONIC, new Character('m')); + a.putValue(ExtAction.TOOLTIP, "Markiert das ganze Dokument"); + mnuEdit.add(a); + } + + ////////////////////////////////////////// + // + ///////////////////////////////////////// + private void createTextArea() { + textArea = new JTextArea(); + getContentPane().add(new JScrollPane(textArea)); + } + + ///////////////////////////////////// + // + ///////////////////////////////////// + private void createListeners() { + textArea.getDocument().addDocumentListener(new DocumentListener() { + private void changed() { + setChanged(true); + } + + @Override + public void changedUpdate(DocumentEvent e) { + changed(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + changed(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + changed(); + } + }); + + textArea.getDocument().addUndoableEditListener(new UndoableEditListener() { + @Override + public void undoableEditHappened(UndoableEditEvent e) { + undo.addEdit(e.getEdit()); + actUndo.update(); + actRedo.update(); + } + }); + } + + //////////////////////////////////////////////////// + // + /////////////////////////////////////////////////// + public JTextEditorInternalFrame(String title) { + super(title); + createTextArea(); + createListeners(); + createActions(); + } + + ////////////////////////////////////////////////// + // + ///////////////////////////////////////////////// + public JTextEditorInternalFrame(File file) { + super(file); + createTextArea(); + + if (file.exists()) { + FileReader in = null; + try { + in = new FileReader(file); + textArea.read(in, null); + } catch (IOException exc) { + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException exc) { + } + } + } + } + + createListeners(); + createActions(); + } @Override - public void setSelected(boolean value) throws java.beans.PropertyVetoException{ - super.setSelected(value); + public void save(File f) { + FileWriter out = null; + try { + out = new FileWriter(f); + textArea.write(out); + } catch (IOException exc) { + } finally { + if (out != null) { + try { + out.close(); + } catch (IOException exc) { + } + } + } - if(value) { - textArea.requestFocus(); - } - } + super.save(f); + } + + @Override + public void setSelected(boolean value) throws java.beans.PropertyVetoException { + super.setSelected(value); + + if (value) { + textArea.requestFocus(); + } + } } diff --git a/src/eva2/gui/JTextoutputFrame.java b/src/eva2/gui/JTextoutputFrame.java index 418f6e95..e41a1aa1 100644 --- a/src/eva2/gui/JTextoutputFrame.java +++ b/src/eva2/gui/JTextoutputFrame.java @@ -8,6 +8,7 @@ package eva2.gui; import eva2.EvAInfo; import eva2.optimization.tools.FileTools; import eva2.tools.BasicResourceLoader; + import java.awt.BorderLayout; import java.awt.Point; import java.awt.event.*; diff --git a/src/eva2/gui/LoggingLevelLabel.java b/src/eva2/gui/LoggingLevelLabel.java index d73b9b9f..b5d4e33c 100644 --- a/src/eva2/gui/LoggingLevelLabel.java +++ b/src/eva2/gui/LoggingLevelLabel.java @@ -26,7 +26,7 @@ public final class LoggingLevelLabel extends JLabel { private JPopupMenu menu; private String[] options; private Logger logger; - + public LoggingLevelLabel(final Logger logger) { options = new String[]{"Info", "Warning", "Severe", "Fine", "Finer", "Finest", "All"}; @@ -36,7 +36,7 @@ public final class LoggingLevelLabel extends JLabel { createPopupMenu(); updateText(); } - + private void createPopupMenu() { this.menu = new JPopupMenu(); addMouseListener(new MouseListener() { @@ -59,7 +59,7 @@ public final class LoggingLevelLabel extends JLabel { } @Override - public void mouseExited(MouseEvent e) { + public void mouseExited(MouseEvent e) { } }); @@ -85,20 +85,20 @@ public final class LoggingLevelLabel extends JLabel { /* Show the updated text */ setText("Level: " + lvl.getName()); } - + /** * Sets the level of the logger to a new level. - * + * * @param level The new level for the logger */ - private void setLoggerLevel(Level level) { + private void setLoggerLevel(Level level) { // Recursively set logging level for all classes under eva2 Logger.getLogger("eva2").setLevel(level); logger.log(Level.INFO, "Logging Level changed to {0}", level.getName()); } - + /** - * + * */ class MenuActionListener implements ActionListener { @@ -115,6 +115,6 @@ public final class LoggingLevelLabel extends JLabel { } LoggingLevelLabel.this.updateText(); - } + } } } diff --git a/src/eva2/gui/LoggingPanel.java b/src/eva2/gui/LoggingPanel.java index 77a68b9e..b966f15d 100644 --- a/src/eva2/gui/LoggingPanel.java +++ b/src/eva2/gui/LoggingPanel.java @@ -9,6 +9,7 @@ package eva2.gui; * $Date: 2007-10-23 12:56:51 +0200 (Tue, 23 Oct 2007) $ * $Author: mkron $ */ + import java.awt.BorderLayout; import java.awt.Color; import java.awt.Point; @@ -26,91 +27,95 @@ import javax.swing.event.ChangeListener; * */ public class LoggingPanel extends JPanel { - protected static Logger logger; - protected JTextArea loggingTextArea = new JTextArea(10,20); - protected boolean firstMessage = true; - protected Handler loggingHandler; - protected JPopupMenu loggingLevelMenu; - /** - * - */ - public LoggingPanel(Logger logger) { - this.logger = logger; - loggingTextArea.setEditable(false); - loggingTextArea.setLineWrap(true); + protected static Logger logger; + protected JTextArea loggingTextArea = new JTextArea(10, 20); + protected boolean firstMessage = true; + protected Handler loggingHandler; + protected JPopupMenu loggingLevelMenu; + + /** + * + */ + public LoggingPanel(Logger logger) { + this.logger = logger; + loggingTextArea.setEditable(false); + loggingTextArea.setLineWrap(true); loggingTextArea.setBorder(BorderFactory.createEmptyBorder()); - - setLayout(new BorderLayout()); - + + setLayout(new BorderLayout()); + add(new JLabel("Info"), BorderLayout.PAGE_START); - - this.loggingHandler = new LoggingHandler(this); - logger.addHandler(loggingHandler); - - final JScrollPane scrollpane = new JScrollPane(loggingTextArea); + + this.loggingHandler = new LoggingHandler(this); + logger.addHandler(loggingHandler); + + final JScrollPane scrollpane = new JScrollPane(loggingTextArea); scrollpane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); // scrollpane.setAutoscrolls(false); - add(scrollpane, BorderLayout.CENTER); - scrollpane.getViewport().addChangeListener(new ChangeListener() { - private int lastHeight; - // + add(scrollpane, BorderLayout.CENTER); + scrollpane.getViewport().addChangeListener(new ChangeListener() { + private int lastHeight; + + // @Override - public void stateChanged(ChangeEvent e) { - JViewport viewport = (JViewport)e.getSource(); - int height = viewport.getViewSize().height; - if (height != lastHeight) { - lastHeight = height; - int x = height - viewport.getExtentSize().height; - viewport.setViewPosition(new Point(0, x)); - } - } - }); - } - /** - * - */ - protected static String getTimestamp() { - return (new SimpleDateFormat("HH:mm:ss:")).format(new Date()); - } - /** - * - */ - public void logMessage(String message) { - loggingTextArea.append(LoggingPanel.getTimestamp() + ' ' + message); - loggingTextArea.append("\n"); - } + public void stateChanged(ChangeEvent e) { + JViewport viewport = (JViewport) e.getSource(); + int height = viewport.getViewSize().height; + if (height != lastHeight) { + lastHeight = height; + int x = height - viewport.getExtentSize().height; + viewport.setViewPosition(new Point(0, x)); + } + } + }); + } + + /** + * + */ + protected static String getTimestamp() { + return (new SimpleDateFormat("HH:mm:ss:")).format(new Date()); + } + + /** + * + */ + public void logMessage(String message) { + loggingTextArea.append(LoggingPanel.getTimestamp() + ' ' + message); + loggingTextArea.append("\n"); + } } class LoggingHandler extends Handler { - protected LoggingPanel loggingPanel; - - public LoggingHandler(LoggingPanel loggingPanel) { - this.loggingPanel = loggingPanel; - } + protected LoggingPanel loggingPanel; - @Override - public void publish(LogRecord record) { - StringBuilder sBuilder = new StringBuilder(); - sBuilder.append("["); - sBuilder.append(record.getLevel().toString()); - sBuilder.append("] "); - MessageFormat messageFormat = new MessageFormat(record.getMessage()); - sBuilder.append(messageFormat.format(record.getParameters())); - // Show message on LogPanel - this.loggingPanel.logMessage(sBuilder.toString()); - } + public LoggingHandler(LoggingPanel loggingPanel) { + this.loggingPanel = loggingPanel; + } - @Override - public void flush() { - /* - * We do nothing here as we don't buffer the entries + @Override + public void publish(LogRecord record) { + StringBuilder sBuilder = new StringBuilder(); + sBuilder.append("["); + sBuilder.append(record.getLevel().toString()); + sBuilder.append("] "); + MessageFormat messageFormat = new MessageFormat(record.getMessage()); + sBuilder.append(messageFormat.format(record.getParameters())); + // Show message on LogPanel + this.loggingPanel.logMessage(sBuilder.toString()); + } + + @Override + public void flush() { + /* + * We do nothing here as we don't buffer the entries */ - } + } - @Override - public void close() throws SecurityException { + @Override + public void close() throws SecurityException { /* * Nothing to close */ - } + } } \ No newline at end of file diff --git a/src/eva2/gui/Main.java b/src/eva2/gui/Main.java index b72db50f..da54173a 100644 --- a/src/eva2/gui/Main.java +++ b/src/eva2/gui/Main.java @@ -77,7 +77,7 @@ public class Main extends JFrame implements OptimizationStateListener { private ExtAction actLicense; // if not null, the module is loaded automatically and no other can be selected - private String useDefaultModule = null; //"Genetic_Optimization"; + private String useDefaultModule = null; //"Genetic_Optimization"; private boolean showLoadModules = false; private boolean localMode = false; @@ -114,7 +114,6 @@ public class Main extends JFrame implements OptimizationStateListener { * Constructor of GUI of EvA2. Works as client for the EvA2 server. Note * that the Main initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. - * */ public Main(final String hostName) { this(hostName, null, false, false); @@ -126,11 +125,11 @@ public class Main extends JFrame implements OptimizationStateListener { * efficiency. Use {@link #awaitGuiInitialized()} to await full * initialization if necessary. * - * @see #EvAClient(String, java.awt.Window, String, boolean, boolean, boolean) * @param hostName * @param paramsFile * @param autorun * @param nosplash + * @see #EvAClient(String, java.awt.Window, String, boolean, boolean, boolean) */ public Main(final String hostName, final String paramsFile, boolean autorun, boolean nosplash) { this(hostName, null, paramsFile, null, autorun, nosplash, false, false); @@ -141,11 +140,10 @@ public class Main extends JFrame implements OptimizationStateListener { * initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * - * @see #Main(String, String, boolean, boolean) - * * @param hostName * @param autorun * @param nosplash + * @see #Main(String, String, boolean, boolean) */ public Main(final String hostName, boolean autorun, boolean nosplash) { this(hostName, null, autorun, nosplash); @@ -156,12 +154,12 @@ public class Main extends JFrame implements OptimizationStateListener { * initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * - * @see #Main(String, String, boolean, boolean) * @param hostName * @param paramsFile * @param autorun * @param noSplash * @param noGui + * @see #Main(String, String, boolean, boolean) */ public Main(final String hostName, String paramsFile, boolean autorun, boolean noSplash, boolean noGui, boolean withTreeView) { this(hostName, null, paramsFile, null, autorun, noSplash, noGui, withTreeView); @@ -172,13 +170,12 @@ public class Main extends JFrame implements OptimizationStateListener { * initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * - * @see #Main(String, String, boolean, boolean) - * * @param hostName * @param paramsFile * @param autorun * @param noSplash * @param noGui + * @see #Main(String, String, boolean, boolean) */ public Main(final String hostName, InterfaceOptimizationParameters goParams, boolean autorun, boolean noSplash, boolean noGui) { this(hostName, null, null, goParams, autorun, noSplash, noGui, false); @@ -401,7 +398,7 @@ public class Main extends JFrame implements OptimizationStateListener { } logPanel = new LoggingPanel(LOGGER); - logPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); + logPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); if (EvAInfo.propShowModules() != null) { @@ -551,7 +548,6 @@ public class Main extends JFrame implements OptimizationStateListener { /** * Refresh the parameter panels (if settings have been changed outside of * the GUI which should be updated in the GUI. - * */ public void refreshMainPanels() { frameMaker.refreshPanels(); @@ -567,8 +563,8 @@ public class Main extends JFrame implements OptimizationStateListener { * @param args command line parameters */ public static void main(String[] args) { - /*============================COPIED FROM SYSBIO==============================*/ - // Properties for Mac OS X support. + /*============================COPIED FROM SYSBIO==============================*/ + // Properties for Mac OS X support. if ((System.getProperty("mrj.version") != null) || (System.getProperty("os.name").toLowerCase().indexOf("mac") != -1)) { /* @@ -585,13 +581,13 @@ public class Main extends JFrame implements OptimizationStateListener { System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); System.setProperty("com.apple.mrj.application.live-resize", "true"); } - /*==========================================================================*/ + /*==========================================================================*/ /* Available command-line parameters */ String[] keys = new String[]{ - "--help", "--autorun", "--nosplash", "--nogui", - "--remotehost", "--params", "--treeView" + "--help", "--autorun", "--nosplash", "--nogui", + "--remotehost", "--params", "--treeView" }; /* Number of arguments per parameter */ int[] arities = new int[]{0, 0, 0, 0, 1, 1, 0}; @@ -627,14 +623,14 @@ public class Main extends JFrame implements OptimizationStateListener { * Initialize the client GUI with given parameters and set listeners. This * will return as soon as the GUI is visible and ready. * - * @param goParams optimization parameters - * @param statisticsListener statistics listener receiving data during - * optimization - * @param windowListener additional window listener for client frame + * @param goParams optimization parameters + * @param statisticsListener statistics listener receiving data during + * optimization + * @param windowListener additional window listener for client frame */ public static Main initClientGUI(OptimizationParameters goParams, - InterfaceStatisticsListener statisticsListener, - WindowListener windowListener, final Window parent) { + InterfaceStatisticsListener statisticsListener, + WindowListener windowListener, final Window parent) { Main evaClient; evaClient = new Main(null, parent, null, goParams, @@ -931,10 +927,10 @@ public class Main extends JFrame implements OptimizationStateListener { * Create a tree view of an object based on EvATreeNode. It is encapsulated * in a JScrollPane. * - * @see eva2.gui.EvATreeNode * @param title * @param object * @return + * @see eva2.gui.EvATreeNode */ public JComponent getEvATreeView(JParaPanel goPanel, String title, Object object) { EvATreeNode root = new EvATreeNode(title, object); // the root of the tree diff --git a/src/eva2/gui/Mnemonic.java b/src/eva2/gui/Mnemonic.java index 3e0bf48a..63761f1a 100644 --- a/src/eva2/gui/Mnemonic.java +++ b/src/eva2/gui/Mnemonic.java @@ -7,6 +7,7 @@ package eva2.gui; * Time: 18:30:44 * To change this template use Options | File Templates. */ + /** * */ diff --git a/src/eva2/gui/MultiLineString.java b/src/eva2/gui/MultiLineString.java index a2e1ab4d..7e8e55ab 100644 --- a/src/eva2/gui/MultiLineString.java +++ b/src/eva2/gui/MultiLineString.java @@ -5,21 +5,23 @@ package eva2.gui; * @version 1.0 */ -public class MultiLineString { +public class MultiLineString { - String string = ""; + String string = ""; - public MultiLineString() { - } + public MultiLineString() { + } - public static void main(String[] args) { - MultiLineString multiLineString1 = new MultiLineString(); - } - public String getString() { - return string; - } - public void setString(String string) { - this.string = string; - } + public static void main(String[] args) { + MultiLineString multiLineString1 = new MultiLineString(); + } + + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } } diff --git a/src/eva2/gui/PanelMaker.java b/src/eva2/gui/PanelMaker.java index 44ff2c77..2484ad7d 100644 --- a/src/eva2/gui/PanelMaker.java +++ b/src/eva2/gui/PanelMaker.java @@ -4,9 +4,9 @@ import javax.swing.JComponent; /** * Simple helper interface. - * @author mkron * + * @author mkron */ public interface PanelMaker { - public JComponent makePanel(); + public JComponent makePanel(); } diff --git a/src/eva2/gui/PropertyDialog.java b/src/eva2/gui/PropertyDialog.java index 77a46786..64819aca 100644 --- a/src/eva2/gui/PropertyDialog.java +++ b/src/eva2/gui/PropertyDialog.java @@ -8,6 +8,7 @@ package eva2.gui; import eva2.EvAInfo; import eva2.tools.BasicResourceLoader; import eva2.tools.EVAHELP; + import java.awt.BorderLayout; import java.awt.Component; import java.beans.PropertyEditor; @@ -25,7 +26,7 @@ public class PropertyDialog extends JDialog { * */ public PropertyDialog(PropertyEditor editor, String title, int x, int y) { - super(); + super(); setTitle(getFrameNameFromEditor(editor)); //super(getFrameNameFromEditor(editor)); // that was the long class name !! BasicResourceLoader loader = BasicResourceLoader.instance(); diff --git a/src/eva2/gui/PropertyDoubleArray.java b/src/eva2/gui/PropertyDoubleArray.java index 8b4efcb5..5b3038e4 100644 --- a/src/eva2/gui/PropertyDoubleArray.java +++ b/src/eva2/gui/PropertyDoubleArray.java @@ -8,13 +8,13 @@ public class PropertyDoubleArray implements java.io.Serializable { private int m_numCols = 1; public PropertyDoubleArray(double[] d) { - setDoubleArray(d); + setDoubleArray(d); } - + public PropertyDoubleArray(double[][] d) { - setDoubleArray(d); + setDoubleArray(d); } - + public PropertyDoubleArray(PropertyDoubleArray d) { this.m_DoubleArray = d.m_DoubleArray.clone(); this.m_numCols = d.m_numCols; @@ -24,189 +24,195 @@ public class PropertyDoubleArray implements java.io.Serializable { /** * Constructor that creates a double matrix with given dimensions and fills * it cyclically with values given. + * * @param rows * @param cols * @param d */ - public PropertyDoubleArray(int rows, int cols, double ... d) { - if (rows>0 && cols>0) { + public PropertyDoubleArray(int rows, int cols, double... d) { + if (rows > 0 && cols > 0) { this.m_DoubleArray = new double[rows][cols]; + } else { + this.m_DoubleArray = null; } - else { - this.m_DoubleArray=null; + this.m_numCols = cols; + int index = 0; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + m_DoubleArray[i][j] = d[index]; + index++; + if (index >= d.length) { + index = 0; + } + } } - this.m_numCols=cols; - int index=0; - for (int i=0; i=d.length) { - index=0; - } - } - } - } + } @Override - public Object clone() { + public Object clone() { return (Object) new PropertyDoubleArray(this); } - /** This method will allow you to set the value of the double array - * @param d The double[] + /** + * This method will allow you to set the value of the double array + * + * @param d The double[] */ public void setDoubleArray(double[] d) { - this.m_DoubleArray = new double[d.length][1]; - for (int i=0; i0) { - m_numCols=d[0].length; - } - else { - m_numCols=1; + this.m_DoubleArray = d; + if (d.length > 0) { + m_numCols = d[0].length; + } else { + m_numCols = 1; } } - - /** + + /** * @return the double array itself (no clone) */ public double[][] getDoubleArrayShallow() { - return this.m_DoubleArray; + return this.m_DoubleArray; } - + /** * Return a column as a vector (in copy) + * * @return a column as a vector (in copy) */ public double[] getDoubleColumnAsVector(int col) { - if (col>=m_numCols) { - throw new IllegalArgumentException("Error, invalid column selected, " + col + " of " + m_numCols); - } - double[] ret = new double[m_DoubleArray.length]; - for (int i=0; i= m_numCols) { + throw new IllegalArgumentException("Error, invalid column selected, " + col + " of " + m_numCols); } - return ret; + double[] ret = new double[m_DoubleArray.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = m_DoubleArray[i][col]; + } + return ret; } - + public int getNumCols() { - return m_numCols; + return m_numCols; } - + public int getNumRows() { - return m_DoubleArray.length; + return m_DoubleArray.length; } - + public double getValue(int i, int j) { - if (i<0 || j<0 || (i>=getNumRows()) || (j>=getNumCols())) { - throw new IllegalArgumentException("Error, invalid access to double array: " + i + "," + j + " within " + getNumRows() + ","+getNumCols()); - } - return m_DoubleArray[i][j]; + if (i < 0 || j < 0 || (i >= getNumRows()) || (j >= getNumCols())) { + throw new IllegalArgumentException("Error, invalid access to double array: " + i + "," + j + " within " + getNumRows() + "," + getNumCols()); + } + return m_DoubleArray[i][j]; } - public void adaptRowCount(int k) { - if (k!=m_DoubleArray.length) { - double[][] newDD = new double[k][m_numCols]; - for (int i=0; i=getNumRows()) { - throw new IllegalArgumentException("Invalid index to deleteRow: " + k + " is not a valid row."); - } - double[][] newDD = new double[getNumRows()-1][getNumCols()]; - int inc=0; - for (int i = 0; i < newDD.length; i++) { - if (i==k) { - inc=1; + public void adaptRowCount(int k) { + if (k != m_DoubleArray.length) { + double[][] newDD = new double[k][m_numCols]; + for (int i = 0; i < k; i++) { + for (int j = 0; j < m_numCols; j++) { + if (i < m_DoubleArray.length) { + newDD[i][j] = m_DoubleArray[i][j]; + } else { + newDD[i][j] = m_DoubleArray[m_DoubleArray.length - 1][j]; } - for (int j=0; j= getNumRows()) { - k=getNumRows()-1; - } - double[][] newDD = new double[getNumRows()+1][getNumCols()]; - - for (int i = 0; i < getNumRows(); i++) { - for (int j = 0; j=0) { - for (int j=0; j= getNumRows()) { + throw new IllegalArgumentException("Invalid index to deleteRow: " + k + " is not a valid row."); + } + double[][] newDD = new double[getNumRows() - 1][getNumCols()]; + int inc = 0; + for (int i = 0; i < newDD.length; i++) { + if (i == k) { + inc = 1; + } + for (int j = 0; j < getNumCols(); j++) { + newDD[i][j] = m_DoubleArray[i + inc][j]; + } + } + setDoubleArray(newDD); + } + + /** + * Add a copy of an indexed row at the end. If the given index + * is invalid, the last row is copied. + * + * @param k + */ + public void addRowCopy(int k) { + if (k < 0 || k >= getNumRows()) { + k = getNumRows() - 1; + } + double[][] newDD = new double[getNumRows() + 1][getNumCols()]; + + for (int i = 0; i < getNumRows(); i++) { + for (int j = 0; j < getNumCols(); j++) { + newDD[i][j] = m_DoubleArray[i][j]; + } + } + if (k >= 0) { + for (int j = 0; j < getNumCols(); j++) { + newDD[newDD.length - 1][j] = newDD[k][j]; + } + } else { + for (int j = 0; j < getNumCols(); j++) { + newDD[newDD.length - 1][j] = 1.; + } + } // if the array was empty + setDoubleArray(newDD); + } + + /** + * Normalize all columns of the array by dividing through the sum. + */ + public void normalizeColumns() { + double colSum = 0; + for (int j = 0; j < getNumCols(); j++) { + colSum = 0; + for (int i = 0; i < getNumRows(); i++) { + colSum += m_DoubleArray[i][j]; + } + if (colSum != 0) { + for (int i = 0; i < getNumRows(); i++) { + m_DoubleArray[i][j] /= colSum; + } + } + } + } + + /** + * Check if k is a valid row index (within 0 and numRows-1). + * + * @param k + * @return + */ + public boolean isValidRow(int k) { + return (k >= 0) && (k < getNumRows()); + } - /** - * Check if k is a valid row index (within 0 and numRows-1). - * @param k - * @return - */ - public boolean isValidRow(int k) { - return (k>=0) && (k= this.m_SelectedObjectives.length)) { return; } - InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length-1]; + InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length - 1]; int j = 0; for (int i = 0; i < this.m_SelectedObjectives.length; i++) { if (index != i) { @@ -73,11 +82,13 @@ public class PropertyOptimizationObjectives implements java.io.Serializable { this.m_SelectedObjectives = newList; } - /** This method allows you to add a new target to the list + /** + * This method allows you to add a new target to the list + * * @param optTarget */ public void addTarget(InterfaceOptimizationObjective optTarget) { - InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length+1]; + InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length + 1]; for (int i = 0; i < this.m_SelectedObjectives.length; i++) { newList[i] = this.m_SelectedObjectives[i]; } diff --git a/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java b/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java index 68627892..f7a1e352 100644 --- a/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java +++ b/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java @@ -11,28 +11,29 @@ import eva2.optimization.problems.InterfaceOptimizationObjective; */ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializable { - public InterfaceOptimizationObjective[] m_AvailableObjectives; - public InterfaceOptimizationObjective[] m_SelectedObjectives; - public double[] m_Weights; - public String m_DescriptiveString = "No Description given."; - public String m_WeightsLabel = "-"; - public boolean m_NormalizationEnabled = true; + public InterfaceOptimizationObjective[] m_AvailableObjectives; + public InterfaceOptimizationObjective[] m_SelectedObjectives; + public double[] m_Weights; + public String m_DescriptiveString = "No Description given."; + public String m_WeightsLabel = "-"; + public boolean m_NormalizationEnabled = true; public PropertyOptimizationObjectivesWithParam(InterfaceOptimizationObjective[] d) { this.m_AvailableObjectives = d; - this.m_SelectedObjectives = null; + this.m_SelectedObjectives = null; } + public PropertyOptimizationObjectivesWithParam(PropertyOptimizationObjectivesWithParam d) { - this.m_DescriptiveString = d.m_DescriptiveString; - this.m_WeightsLabel = d.m_WeightsLabel; - this.m_NormalizationEnabled = d.m_NormalizationEnabled; - this.m_AvailableObjectives = new InterfaceOptimizationObjective[d.m_AvailableObjectives.length]; + this.m_DescriptiveString = d.m_DescriptiveString; + this.m_WeightsLabel = d.m_WeightsLabel; + this.m_NormalizationEnabled = d.m_NormalizationEnabled; + this.m_AvailableObjectives = new InterfaceOptimizationObjective[d.m_AvailableObjectives.length]; for (int i = 0; i < this.m_AvailableObjectives.length; i++) { - this.m_AvailableObjectives[i] = (InterfaceOptimizationObjective)d.m_AvailableObjectives[i].clone(); + this.m_AvailableObjectives[i] = (InterfaceOptimizationObjective) d.m_AvailableObjectives[i].clone(); } - this.m_SelectedObjectives = new InterfaceOptimizationObjective[d.m_SelectedObjectives.length]; + this.m_SelectedObjectives = new InterfaceOptimizationObjective[d.m_SelectedObjectives.length]; for (int i = 0; i < this.m_SelectedObjectives.length; i++) { - this.m_SelectedObjectives[i] = (InterfaceOptimizationObjective)d.m_SelectedObjectives[i].clone(); + this.m_SelectedObjectives[i] = (InterfaceOptimizationObjective) d.m_SelectedObjectives[i].clone(); } if (d.m_Weights != null) { this.m_Weights = new double[d.m_Weights.length]; @@ -45,8 +46,10 @@ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializ return (Object) new PropertyOptimizationObjectivesWithParam(this); } - /** This method will allow you to set the value of the InterfaceOptimizationTarget array - * @param d The InterfaceOptimizationTarget[] + /** + * This method will allow you to set the value of the InterfaceOptimizationTarget array + * + * @param d The InterfaceOptimizationTarget[] */ public void setSelectedTargets(InterfaceOptimizationObjective[] d) { this.m_SelectedObjectives = d; @@ -62,7 +65,7 @@ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializ if (d.length == this.m_Weights.length) { return; } - + if (d.length > this.m_Weights.length) { double[] newWeights = new double[d.length]; for (int i = 0; i < this.m_Weights.length; i++) { @@ -78,70 +81,88 @@ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializ } } - /** This method will return the InterfaceOptimizationTarget array + /** + * This method will return the InterfaceOptimizationTarget array + * * @return The InterfaceOptimizationTarget[]. */ public InterfaceOptimizationObjective[] getSelectedTargets() { return this.m_SelectedObjectives; } - /** This method will return the InterfaceOptimizationTarget array + /** + * This method will return the InterfaceOptimizationTarget array + * * @return The InterfaceOptimizationTarget[]. */ public InterfaceOptimizationObjective[] getAvailableTargets() { return this.m_AvailableObjectives; } - /** This method allows you to read the weights + /** + * This method allows you to read the weights + * * @return the weights */ public double[] getWeights() { return this.m_Weights; } + public void setWeights(double[] d) { this.m_Weights = d; } - /** This method allows you to set/get the descriptive string + /** + * This method allows you to set/get the descriptive string + * * @return the string */ public String getDescriptiveString() { return this.m_DescriptiveString; } + public void setDescriptiveString(String d) { this.m_DescriptiveString = d; } - /** This method allows you to set/get the weights label + /** + * This method allows you to set/get the weights label + * * @return the string */ public String getWeigthsLabel() { return this.m_WeightsLabel; } + public void setWeightsLabel(String d) { this.m_WeightsLabel = d; } - /** This method allows you to set/get the weights label + /** + * This method allows you to set/get the weights label + * * @return the string */ public boolean isNormalizationEnabled() { return this.m_NormalizationEnabled; } + public void enableNormalization(boolean d) { this.m_NormalizationEnabled = d; } - /** This method allows you to remove a Target from the list - * @param index The index of the target to be removed. + /** + * This method allows you to remove a Target from the list + * + * @param index The index of the target to be removed. */ public void removeTarget(int index) { if ((index < 0) || (index >= this.m_SelectedObjectives.length)) { return; } - InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length-1]; - double[] newWeights = new double[this.m_Weights.length - 1]; + InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length - 1]; + double[] newWeights = new double[this.m_Weights.length - 1]; int j = 0; for (int i = 0; i < this.m_SelectedObjectives.length; i++) { if (index != i) { @@ -150,23 +171,25 @@ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializ j++; } } - this.m_SelectedObjectives = newList; - this.m_Weights = newWeights; + this.m_SelectedObjectives = newList; + this.m_Weights = newWeights; } - /** This method allows you to add a new target to the list + /** + * This method allows you to add a new target to the list + * * @param optTarget */ public void addTarget(InterfaceOptimizationObjective optTarget) { - InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length+1]; - double[] newWeights = new double[this.m_Weights.length + 1]; + InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length + 1]; + double[] newWeights = new double[this.m_Weights.length + 1]; for (int i = 0; i < this.m_SelectedObjectives.length; i++) { newList[i] = this.m_SelectedObjectives[i]; newWeights[i] = this.m_Weights[i]; } newList[this.m_SelectedObjectives.length] = optTarget; newWeights[this.m_SelectedObjectives.length] = 1.0; - this.m_SelectedObjectives = newList; - this.m_Weights = newWeights; + this.m_SelectedObjectives = newList; + this.m_Weights = newWeights; } } \ No newline at end of file diff --git a/src/eva2/gui/PropertyPanel.java b/src/eva2/gui/PropertyPanel.java index a5de5b9f..6386b09f 100644 --- a/src/eva2/gui/PropertyPanel.java +++ b/src/eva2/gui/PropertyPanel.java @@ -9,7 +9,9 @@ package eva2.gui; * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ + import eva2.tools.EVAHELP; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -18,76 +20,77 @@ import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; + /** * */ public class PropertyPanel extends JPanel { - private PropertyEditor propertyEditor; - private PropertyDialog propertyDialog; - + private PropertyEditor propertyEditor; + private PropertyDialog propertyDialog; + private JLabel textLabel; - /** - * - */ - public PropertyPanel(PropertyEditor editor) { - setToolTipText("Click to edit properties for this object"); - setOpaque(true); - + + /** + * + */ + public PropertyPanel(PropertyEditor editor) { + setToolTipText("Click to edit properties for this object"); + setOpaque(true); + setLayout(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.gridx = 0; gbConstraints.gridy = 0; gbConstraints.weightx = 1.0; gbConstraints.fill = GridBagConstraints.HORIZONTAL; - propertyEditor = editor; - + propertyEditor = editor; + textLabel = new JLabel(); add(textLabel, gbConstraints); - } - - public void showDialog(int initX, int initY) { - if (propertyDialog == null) { - propertyDialog = new PropertyDialog(propertyEditor, EVAHELP.cutClassName(propertyEditor.getClass().getName()) , initX, initY); - propertyDialog.setPreferredSize(new Dimension(500,300)); + } + + public void showDialog(int initX, int initY) { + if (propertyDialog == null) { + propertyDialog = new PropertyDialog(propertyEditor, EVAHELP.cutClassName(propertyEditor.getClass().getName()), initX, initY); + propertyDialog.setPreferredSize(new Dimension(500, 300)); propertyDialog.setModal(true); propertyDialog.setVisible(true); - } - else { - propertyDialog.updateFrameTitle(propertyEditor); - propertyDialog.setVisible(false); - propertyDialog.requestFocus(); - } - } - - /** - * - */ + } else { + propertyDialog.updateFrameTitle(propertyEditor); + propertyDialog.setVisible(false); + propertyDialog.requestFocus(); + } + } + + /** + * + */ @Override - public void removeNotify() { - if (propertyDialog != null) { - propertyDialog = null; - } - } - - /** - * - */ + public void removeNotify() { + if (propertyDialog != null) { + propertyDialog = null; + } + } + + /** + * + */ @Override - public void paintComponent(Graphics g) { - Insets i = textLabel.getInsets(); - Rectangle box = new Rectangle(i.left, i.top, - getSize().width - i.left - i.right , - getSize().height - i.top - i.bottom); - g.clearRect(i.left, i.top, - getSize().width - i.right - i.left, - getSize().height - i.bottom - i.top); - propertyEditor.paintValue(g, box); - } - - public PropertyEditor getEditor() { - return propertyEditor; - } + public void paintComponent(Graphics g) { + Insets i = textLabel.getInsets(); + Rectangle box = new Rectangle(i.left, i.top, + getSize().width - i.left - i.right, + getSize().height - i.top - i.bottom); + g.clearRect(i.left, i.top, + getSize().width - i.right - i.left, + getSize().height - i.bottom - i.top); + propertyEditor.paintValue(g, box); + } + + public PropertyEditor getEditor() { + return propertyEditor; + } } diff --git a/src/eva2/gui/PropertySelectableList.java b/src/eva2/gui/PropertySelectableList.java index f92e88b3..fafb1483 100644 --- a/src/eva2/gui/PropertySelectableList.java +++ b/src/eva2/gui/PropertySelectableList.java @@ -12,18 +12,18 @@ import java.beans.PropertyChangeSupport; */ public class PropertySelectableList implements java.io.Serializable { - protected T[] m_Objects; - protected boolean[] m_Selection; - private transient PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + protected T[] m_Objects; + protected boolean[] m_Selection; + private transient PropertyChangeSupport m_Support = new PropertyChangeSupport(this); -// public PropertySelectableList() { + // public PropertySelectableList() { // } // public PropertySelectableList(T[] initial) { - m_Objects = initial; - m_Selection = new boolean[initial.length]; + m_Objects = initial; + m_Selection = new boolean[initial.length]; } - + public PropertySelectableList(PropertySelectableList b) { if (b.m_Objects != null) { this.m_Objects = b.m_Objects.clone(); @@ -33,18 +33,18 @@ public class PropertySelectableList implements java.io.Serializable { System.arraycopy(b.m_Selection, 0, this.m_Selection, 0, this.m_Selection.length); } } - + @Override public Object clone() { return (Object) new PropertySelectableList(this); } - + public void setObjects(T[] o) { this.m_Objects = o; this.m_Selection = new boolean[o.length]; m_Support.firePropertyChange("PropertySelectableList", null, this); } - + public void setObjects(T[] o, boolean[] selection) { this.m_Objects = o; this.m_Selection = selection; @@ -53,77 +53,77 @@ public class PropertySelectableList implements java.io.Serializable { } m_Support.firePropertyChange("PropertySelectableList", null, this); } - + public T[] getObjects() { return this.m_Objects; } - + /** * Returns the elements represented by this list where only the selected elements are non-null. + * * @return */ public T[] getSelectedObjects() { - T[] selObjects = getObjects().clone(); - for (int i=0; i implements java.io.Serializable { // } // m_Support.firePropertyChange("PropertySelectableList", null, this); // } - - public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { - m_Support = new PropertyChangeSupport(this); - } - m_Support.addPropertyChangeListener(l); - } - public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { - m_Support = new PropertyChangeSupport(this); - } - m_Support.removePropertyChangeListener(l); - } + public void addPropertyChangeListener(PropertyChangeListener l) { + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } + m_Support.addPropertyChangeListener(l); + } + + public void removePropertyChangeListener(PropertyChangeListener l) { + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } + m_Support.removePropertyChangeListener(l); + } } diff --git a/src/eva2/gui/PropertySheetPanel.java b/src/eva2/gui/PropertySheetPanel.java index 61120e8f..5539d4db 100644 --- a/src/eva2/gui/PropertySheetPanel.java +++ b/src/eva2/gui/PropertySheetPanel.java @@ -9,8 +9,10 @@ package eva2.gui; * $Date: 2007-12-05 11:29:32 +0100 (Wed, 05 Dec 2007) $ * $Author: mkron $ */ + import eva2.gui.editor.GenericObjectEditor; import eva2.tools.EVAHELP; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -25,6 +27,7 @@ import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; + /** * There are some trick methods interpreted here. Check EvA2Notes.txt. */ @@ -92,7 +95,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener boolean stripToolTipToFirstPoint = false; private JTable propertyTable; private DefaultTableModel propertyTableModel; - + /** * Creates the property sheet panel. */ @@ -120,7 +123,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener public void addPropertyChangeListener(PropertyChangeListener l) { if (propertyChangeSupport == null) { propertyChangeSupport = new PropertyChangeSupport(this); - } + } propertyChangeSupport.addPropertyChangeListener(l); } @@ -128,41 +131,41 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener public void removePropertyChangeListener(PropertyChangeListener l) { if (propertyChangeSupport == null) { propertyChangeSupport = new PropertyChangeSupport(this); - } + } propertyChangeSupport.removePropertyChangeListener(l); } - + /** * Create a fitting viewer component for an editor instance. If none can be * identified, null is returned. - * + * * @param editor * @return */ public static JComponent getView(PropertyEditor editor) { - JComponent view = null; - // Now figure out how to display it... - if (editor.isPaintable() && editor.supportsCustomEditor()) { - view = new PropertyPanel(editor); - } else { - String[] tags = editor.getTags(); + JComponent view = null; + // Now figure out how to display it... + if (editor.isPaintable() && editor.supportsCustomEditor()) { + view = new PropertyPanel(editor); + } else { + String[] tags = editor.getTags(); if (tags != null) { if ((tags.length == 2) && (tags[0].equals("True")) && (tags[1].equals("False"))) { view = new PropertyBoolSelector(editor); - } else { + } else { view = new PropertyValueSelector(editor); } } else { - if (editor.getAsText() != null) { - view = new PropertyText(editor); - } else { + if (editor.getAsText() != null) { + view = new PropertyText(editor); + } else { view = null; - } - } - } - return view; + } + } + } + return view; } - + /** * Sets a new target object for customisation. * @@ -171,7 +174,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener public synchronized void setTarget(Object targ) { propertyTableModel = new DefaultTableModel(); propertyTableModel.addColumn("Key"); - propertyTableModel.addColumn("Value"); + propertyTableModel.addColumn("Value"); propertyTable = new JTable(propertyTableModel); propertyTable.setDefaultRenderer(Object.class, new PropertyCellRenderer()); propertyTable.setDefaultEditor(Object.class, new PropertyCellEditor()); @@ -194,7 +197,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener } int rowHeight = 12; - + GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.fill = GridBagConstraints.BOTH; @@ -212,7 +215,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.anchor = GridBagConstraints.PAGE_START; add(infoPanel, gbConstraints); - } + } methsFound++; } // end if (name.equals("globalInfo")) { else if (name.equals("hideHideable")) { @@ -221,10 +224,10 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener meth.invoke(targetObject, args); } catch (Exception ex) { } - methsFound++; + methsFound++; } else if (name.equals("customPropertyOrder")) { - methsFound++; - reorderProperties(meth); + methsFound++; + reorderProperties(meth); } if (methsFound == 3) { break; // small speed-up @@ -232,7 +235,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener } // end for (int i = 0; i < m_Methods.length; i++) { // restore hide states of all properties // GenericObjectEditor.setHideProperties(m_Target.getClass(), hideStateBackup); - + // Now lets search for the individual properties, their // values, views and editors... propertyEditors = new PropertyEditor[propertyDescriptors.length]; @@ -243,7 +246,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener propertyLabels = new JLabel[propertyDescriptors.length]; toolTips = new String[propertyDescriptors.length]; - + for (int i = 0; i < propertyDescriptors.length; i++) { // For each property do this // Don't display hidden or expert properties. @@ -278,7 +281,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener name = eva2.tools.StringTools.humaniseCamelCase(name); propertyTableModel.addRow(new Object[]{name, newView}); } - + JScrollPane scrollableTable = new JScrollPane(propertyTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); gbConstraints.gridx = 0; gbConstraints.gridy = 1; @@ -294,38 +297,38 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener public static PropertyDescriptor[] getProperties(Object target) { BeanInfo bi; - try { - bi = Introspector.getBeanInfo(target.getClass()); - } catch (IntrospectionException e) { - e.printStackTrace(); - return null; - } + try { + bi = Introspector.getBeanInfo(target.getClass()); + } catch (IntrospectionException e) { + e.printStackTrace(); + return null; + } return bi.getPropertyDescriptors(); } - + public static String[] getPropertyNames(Object target) { return getNames(getProperties(target)); } - + public static Object[] getPropertyValues(Object target, boolean omitExpert, boolean omitHidden, boolean onlySetAndGettable) { - return getValues(target, getProperties(target), omitExpert, omitHidden, onlySetAndGettable); + return getValues(target, getProperties(target), omitExpert, omitHidden, onlySetAndGettable); } - + public static String[] getNames(PropertyDescriptor[] props) { String[] names = new String[props.length]; for (int i = 0; i < props.length; i++) { names[i] = props[i].getDisplayName(); - } - return names; + } + return names; } - + /** * Cycle the properties and request the value of each in an array. Null * values may indicate missing getter/setter, expert flag or hidden flag set * depending on the parameters. Note that to show hidden properties * dynamically, views may need be constructed for them anyways, so do not * omit them here. - * + * * @param props * @param omitExpert * @param omitHidden @@ -338,7 +341,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener // For each property do this // Don't display hidden or expert properties. // if (m_Properties[i].isHidden() || m_Properties[i].isExpert()) continue; - // we now look at hidden properties, they can be shown or hidden dynamically (MK) + // we now look at hidden properties, they can be shown or hidden dynamically (MK) String name = props[i].getDisplayName(); if (props[i].isExpert() && omitExpert) { continue; @@ -353,49 +356,49 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener continue; } Object args[] = {}; - Object value = null; - try { - value = getter.invoke(target, args); - } catch (Exception ex) { - System.out.println("Exception on getting value for property " + name + " on target " + target.toString()); - ex.printStackTrace(); + Object value = null; + try { + value = getter.invoke(target, args); + } catch (Exception ex) { + System.out.println("Exception on getting value for property " + name + " on target " + target.toString()); + ex.printStackTrace(); values[i] = null; - } + } // PropertyEditor editor = null; - //Class pec = m_Properties[i].getPropertyEditorClass(); + //Class pec = m_Properties[i].getPropertyEditorClass(); values[i] = value; } // end for each property return values; } - + /** * Create a label to be shown if no other properties are shown. - * + * * @param componentOffset * @param gbLayout * @return */ - private JLabel createDummyLabel(int componentOffset, GridBagLayout gbLayout) { + private JLabel createDummyLabel(int componentOffset, GridBagLayout gbLayout) { JLabel empty = new JLabel("No editable properties", SwingConstants.CENTER); - Dimension d = empty.getPreferredSize(); - empty.setPreferredSize(new Dimension(d.width * 2, d.height * 2)); - empty.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); - GridBagConstraints gbConstraints = new GridBagConstraints(); + Dimension d = empty.getPreferredSize(); + empty.setPreferredSize(new Dimension(d.width * 2, d.height * 2)); + empty.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); + GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.CENTER; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = componentOffset; gbConstraints.gridx = 0; - gbLayout.setConstraints(empty, gbConstraints); - return empty; - } + gbLayout.setConstraints(empty, gbConstraints); + return empty; + } private PropertyEditor makeEditor(PropertyDescriptor property, String name, Object value) { - PropertyEditor editor = PropertyEditorProvider.findEditor(property, value); + PropertyEditor editor = PropertyEditorProvider.findEditor(property, value); if (editor == null) { return null; } - + // Don't try to set null values: if (value == null) { // If it's a user-defined property we give a warning. @@ -408,14 +411,14 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener editor.setValue(value); // System.out.println("PSP editor class: " + editor.getClass()); - + editor.addPropertyChangeListener(this); return editor; } - - private void addLabelView(int componentOffset, GridBagLayout gbLayout, - int i, String name, JComponent newView) { - + + private void addLabelView(int componentOffset, GridBagLayout gbLayout, + int i, String name, JComponent newView) { + propertyLabels[i] = makeLabel(name); views[i] = newView; viewWrappers[i] = new JPanel(); @@ -425,50 +428,50 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener add(propertyLabels[i]); JPanel newPanel = makeViewPanel(toolTips[i], propertyLabels[i], views[i], viewWrappers[i]); gbLayout.setConstraints(newPanel, makeViewConstraints(i + componentOffset)); - add(newPanel); - } + add(newPanel); + } - private JLabel makeLabel(String name) { - JLabel label = new JLabel(name, SwingConstants.RIGHT); + private JLabel makeLabel(String name) { + JLabel label = new JLabel(name, SwingConstants.RIGHT); label.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 5)); - return label; - } - - private static JPanel makeViewPanel(String tipText, JLabel label, - JComponent view, JComponent viewWrapper) { - JPanel newPanel = new JPanel(); - if (tipText != null) { - label.setToolTipText(tipText); - view.setToolTipText(tipText); - } + return label; + } + + private static JPanel makeViewPanel(String tipText, JLabel label, + JComponent view, JComponent viewWrapper) { + JPanel newPanel = new JPanel(); + if (tipText != null) { + label.setToolTipText(tipText); + view.setToolTipText(tipText); + } newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); - newPanel.setLayout(new BorderLayout()); - // @todo: Streiche here i could add the ViewWrapper - viewWrapper.add(view, BorderLayout.CENTER); - newPanel.add(viewWrapper, BorderLayout.CENTER); - return newPanel; - } - - private GridBagConstraints makeLabelConstraints(int componentIndex) { - GridBagConstraints gbConstraints = new GridBagConstraints(); + newPanel.setLayout(new BorderLayout()); + // @todo: Streiche here i could add the ViewWrapper + viewWrapper.add(view, BorderLayout.CENTER); + newPanel.add(viewWrapper, BorderLayout.CENTER); + return newPanel; + } + + private GridBagConstraints makeLabelConstraints(int componentIndex) { + GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = componentIndex; gbConstraints.gridx = 0; - return gbConstraints; - } + return gbConstraints; + } - private GridBagConstraints makeViewConstraints(int componentIndex) { - GridBagConstraints gbConstraints = new GridBagConstraints(); + private GridBagConstraints makeViewConstraints(int componentIndex) { + GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.gridy = componentIndex; gbConstraints.gridx = 1; gbConstraints.weightx = 100; - return gbConstraints; - } - - /** + return gbConstraints; + } + + /** * Be sure to give a clone * * @param oldProps @@ -479,79 +482,79 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener // Mathematics.revertArray(oldProps, newProps); Object[] args = {}; Object retV = null; - PropertyDescriptor[] newProps = null; + PropertyDescriptor[] newProps = null; try { retV = meth.invoke(targetObject, args); // should return String[] to be interpreted as a list of ordered properties } catch (Exception ex) { } if (retV != null) { try { - if (retV.getClass().isArray()) { // reorder the properties + if (retV.getClass().isArray()) { // reorder the properties String[] swProps = (String[]) retV; PropertyDescriptor[] oldProps = propertyDescriptors.clone(); newProps = new PropertyDescriptor[oldProps.length]; - //int findFirst=findFirstProp(props[0], oldProps); + //int findFirst=findFirstProp(props[0], oldProps); int firstNonNull = 0; for (int i = 0; i < oldProps.length; i++) { if (i < swProps.length) { int pInOld = findProp(oldProps, swProps[i]); newProps[i] = oldProps[pInOld]; oldProps[pInOld] = null; - } else { - firstNonNull = findFirstNonNullAfter(oldProps, firstNonNull); + } else { + firstNonNull = findFirstNonNullAfter(oldProps, firstNonNull); newProps[i] = oldProps[firstNonNull]; - firstNonNull++; - } - } + firstNonNull++; + } + } propertyDescriptors = newProps; - } + } } catch (Exception e) { - System.err.println("Error during reordering properties: " + e.getMessage()); + System.err.println("Error during reordering properties: " + e.getMessage()); return propertyDescriptors; } } - return newProps; - } + return newProps; + } /** * Find the first non-null entry in an Array at or after the given index and * return its index. If only null entries are found, -1 is returned. - * + * * @param arr * @param firstLook * @return */ private int findFirstNonNullAfter(PropertyDescriptor[] arr, - int firstLook) { + int firstLook) { for (int i = firstLook; i < arr.length; i++) { if (arr[i] != null) { return i; } } - return -1; - } + return -1; + } - /** + /** * Find a string property in an array and return its index or -1 if not * found. - * + * * @param oldProps * @param string * @return */ - private int findProp(PropertyDescriptor[] oldProps, String string) { + private int findProp(PropertyDescriptor[] oldProps, String string) { for (int i = 0; i < oldProps.length; i++) { if (oldProps[i] == null) { continue; - } + } String name = oldProps[i].getDisplayName(); if (name.compareTo(string) == 0) { return i; } } - System.err.println("Error, property not found: " + string); - return -1; - } + System.err.println("Error, property not found: " + string); + return -1; + } private JPanel makeInfoPanel(Method meth, Object targ, int rowHeight) { if (meth.getReturnType().equals(String.class)) { @@ -583,9 +586,9 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener infoPanel.setBorder(BorderFactory.createTitledBorder("Info")); infoPanel.setLayout(new BorderLayout()); infoPanel.add(infoTextArea, BorderLayout.CENTER); - + if (HtmlDemo.resourceExists(getHelpFileName())) { - // this means that the expected URL really exists + // this means that the expected URL really exists infoPanel.add(helpButton, BorderLayout.LINE_END); } else { LOGGER.log(Level.FINE, "Not adding help button because of missing {0}", getHelpFileName()); @@ -596,7 +599,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener } return null; } - + private String translateGreek(String name) { // Add some specific display for some greeks here if (name.equalsIgnoreCase("alpha")) { @@ -703,19 +706,19 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener if (name.equalsIgnoreCase("pib")) { return "\u03A0"; } - - return name; - } - /** + return name; + } + + /** * Get the html help file name. - * + * * @return */ protected String getHelpFileName() { return EVAHELP.cutClassName(className) + ".html"; } - + /** * This method opens a help frame. */ @@ -732,10 +735,10 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener public int editableProperties() { return numEditableProperties; } - + /** * Return true if the modification was successful. - * + * * @param i * @param newValue * @return @@ -761,12 +764,12 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener ((GenericObjectEditor) tmpEdit).setClassType(propertyDescriptors[i].getPropertyType()); } propertyEditors[i].setValue(newValue); - JComponent newView = null; - newView = getView(tmpEdit); + JComponent newView = null; + newView = getView(tmpEdit); if (newView == null) { System.err.println("Warning: Property \"" + propertyDescriptors[i].getDisplayName() + "\" has non-displayable editor. Skipping."); - return false; - } + return false; + } propertyEditors[i].addPropertyChangeListener(this); views[i] = newView; if (toolTips[i] != null) { @@ -777,7 +780,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener viewWrappers[i].add(views[i], BorderLayout.CENTER); viewWrappers[i].repaint(); } - + // System.out.println("Value: "+value +" / m_Values[i]: " + m_Values[i]); // Now try to update the target with the new value of the property // and allow the target to do some changes to the value, therefore @@ -832,12 +835,12 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener PropertyEditor editor = (PropertyEditor) evt.getSource(); for (int i = 0; i < propertyEditors.length; i++) { if (propertyEditors[i] == editor) { - propIndex = i; + propIndex = i; if (wasModified(i, editor.getValue(), true)) { break; - } + } + } } - } if (propIndex == -1) { System.err.println("error: could not identify event editor! (PropertySheetPanel)"); } @@ -845,7 +848,7 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener System.err.println("unknown event source! (PropertySheetPanel)"); } } - + /** * Updates the propertysheet when a value has been changed (from outside the * propertysheet?). @@ -855,24 +858,24 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener synchronized boolean wasModified(int propIndex, Object value, boolean followDependencies) { if (!updateValue(propIndex, value)) { return false; - } - + } + boolean doRepaint = false; for (int i = 0; i < propertyEditors.length; i++) { // check the views for out-of-date information. this is different than checking the editors - if (i != propIndex) { + if (i != propIndex) { if (updateFieldView(i)) { doRepaint = true; } - }// end if (m_Editors[i] == editor) { + }// end if (m_Editors[i] == editor) { } // end for (int i = 0 ; i < m_Editors.length; i++) { - if (doRepaint) { // some components have been hidden or reappeared - // MK this finally seems to work right, with a scroll pane, too. + if (doRepaint) { // some components have been hidden or reappeared + // MK this finally seems to work right, with a scroll pane, too. Container p = this; - while (p != null && (!p.getSize().equals(p.getPreferredSize()))) { - p.setSize(p.getPreferredSize()); - p = p.getParent(); - } + while (p != null && (!p.getSize().equals(p.getPreferredSize()))) { + p.setSize(p.getPreferredSize()); + p = p.getParent(); + } } // Now re-read all the properties and update the editors @@ -888,44 +891,44 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener Object args[] = {}; o = getter.invoke(targetObject, args); } catch (Exception ex) { - o = null; - System.err.println(ex.getMessage()); - ex.printStackTrace(); + o = null; + System.err.println(ex.getMessage()); + ex.printStackTrace(); } if ((o != null) && o == objectValues[i] && (BeanInspector.isJavaPrimitive(o.getClass()))) { - // The property is equal to its old value. - continue; + // The property is equal to its old value. + continue; } if (o != null && o.equals(objectValues[i])) { - // The property is equal to its old value. - continue; + // The property is equal to its old value. + continue; } objectValues[i] = o; // Make sure we have an editor for this property... if (propertyEditors[i] == null) { - continue; + continue; } // The property has changed! Update the editor. propertyEditors[i].removePropertyChangeListener(this); propertyEditors[i].setValue(o); propertyEditors[i].addPropertyChangeListener(this); if (views[i] != null) { - //System.out.println("Trying to repaint " + (i + 1)); + //System.out.println("Trying to repaint " + (i + 1)); views[i].repaint(); } } if (followDependencies) { - // Handle the special method getGOEPropertyUpdateLinks which returns a list of pairs - // of strings indicating that on an update of the i-th property, the i+1-th property - // should be updated. This is useful for changes within sub-classes of the target - // which are not directly displayed in this panel but in sub-panels (and there have an own view etc.) + // Handle the special method getGOEPropertyUpdateLinks which returns a list of pairs + // of strings indicating that on an update of the i-th property, the i+1-th property + // should be updated. This is useful for changes within sub-classes of the target + // which are not directly displayed in this panel but in sub-panels (and there have an own view etc.) Object o = BeanInspector.callIfAvailable(targetObject, "getGOEPropertyUpdateLinks", null); - if ((o != null) && (o instanceof String[])) { + if ((o != null) && (o instanceof String[])) { maybeTriggerUpdates(propIndex, (String[]) o); - } + } } - + // Make sure the target bean gets repainted. if (Beans.isInstanceOf(targetObject, Component.class)) { //System.out.println("Beans.getInstanceOf repaint "); @@ -942,100 +945,100 @@ public class PropertySheetPanel extends JPanel implements PropertyChangeListener * @return */ private boolean updateFieldView(int i) { - // looking at another field (not changed explicitly, maybe implicitly - boolean valChanged = false; - boolean doRepaint = false; + // looking at another field (not changed explicitly, maybe implicitly + boolean valChanged = false; + boolean doRepaint = false; Object args[] = {}; Method getter = propertyDescriptors[i].getReadMethod(); if (propertyDescriptors[i].isHidden() || propertyDescriptors[i].isExpert()) { if ((propertyLabels[i] != null) && (propertyLabels[i].isVisible())) { - // something is set to hidden but was visible up to now + // something is set to hidden but was visible up to now viewWrappers[i].setVisible(false); views[i].setVisible(false); propertyLabels[i].setVisible(false); - doRepaint = true; - } - return doRepaint; - } else { + doRepaint = true; + } + return doRepaint; + } else { if ((propertyLabels[i] != null) && !(propertyLabels[i].isVisible())) { - // something is invisible but set to not hidden in the mean time + // something is invisible but set to not hidden in the mean time viewWrappers[i].setVisible(true); views[i].setVisible(true); propertyLabels[i].setVisible(true); - doRepaint = true; - } - } - try { // check if view i is up to date and in sync with the value of the getter + doRepaint = true; + } + } + try { // check if view i is up to date and in sync with the value of the getter if (views[i] != null) { Object val = getter.invoke(targetObject, args); if (views[i] instanceof PropertyBoolSelector) { valChanged = (((PropertyBoolSelector) views[i]).isSelected() != ((Boolean) val)); if (valChanged) { ((PropertyBoolSelector) views[i]).setSelected(((Boolean) val)); - } + } } else if (views[i] instanceof PropertyText) { valChanged = !(((PropertyText) views[i]).getText()).equals(val.toString()); if (valChanged) { ((PropertyText) views[i]).setText(val.toString()); - } + } } else if (views[i] instanceof PropertyPanel) { valChanged = false;//!((PropertyPanel)m_Views[i]).equals(value); // disregard whole panels and hope for the best } else if (views[i] instanceof PropertyValueSelector) { - //changed = !((SelectedTag)val).isSelectedString((String)((PropertyValueSelector)m_Views[i]).getSelectedItem()); - // interestingly there seems to be an implicit update of the ValueSelector, possible changes - // are already applied, all we need to see it is a repaint + //changed = !((SelectedTag)val).isSelectedString((String)((PropertyValueSelector)m_Views[i]).getSelectedItem()); + // interestingly there seems to be an implicit update of the ValueSelector, possible changes + // are already applied, all we need to see it is a repaint views[i].repaint(); - } else { - System.out.println("Warning: Property \"" + i - + "\" not recognized. Skipping."); - } - } + } else { + System.out.println("Warning: Property \"" + i + + "\" not recognized. Skipping."); + } + } } catch (Exception exc) { - System.err.println("Exception in PropertySheetPanel"); - } - return doRepaint; - } + System.err.println("Exception in PropertySheetPanel"); + } + return doRepaint; + } /** * Check the given link list and trigger updates of indicated properties. - * + * * @param propIndex * @param links */ - private void maybeTriggerUpdates(int propIndex, String[] links) { - int max = links.length; - if (max % 2 == 1) { - System.err.println("Error in PropertySheetPanel:maybeTriggerUpdates: odd number of strings provided!"); - max -= 1; - } + private void maybeTriggerUpdates(int propIndex, String[] links) { + int max = links.length; + if (max % 2 == 1) { + System.err.println("Error in PropertySheetPanel:maybeTriggerUpdates: odd number of strings provided!"); + max -= 1; + } for (int i = 0; i < max; i += 2) { if (links[i].equals(propertyDescriptors[propIndex].getName())) { updateLinkedProperty(links[i + 1]); - } - } - } + } + } + } - private void updateLinkedProperty(String propName) { + private void updateLinkedProperty(String propName) { for (int i = 0; i < propertyDescriptors.length; i++) { if (propertyDescriptors[i].getName().equals(propName)) { Method getter = propertyDescriptors[i].getReadMethod(); - Object val = null; - try { + Object val = null; + try { val = getter.invoke(targetObject, (Object[]) null); - } catch (Exception e) { - val = null; - e.printStackTrace(); - } - if (val != null) { + } catch (Exception e) { + val = null; + e.printStackTrace(); + } + if (val != null) { propertyEditors[i].setValue(val); } else { System.err.println("Error in PropertySheetPanel:updateLinkedProperty"); } - return; - } - } - } + return; + } + } + } } class PropertyTableModel extends DefaultTableModel implements TableModel { @@ -1062,11 +1065,11 @@ class PropertyCellRenderer implements TableCellRenderer { } else if (value instanceof PropertyValueSelector) { return (PropertyValueSelector) value; } - + throw new UnsupportedOperationException("Not supported yet."); - + } - + } class PropertyCellEditor extends AbstractCellEditor implements TableCellEditor { @@ -1145,5 +1148,4 @@ class PropertyCellEditor extends AbstractCellEditor implements TableCellEditor { } - } \ No newline at end of file diff --git a/src/eva2/gui/PropertySheetPanelStat.java b/src/eva2/gui/PropertySheetPanelStat.java index 305a5b27..ec317c36 100644 --- a/src/eva2/gui/PropertySheetPanelStat.java +++ b/src/eva2/gui/PropertySheetPanelStat.java @@ -12,6 +12,7 @@ package eva2.gui; /*==========================================================================* * IMPORTS *==========================================================================*/ + import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -24,82 +25,84 @@ import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; + /** * */ public class PropertySheetPanelStat extends JPanel implements Serializable { - public final static boolean TRACE = false; - private Object[] m_Values; - private JCheckBoxFlag[] m_Views; - private JLabel[] m_Labels; - private boolean[] m_flag; + public final static boolean TRACE = false; + private Object[] m_Values; + private JCheckBoxFlag[] m_Views; + private JLabel[] m_Labels; + private boolean[] m_flag; - /** - * Creates the property sheet panel. - */ - public PropertySheetPanelStat() { - // setBorder(BorderFactory.createLineBorder(Color.red)); + /** + * Creates the property sheet panel. + */ + public PropertySheetPanelStat() { + // setBorder(BorderFactory.createLineBorder(Color.red)); setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - } + } + /** * A support object for handling property change listeners */ - private PropertyChangeSupport m_support = new PropertyChangeSupport(this); + private PropertyChangeSupport m_support = new PropertyChangeSupport(this); - public synchronized void setTarget(String[] names, boolean[] flag) { - int componentOffset = 0; - // Close any child windows at this point - removeAll(); - GridBagLayout gbLayout = new GridBagLayout(); - setLayout(gbLayout); - setVisible(false); + public synchronized void setTarget(String[] names, boolean[] flag) { + int componentOffset = 0; + // Close any child windows at this point + removeAll(); + GridBagLayout gbLayout = new GridBagLayout(); + setLayout(gbLayout); + setVisible(false); - int rowHeight = 12; + int rowHeight = 12; - m_Values = new Object[flag.length]; - m_Views = new JCheckBoxFlag[flag.length]; - m_Labels = new JLabel[names.length]; + m_Values = new Object[flag.length]; + m_Views = new JCheckBoxFlag[flag.length]; + m_Labels = new JLabel[names.length]; - for (int i = 0; i < names.length; i++) { - m_Labels[i] = new JLabel(names[i], SwingConstants.RIGHT); + for (int i = 0; i < names.length; i++) { + m_Labels[i] = new JLabel(names[i], SwingConstants.RIGHT); m_Labels[i].setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 5)); - m_Views[i] = new JCheckBoxFlag(flag[i]); - GridBagConstraints gbConstraints = new GridBagConstraints(); - gbConstraints.anchor = GridBagConstraints.EAST; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; + m_Views[i] = new JCheckBoxFlag(flag[i]); + GridBagConstraints gbConstraints = new GridBagConstraints(); + gbConstraints.anchor = GridBagConstraints.EAST; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = i + componentOffset; gbConstraints.gridx = 0; - gbLayout.setConstraints(m_Labels[i], gbConstraints); - add(m_Labels[i]); - JPanel newPanel = new JPanel(); + gbLayout.setConstraints(m_Labels[i], gbConstraints); + add(m_Labels[i]); + JPanel newPanel = new JPanel(); newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); - newPanel.setLayout(new BorderLayout()); - newPanel.add(m_Views[i], BorderLayout.CENTER); - gbConstraints = new GridBagConstraints(); - gbConstraints.anchor = GridBagConstraints.WEST; - gbConstraints.fill = GridBagConstraints.BOTH; + newPanel.setLayout(new BorderLayout()); + newPanel.add(m_Views[i], BorderLayout.CENTER); + gbConstraints = new GridBagConstraints(); + gbConstraints.anchor = GridBagConstraints.WEST; + gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.gridy = i + componentOffset; gbConstraints.gridx = 1; - gbConstraints.weightx = 100; - gbLayout.setConstraints(newPanel, gbConstraints); - add(newPanel); + gbConstraints.weightx = 100; + gbLayout.setConstraints(newPanel, gbConstraints); + add(newPanel); + } + validate(); + setVisible(true); } - validate(); - setVisible(true); - } - /** - * - */ - public boolean[] getState() { - boolean[] ret = new boolean[this.m_Views.length]; + /** + * + */ + public boolean[] getState() { + boolean[] ret = new boolean[this.m_Views.length]; for (int i = 0; i < ret.length; i++) { - ret[i] = m_Views[i].isSelected(); + ret[i] = m_Views[i].isSelected(); + } + return ret; } - return ret; - } } /** @@ -107,23 +110,23 @@ public class PropertySheetPanelStat extends JPanel implements Serializable { */ class JCheckBoxFlag extends JCheckBox { - private boolean m_Flag = true; + private boolean m_Flag = true; public JCheckBoxFlag(boolean flag) { - super(); - m_Flag = flag; + super(); + m_Flag = flag; addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent evt) { - if (evt.getStateChange() == evt.SELECTED) { - m_Flag = true; - } - if (evt.getStateChange() == evt.DESELECTED) { - m_Flag = false; - } - } - }); + if (evt.getStateChange() == evt.SELECTED) { + m_Flag = true; + } + if (evt.getStateChange() == evt.DESELECTED) { + m_Flag = false; + } + } + }); - } + } } diff --git a/src/eva2/gui/PropertySlider.java b/src/eva2/gui/PropertySlider.java index 5e89f8f2..9fe2dfb0 100644 --- a/src/eva2/gui/PropertySlider.java +++ b/src/eva2/gui/PropertySlider.java @@ -4,6 +4,7 @@ package eva2.gui; * Architecture @author Holger Ulmer, Felix Streichert, Hannes Planatscher @version: $Revision: 10 $ * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ $Author: streiche $ */ + import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; diff --git a/src/eva2/gui/PropertyText.java b/src/eva2/gui/PropertyText.java index 0fdf53db..83b9c7ed 100644 --- a/src/eva2/gui/PropertyText.java +++ b/src/eva2/gui/PropertyText.java @@ -11,7 +11,6 @@ import javax.swing.JTextField; /** * A text property editor view. Updates the editor on key release and lost focus * events. - * */ public class PropertyText extends JTextField { diff --git a/src/eva2/gui/PropertyWeightedLPTchebycheff.java b/src/eva2/gui/PropertyWeightedLPTchebycheff.java index 6abfcf7e..4214714e 100644 --- a/src/eva2/gui/PropertyWeightedLPTchebycheff.java +++ b/src/eva2/gui/PropertyWeightedLPTchebycheff.java @@ -9,9 +9,9 @@ package eva2.gui; */ public class PropertyWeightedLPTchebycheff implements java.io.Serializable { - public double[] m_IdealValue; - public double[] m_Weights; - public int m_P = 0; + public double[] m_IdealValue; + public double[] m_Weights; + public int m_P = 0; public PropertyWeightedLPTchebycheff() { } @@ -25,7 +25,7 @@ public class PropertyWeightedLPTchebycheff implements java.io.Serializable { this.m_Weights = new double[e.m_Weights.length]; System.arraycopy(e.m_Weights, 0, this.m_Weights, 0, this.m_Weights.length); } - this.m_P = e.m_P; + this.m_P = e.m_P; } @Override diff --git a/src/eva2/gui/SplashScreen.java b/src/eva2/gui/SplashScreen.java index 8fa6f111..bdba9d12 100644 --- a/src/eva2/gui/SplashScreen.java +++ b/src/eva2/gui/SplashScreen.java @@ -11,6 +11,7 @@ package eva2.gui; * @version: $Revision: 322 $ $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007)$ * $Author: mkron $ */ + import eva2.tools.BasicResourceLoader; import java.awt.*; @@ -28,7 +29,7 @@ class SplashScreen extends Frame { /** * Show the splash screen to the end user. - * + *

*

Once this method returns, the splash screen is realized, which means * that almost all work on the splash screen should proceed through the * event dispatch thread. In particular, any call to @@ -41,11 +42,11 @@ class SplashScreen extends Frame { byte[] bytes = loader.getBytesFromResourceLocation(imgLocation, true); ImageIcon ii = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes)); JLabel splashLabel = new JLabel(ii); - + splashWindow.add(splashLabel); splashWindow.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); splashWindow.setLocation(screenSize.width / 2 - splashWindow.getSize().width / 2, screenSize.height / 2 - splashWindow.getSize().height / 2); - splashWindow.setVisible(true); + splashWindow.setVisible(true); } } \ No newline at end of file diff --git a/src/eva2/gui/editor/AbstractListSelectionEditor.java b/src/eva2/gui/editor/AbstractListSelectionEditor.java index a0c7ea3e..ce1c017b 100644 --- a/src/eva2/gui/editor/AbstractListSelectionEditor.java +++ b/src/eva2/gui/editor/AbstractListSelectionEditor.java @@ -28,20 +28,27 @@ import javax.swing.SwingConstants; */ public abstract class AbstractListSelectionEditor extends JPanel implements PropertyEditor, PropertyChangeListener { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - protected JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - - /** The graphics stuff */ - private JPanel m_CustomEditor, m_NodePanel; - protected JCheckBox[] m_BlackCheck; + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + protected JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - - public AbstractListSelectionEditor() { - } + /** + * The graphics stuff + */ + private JPanel m_CustomEditor, m_NodePanel; + protected JCheckBox[] m_BlackCheck; - /** This method will init the CustomEditor Panel + + public AbstractListSelectionEditor() { + } + + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { this.m_CustomEditor = new JPanel(); @@ -54,37 +61,38 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop /** * Return the number of elements in the list. + * * @return */ protected abstract int getElementCount(); - + /** * Get the display name of an element. - * + * * @param i * @return */ protected abstract String getElementName(int i); - + /** * Get the tool tip of an element or null if none is available. - * + * * @param i * @return */ protected String getElementToolTip(int i) { - return null; + return null; } - + /** * Get the selection state of an element. - * + * * @param i * @return */ protected abstract boolean isElementSelected(int i); - - /** + + /** * The object may have changed update the editor. This notifies change listeners automatically. */ private void updateEditor() { @@ -93,9 +101,9 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop this.m_NodePanel.setLayout(new GridLayout(getElementCount(), 1)); this.m_BlackCheck = new JCheckBox[getElementCount()]; for (int i = 0; i < getElementCount(); i++) { - this.m_BlackCheck[i] = new JCheckBox(getElementName(i), isElementSelected(i)); - this.m_BlackCheck[i].setToolTipText(getElementToolTip(i)); - this.m_BlackCheck[i].addActionListener(new ActionListener() { + this.m_BlackCheck[i] = new JCheckBox(getElementName(i), isElementSelected(i)); + this.m_BlackCheck[i].setToolTipText(getElementToolTip(i)); + this.m_BlackCheck[i].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { if (actionOnSelect()) { @@ -108,32 +116,35 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop } } - /** + /** * Perform actions when the selection state changes. Return true if there was an actual change. */ protected abstract boolean actionOnSelect(); /** - * Set the base object, return true on success. Make sure that the editor instance is - * added as a listener to the object (if supported). - * + * Set the base object, return true on success. Make sure that the editor instance is + * added as a listener to the object (if supported). + * * @param o * @return */ protected abstract boolean setObject(Object o); - - /** This method will set the value of object that is to be edited. + + /** + * This method will set the value of object that is to be edited. + * * @param o an object that must be an array. */ @Override public void setValue(Object o) { - if (setObject(o)) { + if (setObject(o)) { updateEditor(); } } - /** + /** * Returns the current object. + * * @return the current object */ @Override @@ -148,7 +159,7 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop public String getAsText() { return null; } - + @Override public void setAsText(String text) throws IllegalArgumentException { throw new IllegalArgumentException(text); @@ -172,16 +183,19 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); + m_Support.removePropertyChangeListener(l); } - - /** Returns true since the Object can be shown + + /** + * Returns true since the Object can be shown + * * @return true */ @Override public boolean isPaintable() { return true; } + /** * Paints a representation of the current classifier. * @@ -193,11 +207,12 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; String rep = "Select from list"; - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); } - - /** + + /** * Returns true because we do support a custom editor. + * * @return true */ @Override @@ -205,9 +220,11 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop return true; } - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override public Component getCustomEditor() { if (this.m_CustomEditor == null) { @@ -215,9 +232,9 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop } return m_CustomEditor; } - + @Override public void propertyChange(PropertyChangeEvent evt) { - m_Support.firePropertyChange("AbstractListSelectionEditor", null, this); + m_Support.firePropertyChange("AbstractListSelectionEditor", null, this); } } \ No newline at end of file diff --git a/src/eva2/gui/editor/BigStringEditor.java b/src/eva2/gui/editor/BigStringEditor.java index dd8c4381..16cbb776 100644 --- a/src/eva2/gui/editor/BigStringEditor.java +++ b/src/eva2/gui/editor/BigStringEditor.java @@ -12,9 +12,10 @@ package eva2.gui.editor; /*==========================================================================* * IMPORTS *==========================================================================*/ + import eva2.gui.PropertyDialog; -import java.awt.*; +import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; @@ -23,212 +24,219 @@ import javax.swing.*; * CLASS DECLARATION *==========================================================================*/ public class BigStringEditor implements PropertyEditor { - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - private PropertyEditor m_ElementEditor; - private JTextArea m_TextArea; - private JScrollPane m_ScrollPane; - private JPanel m_Panel; -// private Source m_Source; - private JButton m_SetButton; - static private boolean m_finished = false; - /** - * - */ - public static void editSource (String file) { + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + private PropertyEditor m_ElementEditor; + private JTextArea m_TextArea; + private JScrollPane m_ScrollPane; + private JPanel m_Panel; + // private Source m_Source; + private JButton m_SetButton; + static private boolean m_finished = false; - try { - m_finished=false; - BigStringEditor editor = new BigStringEditor(); + /** + * + */ + public static void editSource(String file) { - PropertyDialog dialog = new PropertyDialog(editor,file, 50, 50); - //frame.setSize(200, 200); - dialog.addWindowListener(new WindowListener() { + try { + m_finished = false; + BigStringEditor editor = new BigStringEditor(); + + PropertyDialog dialog = new PropertyDialog(editor, file, 50, 50); + //frame.setSize(200, 200); + dialog.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { - + } @Override public void windowClosing(WindowEvent e) { - + } @Override - public void windowClosed(WindowEvent e) { + public void windowClosed(WindowEvent e) { m_finished = true; } @Override public void windowIconified(WindowEvent e) { - + } @Override public void windowDeiconified(WindowEvent e) { - + } @Override public void windowActivated(WindowEvent e) { - + } @Override public void windowDeactivated(WindowEvent e) { - + } } - ); - while (m_finished==false) { - try {Thread.sleep(1000);} - catch (Exception e) { - System.out.println("e+"+e.getMessage()); + ); + while (m_finished == false) { + try { + Thread.sleep(1000); + } catch (Exception e) { + System.out.println("e+" + e.getMessage()); + } + } + + + } catch (Exception e) { + e.printStackTrace(); + System.out.println(e.getMessage()); } - } - - - } catch (Exception e) { - e.printStackTrace(); - System.out.println(e.getMessage()); } - } - /** - * - */ - public BigStringEditor () { - super(); + + /** + * + */ + public BigStringEditor() { + super(); // m_TextArea = new JEditTextArea(); // m_TextArea.setTokenMarker(new JavaTokenMarker()); - m_TextArea = new JTextArea(60,60); - m_TextArea.setEditable(true); - m_TextArea.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); - m_ScrollPane = new JScrollPane(m_TextArea); - m_Panel = new JPanel(); - m_Panel.setBorder(BorderFactory.createTitledBorder("Sourcecode")); - m_Panel.setLayout(new BorderLayout()); - m_SetButton = new JButton("SET"); - m_SetButton.addActionListener(new ActionListener() { + m_TextArea = new JTextArea(60, 60); + m_TextArea.setEditable(true); + m_TextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + m_ScrollPane = new JScrollPane(m_TextArea); + m_Panel = new JPanel(); + m_Panel.setBorder(BorderFactory.createTitledBorder("Sourcecode")); + m_Panel.setLayout(new BorderLayout()); + m_SetButton = new JButton("SET"); + m_SetButton.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { - setValue(m_TextArea.getText()); - } - }); - m_Panel.add(m_ScrollPane, BorderLayout.CENTER); - m_Panel.add(m_SetButton, BorderLayout.SOUTH); - } - /** - * - */ - @Override - public void setValue (Object value) { - m_ElementEditor = null; - if (value instanceof String) { -// m_Source.setString((String)value); - m_TextArea.setText((String)value); - + public void actionPerformed(ActionEvent e) { + setValue(m_TextArea.getText()); + } + }); + m_Panel.add(m_ScrollPane, BorderLayout.CENTER); + m_Panel.add(m_SetButton, BorderLayout.SOUTH); } + + /** + * + */ + @Override + public void setValue(Object value) { + m_ElementEditor = null; + if (value instanceof String) { +// m_Source.setString((String)value); + m_TextArea.setText((String) value); + + } /* if (value instanceof Source) { // m_Source = (Source) value; m_TextArea.setText(((Source)value).getString()); }*/ - m_Support.firePropertyChange("", null, null); - } - /** - * - */ - @Override - public Object getValue () { - // m_Source.setString(m_TextArea.getText()); - return null; - } - /** - * - */ - @Override - public String getJavaInitializationString () { - return "null"; - } + m_Support.firePropertyChange("", null, null); + } - /** - * Returns true to indicate that we can paint a representation of the - * string array - * - * @return true - */ + /** + * + */ @Override - public boolean isPaintable () { - return true; - } + public Object getValue() { + // m_Source.setString(m_TextArea.getText()); + return null; + } - /** - * Paints a representation of the current classifier. - * - * @param gfx the graphics context to use - * @param box the area we are allowed to paint into - */ + /** + * + */ @Override - public void paintValue (Graphics gfx, Rectangle box) { - FontMetrics fm = gfx.getFontMetrics(); - int vpad = (box.height - fm.getAscent())/2; - //String rep = EVAHELP.cutClassName(m_ElementClass.getName()); - gfx.drawString("BigStringEditor", 2, fm.getHeight() + vpad - 3); - } + public String getJavaInitializationString() { + return "null"; + } - /** - * - */ + /** + * Returns true to indicate that we can paint a representation of the + * string array + * + * @return true + */ @Override - public String getAsText () { - return null; - } + public boolean isPaintable() { + return true; + } - /** - * - */ + /** + * Paints a representation of the current classifier. + * + * @param gfx the graphics context to use + * @param box the area we are allowed to paint into + */ @Override - public void setAsText (String text) throws IllegalArgumentException { - throw new IllegalArgumentException(text); - } + public void paintValue(Graphics gfx, Rectangle box) { + FontMetrics fm = gfx.getFontMetrics(); + int vpad = (box.height - fm.getAscent()) / 2; + //String rep = EVAHELP.cutClassName(m_ElementClass.getName()); + gfx.drawString("BigStringEditor", 2, fm.getHeight() + vpad - 3); + } - /** - * - */ + /** + * + */ @Override - public String[] getTags () { - return null; - } + public String getAsText() { + return null; + } - /** - * - */ + /** + * + */ @Override - public boolean supportsCustomEditor () { - return true; - } - /** - * - */ + public void setAsText(String text) throws IllegalArgumentException { + throw new IllegalArgumentException(text); + } + + /** + * + */ @Override - public Component getCustomEditor () { - return m_Panel; - } + public String[] getTags() { + return null; + } + + /** + * + */ + @Override + public boolean supportsCustomEditor() { + return true; + } + + /** + * + */ + @Override + public Component getCustomEditor() { + return m_Panel; + } @Override - public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { - m_Support = new PropertyChangeSupport(this); - } - m_Support.addPropertyChangeListener(l); - } + public void addPropertyChangeListener(PropertyChangeListener l) { + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } + m_Support.addPropertyChangeListener(l); + } @Override - public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { - m_Support = new PropertyChangeSupport(this); - } - m_Support.removePropertyChangeListener(l); - } + public void removePropertyChangeListener(PropertyChangeListener l) { + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } + m_Support.removePropertyChangeListener(l); + } } diff --git a/src/eva2/gui/editor/ComponentFilter.java b/src/eva2/gui/editor/ComponentFilter.java index b90c8b19..d4781359 100644 --- a/src/eva2/gui/editor/ComponentFilter.java +++ b/src/eva2/gui/editor/ComponentFilter.java @@ -1,4 +1,5 @@ package eva2.gui.editor; + /* * Title: EvA2 * Description: @@ -10,5 +11,5 @@ package eva2.gui.editor; * $Author: streiche $ */ public interface ComponentFilter { - public boolean accept(java.awt.Component component); + public boolean accept(java.awt.Component component); } diff --git a/src/eva2/gui/editor/EnumEditor.java b/src/eva2/gui/editor/EnumEditor.java index 996a01a1..a808d17f 100644 --- a/src/eva2/gui/editor/EnumEditor.java +++ b/src/eva2/gui/editor/EnumEditor.java @@ -16,78 +16,80 @@ import javax.swing.JFrame; * To change this template use Options | File Templates. */ public class EnumEditor extends PropertyEditorSupport { - /** The Enum values that may be chosen */ - private Enum[] enumConstants; + /** + * The Enum values that may be chosen + */ + private Enum[] enumConstants; @Override - public String getAsText() { - return getValue().toString(); - } - + public String getAsText() { + return getValue().toString(); + } + @Override - public void setValue(Object value) { - if (value instanceof Enum) { - enumConstants = ((Enum)value).getClass().getEnumConstants(); + public void setValue(Object value) { + if (value instanceof Enum) { + enumConstants = ((Enum) value).getClass().getEnumConstants(); // enumType = ((Enum)value); - super.setValue(value); - } else if (value.getClass().isArray() && value.getClass().getComponentType().isEnum() ) { + super.setValue(value); + } else if (value.getClass().isArray() && value.getClass().getComponentType().isEnum()) { // values = value.getClass().getComponentType().getEnumConstants(); - Enum[] e = (Enum[])(value); - enumConstants =(Enum[]) e.getClass().getComponentType().getEnumConstants(); - super.setValue(value); - } - } - - @Override - public void setAsText(String text) throws IllegalArgumentException { - for (int i=0; i[] e = (Enum[]) (value); + enumConstants = (Enum[]) e.getClass().getComponentType().getEnumConstants(); + super.setValue(value); } - return tags; - } + } - /** - * Test the editor. - * - * @param args ignored - */ - public static void main(String [] args) { - try { - Enum initial = TestEnum.asdf; - EnumEditor ed = new EnumEditor(); - ed.setValue(initial); - PropertyValueSelector ps = new PropertyValueSelector(ed); - JFrame f = new JFrame(); - f.addWindowListener(new WindowAdapter() { + @Override + public void setAsText(String text) throws IllegalArgumentException { + for (int i = 0; i < enumConstants.length; i++) { + if (text.equals(enumConstants[i].toString())) { + setValue((Enum) enumConstants[i]); + return; + } + } + throw new IllegalArgumentException("Invalid text for enum"); + } + + @Override + public String[] getTags() { + if (getValue() == null) { + return null; + } + String[] tags = new String[enumConstants.length]; + for (int i = 0; i < tags.length; i++) { + tags[i] = enumConstants[i].toString(); + } + return tags; + } + + /** + * Test the editor. + * + * @param args ignored + */ + public static void main(String[] args) { + try { + Enum initial = TestEnum.asdf; + EnumEditor ed = new EnumEditor(); + ed.setValue(initial); + PropertyValueSelector ps = new PropertyValueSelector(ed); + JFrame f = new JFrame(); + f.addWindowListener(new WindowAdapter() { @Override - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - f.getContentPane().setLayout(new BorderLayout()); - f.getContentPane().add(ps, BorderLayout.CENTER); - f.pack(); - f.setVisible(true); - } catch (Exception ex) { - ex.printStackTrace(); - System.err.println(ex.getMessage()); - } - } + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + f.getContentPane().setLayout(new BorderLayout()); + f.getContentPane().add(ps, BorderLayout.CENTER); + f.pack(); + f.setVisible(true); + } catch (Exception ex) { + ex.printStackTrace(); + System.err.println(ex.getMessage()); + } + } } -enum TestEnum { asdf, sdf, asdfa}; \ No newline at end of file +enum TestEnum {asdf, sdf, asdfa}; \ No newline at end of file diff --git a/src/eva2/gui/editor/GenericAreaEditor.java b/src/eva2/gui/editor/GenericAreaEditor.java index f496e661..e481f4cc 100644 --- a/src/eva2/gui/editor/GenericAreaEditor.java +++ b/src/eva2/gui/editor/GenericAreaEditor.java @@ -11,53 +11,55 @@ import eva2.optimization.individuals.codings.gp.GPArea; * To change this template use Options | File Templates. */ public class GenericAreaEditor extends AbstractListSelectionEditor { - /** The GPArea that is to be edited*/ - private GPArea m_AreaObject; - + /** + * The GPArea that is to be edited + */ + private GPArea m_AreaObject; + public GenericAreaEditor() { // compiled code } - - @Override - protected int getElementCount() { - return m_AreaObject.getCompleteList().size(); - } - @Override - protected String getElementName(int i) { - AbstractGPNode an = (AbstractGPNode)m_AreaObject.getCompleteList().get(i); - return an.getName(); - } + @Override + protected int getElementCount() { + return m_AreaObject.getCompleteList().size(); + } - @Override - protected boolean isElementSelected(int i) { - return ((Boolean)m_AreaObject.getBlackList().get(i)).booleanValue(); - } + @Override + protected String getElementName(int i) { + AbstractGPNode an = (AbstractGPNode) m_AreaObject.getCompleteList().get(i); + return an.getName(); + } - @Override - protected boolean actionOnSelect() { - /** This method checks the current BlackList and compiles it - * to a new ReducedList. - */ - for (int i = 0; i < this.m_BlackCheck.length; i++) { - this.m_AreaObject.setBlackListElement(i, this.m_BlackCheck[i].isSelected()); - } - this.m_AreaObject.compileReducedList(); - return true; - } + @Override + protected boolean isElementSelected(int i) { + return ((Boolean) m_AreaObject.getBlackList().get(i)).booleanValue(); + } - @Override - protected boolean setObject(Object o) { + @Override + protected boolean actionOnSelect() { + /** This method checks the current BlackList and compiles it + * to a new ReducedList. + */ + for (int i = 0; i < this.m_BlackCheck.length; i++) { + this.m_AreaObject.setBlackListElement(i, this.m_BlackCheck[i].isSelected()); + } + this.m_AreaObject.compileReducedList(); + return true; + } + + @Override + protected boolean setObject(Object o) { if (o instanceof GPArea) { this.m_AreaObject = (GPArea) o; m_AreaObject.addPropertyChangeListener(this); return true; } else { - return false; - } - } - - @Override + return false; + } + } + + @Override public Object getValue() { return this.m_AreaObject; } diff --git a/src/eva2/gui/editor/GenericArrayEditor.java b/src/eva2/gui/editor/GenericArrayEditor.java index ae597135..f00a9f00 100644 --- a/src/eva2/gui/editor/GenericArrayEditor.java +++ b/src/eva2/gui/editor/GenericArrayEditor.java @@ -3,6 +3,7 @@ package eva2.gui.editor; import eva2.gui.*; import eva2.tools.EVAHELP; import eva2.tools.SerializedObject; + import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; @@ -165,7 +166,7 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor { } return os; } - + /** * Listens to list items being selected and takes appropriate action */ @@ -173,7 +174,7 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor { new ListSelectionListener() { // - @Override + @Override public void valueChanged(ListSelectionEvent e) { if (e.getSource() == elementList) { @@ -261,7 +262,7 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor { * Creates the list cell renderer. * * @param editorClass The class of the property editor for array objects - * @param valueClass The class of the array values + * @param valueClass The class of the array values */ public EditorListCellRenderer(Class editorClass, Class valueClass) { this.editorClass = editorClass; @@ -271,24 +272,24 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor { /** * Creates a cell rendering component. * - * @param JList the list that will be rendered in - * @param Object the cell value - * @param int which element of the list to render + * @param JList the list that will be rendered in + * @param Object the cell value + * @param int which element of the list to render * @param boolean true if the cell is selected * @param boolean true if the cell has the focus * @return the rendering component */ @Override public Component getListCellRendererComponent(final JList list, - final Object value, - final int index, - final boolean isSelected, - final boolean cellHasFocus) { + final Object value, + final int index, + final boolean isSelected, + final boolean cellHasFocus) { try { final PropertyEditor e = (PropertyEditor) editorClass.newInstance(); if (e instanceof GenericObjectEditor) { ((GenericObjectEditor) e).setClassType(valueClass); - } + } e.setValue(value); JPanel cellPanel = new JPanel() { @@ -644,7 +645,7 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor { * @return */ private JMenuItem createMenuItem(String title, boolean enabled, - ActionListener aListener) { + ActionListener aListener) { JMenuItem item = new JMenuItem(title); // if (bgColor!=null) item.setForeground(bgColor); item.addActionListener(aListener); diff --git a/src/eva2/gui/editor/GenericDoubleArrayEditor.java b/src/eva2/gui/editor/GenericDoubleArrayEditor.java index db75222e..5684d69b 100644 --- a/src/eva2/gui/editor/GenericDoubleArrayEditor.java +++ b/src/eva2/gui/editor/GenericDoubleArrayEditor.java @@ -26,32 +26,36 @@ import javax.swing.SwingConstants; /** * A simple focus listener with an object ID and callback. - * - * @author mkron * + * @author mkron */ class MyFocusListener implements FocusListener { - private int myID = -1; - private GenericDoubleArrayEditor arrEditor = null; - - public MyFocusListener(int id, GenericDoubleArrayEditor gdae) { - myID = id; - this.arrEditor = gdae; - } - - /* - * (non-Javadoc) - * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent) - */ + private int myID = -1; + private GenericDoubleArrayEditor arrEditor = null; + + public MyFocusListener(int id, GenericDoubleArrayEditor gdae) { + myID = id; + this.arrEditor = gdae; + } + + /* + * (non-Javadoc) + * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent) + */ @Override - public void focusLost(FocusEvent e) { } - - /* - * (non-Javadoc) - * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent) - */ + public void focusLost(FocusEvent e) { + } + + /* + * (non-Javadoc) + * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent) + */ @Override - public void focusGained(FocusEvent e) { arrEditor.notifyFocusID(myID);}; + public void focusGained(FocusEvent e) { + arrEditor.notifyFocusID(myID); + } + + ; }; @@ -60,29 +64,41 @@ class MyFocusListener implements FocusListener { */ public class GenericDoubleArrayEditor extends JPanel implements PropertyEditor { - private static final long serialVersionUID = 7749892624600018812L; - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The FilePath that is to be edited*/ + private static final long serialVersionUID = 7749892624600018812L; + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The FilePath that is to be edited + */ private PropertyDoubleArray m_DoubleArray; - /** The gaphix stuff */ - private JPanel m_CustomEditor, m_DataPanel, m_ButtonPanel; - private JTextField[][] m_InputTextFields; - private JButton m_OKButton, m_AddButton, m_DeleteButton, m_NormalizeButton; - - /** Which columns has the focus? **/ - private int lastFocussedRow = -1; + /** + * The gaphix stuff + */ + private JPanel m_CustomEditor, m_DataPanel, m_ButtonPanel; + private JTextField[][] m_InputTextFields; + private JButton m_OKButton, m_AddButton, m_DeleteButton, m_NormalizeButton; + + /** + * Which columns has the focus? * + */ + private int lastFocussedRow = -1; + public GenericDoubleArrayEditor() { // compiled code } - /** This method will init the CustomEditor Panel + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { - this.m_CustomEditor = new JPanel(); + this.m_CustomEditor = new JPanel(); this.m_CustomEditor.setLayout(new BorderLayout()); this.m_CustomEditor.add(new JLabel("Current Double Array:"), BorderLayout.NORTH); @@ -100,17 +116,17 @@ public class GenericDoubleArrayEditor extends JPanel implements PropertyEditor { this.m_DeleteButton.addActionListener(this.deleteAction); this.m_NormalizeButton = new JButton("Normalize"); this.m_NormalizeButton.addActionListener(this.normalizeAction); - this.m_OKButton = new JButton("OK"); + this.m_OKButton = new JButton("OK"); this.m_OKButton.setEnabled(true); this.m_OKButton.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { - //m_Backup = copyObject(m_Object); - if ((m_CustomEditor.getTopLevelAncestor() != null) && (m_CustomEditor.getTopLevelAncestor() instanceof Window)) { - Window w = (Window) m_CustomEditor.getTopLevelAncestor(); - w.dispose(); - } - } + public void actionPerformed(ActionEvent e) { + //m_Backup = copyObject(m_Object); + if ((m_CustomEditor.getTopLevelAncestor() != null) && (m_CustomEditor.getTopLevelAncestor() instanceof Window)) { + Window w = (Window) m_CustomEditor.getTopLevelAncestor(); + w.dispose(); + } + } }); this.m_ButtonPanel.add(this.m_AddButton); this.m_ButtonPanel.add(this.m_DeleteButton); @@ -120,74 +136,79 @@ public class GenericDoubleArrayEditor extends JPanel implements PropertyEditor { this.updateEditor(); } - /** This action listener adds an element to DoubleArray + /** + * This action listener adds an element to DoubleArray */ ActionListener addAction = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_DoubleArray.addRowCopy(lastFocussedRow); // copy the last focussed row + m_DoubleArray.addRowCopy(lastFocussedRow); // copy the last focussed row updateEditor(); } }; - - /** This action listener removes an element from the DoubleArray. + + /** + * This action listener removes an element from the DoubleArray. */ ActionListener deleteAction = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - if (!m_DoubleArray.isValidRow(lastFocussedRow)) { - m_DoubleArray.deleteRow(m_DoubleArray.getNumRows()-1); - } else { - m_DoubleArray.deleteRow(lastFocussedRow); - } + if (!m_DoubleArray.isValidRow(lastFocussedRow)) { + m_DoubleArray.deleteRow(m_DoubleArray.getNumRows() - 1); + } else { + m_DoubleArray.deleteRow(lastFocussedRow); + } updateEditor(); } }; - - /** + + /** * This action listener nomalizes each columng of the values of the DoubleArray. */ ActionListener normalizeAction = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_DoubleArray.normalizeColumns(); + m_DoubleArray.normalizeColumns(); updateEditor(); } }; - - /** This action listener reads all values + + /** + * This action listener reads all values */ KeyListener readDoubleArrayAction = new KeyListener() { @Override - public void keyPressed(KeyEvent event) { + public void keyPressed(KeyEvent event) { } + @Override public void keyTyped(KeyEvent event) { } @Override public void keyReleased(KeyEvent event) { - double[][] tmpDD = new double[m_InputTextFields.length][m_InputTextFields[0].length]; + double[][] tmpDD = new double[m_InputTextFields.length][m_InputTextFields[0].length]; for (int i = 0; i < tmpDD.length; i++) { - for (int j=0; j< tmpDD[0].length; j++) { - try { - double d = 0; - d = new Double(m_InputTextFields[i][j].getText()).doubleValue(); - tmpDD[i][j] = d; - } catch (Exception e) { - } - } + for (int j = 0; j < tmpDD[0].length; j++) { + try { + double d = 0; + d = new Double(m_InputTextFields[i][j].getText()).doubleValue(); + tmpDD[i][j] = d; + } catch (Exception e) { + } + } //tmpD[i] = new Double(m_InputTextField[i].getText()).doubleValue(); } m_DoubleArray.setDoubleArray(tmpDD); //updateEditor(); - } + } }; - /** The object may have changed update the editor. + /** + * The object may have changed update the editor. */ private void updateEditor() { if (this.m_CustomEditor != null) { @@ -215,34 +236,37 @@ public class GenericDoubleArrayEditor extends JPanel implements PropertyEditor { // } // } - /** This method updates the data panel + /** + * This method updates the data panel */ private void updateDataPanel() { - int numRows = m_DoubleArray.getNumRows(); - int numCols = m_DoubleArray.getNumCols(); + int numRows = m_DoubleArray.getNumRows(); + int numCols = m_DoubleArray.getNumCols(); this.m_DataPanel.removeAll(); - this.m_DataPanel.setLayout(new GridLayout(numRows, numCols+1)); + this.m_DataPanel.setLayout(new GridLayout(numRows, numCols + 1)); this.m_InputTextFields = new JTextField[numRows][numCols]; for (int i = 0; i < numRows; i++) { - JLabel label = new JLabel("Value X"+i+": "); + JLabel label = new JLabel("Value X" + i + ": "); this.m_DataPanel.add(label); - for (int j=0; j getClassesFromClassPath(String className, ArrayList> instances) { ArrayList classes = new ArrayList(); @@ -110,7 +111,7 @@ public class GenericObjectEditor implements PropertyEditor { } - if (!Modifier.isAbstract(m) && !clazz.isInterface()) { // dont take abstract classes or interfaces + if (!Modifier.isAbstract(m) && !clazz.isInterface()) { // dont take abstract classes or interfaces try { Class[] params = new Class[0]; clazz.getConstructor(params); @@ -134,9 +135,9 @@ public class GenericObjectEditor implements PropertyEditor { * this only sets the hidden property of the java bean which is checked in the wasModified * method of PropertySheetPanel. * - * @param cls class the property belongs to - * @param property string name of the property - * @param hide desired value to set, true for hidden, false for visible + * @param cls class the property belongs to + * @param property string name of the property + * @param hide desired value to set, true for hidden, false for visible * @return false, if an error occurs, else true */ public static boolean setExpertProperty(Class cls, String property, boolean expertValue) { @@ -164,9 +165,9 @@ public class GenericObjectEditor implements PropertyEditor { * this only sets the hidden property of the java bean which is checked in the wasModified * method of PropertySheetPanel. * - * @param cls class the property belongs to - * @param property string name of the property - * @param hide desired value to set, true for hidden, false for visible + * @param cls class the property belongs to + * @param property string name of the property + * @param hide desired value to set, true for hidden, false for visible * @return false, if an error occurs, else true */ public static boolean setHideProperty(Class cls, String property, boolean hide) { @@ -263,7 +264,7 @@ public class GenericObjectEditor implements PropertyEditor { * * @param type a value of type 'Class' */ - public void setClassType(Class type) { + public void setClassType(Class type) { classType = type; if (editorComponent != null) { editorComponent.updateClassType(); @@ -286,7 +287,7 @@ public class GenericObjectEditor implements PropertyEditor { Vector v = null; v = new Vector(getClassesFromProperties(classType.getName(), null)); - + try { if (v.size() > 0) { setObject((Object) Class.forName((String) v.get(0)).newInstance()); @@ -439,7 +440,7 @@ public class GenericObjectEditor implements PropertyEditor { * Returns null as we don't support getting/setting values as text. * * @param text the text value - * @exception IllegalArgumentException as we don't support getting/setting values as text. + * @throws IllegalArgumentException as we don't support getting/setting values as text. */ @Override public void setAsText(String text) throws IllegalArgumentException { diff --git a/src/eva2/gui/editor/GenericObjectListSelectionEditor.java b/src/eva2/gui/editor/GenericObjectListSelectionEditor.java index c6c85336..5a7648d9 100644 --- a/src/eva2/gui/editor/GenericObjectListSelectionEditor.java +++ b/src/eva2/gui/editor/GenericObjectListSelectionEditor.java @@ -4,52 +4,54 @@ import eva2.gui.PropertySelectableList; /** * An editor for a selectable List. - * */ public class GenericObjectListSelectionEditor extends AbstractListSelectionEditor { private PropertySelectableList objList; - - public GenericObjectListSelectionEditor() {} - - @Override - protected int getElementCount() { - return objList.size(); - } - @Override - protected String getElementName(int i) { - return objList.get(i).toString(); - } + public GenericObjectListSelectionEditor() { + } - @Override - protected boolean isElementSelected(int i) { - return objList.isSelected(i); - } + @Override + protected int getElementCount() { + return objList.size(); + } - @Override - protected boolean actionOnSelect() { - boolean changed=false; - for (int i = 0; i < this.m_BlackCheck.length; i++) { - if (objList.isSelected(i)!=this.m_BlackCheck[i].isSelected()) { - objList.setSelectionForElement(i, this.m_BlackCheck[i].isSelected()); - changed=true; - } - } - return changed; - } + @Override + protected String getElementName(int i) { + return objList.get(i).toString(); + } - @Override - protected boolean setObject(Object o) { + @Override + protected boolean isElementSelected(int i) { + return objList.isSelected(i); + } + + @Override + protected boolean actionOnSelect() { + boolean changed = false; + for (int i = 0; i < this.m_BlackCheck.length; i++) { + if (objList.isSelected(i) != this.m_BlackCheck[i].isSelected()) { + objList.setSelectionForElement(i, this.m_BlackCheck[i].isSelected()); + changed = true; + } + } + return changed; + } + + @Override + protected boolean setObject(Object o) { if (o instanceof PropertySelectableList) { this.objList = (PropertySelectableList) o; objList.addPropertyChangeListener(this); return true; } else { - return false; - } - } + return false; + } + } - /** Retruns the current object. + /** + * Retruns the current object. + * * @return the current object */ @Override diff --git a/src/eva2/gui/editor/GenericOptimizationObjectivesEditor.java b/src/eva2/gui/editor/GenericOptimizationObjectivesEditor.java index dc30a809..36d09741 100644 --- a/src/eva2/gui/editor/GenericOptimizationObjectivesEditor.java +++ b/src/eva2/gui/editor/GenericOptimizationObjectivesEditor.java @@ -8,6 +8,7 @@ import eva2.optimization.problems.InterfaceOptimizationTarget; import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGOEProperty; import eva2.tools.BasicResourceLoader; + import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; @@ -44,28 +45,37 @@ import javax.swing.SwingConstants; */ public class GenericOptimizationObjectivesEditor extends JPanel implements PropertyEditor, java.beans.PropertyChangeListener { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The FilePath that is to be edited*/ + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The FilePath that is to be edited + */ private PropertyOptimizationObjectives m_OptimizationObjectives; - /** The gaphix stuff */ - private JComponent m_Editor; - private JPanel m_TargetList; - private JComponent[] m_Targets; - private JButton[] m_Delete; - private JScrollPane m_ScrollTargets; - private GeneralGOEProperty[] m_Editors; - private PropertyChangeListener m_self; + /** + * The gaphix stuff + */ + private JComponent m_Editor; + private JPanel m_TargetList; + private JComponent[] m_Targets; + private JButton[] m_Delete; + private JScrollPane m_ScrollTargets; + private GeneralGOEProperty[] m_Editors; + private PropertyChangeListener m_self; public GenericOptimizationObjectivesEditor() { m_self = this; } - /** This method will init the CustomEditor Panel + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { m_self = this; @@ -74,14 +84,14 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope this.m_Editor.setMinimumSize(new Dimension(400, 200)); // init the editors - InterfaceOptimizationObjective[] list = this.m_OptimizationObjectives.getSelectedTargets(); + InterfaceOptimizationObjective[] list = this.m_OptimizationObjectives.getSelectedTargets(); this.m_Editors = new GeneralGOEProperty[list.length]; for (int i = 0; i < list.length; i++) { this.m_Editors[i] = new GeneralGOEProperty(); - this.m_Editors[i].m_Name = list[i].getName(); + this.m_Editors[i].m_Name = list[i].getName(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); } @@ -99,87 +109,87 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } } this.m_TargetList = new JPanel(); - this.updateTargetList(); + this.updateTargetList(); this.m_ScrollTargets = new JScrollPane(this.m_TargetList); this.m_Editor.setLayout(new BorderLayout()); this.m_Editor.add(this.m_ScrollTargets, BorderLayout.CENTER); // the add button - JButton addButton = new JButton("Add Opt. Target"); + JButton addButton = new JButton("Add Opt. Target"); addButton.addActionListener(addTarget); this.m_Editor.add(addButton, BorderLayout.SOUTH); // Some description would be nice - JTextArea jt = new JTextArea(); - jt.setFont(new Font("SansSerif", Font.PLAIN,12)); - jt.setEditable(false); - jt.setLineWrap(true); - jt.setWrapStyleWord(true); - jt.setText("Choose and parameterize optimization objectives."); + JTextArea jt = new JTextArea(); + jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); + jt.setEditable(false); + jt.setLineWrap(true); + jt.setWrapStyleWord(true); + jt.setText("Choose and parameterize optimization objectives."); jt.setBackground(getBackground()); - JPanel jp = new JPanel(); - jp.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Info"), - BorderFactory.createEmptyBorder(0, 5, 5, 5) - )); - jp.setLayout(new BorderLayout()); - jp.add(jt, BorderLayout.CENTER); - JPanel p2 = new JPanel(); + JPanel jp = new JPanel(); + jp.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createTitledBorder("Info"), + BorderFactory.createEmptyBorder(0, 5, 5, 5) + )); + jp.setLayout(new BorderLayout()); + jp.add(jt, BorderLayout.CENTER); + JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); JButton help = new JButton("Help"); help.setEnabled(false); p2.add(help, BorderLayout.NORTH); jp.add(p2, BorderLayout.EAST); - GridBagConstraints gbConstraints = new GridBagConstraints(); + GridBagConstraints gbConstraints = new GridBagConstraints(); this.m_Editor.add(jp, BorderLayout.NORTH); - this.updateEditor(); + this.updateEditor(); } - /** This method updates the server list - * + /** + * This method updates the server list */ private void updateTargetList() { - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes; - InterfaceOptimizationObjective[] list = this.m_OptimizationObjectives.getSelectedTargets(); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes; + InterfaceOptimizationObjective[] list = this.m_OptimizationObjectives.getSelectedTargets(); this.m_TargetList.removeAll(); this.m_TargetList.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - this.m_Targets = new JComponent[list.length]; - this.m_Delete = new JButton[list.length]; - String[] cups = new String[8]; + this.m_Targets = new JComponent[list.length]; + this.m_Delete = new JButton[list.length]; + String[] cups = new String[8]; for (int i = 0; i < cups.length; i++) { - cups[i] = ""+(i+1); + cups[i] = "" + (i + 1); } // The head title - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 10; this.m_TargetList.add(new JLabel("Target"), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 1; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 1; + gbc.weightx = 1; this.m_TargetList.add(new JLabel("Remove"), gbc); for (int i = 0; i < list.length; i++) { // the status indicator - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 10; // this.m_Targets[i] = new JButton(""+list[i].getName()); // this.m_Targets[i].setEnabled(false); this.m_Targets[i] = this.m_Editors[i].m_View; this.m_TargetList.add(this.m_Targets[i], gbc); // The delete button - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 1; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 1; + gbc.weightx = 1; bytes = loader.getBytesFromResourceLocation("images/Sub24.gif", true); this.m_Delete[i] = new JButton("", new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); this.m_Delete[i].addActionListener(deleteTarget); @@ -197,7 +207,8 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } } - /** This action listener,... + /** + * This action listener,... */ ActionListener updateTargets = new ActionListener() { @Override @@ -206,12 +217,13 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener addTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_OptimizationObjectives.addTarget((InterfaceOptimizationObjective)m_OptimizationObjectives.getAvailableTargets()[0].clone()); + m_OptimizationObjectives.addTarget((InterfaceOptimizationObjective) m_OptimizationObjectives.getAvailableTargets()[0].clone()); int l = m_OptimizationObjectives.getSelectedTargets().length; GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l]; for (int i = 0; i < m_Editors.length; i++) { @@ -219,11 +231,11 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } InterfaceOptimizationObjective[] list = m_OptimizationObjectives.getSelectedTargets(); l--; - newEdit[l] = new GeneralGOEProperty(); - newEdit[l].m_Name = list[l].getName(); + newEdit[l] = new GeneralGOEProperty(); + newEdit[l].m_Name = list[l].getName(); try { - newEdit[l].m_Value = list[l]; - newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); + newEdit[l].m_Value = list[l]; + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); if (newEdit[l].m_Editor == null) { newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); } @@ -244,18 +256,18 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener deleteTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int l = m_OptimizationObjectives.getSelectedTargets().length, j = 0; - GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l-1]; + GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l - 1]; for (int i = 0; i < m_Delete.length; i++) { if (event.getSource().equals(m_Delete[i])) { m_OptimizationObjectives.removeTarget(i); - } - else { + } else { newEdit[j] = m_Editors[i]; j++; } @@ -265,7 +277,8 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } }; - /** The object may have changed update the editor. + /** + * The object may have changed update the editor. */ private void updateEditor() { if (this.m_Editor != null) { @@ -279,18 +292,22 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope } - /** This method will set the value of object that is to be edited. + /** + * This method will set the value of object that is to be edited. + * * @param o an object that must be an array. */ @Override public void setValue(Object o) { if (o instanceof PropertyOptimizationObjectives) { - this.m_OptimizationObjectives= (PropertyOptimizationObjectives) o; + this.m_OptimizationObjectives = (PropertyOptimizationObjectives) o; this.updateEditor(); } } - /** Returns the current object. + /** + * Returns the current object. + * * @return the current object */ @Override @@ -327,21 +344,27 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope return null; } - /** This is used to hook an action listener to the ok button + /** + * This is used to hook an action listener to the ok button + * * @param a The action listener. */ public void addOkListener(ActionListener a) { //m_OKButton.addActionListener(a); } - /** This is used to remove an action listener from the ok button + /** + * This is used to remove an action listener from the ok button + * * @param a The action listener */ public void removeOkListener(ActionListener a) { //m_OKButton.removeActionListener(a); } - /** Returns true since the Object can be shown + /** + * Returns true since the Object can be shown + * * @return true */ @Override @@ -349,7 +372,8 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope return true; } - /** Paints a representation of the current classifier. + /** + * Paints a representation of the current classifier. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into @@ -359,20 +383,24 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; String rep = "Optimization Targets"; - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); } - /** Returns true because we do support a custom editor. - * @return true - */ + /** + * Returns true because we do support a custom editor. + * + * @return true + */ @Override public boolean supportsCustomEditor() { return true; } - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override public Component getCustomEditor() { if (this.m_Editor == null) { @@ -381,7 +409,8 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope return m_Editor; } - /** This method will udate the status of the object taking the values from all + /** + * This method will udate the status of the object taking the values from all * supsequent editors and setting them to my object. */ public void updateCenterComponent(PropertyChangeEvent evt) { @@ -389,39 +418,44 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope this.updateEditor(); } - /********************************* java.beans.PropertyChangeListener *************************/ + /** + * ****************************** java.beans.PropertyChangeListener ************************ + */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.addPropertyChangeListener(l); + m_Support.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); + m_Support.removePropertyChangeListener(l); } - /** This will wait for the GenericObjectEditor to finish + + /** + * This will wait for the GenericObjectEditor to finish * editing an object. + * * @param evt */ @Override - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(PropertyChangeEvent evt) { Object newVal = evt.getNewValue(); Object oldVal = evt.getOldValue(); InterfaceOptimizationObjective[] list = this.m_OptimizationObjectives.getSelectedTargets(); for (int i = 0; i < list.length; i++) { if (oldVal.equals(list[i])) { - list[i] = (InterfaceOptimizationObjective)newVal; - this.m_Editors[i].m_Name = list[i].getName(); + list[i] = (InterfaceOptimizationObjective) newVal; + this.m_Editors[i].m_Name = list[i].getName(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); } diff --git a/src/eva2/gui/editor/GenericOptimizationObjectivesWithParamEditor.java b/src/eva2/gui/editor/GenericOptimizationObjectivesWithParamEditor.java index caa48357..2a05c6e6 100644 --- a/src/eva2/gui/editor/GenericOptimizationObjectivesWithParamEditor.java +++ b/src/eva2/gui/editor/GenericOptimizationObjectivesWithParamEditor.java @@ -7,6 +7,7 @@ import eva2.optimization.problems.InterfaceOptimizationObjective; import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGOEProperty; import eva2.tools.BasicResourceLoader; + import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; @@ -47,28 +48,37 @@ import javax.swing.SwingConstants; */ public class GenericOptimizationObjectivesWithParamEditor extends JPanel implements PropertyEditor, java.beans.PropertyChangeListener { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The FilePath that is to be edited*/ + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The FilePath that is to be edited + */ private PropertyOptimizationObjectivesWithParam m_OptimizationObjectivesWithWeights; - /** The gaphix stuff */ - private JComponent m_Editor; - private JPanel m_TargetList; - private JTextField[] m_Weights; - private JComponent[] m_Targets; - private JButton[] m_Delete; - private JScrollPane m_ScrollTargets; - private GeneralGOEProperty[] m_Editors; - private PropertyChangeListener m_self; + /** + * The gaphix stuff + */ + private JComponent m_Editor; + private JPanel m_TargetList; + private JTextField[] m_Weights; + private JComponent[] m_Targets; + private JButton[] m_Delete; + private JScrollPane m_ScrollTargets; + private GeneralGOEProperty[] m_Editors; + private PropertyChangeListener m_self; public GenericOptimizationObjectivesWithParamEditor() { m_self = this; } - /** This method will init the CustomEditor Panel + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { m_self = this; @@ -77,14 +87,14 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme this.m_Editor.setMinimumSize(new Dimension(450, 200)); // init the editors - InterfaceOptimizationObjective[] list = this.m_OptimizationObjectivesWithWeights.getSelectedTargets(); + InterfaceOptimizationObjective[] list = this.m_OptimizationObjectivesWithWeights.getSelectedTargets(); this.m_Editors = new GeneralGOEProperty[list.length]; for (int i = 0; i < list.length; i++) { this.m_Editors[i] = new GeneralGOEProperty(); - this.m_Editors[i].m_Name = list[i].getName(); + this.m_Editors[i].m_Name = list[i].getName(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); } @@ -102,17 +112,17 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } } this.m_TargetList = new JPanel(); - this.updateTargetList(); + this.updateTargetList(); this.m_ScrollTargets = new JScrollPane(this.m_TargetList); this.m_Editor.setLayout(new BorderLayout()); this.m_Editor.add(this.m_ScrollTargets, BorderLayout.CENTER); // The Button Panel - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new GridLayout(1,2)); - JButton addButton = new JButton("Add Opt. Target"); - JButton normButton = new JButton("Normalize Weights"); + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new GridLayout(1, 2)); + JButton addButton = new JButton("Add Opt. Target"); + JButton normButton = new JButton("Normalize Weights"); normButton.setEnabled(this.m_OptimizationObjectivesWithWeights.isNormalizationEnabled()); normButton.addActionListener(normalizeWeights); addButton.addActionListener(addTarget); @@ -122,89 +132,89 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme this.m_Editor.add(buttonPanel, BorderLayout.SOUTH); // Some description would be nice - JTextArea jt = new JTextArea(); - jt.setFont(new Font("SansSerif", Font.PLAIN,12)); - jt.setEditable(false); - jt.setLineWrap(true); - jt.setWrapStyleWord(true); - jt.setText(this.m_OptimizationObjectivesWithWeights.getDescriptiveString()); + JTextArea jt = new JTextArea(); + jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); + jt.setEditable(false); + jt.setLineWrap(true); + jt.setWrapStyleWord(true); + jt.setText(this.m_OptimizationObjectivesWithWeights.getDescriptiveString()); jt.setBackground(getBackground()); - JPanel jp = new JPanel(); - jp.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Info"), - BorderFactory.createEmptyBorder(0, 5, 5, 5) - )); - jp.setLayout(new BorderLayout()); - jp.add(jt, BorderLayout.CENTER); - JPanel p2 = new JPanel(); + JPanel jp = new JPanel(); + jp.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createTitledBorder("Info"), + BorderFactory.createEmptyBorder(0, 5, 5, 5) + )); + jp.setLayout(new BorderLayout()); + jp.add(jt, BorderLayout.CENTER); + JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); JButton help = new JButton("Help"); help.setEnabled(false); p2.add(help, BorderLayout.NORTH); jp.add(p2, BorderLayout.EAST); - GridBagConstraints gbConstraints = new GridBagConstraints(); + GridBagConstraints gbConstraints = new GridBagConstraints(); this.m_Editor.add(jp, BorderLayout.NORTH); this.updateEditor(); } - /** This method updates the server list - * + /** + * This method updates the server list */ private void updateTargetList() { - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes; - InterfaceOptimizationObjective[] list = this.m_OptimizationObjectivesWithWeights.getSelectedTargets(); - double[] weights = this.m_OptimizationObjectivesWithWeights.getWeights(); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes; + InterfaceOptimizationObjective[] list = this.m_OptimizationObjectivesWithWeights.getSelectedTargets(); + double[] weights = this.m_OptimizationObjectivesWithWeights.getWeights(); this.m_TargetList.removeAll(); this.m_TargetList.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - this.m_Weights = new JTextField[list.length]; - this.m_Targets = new JComponent[list.length]; - this.m_Delete = new JButton[list.length]; - String[] cups = new String[8]; + this.m_Weights = new JTextField[list.length]; + this.m_Targets = new JComponent[list.length]; + this.m_Delete = new JButton[list.length]; + String[] cups = new String[8]; for (int i = 0; i < cups.length; i++) { - cups[i] = ""+(i+1); + cups[i] = "" + (i + 1); } // The head title - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 2; this.m_TargetList.add(new JLabel(this.m_OptimizationObjectivesWithWeights.getWeigthsLabel()), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.weightx = 10; this.m_TargetList.add(new JLabel("Target"), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 2; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 2; + gbc.weightx = 1; this.m_TargetList.add(new JLabel("Remove"), gbc); for (int i = 0; i < list.length; i++) { // the weight - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 2; - this.m_Weights[i] = new JTextField(""+weights[i]); + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 2; + this.m_Weights[i] = new JTextField("" + weights[i]); this.m_Weights[i].addKeyListener(this.readDoubleArrayAction); this.m_TargetList.add(this.m_Weights[i], gbc); // the status indicator - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.weightx = 10; this.m_Targets[i] = this.m_Editors[i].m_View; this.m_TargetList.add(this.m_Targets[i], gbc); // The delete button - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 2; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 2; + gbc.weightx = 1; bytes = loader.getBytesFromResourceLocation("images/Sub24.gif", true); this.m_Delete[i] = new JButton("", new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); this.m_Delete[i].addActionListener(deleteTarget); @@ -222,7 +232,8 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } } - /** This action listener,... + /** + * This action listener,... */ ActionListener updateTargets = new ActionListener() { @Override @@ -231,12 +242,13 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener addTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_OptimizationObjectivesWithWeights.addTarget((InterfaceOptimizationObjective)m_OptimizationObjectivesWithWeights.getAvailableTargets()[0].clone()); + m_OptimizationObjectivesWithWeights.addTarget((InterfaceOptimizationObjective) m_OptimizationObjectivesWithWeights.getAvailableTargets()[0].clone()); int l = m_OptimizationObjectivesWithWeights.getSelectedTargets().length; GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l]; for (int i = 0; i < m_Editors.length; i++) { @@ -244,11 +256,11 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } InterfaceOptimizationObjective[] list = m_OptimizationObjectivesWithWeights.getSelectedTargets(); l--; - newEdit[l] = new GeneralGOEProperty(); - newEdit[l].m_Name = list[l].getName(); + newEdit[l] = new GeneralGOEProperty(); + newEdit[l].m_Name = list[l].getName(); try { - newEdit[l].m_Value = list[l]; - newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); + newEdit[l].m_Value = list[l]; + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); if (newEdit[l].m_Editor == null) { newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); } @@ -269,18 +281,18 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener deleteTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int l = m_OptimizationObjectivesWithWeights.getSelectedTargets().length, j = 0; - GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l-1]; + GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l - 1]; for (int i = 0; i < m_Delete.length; i++) { if (event.getSource().equals(m_Delete[i])) { m_OptimizationObjectivesWithWeights.removeTarget(i); - } - else { + } else { newEdit[j] = m_Editors[i]; j++; } @@ -290,7 +302,8 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener normalizeWeights = new ActionListener() { @Override @@ -310,19 +323,21 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } }; - /** This action listener reads all values + /** + * This action listener reads all values */ KeyListener readDoubleArrayAction = new KeyListener() { @Override public void keyPressed(KeyEvent event) { } + @Override public void keyTyped(KeyEvent event) { } @Override public void keyReleased(KeyEvent event) { - double[] newW = m_OptimizationObjectivesWithWeights.getWeights(); + double[] newW = m_OptimizationObjectivesWithWeights.getWeights(); for (int i = 0; i < newW.length; i++) { try { @@ -334,10 +349,11 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } m_OptimizationObjectivesWithWeights.setWeights(newW); - } + } }; - /** The object may have changed update the editor. + /** + * The object may have changed update the editor. */ private void updateEditor() { if (this.m_Editor != null) { @@ -350,18 +366,22 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme } } - /** This method will set the value of object that is to be edited. + /** + * This method will set the value of object that is to be edited. + * * @param o an object that must be an array. */ @Override public void setValue(Object o) { if (o instanceof PropertyOptimizationObjectivesWithParam) { - this.m_OptimizationObjectivesWithWeights= (PropertyOptimizationObjectivesWithParam) o; + this.m_OptimizationObjectivesWithWeights = (PropertyOptimizationObjectivesWithParam) o; this.updateEditor(); } } - /** Returns the current object. + /** + * Returns the current object. + * * @return the current object */ @Override @@ -398,21 +418,27 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme return null; } - /** This is used to hook an action listener to the ok button + /** + * This is used to hook an action listener to the ok button + * * @param a The action listener. */ public void addOkListener(ActionListener a) { //m_OKButton.addActionListener(a); } - /** This is used to remove an action listener from the ok button + /** + * This is used to remove an action listener from the ok button + * * @param a The action listener */ public void removeOkListener(ActionListener a) { //m_OKButton.removeActionListener(a); } - /** Returns true since the Object can be shown + /** + * Returns true since the Object can be shown + * * @return true */ @Override @@ -420,7 +446,8 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme return true; } - /** Paints a representation of the current classifier. + /** + * Paints a representation of the current classifier. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into @@ -430,20 +457,24 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; String rep = "Optimization Targets With Weights"; - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); } - /** Returns true because we do support a custom editor. - * @return true - */ + /** + * Returns true because we do support a custom editor. + * + * @return true + */ @Override public boolean supportsCustomEditor() { return true; } - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override public Component getCustomEditor() { if (this.m_Editor == null) { @@ -452,7 +483,8 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme return m_Editor; } - /** This method will udate the status of the object taking the values from all + /** + * This method will udate the status of the object taking the values from all * supsequent editors and setting them to my object. */ public void updateCenterComponent(PropertyChangeEvent evt) { @@ -460,39 +492,44 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme this.updateEditor(); } - /********************************* java.beans.PropertyChangeListener *************************/ + /** + * ****************************** java.beans.PropertyChangeListener ************************ + */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.addPropertyChangeListener(l); + m_Support.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); + m_Support.removePropertyChangeListener(l); } - /** This will wait for the GenericObjectEditor to finish + + /** + * This will wait for the GenericObjectEditor to finish * editing an object. + * * @param evt */ @Override - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(PropertyChangeEvent evt) { Object newVal = evt.getNewValue(); Object oldVal = evt.getOldValue(); InterfaceOptimizationObjective[] list = this.m_OptimizationObjectivesWithWeights.getSelectedTargets(); for (int i = 0; i < list.length; i++) { if (oldVal.equals(list[i])) { - list[i] = (InterfaceOptimizationObjective)newVal; - this.m_Editors[i].m_Name = list[i].getName(); + list[i] = (InterfaceOptimizationObjective) newVal; + this.m_Editors[i].m_Name = list[i].getName(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); } diff --git a/src/eva2/gui/editor/GenericWeigthedLPTchebycheffEditor.java b/src/eva2/gui/editor/GenericWeigthedLPTchebycheffEditor.java index f1ea99bc..5d4bf39a 100644 --- a/src/eva2/gui/editor/GenericWeigthedLPTchebycheffEditor.java +++ b/src/eva2/gui/editor/GenericWeigthedLPTchebycheffEditor.java @@ -18,34 +18,43 @@ import javax.swing.*; */ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements PropertyEditor { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The FilePath that is to be edited*/ + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The FilePath that is to be edited + */ private PropertyWeightedLPTchebycheff m_WLPT; - /** The gaphix stuff */ - private JPanel m_CustomEditor, m_DataPanel, m_ButtonPanel, m_TargetPanel; - private JTextField[] m_IdealTextField, m_WeightTextField; - private JTextField m_PValue; - private JButton m_OKButton; + /** + * The gaphix stuff + */ + private JPanel m_CustomEditor, m_DataPanel, m_ButtonPanel, m_TargetPanel; + private JTextField[] m_IdealTextField, m_WeightTextField; + private JTextField m_PValue; + private JButton m_OKButton; public GenericWeigthedLPTchebycheffEditor() { // compiled code } - /** This method will init the CustomEditor Panel + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { - this.m_CustomEditor = new JPanel(); + this.m_CustomEditor = new JPanel(); this.m_CustomEditor.setLayout(new BorderLayout()); // target panel this.m_TargetPanel = new JPanel(); this.m_TargetPanel.setLayout(new GridLayout(1, 2)); this.m_TargetPanel.add(new JLabel("Choose P:")); - this.m_PValue = new JTextField(""+this.m_WLPT.m_P); + this.m_PValue = new JTextField("" + this.m_WLPT.m_P); this.m_TargetPanel.add(this.m_PValue); this.m_PValue.addKeyListener(this.readDoubleAction); this.m_CustomEditor.add(this.m_TargetPanel, BorderLayout.NORTH); @@ -57,58 +66,62 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper // init button panel this.m_ButtonPanel = new JPanel(); - this.m_OKButton = new JButton("OK"); + this.m_OKButton = new JButton("OK"); this.m_OKButton.setEnabled(true); this.m_OKButton.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { - //m_Backup = copyObject(m_Object); - if ((m_CustomEditor.getTopLevelAncestor() != null) && (m_CustomEditor.getTopLevelAncestor() instanceof Window)) { - Window w = (Window) m_CustomEditor.getTopLevelAncestor(); - w.dispose(); - } - } + public void actionPerformed(ActionEvent e) { + //m_Backup = copyObject(m_Object); + if ((m_CustomEditor.getTopLevelAncestor() != null) && (m_CustomEditor.getTopLevelAncestor() instanceof Window)) { + Window w = (Window) m_CustomEditor.getTopLevelAncestor(); + w.dispose(); + } + } }); this.m_ButtonPanel.add(this.m_OKButton); this.m_CustomEditor.add(this.m_ButtonPanel, BorderLayout.SOUTH); this.updateEditor(); } - /** This action listener reads all values + /** + * This action listener reads all values */ KeyListener readDoubleAction = new KeyListener() { @Override public void keyPressed(KeyEvent event) { } + @Override public void keyTyped(KeyEvent event) { } @Override public void keyReleased(KeyEvent event) { - try { + try { int d = new Integer(m_PValue.getText()).intValue(); m_WLPT.m_P = d; - } catch (Exception e) { + } catch (Exception e) { - } - } + } + } }; - /** This action listener reads all values + /** + * This action listener reads all values */ KeyListener readDoubleArrayAction = new KeyListener() { @Override public void keyPressed(KeyEvent event) { } + @Override public void keyTyped(KeyEvent event) { } @Override public void keyReleased(KeyEvent event) { - double[] tmpT = m_WLPT.m_IdealValue; - double[] tmpP = m_WLPT.m_Weights; + double[] tmpT = m_WLPT.m_IdealValue; + double[] tmpP = m_WLPT.m_Weights; for (int i = 0; i < tmpT.length; i++) { @@ -128,12 +141,13 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper } } - m_WLPT.m_IdealValue = tmpT; - m_WLPT.m_Weights = tmpP; - } + m_WLPT.m_IdealValue = tmpT; + m_WLPT.m_Weights = tmpP; + } }; - /** The object may have changed update the editor. + /** + * The object may have changed update the editor. */ private void updateEditor() { if (this.m_CustomEditor != null) { @@ -143,37 +157,40 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper } } - /** This method updates the data panel + /** + * This method updates the data panel */ private void updateDataPanel() { - double[] tmpT = this.m_WLPT.m_IdealValue; - double[] tmpP = this.m_WLPT.m_Weights; - int obj = this.m_WLPT.m_P; + double[] tmpT = this.m_WLPT.m_IdealValue; + double[] tmpP = this.m_WLPT.m_Weights; + int obj = this.m_WLPT.m_P; - this.m_PValue.setText(""+obj); + this.m_PValue.setText("" + obj); this.m_DataPanel.removeAll(); - this.m_DataPanel.setLayout(new GridLayout(tmpT.length+1, 3)); + this.m_DataPanel.setLayout(new GridLayout(tmpT.length + 1, 3)); this.m_DataPanel.add(new JLabel()); this.m_DataPanel.add(new JLabel("Ideal Value")); this.m_DataPanel.add(new JLabel("Weights")); this.m_IdealTextField = new JTextField[tmpT.length]; this.m_WeightTextField = new JTextField[tmpT.length]; for (int i = 0; i < tmpT.length; i++) { - JLabel label = new JLabel("Objective "+i+": "); + JLabel label = new JLabel("Objective " + i + ": "); this.m_DataPanel.add(label); - this.m_IdealTextField[i] = new JTextField(); - this.m_IdealTextField[i].setText(""+tmpT[i]); + this.m_IdealTextField[i] = new JTextField(); + this.m_IdealTextField[i].setText("" + tmpT[i]); this.m_IdealTextField[i].addKeyListener(this.readDoubleArrayAction); this.m_DataPanel.add(this.m_IdealTextField[i]); - this.m_WeightTextField[i] = new JTextField(); - this.m_WeightTextField[i].setText(""+tmpP[i]); + this.m_WeightTextField[i] = new JTextField(); + this.m_WeightTextField[i].setText("" + tmpP[i]); this.m_WeightTextField[i].addKeyListener(this.readDoubleArrayAction); this.m_DataPanel.add(this.m_WeightTextField[i]); } } - /** This method will set the value of object that is to be edited. + /** + * This method will set the value of object that is to be edited. + * * @param o an object that must be an array. */ @Override @@ -184,7 +201,9 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper } } - /** Returns the current object. + /** + * Returns the current object. + * * @return the current object */ @Override @@ -223,35 +242,41 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.addPropertyChangeListener(l); + m_Support.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); + m_Support.removePropertyChangeListener(l); } - /** This is used to hook an action listener to the ok button + /** + * This is used to hook an action listener to the ok button + * * @param a The action listener. */ public void addOkListener(ActionListener a) { m_OKButton.addActionListener(a); } - /** This is used to remove an action listener from the ok button + /** + * This is used to remove an action listener from the ok button + * * @param a The action listener */ public void removeOkListener(ActionListener a) { m_OKButton.removeActionListener(a); } - /** Returns true since the Object can be shown + /** + * Returns true since the Object can be shown + * * @return true */ @Override @@ -259,7 +284,8 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper return true; } - /** Paints a representation of the current classifier. + /** + * Paints a representation of the current classifier. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into @@ -269,20 +295,24 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; String rep = "Edit the ideal vector, p and ev. the weights."; - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); } - /** Returns true because we do support a custom editor. - * @return true - */ + /** + * Returns true because we do support a custom editor. + * + * @return true + */ @Override public boolean supportsCustomEditor() { return true; } - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override public Component getCustomEditor() { if (this.m_CustomEditor == null) { diff --git a/src/eva2/gui/editor/MultiLineStringEditor.java b/src/eva2/gui/editor/MultiLineStringEditor.java index 317ed3a9..0f4b9f1f 100644 --- a/src/eva2/gui/editor/MultiLineStringEditor.java +++ b/src/eva2/gui/editor/MultiLineStringEditor.java @@ -12,80 +12,101 @@ import java.beans.*; *

Description:

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author not attributable * @version 1.0 */ public class MultiLineStringEditor implements PropertyEditor { - protected MultiLineString value; // The value we will be editing. + protected MultiLineString value; // The value we will be editing. @Override - public void setValue(Object o) { value=(MultiLineString) o;} - @Override - public Object getValue() { return value; } - @Override - public void setAsText(String s) { value.setString(s); } - @Override - public String getAsText() { return value.getString(); } - @Override - public String[] getTags() { return null; } // not enumerated; no tags + public void setValue(Object o) { + value = (MultiLineString) o; + } - // Say that we allow custom editing. @Override - public boolean supportsCustomEditor() { return true; } + public Object getValue() { + return value; + } - // Return the custom editor. This just creates and returns a TextArea - // to edit the multi-line text. But it also registers a listener on the - // text area to update the value as the user types and to fire the - // property change events that property editors are required to fire. @Override - public Component getCustomEditor() { - final TextArea t = new TextArea(value.string); - t.setSize(300, 150); // TextArea doesn't have a preferred size, so set one - t.addTextListener(new TextListener() { + public void setAsText(String s) { + value.setString(s); + } + + @Override + public String getAsText() { + return value.getString(); + } + + @Override + public String[] getTags() { + return null; + } // not enumerated; no tags + + // Say that we allow custom editing. + @Override + public boolean supportsCustomEditor() { + return true; + } + + // Return the custom editor. This just creates and returns a TextArea + // to edit the multi-line text. But it also registers a listener on the + // text area to update the value as the user types and to fire the + // property change events that property editors are required to fire. + @Override + public Component getCustomEditor() { + final TextArea t = new TextArea(value.string); + t.setSize(300, 150); // TextArea doesn't have a preferred size, so set one + t.addTextListener(new TextListener() { @Override - public void textValueChanged(TextEvent e) { - value.setString(t.getText()); - listeners.firePropertyChange(null, null, null); - } - }); - return t; - } + public void textValueChanged(TextEvent e) { + value.setString(t.getText()); + listeners.firePropertyChange(null, null, null); + } + }); + return t; + } - // Visual display of the value, for use with the custom editor. - // Just print some instructions and hope they fit in the in the box. - // This could be more sophisticated. + // Visual display of the value, for use with the custom editor. + // Just print some instructions and hope they fit in the in the box. + // This could be more sophisticated. @Override - public boolean isPaintable() { return true; } + public boolean isPaintable() { + return true; + } @Override - public void paintValue(Graphics g, Rectangle r) { - g.setClip(r); - g.drawString("Click to edit...", r.x+5, r.y+15); - } + public void paintValue(Graphics g, Rectangle r) { + g.setClip(r); + g.drawString("Click to edit...", r.x + 5, r.y + 15); + } - // Important method for code generators. Note that it - // ought to add any necessary escape sequences. + // Important method for code generators. Note that it + // ought to add any necessary escape sequences. @Override - public String getJavaInitializationString() { return "\"" + value + "\""; } + public String getJavaInitializationString() { + return "\"" + value + "\""; + } - // This code uses the PropertyChangeSupport class to maintain a list of - // listeners interested in the edits we make to the value. - protected PropertyChangeSupport listeners = new PropertyChangeSupport(this); - - @Override - public void addPropertyChangeListener(PropertyChangeListener l) { - if (listeners == null) { - listeners = new PropertyChangeSupport(this); - } - listeners.addPropertyChangeListener(l); - } + // This code uses the PropertyChangeSupport class to maintain a list of + // listeners interested in the edits we make to the value. + protected PropertyChangeSupport listeners = new PropertyChangeSupport(this); @Override - public void removePropertyChangeListener(PropertyChangeListener l) { - if (listeners == null) { - listeners = new PropertyChangeSupport(this); - } - listeners.removePropertyChangeListener(l); - } + public void addPropertyChangeListener(PropertyChangeListener l) { + if (listeners == null) { + listeners = new PropertyChangeSupport(this); + } + listeners.addPropertyChangeListener(l); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener l) { + if (listeners == null) { + listeners = new PropertyChangeSupport(this); + } + listeners.removePropertyChangeListener(l); + } } diff --git a/src/eva2/gui/editor/StatisticsEditor.java b/src/eva2/gui/editor/StatisticsEditor.java index d49037d9..94c71336 100644 --- a/src/eva2/gui/editor/StatisticsEditor.java +++ b/src/eva2/gui/editor/StatisticsEditor.java @@ -9,144 +9,146 @@ package eva2.gui.editor; * $Date: 2007-10-23 13:43:24 +0200 (Tue, 23 Oct 2007) $ * $Author: mkron $ */ + import eva2.gui.PropertySheetPanelStat; import eva2.optimization.stat.GenericStatistics; + import java.awt.*; import java.beans.*; import javax.swing.*; public class StatisticsEditor implements PropertyEditor { - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - private PropertySheetPanelStat m_StatPanel; - private JScrollPane m_ScrollPane; - private JPanel m_Panel; - private GenericStatistics m_Value; + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + private PropertySheetPanelStat m_StatPanel; + private JScrollPane m_ScrollPane; + private JPanel m_Panel; + private GenericStatistics m_Value; - /** - * - */ + /** + * + */ public StatisticsEditor() { - super(); - m_StatPanel = new PropertySheetPanelStat(); - m_StatPanel.addPropertyChangeListener( - new PropertyChangeListener() { + super(); + m_StatPanel = new PropertySheetPanelStat(); + m_StatPanel.addPropertyChangeListener( + new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - m_Support.firePropertyChange("", null, null); - } - }); - m_ScrollPane = new JScrollPane(m_StatPanel); - m_Panel = new JPanel(); - m_Panel.setLayout(new BorderLayout()); + @Override + public void propertyChange(PropertyChangeEvent evt) { + m_Support.firePropertyChange("", null, null); + } + }); + m_ScrollPane = new JScrollPane(m_StatPanel); + m_Panel = new JPanel(); + m_Panel.setLayout(new BorderLayout()); - m_Panel.add(m_ScrollPane, BorderLayout.CENTER); + m_Panel.add(m_ScrollPane, BorderLayout.CENTER); - } + } - /** - * - */ + /** + * + */ @Override public void setValue(Object value) { - if (value instanceof GenericStatistics) { + if (value instanceof GenericStatistics) { m_Value = (GenericStatistics) value; m_StatPanel.setTarget(m_Value.getPropertyNames(), m_Value.getState()); + } + m_Support.firePropertyChange("", null, null); } - m_Support.firePropertyChange("", null, null); - } - /** - * - */ + /** + * + */ @Override public Object getValue() { - System.out.println("getValue !!!!!!!!!!!!"); - m_Value.setState(m_StatPanel.getState()); - return m_Value; - } + System.out.println("getValue !!!!!!!!!!!!"); + m_Value.setState(m_StatPanel.getState()); + return m_Value; + } - /** - * - */ + /** + * + */ @Override public String getJavaInitializationString() { return "null"; - } + } - /** - * - */ + /** + * + */ @Override public boolean isPaintable() { return true; - } + } - /** - * - */ + /** + * + */ @Override public void paintValue(Graphics gfx, Rectangle box) { - FontMetrics fm = gfx.getFontMetrics(); + FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; - //String rep = EVAHELP.cutClassName(m_ElementClass.getName()); - gfx.drawString("StatisticeEditor", 2, fm.getHeight() + vpad - 3); - } + //String rep = EVAHELP.cutClassName(m_ElementClass.getName()); + gfx.drawString("StatisticeEditor", 2, fm.getHeight() + vpad - 3); + } - /** - * - */ + /** + * + */ @Override public String getAsText() { return null; - } + } - /** - * - */ + /** + * + */ @Override public void setAsText(String text) throws IllegalArgumentException { throw new IllegalArgumentException(text); - } + } - /** - * - */ + /** + * + */ @Override public String[] getTags() { return null; - } + } - /** - * - */ + /** + * + */ @Override public boolean supportsCustomEditor() { return true; - } + } - /** - * - */ + /** + * + */ @Override public Component getCustomEditor() { return m_Panel; - } + } @Override - public void addPropertyChangeListener(PropertyChangeListener l) { + public void addPropertyChangeListener(PropertyChangeListener l) { if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.addPropertyChangeListener(l); - } + m_Support.addPropertyChangeListener(l); + } @Override - public void removePropertyChangeListener(PropertyChangeListener l) { + public void removePropertyChangeListener(PropertyChangeListener l) { if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); - } + m_Support.removePropertyChangeListener(l); + } } diff --git a/src/eva2/gui/editor/StringSelectionEditor.java b/src/eva2/gui/editor/StringSelectionEditor.java index 320f9a3b..e9da11f0 100644 --- a/src/eva2/gui/editor/StringSelectionEditor.java +++ b/src/eva2/gui/editor/StringSelectionEditor.java @@ -3,83 +3,83 @@ package eva2.gui.editor; import eva2.tools.StringSelection; public class StringSelectionEditor extends AbstractListSelectionEditor { - StringSelection strs; - - public StringSelectionEditor() { - strs = new StringSelection(new String[]{}, null); - } - - @Override - protected boolean actionOnSelect() { - for (int i = 0; i < this.m_BlackCheck.length; i++) { - strs.setSelected(i, this.m_BlackCheck[i].isSelected()); - } - return true; - } + StringSelection strs; - @Override - protected int getElementCount() { - return strs.getLength(); - } + public StringSelectionEditor() { + strs = new StringSelection(new String[]{}, null); + } - @Override - protected String getElementName(int i) { - return strs.getElement(i); - } - - @Override - protected String getElementToolTip(int i) { - return strs.getElementInfo(i); - } + @Override + protected boolean actionOnSelect() { + for (int i = 0; i < this.m_BlackCheck.length; i++) { + strs.setSelected(i, this.m_BlackCheck[i].isSelected()); + } + return true; + } - @Override - public Object getValue() { - return strs; - } + @Override + protected int getElementCount() { + return strs.getLength(); + } - @Override - protected boolean isElementSelected(int i) { - return strs.isSelected(i); - } + @Override + protected String getElementName(int i) { + return strs.getElement(i); + } - @Override - protected boolean setObject(Object o) { + @Override + protected String getElementToolTip(int i) { + return strs.getElementInfo(i); + } + + @Override + public Object getValue() { + return strs; + } + + @Override + protected boolean isElementSelected(int i) { + return strs.isSelected(i); + } + + @Override + protected boolean setObject(Object o) { if (o instanceof StringSelection) { strs = (StringSelection) o; // m_AreaObject.addPropertyChangeListener(this); return true; } else { - return false; + return false; + } + } + + @Override + public String getName() { + return "StringSelection"; + } + + @Override + public String getAsText() { + StringBuffer sbuf = new StringBuffer("{"); + boolean first = true; + for (int i = 0; i < getElementCount(); i++) { + if (isElementSelected(i)) { + if (!first) { + sbuf.append(", "); + } + sbuf.append(getElementName(i)); + first = false; } - } + } + sbuf.append("}"); + return sbuf.toString(); + } - @Override - public String getName() { - return "StringSelection"; - } + @Override + public void setAsText(String text) throws IllegalArgumentException { + for (int i = 0; i < getElementCount(); i++) { + strs.setSelected(i, text.contains(getElementName(i))); + } + } - @Override - public String getAsText() { - StringBuffer sbuf = new StringBuffer("{"); - boolean first = true; - for (int i=0; i jumps = new ArrayList(); - public void addJump() - { + public void addJump() { jumps.add(getSize()); } - public boolean hasMoreIntervals() - { + public boolean hasMoreIntervals() { return index < jumps.size(); } - public int[] nextInterval() - { + public int[] nextInterval() { int no_jumps = jumps.size(); - if (index >= no_jumps) - { + if (index >= no_jumps) { throw new ArrayIndexOutOfBoundsException( - "No more intervals in JumpManager"); + "No more intervals in JumpManager"); } int[] inter = new int[2]; - if (index == -1) - { + if (index == -1) { inter[0] = 0; - } - else - { + } else { inter[0] = jumps.get(index); } index++; - if (index < no_jumps) - { + if (index < no_jumps) { inter[1] = jumps.get(index); - } - else - { + } else { inter[1] = getSize(); } return inter; } - public void reset() - { + public void reset() { index = -1; jumps.clear(); } - public void restore() - { + public void restore() { index = -1; } } + protected boolean connectedMI; protected DPointIcon iconMI = null; protected DPointSetMultiIcon.JumpManager jumperMI = new DPointSetMultiIcon.JumpManager(); @@ -104,17 +91,14 @@ public class DPointSetMultiIcon extends DComponent protected DIntDoubleMap yMI; - public DPointSetMultiIcon() - { + public DPointSetMultiIcon() { this(10, 2); } - public DPointSetMultiIcon(DIntDoubleMap x_values, DIntDoubleMap y_values) - { - if (x_values.getSize() != y_values.getSize()) - { + public DPointSetMultiIcon(DIntDoubleMap x_values, DIntDoubleMap y_values) { + if (x_values.getSize() != y_values.getSize()) { throw new IllegalArgumentException( - "The number of x-values has to be the same than the number of y-values"); + "The number of x-values has to be the same than the number of y-values"); } xMI = x_values; @@ -123,26 +107,22 @@ public class DPointSetMultiIcon extends DComponent setDBorder(new DBorder(1, 1, 1, 1)); } - public DPointSetMultiIcon(int initial_capacity) - { + public DPointSetMultiIcon(int initial_capacity) { this(initial_capacity, 2); } //~ Methods //////////////////////////////////////////////////////////////// - public DPointSetMultiIcon(int initial_capacity, int length_multiplier) - { + public DPointSetMultiIcon(int initial_capacity, int length_multiplier) { this(new DArray(initial_capacity, length_multiplier), - new DArray(initial_capacity, length_multiplier)); + new DArray(initial_capacity, length_multiplier)); } - public void addDPoint(double x, double y) - { + public void addDPoint(double x, double y) { addDPoint(new DPoint(x, y)); } - public void addDPoint(DPoint p) - { + public void addDPoint(DPoint p) { xMI.addImage(p.x); yMI.addImage(p.y); m_IconsMI.add(p.getIcon()); @@ -156,10 +136,8 @@ public class DPointSetMultiIcon extends DComponent * @param index the index of the DPoint * @return the DPoint at the given index */ - public DPoint getDPoint(int index) - { - if (index >= xMI.getSize()) - { + public DPoint getDPoint(int index) { + if (index >= xMI.getSize()) { throw new ArrayIndexOutOfBoundsException(index); } @@ -170,8 +148,7 @@ public class DPointSetMultiIcon extends DComponent return p; } - public DPointSet getDPointSet() - { + public DPointSet getDPointSet() { return new DPointSet(xMI, yMI); } @@ -180,8 +157,7 @@ public class DPointSetMultiIcon extends DComponent * * @return the DPointIcon */ - public DPointIcon getIcon() - { + public DPointIcon getIcon() { return iconMI; } @@ -194,16 +170,12 @@ public class DPointSetMultiIcon extends DComponent * * @return the nearest DPoint */ - public DPoint getNearestDPoint(DPoint point) - { + public DPoint getNearestDPoint(DPoint point) { int minIndex = getNearestDPointIndex(point); - if (minIndex == -1) - { + if (minIndex == -1) { return null; - } - else - { + } else { DPoint result = new DPoint(xMI.getImage(minIndex), yMI.getImage(minIndex)); result.setIcon((DPointIcon) this.m_IconsMI.get(minIndex)); @@ -212,22 +184,21 @@ public class DPointSetMultiIcon extends DComponent } } - /** method returns the index to the nearest DPoint in this DPointSet. + /** + * method returns the index to the nearest DPoint in this DPointSet. + * * @return the index to the nearest DPoint. -1 if no nearest DPoint was found. */ - public int getNearestDPointIndex(DPoint point) - { + public int getNearestDPointIndex(DPoint point) { double minValue = Double.MAX_VALUE; int minIndex = -1; - for (int i = 0; i < xMI.getSize(); i++) - { + for (int i = 0; i < xMI.getSize(); i++) { double dx = point.x - xMI.getImage(i); double dy = point.y - yMI.getImage(i); double dummy = (dx * dx) + (dy * dy); - if (dummy < minValue) - { + if (dummy < minValue) { minValue = dummy; minIndex = i; } @@ -236,8 +207,7 @@ public class DPointSetMultiIcon extends DComponent return minIndex; } - public int getSize() - { + public int getSize() { int size = Math.min(xMI.getSize(), yMI.getSize()); // int size = x.getSize(); @@ -254,8 +224,7 @@ public class DPointSetMultiIcon extends DComponent * * @return the stroke */ - public Stroke getStroke() - { + public Stroke getStroke() { return strokeMI; } @@ -263,58 +232,46 @@ public class DPointSetMultiIcon extends DComponent * This method causes the DPointSet to interupt the connected painting at the * current position. */ - public void jump() - { + public void jump() { jumperMI.addJump(); } @Override - public void paint(DMeasures m) - { - try - { + public void paint(DMeasures m) { + try { Graphics2D g = (Graphics2D) m.getGraphics(); g.setStroke(strokeMI); - if (color != null) - { + if (color != null) { g.setColor(color); } int size = getSize(); - if (connectedMI && (size > 1)) - { + if (connectedMI && (size > 1)) { jumperMI.restore(); - while (jumperMI.hasMoreIntervals()) - { + while (jumperMI.hasMoreIntervals()) { int[] interval = jumperMI.nextInterval(); Point p1 = null; Point p2; - for (int i = interval[0]; i < interval[1]; i++) - { + for (int i = interval[0]; i < interval[1]; i++) { p2 = m.getPoint(xMI.getImage(i), yMI.getImage(i)); - if (p1 != null) - { - if (p2!=null) { - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } + if (p1 != null) { + if (p2 != null) { + g.drawLine(p1.x, p1.y, p2.x, p2.y); + } } - if ((i < this.m_IconsMI.size()) && (this.m_IconsMI.get(i) != null)) - { + if ((i < this.m_IconsMI.size()) && (this.m_IconsMI.get(i) != null)) { g.setStroke(new BasicStroke()); g.translate(p2.x, p2.y); ((DPointIcon) this.m_IconsMI.get(i)).paint(g); g.translate(-p2.x, -p2.y); g.setStroke(strokeMI); - } - else - { - if (iconMI != null) - { + } else { + if (iconMI != null) { g.setStroke(new BasicStroke()); g.translate(p2.x, p2.y); iconMI.paint(g); @@ -326,66 +283,50 @@ public class DPointSetMultiIcon extends DComponent p1 = p2; } } - } - else - { + } else { Point p; //for (int i = 0; i < size; i++) // @todo Streiche: Mal wieder eine index out of bounds exception, dass ist einfach mist... - for (int i = 0; i < this.m_IconsMI.size(); i++) - { - try - { + for (int i = 0; i < this.m_IconsMI.size(); i++) { + try { p = m.getPoint(xMI.getImage(i), yMI.getImage(i)); - if (p==null) { + if (p == null) { continue; } - if (this.m_IconsMI.get(i) != null) - { + if (this.m_IconsMI.get(i) != null) { g.setStroke(new BasicStroke()); g.translate(p.x, p.y); ((DPointIcon) this.m_IconsMI.get(i)).paint(g); g.translate(-p.x, -p.y); g.setStroke(strokeMI); - } - else - { - if (iconMI == null) - { + } else { + if (iconMI == null) { g.drawLine(p.x - 1, p.y - 1, p.x + 1, p.y + 1); g.drawLine(p.x + 1, p.y - 1, p.x - 1, p.y + 1); - } - else - { + } else { g.setStroke(new BasicStroke()); g.translate(p.x, p.y); iconMI.paint(g); g.translate(-p.x, -p.y); } } - } - catch (java.lang.IllegalArgumentException e) - { + } catch (java.lang.IllegalArgumentException e) { System.out.println( - "The rectangle lies not in the currently painted rectangle."); + "The rectangle lies not in the currently painted rectangle."); } } } g.setStroke(new BasicStroke()); - } - catch (java.lang.ArrayIndexOutOfBoundsException e) - { + } catch (java.lang.ArrayIndexOutOfBoundsException e) { // *pff* } } - public void removeAllPoints() - { - if (xMI.getSize() == 0) - { + public void removeAllPoints() { + if (xMI.getSize() == 0) { return; } @@ -401,15 +342,12 @@ public class DPointSetMultiIcon extends DComponent * if the DPointSet is connected, all points will be painted connected to * their following point */ - public void removeJumps() - { + public void removeJumps() { jumperMI.reset(); } - protected void restore() - { - if (getSize() == 0) - { + protected void restore() { + if (getSize() == 0) { rectangle = DRectangle.getEmpty(); return; @@ -422,13 +360,11 @@ public class DPointSetMultiIcon extends DComponent rectangle = new DRectangle(min_x, min_y, max_x - min_x, max_y - min_y); } - public void setConnected(boolean aFlag) - { + public void setConnected(boolean aFlag) { boolean changed = !(aFlag == connectedMI); connectedMI = aFlag; - if (changed) - { + if (changed) { repaint(); } } @@ -439,10 +375,8 @@ public class DPointSetMultiIcon extends DComponent * @param index the index of the point * @param p the point to insert */ - public void setDPoint(int index, DPoint p) - { - if (index >= xMI.getSize()) - { + public void setDPoint(int index, DPoint p) { + if (index >= xMI.getSize()) { throw new ArrayIndexOutOfBoundsException(index); } @@ -459,30 +393,24 @@ public class DPointSetMultiIcon extends DComponent * * @param icon the DPointIcon */ - public void setIcon(DPointIcon icon) - { + public void setIcon(DPointIcon icon) { this.iconMI = icon; - if (icon == null) - { + if (icon == null) { setDBorder(new DBorder(1, 1, 1, 1)); - } - else - { + } else { setDBorder(icon.getDBorder()); } } /** - * method sets the stroke of the line - * if the points were not connected, they now will be connected + * method sets the stroke of the line + * if the points were not connected, they now will be connected * * @param s the new stroke */ - public void setStroke(Stroke s) - { - if (s == null) - { + public void setStroke(Stroke s) { + if (s == null) { s = new BasicStroke(); } @@ -493,12 +421,10 @@ public class DPointSetMultiIcon extends DComponent //~ Inner Classes ////////////////////////////////////////////////////////// @Override - public String toString() - { + public String toString() { String text = "eva2.tools.chart2d.DPointSet[size:" + getSize(); - for (int i = 0; i < xMI.getSize(); i++) - { + for (int i = 0; i < xMI.getSize(); i++) { text += (",(" + xMI.getImage(i) + "," + yMI.getImage(i) + ")"); } diff --git a/src/eva2/gui/plot/DataViewer.java b/src/eva2/gui/plot/DataViewer.java index 425f60d6..808d194d 100644 --- a/src/eva2/gui/plot/DataViewer.java +++ b/src/eva2/gui/plot/DataViewer.java @@ -31,7 +31,7 @@ public class DataViewer implements DataViewerInterface { } DataViewerInterface ret = null; try { - if (!viewContainer.containsName(graphWindowName)) { + if (!viewContainer.containsName(graphWindowName)) { ret = new DataViewer(graphWindowName, true); viewContainer.add(ret); } else { @@ -89,7 +89,8 @@ class ViewContainer extends ArrayList { /** * */ - public ViewContainer() { } + public ViewContainer() { + } /** * diff --git a/src/eva2/gui/plot/DataViewerInterface.java b/src/eva2/gui/plot/DataViewerInterface.java index 229ad6b2..b83fb63d 100644 --- a/src/eva2/gui/plot/DataViewerInterface.java +++ b/src/eva2/gui/plot/DataViewerInterface.java @@ -16,6 +16,7 @@ import eva2.gui.plot.Graph; * IMPORTS *==========================================================================*/ public interface DataViewerInterface { - public Graph getNewGraph(String InfoString); - public void init(); + public Graph getNewGraph(String InfoString); + + public void init(); } \ No newline at end of file diff --git a/src/eva2/gui/plot/FunctionArea.java b/src/eva2/gui/plot/FunctionArea.java index 7b79d01d..41fe3a1b 100644 --- a/src/eva2/gui/plot/FunctionArea.java +++ b/src/eva2/gui/plot/FunctionArea.java @@ -11,6 +11,7 @@ package eva2.gui.plot; * IMPORTS *========================================================================== */ + import eva2.gui.*; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.mocco.paretofrontviewer.InterfaceRefPointListener; @@ -27,6 +28,7 @@ import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointSet; import eva2.tools.chart2d.ScaledBorder; + import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; @@ -205,11 +207,11 @@ public class FunctionArea extends DArea implements Serializable { + " graph tool tips"; addMenuItem(graphPopupMenu, togGTTName, new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - setShowGraphToolTips(!isShowGraphToolTips()); - } - }); + @Override + public void actionPerformed(ActionEvent ee) { + setShowGraphToolTips(!isShowGraphToolTips()); + } + }); String togLName = (isShowLegend() ? "Hide" : "Show") + " legend"; @@ -230,11 +232,11 @@ public class FunctionArea extends DArea implements Serializable { if (FunctionArea.this.pointSetContainer.size() > 0) { addMenuItem(graphPopupMenu, "Recolor all graphs", new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - recolorAllGraphsByIndex(); - } - }); + @Override + public void actionPerformed(ActionEvent ee) { + recolorAllGraphsByIndex(); + } + }); } if (refPointListener != null) { @@ -242,16 +244,16 @@ public class FunctionArea extends DArea implements Serializable { addMenuItem(graphPopupMenu, "Select Reference Point:(" + temp.x + "/" + temp.y + ")", new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - DPoint temp = getDMeasures().getDPoint( - xPos, yPos); - double[] point = new double[2]; - point[0] = temp.x; - point[1] = temp.y; - refPointListener.refPointGiven(point); - } - }); + @Override + public void actionPerformed(ActionEvent ee) { + DPoint temp = getDMeasures().getDPoint( + xPos, yPos); + double[] point = new double[2]; + point[0] = temp.x; + point[1] = temp.y; + refPointListener.refPointGiven(point); + } + }); } // darn this point is an empty copy !! @@ -261,19 +263,19 @@ public class FunctionArea extends DArea implements Serializable { addMenuItem(graphPopupMenu, "Nearest point: (" + point.x + "/" + point.y + ")", new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - } - }, false); + @Override + public void actionPerformed(ActionEvent ee) { + } + }, false); addMenuItem(graphPopupMenu, " Remove point", new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - removePoint(FunctionArea.this.xPos, - FunctionArea.this.yPos); - } - }); + @Override + public void actionPerformed(ActionEvent ee) { + removePoint(FunctionArea.this.xPos, + FunctionArea.this.yPos); + } + }); if (point.getIcon() instanceof InterfaceSelectablePointIcon) { currentPointIcon = point.getIcon(); @@ -283,13 +285,13 @@ public class FunctionArea extends DArea implements Serializable { : " Select individual"; addMenuItem(graphPopupMenu, selectTitle, new ActionListener() { - @Override - public void actionPerformed( - ActionEvent ee) { - ((InterfaceSelectablePointIcon) currentPointIcon).getSelectionListener().individualSelected( - ((InterfaceSelectablePointIcon) currentPointIcon).getEAIndividual()); - } - }); + @Override + public void actionPerformed( + ActionEvent ee) { + ((InterfaceSelectablePointIcon) currentPointIcon).getSelectionListener().individualSelected( + ((InterfaceSelectablePointIcon) currentPointIcon).getEAIndividual()); + } + }); } } @@ -297,16 +299,16 @@ public class FunctionArea extends DArea implements Serializable { currentPointIcon = point.getIcon(); addMenuItem(graphPopupMenu, " Show individual", new ActionListener() { - @Override - public void actionPerformed( - ActionEvent ee) { - ((InterfaceDPointWithContent) currentPointIcon).showIndividual(); - } - }); + @Override + public void actionPerformed( + ActionEvent ee) { + ((InterfaceDPointWithContent) currentPointIcon).showIndividual(); + } + }); } } - if (FunctionArea.this.pointSetContainer.size() > 0) { + if (FunctionArea.this.pointSetContainer.size() > 0) { // there is at least one graph // The graph info element // int gIndex = getNearestGraphIndex(e.getX(), @@ -314,45 +316,45 @@ public class FunctionArea extends DArea implements Serializable { addMenuItem(graphPopupMenu, "Graph Info: " + getGraphInfo(e.getX(), e.getY()), new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - DPoint temp = FunctionArea.this.getDMeasures().getDPoint( - FunctionArea.this.xPos, - FunctionArea.this.yPos); - DPointIcon icon1 = new DPointIcon() { @Override - public DBorder getDBorder() { - return new DBorder(4, 4, 4, 4); - } + public void actionPerformed(ActionEvent ee) { + DPoint temp = FunctionArea.this.getDMeasures().getDPoint( + FunctionArea.this.xPos, + FunctionArea.this.yPos); + DPointIcon icon1 = new DPointIcon() { + @Override + public DBorder getDBorder() { + return new DBorder(4, 4, 4, 4); + } - @Override - public void paint(Graphics g) { - g.drawLine(-2, 0, 2, 0); - g.drawLine(0, 0, 0, 4); + @Override + public void paint(Graphics g) { + g.drawLine(-2, 0, 2, 0); + g.drawLine(0, 0, 0, 4); + } + }; + temp.setIcon(icon1); + FunctionArea.this.addDElement(temp); } - }; - temp.setIcon(icon1); - FunctionArea.this.addDElement(temp); - } - }, false); + }, false); addMenuItem(graphPopupMenu, " Remove graph", new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - clearGraph(FunctionArea.this.xPos, - FunctionArea.this.yPos); - } - }); + @Override + public void actionPerformed(ActionEvent ee) { + clearGraph(FunctionArea.this.xPos, + FunctionArea.this.yPos); + } + }); addMenuItem(graphPopupMenu, " Change graph color", new ActionListener() { - @Override - public void actionPerformed(ActionEvent ee) { - changeColorGraph(FunctionArea.this.xPos, - FunctionArea.this.yPos); - } - }); + @Override + public void actionPerformed(ActionEvent ee) { + changeColorGraph(FunctionArea.this.xPos, + FunctionArea.this.yPos); + } + }); } graphPopupMenu.show(FunctionArea.this, e.getX(), e.getY()); } @@ -370,7 +372,7 @@ public class FunctionArea extends DArea implements Serializable { * @return */ private JMenuItem addMenuItem(JPopupMenu menu, String title, - ActionListener aListener) { + ActionListener aListener) { return addMenuItem(menu, title, aListener, true); } @@ -385,7 +387,7 @@ public class FunctionArea extends DArea implements Serializable { * @return */ private JMenuItem addMenuItem(JPopupMenu menu, String title, - ActionListener aListener, boolean enabled) { + ActionListener aListener, boolean enabled) { JMenuItem item = new JMenuItem(title); // if (bgColor!=null) item.setForeground(bgColor); item.addActionListener(aListener); @@ -431,7 +433,6 @@ public class FunctionArea extends DArea implements Serializable { /** * Re-color all graphs which are nonempty by their index. - * */ public void recolorAllGraphsByIndex() { int index = 0; @@ -446,7 +447,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @return */ public boolean checkLoggable() { @@ -602,7 +602,7 @@ public class FunctionArea extends DArea implements Serializable { * @param graphID */ public void drawIcon(DPointIcon theIcon, String label, double[] position, - int graphID) { + int graphID) { DPointSet popRep; popRep = new DPointSet(); popRep.addDPoint(new DPoint(position[0], position[1])); @@ -623,7 +623,7 @@ public class FunctionArea extends DArea implements Serializable { * @param graphID */ public void drawIcon(int iconType, String label, double[] position, - int graphID) { + int graphID) { DPointIcon theIcon; switch (iconType) { case 0: @@ -656,7 +656,6 @@ public class FunctionArea extends DArea implements Serializable { /** * Export contained data to standard output. - * */ public void exportToAscii() { exportToAscii((File) null); @@ -758,7 +757,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param x * @param y * @return @@ -798,7 +796,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param GraphLabel * @return */ @@ -857,7 +854,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param x * @param y * @return @@ -941,7 +937,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @return */ public DPointSet[] printPoints() { @@ -957,7 +952,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param i * @return */ @@ -971,7 +965,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param x * @param y */ @@ -1004,7 +997,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param p * @param graphLabel */ @@ -1013,7 +1005,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param GraphLabel * @param color */ @@ -1022,7 +1013,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param GraphLabel * @param colorindex */ @@ -1031,7 +1021,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param GraphLabel * @param Info * @param stroke @@ -1054,7 +1043,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param x * @param y * @param GraphLabel @@ -1073,7 +1061,6 @@ public class FunctionArea extends DArea implements Serializable { } /** - * * @param p * @param GraphLabel */ @@ -1191,7 +1178,7 @@ public class FunctionArea extends DArea implements Serializable { * Allows setting whether or not to paint the y-axis in logarithmic scale. * * @param log if true logarithmic scale is used, linear scale in case of - * false. + * false. */ public void toggleLog(boolean log) { if (log != log) { @@ -1201,7 +1188,6 @@ public class FunctionArea extends DArea implements Serializable { /** * Recreate the legend object with the current point sets. - * */ public void updateLegend() { GraphPointSetLegend lb = new GraphPointSetLegend(pointSetContainer, diff --git a/src/eva2/gui/plot/Graph.java b/src/eva2/gui/plot/Graph.java index 0673b57a..a6222bc4 100644 --- a/src/eva2/gui/plot/Graph.java +++ b/src/eva2/gui/plot/Graph.java @@ -32,7 +32,6 @@ public class Graph implements Serializable { } /** - * * @param Info * @param stroke */ @@ -84,7 +83,7 @@ public class Graph implements Serializable { * false if force was used and points possibly have been lost. * * @return true if the graph could be added directly or false if the graph was added by force - * losing some data points + * losing some data points * @see PlotInterface.addGraph */ public boolean addGraph(Graph x) { diff --git a/src/eva2/gui/plot/GraphPointSet.java b/src/eva2/gui/plot/GraphPointSet.java index b029abe4..b9952e14 100644 --- a/src/eva2/gui/plot/GraphPointSet.java +++ b/src/eva2/gui/plot/GraphPointSet.java @@ -20,6 +20,7 @@ import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointSet; import eva2.tools.math.Mathematics; + import java.awt.BasicStroke; import java.awt.Color; import java.io.Serializable; @@ -28,549 +29,527 @@ import java.util.ArrayList; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ + /** - * - */ + * + */ public class GraphPointSet { - // Color sequence of the plot graphs - public static Color[] colorSequence = - new Color[]{ - Color.black, Color.red, Color.blue, Color.pink, Color.green, - Color.gray, Color.magenta, Color.cyan, Color.orange, - new Color(148, 0, 211), // dark violet, - new Color(72 , 209 , 204), // turquoise - new Color(128 ,128 ,0), // olive - new Color(34 ,139 ,34), // forest green - new Color(100 ,149 ,237 ) // cornflower - }; - - /** - * - */ - class PointSet implements Serializable { - /** - * Generated serial version identifier - */ - private static final long serialVersionUID = -5863595580492128866L; - private Color m_Color; - private double[] m_X; - private double[] m_Y; + // Color sequence of the plot graphs + public static Color[] colorSequence = + new Color[]{ + Color.black, Color.red, Color.blue, Color.pink, Color.green, + Color.gray, Color.magenta, Color.cyan, Color.orange, + new Color(148, 0, 211), // dark violet, + new Color(72, 209, 204), // turquoise + new Color(128, 128, 0), // olive + new Color(34, 139, 34), // forest green + new Color(100, 149, 237) // cornflower + }; - /** - * - * @param pointset - */ - public PointSet(DPointSet pointset) { - m_Color = pointset.getColor(); - m_X = new double[pointset.getSize()]; - m_Y = new double[pointset.getSize()]; - for (int i = 0; i < pointset.getSize(); i++) { - DPoint point = pointset.getDPoint(i); - m_X[i] = point.x; - m_Y[i] = point.y; - } - } + /** + * + */ + class PointSet implements Serializable { + /** + * Generated serial version identifier + */ + private static final long serialVersionUID = -5863595580492128866L; + private Color m_Color; + private double[] m_X; + private double[] m_Y; - /** - * - * @return - */ - public DPointSet getDPointSet() { - DPointSet ret = new DPointSet(100); - ret.setColor(m_Color); - for (int i = 0; i < m_X.length; i++) { + /** + * @param pointset + */ + public PointSet(DPointSet pointset) { + m_Color = pointset.getColor(); + m_X = new double[pointset.getSize()]; + m_Y = new double[pointset.getSize()]; + for (int i = 0; i < pointset.getSize(); i++) { + DPoint point = pointset.getDPoint(i); + m_X[i] = point.x; + m_Y[i] = point.y; + } + } + + /** + * @return + */ + public DPointSet getDPointSet() { + DPointSet ret = new DPointSet(100); + ret.setColor(m_Color); + for (int i = 0; i < m_X.length; i++) { ret.addDPoint(m_X[i], m_Y[i]); } - return ret; - } + return ret; + } - /** - * - * @return - */ - public int getSize() { - return m_X.length; - } + /** + * @return + */ + public int getSize() { + return m_X.length; + } - // /** - // * - // */ - // public DPointSet printPoints() { - // for (int i = 0; i < m_ConnectedPointSet.getSize();i++) { - // DPoint p = m_ConnectedPointSet.getDPoint(i); - // double x = p.x; - // double y = p.y; - // //System.out.println("point "+i+ " x= "+x+"y= "+y); - // } - // return m_ConnectedPointSet.getDPointSet(); - // } + // /** + // * + // */ + // public DPointSet printPoints() { + // for (int i = 0; i < m_ConnectedPointSet.getSize();i++) { + // DPoint p = m_ConnectedPointSet.getDPoint(i); + // double x = p.x; + // double y = p.y; + // //System.out.println("point "+i+ " x= "+x+"y= "+y); + // } + // return m_ConnectedPointSet.getDPointSet(); + // } - } + } - private int colorOffset = 0; - private DArea m_Area; - private int m_CacheIndex = 0; - private int m_CacheSize = 0; - private double[] m_cachex; - private double[] m_cachey; - private Color m_Color; - // private DPointSet m_PointSet_1; - // private DPointSet m_PointSet_2; - // private DPointSet m_PointSet_3; - private DPointSetMultiIcon m_ConnectedPointSet; - private int m_GraphLabel; - private DPointIcon m_Icon; - private String m_InfoString = "Incomplete_Run"; - private boolean m_isStatisticsGraph = false; - private ArrayList m_PointSetContainer = new ArrayList(); + private int colorOffset = 0; + private DArea m_Area; + private int m_CacheIndex = 0; + private int m_CacheSize = 0; + private double[] m_cachex; + private double[] m_cachey; + private Color m_Color; + // private DPointSet m_PointSet_1; + // private DPointSet m_PointSet_2; + // private DPointSet m_PointSet_3; + private DPointSetMultiIcon m_ConnectedPointSet; + private int m_GraphLabel; + private DPointIcon m_Icon; + private String m_InfoString = "Incomplete_Run"; + private boolean m_isStatisticsGraph = false; + private ArrayList m_PointSetContainer = new ArrayList(); - private float m_Stroke = (float) 1.0; + private float m_Stroke = (float) 1.0; - /** - * - */ - public GraphPointSet(/* int size */int GraphLabel, DArea Area) { - // System.out.println("Constructor GraphPointSet "+ GraphLabel); - m_cachex = new double[m_CacheSize]; - m_cachey = new double[m_CacheSize]; - m_Area = Area; - m_GraphLabel = GraphLabel; - m_ConnectedPointSet = new DPointSetMultiIcon(100); - // m_PointSet_1 = new DPointSet(100); - // m_PointSet_2 = new DPointSet(100); - // m_PointSet_3 = new DPointSet(100); - // - // DPointIcon icon1 = new DPointIcon(){ - // public void paint( Graphics g ){ - // g.drawLine(-2, 0, 2, 0); - // g.drawLine(0, 0, 0, 4); - // } - // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } - // }; - // DPointIcon icon2 = new DPointIcon(){ - // public void paint( Graphics g ){ - // g.drawLine(-2, 0, 2, 0); - // g.drawLine(0, 0, 0, -4); - // } - // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } - // }; - // - m_ConnectedPointSet.setStroke(new BasicStroke(m_Stroke)); - m_ConnectedPointSet.setConnected(true); + /** + * + */ + public GraphPointSet(/* int size */int GraphLabel, DArea Area) { + // System.out.println("Constructor GraphPointSet "+ GraphLabel); + m_cachex = new double[m_CacheSize]; + m_cachey = new double[m_CacheSize]; + m_Area = Area; + m_GraphLabel = GraphLabel; + m_ConnectedPointSet = new DPointSetMultiIcon(100); + // m_PointSet_1 = new DPointSet(100); + // m_PointSet_2 = new DPointSet(100); + // m_PointSet_3 = new DPointSet(100); + // + // DPointIcon icon1 = new DPointIcon(){ + // public void paint( Graphics g ){ + // g.drawLine(-2, 0, 2, 0); + // g.drawLine(0, 0, 0, 4); + // } + // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } + // }; + // DPointIcon icon2 = new DPointIcon(){ + // public void paint( Graphics g ){ + // g.drawLine(-2, 0, 2, 0); + // g.drawLine(0, 0, 0, -4); + // } + // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } + // }; + // + m_ConnectedPointSet.setStroke(new BasicStroke(m_Stroke)); + m_ConnectedPointSet.setConnected(true); - setColor(indexToColor(GraphLabel)); - initGraph(Area); - } + setColor(indexToColor(GraphLabel)); + initGraph(Area); + } - /** - * - * @param size - * @param GraphLabel - */ - private GraphPointSet(int size, int GraphLabel) { - m_GraphLabel = GraphLabel; - m_cachex = new double[m_CacheSize]; - m_cachey = new double[m_CacheSize]; - m_ConnectedPointSet = new DPointSetMultiIcon(100); - // m_PointSet_1 = new DPointSet(100); - // m_PointSet_2 = new DPointSet(100); - // m_PointSet_3 = new DPointSet(100); - // - // DPointIcon icon1 = new DPointIcon(){ - // public void paint( Graphics g ){ - // g.drawLine(-2, 0, 2, 0); - // g.drawLine(0, 0, 0, 4); - // } - // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } - // }; - // DPointIcon icon2 = new DPointIcon(){ - // public void paint( Graphics g ){ - // g.drawLine(-2, 0, 2, 0); - // g.drawLine(0, 0, 0, -4); - // } - // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } - // }; - // m_PointSet_2.setIcon(icon1); - // m_PointSet_3.setIcon(icon1); - // - m_ConnectedPointSet.setStroke(new BasicStroke(m_Stroke)); + /** + * @param size + * @param GraphLabel + */ + private GraphPointSet(int size, int GraphLabel) { + m_GraphLabel = GraphLabel; + m_cachex = new double[m_CacheSize]; + m_cachey = new double[m_CacheSize]; + m_ConnectedPointSet = new DPointSetMultiIcon(100); + // m_PointSet_1 = new DPointSet(100); + // m_PointSet_2 = new DPointSet(100); + // m_PointSet_3 = new DPointSet(100); + // + // DPointIcon icon1 = new DPointIcon(){ + // public void paint( Graphics g ){ + // g.drawLine(-2, 0, 2, 0); + // g.drawLine(0, 0, 0, 4); + // } + // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } + // }; + // DPointIcon icon2 = new DPointIcon(){ + // public void paint( Graphics g ){ + // g.drawLine(-2, 0, 2, 0); + // g.drawLine(0, 0, 0, -4); + // } + // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } + // }; + // m_PointSet_2.setIcon(icon1); + // m_PointSet_3.setIcon(icon1); + // + m_ConnectedPointSet.setStroke(new BasicStroke(m_Stroke)); - m_ConnectedPointSet.setConnected(true); - m_Color = Color.black; + m_ConnectedPointSet.setConnected(true); + m_Color = Color.black; - m_Color = indexToColor(GraphLabel); + m_Color = indexToColor(GraphLabel); - m_ConnectedPointSet.setColor(m_Color); + m_ConnectedPointSet.setColor(m_Color); - } + } - /** - * - * @param x - * @param y - */ - public void addDPoint(double x, double y) { - // System.out.println(" "+x+" "+y); - if (m_CacheIndex == m_CacheSize) { - for (int i = 0; i < m_CacheSize; i++) { - m_ConnectedPointSet.addDPoint(m_cachex[i], m_cachey[i]); - } - m_ConnectedPointSet.addDPoint(x, y); - m_CacheIndex = 0; - } else { - m_cachex[m_CacheIndex] = x; - m_cachey[m_CacheIndex] = y; - m_CacheIndex++; - } - } - - /** - * - * @param p - */ - public void addDPoint(DPoint p) { - m_ConnectedPointSet.addDPoint(p); - } - - /** - * Add a graph to another one forming a statistics graph if it isnt one - * already. - * - * @param set - * @param measures - * @param useForce - * forces the add even if point counts mismatch, maybe losing - * some data points - */ - public void addGraph(GraphPointSet set, DMeasures measures, boolean useForce) { - if (set.m_ConnectedPointSet.getSize() != m_ConnectedPointSet.getSize() - && m_ConnectedPointSet.getSize() != 0 && !useForce) { - System.err - .println("WARNING addGraph not possible, lost last graph"); - System.err.println(" m_ConnectedPointSet.getSize() " - + m_ConnectedPointSet.getSize()); - return; - } - if (set.getPointSet().getSize() == 0) { - System.err.println("Refusing to add empty graph..."); - return; - } - m_isStatisticsGraph = true; - removeAllPoints(); - m_ConnectedPointSet.setColor(set.getColor()); - - m_PointSetContainer.add(set.getPointSet()); - int[] index = new int[m_PointSetContainer.size()]; - int[] GraphSize = new int[m_PointSetContainer.size()]; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - GraphSize[i] = ((PointSet) m_PointSetContainer.get(i)).getSize(); - if (GraphSize[i] <= 0) { - System.err.println("Warning: invalid graph size of " - + GraphSize[i] + " at " + i - + "! (GraphPointSet.addGraph)"); - } - } - if (Mathematics.sum(GraphSize) == 0) { - System.err - .println("Error: not adding empty graphs... (GraphPointSet.addGraph)"); - return; - } - boolean allSetsHaveMorePoints = true; - double nextXValue; - double[] y = new double[m_PointSetContainer.size()]; - while (allSetsHaveMorePoints) { // Loop over all point sets, add them up - // and calc. mean - // this is a bit more complicated because it is allowed that the - // point sets are asynchronouos - // in the sense that the x values do not have to match - y values - // for any x value found are averaged - // over all points. However curves may look strange if this happens, - // since they consist of - // heterogenous points. - nextXValue = m_PointSetContainer.get(0).m_X[index[0]]; - // System.out.println("m_PointSetContainer.size()"+m_PointSetContainer.size()); - for (int i = 1; i < m_PointSetContainer.size(); i++) { // search for - // smalles x - // value at - // next - // index - // System.out.println("i="+i); - if (nextXValue > m_PointSetContainer.get(i).m_X[index[i]]) { - nextXValue = m_PointSetContainer.get(i).m_X[index[i]]; - } - } - // Stelle nextXValue wird gezeichnet. jetzt alle y werte dazu finden - int numberofpoints = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { // collect - // all - // points at - // next - // x-value - if (nextXValue == m_PointSetContainer.get(i).m_X[index[i]]) { - y[i] = m_PointSetContainer.get(i).m_Y[index[i]]; - index[i]++; - numberofpoints++; - } else { - y[i] = 0; - } - } - double ymean = Mathematics.sum(y) / numberofpoints; - // compute median double median = getMedian(y); - addDPoint(nextXValue, ymean);// System.out.println("ymean "+ymean+" y.length "+ - // y.length); - // addDPoint(minx,median);// - // System.out.println("ymean "+ymean+" y.length "+ y.length); - for (int i = 0; i < m_PointSetContainer.size(); i++) { // Stop if - // one of - // the point - // sets has - // no more - // points - if (GraphSize[i] <= index[i]) { - allSetsHaveMorePoints = false; - break; - } - } - } - } - - /** - * - * @return - */ - public Color getColor() { - return m_ConnectedPointSet.getColor(); - } - - /** - * - * @return - */ - public DPointSet getConnectedPointSet() { - return m_ConnectedPointSet.getDPointSet(); - } - - /** - * - * @return - */ - public int getGraphLabel() { - return m_GraphLabel; - } - - // /** - // * - // */ - // public void setUnconnectedPoint (double x, double y) { - // m_PointSet_1.addDPoint(x,y); - // } - /** - * - */ - public String getInfoString() { - return m_InfoString; - } - - /** - * - * @param p - * @return - */ - public DPoint getNearestDPoint(DPoint p) { - return m_ConnectedPointSet.getNearestDPoint(p); - } - - /** - * - * @return - */ - public int getPointCount() { - return m_ConnectedPointSet.getSize(); - } - - /** - * - * @return - */ - public PointSet getPointSet() { - return new PointSet(this.m_ConnectedPointSet.getDPointSet()); - } - - /** - * - * @return - */ - public DPointSetMultiIcon getReference2ConnectedPointSet() { - return m_ConnectedPointSet; - } - - /** - * Increase the color sequentially. - */ - public void incColor() { - colorOffset++; - setColor(indexToColor(m_GraphLabel + colorOffset)); - } - - /** - * - * @param index - * @return - */ - private Color indexToColor(int index) { - int k = index % colorSequence.length; - return colorSequence[k]; - } - - /** - * - * @param Area - */ - public void initGraph(DArea Area) { - m_Area = Area; - m_Area.addDElement(m_ConnectedPointSet); - ((FunctionArea) m_Area).addGraphPointSet(this); - // m_Area.addDElement(m_PointSet_1); - // m_Area.addDElement(m_PointSet_2); - // m_Area.addDElement(m_PointSet_3); - // DPointIcon icon1 = new DPointIcon(){ - // public void paint( Graphics g ){ - // g.drawLine(-2, 0, 2, 0); - // g.drawLine(0, 0, 0, 4); - // } - // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } - // }; - // DPointIcon icon2 = new DPointIcon(){ - // public void paint( Graphics g ){ - // g.drawLine(-2, 0, 2, 0); - // g.drawLine(0, 0, 0, -4); - // } - // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } - // }; - } - - /** - * - * @return - */ - public boolean isStatisticsGraph() { - return m_isStatisticsGraph; - } - - /** - * Causes the PointSet to interrupt the connected painting at the current - * position. - */ - public void jump() { - m_ConnectedPointSet.jump(); - } - - /** - * - * @return - */ - public DPointSet printPoints() { - for (int i = 0; i < m_ConnectedPointSet.getSize(); i++) { - DPoint p = m_ConnectedPointSet.getDPoint(i); - double x = p.x; - double y = p.y; - System.out.println("point " + i + " x = " + x + "y = " + y); - } - return m_ConnectedPointSet.getDPointSet(); - } - - /** - * - */ - public void removeAllPoints() { - m_ConnectedPointSet.removeAllPoints(); - // m_PointSet_1.removeAllPoints(); - // m_PointSet_2.removeAllPoints(); - // m_PointSet_3.removeAllPoints(); - } - - /** - * - * @param x - */ - public void removePoint(DPoint x) { - System.out.println("removePoint " + x.x + " " + x.y); - DPoint[] buf = new DPoint[m_ConnectedPointSet.getSize()]; - for (int i = 0; i < m_ConnectedPointSet.getSize(); i++) { - buf[i] = m_ConnectedPointSet.getDPoint(i); - } - m_ConnectedPointSet.removeAllPoints(); - for (int i = 0; i < buf.length; i++) { - if (buf[i].x == x.x && buf[i].y == x.y) { - System.out.println("point found"); - } - else { - m_ConnectedPointSet.addDPoint(buf[i]); - } - - } - } - - /** - * - * @param c - */ - public void setColor(Color c) { - m_Color = c; - m_ConnectedPointSet.setColor(m_Color); - } - - public void setColorByIndex(int i) { - setColor(indexToColor(i)); - } - - /** - * - * @param p - */ - public void setConnectedMode(boolean p) { - m_ConnectedPointSet.setConnected(p); - } - - /** - * - * @param p - */ - public void setIcon(DPointIcon p) { - this.m_Icon = p; - this.m_ConnectedPointSet.setIcon(p); - } - - /** - * - * @param x - * @param stroke - */ - public void setInfoString(String x, float stroke) { - m_InfoString = x; - m_Stroke = stroke; - // setStroke(new BasicStroke( m_Stroke )); - } - - /** - * Sets the info string without changing the stroke. - * - * @param x - */ - public void setInfoString(String x) { - m_InfoString = x; - } - - /** - * Retrieve the median point of this point set. - * - * @return the median point of this point set or null if it is empty - */ - public DPoint getMedPoint() { - if (m_ConnectedPointSet==null) { - return null; + /** + * @param x + * @param y + */ + public void addDPoint(double x, double y) { + // System.out.println(" "+x+" "+y); + if (m_CacheIndex == m_CacheSize) { + for (int i = 0; i < m_CacheSize; i++) { + m_ConnectedPointSet.addDPoint(m_cachex[i], m_cachey[i]); } - int medX = m_ConnectedPointSet.getSize()/2; - return m_ConnectedPointSet.getDPoint(medX); - } + m_ConnectedPointSet.addDPoint(x, y); + m_CacheIndex = 0; + } else { + m_cachex[m_CacheIndex] = x; + m_cachey[m_CacheIndex] = y; + m_CacheIndex++; + } + } + + /** + * @param p + */ + public void addDPoint(DPoint p) { + m_ConnectedPointSet.addDPoint(p); + } + + /** + * Add a graph to another one forming a statistics graph if it isnt one + * already. + * + * @param set + * @param measures + * @param useForce forces the add even if point counts mismatch, maybe losing + * some data points + */ + public void addGraph(GraphPointSet set, DMeasures measures, boolean useForce) { + if (set.m_ConnectedPointSet.getSize() != m_ConnectedPointSet.getSize() + && m_ConnectedPointSet.getSize() != 0 && !useForce) { + System.err + .println("WARNING addGraph not possible, lost last graph"); + System.err.println(" m_ConnectedPointSet.getSize() " + + m_ConnectedPointSet.getSize()); + return; + } + if (set.getPointSet().getSize() == 0) { + System.err.println("Refusing to add empty graph..."); + return; + } + m_isStatisticsGraph = true; + removeAllPoints(); + m_ConnectedPointSet.setColor(set.getColor()); + + m_PointSetContainer.add(set.getPointSet()); + int[] index = new int[m_PointSetContainer.size()]; + int[] GraphSize = new int[m_PointSetContainer.size()]; + for (int i = 0; i < m_PointSetContainer.size(); i++) { + GraphSize[i] = ((PointSet) m_PointSetContainer.get(i)).getSize(); + if (GraphSize[i] <= 0) { + System.err.println("Warning: invalid graph size of " + + GraphSize[i] + " at " + i + + "! (GraphPointSet.addGraph)"); + } + } + if (Mathematics.sum(GraphSize) == 0) { + System.err + .println("Error: not adding empty graphs... (GraphPointSet.addGraph)"); + return; + } + boolean allSetsHaveMorePoints = true; + double nextXValue; + double[] y = new double[m_PointSetContainer.size()]; + while (allSetsHaveMorePoints) { // Loop over all point sets, add them up + // and calc. mean + // this is a bit more complicated because it is allowed that the + // point sets are asynchronouos + // in the sense that the x values do not have to match - y values + // for any x value found are averaged + // over all points. However curves may look strange if this happens, + // since they consist of + // heterogenous points. + nextXValue = m_PointSetContainer.get(0).m_X[index[0]]; + // System.out.println("m_PointSetContainer.size()"+m_PointSetContainer.size()); + for (int i = 1; i < m_PointSetContainer.size(); i++) { // search for + // smalles x + // value at + // next + // index + // System.out.println("i="+i); + if (nextXValue > m_PointSetContainer.get(i).m_X[index[i]]) { + nextXValue = m_PointSetContainer.get(i).m_X[index[i]]; + } + } + // Stelle nextXValue wird gezeichnet. jetzt alle y werte dazu finden + int numberofpoints = 0; + for (int i = 0; i < m_PointSetContainer.size(); i++) { // collect + // all + // points at + // next + // x-value + if (nextXValue == m_PointSetContainer.get(i).m_X[index[i]]) { + y[i] = m_PointSetContainer.get(i).m_Y[index[i]]; + index[i]++; + numberofpoints++; + } else { + y[i] = 0; + } + } + double ymean = Mathematics.sum(y) / numberofpoints; + // compute median double median = getMedian(y); + addDPoint(nextXValue, ymean);// System.out.println("ymean "+ymean+" y.length "+ + // y.length); + // addDPoint(minx,median);// + // System.out.println("ymean "+ymean+" y.length "+ y.length); + for (int i = 0; i < m_PointSetContainer.size(); i++) { // Stop if + // one of + // the point + // sets has + // no more + // points + if (GraphSize[i] <= index[i]) { + allSetsHaveMorePoints = false; + break; + } + } + } + } + + /** + * @return + */ + public Color getColor() { + return m_ConnectedPointSet.getColor(); + } + + /** + * @return + */ + public DPointSet getConnectedPointSet() { + return m_ConnectedPointSet.getDPointSet(); + } + + /** + * @return + */ + public int getGraphLabel() { + return m_GraphLabel; + } + + // /** + // * + // */ + // public void setUnconnectedPoint (double x, double y) { + // m_PointSet_1.addDPoint(x,y); + // } + + /** + * + */ + public String getInfoString() { + return m_InfoString; + } + + /** + * @param p + * @return + */ + public DPoint getNearestDPoint(DPoint p) { + return m_ConnectedPointSet.getNearestDPoint(p); + } + + /** + * @return + */ + public int getPointCount() { + return m_ConnectedPointSet.getSize(); + } + + /** + * @return + */ + public PointSet getPointSet() { + return new PointSet(this.m_ConnectedPointSet.getDPointSet()); + } + + /** + * @return + */ + public DPointSetMultiIcon getReference2ConnectedPointSet() { + return m_ConnectedPointSet; + } + + /** + * Increase the color sequentially. + */ + public void incColor() { + colorOffset++; + setColor(indexToColor(m_GraphLabel + colorOffset)); + } + + /** + * @param index + * @return + */ + private Color indexToColor(int index) { + int k = index % colorSequence.length; + return colorSequence[k]; + } + + /** + * @param Area + */ + public void initGraph(DArea Area) { + m_Area = Area; + m_Area.addDElement(m_ConnectedPointSet); + ((FunctionArea) m_Area).addGraphPointSet(this); + // m_Area.addDElement(m_PointSet_1); + // m_Area.addDElement(m_PointSet_2); + // m_Area.addDElement(m_PointSet_3); + // DPointIcon icon1 = new DPointIcon(){ + // public void paint( Graphics g ){ + // g.drawLine(-2, 0, 2, 0); + // g.drawLine(0, 0, 0, 4); + // } + // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } + // }; + // DPointIcon icon2 = new DPointIcon(){ + // public void paint( Graphics g ){ + // g.drawLine(-2, 0, 2, 0); + // g.drawLine(0, 0, 0, -4); + // } + // public DBorder getDBorder(){ return new DBorder(4, 4, 4, 4); } + // }; + } + + /** + * @return + */ + public boolean isStatisticsGraph() { + return m_isStatisticsGraph; + } + + /** + * Causes the PointSet to interrupt the connected painting at the current + * position. + */ + public void jump() { + m_ConnectedPointSet.jump(); + } + + /** + * @return + */ + public DPointSet printPoints() { + for (int i = 0; i < m_ConnectedPointSet.getSize(); i++) { + DPoint p = m_ConnectedPointSet.getDPoint(i); + double x = p.x; + double y = p.y; + System.out.println("point " + i + " x = " + x + "y = " + y); + } + return m_ConnectedPointSet.getDPointSet(); + } + + /** + * + */ + public void removeAllPoints() { + m_ConnectedPointSet.removeAllPoints(); + // m_PointSet_1.removeAllPoints(); + // m_PointSet_2.removeAllPoints(); + // m_PointSet_3.removeAllPoints(); + } + + /** + * @param x + */ + public void removePoint(DPoint x) { + System.out.println("removePoint " + x.x + " " + x.y); + DPoint[] buf = new DPoint[m_ConnectedPointSet.getSize()]; + for (int i = 0; i < m_ConnectedPointSet.getSize(); i++) { + buf[i] = m_ConnectedPointSet.getDPoint(i); + } + m_ConnectedPointSet.removeAllPoints(); + for (int i = 0; i < buf.length; i++) { + if (buf[i].x == x.x && buf[i].y == x.y) { + System.out.println("point found"); + } else { + m_ConnectedPointSet.addDPoint(buf[i]); + } + + } + } + + /** + * @param c + */ + public void setColor(Color c) { + m_Color = c; + m_ConnectedPointSet.setColor(m_Color); + } + + public void setColorByIndex(int i) { + setColor(indexToColor(i)); + } + + /** + * @param p + */ + public void setConnectedMode(boolean p) { + m_ConnectedPointSet.setConnected(p); + } + + /** + * @param p + */ + public void setIcon(DPointIcon p) { + this.m_Icon = p; + this.m_ConnectedPointSet.setIcon(p); + } + + /** + * @param x + * @param stroke + */ + public void setInfoString(String x, float stroke) { + m_InfoString = x; + m_Stroke = stroke; + // setStroke(new BasicStroke( m_Stroke )); + } + + /** + * Sets the info string without changing the stroke. + * + * @param x + */ + public void setInfoString(String x) { + m_InfoString = x; + } + + /** + * Retrieve the median point of this point set. + * + * @return the median point of this point set or null if it is empty + */ + public DPoint getMedPoint() { + if (m_ConnectedPointSet == null) { + return null; + } + int medX = m_ConnectedPointSet.getSize() / 2; + return m_ConnectedPointSet.getDPoint(medX); + } } diff --git a/src/eva2/gui/plot/GraphPointSetLegend.java b/src/eva2/gui/plot/GraphPointSetLegend.java index 796ceff0..16f9c99e 100644 --- a/src/eva2/gui/plot/GraphPointSetLegend.java +++ b/src/eva2/gui/plot/GraphPointSetLegend.java @@ -3,6 +3,7 @@ package eva2.gui.plot; import eva2.tools.Pair; import eva2.tools.StringTools; import eva2.tools.chart2d.SlimRect; + import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; @@ -22,180 +23,172 @@ import javax.swing.JPanel; * A class representing the legend of a plot. It is created from a list of * GraphPointSets as used in FunctionArea. Painting is done in FunctionArea. As * an alternative, an own frame could be created. - * + * * @author mkron, draeger - * */ public class GraphPointSetLegend { - SortedSet> legendEntries; + SortedSet> legendEntries; - /** - * - * @author draeger - * - */ - private static class PairComp implements Comparator> { + /** + * @author draeger + */ + private static class PairComp implements Comparator> { - /* - * (non-Javadoc) - * - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ @Override - public int compare(Pair o1, Pair o2) { - int comp = o1.car().compareTo(o2.car()); - // Same text; let us see if the color is also identical. - return comp == 0 ? comp = Integer.valueOf(o1.cdr().getRGB()) - .compareTo(Integer.valueOf(o2.cdr().getRGB())) : comp; - } + public int compare(Pair o1, Pair o2) { + int comp = o1.car().compareTo(o2.car()); + // Same text; let us see if the color is also identical. + return comp == 0 ? comp = Integer.valueOf(o1.cdr().getRGB()) + .compareTo(Integer.valueOf(o2.cdr().getRGB())) : comp; + } - } + } - private static final PairComp comparator = new PairComp(); + private static final PairComp comparator = new PairComp(); - /** - * A constructor which may enumerate the point sets. - * - * @param pointSetContainer the set of point sets to be shown. - * @param appendIndex if true, the string entries are enumerated according to the index - */ - public GraphPointSetLegend(List pointSetContainer, boolean appendIndex) { - legendEntries = new TreeSet>(comparator); - for (int i = 0; i < pointSetContainer.size(); i++) { - GraphPointSet pointset = pointSetContainer.get(i); - if (pointset.getPointSet().getSize()>0) { - String entryStr; - if (appendIndex) { - entryStr = StringTools.expandPrefixZeros(i, pointSetContainer.size()-1) + ": " + pointset.getInfoString(); - } - else { - entryStr = pointset.getInfoString(); - } - legendEntries.add(new Pair(entryStr,pointset.getColor())); - } - } - } + /** + * A constructor which may enumerate the point sets. + * + * @param pointSetContainer the set of point sets to be shown. + * @param appendIndex if true, the string entries are enumerated according to the index + */ + public GraphPointSetLegend(List pointSetContainer, boolean appendIndex) { + legendEntries = new TreeSet>(comparator); + for (int i = 0; i < pointSetContainer.size(); i++) { + GraphPointSet pointset = pointSetContainer.get(i); + if (pointset.getPointSet().getSize() > 0) { + String entryStr; + if (appendIndex) { + entryStr = StringTools.expandPrefixZeros(i, pointSetContainer.size() - 1) + ": " + pointset.getInfoString(); + } else { + entryStr = pointset.getInfoString(); + } + legendEntries.add(new Pair(entryStr, pointset.getColor())); + } + } + } - /** - * A constructor without enumeration. - * - * @param pointSetContainer the set of point sets to be shown. - */ - public GraphPointSetLegend(List pointSetContainer) { - this(pointSetContainer, false); - } + /** + * A constructor without enumeration. + * + * @param pointSetContainer the set of point sets to be shown. + */ + public GraphPointSetLegend(List pointSetContainer) { + this(pointSetContainer, false); + } - /** - * Add the legend labels to a container. - * - * @param comp - */ - public void addToContainer(JComponent comp) { - for (Pair legendEntry : legendEntries) { - JLabel label = new JLabel(legendEntry.head); - label.setForeground(legendEntry.tail); - comp.add(label); - } - } + /** + * Add the legend labels to a container. + * + * @param comp + */ + public void addToContainer(JComponent comp) { + for (Pair legendEntry : legendEntries) { + JLabel label = new JLabel(legendEntry.head); + label.setForeground(legendEntry.tail); + comp.add(label); + } + } - /** - * - * @param bgCol - * @param pointSetContainer - * @return - */ - public static JPanel makeLegendPanel(Color bgCol, - ArrayList pointSetContainer) { - JPanel pan = new JPanel(); - pan.setBackground(bgCol); - pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS)); - GraphPointSetLegend lBox = new GraphPointSetLegend(pointSetContainer); - lBox.addToContainer(pan); - return pan; - } + /** + * @param bgCol + * @param pointSetContainer + * @return + */ + public static JPanel makeLegendPanel(Color bgCol, + ArrayList pointSetContainer) { + JPanel pan = new JPanel(); + pan.setBackground(bgCol); + pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS)); + GraphPointSetLegend lBox = new GraphPointSetLegend(pointSetContainer); + lBox.addToContainer(pan); + return pan; + } - /** - * - * @param bgCol - * @param pointSetContainer - * @return - */ - public static JFrame makeLegendFrame(Color bgCol, - ArrayList pointSetContainer) { - JFrame frame = new JFrame("Legend"); - // LegendBox lBox = new LegendBox(bgCol, pointSetContainer); - frame.add(makeLegendPanel(bgCol, pointSetContainer)); - frame.pack(); - frame.setVisible(true); - return frame; - } + /** + * @param bgCol + * @param pointSetContainer + * @return + */ + public static JFrame makeLegendFrame(Color bgCol, + ArrayList pointSetContainer) { + JFrame frame = new JFrame("Legend"); + // LegendBox lBox = new LegendBox(bgCol, pointSetContainer); + frame.add(makeLegendPanel(bgCol, pointSetContainer)); + frame.pack(); + frame.setVisible(true); + return frame; + } - /** - * - * @param component - */ - public void paintIn(JComponent component) { - Graphics g = component.getGraphics(); - FontMetrics fm = g.getFontMetrics(); - int yOffs = 5 + fm.getHeight(); - int xOffs = 0; - Color origCol = g.getColor(); + /** + * @param component + */ + public void paintIn(JComponent component) { + Graphics g = component.getGraphics(); + FontMetrics fm = g.getFontMetrics(); + int yOffs = 5 + fm.getHeight(); + int xOffs = 0; + Color origCol = g.getColor(); - for (Pair legendEntry : legendEntries) { - g.setColor(legendEntry.tail); - Rectangle2D rect = fm.getStringBounds(legendEntry.head, g); - xOffs = (int) (component.getWidth() - rect.getWidth() - 5); - g.drawString(legendEntry.head, xOffs, yOffs); - yOffs += (5 + rect.getHeight()); - } - g.setColor(origCol); - } + for (Pair legendEntry : legendEntries) { + g.setColor(legendEntry.tail); + Rectangle2D rect = fm.getStringBounds(legendEntry.head, g); + xOffs = (int) (component.getWidth() - rect.getWidth() - 5); + g.drawString(legendEntry.head, xOffs, yOffs); + yOffs += (5 + rect.getHeight()); + } + g.setColor(origCol); + } - // public void paintIn(Graphics g, Dimension dim) { - // paintIn(g, dim.width); - // } - // - // public void paintIn(Graphics g, Rectangle rect) { - // paintIn(g, rect.width); - // } - // - // public void paintIn(Graphics g, DRectangle rect) { - // paintIn(g, (int)rect.width); - // } + // public void paintIn(Graphics g, Dimension dim) { + // paintIn(g, dim.width); + // } + // + // public void paintIn(Graphics g, Rectangle rect) { + // paintIn(g, rect.width); + // } + // + // public void paintIn(Graphics g, DRectangle rect) { + // paintIn(g, (int)rect.width); + // } - /** - * - */ - public void paintIn(Graphics g, SlimRect rect) { - paintIn(g, (int) rect.getX(), (int) rect.getY(), (int) rect.getX() - + (int) rect.getWidth()); - } + /** + * + */ + public void paintIn(Graphics g, SlimRect rect) { + paintIn(g, (int) rect.getX(), (int) rect.getY(), (int) rect.getX() + + (int) rect.getWidth()); + } - /** - * - * @param g - * @param x - * @param y - * @param maxX - */ - private void paintIn(Graphics g, int x, int y, int maxX) { - FontMetrics fm = g.getFontMetrics(); - // System.out.println("In LegendBox.paintIn!"); - int yOffs = 5 + y + fm.getHeight(); - int xOffs = x; - Color origCol = g.getColor(); - // avoid that an entry with identical label and color occurs multiple - // times. - for (Pair legendEntry : legendEntries) { - // System.out.println(legendEntries[i].toString() + "\tcontaines: " - // + set.contains(legendEntries[i])); - g.setColor(legendEntry.tail); - Rectangle2D stringBounds = fm.getStringBounds(legendEntry.head, g); - xOffs = (int) (maxX - stringBounds.getWidth() - 5); - g.drawString(legendEntry.head, xOffs, yOffs); - // g.drawString(legendEntries[i].head, 80, 80); - yOffs += (5 + stringBounds.getHeight()); - } - g.setColor(origCol); - } + /** + * @param g + * @param x + * @param y + * @param maxX + */ + private void paintIn(Graphics g, int x, int y, int maxX) { + FontMetrics fm = g.getFontMetrics(); + // System.out.println("In LegendBox.paintIn!"); + int yOffs = 5 + y + fm.getHeight(); + int xOffs = x; + Color origCol = g.getColor(); + // avoid that an entry with identical label and color occurs multiple + // times. + for (Pair legendEntry : legendEntries) { + // System.out.println(legendEntries[i].toString() + "\tcontaines: " + // + set.contains(legendEntries[i])); + g.setColor(legendEntry.tail); + Rectangle2D stringBounds = fm.getStringBounds(legendEntry.head, g); + xOffs = (int) (maxX - stringBounds.getWidth() - 5); + g.drawString(legendEntry.head, xOffs, yOffs); + // g.drawString(legendEntries[i].head, 80, 80); + yOffs += (5 + stringBounds.getHeight()); + } + g.setColor(origCol); + } } diff --git a/src/eva2/gui/plot/GraphWindow.java b/src/eva2/gui/plot/GraphWindow.java index 1af6e6cc..1b1e3973 100644 --- a/src/eva2/gui/plot/GraphWindow.java +++ b/src/eva2/gui/plot/GraphWindow.java @@ -23,7 +23,7 @@ public class GraphWindow { * */ public static GraphWindow getInstance(String graphWindowName, - String strx, String stry) { + String strx, String stry) { if (plotContainer == null) { plotContainer = new PlotContainer(); } diff --git a/src/eva2/gui/plot/InterfaceDPointWithContent.java b/src/eva2/gui/plot/InterfaceDPointWithContent.java index 0746f0ca..67fdf246 100644 --- a/src/eva2/gui/plot/InterfaceDPointWithContent.java +++ b/src/eva2/gui/plot/InterfaceDPointWithContent.java @@ -12,15 +12,20 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; */ public interface InterfaceDPointWithContent { public void setEAIndividual(AbstractEAIndividual indy); + public AbstractEAIndividual getEAIndividual(); - /** This method allows you to set the according optimization problem - * @param problem InterfaceOptimizationProblem + /** + * This method allows you to set the according optimization problem + * + * @param problem InterfaceOptimizationProblem */ public void setProblem(InterfaceOptimizationProblem problem); + public InterfaceOptimizationProblem getProblem(); - /** This method allows you to draw additional data of the individual + /** + * This method allows you to draw additional data of the individual */ public void showIndividual(); } diff --git a/src/eva2/gui/plot/Plot.java b/src/eva2/gui/plot/Plot.java index 0bba858e..b18294d0 100644 --- a/src/eva2/gui/plot/Plot.java +++ b/src/eva2/gui/plot/Plot.java @@ -6,12 +6,14 @@ package eva2.gui.plot; * Hannes Planatscher @version: $Revision: 322 $ $Date: 2007-12-11 17:24:07 * +0100 (Tue, 11 Dec 2007) $ $Author: mkron $ */ + import eva2.EvAInfo; import eva2.gui.JEFrame; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.BasicResourceLoader; import eva2.tools.chart2d.DPointSet; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -260,7 +262,7 @@ public class Plot implements PlotInterface, Serializable { * Toggle whether the graphs should be annotated by tool tip info strings. * * @param doShowGraphToolTips true if the graphs should be annotated by tool - * tip info strings + * tip info strings */ public void setShowGraphToolTips(boolean doShowGraphToolTips) { m_PlotArea.setShowGraphToolTips(doShowGraphToolTips); @@ -455,7 +457,7 @@ public class Plot implements PlotInterface, Serializable { } catch (IOException ex) { JOptionPane.showMessageDialog(m_Frame, "Couldn't write to file: " + sFile.getName() + "\n" - + ex.getMessage(), "Save object", + + ex.getMessage(), "Save object", JOptionPane.ERROR_MESSAGE); } } diff --git a/src/eva2/gui/plot/PlotInterface.java b/src/eva2/gui/plot/PlotInterface.java index 2ba7980e..3a8d9196 100644 --- a/src/eva2/gui/plot/PlotInterface.java +++ b/src/eva2/gui/plot/PlotInterface.java @@ -1,4 +1,5 @@ package eva2.gui.plot; + /* * Title: EvA2 * Description: @@ -13,25 +14,34 @@ package eva2.gui.plot; * IMPORTS *==========================================================================*/ public interface PlotInterface { - public void setConnectedPoint (double x,double y,int GraphLabel); - - /** - * Add two graphs to form an average graph - * - * @param g1 graph object one - * @param g2 graph object two - * @param forceAdd if the graph mismatch in point counts, try to add them anyway in a useful manner. - */ - public void addGraph (int g1,int g2, boolean forceAdd); - public void setUnconnectedPoint (double x, double y,int GraphLabel); - public void clearAll (); - public void clearGraph (int GraphNumber); - public void setInfoString (int GraphLabel, String Info, float stroke); - public void jump (); - public String getName(); - public int getPointCount(int graphLabel); -// public FunctionArea getFunctionArea(); // this is bad for RMI - public boolean isValid(); - public void init(); + public void setConnectedPoint(double x, double y, int GraphLabel); + + /** + * Add two graphs to form an average graph + * + * @param g1 graph object one + * @param g2 graph object two + * @param forceAdd if the graph mismatch in point counts, try to add them anyway in a useful manner. + */ + public void addGraph(int g1, int g2, boolean forceAdd); + + public void setUnconnectedPoint(double x, double y, int GraphLabel); + + public void clearAll(); + + public void clearGraph(int GraphNumber); + + public void setInfoString(int GraphLabel, String Info, float stroke); + + public void jump(); + + public String getName(); + + public int getPointCount(int graphLabel); + + // public FunctionArea getFunctionArea(); // this is bad for RMI + public boolean isValid(); + + public void init(); } diff --git a/src/eva2/gui/plot/TopoPlot.java b/src/eva2/gui/plot/TopoPlot.java index fcbf254c..a3cc7e1a 100644 --- a/src/eva2/gui/plot/TopoPlot.java +++ b/src/eva2/gui/plot/TopoPlot.java @@ -12,11 +12,13 @@ package eva2.gui.plot; /*==========================================================================* * IMPORTS *==========================================================================*/ + import eva2.optimization.problems.Interface2DBorderProblem; import eva2.optimization.problems.InterfaceFirstOrderDerivableProblem; import eva2.tools.chart2d.DRectangle; import eva2.tools.diagram.ColorBarCalculator; import eva2.tools.math.Mathematics; + import java.awt.Color; import javax.swing.JPanel; @@ -24,52 +26,55 @@ import javax.swing.JPanel; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ + /** * */ public class TopoPlot extends Plot { - Interface2DBorderProblem prob=null; - double[][] range=null; - boolean withGrads=false; - private int gridx = 50; - private int gridy = 50; - int colorScale = ColorBarCalculator.BLUE_TO_RED; + Interface2DBorderProblem prob = null; + double[][] range = null; + boolean withGrads = false; + private int gridx = 50; + private int gridy = 50; + int colorScale = ColorBarCalculator.BLUE_TO_RED; - /** - * - */ - public TopoPlot(String PlotName,String xname,String yname) { - super(PlotName, xname, yname, true); - //if (TRACE) System.out.println("Constructor TopoPlot "+PlotName); - } - public TopoPlot(String PlotName,String xname,String yname,double[] a, double[] b) { - super(PlotName, xname, yname, a, b); - //if (TRACE) System.out.println("Constructor TopoPlot "+PlotName); - } - /** - * Defines parameters used for drawing the topology. - * @param gridX the x-resolution of the topology, higher value means higher resolution - * @param gridY the y-resolution of the topology, higher value means higher resolution - * @param color_scale the topologies color coding. Values (0-3) are valid. @See ColorBarCalculator. - */ - public void setParams(int gridX, int gridY, int color_scale) { - if (gridX>m_Frame.getWidth()) { - gridX = m_Frame.getWidth(); - } - if (gridY>m_Frame.getHeight()) { - gridY = m_Frame.getHeight(); - } - gridx = gridX; - gridy = gridY; - colorScale = color_scale; - } + /** + * + */ + public TopoPlot(String PlotName, String xname, String yname) { + super(PlotName, xname, yname, true); + //if (TRACE) System.out.println("Constructor TopoPlot "+PlotName); + } - - - @Override - protected void installButtons(JPanel buttonPan) { - super.installButtons(buttonPan); - // TODO this actually works, but it is horribly slow + public TopoPlot(String PlotName, String xname, String yname, double[] a, double[] b) { + super(PlotName, xname, yname, a, b); + //if (TRACE) System.out.println("Constructor TopoPlot "+PlotName); + } + + /** + * Defines parameters used for drawing the topology. + * + * @param gridX the x-resolution of the topology, higher value means higher resolution + * @param gridY the y-resolution of the topology, higher value means higher resolution + * @param color_scale the topologies color coding. Values (0-3) are valid. @See ColorBarCalculator. + */ + public void setParams(int gridX, int gridY, int color_scale) { + if (gridX > m_Frame.getWidth()) { + gridX = m_Frame.getWidth(); + } + if (gridY > m_Frame.getHeight()) { + gridY = m_Frame.getHeight(); + } + gridx = gridX; + gridy = gridY; + colorScale = color_scale; + } + + + @Override + protected void installButtons(JPanel buttonPan) { + super.installButtons(buttonPan); + // TODO this actually works, but it is horribly slow // JButton refineButton = new JButton ("Refine"); // refineButton.setToolTipText("Refine the graph resolution"); // refineButton.addActionListener(new ActionListener() { @@ -80,90 +85,93 @@ public class TopoPlot extends Plot { // } // }); // buttonPan.add(refineButton); - } -/** - * Defines parameters used for drawing the topology. - * @param gridX the x-resolution of the topology, higher value means higher resolution - * @param gridY the y-resolution of the topology, higher value means higher resolution - */ - public void setParams(int gridX, int gridY) { - setParams(gridX, gridY, colorScale); - } - - /** - * Defines the topology (by setting a specific problem) and draws the topology - */ - public void setTopology(Interface2DBorderProblem problem) { - setTopology(problem, problem.get2DBorder(), false); - } - /** - * Defines the topology (by setting a specific problem) and draws the topology - */ - public void setTopology(Interface2DBorderProblem problem, double[][] border, boolean withGradientsIfAvailable) { - prob=problem; - range=border; - withGrads=withGradientsIfAvailable; - double[] sizeXY=Mathematics.getAbsRange(border); - double deltaX = sizeXY[0]/gridx; - double deltaY = sizeXY[1]/gridy; - double maxDeriv=0; - double[] pos = new double[2]; - boolean TRACEMETH=false; - //double fitRange = java.lang.Math.abs(problem.getMinFitness()-problem.getMaxFitness() ); - double fitRange = 0, max = -Double.MAX_VALUE, min = Double.MAX_VALUE, tmp; - for (int x=0; x max) { - max = tmp; - } - if (withGradientsIfAvailable && (problem instanceof InterfaceFirstOrderDerivableProblem)) { - double[] deriv = ((InterfaceFirstOrderDerivableProblem)problem).getFirstOrderGradients(problem.project2DPoint(pos)); - for (int i=0; i<2;i++) { - maxDeriv=Math.max(maxDeriv, Math.abs(deriv[i])); - } // maximum deriv of first 2 dims - } - - } // for y - } // for x - fitRange = java.lang.Math.abs(max - min); - ColorBarCalculator colorBar = new ColorBarCalculator(colorScale); - - m_Frame.setVisible(false); - for (int x=0; x max) { + max = tmp; + } + if (withGradientsIfAvailable && (problem instanceof InterfaceFirstOrderDerivableProblem)) { + double[] deriv = ((InterfaceFirstOrderDerivableProblem) problem).getFirstOrderGradients(problem.project2DPoint(pos)); + for (int i = 0; i < 2; i++) { + maxDeriv = Math.max(maxDeriv, Math.abs(deriv[i])); + } // maximum deriv of first 2 dims + } + + } // for y + } // for x + fitRange = java.lang.Math.abs(max - min); + ColorBarCalculator colorBar = new ColorBarCalculator(colorScale); + + m_Frame.setVisible(false); + for (int x = 0; x < gridx; x++) { + for (int y = 0; y < gridy; y++) { + pos[0] = border[0][0] + x * deltaX; + pos[1] = border[1][0] + y * deltaY; + DRectangle rect = new DRectangle(pos[0] - (deltaX / 2), pos[1] - (deltaY / 2), deltaX, deltaY); + Color color = new Color(colorBar.getRGB((float) ((problem.functionValue(pos) - min) / fitRange))); + // Color color = new Color(255,(int)(problem.doEvaluation(pos)[0]/fitRange*255),(int)(problem.doEvaluation(pos)[0]/fitRange*255)); + // Color color = new Color(colorBar.getRGB((float)(problem.functionValue(pos)/fitRange))); // Color color = new Color(255,(int)(problem.doEvaluation(pos)[0]/fitRange*255),(int)(problem.doEvaluation(pos)[0]/fitRange*255)); + rect.setColor(color); + rect.setFillColor(color); + m_PlotArea.addDElement(rect); + } // for y + } // for x + if (withGradientsIfAvailable && (problem instanceof InterfaceFirstOrderDerivableProblem)) { + for (int x = 0; x < gridx; x++) { + for (int y = 0; y < gridy; y++) { + pos[0] = border[0][0] + x * deltaX; + pos[1] = border[1][0] + y * deltaY; + double[] derivPos = ((InterfaceFirstOrderDerivableProblem) problem).getFirstOrderGradients(problem.project2DPoint(pos)); + Mathematics.svDiv(1.1 * (2 * maxDeriv / Math.max(deltaX, deltaY)), derivPos, derivPos); + Mathematics.vvAdd(pos, derivPos, derivPos); + getFunctionArea().drawLine(pos, derivPos); + getFunctionArea().drawIcon(1, "", derivPos, 0); + } // for y + } // for x + } + m_Frame.setVisible(true); + } // setTopology } // class diff --git a/src/eva2/gui/utils/CustomTabbedPaneUI.java b/src/eva2/gui/utils/CustomTabbedPaneUI.java index 0342170a..c3e66f93 100644 --- a/src/eva2/gui/utils/CustomTabbedPaneUI.java +++ b/src/eva2/gui/utils/CustomTabbedPaneUI.java @@ -96,13 +96,13 @@ public class CustomTabbedPaneUI extends BasicTabbedPaneUI { @Override protected int calculateTabHeight(int tabPlacement, int tabIndex, - int fontHeight) { + int fontHeight) { return 21; } @Override protected int calculateTabWidth(int tabPlacement, int tabIndex, - FontMetrics metrics) { + FontMetrics metrics) { int w = super.calculateTabWidth(tabPlacement, tabIndex, metrics); int wid = metrics.charWidth('M'); w += wid * 2; @@ -134,7 +134,7 @@ public class CustomTabbedPaneUI extends BasicTabbedPaneUI { @Override protected void paintTabBackground(Graphics g, int tabPlacement, - int tabIndex, int x, int y, int w, int h, boolean isSelected) { + int tabIndex, int x, int y, int w, int h, boolean isSelected) { Graphics2D g2d = (Graphics2D) g; ColorSet colorSet; @@ -174,7 +174,7 @@ public class CustomTabbedPaneUI extends BasicTabbedPaneUI { @Override protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, - int x, int y, int w, int h, boolean isSelected) { + int x, int y, int w, int h, boolean isSelected) { Rectangle rect = getTabBounds(tabIndex, new Rectangle(x, y, w, h)); g.setColor(dividerColor); g.drawLine(rect.x + rect.width, 0, rect.x + rect.width, 20); @@ -182,37 +182,37 @@ public class CustomTabbedPaneUI extends BasicTabbedPaneUI { @Override protected void paintContentBorderTopEdge(Graphics g, int tabPlacement, - int selectedIndex, int x, int y, int w, int h) { + int selectedIndex, int x, int y, int w, int h) { } @Override protected void paintContentBorderRightEdge(Graphics g, int tabPlacement, - int selectedIndex, int x, int y, int w, int h) { + int selectedIndex, int x, int y, int w, int h) { // Do nothing } @Override protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement, - int selectedIndex, int x, int y, int w, int h) { + int selectedIndex, int x, int y, int w, int h) { // Do nothing } @Override protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement, - int selectedIndex, int x, int y, int w, int h) { + int selectedIndex, int x, int y, int w, int h) { // Do nothing } @Override protected void paintFocusIndicator(Graphics g, int tabPlacement, - Rectangle[] rects, int tabIndex, Rectangle iconRect, - Rectangle textRect, boolean isSelected) { + Rectangle[] rects, int tabIndex, Rectangle iconRect, + Rectangle textRect, boolean isSelected) { // Do nothing } @Override protected int getTabLabelShiftY(int tabPlacement, int tabIndex, - boolean isSelected) { + boolean isSelected) { return 0; } diff --git a/src/eva2/gui/utils/VerticalButtonUI.java b/src/eva2/gui/utils/VerticalButtonUI.java index ece31348..385ce527 100644 --- a/src/eva2/gui/utils/VerticalButtonUI.java +++ b/src/eva2/gui/utils/VerticalButtonUI.java @@ -8,79 +8,78 @@ import javax.swing.JComponent; import javax.swing.plaf.basic.BasicButtonUI; public class VerticalButtonUI extends BasicButtonUI { - + protected int angle; - + public VerticalButtonUI(int angle) { super(); this.angle = angle; } - + @Override public Dimension getPreferredSize(JComponent c) { Dimension dim = super.getPreferredSize(c); - return new Dimension( dim.height, dim.width ); + return new Dimension(dim.height, dim.width); } - + private static Rectangle paintIconR = new Rectangle(); private static Rectangle paintTextR = new Rectangle(); private static Rectangle paintViewR = new Rectangle(); private static Insets paintViewInsets = new Insets(0, 0, 0, 0); - + @Override public void paint(Graphics g, JComponent c) { - JButton button = (JButton)c; + JButton button = (JButton) c; String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); - + if ((icon == null) && (text == null)) { return; } - + FontMetrics fm = g.getFontMetrics(); paintViewInsets = c.getInsets(paintViewInsets); - + paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; - + // Use inverted height & width paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); - + paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0; paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0; - + Graphics2D g2 = (Graphics2D) g; AffineTransform tr = g2.getTransform(); - + if (angle == 90) { - g2.rotate( Math.PI / 2 ); - g2.translate( 0, - c.getWidth() ); - paintViewR.x = c.getHeight()/2 - (int)fm.getStringBounds(text, g).getWidth()/2; - paintViewR.y = c.getWidth()/2 - (int)fm.getStringBounds(text, g).getHeight()/2; + g2.rotate(Math.PI / 2); + g2.translate(0, -c.getWidth()); + paintViewR.x = c.getHeight() / 2 - (int) fm.getStringBounds(text, g).getWidth() / 2; + paintViewR.y = c.getWidth() / 2 - (int) fm.getStringBounds(text, g).getHeight() / 2; + } else if (angle == 270 || angle == -90) { + g2.rotate(-Math.PI / 2); + g2.translate(-c.getHeight(), 0); + paintViewR.x = c.getHeight() / 2 - (int) fm.getStringBounds(text, g).getWidth() / 2; + paintViewR.y = c.getWidth() / 2 - (int) fm.getStringBounds(text, g).getHeight() / 2; } - else if (angle == 270 || angle == -90) { - g2.rotate( - Math.PI / 2 ); - g2.translate( - c.getHeight(), 0 ); - paintViewR.x = c.getHeight()/2 - (int)fm.getStringBounds(text, g).getWidth()/2; - paintViewR.y = c.getWidth()/2 - (int)fm.getStringBounds(text, g).getHeight()/2; - } - + if (icon != null) { icon.paintIcon(c, g, paintIconR.x, paintIconR.y); } - + if (text != null) { int textX = paintTextR.x; int textY = paintTextR.y + fm.getAscent(); - + if (button.isEnabled()) { - paintText(g,c,new Rectangle(paintViewR.x,paintViewR.y,textX,textY),text); + paintText(g, c, new Rectangle(paintViewR.x, paintViewR.y, textX, textY), text); } else { - paintText(g,c,new Rectangle(paintViewR.x,paintViewR.y,textX,textY),text); + paintText(g, c, new Rectangle(paintViewR.x, paintViewR.y, textX, textY), text); } } - - g2.setTransform( tr ); + + g2.setTransform(tr); } } \ No newline at end of file diff --git a/src/eva2/optimization/EvAMainAdapter.java b/src/eva2/optimization/EvAMainAdapter.java index ecd6d2ab..5f0d8a0e 100644 --- a/src/eva2/optimization/EvAMainAdapter.java +++ b/src/eva2/optimization/EvAMainAdapter.java @@ -4,12 +4,14 @@ package eva2.optimization; * Description: API for distributed and parallel computing. * Copyright: Copyright (c) 2004 * Company: University of Tuebingen - * @version: $Revision: 259 $ + * @version: $Revision: 259 $ * $Date: 2007-11-16 17:25:09 +0100 (Fri, 16 Nov 2007) $ * $Author: mkron $ */ + import eva2.optimization.go.InterfaceOptimizationParameters; import eva2.optimization.modules.ModuleAdapter; + /** * */ diff --git a/src/eva2/optimization/EvAMainAdapterImpl.java b/src/eva2/optimization/EvAMainAdapterImpl.java index c351e949..40930211 100644 --- a/src/eva2/optimization/EvAMainAdapterImpl.java +++ b/src/eva2/optimization/EvAMainAdapterImpl.java @@ -5,15 +5,17 @@ package eva2.optimization; * Description: API for distributed and parallel computing. * Copyright: Copyright (c) 2004 * Company: University of Tuebingen - * @version: $Revision: 315 $ + * @version: $Revision: 315 $ * $Date: 2007-12-04 15:23:57 +0100 (Tue, 04 Dec 2007) $ * $Author: mkron $ */ + import eva2.EvAInfo; import eva2.optimization.go.InterfaceOptimizationParameters; import eva2.optimization.modules.ModuleAdapter; + /** - * + * */ public class EvAMainAdapterImpl implements EvAMainAdapter { diff --git a/src/eva2/optimization/ModuleServer.java b/src/eva2/optimization/ModuleServer.java index 15a58cf7..f75a9600 100644 --- a/src/eva2/optimization/ModuleServer.java +++ b/src/eva2/optimization/ModuleServer.java @@ -10,11 +10,13 @@ package eva2.optimization; * $Date: 2007-12-06 16:05:11 +0100 (Thu, 06 Dec 2007) $ * $Author: mkron $ */ + import eva2.optimization.go.InterfaceOptimizationParameters; import eva2.optimization.modules.GOModuleAdapter; import eva2.optimization.modules.ModuleAdapter; import eva2.tools.EVAERROR; import eva2.tools.ReflectPackage; + import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; @@ -92,7 +94,7 @@ public class ModuleServer { } } - + String[] x = new String[moduleNameList.size()]; moduleNameList.toArray(x); return x; @@ -153,7 +155,7 @@ public class ModuleServer { constrIndex++; } moduleAdapter = (ModuleAdapter) constructorArr[constrIndex].newInstance(param); - } + } // m_RunnungModules.add(m_ModuleAdapter); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Error in RMI-Moduladapter initialization", ex); diff --git a/src/eva2/optimization/OptimizationStateListener.java b/src/eva2/optimization/OptimizationStateListener.java index 04143209..377a1241 100644 --- a/src/eva2/optimization/OptimizationStateListener.java +++ b/src/eva2/optimization/OptimizationStateListener.java @@ -5,12 +5,14 @@ package eva2.optimization; /** - * * @author becker */ public interface OptimizationStateListener { void performedStop(); + void performedStart(String infoString); + void performedRestart(String infoString); + void updateProgress(final int percent, String msg); } diff --git a/src/eva2/optimization/enums/BOAScoringMethods.java b/src/eva2/optimization/enums/BOAScoringMethods.java index 9e9fdc81..266fe1cd 100644 --- a/src/eva2/optimization/enums/BOAScoringMethods.java +++ b/src/eva2/optimization/enums/BOAScoringMethods.java @@ -1,9 +1,9 @@ package eva2.optimization.enums; public enum BOAScoringMethods { - BDM, K2, BIC; - - public static String[] getInfoStrings(){ - return new String[] {"The Bayesian Dirichlet Metric", "The K2 Metric", "The Bayesian Information Criterion"}; - } + BDM, K2, BIC; + + public static String[] getInfoStrings() { + return new String[]{"The Bayesian Dirichlet Metric", "The K2 Metric", "The Bayesian Information Criterion"}; + } } \ No newline at end of file diff --git a/src/eva2/optimization/enums/DETypeEnum.java b/src/eva2/optimization/enums/DETypeEnum.java index 7a9dc8ea..a1a2d561 100644 --- a/src/eva2/optimization/enums/DETypeEnum.java +++ b/src/eva2/optimization/enums/DETypeEnum.java @@ -1,6 +1,6 @@ package eva2.optimization.enums; public enum DETypeEnum { - DE1_Rand_1, DE2_CurrentToBest, DE_Best_2, TrigonometricDE,DE_CurrentToRand; - //", "DE2 - DE/current-to-best/1", "DE/best/2", "Trigonometric DE"}; + DE1_Rand_1, DE2_CurrentToBest, DE_Best_2, TrigonometricDE, DE_CurrentToRand; + //", "DE2 - DE/current-to-best/1", "DE/best/2", "Trigonometric DE"}; } diff --git a/src/eva2/optimization/enums/ESMutationInitialSigma.java b/src/eva2/optimization/enums/ESMutationInitialSigma.java index 1e1504e7..ce176f5e 100644 --- a/src/eva2/optimization/enums/ESMutationInitialSigma.java +++ b/src/eva2/optimization/enums/ESMutationInitialSigma.java @@ -1,5 +1,5 @@ package eva2.optimization.enums; public enum ESMutationInitialSigma { - halfRange, quarterRange, avgInitialDistance, userDefined; + halfRange, quarterRange, avgInitialDistance, userDefined; } diff --git a/src/eva2/optimization/enums/MutateESCrossoverTypeEnum.java b/src/eva2/optimization/enums/MutateESCrossoverTypeEnum.java index 3308e9b7..6a82a4c8 100644 --- a/src/eva2/optimization/enums/MutateESCrossoverTypeEnum.java +++ b/src/eva2/optimization/enums/MutateESCrossoverTypeEnum.java @@ -1,5 +1,5 @@ package eva2.optimization.enums; public enum MutateESCrossoverTypeEnum { - none, intermediate, discrete; + none, intermediate, discrete; } diff --git a/src/eva2/optimization/enums/PSOTopologyEnum.java b/src/eva2/optimization/enums/PSOTopologyEnum.java index 7e96932c..fa05846c 100644 --- a/src/eva2/optimization/enums/PSOTopologyEnum.java +++ b/src/eva2/optimization/enums/PSOTopologyEnum.java @@ -1,53 +1,63 @@ package eva2.optimization.enums; public enum PSOTopologyEnum { - /** - * - */ - linear, - /** - * - */ - grid, - /** - * - */ - star, - /** - * - */ - multiSwarm, - /** - * - */ - tree, - /** - * - */ - hpso, - /** - * - */ - random, - dms; + /** + * + */ + linear, + /** + * + */ + grid, + /** + * + */ + star, + /** + * + */ + multiSwarm, + /** + * + */ + tree, + /** + * + */ + hpso, + /** + * + */ + random, + dms; - /** - * A method to translate the "old" integer tags into the enum type. - * @param oldID - * @return - */ - public static PSOTopologyEnum translateOldID(int oldID) { - switch (oldID) { - case 0: return linear; - case 1: return grid; - case 2: return star; - case 3: return multiSwarm; - case 4: return tree; - case 5: return hpso; - case 6: return random; - case 7: return dms; - default: System.err.println("Error: invalid old topology ID in PSOTopologyEnum translateOldID! Returning grid."); - return grid; - } - } + /** + * A method to translate the "old" integer tags into the enum type. + * + * @param oldID + * @return + */ + public static PSOTopologyEnum translateOldID(int oldID) { + switch (oldID) { + case 0: + return linear; + case 1: + return grid; + case 2: + return star; + case 3: + return multiSwarm; + case 4: + return tree; + case 5: + return hpso; + case 6: + return random; + case 7: + return dms; + default: + System.err.println("Error: invalid old topology ID in PSOTopologyEnum translateOldID! Returning grid."); + return grid; + } + } } \ No newline at end of file diff --git a/src/eva2/optimization/enums/PostProcessMethod.java b/src/eva2/optimization/enums/PostProcessMethod.java index ca0ddd59..4d810231 100644 --- a/src/eva2/optimization/enums/PostProcessMethod.java +++ b/src/eva2/optimization/enums/PostProcessMethod.java @@ -1,5 +1,5 @@ package eva2.optimization.enums; public enum PostProcessMethod { - hillClimber, nelderMead, cmaES; + hillClimber, nelderMead, cmaES; } \ No newline at end of file diff --git a/src/eva2/optimization/go/GOStandaloneVersion.java b/src/eva2/optimization/go/GOStandaloneVersion.java index a7320340..4a07e987 100644 --- a/src/eva2/optimization/go/GOStandaloneVersion.java +++ b/src/eva2/optimization/go/GOStandaloneVersion.java @@ -20,6 +20,7 @@ import eva2.optimization.strategies.EvolutionStrategies; import eva2.optimization.strategies.GeneticAlgorithm; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.math.RNG; + import java.awt.BorderLayout; import java.awt.List; import java.awt.event.ActionEvent; @@ -54,7 +55,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu transient private JProgressBar m_ProgressBar; transient private SwingWorker worker; transient private boolean show = false; -// transient private InterfaceTest test = new Test1(); + // transient private InterfaceTest test = new Test1(); // Opt. Algorithms and Parameters //transient private InterfaceOptimizer optimizer = new EvolutionaryMultiObjectiveOptimization(); //transient private InterfaceOptimizationProblem problem = new TF1Problem(); @@ -68,7 +69,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu transient private String m_ExperimentName; transient private String m_OutputPath = ""; transient private String m_OutputFileName = "none"; -// transient private GOStandaloneVersion m_yself; + // transient private GOStandaloneVersion m_yself; // these parameters are for the continue option transient private Population m_Backup; transient private boolean m_ContinueFlag; @@ -97,7 +98,6 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu /** * This method allows you to get the current GO parameters - * */ public OptimizationParameters getGOParameters() { return this.m_GO; @@ -192,6 +192,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu this.m_Frame.validate(); this.m_Frame.setVisible(true); } + /** * This action listener, called by the "Run/Restart" button, will init the * problem and start the computation. @@ -572,7 +573,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu * This method allows an optimizer to register a change in the optimizer. * * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. + * @param name Could be used to indicate the nature of the event. */ @Override public void registerPopulationStateChanged(Object source, String name) { @@ -695,6 +696,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu // public String seedTipText() { // return "Choose the seed for the random number generator."; // } + /** * This method sets the name of the current experiment as it will occur in * the plot legend. diff --git a/src/eva2/optimization/go/IndividualInterface.java b/src/eva2/optimization/go/IndividualInterface.java index 186806bc..c7504813 100644 --- a/src/eva2/optimization/go/IndividualInterface.java +++ b/src/eva2/optimization/go/IndividualInterface.java @@ -17,57 +17,57 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * Minimal interface for an EA individual. */ public interface IndividualInterface { - /** - * Create a clone of the individual instance. - * - * @return a clone of the individual instance - */ - IndividualInterface getClone(); + /** + * Create a clone of the individual instance. + * + * @return a clone of the individual instance + */ + IndividualInterface getClone(); - /** - * Get the fitness array of the individual which may be null if none has been set. - * - * @return the fitness array of the individual - */ - double[] getFitness(); + /** + * Get the fitness array of the individual which may be null if none has been set. + * + * @return the fitness array of the individual + */ + double[] getFitness(); - /** - * Set the fitness array to the given array. - * - * @param fit new fitness of the individual - */ - void setFitness (double[] fit); + /** + * Set the fitness array to the given array. + * + * @param fit new fitness of the individual + */ + void setFitness(double[] fit); - /** - * Check whether the instance is dominating the given other individual and return - * true in this case. - * - * @param other a second individual of the same type - * @return true if the instance dominates the other individual, else false - */ - boolean isDominant(double[] fitness); + /** + * Check whether the instance is dominating the given other individual and return + * true in this case. + * + * @param other a second individual of the same type + * @return true if the instance dominates the other individual, else false + */ + boolean isDominant(double[] fitness); - /** - * Check whether the instance is dominating the given other individual and return - * true in this case. - * Should behave equally to {@link #isDominant(double[])} if called with the fitness - * of the given individual. - * - * @param other a second individual of the same type - * @return true if the instance dominates the other individual, else false - */ - boolean isDominant(IndividualInterface other); + /** + * Check whether the instance is dominating the given other individual and return + * true in this case. + * Should behave equally to {@link #isDominant(double[])} if called with the fitness + * of the given individual. + * + * @param other a second individual of the same type + * @return true if the instance dominates the other individual, else false + */ + boolean isDominant(IndividualInterface other); - /** - * Perform a standard mutation operation on the individual. The exact implementation - * depends on the implemented genotype. - */ - void defaultMutate(); + /** + * Perform a standard mutation operation on the individual. The exact implementation + * depends on the implemented genotype. + */ + void defaultMutate(); - /** - * Initialize the genotype randomly, usually in a uniform distribution. Make sure, - * if the problem has an initial range (it implements InterfaceHasInitialRange), that this - * initial range is used. - */ - void defaultInit(InterfaceOptimizationProblem prob); + /** + * Initialize the genotype randomly, usually in a uniform distribution. Make sure, + * if the problem has an initial range (it implements InterfaceHasInitialRange), that this + * initial range is used. + */ + void defaultInit(InterfaceOptimizationProblem prob); } \ No newline at end of file diff --git a/src/eva2/optimization/go/InterfaceGOStandalone.java b/src/eva2/optimization/go/InterfaceGOStandalone.java index 7a9115c1..1b674c43 100644 --- a/src/eva2/optimization/go/InterfaceGOStandalone.java +++ b/src/eva2/optimization/go/InterfaceGOStandalone.java @@ -9,5 +9,6 @@ package eva2.optimization.go; */ public interface InterfaceGOStandalone { void startExperiment(); + void setShow(boolean t); } diff --git a/src/eva2/optimization/go/InterfaceNotifyOnInformers.java b/src/eva2/optimization/go/InterfaceNotifyOnInformers.java index 0f3bf7e1..8656cb57 100644 --- a/src/eva2/optimization/go/InterfaceNotifyOnInformers.java +++ b/src/eva2/optimization/go/InterfaceNotifyOnInformers.java @@ -1,11 +1,12 @@ package eva2.optimization.go; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; + import java.util.List; public interface InterfaceNotifyOnInformers { - /** - * Notify the object about informer instances. - */ - public void setInformers(List informers); + /** + * Notify the object about informer instances. + */ + public void setInformers(List informers); } diff --git a/src/eva2/optimization/go/InterfaceOptimizationParameters.java b/src/eva2/optimization/go/InterfaceOptimizationParameters.java index 217082ec..a03b05da 100644 --- a/src/eva2/optimization/go/InterfaceOptimizationParameters.java +++ b/src/eva2/optimization/go/InterfaceOptimizationParameters.java @@ -19,63 +19,85 @@ public interface InterfaceOptimizationParameters { */ // public String globalInfo(); - /** This method allows you to serialize the current parameters into a *.ser file + /** + * This method allows you to serialize the current parameters into a *.ser file */ public void saveInstance(); - /** This method returns the name + /** + * This method returns the name + * * @return string */ public String getName(); - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. + /** + * This methods allow you to set and get the Seed for the Random Number Generator. + * + * @param x Long seed. */ public void setSeed(long x); + public long getSeed(); + public String seedTipText(); - /** This method allows you to choose a termination criteria for the + /** + * This method allows you to choose a termination criteria for the * evolutionary algorithm. - * @param term The new terminator + * + * @param term The new terminator */ public void setTerminator(InterfaceTerminator term); + public InterfaceTerminator getTerminator(); + public String terminatorTipText(); - /** This method allows you to set the current optimizing algorithm + /** + * This method allows you to set the current optimizing algorithm + * * @param optimizer The new optimizing algorithm */ public void setOptimizer(InterfaceOptimizer optimizer); + public InterfaceOptimizer getOptimizer(); // public String optimizerTipText(); - /** This method will set the problem that is to be optimized + /** + * This method will set the problem that is to be optimized + * * @param problem */ - public void setProblem (InterfaceOptimizationProblem problem); - public InterfaceOptimizationProblem getProblem (); + public void setProblem(InterfaceOptimizationProblem problem); + + public InterfaceOptimizationProblem getProblem(); + public String problemTipText(); - /** This method will set the output filename - * @param name - * TODO invalidate these! + /** + * This method will set the output filename + * + * @param name TODO invalidate these! */ // public void setOutputFileName (String name); // public String getOutputFileName (); // public String outputFileNameTipText(); - public InterfacePostProcessParams getPostProcessParams(); + public void setPostProcessParams(InterfacePostProcessParams ppp); + public String postProcessParamsTipText(); + public void setDoPostProcessing(boolean doPP); - + /** * Give an instance which should be informed about elements which are additional informers. - * - * @see InterfaceAdditionalPopulationInformer + * * @param o + * @see InterfaceAdditionalPopulationInformer */ public void addInformableInstance(InterfaceNotifyOnInformers o); + public boolean removeInformableInstance(InterfaceNotifyOnInformers o); } diff --git a/src/eva2/optimization/go/InterfacePopulationChangedEventListener.java b/src/eva2/optimization/go/InterfacePopulationChangedEventListener.java index 881c6265..ad2223ad 100644 --- a/src/eva2/optimization/go/InterfacePopulationChangedEventListener.java +++ b/src/eva2/optimization/go/InterfacePopulationChangedEventListener.java @@ -10,9 +10,11 @@ package eva2.optimization.go; */ public interface InterfacePopulationChangedEventListener { - /** This method allows an optimizer to register a change in the optimizer. - * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. + /** + * This method allows an optimizer to register a change in the optimizer. + * + * @param source The source of the event. + * @param name Could be used to indicate the nature of the event. */ void registerPopulationStateChanged(Object source, String name); } diff --git a/src/eva2/optimization/go/InterfaceProcessor.java b/src/eva2/optimization/go/InterfaceProcessor.java index 58f7a6d5..ba1f61cb 100644 --- a/src/eva2/optimization/go/InterfaceProcessor.java +++ b/src/eva2/optimization/go/InterfaceProcessor.java @@ -32,6 +32,7 @@ public interface InterfaceProcessor { /** * Get Info String about the Optimization. + * * @return The info String */ String getInfoString(); diff --git a/src/eva2/optimization/go/InterfaceTerminator.java b/src/eva2/optimization/go/InterfaceTerminator.java index 5897d33a..0a866f64 100644 --- a/src/eva2/optimization/go/InterfaceTerminator.java +++ b/src/eva2/optimization/go/InterfaceTerminator.java @@ -6,22 +6,24 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; /** * Interface for a termination criterion. - * - * @author mkron, streiche * + * @author mkron, streiche */ public interface InterfaceTerminator { - /** - * Test a given population for convergence with the criterion defined by the instance. - * - * @param pop the population to test - * @return true if the population fulfills the termination criterion, else false - */ - public boolean isTerminated(PopulationInterface pop); - public boolean isTerminated(InterfaceSolutionSet pop); + /** + * Test a given population for convergence with the criterion defined by the instance. + * + * @param pop the population to test + * @return true if the population fulfills the termination criterion, else false + */ + public boolean isTerminated(PopulationInterface pop); + + public boolean isTerminated(InterfaceSolutionSet pop); @Override - public String toString(); - public String lastTerminationMessage(); - public void init(InterfaceOptimizationProblem prob); + public String toString(); + + public String lastTerminationMessage(); + + public void init(InterfaceOptimizationProblem prob); } \ No newline at end of file diff --git a/src/eva2/optimization/go/MOCCOStandalone.java b/src/eva2/optimization/go/MOCCOStandalone.java index 9c3b9197..f3397a96 100644 --- a/src/eva2/optimization/go/MOCCOStandalone.java +++ b/src/eva2/optimization/go/MOCCOStandalone.java @@ -29,6 +29,7 @@ import eva2.optimization.operator.terminators.EvaluationTerminator; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.IslandModelEA; + import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; @@ -46,23 +47,24 @@ import javax.swing.*; */ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulationChangedEventListener, Serializable { - public volatile MOCCOState m_State; - private SwingWorker worker; - private volatile boolean m_StillWorking = false; - public int m_Iteration = -1; - public JFrame m_JFrame; + public volatile MOCCOState m_State; + private SwingWorker worker; + private volatile boolean m_StillWorking = false; + public int m_Iteration = -1; + public JFrame m_JFrame; //public ParetoFrontView n_ParetoFrontView; - public boolean m_Debug = false; - public MOCCOViewer m_View; - public JPanel m_JPanelMain, m_JPanelParameters, m_JPanelControl, m_JPanelButtom; - private JLabel m_CurrentState; - private JProgressBar m_ProgressBar; + public boolean m_Debug = false; + public MOCCOViewer m_View; + public JPanel m_JPanelMain, m_JPanelParameters, m_JPanelControl, m_JPanelButtom; + private JLabel m_CurrentState; + private JProgressBar m_ProgressBar; public MOCCOStandalone() { this.m_State = new MOCCOState(); } - /** This method will init the main MOCCO GUI + /** + * This method will init the main MOCCO GUI * frame */ public void initMOCCOFrame() { @@ -80,12 +82,12 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati } }); // init basic panel structure - this.m_JPanelMain = new JPanel(); + this.m_JPanelMain = new JPanel(); this.m_JPanelParameters = new JPanel(); this.m_JPanelParameters.setPreferredSize(new Dimension(500, 300)); this.m_JPanelParameters.setMinimumSize(new Dimension(500, 300)); - this.m_JPanelControl = new JPanel(); - this.m_View = new MOCCOViewer(this); + this.m_JPanelControl = new JPanel(); + this.m_View = new MOCCOViewer(this); this.m_JFrame.getContentPane().add(this.m_JPanelMain); this.m_JPanelMain.setLayout(new BorderLayout()); this.m_JPanelMain.add(this.m_JPanelParameters, BorderLayout.WEST); @@ -93,14 +95,14 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.m_JPanelButtom = new JPanel(); this.m_JPanelButtom.setLayout(new BorderLayout()); JPanel tmpP = new JPanel(); - tmpP.setLayout(new GridLayout(2,1)); + tmpP.setLayout(new GridLayout(2, 1)); this.m_CurrentState = new JLabel("Problem Initialization"); tmpP.add(this.m_CurrentState); this.m_ProgressBar = new JProgressBar(); tmpP.add(this.m_ProgressBar); this.m_JPanelButtom.add(tmpP, BorderLayout.CENTER); - this.m_JPanelControl.setMinimumSize(new Dimension(400,0)); - this.m_JPanelControl.setPreferredSize(new Dimension(400,0)); + this.m_JPanelControl.setMinimumSize(new Dimension(400, 0)); + this.m_JPanelControl.setPreferredSize(new Dimension(400, 0)); this.m_JPanelButtom.add(this.m_JPanelControl, BorderLayout.EAST); this.m_JPanelMain.add(this.m_JPanelButtom, BorderLayout.SOUTH); this.m_JFrame.validate(); @@ -109,22 +111,37 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati } public void MOCCOOptimization() { - boolean cont = true; + boolean cont = true; InterfaceProcessElement tmpP; while (cont) { this.m_Iteration++; - while (m_StillWorking) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (m_StillWorking) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } if (this.m_State.m_OriginalProblem == null) { this.m_State.m_OriginalProblem = new TF1Problem(); tmpP = new MOCCOProblemInitialization(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { }} - this.m_State.m_CurrentProblem = (InterfaceOptimizationProblem)this.m_State.m_OriginalProblem.clone(); + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + this.m_State.m_CurrentProblem = (InterfaceOptimizationProblem) this.m_State.m_OriginalProblem.clone(); this.m_View.problemChanged(true); this.m_JPanelParameters.removeAll(); tmpP = new MOCCOInitialPopulationSize(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { }} + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } this.m_State.m_InitialPopulationSize = Math.max(1, this.m_State.m_InitialPopulationSize); Population pop = new Population(); pop.setTargetSize(this.m_State.m_InitialPopulationSize); @@ -134,12 +151,17 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.m_State.addPopulation2History(pop); this.m_View.problemChanged(true); } - ((InterfaceMultiObjectiveDeNovoProblem)this.m_State.m_CurrentProblem).deactivateRepresentationEdit(); + ((InterfaceMultiObjectiveDeNovoProblem) this.m_State.m_CurrentProblem).deactivateRepresentationEdit(); this.updateStatus("Analysis/Redefinition", 33); tmpP = new MOCCOProblemRedefinition(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } - this.m_State.makeFitnessCache(true); + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + this.m_State.makeFitnessCache(true); this.m_State.m_CurrentProblem.initializeProblem(); this.m_State.makeBackup(); this.m_View.problemChanged(true); @@ -147,70 +169,125 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.updateStatus("MO Strategy Selection", 50); tmpP = new MOCCOChooseMOStrategy(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } - switch (((MOCCOChooseMOStrategy)tmpP).getMOStrategy()) { - case MOCCOChooseMOStrategy.STRATEGY_MOEA : { + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + switch (((MOCCOChooseMOStrategy) tmpP).getMOStrategy()) { + case MOCCOChooseMOStrategy.STRATEGY_MOEA: { this.updateStatus("MOEA Parameterization", 75); tmpP = new MOCCOParameterizeMO(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } break; } - case MOCCOChooseMOStrategy.STRATEGY_STEP : { + case MOCCOChooseMOStrategy.STRATEGY_STEP: { this.updateStatus("Reference Solution...", 75); tmpP = new MOCCOChooseReferenceSolution(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } - AbstractEAIndividual reference = ((MOCCOChooseReferenceSolution)tmpP).getReferenceSolution(); + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + AbstractEAIndividual reference = ((MOCCOChooseReferenceSolution) tmpP).getReferenceSolution(); this.updateStatus("STEP Parameterization...", 90); tmpP = new MOCCOParameterizeSTEP(this); - ((MOCCOParameterizeSTEP)tmpP).setReferenceSolution(reference); + ((MOCCOParameterizeSTEP) tmpP).setReferenceSolution(reference); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } break; } - case MOCCOChooseMOStrategy.STRATEGY_REFP : { + case MOCCOChooseMOStrategy.STRATEGY_REFP: { this.updateStatus("Reference Point...", 75); tmpP = new MOCCOChooseReferencePoint(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } - double[] reference = ((MOCCOChooseReferencePoint)tmpP).getReferencePoint(); + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + double[] reference = ((MOCCOChooseReferencePoint) tmpP).getReferencePoint(); this.updateStatus("Reference Point Parameterization...", 90); tmpP = new MOCCOParameterizeRefPoint(this); - ((MOCCOParameterizeRefPoint)tmpP).setReferencePoint(reference); + ((MOCCOParameterizeRefPoint) tmpP).setReferencePoint(reference); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } break; } - case MOCCOChooseMOStrategy.STRATEGY_TBCH : { + case MOCCOChooseMOStrategy.STRATEGY_TBCH: { this.updateStatus("Reference Point...", 75); tmpP = new MOCCOChooseReferencePoint(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } - double[] reference = ((MOCCOChooseReferencePoint)tmpP).getReferencePoint(); + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + double[] reference = ((MOCCOChooseReferencePoint) tmpP).getReferencePoint(); this.updateStatus("Tchebycheff Method Parameterization...", 90); tmpP = new MOCCOParameterizeTchebycheff(this); - ((MOCCOParameterizeTchebycheff)tmpP).setReferencePoint(reference); + ((MOCCOParameterizeTchebycheff) tmpP).setReferencePoint(reference); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } break; } - case MOCCOChooseMOStrategy.STRATEGY_GDF : { + case MOCCOChooseMOStrategy.STRATEGY_GDF: { this.updateStatus("Reference Solution...", 75); tmpP = new MOCCOChooseReferenceSolution(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } - AbstractEAIndividual reference = ((MOCCOChooseReferenceSolution)tmpP).getReferenceSolution(); + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } + AbstractEAIndividual reference = ((MOCCOChooseReferenceSolution) tmpP).getReferenceSolution(); this.updateStatus("Geoffrion-Dyer-Feinberg Method Parameterization...", 90); tmpP = new MOCCOParameterizeGDF(this); - ((MOCCOParameterizeGDF)tmpP).setReferenceSolution(reference); + ((MOCCOParameterizeGDF) tmpP).setReferenceSolution(reference); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } break; } - default : { + default: { tmpP = new MOCCOParameterizeMO(this); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } break; } } @@ -218,7 +295,12 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.updateStatus("SO-Optimizer Parameterization", 66); tmpP = new MOCCOParameterizeSO(this); tmpP.initProcessElementParametrization(); - while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { } } + while (!tmpP.isFinished()) { + try { + Thread.sleep(1000); + } catch (java.lang.InterruptedException e) { + } + } } // now optimize this.updateStatus("Optimizing...", 0); @@ -227,27 +309,24 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati } private void checkForObjectives(String w) { - System.out.println("I'm currently "+w); + System.out.println("I'm currently " + w); System.out.print("Original Problem is "); if (this.m_State.m_OriginalProblem.isMultiObjective()) { System.out.println("multi-objective."); - } - else { + } else { System.out.println("single-objective."); } System.out.print("Current Problem is "); if (this.m_State.m_CurrentProblem.isMultiObjective()) { System.out.println("multi-objective."); - } - else { + } else { System.out.println("single-objective."); } if (this.m_State.m_BackupProblem != null) { System.out.print("Backup Problem is "); if (this.m_State.m_BackupProblem.isMultiObjective()) { System.out.println("multi-objective."); - } - else { + } else { System.out.println("single-objective."); } } else { @@ -257,30 +336,30 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati private void checktForMOSO(String w) { String s; - System.out.println("I'm currently at "+w); - InterfaceMOSOConverter moso = ((AbstractMultiObjectiveOptimizationProblem)this.m_State.m_CurrentProblem).getMOSOConverter(); - System.out.println("MOSO selected: "+moso.getName()); - InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_State.m_CurrentProblem).getProblemObjectives(); + System.out.println("I'm currently at " + w); + InterfaceMOSOConverter moso = ((AbstractMultiObjectiveOptimizationProblem) this.m_State.m_CurrentProblem).getMOSOConverter(); + System.out.println("MOSO selected: " + moso.getName()); + InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_State.m_CurrentProblem).getProblemObjectives(); s = "Objectives: {"; for (int i = 0; i < obj.length; i++) { s += obj[i].getIdentName(); - if (i < (obj.length-1)) { + if (i < (obj.length - 1)) { s += "; "; } } s += "}"; - System.out.println(""+s); + System.out.println("" + s); if (moso instanceof MOSOWeightedFitness) { - PropertyDoubleArray prop = ((MOSOWeightedFitness)moso).getWeights(); + PropertyDoubleArray prop = ((MOSOWeightedFitness) moso).getWeights(); s = "Weights : {"; for (int i = 0; i < prop.getNumRows(); i++) { - s += prop.getValue(i,0); - if (i < (prop.getNumRows()-1)) { + s += prop.getValue(i, 0); + if (i < (prop.getNumRows() - 1)) { s += "; "; } } s += "}"; - System.out.println(""+s); + System.out.println("" + s); } } @@ -318,7 +397,8 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati } }*/ - /** This is the main method + /** + * This is the main method * * @param args */ @@ -337,8 +417,8 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati if (go.m_State.m_Optimizer.getPopulation().getFunctionCalls() == 0) { // start to optimize go.startExperiment(); - file = file.replaceAll(".ser",""); - go.saveObject(file+"_Finished.ser"); + file = file.replaceAll(".ser", ""); + go.saveObject(file + "_Finished.ser"); } else { // start GUI go.initMOCCOFrame(); @@ -347,54 +427,58 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati } } - /** This methods loads the current state of MOCO from a serialized file - * @param loadFrom The name of the serialized file + /** + * This methods loads the current state of MOCO from a serialized file + * + * @param loadFrom The name of the serialized file * @return The new state of MOCO */ public Object openObject(String loadFrom) { File selected = new File(loadFrom); - try { - ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); + try { + ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); Object obj = oi.readObject(); oi.close(); if (!(obj instanceof MOCCOState)) { throw new Exception("Object not of type MOCCOState"); - } return obj; - } catch (Exception ex) { + } + return obj; + } catch (Exception ex) { if (this.m_JFrame != null) { - JOptionPane.showMessageDialog(this.m_JFrame, "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(), "Open object file", JOptionPane.ERROR_MESSAGE); - } - else { - System.out.println("Couldn't read object: " + selected.getName() + "\n" + ex.getMessage()); - } - } + JOptionPane.showMessageDialog(this.m_JFrame, "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(), "Open object file", JOptionPane.ERROR_MESSAGE); + } else { + System.out.println("Couldn't read object: " + selected.getName() + "\n" + ex.getMessage()); + } + } return null; } - /** This method saves the current MOCOData into a serialized file - * @param saveAs The name of the outputfile + /** + * This method saves the current MOCOData into a serialized file + * + * @param saveAs The name of the outputfile */ public void saveObject(String saveAs) { - File sFile = new File(saveAs); - try { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); + File sFile = new File(saveAs); + try { + ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); oo.writeObject(this.m_State); oo.close(); - } catch (Exception ex) { + } catch (Exception ex) { if (this.m_JFrame != null) { - JOptionPane.showMessageDialog(this.m_JFrame, "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(), "Save object", JOptionPane.ERROR_MESSAGE); - } - else { - System.out.println("Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage()); - } - } + JOptionPane.showMessageDialog(this.m_JFrame, "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(), "Save object", JOptionPane.ERROR_MESSAGE); + } else { + System.out.println("Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage()); + } + } } /*********************************************************************************************** * InterfaceGOStandalone */ - /** This method starts the actual optimization procedure + /** + * This method starts the actual optimization procedure */ @Override public void startExperiment() { @@ -403,7 +487,7 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.m_StillWorking = true; this.m_State.m_Optimizer.setProblem(this.m_State.m_CurrentProblem); if (this.m_Debug) { - System.out.println(""+this.m_State.m_Optimizer.getStringRepresentation()); + System.out.println("" + this.m_State.m_Optimizer.getStringRepresentation()); } this.m_State.m_CurrentProblem.evaluate(this.m_State.m_Optimizer.getPopulation()); this.m_State.m_Optimizer.getPopulation().SetFunctionCalls(0); @@ -416,11 +500,12 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati public Object construct() { return doWork(); } + @Override public void finished() { Population[] pop = null; if (m_State.m_Optimizer instanceof IslandModelEA) { - InterfaceOptimizer[] opt = ((IslandModelEA)m_State.m_Optimizer).getOptimizers(); + InterfaceOptimizer[] opt = ((IslandModelEA) m_State.m_Optimizer).getOptimizers(); pop = new Population[opt.length]; for (int i = 0; i < opt.length; i++) { pop[i] = opt[i].getPopulation(); @@ -444,7 +529,8 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati worker.start(); } - /** When the worker needs to update the GUI we do so by queuing + /** + * When the worker needs to update the GUI we do so by queuing * a Runnable for the event dispatching thread with * SwingUtilities.invokeLater(). In this case we're just * changing the progress bars value. @@ -462,7 +548,8 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.m_CurrentState.setText(t); } - /** This method represents the application code that we'd like to + /** + * This method represents the application code that we'd like to * run on a separate thread. It simulates slowly computing * a value, in this case just a string 'All Done'. It updates the * progress bar every half second to remind the user that @@ -480,8 +567,7 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati this.m_State.m_Optimizer.optimize(); } System.gc(); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { updateStatus("Interrupted", 0); return "Interrupted"; } @@ -497,27 +583,29 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati /*********************************************************************************************** * InterfacePopulationChangedEventListener */ - /** This method allows an optimizer to register a change in the optimizer. - * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. + /** + * This method allows an optimizer to register a change in the optimizer. + * + * @param source The source of the event. + * @param name Could be used to indicate the nature of the event. */ @Override public void registerPopulationStateChanged(Object source, String name) { - int currentProgress; - if (name.equals(Population.nextGenerationPerformed)) { - if (this.m_State.isVisible) { - Population population = ((InterfaceOptimizer)source).getPopulation(); - double x = 100; - if (this.m_State.m_Terminator instanceof EvaluationTerminator) { - double y = x/(double)((EvaluationTerminator)this.m_State.m_Terminator).getFitnessCalls(); - currentProgress = (int)(population.getFunctionCalls()*y); - } else { - currentProgress = (int)(0); - } - updateStatus("Optimizing...",currentProgress); - } else { - // perhaps i could write it to file!? - } - } + int currentProgress; + if (name.equals(Population.nextGenerationPerformed)) { + if (this.m_State.isVisible) { + Population population = ((InterfaceOptimizer) source).getPopulation(); + double x = 100; + if (this.m_State.m_Terminator instanceof EvaluationTerminator) { + double y = x / (double) ((EvaluationTerminator) this.m_State.m_Terminator).getFitnessCalls(); + currentProgress = (int) (population.getFunctionCalls() * y); + } else { + currentProgress = (int) (0); + } + updateStatus("Optimizing...", currentProgress); + } else { + // perhaps i could write it to file!? + } + } } } diff --git a/src/eva2/optimization/go/SwingWorker.java b/src/eva2/optimization/go/SwingWorker.java index 0a9540db..052b9d71 100644 --- a/src/eva2/optimization/go/SwingWorker.java +++ b/src/eva2/optimization/go/SwingWorker.java @@ -1,4 +1,5 @@ package eva2.optimization.go; + import javax.swing.SwingUtilities; /** @@ -6,11 +7,11 @@ import javax.swing.SwingUtilities; * SwingWorker 3), an abstract class that you subclass to * perform GUI-related work in a dedicated thread. For * instructions on using this class, see: - * + *

* http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html * or * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html - * + *

* Note that the API changed slightly in the 3rd version: * You must now invoke start() on the SwingWorker after * creating it. @@ -20,36 +21,45 @@ public abstract class SwingWorker { private Object value; // see getValue(), setValue() private Thread thread; - /** + /** * Class to maintain reference to current worker thread * under separate synchronization control. */ private static class ThreadVar { private Thread thread; - ThreadVar(Thread t) { thread = t; } - synchronized Thread get() { return thread; } - synchronized void clear() { thread = null; } + + ThreadVar(Thread t) { + thread = t; + } + + synchronized Thread get() { + return thread; + } + + synchronized void clear() { + thread = null; + } } private ThreadVar threadVar; - /** - * Get the value produced by the worker thread, or null if it + /** + * Get the value produced by the worker thread, or null if it * hasn't been constructed yet. */ protected synchronized Object getValue() { - return value; + return value; } - /** - * Set the value produced by worker thread + /** + * Set the value produced by worker thread */ private synchronized void setValue(Object x) { - value = x; + value = x; } - /** - * Compute the value to be returned by the get method. + /** + * Compute the value to be returned by the get method. */ public abstract Object construct(); @@ -61,22 +71,21 @@ public abstract class SwingWorker { } /** - * Return the value created by the construct method. + * Return the value created by the construct method. * Returns null if either the constructing thread or the current * thread was interrupted before a value was produced. - * + * * @return the value created by the construct method */ public Object get() { - while (true) { + while (true) { Thread t = threadVar.get(); if (t == null) { return getValue(); } try { t.join(); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate return null; } @@ -90,7 +99,9 @@ public abstract class SwingWorker { public SwingWorker() { final Runnable doFinished = new Runnable() { @Override - public void run() { finished(); } + public void run() { + finished(); + } }; Runnable doConstruct = new Runnable() { @@ -98,8 +109,7 @@ public abstract class SwingWorker { public void run() { try { setValue(construct()); - } - finally { + } finally { threadVar.clear(); } diff --git a/src/eva2/optimization/individuals/AbstractEAIndividual.java b/src/eva2/optimization/individuals/AbstractEAIndividual.java index a84cb40e..c9023a97 100644 --- a/src/eva2/optimization/individuals/AbstractEAIndividual.java +++ b/src/eva2/optimization/individuals/AbstractEAIndividual.java @@ -14,9 +14,11 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.RNG; + import java.util.*; -/** This is the abstract EA individual implementing the most important methods giving +/** + * This is the abstract EA individual implementing the most important methods giving * access to mutation and crossover rates and operators, fitness values and selection * probabilities. All EA individuals should typically extend this abstract EA individual. * In that case the EA individuals only implement the genotype and phenotype interfaces. @@ -44,7 +46,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. private double constraintViolation = 0; public boolean areaConst4ParallelViolated = false; // no idea what felix used this for... public boolean isMarked = false; // is for GUI only! - public boolean isPenalized = false; // may be set true for penalty based constraints + public boolean isPenalized = false; // may be set true for penalty based constraints protected double[] selectionProbability = new double[1]; protected double crossoverProbability = 1.0; @@ -249,6 +251,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // public String getIndividualName() { // return this.m_Name; // } + /** * This method is used when a new offspring is created the increment the * name. @@ -307,6 +310,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // return false; // } // } + /** * This method will allow a default initialisation of the individual * @@ -385,6 +389,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // public void setLogHeritagetLen(int logLen) { // logParentLen = logLen; // } + /** * Add an ancestor generation with multiple parents. * @@ -446,6 +451,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // heritage.add(parentIDs); //// if (heritage.size() > logParentLen) heritage.remove(0); // } + /** * Add an ancestor generation with only one parent. * @@ -468,6 +474,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // if (heritage != null) return heritage.getLast(); // else return null; // } + /** * This method will allow you to get the current age of an individual Zero * means it has not even been evaluated. @@ -627,7 +634,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. /** * This method allows you to set the i-th fitness value * - * @param index The index of the fitness value to set. + * @param index The index of the fitness value to set. * @param fitness The new fitness value. */ public void SetFitness(int index, double fitness) { @@ -764,7 +771,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. * * @param indy The individual to compare to. * @return 1 if the instance is better (regarding constraints only), -1 if - * is worse, 0 if they are equal in that respect. + * is worse, 0 if they are equal in that respect. */ public int compareConstraintViolation(AbstractEAIndividual indy) { if ((this.constraintViolation > 0) && (indy.constraintViolation <= 0)) { @@ -883,7 +890,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. * This method allows you to set the i-th selection probability value * * @param index The index of the selection probability value to set. - * @param sel The new selection probability value. + * @param sel The new selection probability value. */ public void SetSelectionProbability(int index, double sel) { if (this.selectionProbability.length > index) { @@ -998,7 +1005,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. * name. * * @param name The identifying name. - * @param obj The object that is to be stored. + * @param obj The object that is to be stored. */ public void putData(String name, Object obj) { dataHash.put(name, obj); @@ -1010,7 +1017,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. * fitness array. * * @param name The name of the requested Object - * @return Object The associated object or null if none is found + * @return Object The associated object or null if none is found */ public Object getData(String name) { // if (name.equalsIgnoreCase("SelectionProbability")) return this.getSelectionProbability(); @@ -1286,7 +1293,6 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. /** * @return true if parent history logging is activated - * */ protected boolean isLogParents() { return logParents; @@ -1309,7 +1315,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. return (IndividualInterface) this.clone(); } -// /** This method is used to get the basic data type of an individual double[]. + // /** This method is used to get the basic data type of an individual double[]. // * @deprecated Since not all EAIndividuals provide double as basic data type // * the fitness can be is returned as default value. // * @see #getFitness() diff --git a/src/eva2/optimization/individuals/AbstractEAIndividualComparator.java b/src/eva2/optimization/individuals/AbstractEAIndividualComparator.java index 51e1f23b..75c3626b 100644 --- a/src/eva2/optimization/individuals/AbstractEAIndividualComparator.java +++ b/src/eva2/optimization/individuals/AbstractEAIndividualComparator.java @@ -9,204 +9,207 @@ import java.util.Comparator; * class and assigns -1 if first is dominant, 1 if second is dominant, 0 if the two ind.s * are not comparable. * By default, the dominance criterion is used on fitness vectors. - * If a specific criterion i is set, the comparison is based only on the i-th + * If a specific criterion i is set, the comparison is based only on the i-th * entry of the fitness vector. * As an alternative, a data key String may be set which is then used to request a data * object from the individuals. The objects are interpreted as fitness vectors (double[]) and * the comparison is based on those. This may be used to access alternative (e.g. older or * best-so-far fitness values) for individual comparison. * - * @see #AbstractEAIndividual().isDominatingFitness(double[], double[]) * @author mkron - * + * @see #AbstractEAIndividual().isDominatingFitness(double[], double[]) */ public class AbstractEAIndividualComparator implements Comparator, Serializable { - // flag whether a data field should be used. - private String indyDataKey = ""; - private int fitCriterion = -1; - private boolean preferFeasible = true; - - /** - * Comparator implementation which compares two individuals based on their fitness. - * The default version calls compares based on dominance with priority of feasibility if there are constraints. - * It assigns -1 if first is better, 1 if second is better, 0 if the two ind.s are not comparable. - * - */ - public AbstractEAIndividualComparator() { - this("", -1, true); - } - - /** - * Constructor with data key. A data field of the individuals may be used to retrieve - * the double array used for comparison. Both individuals must have a data field with - * the given key and return a double array of the same dimension. Constraints are - * also regarded by default. - * If indyDataKey is null, the default comparison is used. - * - * @param indyDataKey - */ - public AbstractEAIndividualComparator(String indyDataKey) { - this(indyDataKey, -1, true); - } - - /** - * Constructor for a specific fitness criterion in the multi-objective case. - * For comparison, only the given fitness criterion is used if it is >= 0. - * - * @param fitnessCriterion - */ - public AbstractEAIndividualComparator(int fitnessCriterion) { - this("", fitnessCriterion, true); - } - - /** - * Constructor for a specific fitness criterion in the multi-objective case. - * For comparison, only the given fitness criterion is used if it is >= 0. - * If preferFeasible is true, feasible individuals will always be prefered. - * - * @param fitIndex - * @param preferFeasible - */ - public AbstractEAIndividualComparator(int fitIndex, boolean preferFeasible) { - this("", fitIndex, preferFeasible); - } - - @Override - public boolean equals(Object other) { - if (other instanceof AbstractEAIndividualComparator) { - AbstractEAIndividualComparator o = (AbstractEAIndividualComparator)other; - if ((indyDataKey==o.indyDataKey) || (indyDataKey!=null && (indyDataKey.equals(o.indyDataKey)))) { - if ((fitCriterion == o.fitCriterion) && (preferFeasible == o.preferFeasible)) { - return true; - } - } - } - return false; - } - - @Override - public int hashCode() { - return indyDataKey.hashCode()+100+fitCriterion+(preferFeasible ? 7 : 13); - } - - /** - * Generic constructor. - * - * @see #AbstractEAIndividualComparator(int) - * @see #AbstractEAIndividualComparator(String) - * @param indyDataKey - * @param fitnessCriterion - * @param priorizeConstraints - */ - public AbstractEAIndividualComparator(String indDataKey, int fitnessCriterion, boolean preferFeasible) { - this.indyDataKey = indDataKey; - this.fitCriterion = fitnessCriterion; - this.preferFeasible = preferFeasible; - } + // flag whether a data field should be used. + private String indyDataKey = ""; + private int fitCriterion = -1; + private boolean preferFeasible = true; - public AbstractEAIndividualComparator(AbstractEAIndividualComparator other) { - indyDataKey = other.indyDataKey; - fitCriterion = other.fitCriterion; - preferFeasible = other.preferFeasible; - } + /** + * Comparator implementation which compares two individuals based on their fitness. + * The default version calls compares based on dominance with priority of feasibility if there are constraints. + * It assigns -1 if first is better, 1 if second is better, 0 if the two ind.s are not comparable. + */ + public AbstractEAIndividualComparator() { + this("", -1, true); + } + + /** + * Constructor with data key. A data field of the individuals may be used to retrieve + * the double array used for comparison. Both individuals must have a data field with + * the given key and return a double array of the same dimension. Constraints are + * also regarded by default. + * If indyDataKey is null, the default comparison is used. + * + * @param indyDataKey + */ + public AbstractEAIndividualComparator(String indyDataKey) { + this(indyDataKey, -1, true); + } + + /** + * Constructor for a specific fitness criterion in the multi-objective case. + * For comparison, only the given fitness criterion is used if it is >= 0. + * + * @param fitnessCriterion + */ + public AbstractEAIndividualComparator(int fitnessCriterion) { + this("", fitnessCriterion, true); + } + + /** + * Constructor for a specific fitness criterion in the multi-objective case. + * For comparison, only the given fitness criterion is used if it is >= 0. + * If preferFeasible is true, feasible individuals will always be prefered. + * + * @param fitIndex + * @param preferFeasible + */ + public AbstractEAIndividualComparator(int fitIndex, boolean preferFeasible) { + this("", fitIndex, preferFeasible); + } @Override - public Object clone() { - return new AbstractEAIndividualComparator(this); - } - - /** - * Compare two individuals, return -1 if the first is dominant, 1 if the second is dominant, 0 if they - * are not comparable. - * - * @param o1 the first AbstractEAIndividual to compare - * @param o2 the second AbstractEAIndividual to compare - * @return -1 if the first is dominant, 1 if the second is dominant, otherwise 0 - */ + public boolean equals(Object other) { + if (other instanceof AbstractEAIndividualComparator) { + AbstractEAIndividualComparator o = (AbstractEAIndividualComparator) other; + if ((indyDataKey == o.indyDataKey) || (indyDataKey != null && (indyDataKey.equals(o.indyDataKey)))) { + if ((fitCriterion == o.fitCriterion) && (preferFeasible == o.preferFeasible)) { + return true; + } + } + } + return false; + } + @Override - public int compare(Object o1, Object o2) { - boolean o1domO2, o2domO1; - - if (preferFeasible) { // check constraint violation first? - int constrViolComp = ((AbstractEAIndividual) o1).compareConstraintViolation((AbstractEAIndividual) o2); - if (constrViolComp>0) { - return -1; - } - else if (constrViolComp < 0) { - return 1; - } - // otherwise both do not violate, so regard fitness - } - if (indyDataKey != null && (indyDataKey.length()>0)) { // check specific key - double[] fit1 = (double[])((AbstractEAIndividual)o1).getData(indyDataKey); - double[] fit2 = (double[])((AbstractEAIndividual)o2).getData(indyDataKey); - if ((fit1==null) || (fit2==null)) { - throw new RuntimeException("Unknown individual data key " + indyDataKey + ", unable to compare individuals ("+this.getClass().getSimpleName()+")"); - } - if (fitCriterion < 0) { - o1domO2 = AbstractEAIndividual.isDominatingFitness(fit1, fit2); - o2domO1 = AbstractEAIndividual.isDominatingFitness(fit2, fit1); - } else { - if (fit1[fitCriterion] == fit2[fitCriterion]) { - return 0; - } - else { - return (fit1[fitCriterion] < fit2[fitCriterion]) ? -1 : 1; - } - } - } else { - if (fitCriterion < 0) { - o1domO2 = ((AbstractEAIndividual) o1).isDominating((AbstractEAIndividual) o2); - o2domO1 = ((AbstractEAIndividual) o2).isDominating((AbstractEAIndividual) o1); - } else { - if (((AbstractEAIndividual) o1).getFitness()[fitCriterion] == ((AbstractEAIndividual) o2).getFitness()[fitCriterion]) { - return 0; - } - return (((AbstractEAIndividual) o1).getFitness()[fitCriterion] < ((AbstractEAIndividual) o2).getFitness()[fitCriterion]) ? -1 : 1; - } - } - if (o1domO2 ^ o2domO1) { - return (o1domO2 ? -1 : 1); - } // they are comparable - else { - return 0; - } // they are not comparable - } + public int hashCode() { + return indyDataKey.hashCode() + 100 + fitCriterion + (preferFeasible ? 7 : 13); + } - public String getIndyDataKey() { - return indyDataKey; - } - public void setIndyDataKey(String indyDataKey) { - this.indyDataKey = indyDataKey; - } - public String indyDataKeyTipText() { - return "A String can be given which retrievies individual properties based on which the comparison is performed."; - } + /** + * Generic constructor. + * + * @param indyDataKey + * @param fitnessCriterion + * @param priorizeConstraints + * @see #AbstractEAIndividualComparator(int) + * @see #AbstractEAIndividualComparator(String) + */ + public AbstractEAIndividualComparator(String indDataKey, int fitnessCriterion, boolean preferFeasible) { + this.indyDataKey = indDataKey; + this.fitCriterion = fitnessCriterion; + this.preferFeasible = preferFeasible; + } - public int getFitCriterion() { - return fitCriterion; - } - public void setFitCriterion(int fitCriterion) { - this.fitCriterion = fitCriterion; - } - public String fitCriterionTipText() { - return "If -1, dominance is used, otherwise the indexed fitness criterion (for multiobjective problems)"; - } - - public boolean isPreferFeasible() { - return preferFeasible; - } - public void setPreferFeasible(boolean priorConst) { - preferFeasible = priorConst; - } - public String preferFeasibleTipText() { - return "Activate preference of feasible individuals in any comparison acc. to Deb's rules."; - } - - public static String globalInfo() { - return "A comparator class for general EA individuals. Compares individuals based on their fitness in context of minimization."; - } - public String getName() { - return "IndividualComparator"; - } + public AbstractEAIndividualComparator(AbstractEAIndividualComparator other) { + indyDataKey = other.indyDataKey; + fitCriterion = other.fitCriterion; + preferFeasible = other.preferFeasible; + } + + @Override + public Object clone() { + return new AbstractEAIndividualComparator(this); + } + + /** + * Compare two individuals, return -1 if the first is dominant, 1 if the second is dominant, 0 if they + * are not comparable. + * + * @param o1 the first AbstractEAIndividual to compare + * @param o2 the second AbstractEAIndividual to compare + * @return -1 if the first is dominant, 1 if the second is dominant, otherwise 0 + */ + @Override + public int compare(Object o1, Object o2) { + boolean o1domO2, o2domO1; + + if (preferFeasible) { // check constraint violation first? + int constrViolComp = ((AbstractEAIndividual) o1).compareConstraintViolation((AbstractEAIndividual) o2); + if (constrViolComp > 0) { + return -1; + } else if (constrViolComp < 0) { + return 1; + } + // otherwise both do not violate, so regard fitness + } + if (indyDataKey != null && (indyDataKey.length() > 0)) { // check specific key + double[] fit1 = (double[]) ((AbstractEAIndividual) o1).getData(indyDataKey); + double[] fit2 = (double[]) ((AbstractEAIndividual) o2).getData(indyDataKey); + if ((fit1 == null) || (fit2 == null)) { + throw new RuntimeException("Unknown individual data key " + indyDataKey + ", unable to compare individuals (" + this.getClass().getSimpleName() + ")"); + } + if (fitCriterion < 0) { + o1domO2 = AbstractEAIndividual.isDominatingFitness(fit1, fit2); + o2domO1 = AbstractEAIndividual.isDominatingFitness(fit2, fit1); + } else { + if (fit1[fitCriterion] == fit2[fitCriterion]) { + return 0; + } else { + return (fit1[fitCriterion] < fit2[fitCriterion]) ? -1 : 1; + } + } + } else { + if (fitCriterion < 0) { + o1domO2 = ((AbstractEAIndividual) o1).isDominating((AbstractEAIndividual) o2); + o2domO1 = ((AbstractEAIndividual) o2).isDominating((AbstractEAIndividual) o1); + } else { + if (((AbstractEAIndividual) o1).getFitness()[fitCriterion] == ((AbstractEAIndividual) o2).getFitness()[fitCriterion]) { + return 0; + } + return (((AbstractEAIndividual) o1).getFitness()[fitCriterion] < ((AbstractEAIndividual) o2).getFitness()[fitCriterion]) ? -1 : 1; + } + } + if (o1domO2 ^ o2domO1) { + return (o1domO2 ? -1 : 1); + } // they are comparable + else { + return 0; + } // they are not comparable + } + + public String getIndyDataKey() { + return indyDataKey; + } + + public void setIndyDataKey(String indyDataKey) { + this.indyDataKey = indyDataKey; + } + + public String indyDataKeyTipText() { + return "A String can be given which retrievies individual properties based on which the comparison is performed."; + } + + public int getFitCriterion() { + return fitCriterion; + } + + public void setFitCriterion(int fitCriterion) { + this.fitCriterion = fitCriterion; + } + + public String fitCriterionTipText() { + return "If -1, dominance is used, otherwise the indexed fitness criterion (for multiobjective problems)"; + } + + public boolean isPreferFeasible() { + return preferFeasible; + } + + public void setPreferFeasible(boolean priorConst) { + preferFeasible = priorConst; + } + + public String preferFeasibleTipText() { + return "Activate preference of feasible individuals in any comparison acc. to Deb's rules."; + } + + public static String globalInfo() { + return "A comparator class for general EA individuals. Compares individuals based on their fitness in context of minimization."; + } + + public String getName() { + return "IndividualComparator"; + } } diff --git a/src/eva2/optimization/individuals/ESIndividualBinaryData.java b/src/eva2/optimization/individuals/ESIndividualBinaryData.java index 040992d9..d5047a50 100644 --- a/src/eva2/optimization/individuals/ESIndividualBinaryData.java +++ b/src/eva2/optimization/individuals/ESIndividualBinaryData.java @@ -6,10 +6,12 @@ import eva2.optimization.operator.mutation.MutateESGlobal; import eva2.optimization.problems.InterfaceHasInitRange; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; -/** This individual uses a real-valued genotype to code for binary values, either +/** + * This individual uses a real-valued genotype to code for binary values, either * by using a threshold value of by interpreting the double value as probability. * Created by IntelliJ IDEA. * User: streiche @@ -19,40 +21,40 @@ import java.util.BitSet; */ public class ESIndividualBinaryData extends AbstractEAIndividual implements InterfaceESIndividual, InterfaceDataTypeBinary, java.io.Serializable { - private BitSet m_Phenotype = new BitSet(); - private double[] m_Genotype; - private boolean m_UseHardSwitch = false; - private double[][] m_Range; + private BitSet m_Phenotype = new BitSet(); + private double[] m_Genotype; + private boolean m_UseHardSwitch = false; + private double[][] m_Range; public ESIndividualBinaryData() { this.mutationProbability = 1.0; this.mutationOperator = new MutateESGlobal(); this.crossoverProbability = 0.5; this.crossoverOperator = new CrossoverESDefault(); - this.m_Genotype = new double[1]; - this.m_Range = new double[1][2]; - this.m_Range[0][0] = 0; - this.m_Range[0][1] = 1; + this.m_Genotype = new double[1]; + this.m_Range = new double[1][2]; + this.m_Range[0][0] = 0; + this.m_Range[0][1] = 1; } public ESIndividualBinaryData(ESIndividualBinaryData individual) { if (individual.m_Phenotype != null) { - this.m_Phenotype = (BitSet) individual.m_Phenotype.clone(); + this.m_Phenotype = (BitSet) individual.m_Phenotype.clone(); } - this.m_Genotype = new double[individual.m_Genotype.length]; - this.m_Range = new double[individual.m_Genotype.length][2]; + this.m_Genotype = new double[individual.m_Genotype.length]; + this.m_Range = new double[individual.m_Genotype.length][2]; for (int i = 0; i < this.m_Genotype.length; i++) { - this.m_Genotype[i] = individual.m_Genotype[i]; - this.m_Range[i][0] = individual.m_Range[i][0]; - this.m_Range[i][1] = individual.m_Range[i][1]; + this.m_Genotype[i] = individual.m_Genotype[i]; + this.m_Range[i][0] = individual.m_Range[i][0]; + this.m_Range[i][1] = individual.m_Range[i][1]; } - this.m_UseHardSwitch = individual.m_UseHardSwitch; + this.m_UseHardSwitch = individual.m_UseHardSwitch; // cloning the members of AbstractEAIndividual this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -70,8 +72,10 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return (Object) new ESIndividualBinaryData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -104,20 +108,24 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte /************************************************************************************ * InterfaceDataTypeBinary methods */ - /** This method allows you to request a certain amount of binary data - * @param length The lenght of the BitSet that is to be optimized + /** + * This method allows you to request a certain amount of binary data + * + * @param length The lenght of the BitSet that is to be optimized */ @Override public void setBinaryDataLength(int length) { - this.m_Genotype = new double[length]; - this.m_Range = new double[length][2]; + this.m_Genotype = new double[length]; + this.m_Range = new double[length][2]; for (int i = 0; i < this.m_Range.length; i++) { this.m_Range[i][0] = 0; this.m_Range[i][1] = 1; } } - /** This method returns the length of the binary data set + /** + * This method returns the length of the binary data set + * * @return The number of bits stored */ @Override @@ -125,7 +133,9 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Genotype.length; } - /** This method allows you to read the binary data + /** + * This method allows you to read the binary data + * * @return BitSet representing the binary data. */ @Override @@ -152,8 +162,10 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Phenotype; } - /** This method allows you to read the binary data without + /** + * This method allows you to read the binary data without * an update from the genotype + * * @return BitSet representing the binary data. */ @Override @@ -161,16 +173,21 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Phenotype; } - /** This method allows you to set the binary data. - * @param binaryData The new binary data. + /** + * This method allows you to set the binary data. + * + * @param binaryData The new binary data. */ @Override public void SetBinaryPhenotype(BitSet binaryData) { this.m_Phenotype = binaryData; } - /** This method allows you to set the binary data, this can be used for + + /** + * This method allows you to set the binary data, this can be used for * memetic algorithms. - * @param binaryData The new binary data. + * + * @param binaryData The new binary data. */ @Override public void SetBinaryGenotype(BitSet binaryData) { @@ -178,16 +195,14 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte for (int i = 0; i < this.m_Genotype.length; i++) { if (this.m_UseHardSwitch) { if (binaryData.get(i)) { - this.m_Genotype[i] = RNG.randomDouble(0.55,1.0); - } - else { - this.m_Genotype[i] = RNG.randomDouble(0.0,0.45); + this.m_Genotype[i] = RNG.randomDouble(0.55, 1.0); + } else { + this.m_Genotype[i] = RNG.randomDouble(0.0, 0.45); } } else { if (binaryData.get(i)) { this.m_Genotype[i] = 0.9; - } - else { + } else { this.m_Genotype[i] = 0.1; } } @@ -197,15 +212,17 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte /************************************************************************************ * AbstractEAIndividual methods */ - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof BitSet) { - BitSet bs = (BitSet) obj; + BitSet bs = (BitSet) obj; this.SetBinaryGenotype(bs); } else { this.defaultInit(opt); @@ -215,8 +232,10 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte this.crossoverOperator.init(this, opt); } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override @@ -243,8 +262,10 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte /************************************************************************************ * InterfaceESIndividual methods */ - - /** This method will allow the user to read the ES 'genotype' + + /** + * This method will allow the user to read the ES 'genotype' + * * @return BitSet */ @Override @@ -252,8 +273,10 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Genotype; } - /** This method will allow the user to set the current ES 'genotype'. - * @param b The new genotype of the Individual + /** + * This method will allow the user to set the current ES 'genotype'. + * + * @param b The new genotype of the Individual */ @Override public void SetDGenotype(double[] b) { @@ -277,7 +300,9 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte // this.m_Range = range; // } - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ @Override @@ -285,27 +310,29 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Range; } - /** This method performs a simple one element mutation on the double vector + /** + * This method performs a simple one element mutation on the double vector */ @Override public void defaultMutate() { - ESIndividualDoubleData.defaultMutate(m_Genotype, m_Range); + ESIndividualDoubleData.defaultMutate(m_Genotype, m_Range); } @Override public void defaultInit(InterfaceOptimizationProblem prob) { - if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange)prob).getInitRange()!=null)) { - ESIndividualDoubleData.defaultInit(m_Genotype, (double[][])((InterfaceHasInitRange)prob).getInitRange()); - } - else { + if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange) prob).getInitRange() != null)) { + ESIndividualDoubleData.defaultInit(m_Genotype, (double[][]) ((InterfaceHasInitRange) prob).getInitRange()); + } else { ESIndividualDoubleData.defaultInit(m_Genotype, m_Range); } } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -313,23 +340,29 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte return "ES individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is an ES individual adopted to optimize binary values."; } - /** This method will toggle between genotype interpretation as bit probability and + /** + * This method will toggle between genotype interpretation as bit probability and * fixed switch. - * @param b the Switch. + * + * @param b the Switch. */ public void setToggleInterpretation(boolean b) { this.m_UseHardSwitch = b; } + public boolean getToggleInterpretation() { return this.m_UseHardSwitch; } + public String toggleInterpretationTipText() { return "Toggle between interpretation as probability or if(>0.5)."; } diff --git a/src/eva2/optimization/individuals/ESIndividualDoubleData.java b/src/eva2/optimization/individuals/ESIndividualDoubleData.java index ca11bf39..63f4a9c9 100644 --- a/src/eva2/optimization/individuals/ESIndividualDoubleData.java +++ b/src/eva2/optimization/individuals/ESIndividualDoubleData.java @@ -11,7 +11,8 @@ import eva2.tools.EVAERROR; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; -/** This individual uses a real-valued genotype to code for double values. +/** + * This individual uses a real-valued genotype to code for double values. * Created by IntelliJ IDEA. * User: streiche * Date: 24.03.2003 @@ -20,40 +21,40 @@ import eva2.tools.math.RNG; */ public class ESIndividualDoubleData extends AbstractEAIndividual implements InterfaceESIndividual, InterfaceDataTypeDouble, java.io.Serializable { - private double[] m_Genotype; - private double[] m_Phenotype; - private double[][] m_Range; + private double[] m_Genotype; + private double[] m_Phenotype; + private double[][] m_Range; public ESIndividualDoubleData() { this.mutationProbability = 1.0; this.mutationOperator = new MutateESGlobal(0.2, MutateESCrossoverTypeEnum.intermediate); this.crossoverProbability = 0.5; this.crossoverOperator = new CrossoverESDefault(); - this.m_Genotype = new double[1]; - this.m_Phenotype = null; - this.m_Range = new double[1][2]; - this.m_Range[0][0] = -10; - this.m_Range[0][1] = 10; + this.m_Genotype = new double[1]; + this.m_Phenotype = null; + this.m_Range = new double[1][2]; + this.m_Range[0][0] = -10; + this.m_Range[0][1] = 10; } public ESIndividualDoubleData(ESIndividualDoubleData individual) { if (individual.m_Phenotype != null) { - this.m_Phenotype = new double[individual.m_Phenotype.length]; + this.m_Phenotype = new double[individual.m_Phenotype.length]; System.arraycopy(individual.m_Phenotype, 0, this.m_Phenotype, 0, this.m_Phenotype.length); } - this.m_Genotype = new double[individual.m_Genotype.length]; - this.m_Range = new double[individual.m_Range.length][2]; + this.m_Genotype = new double[individual.m_Genotype.length]; + this.m_Range = new double[individual.m_Range.length][2]; for (int i = 0; i < this.m_Genotype.length; i++) { - this.m_Genotype[i] = individual.m_Genotype[i]; - this.m_Range[i][0] = individual.m_Range[i][0]; - this.m_Range[i][1] = individual.m_Range[i][1]; + this.m_Genotype[i] = individual.m_Genotype[i]; + this.m_Range[i][0] = individual.m_Range[i][0]; + this.m_Range[i][1] = individual.m_Range[i][1]; } // cloning the members of AbstractEAIndividual this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -71,8 +72,10 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte return (Object) new ESIndividualDoubleData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -111,29 +114,31 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte /************************************************************************************ * InterfaceDataTypeDouble methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setDoubleDataLength (int length) { - double[] newDesPa = new double[length]; - double[][] newRange = new double[length][2]; + public void setDoubleDataLength(int length) { + double[] newDesPa = new double[length]; + double[][] newRange = new double[length][2]; // copy the old values for the decision parameters and the range for (int i = 0; ((i < newDesPa.length) && (i < this.m_Genotype.length)); i++) { - newDesPa[i] = this.m_Genotype[i]; - newRange[i][0] = this.m_Range[i][0]; - newRange[i][1] = this.m_Range[i][1]; + newDesPa[i] = this.m_Genotype[i]; + newRange[i][0] = this.m_Range[i][0]; + newRange[i][1] = this.m_Range[i][1]; } // if the new length is bigger than the last value fills the extra elements for (int i = this.m_Genotype.length; (i < newDesPa.length); i++) { - newDesPa[i] = this.m_Genotype[this.m_Genotype.length-1]; - newRange[i][0] = this.m_Range[this.m_Genotype.length-1][0]; - newRange[i][1] = this.m_Range[this.m_Genotype.length-1][1]; + newDesPa[i] = this.m_Genotype[this.m_Genotype.length - 1]; + newRange[i][0] = this.m_Range[this.m_Genotype.length - 1][0]; + newRange[i][1] = this.m_Range[this.m_Genotype.length - 1][1]; } - this.m_Genotype = newDesPa; - this.m_Range = newRange; + this.m_Genotype = newDesPa; + this.m_Range = newRange; this.m_Phenotype = null; // mark as invalid // changed 28.08.03 by request of Spieth @@ -145,7 +150,9 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte // } } - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of bits stored */ @Override @@ -153,10 +160,12 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Genotype.length; } - /** This method will set the range of the double attributes. If range.length + /** + * This method will set the range of the double attributes. If range.length * does not equal doubledata.length only range[i] will be used to set all * ranges. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ @Override public void SetDoubleRange(double[][] range) { @@ -170,7 +179,9 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte } } - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ @Override @@ -178,56 +189,61 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Range; } - /** This method allows you to read the double data. A new phenotype array is allocated + /** + * This method allows you to read the double data. A new phenotype array is allocated * and the genotype copied. + * * @return BitSet representing the double data. */ @Override public double[] getDoubleData() { - // since the phenotype is set to null if the genotype is changed, - // it should now be save to only perform the copy if the phenotype is null - if (this.m_Phenotype!=null) { + // since the phenotype is set to null if the genotype is changed, + // it should now be save to only perform the copy if the phenotype is null + if (this.m_Phenotype != null) { return m_Phenotype; - } - else { - this.m_Phenotype = new double[this.m_Genotype.length]; + } else { + this.m_Phenotype = new double[this.m_Genotype.length]; System.arraycopy(this.m_Genotype, 0, this.m_Phenotype, 0, this.m_Genotype.length); return this.m_Phenotype; } } - - /** + + /** * This method allows you to read the double data without * an update from the genotype. + * * @return double[] representing the double data. */ @Override public double[] getDoubleDataWithoutUpdate() { - if (m_Phenotype==null) { + if (m_Phenotype == null) { return getDoubleData(); - } - else { + } else { return this.m_Phenotype; } } - /** This method allows you to set the phenotype double data. To change the genotype, + /** + * This method allows you to set the phenotype double data. To change the genotype, * use SetDoubleDataLamarckian(). - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetDoublePhenotype(double[] doubleData) { this.m_Phenotype = doubleData; } - /** This method allows you to set the genotype data, this can be used for + /** + * This method allows you to set the genotype data, this can be used for * memetic algorithms. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetDoubleGenotype(double[] doubleData) { // this.SetDoublePhenotype(doubleData); - this.SetDoublePhenotype(null); // tag it as invalid + this.SetDoublePhenotype(null); // tag it as invalid this.m_Genotype = new double[doubleData.length]; System.arraycopy(doubleData, 0, this.m_Genotype, 0, doubleData.length); } @@ -235,8 +251,10 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte /************************************************************************************ * AbstractEAIndividual methods */ - /** This method will allow a default initialisation of the individual - * @param opt The optimization problem that is to be solved. + /** + * This method will allow a default initialisation of the individual + * + * @param opt The optimization problem that is to be solved. */ @Override public void init(InterfaceOptimizationProblem opt) { @@ -247,15 +265,17 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte } } - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof double[]) { - double[] bs = (double[]) obj; + double[] bs = (double[]) obj; if (bs.length != this.m_Genotype.length) { System.out.println("Init value and requested length doesn't match!"); } @@ -268,28 +288,30 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte this.crossoverOperator.init(this, opt); } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override public String getStringRepresentation() { - StringBuilder strB = new StringBuilder(200); - strB.append("ESIndividual coding double: (Fitness {"); + StringBuilder strB = new StringBuilder(200); + strB.append("ESIndividual coding double: (Fitness {"); for (int i = 0; i < this.fitness.length; i++) { - strB.append(this.fitness[i]); - strB.append(";"); + strB.append(this.fitness[i]); + strB.append(";"); } - strB.append("}/SelProb{"); - + strB.append("}/SelProb{"); + for (int i = 0; i < this.selectionProbability.length; i++) { - strB.append(this.selectionProbability[i]); - strB.append(";"); + strB.append(this.selectionProbability[i]); + strB.append(";"); } strB.append("}) Value: ["); for (int i = 0; i < this.m_Genotype.length; i++) { - strB.append(this.m_Genotype[i]); - strB.append("; "); + strB.append(this.m_Genotype[i]); + strB.append("; "); } strB.append("]"); return strB.toString(); @@ -298,7 +320,9 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte /************************************************************************************ * InterfaceESIndividual methods */ - /** This method will allow the user to read the ES 'genotype' + /** + * This method will allow the user to read the ES 'genotype' + * * @return BitSet */ @Override @@ -306,13 +330,15 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Genotype; } - /** This method will allow the user to set the current ES 'genotype'. - * @param b The new genotype of the Individual + /** + * This method will allow the user to set the current ES 'genotype'. + * + * @param b The new genotype of the Individual */ @Override public void SetDGenotype(double[] b) { this.m_Genotype = b; - this.m_Phenotype=null; // mark it as invalid + this.m_Phenotype = null; // mark it as invalid for (int i = 0; i < this.m_Genotype.length; i++) { if (this.m_Genotype[i] < this.m_Range[i][0]) { this.m_Genotype[i] = this.m_Range[i][0]; @@ -322,34 +348,37 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte } } } - - /** This method will allow the user to set the current ES 'genotype'. - * @param b The new genotype of the Individual + + /** + * This method will allow the user to set the current ES 'genotype'. + * + * @param b The new genotype of the Individual */ public void SetDGenotypeNocheck(double[] b) { - this.m_Phenotype = null; // mark it as invalid + this.m_Phenotype = null; // mark it as invalid this.m_Genotype = b; } - - /** This method performs a simple one element mutation on the double vector + + /** + * This method performs a simple one element mutation on the double vector */ @Override public void defaultMutate() { - ESIndividualDoubleData.defaultMutate(this.m_Genotype, this.m_Range); - m_Phenotype=null; // mark it as invalid + ESIndividualDoubleData.defaultMutate(this.m_Genotype, this.m_Range); + m_Phenotype = null; // mark it as invalid } /** * Helper method for default ES mutation. A single, uniformly chosen double entry - * is mutated with a gaussian value. - * If the range constraint is violated, the value is set on the bound. - * + * is mutated with a gaussian value. + * If the range constraint is violated, the value is set on the bound. + * * @param genotype * @param range */ public static void defaultMutate(double[] genotype, double[][] range) { - int mutationIndex = RNG.randomInt(0, genotype.length-1); - genotype[mutationIndex] += ((range[mutationIndex][1] - range[mutationIndex][0])/2)*RNG.gaussianDouble(0.05f); + int mutationIndex = RNG.randomInt(0, genotype.length - 1); + genotype[mutationIndex] += ((range[mutationIndex][1] - range[mutationIndex][0]) / 2) * RNG.gaussianDouble(0.05f); if (genotype[mutationIndex] < range[mutationIndex][0]) { genotype[mutationIndex] = range[mutationIndex][0]; } @@ -357,22 +386,21 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte genotype[mutationIndex] = range[mutationIndex][1]; } } - + @Override public void defaultInit(InterfaceOptimizationProblem prob) { - if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange)prob).getInitRange()!=null)) { - ESIndividualDoubleData.defaultInit(m_Genotype, (double[][])((InterfaceHasInitRange)prob).getInitRange()); - } - else { + if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange) prob).getInitRange() != null)) { + ESIndividualDoubleData.defaultInit(m_Genotype, (double[][]) ((InterfaceHasInitRange) prob).getInitRange()); + } else { ESIndividualDoubleData.defaultInit(m_Genotype, m_Range); } - m_Phenotype = null; // mark as invalid + m_Phenotype = null; // mark as invalid } - + /** * Helper method for initialization. The genotype is distributed uniformly * within the given range. - * + * * @param genotype * @param range */ @@ -381,12 +409,14 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte genotype[i] = RNG.randomDouble(range[i][0], range[i][1]); } } - + /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -394,13 +424,15 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte return "ES individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is an ES individual suited to optimize double values."; } - + // public String toString() { // String str = "Ind " + m_Genotype[0]; // for (int i=1; i biggest) { - biggest = perm[p][i]; - } - if (perm[p][i] < smallest) { - smallest = perm[p][i]; - } - this.m_Range[p][i][0] = 0; - this.m_Range[p][i][1] = 1; - } - for (int i = 0; i < this.m_Genotype[p].length; i++) { - this.m_Genotype[p][i] = (perm[p][i] - smallest)/(double)biggest; - } - } - - - } - - @Override - public int[][] getPermutationData() { - this.m_Phenotype = new int[this.m_Genotype.length][]; - for (int p = 0; p < m_Genotype.length; p++) { - this.m_Phenotype[p] = new int[m_Genotype[p].length]; - boolean notValid = true; - while (notValid) { - notValid = false; - for (int i = 0; i < this.m_Genotype[p].length; i++) { - for (int j = 0; j < this.m_Genotype[p].length; j++) { - if ((i != j) && (this.m_Genotype[p][i] == this.m_Genotype[p][j])) { - notValid = true; - this.m_Genotype[p][j] = RNG.randomDouble(0, 1); - } - } - } - - } - for (int i = 0; i < this.m_Genotype[p].length; i++) { - for (int j = 0; j < this.m_Genotype[p].length; j++) { - if (this.m_Genotype[p][i] > this.m_Genotype[p][j]) { - this.m_Phenotype[p][i]++; - } - } - } - } - return this.m_Phenotype; - } - - /** This method allows you to read the permutation data without - * an update from the genotype - * @return int[] representing the permutation. - */ - @Override - public int[][] getPermutationDataWithoutUpdate() { - return this.m_Phenotype; - } - - public int[] getFirstindex() { - return firstindex; - } - @Override - public void setFirstindex(int[] firstindex) { - this.firstindex = firstindex; - } - - /************************************************************************************ - * AbstractEAIndividual methods - */ - - /** This method will init the individual with a given value for the - * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. - */ - @Override - public void initByValue(Object obj, InterfaceOptimizationProblem opt) { - if (obj instanceof int[][]) { - int[][] bs = (int[][]) obj; - if (bs.length != this.m_Genotype.length) { - System.out.println("Init value and requested length doesn't match!"); - } - this.SetPermutationGenotype(bs); - } else { - this.defaultInit(opt); - System.out.println("Initial value for ESIndividualPermutationData is not int[]!"); - } - this.mutationOperator.init(this, opt); - this.crossoverOperator.init(this, opt); - } - - /** This method will return a string description of the GAIndividal - * noteably the Genotype. - * @return A descriptive string - */ - @Override - public String getStringRepresentation() { - String result = ""; - result += "ESIndividual coding permutation: ("; - result += "Fitness {"; - for (int i = 0; i < this.fitness.length; i++) { - result += this.fitness[i] + ";"; + public ESIndividualPermutationData(ESIndividualPermutationData individual) { + if (individual.m_Phenotype != null) { + this.m_Phenotype = new int[individual.m_Phenotype.length][]; + for (int i = 0; i < m_Phenotype.length; i++) { + this.m_Phenotype[i] = new int[individual.m_Phenotype[i].length]; + System.arraycopy(individual.m_Phenotype[i], 0, this.m_Phenotype[i], 0, this.m_Phenotype[i].length); } - result += "}/SelProb{"; - for (int i = 0; i < this.selectionProbability.length; i++) { - result += this.selectionProbability[i] + ";"; + } + + this.firstindex = individual.firstindex; + this.m_Genotype = new double[individual.m_Genotype.length][]; + this.m_Range = new double[individual.m_Genotype.length][][]; + for (int i = 0; i < this.m_Genotype.length; i++) { + // if (individual.m_Phenotype != null) { + + this.m_Genotype[i] = new double[individual.m_Genotype[i].length]; + this.m_Range[i] = new double[individual.m_Genotype[i].length][2]; + for (int j = 0; j < this.m_Genotype[i].length; j++) { + this.m_Genotype[i][j] = individual.m_Genotype[i][j]; + this.m_Range[i][j][0] = individual.m_Range[i][j][0]; + this.m_Range[i][j][1] = individual.m_Range[i][j][1]; + // } } - result += "})\n Value: "; - result += "["; - for (int i = 0; i < this.m_Genotype.length; i++) { - result += this.m_Genotype[i] + "; "; - } - result += "]"; - return result; - } + } - /************************************************************************************ - * InterfaceESIndividual methods - */ - /** This method will allow the user to read the ES 'genotype' - * @return BitSet - */ - @Override - public double[] getDGenotype() { - return mapMatrixToVector(m_Genotype); - } + // cloning the members of AbstractEAIndividual + this.age = individual.age; + this.crossoverOperator = individual.crossoverOperator; + this.crossoverProbability = individual.crossoverProbability; + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); + this.mutationProbability = individual.mutationProbability; + this.selectionProbability = new double[individual.selectionProbability.length]; + for (int i = 0; i < this.selectionProbability.length; i++) { + this.selectionProbability[i] = individual.selectionProbability[i]; + } + this.fitness = new double[individual.fitness.length]; + for (int i = 0; i < this.fitness.length; i++) { + this.fitness[i] = individual.fitness[i]; + } + cloneAEAObjects((AbstractEAIndividual) individual); - - public double[] mapMatrixToVector(double[][] matrix) { - int sumentries = 0; - for (int i = 0; i < matrix.length; i++) { - sumentries += matrix[i].length; - } - double[] res = new double[sumentries]; - int counter = 0; - for (int i = 0; i < matrix.length; i++) { - for (int j = 0; j < matrix[i].length; j++) { - res[counter] = matrix[i][j]; - counter++; - } - } - return res; - } - - public double[][] mapVectorToMatrix(double[] vector, int[] sizes) { - double[][] matrix = new double[sizes.length][]; - int counter = 0; - for (int i = 0; i < sizes.length; i++) { - matrix[i] = new double[sizes[i]]; - for (int j = 0; j < matrix[i].length; j++) { - matrix[i][j] = vector[counter]; - counter++; - } - } - - return matrix; - } - - /** This method will allow the user to set the current ES 'genotype'. - * @param b The new genotype of the Individual - */ - @Override - public void SetDGenotype(double[] b) { - this.m_Genotype = mapVectorToMatrix(b, this.sizePermutation()); - for (int i = 0; i < this.m_Genotype.length; i++) { - for (int j = 0; j < this.m_Genotype[i].length; j++) { - if (this.m_Genotype[i][j] < this.m_Range[i][j][0]) { - this.m_Genotype[i][j] = this.m_Range[i][j][0]; - } - if (this.m_Genotype[i][j] > this.m_Range[i][j][1]) { - this.m_Genotype[i][j] = this.m_Range[i][j][1]; - } - } - } - - - } - - /** This method performs a one element mutation on every permutation coded by a double vector. - */ - @Override - public void defaultMutate() { - for (int i = 0; i < m_Genotype.length; i++) { - ESIndividualDoubleData.defaultMutate(m_Genotype[i], m_Range[i]); - } - } + } @Override - public void defaultInit(InterfaceOptimizationProblem prob) { - double[][][] range = m_Range; - if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange)prob).getInitRange()!=null)) { - range = (double[][][])((InterfaceHasInitRange)prob).getInitRange(); - } - - for (int i = 0; i < this.m_Genotype.length; i++) { - ESIndividualDoubleData.defaultInit(m_Genotype[i], range[i]); - } - } + public Object clone() { + return (Object) new ESIndividualPermutationData(this); + } - /** This method will return the range for all double attributes. - * @return The range array. - */ + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. + * @return boolean if equal true else false. + */ @Override - public double[][] getDoubleRange() { - int sumentries = 0; - for (int i = 0; i < this.m_Range.length; i++) { - sumentries += this.m_Range[i].length; - } - double[][] res = new double[sumentries][2]; - int counter = 0; - for (int i = 0; i < this.m_Range.length; i++) { - for (int j = 0; j < this.m_Range[i].length; j++) { - res[counter][0] = this.m_Range[i][j][0]; - res[counter][1] = this.m_Range[i][j][1]; - counter++; - } - } - return res; - } + public boolean equalGenotypes(AbstractEAIndividual individual) { + if (individual instanceof ESIndividualPermutationData) { + ESIndividualPermutationData indy = (ESIndividualPermutationData) individual; + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if ((this.m_Range == null) || (indy.m_Range == null)) { + return false; + } + if (this.m_Range.length != indy.m_Range.length) { + return false; + } + for (int i = 0; i < this.m_Range.length; i++) { + if (this.m_Genotype[i] != indy.m_Genotype[i]) { + return false; + } + if (this.m_Range[i][0] != indy.m_Range[i][0]) { + return false; + } + if (this.m_Range[i][1] != indy.m_Range[i][1]) { + return false; + } + } + return true; + } else { + return false; + } + } + + /** + * ********************************************************************************* + * InterfaceDataTypePermutation methods + */ - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the - * name to the current object. - * @return The name. - */ @Override - public String getName() { - return "ES individual"; - } + public void setPermutationDataLength(int[] length) { - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "This is an ES individual suited to optimize permutations."; - } + this.m_Genotype = new double[length.length][]; + this.m_Range = new double[length.length][][]; + for (int i = 0; i < this.m_Range.length; i++) { + this.m_Genotype[i] = new double[length[i]]; + } + + for (int i = 0; i < this.m_Range.length; i++) { + + this.m_Range[i] = new double[length[i]][2]; + for (int j = 0; j < this.m_Range[i].length; j++) { + this.m_Range[i][j][0] = 0; + this.m_Range[i][j][1] = 1; + } + } + } + + @Override + public int[] sizePermutation() { + int[] res = new int[m_Genotype.length]; + for (int i = 0; i < m_Genotype.length; i++) { + res[i] = m_Genotype[i].length; + } + return res; + } + + @Override + public void SetPermutationPhenotype(int[][] perm) { + this.m_Phenotype = perm; + this.m_Range = new double[perm.length][][]; + for (int i = 0; i < perm.length; i++) { + this.m_Range[i] = new double[perm[i].length][2]; + for (int j = 0; j < this.m_Range[i].length; j++) { + this.m_Range[i][j][0] = 0; + this.m_Range[i][j][1] = 1; + } + } + + } + + @Override + public void SetPermutationGenotype(int[][] perm) { + this.SetPermutationPhenotype(perm); + + this.m_Genotype = new double[perm.length][]; + this.m_Range = new double[perm.length][][]; + for (int p = 0; p < perm.length; p++) { + int biggest = Integer.MIN_VALUE; + int smallest = Integer.MAX_VALUE; + this.m_Range[p] = new double[perm[p].length][2]; + for (int i = 0; i < perm[p].length; i++) { + if (perm[p][i] > biggest) { + biggest = perm[p][i]; + } + if (perm[p][i] < smallest) { + smallest = perm[p][i]; + } + this.m_Range[p][i][0] = 0; + this.m_Range[p][i][1] = 1; + } + for (int i = 0; i < this.m_Genotype[p].length; i++) { + this.m_Genotype[p][i] = (perm[p][i] - smallest) / (double) biggest; + } + } + + + } + + @Override + public int[][] getPermutationData() { + this.m_Phenotype = new int[this.m_Genotype.length][]; + for (int p = 0; p < m_Genotype.length; p++) { + this.m_Phenotype[p] = new int[m_Genotype[p].length]; + boolean notValid = true; + while (notValid) { + notValid = false; + for (int i = 0; i < this.m_Genotype[p].length; i++) { + for (int j = 0; j < this.m_Genotype[p].length; j++) { + if ((i != j) && (this.m_Genotype[p][i] == this.m_Genotype[p][j])) { + notValid = true; + this.m_Genotype[p][j] = RNG.randomDouble(0, 1); + } + } + } + + } + for (int i = 0; i < this.m_Genotype[p].length; i++) { + for (int j = 0; j < this.m_Genotype[p].length; j++) { + if (this.m_Genotype[p][i] > this.m_Genotype[p][j]) { + this.m_Phenotype[p][i]++; + } + } + } + } + return this.m_Phenotype; + } + + /** + * This method allows you to read the permutation data without + * an update from the genotype + * + * @return int[] representing the permutation. + */ + @Override + public int[][] getPermutationDataWithoutUpdate() { + return this.m_Phenotype; + } + + public int[] getFirstindex() { + return firstindex; + } + + @Override + public void setFirstindex(int[] firstindex) { + this.firstindex = firstindex; + } + + /************************************************************************************ + * AbstractEAIndividual methods + */ + + /** + * This method will init the individual with a given value for the + * phenotype. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. + */ + @Override + public void initByValue(Object obj, InterfaceOptimizationProblem opt) { + if (obj instanceof int[][]) { + int[][] bs = (int[][]) obj; + if (bs.length != this.m_Genotype.length) { + System.out.println("Init value and requested length doesn't match!"); + } + this.SetPermutationGenotype(bs); + } else { + this.defaultInit(opt); + System.out.println("Initial value for ESIndividualPermutationData is not int[]!"); + } + this.mutationOperator.init(this, opt); + this.crossoverOperator.init(this, opt); + } + + /** + * This method will return a string description of the GAIndividal + * noteably the Genotype. + * + * @return A descriptive string + */ + @Override + public String getStringRepresentation() { + String result = ""; + result += "ESIndividual coding permutation: ("; + result += "Fitness {"; + for (int i = 0; i < this.fitness.length; i++) { + result += this.fitness[i] + ";"; + } + result += "}/SelProb{"; + for (int i = 0; i < this.selectionProbability.length; i++) { + result += this.selectionProbability[i] + ";"; + } + result += "})\n Value: "; + result += "["; + for (int i = 0; i < this.m_Genotype.length; i++) { + result += this.m_Genotype[i] + "; "; + } + result += "]"; + return result; + } + + /************************************************************************************ + * InterfaceESIndividual methods + */ + /** + * This method will allow the user to read the ES 'genotype' + * + * @return BitSet + */ + @Override + public double[] getDGenotype() { + return mapMatrixToVector(m_Genotype); + } + + + public double[] mapMatrixToVector(double[][] matrix) { + int sumentries = 0; + for (int i = 0; i < matrix.length; i++) { + sumentries += matrix[i].length; + } + double[] res = new double[sumentries]; + int counter = 0; + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[i].length; j++) { + res[counter] = matrix[i][j]; + counter++; + } + } + return res; + } + + public double[][] mapVectorToMatrix(double[] vector, int[] sizes) { + double[][] matrix = new double[sizes.length][]; + int counter = 0; + for (int i = 0; i < sizes.length; i++) { + matrix[i] = new double[sizes[i]]; + for (int j = 0; j < matrix[i].length; j++) { + matrix[i][j] = vector[counter]; + counter++; + } + } + + return matrix; + } + + /** + * This method will allow the user to set the current ES 'genotype'. + * + * @param b The new genotype of the Individual + */ + @Override + public void SetDGenotype(double[] b) { + this.m_Genotype = mapVectorToMatrix(b, this.sizePermutation()); + for (int i = 0; i < this.m_Genotype.length; i++) { + for (int j = 0; j < this.m_Genotype[i].length; j++) { + if (this.m_Genotype[i][j] < this.m_Range[i][j][0]) { + this.m_Genotype[i][j] = this.m_Range[i][j][0]; + } + if (this.m_Genotype[i][j] > this.m_Range[i][j][1]) { + this.m_Genotype[i][j] = this.m_Range[i][j][1]; + } + } + } + + + } + + /** + * This method performs a one element mutation on every permutation coded by a double vector. + */ + @Override + public void defaultMutate() { + for (int i = 0; i < m_Genotype.length; i++) { + ESIndividualDoubleData.defaultMutate(m_Genotype[i], m_Range[i]); + } + } + + @Override + public void defaultInit(InterfaceOptimizationProblem prob) { + double[][][] range = m_Range; + if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange) prob).getInitRange() != null)) { + range = (double[][][]) ((InterfaceHasInitRange) prob).getInitRange(); + } + + for (int i = 0; i < this.m_Genotype.length; i++) { + ESIndividualDoubleData.defaultInit(m_Genotype[i], range[i]); + } + } + + /** + * This method will return the range for all double attributes. + * + * @return The range array. + */ + @Override + public double[][] getDoubleRange() { + int sumentries = 0; + for (int i = 0; i < this.m_Range.length; i++) { + sumentries += this.m_Range[i].length; + } + double[][] res = new double[sumentries][2]; + int counter = 0; + for (int i = 0; i < this.m_Range.length; i++) { + for (int j = 0; j < this.m_Range[i].length; j++) { + res[counter][0] = this.m_Range[i][j][0]; + res[counter][1] = this.m_Range[i][j][1]; + counter++; + } + } + return res; + } + + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the + * name to the current object. + * + * @return The name. + */ + @Override + public String getName() { + return "ES individual"; + } + + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "This is an ES individual suited to optimize permutations."; + } } diff --git a/src/eva2/optimization/individuals/GAESIndividualBinaryDoubleData.java b/src/eva2/optimization/individuals/GAESIndividualBinaryDoubleData.java index 6acd6052..768aeb17 100644 --- a/src/eva2/optimization/individuals/GAESIndividualBinaryDoubleData.java +++ b/src/eva2/optimization/individuals/GAESIndividualBinaryDoubleData.java @@ -5,9 +5,11 @@ import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; -/** This individual combines a binary and a real-valued phenotype. +/** + * This individual combines a binary and a real-valued phenotype. * Created by IntelliJ IDEA. * User: streiche * Date: 13.05.2003 @@ -16,25 +18,25 @@ import java.util.BitSet; */ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual implements InterfaceDataTypeBinary, InterfaceDataTypeDouble, java.io.Serializable { - private InterfaceDataTypeDouble m_Numbers = new ESIndividualDoubleData(); - private InterfaceDataTypeBinary m_BitSet = new GAIndividualBinaryData(); + private InterfaceDataTypeDouble m_Numbers = new ESIndividualDoubleData(); + private InterfaceDataTypeBinary m_BitSet = new GAIndividualBinaryData(); public GAESIndividualBinaryDoubleData() { this.mutationProbability = 1.0; this.crossoverProbability = 1.0; - this.m_Numbers = new GAIndividualDoubleData(); - this.m_BitSet = new GAIndividualBinaryData(); + this.m_Numbers = new GAIndividualDoubleData(); + this.m_BitSet = new GAIndividualBinaryData(); } public GAESIndividualBinaryDoubleData(GAESIndividualBinaryDoubleData individual) { - this.m_Numbers = (InterfaceDataTypeDouble)((AbstractEAIndividual)individual.getNumbers()).clone(); - this.m_BitSet = (InterfaceDataTypeBinary)((AbstractEAIndividual)individual.getBitSet()).clone(); + this.m_Numbers = (InterfaceDataTypeDouble) ((AbstractEAIndividual) individual.getNumbers()).clone(); + this.m_BitSet = (InterfaceDataTypeBinary) ((AbstractEAIndividual) individual.getBitSet()).clone(); // cloning the members of AbstractEAIndividual this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -52,18 +54,20 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return (Object) new GAESIndividualBinaryDoubleData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GAESIndividualBinaryDoubleData) { - GAESIndividualBinaryDoubleData indy = (GAESIndividualBinaryDoubleData)individual; - if (!((AbstractEAIndividual)this.m_Numbers).equalGenotypes((AbstractEAIndividual)indy.m_Numbers)) { + GAESIndividualBinaryDoubleData indy = (GAESIndividualBinaryDoubleData) individual; + if (!((AbstractEAIndividual) this.m_Numbers).equalGenotypes((AbstractEAIndividual) indy.m_Numbers)) { return false; } - if (!((AbstractEAIndividual)this.m_BitSet).equalGenotypes((AbstractEAIndividual)indy.m_BitSet)) { + if (!((AbstractEAIndividual) this.m_BitSet).equalGenotypes((AbstractEAIndividual) indy.m_BitSet)) { return false; } return true; @@ -72,115 +76,122 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme } } - /** This method will allow a default initialisation of the individual - * @param opt The optimization problem that is to be solved. + /** + * This method will allow a default initialisation of the individual + * + * @param opt The optimization problem that is to be solved. */ @Override public void init(InterfaceOptimizationProblem opt) { - ((AbstractEAIndividual)this.m_Numbers).init(opt); - ((AbstractEAIndividual)this.m_BitSet).init(opt); + ((AbstractEAIndividual) this.m_Numbers).init(opt); + ((AbstractEAIndividual) this.m_BitSet).init(opt); } @Override public void defaultInit(InterfaceOptimizationProblem prob) { - ((AbstractEAIndividual)this.m_Numbers).defaultInit(prob); - ((AbstractEAIndividual)this.m_BitSet).defaultInit(prob); + ((AbstractEAIndividual) this.m_Numbers).defaultInit(prob); + ((AbstractEAIndividual) this.m_BitSet).defaultInit(prob); } - - /** This method will init the individual with a given value for the + + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof Object[]) { - if (((Object[])obj)[0] instanceof double[]) { - ((AbstractEAIndividual)this.m_Numbers).initByValue(((Object[])obj)[0], opt); - ((AbstractEAIndividual)this.m_BitSet).initByValue(((Object[])obj)[1], opt); + if (((Object[]) obj)[0] instanceof double[]) { + ((AbstractEAIndividual) this.m_Numbers).initByValue(((Object[]) obj)[0], opt); + ((AbstractEAIndividual) this.m_BitSet).initByValue(((Object[]) obj)[1], opt); } else { - ((AbstractEAIndividual)this.m_Numbers).initByValue(((Object[])obj)[1], opt); - ((AbstractEAIndividual)this.m_BitSet).initByValue(((Object[])obj)[0], opt); + ((AbstractEAIndividual) this.m_Numbers).initByValue(((Object[]) obj)[1], opt); + ((AbstractEAIndividual) this.m_BitSet).initByValue(((Object[]) obj)[0], opt); } } else { - ((AbstractEAIndividual)this.m_Numbers).init(opt); - ((AbstractEAIndividual)this.m_BitSet).init(opt); + ((AbstractEAIndividual) this.m_Numbers).init(opt); + ((AbstractEAIndividual) this.m_BitSet).init(opt); System.out.println("Initial value for GAESIndividualDoubleData is not suitable!"); } } - /** This method will mutate the individual randomly + /** + * This method will mutate the individual randomly */ @Override public void mutate() { if (RNG.flipCoin(this.mutationProbability)) { - ((AbstractEAIndividual)this.m_Numbers).mutate(); + ((AbstractEAIndividual) this.m_Numbers).mutate(); } if (RNG.flipCoin(this.mutationProbability)) { - ((AbstractEAIndividual)this.m_BitSet).mutate(); + ((AbstractEAIndividual) this.m_BitSet).mutate(); } } @Override public void defaultMutate() { - ((AbstractEAIndividual)this.m_Numbers).defaultMutate(); - ((AbstractEAIndividual)this.m_BitSet).defaultMutate(); + ((AbstractEAIndividual) this.m_Numbers).defaultMutate(); + ((AbstractEAIndividual) this.m_BitSet).defaultMutate(); } - - /** This method will mate the Individual with given other individuals + + /** + * This method will mate the Individual with given other individuals * of the same type. - * @param partners The possible partners + * + * @param partners The possible partners * @return offsprings */ @Override public AbstractEAIndividual[] mateWith(Population partners) { AbstractEAIndividual[] result; if (RNG.flipCoin(this.crossoverProbability)) { - AbstractEAIndividual[] resNum, resBin; - AbstractEAIndividual numTmp, binTmp; - Population numPop, binPop; + AbstractEAIndividual[] resNum, resBin; + AbstractEAIndividual numTmp, binTmp; + Population numPop, binPop; - // String out = "Input: \n"; - // out += this.getSolutionRepresentationFor() + "\n" + partners.getSolutionRepresentationFor(); - // System.out.println(out); + // String out = "Input: \n"; + // out += this.getSolutionRepresentationFor() + "\n" + partners.getSolutionRepresentationFor(); + // System.out.println(out); - numTmp = (AbstractEAIndividual)this.getNumbers(); + numTmp = (AbstractEAIndividual) this.getNumbers(); numPop = new Population(); for (int i = 0; i < partners.size(); i++) { - numPop.add(((GAESIndividualBinaryDoubleData)partners.get(i)).getNumbers()); + numPop.add(((GAESIndividualBinaryDoubleData) partners.get(i)).getNumbers()); } resNum = numTmp.mateWith(numPop); - binTmp = (AbstractEAIndividual)this.getBitSet(); + binTmp = (AbstractEAIndividual) this.getBitSet(); binPop = new Population(); for (int i = 0; i < partners.size(); i++) { - binPop.add(((GAESIndividualBinaryDoubleData)partners.get(i)).getBitSet()); + binPop.add(((GAESIndividualBinaryDoubleData) partners.get(i)).getBitSet()); } resBin = binTmp.mateWith(binPop); result = new GAESIndividualBinaryDoubleData[resNum.length]; for (int i = 0; i < result.length; i++) { result[i] = new GAESIndividualBinaryDoubleData(this); - ((GAESIndividualBinaryDoubleData)result[i]).setNumbers((InterfaceDataTypeDouble)resNum[i]); - ((GAESIndividualBinaryDoubleData)result[i]).setBitSet((InterfaceDataTypeBinary)resBin[i]); + ((GAESIndividualBinaryDoubleData) result[i]).setNumbers((InterfaceDataTypeDouble) resNum[i]); + ((GAESIndividualBinaryDoubleData) result[i]).setBitSet((InterfaceDataTypeBinary) resBin[i]); } - // result = ((AbstractEAIndividual)this.m_Numbers).mateWith(partners); - // AbstractEAIndividual dad = (AbstractEAIndividual)result[0]; - // Population tpartners = new Population(); - // for (int i = 1; i < result.length; i++) tpartners.add(result[i]); - // result = dad.mateWith(tpartners); + // result = ((AbstractEAIndividual)this.m_Numbers).mateWith(partners); + // AbstractEAIndividual dad = (AbstractEAIndividual)result[0]; + // Population tpartners = new Population(); + // for (int i = 1; i < result.length; i++) tpartners.add(result[i]); + // result = dad.mateWith(tpartners); - // out = "Result:\n"; - // for (int i = 0; i < result.length; i++) out += result[i].getSolutionRepresentationFor() + "\n"; - // System.out.println(out); + // out = "Result:\n"; + // for (int i = 0; i < result.length; i++) out += result[i].getSolutionRepresentationFor() + "\n"; + // System.out.println(out); } else { // simply return a number of perfect clones - result = new AbstractEAIndividual[partners.size() +1]; - result[0] = (AbstractEAIndividual)this.clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) this.clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } } for (int i = 0; i < result.length; i++) { @@ -189,31 +200,37 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return result; } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override public String getStringRepresentation() { String result = "This is a hybrid Individual:\n"; - result += "The Numbers Part:\n"+((AbstractEAIndividual)this.m_Numbers).getStringRepresentation(); - result += "\nThe Binarys Part:\n"+((AbstractEAIndividual)this.m_BitSet).getStringRepresentation(); + result += "The Numbers Part:\n" + ((AbstractEAIndividual) this.m_Numbers).getStringRepresentation(); + result += "\nThe Binarys Part:\n" + ((AbstractEAIndividual) this.m_BitSet).getStringRepresentation(); return result; } -/********************************************************************************************************************** - * These are for InterfaceDataTypeDouble - - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * ******************************************************************************************************************* + * These are for InterfaceDataTypeDouble + *

+ * /** This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setDoubleDataLength (int length) { + public void setDoubleDataLength(int length) { this.m_Numbers.setDoubleDataLength(length); this.m_BitSet.setBinaryDataLength(length); } - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of bits stored */ @Override @@ -221,17 +238,21 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return this.m_Numbers.size(); } - /** This method will set the range of the double attributes. + /** + * This method will set the range of the double attributes. * Note: range[d][0] gives the lower bound and range[d] gives the upper bound * for dimension d. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ @Override public void SetDoubleRange(double[][] range) { this.m_Numbers.SetDoubleRange(range); } - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ @Override @@ -239,7 +260,9 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return this.m_Numbers.getDoubleRange(); } - /** This method allows you to read the double data + /** + * This method allows you to read the double data + * * @return BitSet representing the double data. */ @Override @@ -247,8 +270,10 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return this.m_Numbers.getDoubleData(); } - /** This method allows you to read the double data without + /** + * This method allows you to read the double data without * an update from the genotype + * * @return double[] representing the double data. */ @Override @@ -256,8 +281,10 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return this.m_Numbers.getDoubleDataWithoutUpdate(); } - /** This method allows you to set the double data. - * @param doubleData The new double data. + /** + * This method allows you to set the double data. + * + * @param doubleData The new double data. * @see InterfaceDataTypeDouble.SetDoubleData() */ @Override @@ -265,9 +292,11 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme this.m_Numbers.SetDoublePhenotype(doubleData); } - /** This method allows you to set the double data, this can be used for + /** + * This method allows you to set the double data, this can be used for * memetic algorithms. - * @param doubleData The new double data. + * + * @param doubleData The new double data. * @see InterfaceDataTypeDouble.SetDoubleDataLamarckian() */ @Override @@ -275,26 +304,32 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme this.m_Numbers.SetDoubleGenotype(doubleData); } -/********************************************************************************************************************** - * These are for InterfaceDataTypeBinary - - /** This method allows you to request a certain amount of binary data - * @param length The lenght of the BitSet that is to be optimized + /** + * ******************************************************************************************************************* + * These are for InterfaceDataTypeBinary + *

+ * /** This method allows you to request a certain amount of binary data + * + * @param length The lenght of the BitSet that is to be optimized */ @Override - public void setBinaryDataLength (int length) { + public void setBinaryDataLength(int length) { this.m_Numbers.setDoubleDataLength(length); this.m_BitSet.setBinaryDataLength(length); } - /** This method returns the length of the binary data set + /** + * This method returns the length of the binary data set + * * @return The number of bits stored */ public int GetBinaryDataLength() { return this.m_BitSet.size(); } - /** This method allows you to read the binary data + /** + * This method allows you to read the binary data + * * @return BitSet representing the binary data. */ @Override @@ -302,8 +337,10 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return this.m_BitSet.getBinaryData(); } - /** This method allows you to read the binary data without + /** + * This method allows you to read the binary data without * an update from the genotype + * * @return BitSet representing the binary data. */ @Override @@ -311,8 +348,10 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return this.m_BitSet.getBinaryDataWithoutUpdate(); } - /** This method allows you to set the binary data. - * @param binaryData The new binary data. + /** + * This method allows you to set the binary data. + * + * @param binaryData The new binary data. * @see InterfaceDataTypeBinary.SetBinaryData() */ @Override @@ -320,9 +359,11 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme this.m_BitSet.SetBinaryPhenotype(binaryData); } - /** This method allows you to set the binary data, this can be used for + /** + * This method allows you to set the binary data, this can be used for * memetic algorithms. - * @param binaryData The new binary data. + * + * @param binaryData The new binary data. * @see InterfaceBinaryData.SetBinaryDataLamarckian() */ @Override @@ -333,8 +374,10 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -342,34 +385,45 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme return "GA/ES individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a mixed data type combining a BitSet and a real-valued vector."; } - /** This method will allow you to set the inner constants - * @param Numbers The new representation for the inner constants. - */ + /** + * This method will allow you to set the inner constants + * + * @param Numbers The new representation for the inner constants. + */ public void setNumbers(InterfaceDataTypeDouble Numbers) { this.m_Numbers = Numbers; } + public InterfaceDataTypeDouble getNumbers() { return this.m_Numbers; } + public String numbersTipText() { return "Choose the type of inner binary representation to use."; } - /** This method will allow you to set the inner constants - * @param BitSet The new representation for the inner constants. - */ + + /** + * This method will allow you to set the inner constants + * + * @param BitSet The new representation for the inner constants. + */ public void setBitSet(InterfaceDataTypeBinary BitSet) { this.m_BitSet = BitSet; } + public InterfaceDataTypeBinary getBitSet() { return this.m_BitSet; } + public String bitSetTipText() { return "Choose the type of inner real-valued representation to use."; } diff --git a/src/eva2/optimization/individuals/GAIndividualBinaryData.java b/src/eva2/optimization/individuals/GAIndividualBinaryData.java index d6bf016b..1497e635 100644 --- a/src/eva2/optimization/individuals/GAIndividualBinaryData.java +++ b/src/eva2/optimization/individuals/GAIndividualBinaryData.java @@ -7,9 +7,11 @@ import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.operator.mutation.MutateGANBit; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; -/** This individual uses a binary genotype to code for binary values. +/** + * This individual uses a binary genotype to code for binary values. * Created by IntelliJ IDEA. * User: streiche * Date: 24.03.2003 @@ -18,38 +20,38 @@ import java.util.BitSet; */ public class GAIndividualBinaryData extends AbstractEAIndividual implements InterfaceDataTypeBinary, InterfaceGAIndividual, java.io.Serializable { - protected BitSet m_Genotype = new BitSet(); - protected BitSet m_Phenotype = new BitSet(); - protected int m_GenotypeLength; + protected BitSet m_Genotype = new BitSet(); + protected BitSet m_Phenotype = new BitSet(); + protected int m_GenotypeLength; public GAIndividualBinaryData() { this.mutationProbability = 0.1; this.mutationOperator = new MutateGANBit(); this.crossoverProbability = 1.0; this.crossoverOperator = new CrossoverGAGINPoint(); - this.m_GenotypeLength = 20; - this.m_Genotype = new BitSet(); + this.m_GenotypeLength = 20; + this.m_Genotype = new BitSet(); } public GAIndividualBinaryData(int genotypeLen) { - this(); - this.setBinaryDataLength(genotypeLen); + this(); + this.setBinaryDataLength(genotypeLen); } - + public GAIndividualBinaryData(GAIndividualBinaryData individual) { if (individual.m_Phenotype != null) { - this.m_Phenotype = (BitSet) individual.m_Phenotype.clone(); + this.m_Phenotype = (BitSet) individual.m_Phenotype.clone(); } - this.m_GenotypeLength = individual.m_GenotypeLength; + this.m_GenotypeLength = individual.m_GenotypeLength; if (individual.m_Genotype != null) { - this.m_Genotype = (BitSet)individual.m_Genotype.clone(); + this.m_Genotype = (BitSet) individual.m_Genotype.clone(); } // cloning the members of AbstractEAIndividual this.age = individual.age; - this.crossoverOperator = (InterfaceCrossover)individual.crossoverOperator.clone(); + this.crossoverOperator = (InterfaceCrossover) individual.crossoverOperator.clone(); this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -67,8 +69,10 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte return (Object) new GAIndividualBinaryData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -80,7 +84,7 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte } if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { return false; - } + } if (!this.m_Genotype.equals(indy.m_Genotype)) { return false; } @@ -90,12 +94,14 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte } } - /** This method evaluates the GAIndividual as simple minimize number + /** + * This method evaluates the GAIndividual as simple minimize number * of bits problem. + * * @return The number of true bits */ public double defaultEvaulateAsMiniBits() { - double result = 0; + double result = 0; for (int i = 0; i < this.m_GenotypeLength; i++) { if (this.m_Genotype.get(i)) { result++; @@ -107,15 +113,17 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte /************************************************************************************ * AbstractEAIndividual methods */ - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof BitSet) { - BitSet bs = (BitSet) obj; + BitSet bs = (BitSet) obj; this.SetBinaryGenotype(bs); } else { this.defaultInit(opt); @@ -125,9 +133,11 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte this.crossoverOperator.init(this, opt); } - /** This method can be used to read the current fitness of the individual. + /** + * This method can be used to read the current fitness of the individual. * Please note that the fitness can be based on multiple criteria therefore * double[] is used instead of a single double. + * * @return The complete fitness array */ @Override @@ -135,17 +145,17 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte return this.fitness; } - /** + /** * This method will return a string description of the GAIndividal * notably the Genotype. - * + * * @return A descriptive string */ @Override public String getStringRepresentation() { String result = ""; result += "GAIndividual: ("; - result += "Fitness {"; + result += "Fitness {"; for (int i = 0; i < this.fitness.length; i++) { result += this.fitness[i] + ";"; } @@ -156,22 +166,23 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte result += "})\n Value: "; result += "{"; for (int i = 0; i < this.m_GenotypeLength; i++) { - if (i%8==0) { - result+="|"; + if (i % 8 == 0) { + result += "|"; } if (this.m_Genotype.get(i)) { result += "1"; - } - else { + } else { result += "0"; } } result += "}"; - result += "\n Mutation ("+this.mutationProbability +"):" + this.mutationOperator.getStringRepresentation(); + result += "\n Mutation (" + this.mutationProbability + "):" + this.mutationOperator.getStringRepresentation(); return result; } - /** This method allows you to read the binary data + /** + * This method allows you to read the binary data + * * @return BitSet representing the binary data. */ @Override @@ -179,20 +190,22 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Genotype; } - /** + /** * This method allows you to set the binary data, this can be used for * memetic algorithms. - * - * @param binaryData The new binary data. + * + * @param binaryData The new binary data. */ @Override public void SetBGenotype(BitSet binaryData) { this.m_Genotype = binaryData; } - /** This method allows the user to read the length of the genotype. + /** + * This method allows the user to read the length of the genotype. * This may be necessary since BitSet.length only returns the index * of the last significant bit. + * * @return The length of the genotype. */ @Override @@ -205,14 +218,14 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte for (int i = 0; i < this.m_GenotypeLength; i++) { if (RNG.flipCoin(0.5)) { this.m_Genotype.set(i); - } - else { + } else { this.m_Genotype.clear(i); } } } - /** This method performs a simple one point mutation in the genotype + /** + * This method performs a simple one point mutation in the genotype */ @Override public void defaultMutate() { @@ -220,8 +233,7 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte //if (mutationIndex > 28) System.out.println("Mutate: " + this.getSolutionRepresentationFor()); if (this.m_Genotype.get(mutationIndex)) { this.m_Genotype.clear(mutationIndex); - } - else { + } else { this.m_Genotype.set(mutationIndex); } //if (mutationIndex > 28) System.out.println(this.getSolutionRepresentationFor()); @@ -230,15 +242,19 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte /************************************************************************************ * InterfaceDataTypeBinary methods */ - /** This method allows you to request a certain amount of binary data - * @param length The lenght of the BitSet that is to be optimized + /** + * This method allows you to request a certain amount of binary data + * + * @param length The lenght of the BitSet that is to be optimized */ @Override public void setBinaryDataLength(int length) { this.m_GenotypeLength = length; } - /** This method returns the length of the binary data set + /** + * This method returns the length of the binary data set + * * @return The number of bits stored */ @Override @@ -246,17 +262,21 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_GenotypeLength; } - /** This method allows you to read the binary data + /** + * This method allows you to read the binary data + * * @return BitSet representing the binary data. */ @Override public BitSet getBinaryData() { - this.m_Phenotype = (BitSet)this.m_Genotype.clone(); + this.m_Phenotype = (BitSet) this.m_Genotype.clone(); return this.m_Phenotype; } - /** This method allows you to read the binary data without + /** + * This method allows you to read the binary data without * an update from the genotype + * * @return BitSet representing the binary data. */ @Override @@ -264,29 +284,35 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte return this.m_Phenotype; } - /** This method allows you to set the binary data. - * @param binaryData The new binary data. + /** + * This method allows you to set the binary data. + * + * @param binaryData The new binary data. */ @Override public void SetBinaryPhenotype(BitSet binaryData) { this.m_Phenotype = binaryData; } - /** This method allows you to set the binary data, this can be used for + /** + * This method allows you to set the binary data, this can be used for * memetic algorithms. - * @param binaryData The new binary data. + * + * @param binaryData The new binary data. */ @Override public void SetBinaryGenotype(BitSet binaryData) { this.SetBinaryPhenotype(binaryData); - this.m_Genotype =(BitSet)binaryData.clone(); + this.m_Genotype = (BitSet) binaryData.clone(); } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -294,7 +320,9 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte return "GA binary individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/individuals/GAIndividualDoubleData.java b/src/eva2/optimization/individuals/GAIndividualDoubleData.java index 7b697a28..fa38248f 100644 --- a/src/eva2/optimization/individuals/GAIndividualDoubleData.java +++ b/src/eva2/optimization/individuals/GAIndividualDoubleData.java @@ -9,9 +9,11 @@ import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.operator.mutation.MutateGAUniform; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; -/** This individual uses a binary genotype to code for double values +/** + * This individual uses a binary genotype to code for double values * using two alternative encodings. * Created by IntelliJ IDEA. * User: streiche @@ -21,50 +23,50 @@ import java.util.BitSet; */ public class GAIndividualDoubleData extends AbstractEAIndividual implements InterfaceGAIndividual, InterfaceDataTypeDouble, java.io.Serializable { - private double[] m_Phenotype; - private double[][] m_Range; - protected BitSet m_Genotype; - protected int m_GenotypeLength; - private int m_Precision = 32; - private InterfaceGADoubleCoding m_DoubleCoding = new GAStandardCodingDouble(); + private double[] m_Phenotype; + private double[][] m_Range; + protected BitSet m_Genotype; + protected int m_GenotypeLength; + private int m_Precision = 32; + private InterfaceGADoubleCoding m_DoubleCoding = new GAStandardCodingDouble(); public GAIndividualDoubleData() { this.mutationProbability = 0.1; this.mutationOperator = new MutateGAUniform(); this.crossoverProbability = 0.7; this.crossoverOperator = new CrossoverGAGINPoint(); - this.m_Range = new double[1][2]; - this.m_Range[0][0] = -10; - this.m_Range[0][1] = 10; - this.m_GenotypeLength = this.m_Precision; - this.m_Genotype = new BitSet(); + this.m_Range = new double[1][2]; + this.m_Range[0][0] = -10; + this.m_Range[0][1] = 10; + this.m_GenotypeLength = this.m_Precision; + this.m_Genotype = new BitSet(); } public GAIndividualDoubleData(GAIndividualDoubleData individual) { if (individual.m_Phenotype != null) { - this.m_Phenotype = new double[individual.m_Phenotype.length]; + this.m_Phenotype = new double[individual.m_Phenotype.length]; System.arraycopy(individual.m_Phenotype, 0, this.m_Phenotype, 0, this.m_Phenotype.length); } - this.m_GenotypeLength = individual.m_GenotypeLength; - this.m_Genotype = (BitSet) individual.m_Genotype.clone(); - this.m_Range = new double[individual.m_Range.length][2]; + this.m_GenotypeLength = individual.m_GenotypeLength; + this.m_Genotype = (BitSet) individual.m_Genotype.clone(); + this.m_Range = new double[individual.m_Range.length][2]; for (int i = 0; i < this.m_Range.length; i++) { - this.m_Range[i][0] = individual.m_Range[i][0]; - this.m_Range[i][1] = individual.m_Range[i][1]; + this.m_Range[i][0] = individual.m_Range[i][0]; + this.m_Range[i][1] = individual.m_Range[i][1]; } // cloning the members of AbstractEAIndividual this.age = individual.age; - this.crossoverOperator = (InterfaceCrossover)individual.crossoverOperator.clone(); + this.crossoverOperator = (InterfaceCrossover) individual.crossoverOperator.clone(); this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { this.selectionProbability[i] = individual.selectionProbability[i]; } - this.m_Precision = individual.m_Precision; - this.m_DoubleCoding = individual.m_DoubleCoding; + this.m_Precision = individual.m_Precision; + this.m_DoubleCoding = individual.m_DoubleCoding; this.fitness = new double[individual.fitness.length]; for (int i = 0; i < this.fitness.length; i++) { this.fitness[i] = individual.fitness[i]; @@ -77,8 +79,10 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte return (Object) new GAIndividualDoubleData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -91,7 +95,7 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte } if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { return false; - } + } if (!this.m_Genotype.equals(indy.m_Genotype)) { return false; } @@ -112,27 +116,29 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte /************************************************************************************ * InterfaceDataTypeDouble methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setDoubleDataLength (int length) { - double[] newDesPa = new double[length]; - double[][] newRange = new double[length][2]; + public void setDoubleDataLength(int length) { + double[] newDesPa = new double[length]; + double[][] newRange = new double[length][2]; // copy the old values for the decision parameters and the range for (int i = 0; ((i < newDesPa.length) && (i < this.m_Range.length)); i++) { - newRange[i][0] = this.m_Range[i][0]; - newRange[i][1] = this.m_Range[i][1]; + newRange[i][0] = this.m_Range[i][0]; + newRange[i][1] = this.m_Range[i][1]; } // if the new length is bigger than the last value fills the extra elements for (int i = this.m_Range.length; (i < newDesPa.length); i++) { - newRange[i][0] = this.m_Range[this.m_Range.length-1][0]; - newRange[i][1] = this.m_Range[this.m_Range.length-1][1]; + newRange[i][0] = this.m_Range[this.m_Range.length - 1][0]; + newRange[i][1] = this.m_Range[this.m_Range.length - 1][1]; } - this.m_Range = newRange; - this.m_GenotypeLength = length * this.m_Precision; + this.m_Range = newRange; + this.m_GenotypeLength = length * this.m_Precision; // changed 28.08.03 by request of Spieth // this.m_DecisionParameters = new double[length]; @@ -143,7 +149,9 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte // } } - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of bits stored */ @Override @@ -151,10 +159,12 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Range.length; } - /** This method will set the range of the double attributes. If range.length + /** + * This method will set the range of the double attributes. If range.length * does not equal doubledata.length only range[i] will be used to set all * ranges. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ @Override public void SetDoubleRange(double[][] range) { @@ -168,7 +178,9 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte } } - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ @Override @@ -176,7 +188,9 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Range; } - /** This method allows you to read the double data + /** + * This method allows you to read the double data + * * @return BitSet representing the double data. */ @Override @@ -190,9 +204,11 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte } return this.m_Phenotype; } - - /** This method allows you to read the double data without + + /** + * This method allows you to read the double data without * an update from the genotype + * * @return double[] representing the double data. */ @Override @@ -200,18 +216,22 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Phenotype; } - /** This method allows you to set the phenotype data. To change the genotype data, + /** + * This method allows you to set the phenotype data. To change the genotype data, * use SetDoubleDataLamarckian. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetDoublePhenotype(double[] doubleData) { this.m_Phenotype = doubleData; } - /** This method allows you to set the double data, this can be used for + /** + * This method allows you to set the double data, this can be used for * memetic algorithms. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetDoubleGenotype(double[] doubleData) { @@ -221,22 +241,24 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte locus[0] = i * this.m_Precision; locus[1] = this.m_Precision; this.m_DoubleCoding.codeValue(doubleData[i], this.m_Range[i], this.m_Genotype, locus); - } + } } /************************************************************************************ * AbstractEAIndividual methods */ - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof double[]) { - double[] bs = (double[]) obj; + double[] bs = (double[]) obj; if (bs.length != this.m_Range.length) { System.out.println("Init value and requested length doesn't match!"); } @@ -249,8 +271,10 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte this.crossoverOperator.init(this, opt); } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override @@ -276,8 +300,7 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte for (int i = 0; i < this.m_GenotypeLength; i++) { if (this.m_Genotype.get(i)) { result += "1"; - } - else { + } else { result += "0"; } } @@ -289,7 +312,9 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte * InterfaceGAIndividual methods */ - /** This method allows you to read the binary data + /** + * This method allows you to read the binary data + * * @return BitSet representing the binary data. */ @Override @@ -297,18 +322,22 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte return this.m_Genotype; } - /** This method allows you to set the binary data, this can be used for + /** + * This method allows you to set the binary data, this can be used for * memetic algorithms. - * @param binaryData The new binary data. + * + * @param binaryData The new binary data. */ @Override public void SetBGenotype(BitSet binaryData) { this.m_Genotype = binaryData; } - /** This method allows the user to read the length of the genotype. + /** + * This method allows the user to read the length of the genotype. * This may be necessary since BitSet.lenght only returns the index * of the last significat bit. + * * @return The length of the genotype. */ @Override @@ -321,30 +350,31 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte for (int i = 0; i < this.m_GenotypeLength; i++) { if (RNG.flipCoin(0.5)) { this.m_Genotype.set(i); - } - else { + } else { this.m_Genotype.clear(i); } } } - /** This method performs a simple one point mutation in the genotype + /** + * This method performs a simple one point mutation in the genotype */ @Override public void defaultMutate() { int mutationIndex = RNG.randomInt(0, this.m_GenotypeLength); if (this.m_Genotype.get(mutationIndex)) { this.m_Genotype.clear(mutationIndex); - } - else { + } else { this.m_Genotype.set(mutationIndex); } } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -352,37 +382,47 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte return "GA individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a GA individual suited to optimize double values."; } - /** This method allows you to set the Coding that is to be used, currently either standard binary + /** + * This method allows you to set the Coding that is to be used, currently either standard binary * coding or Gray coding. + * * @param coding The used genotype coding method */ public void setGACoding(InterfaceGADoubleCoding coding) { this.m_DoubleCoding = coding; } + public InterfaceGADoubleCoding getGACoding() { return this.m_DoubleCoding; } + public String gADoubleCodingTipText() { return "Choose the coding to use."; } - /** This method allows you to set the number of mulitruns that are to be performed, + /** + * This method allows you to set the number of mulitruns that are to be performed, * necessary for stochastic optimizers to ensure reliable results. + * * @param precision The number of multiruns that are to be performed */ public void setPrecision(int precision) { this.m_Precision = precision; } + public int getPrecision() { return this.m_Precision; } + public String precisionTipText() { return "Gives the number of bits to be used to code a double."; } diff --git a/src/eva2/optimization/individuals/GAIndividualIntegerData.java b/src/eva2/optimization/individuals/GAIndividualIntegerData.java index a371f0b0..e5e738f0 100644 --- a/src/eva2/optimization/individuals/GAIndividualIntegerData.java +++ b/src/eva2/optimization/individuals/GAIndividualIntegerData.java @@ -8,9 +8,11 @@ import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.operator.mutation.MutateGANBit; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; -/** This individual uses a binary genotype to code for binary values using +/** + * This individual uses a binary genotype to code for binary values using * two alternative encodings. * Created by IntelliJ IDEA. * User: streiche @@ -20,50 +22,50 @@ import java.util.BitSet; */ public class GAIndividualIntegerData extends AbstractEAIndividual implements InterfaceGAIndividual, InterfaceDataTypeInteger, java.io.Serializable { - private int[] m_Phenotype; - private int[][] m_Range; - protected BitSet m_Genotype; - protected int[] m_CodingLenghts; - private InterfaceGAIntegerCoding m_IntegerCoding = new GAStandardCodingInteger(); + private int[] m_Phenotype; + private int[][] m_Range; + protected BitSet m_Genotype; + protected int[] m_CodingLenghts; + private InterfaceGAIntegerCoding m_IntegerCoding = new GAStandardCodingInteger(); public GAIndividualIntegerData() { this.mutationProbability = 0.2; this.mutationOperator = new MutateGANBit(); this.crossoverProbability = 0.7; this.crossoverOperator = new CrossoverGAGINPoint(); - this.m_Range = new int[1][2]; - this.m_CodingLenghts = new int[1]; - this.m_CodingLenghts[0] = 3; - this.m_Range[0][0] = 0; - this.m_Range[0][1] = 7; - this.m_Genotype = new BitSet(); + this.m_Range = new int[1][2]; + this.m_CodingLenghts = new int[1]; + this.m_CodingLenghts[0] = 3; + this.m_Range[0][0] = 0; + this.m_Range[0][1] = 7; + this.m_Genotype = new BitSet(); } public GAIndividualIntegerData(GAIndividualIntegerData individual) { if (individual.m_Phenotype != null) { - this.m_Phenotype = new int[individual.m_Phenotype.length]; + this.m_Phenotype = new int[individual.m_Phenotype.length]; System.arraycopy(individual.m_Phenotype, 0, this.m_Phenotype, 0, this.m_Phenotype.length); } - this.m_Genotype = (BitSet) individual.m_Genotype.clone(); - this.m_Range = new int[individual.m_Range.length][2]; - this.m_CodingLenghts = new int[individual.m_CodingLenghts.length]; + this.m_Genotype = (BitSet) individual.m_Genotype.clone(); + this.m_Range = new int[individual.m_Range.length][2]; + this.m_CodingLenghts = new int[individual.m_CodingLenghts.length]; for (int i = 0; i < this.m_Range.length; i++) { this.m_CodingLenghts[i] = individual.m_CodingLenghts[i]; - this.m_Range[i][0] = individual.m_Range[i][0]; - this.m_Range[i][1] = individual.m_Range[i][1]; + this.m_Range[i][0] = individual.m_Range[i][0]; + this.m_Range[i][1] = individual.m_Range[i][1]; } // cloning the members of AbstractEAIndividual this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { this.selectionProbability[i] = individual.selectionProbability[i]; } - this.m_IntegerCoding = individual.m_IntegerCoding; + this.m_IntegerCoding = individual.m_IntegerCoding; this.fitness = new double[individual.fitness.length]; for (int i = 0; i < this.fitness.length; i++) { this.fitness[i] = individual.fitness[i]; @@ -77,8 +79,10 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -112,33 +116,37 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int /************************************************************************************ * InterfaceDataTypeInteger methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setIntegerDataLength (int length) { - int[] newDesPa = new int[length]; - int[][] newRange = new int[length][2]; + public void setIntegerDataLength(int length) { + int[] newDesPa = new int[length]; + int[][] newRange = new int[length][2]; // copy the old values for the decision parameters and the range for (int i = 0; ((i < newDesPa.length) && (i < this.m_Range.length)); i++) { - newRange[i][0] = this.m_Range[i][0]; - newRange[i][1] = this.m_Range[i][1]; + newRange[i][0] = this.m_Range[i][0]; + newRange[i][1] = this.m_Range[i][1]; } // if the new length is bigger than the last value fills the extra elements for (int i = this.m_Range.length; (i < newDesPa.length); i++) { - newRange[i][0] = this.m_Range[this.m_Range.length-1][0]; - newRange[i][1] = this.m_Range[this.m_Range.length-1][1]; + newRange[i][0] = this.m_Range[this.m_Range.length - 1][0]; + newRange[i][1] = this.m_Range[this.m_Range.length - 1][1]; } - this.m_Range = newRange; - this.m_CodingLenghts = new int[this.m_Range.length]; + this.m_Range = newRange; + this.m_CodingLenghts = new int[this.m_Range.length]; for (int i = 0; i < this.m_Range.length; i++) { this.m_CodingLenghts[i] = this.m_IntegerCoding.calculateNecessaryBits(this.m_Range[i]); } } - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of bits stored */ @Override @@ -146,10 +154,12 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Range.length; } - /** This method will set the range of the integer attributes. If range.length + /** + * This method will set the range of the integer attributes. If range.length * does not equal doubledata.length only range[i] will be used to set all * ranges. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ @Override public void SetIntRange(int[][] range) { @@ -166,31 +176,33 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int /** * Set lower and upper integer range in all dimensions. - * + * * @param lower * @param upper */ public void SetIntRange(int lower, int upper) { - for (int i=0; i + * /** This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setDoubleDataLength (int length) { + public void setDoubleDataLength(int length) { this.m_Numbers.setDoubleDataLength(length); } - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of bits stored */ @Override @@ -205,17 +221,21 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return this.m_Numbers.size(); } - /** This method will set the range of the double attributes. + /** + * This method will set the range of the double attributes. * Note: range[d][0] gives the lower bound and range[d] gives the upper bound * for dimension d. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ @Override public void SetDoubleRange(double[][] range) { this.m_Numbers.SetDoubleRange(range); } - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ @Override @@ -223,7 +243,9 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return this.m_Numbers.getDoubleRange(); } - /** This method allows you to read the double data + /** + * This method allows you to read the double data + * * @return BitSet representing the double data. */ @Override @@ -231,8 +253,10 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return this.m_Numbers.getDoubleData(); } - /** This method allows you to read the double data without + /** + * This method allows you to read the double data without * an update from the genotype + * * @return double[] representing the double data. */ @Override @@ -240,18 +264,22 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return this.m_Numbers.getDoubleDataWithoutUpdate(); } - /** This method allows you to set the phenotype data. To change the genotype, use + /** + * This method allows you to set the phenotype data. To change the genotype, use * SetDoubleDataLamarckian(). - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetDoublePhenotype(double[] doubleData) { this.m_Numbers.SetDoublePhenotype(doubleData); } - /** This method allows you to set the genotype data, this can be used for + /** + * This method allows you to set the genotype data, this can be used for * memetic algorithms. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetDoubleGenotype(double[] doubleData) { @@ -261,15 +289,19 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In /************************************************************************************ * InterfaceDataTypeProgram methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setProgramDataLength (int length) { + public void setProgramDataLength(int length) { this.m_Program.setProgramDataLength(length); } - /** This method allows you to read the program stored as Koza style node tree + /** + * This method allows you to read the program stored as Koza style node tree + * * @return AbstractGPNode representing the binary data. */ @Override @@ -277,8 +309,10 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return this.m_Program.getProgramData(); } - /** This method allows you to read the Program data without + /** + * This method allows you to read the Program data without * an update from the genotype + * * @return InterfaceProgram[] representing the Program. */ @Override @@ -286,31 +320,39 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return this.m_Program.getProgramDataWithoutUpdate(); } - /** This method allows you to set the program. - * @param program The new program. + /** + * This method allows you to set the program. + * + * @param program The new program. */ @Override public void SetProgramPhenotype(InterfaceProgram[] program) { this.m_Program.SetProgramPhenotype(program); } - /** This method allows you to set the program. - * @param program The new program. + /** + * This method allows you to set the program. + * + * @param program The new program. */ @Override public void SetProgramGenotype(InterfaceProgram[] program) { this.m_Program.SetProgramGenotype(program); } - /** This method allows you to set the function area - * @param area The area contains functions and terminals + /** + * This method allows you to set the function area + * + * @param area The area contains functions and terminals */ @Override public void SetFunctionArea(Object[] area) { this.m_Program.SetFunctionArea(area); } - /** This method allows you to set the function area + /** + * This method allows you to set the function area + * * @return The function area */ @Override @@ -321,8 +363,10 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -330,27 +374,36 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In return "GAP individual"; } - /** This method will allow you to set the inner constants - * @param Numbers The new representation for the inner constants. - */ + /** + * This method will allow you to set the inner constants + * + * @param Numbers The new representation for the inner constants. + */ public void setNumbers(InterfaceDataTypeDouble Numbers) { this.m_Numbers = Numbers; } + public InterfaceDataTypeDouble getNumbers() { return this.m_Numbers; } + public String numbersTipText() { return "Choose the type of inner constants to use."; } - /** This method will allow you to set the inner constants - * @param program The new representation for the program. - */ + + /** + * This method will allow you to set the inner constants + * + * @param program The new representation for the program. + */ public void setProgramRepresentation(InterfaceDataTypeProgram program) { this.m_Program = program; } + public InterfaceDataTypeProgram getProgramRepresentation() { return this.m_Program; } + public String programRepresentationTipText() { return "Choose the type of inner constants to use."; } diff --git a/src/eva2/optimization/individuals/GEIndividualProgramData.java b/src/eva2/optimization/individuals/GEIndividualProgramData.java index e5ff40c5..69c8cbd6 100644 --- a/src/eva2/optimization/individuals/GEIndividualProgramData.java +++ b/src/eva2/optimization/individuals/GEIndividualProgramData.java @@ -9,10 +9,12 @@ import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.operator.mutation.MutateDefault; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.ArrayList; import java.util.BitSet; -/** This individual uses a binary genotype to code for a tree-based representation +/** + * This individual uses a binary genotype to code for a tree-based representation * using a BNF grammar, see also Grammatical Evolution. * Created by IntelliJ IDEA. * User: streiche @@ -22,25 +24,25 @@ import java.util.BitSet; */ public class GEIndividualProgramData extends AbstractEAIndividual implements InterfaceGAIndividual, InterfaceDataTypeProgram, java.io.Serializable { - protected GPArea[] m_Area; - protected double m_InitFullGrowRatio = 0.5; - protected int m_InitDepth = 5; - protected int m_TargetDepth = 10; - protected boolean m_CheckTargetDepth = true; + protected GPArea[] m_Area; + protected double m_InitFullGrowRatio = 0.5; + protected int m_InitDepth = 5; + protected int m_TargetDepth = 10; + protected boolean m_CheckTargetDepth = true; - protected BitSet m_Genotype; - protected AbstractGPNode[] m_Phenotype; - protected int m_GenotypeLengthPerProgram = 240; // this is the overall length - protected int m_MaxNumberOfNodes = 80; - protected int m_NumberOfBitPerInt = 6; - protected int m_CurrentIndex = 0; - protected int m_CurrentNumberOfNodes = 0; - protected Object[][] m_Rules; + protected BitSet m_Genotype; + protected AbstractGPNode[] m_Phenotype; + protected int m_GenotypeLengthPerProgram = 240; // this is the overall length + protected int m_MaxNumberOfNodes = 80; + protected int m_NumberOfBitPerInt = 6; + protected int m_CurrentIndex = 0; + protected int m_CurrentNumberOfNodes = 0; + protected Object[][] m_Rules; public GEIndividualProgramData() { - this.m_Area = new GPArea[1]; - this.m_GenotypeLengthPerProgram = 240; - this.m_Genotype = new BitSet(); + this.m_Area = new GPArea[1]; + this.m_GenotypeLengthPerProgram = 240; + this.m_Genotype = new BitSet(); this.mutationOperator = new MutateDefault(); this.crossoverOperator = new CrossoverGADefault(); this.mutationProbability = 0.5; @@ -51,20 +53,20 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int if (individual.m_Phenotype != null) { this.m_Phenotype = new AbstractGPNode[individual.m_Phenotype.length]; for (int i = 0; i < individual.m_Phenotype.length; i++) { - this.m_Phenotype[i] = (AbstractGPNode)individual.m_Phenotype[i].clone(); + this.m_Phenotype[i] = (AbstractGPNode) individual.m_Phenotype[i].clone(); } } - this.m_GenotypeLengthPerProgram = individual.m_GenotypeLengthPerProgram; + this.m_GenotypeLengthPerProgram = individual.m_GenotypeLengthPerProgram; this.m_MaxNumberOfNodes = individual.m_MaxNumberOfNodes; - this.m_NumberOfBitPerInt= individual.m_NumberOfBitPerInt; - this.m_CurrentIndex = individual.m_CurrentIndex; + this.m_NumberOfBitPerInt = individual.m_NumberOfBitPerInt; + this.m_CurrentIndex = individual.m_CurrentIndex; if (individual.m_Genotype != null) { - this.m_Genotype = (BitSet)individual.m_Genotype.clone(); + this.m_Genotype = (BitSet) individual.m_Genotype.clone(); } if (individual.m_Area != null) { - this.m_Area = new GPArea[individual.m_Area.length]; + this.m_Area = new GPArea[individual.m_Area.length]; for (int i = 0; i < this.m_Area.length; i++) { - this.m_Area[i] = (GPArea)individual.m_Area[i].clone(); + this.m_Area[i] = (GPArea) individual.m_Area[i].clone(); } } // User : "Copy the rules set!" @@ -80,9 +82,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int System.arraycopy(orgRulz[i], 0, copyRulz[i], 0, orgRulz[i].length); } this.m_Rules[t][0] = copyRulz; - AbstractGPNode[] copyNode, orgNode; + AbstractGPNode[] copyNode, orgNode; for (int i = 1; i < this.m_Rules[t].length; i++) { - orgNode = (AbstractGPNode[])individual.m_Rules[t][i]; + orgNode = (AbstractGPNode[]) individual.m_Rules[t][i]; copyNode = new AbstractGPNode[orgNode.length]; for (int j = 0; j < orgNode.length; j++) { copyNode[j] = (AbstractGPNode) orgNode[j].clone(); @@ -95,7 +97,7 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -113,8 +115,10 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int return (Object) new GEIndividualProgramData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -142,7 +146,8 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } } - /** This method compiles the area + /** + * This method compiles the area */ private void compileArea() { if (this.m_Area == null) { @@ -152,7 +157,7 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int //this.m_Rules = new Object[this.m_Area.length][]; for (int t = 0; t < this.m_Area.length; t++) { // first lets find out what kind of elements are available - int arity, maxArity = 0; + int arity, maxArity = 0; // first find out the max arity in the GPArea this.m_Area[t].compileReducedList(); @@ -173,21 +178,21 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int directList[((AbstractGPNode) area.get(i)).getArity()].add(area.get(i)); } // Now write the rules - this.m_Rules[t] = new Object[maxArity+2]; + this.m_Rules[t] = new Object[maxArity + 2]; // the first rule describes how to decode an - int numberOfRules = 0, index = 0; - int[] tmpRule; - int[][] tmpExpr = new int[directList.length+1][]; + int numberOfRules = 0, index = 0; + int[] tmpRule; + int[][] tmpExpr = new int[directList.length + 1][]; for (int i = 0; i < directList.length; i++) { - tmpRule = new int[i+1]; + tmpRule = new int[i + 1]; if (i == 0) { // this is a tmpRule[0] = 1; } else { // this is a .... if (directList[i].size() > 0) { - tmpRule[0] = i+1; - for (int j = 1; j < i+1; j++) { + tmpRule[0] = i + 1; + for (int j = 1; j < i + 1; j++) { tmpRule[j] = 0; } } else { @@ -208,41 +213,40 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int index++; } } - this.m_Rules[t][0] =trueExpr; + this.m_Rules[t][0] = trueExpr; // now the rules that define , , , .... - AbstractGPNode[] tmpListOfGPNodes; + AbstractGPNode[] tmpListOfGPNodes; for (int i = 0; i < directList.length; i++) { tmpListOfGPNodes = new AbstractGPNode[directList[i].size()]; for (int j = 0; j < directList[i].size(); j++) { - tmpListOfGPNodes[j] = (AbstractGPNode)directList[i].get(j); + tmpListOfGPNodes[j] = (AbstractGPNode) directList[i].get(j); } - this.m_Rules[t][i+1] = tmpListOfGPNodes; + this.m_Rules[t][i + 1] = tmpListOfGPNodes; } // this should be the complete rules set //this.printRuleSet(); } } - /** This method will print the currently used rule set + /** + * This method will print the currently used rule set */ private void printRuleSet() { - String result = ""; - AbstractGPNode[] tmpNodes; + String result = ""; + AbstractGPNode[] tmpNodes; for (int t = 0; t < this.m_Area.length; t++) { // first the Non-Terminals result += "N \t := \t{"; for (int i = 0; i < this.m_Rules[t].length; i++) { if (i == 0) { result += "expr, "; - } - else { + } else { if (i == 1) { result += "var, "; - } - else { - if (((AbstractGPNode[])this.m_Rules[t][i]).length > 0) { - result += "op"+(i-1)+", "; + } else { + if (((AbstractGPNode[]) this.m_Rules[t][i]).length > 0) { + result += "op" + (i - 1) + ", "; } } } @@ -253,7 +257,7 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int this.m_Area[t].compileReducedList(); ArrayList area = this.m_Area[t].getReducedList(); for (int i = 0; i < area.size(); i++) { - result += ((AbstractGPNode)area.get(i)).getStringRepresentation()+", "; + result += ((AbstractGPNode) area.get(i)).getStringRepresentation() + ", "; } result += "}\n"; // now the S @@ -265,10 +269,10 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int // the first rules result += "0. \t := \t \t::\t"; System.out.println("i: " + i); - int[][] rulz = (int[][])this.m_Rules[t][i]; + int[][] rulz = (int[][]) this.m_Rules[t][i]; for (int j = 0; j < rulz.length; j++) { result += this.getRuleString(rulz[j]) + "\n"; - if ((j+1) < rulz.length) { + if ((j + 1) < rulz.length) { result += "\t \t \t \t \t \t"; } } @@ -276,18 +280,18 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int // now the rules for the terminals if (i == 1) { // These are the GP-Terminals - tmpNodes = (AbstractGPNode[])this.m_Rules[t][i]; - result += "1. \t := \t \t::\t"+ tmpNodes[0].getStringRepresentation()+"\n"; + tmpNodes = (AbstractGPNode[]) this.m_Rules[t][i]; + result += "1. \t := \t \t::\t" + tmpNodes[0].getStringRepresentation() + "\n"; for (int j = 1; j < tmpNodes.length; j++) { - result += "\t \t \t \t \t \t"+ tmpNodes[j].getStringRepresentation()+"\n"; + result += "\t \t \t \t \t \t" + tmpNodes[j].getStringRepresentation() + "\n"; } } else { // These are the GP-Functions - tmpNodes = (AbstractGPNode[])this.m_Rules[t][i]; + tmpNodes = (AbstractGPNode[]) this.m_Rules[t][i]; if (tmpNodes.length > 0) { - result += i+". \t := \t \t::\t"+ tmpNodes[0].getStringRepresentation()+"\n"; + result += i + ". \t := \t \t::\t" + tmpNodes[0].getStringRepresentation() + "\n"; for (int j = 1; j < tmpNodes.length; j++) { - result += "\t \t \t \t \t \t"+ tmpNodes[j].getStringRepresentation()+"\n"; + result += "\t \t \t \t \t \t" + tmpNodes[j].getStringRepresentation() + "\n"; } } } @@ -297,24 +301,25 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } // Now print the result: - System.out.println(""+result); + System.out.println("" + result); } - /** This method returns a string for the BitSet + /** + * This method returns a string for the BitSet + * * @return A String */ private String getBitSetString() { String result = ""; result += "{"; - for (int i = 0; i < this.m_GenotypeLengthPerProgram*this.m_Area.length; i++) { + for (int i = 0; i < this.m_GenotypeLengthPerProgram * this.m_Area.length; i++) { if (i % this.m_NumberOfBitPerInt == 0) { result += " "; } if (this.m_Genotype.get(i)) { result += "1"; - } - else { + } else { result += "0"; } } @@ -322,12 +327,14 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int return result; } - /** This method returns a String for a given rule - * @param rule The rulz to transform into a string + /** + * This method returns a String for a given rule + * + * @param rule The rulz to transform into a string * @return String */ private String getRuleString(int[] rule) { - String result =""; + String result = ""; for (int k = 0; k < rule.length; k++) { if (rule[k] == 0) { result += " "; @@ -335,8 +342,8 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int if (rule[k] == 1) { result += " "; } - if (rule[k] > 1) { - result += " "; + if (rule[k] > 1) { + result += " "; } } return result; @@ -345,28 +352,30 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int /************************************************************************************ * InterfaceDataTypeProgram methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setProgramDataLength (int length) { - GPArea[] oldArea = this.m_Area; - Object[][] oldRulz = this.m_Rules; + public void setProgramDataLength(int length) { + GPArea[] oldArea = this.m_Area; + Object[][] oldRulz = this.m_Rules; - this.m_Area = new GPArea[length]; + this.m_Area = new GPArea[length]; for (int t = 0; ((t < this.m_Area.length) && (t < oldArea.length)); t++) { - this.m_Area[t] = oldArea[t]; + this.m_Area[t] = oldArea[t]; } for (int t = oldArea.length; t < this.m_Area.length; t++) { - this.m_Area[t] = oldArea[oldArea.length-1]; + this.m_Area[t] = oldArea[oldArea.length - 1]; } - this.m_Rules = new Object[length][]; + this.m_Rules = new Object[length][]; if (oldRulz == null) { return; } for (int t = 0; ((t < this.m_Area.length) && (t < oldArea.length)); t++) { if (oldRulz[t] != null) { - this.m_Rules[t] = new Object[oldRulz[t].length]; + this.m_Rules[t] = new Object[oldRulz[t].length]; int[][] copyRulz, orgRulz = (int[][]) oldRulz[t][0]; copyRulz = new int[orgRulz.length][]; for (int i = 0; i < copyRulz.length; i++) { @@ -374,9 +383,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int System.arraycopy(orgRulz[i], 0, copyRulz[i], 0, orgRulz[i].length); } this.m_Rules[t][0] = copyRulz; - AbstractGPNode[] copyNode, orgNode; + AbstractGPNode[] copyNode, orgNode; for (int i = 1; i < this.m_Rules[t].length; i++) { - orgNode = (AbstractGPNode[])oldRulz[t][i]; + orgNode = (AbstractGPNode[]) oldRulz[t][i]; copyNode = new AbstractGPNode[orgNode.length]; for (int j = 0; j < orgNode.length; j++) { copyNode[j] = (AbstractGPNode) orgNode[j].clone(); @@ -386,18 +395,18 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } } for (int t = oldArea.length; t < this.m_Area.length; t++) { - if (oldRulz[oldArea.length-1] != null) { - this.m_Rules[t] = new Object[oldRulz[oldArea.length-1].length]; - int[][] copyRulz, orgRulz = (int[][]) oldRulz[oldArea.length-1][0]; + if (oldRulz[oldArea.length - 1] != null) { + this.m_Rules[t] = new Object[oldRulz[oldArea.length - 1].length]; + int[][] copyRulz, orgRulz = (int[][]) oldRulz[oldArea.length - 1][0]; copyRulz = new int[orgRulz.length][]; for (int i = 0; i < copyRulz.length; i++) { copyRulz[i] = new int[orgRulz[i].length]; System.arraycopy(orgRulz[i], 0, copyRulz[i], 0, orgRulz[i].length); } this.m_Rules[t][0] = copyRulz; - AbstractGPNode[] copyNode, orgNode; + AbstractGPNode[] copyNode, orgNode; for (int i = 1; i < this.m_Rules[t].length; i++) { - orgNode = (AbstractGPNode[])oldRulz[oldArea.length-1][i]; + orgNode = (AbstractGPNode[]) oldRulz[oldArea.length - 1][i]; copyNode = new AbstractGPNode[orgNode.length]; for (int j = 0; j < orgNode.length; j++) { copyNode[j] = (AbstractGPNode) orgNode[j].clone(); @@ -408,42 +417,46 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } } - /** This method will fetch the next int value from the BitSet. If necessary the + /** + * This method will fetch the next int value from the BitSet. If necessary the * method will continue at the beginning of the BitSet if m_Genotype length is * exceeded. * Note: You need to set the current ReadingIndx = 0 before starting to decode * the BitSet - * @param t The index of the program. - * @return The int value + * + * @param t The index of the program. + * @return The int value */ private int decodeNextInt(int t) { int result = 0; for (int i = 0; i < this.m_NumberOfBitPerInt; i++) { - if (this.m_Genotype.get(this.m_CurrentIndex+(t*this.m_GenotypeLengthPerProgram))) { + if (this.m_Genotype.get(this.m_CurrentIndex + (t * this.m_GenotypeLengthPerProgram))) { result += Math.pow(2, i); } this.m_CurrentIndex++; - if (this.m_CurrentIndex >= (t+1)*this.m_GenotypeLengthPerProgram) { - this.m_CurrentIndex = t*this.m_GenotypeLengthPerProgram; + if (this.m_CurrentIndex >= (t + 1) * this.m_GenotypeLengthPerProgram) { + this.m_CurrentIndex = t * this.m_GenotypeLengthPerProgram; } } return result; } - /** This method will decode a GPNode from the BitSet - * @param t The index of the program - * @param mode The modex + /** + * This method will decode a GPNode from the BitSet + * + * @param t The index of the program + * @param mode The modex * @return GPNode */ private AbstractGPNode decodeGPNode(int t, int mode) { - AbstractGPNode result = null; - int value = this.decodeNextInt(t); + AbstractGPNode result = null; + int value = this.decodeNextInt(t); // System.out.println("Decoding mode: " + mode); if (mode == 0) { int[][] rulz = (int[][]) this.m_Rules[t][0]; - int[] myRule = rulz[value%rulz.length]; + int[] myRule = rulz[value % rulz.length]; // System.out.print("Value % rulz : "+ value +" % " + rulz.length + " = " +(value%rulz.length)); // System.out.println(" => my rule " + this.getRuleString(myRule)); this.m_CurrentNumberOfNodes += myRule.length; @@ -455,18 +468,20 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int result = this.decodeGPNode(t, myRule[0]); result.initNodeArray(); for (int i = 0; i < result.getArity(); i++) { - result.setNode(this.decodeGPNode(t, myRule[i+1]), i); + result.setNode(this.decodeGPNode(t, myRule[i + 1]), i); } } else { AbstractGPNode[] availableNodes = (AbstractGPNode[]) this.m_Rules[t][mode]; // System.out.print("Choosing a terminal : "+ value +" % " + availableNodes.length + " = " +(value%availableNodes.length)); // System.out.println(" => " +availableNodes[value % availableNodes.length].getStringRepresentation()); - result = (AbstractGPNode)availableNodes[value % availableNodes.length].clone(); + result = (AbstractGPNode) availableNodes[value % availableNodes.length].clone(); } return result; } - /** This method allows you to read the program stored as Koza style node tree + /** + * This method allows you to read the program stored as Koza style node tree + * * @return GPNode representing the binary data. */ @Override @@ -489,13 +504,13 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int return null; } } - this.m_CurrentIndex = 0; + this.m_CurrentIndex = 0; this.m_CurrentNumberOfNodes = 0; - int mode = 0; + int mode = 0; this.m_Phenotype = new AbstractGPNode[this.m_Area.length]; for (int t = 0; t < this.m_Area.length; t++) { - mode = 0; - this.m_CurrentIndex = t*this.m_GenotypeLengthPerProgram; + mode = 0; + this.m_CurrentIndex = t * this.m_GenotypeLengthPerProgram; this.m_CurrentNumberOfNodes = 0; this.m_Phenotype[t] = this.decodeGPNode(t, mode); } @@ -504,8 +519,10 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int return this.m_Phenotype; } - /** This method allows you to read the Program data without + /** + * This method allows you to read the Program data without * an update from the genotype + * * @return InterfaceProgram[] representing the Program. */ @Override @@ -513,22 +530,25 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int return this.m_Phenotype; } - /** This method allows you to set the program phenotype. - * @param program The new program. + /** + * This method allows you to set the program phenotype. + * + * @param program The new program. */ @Override public void SetProgramPhenotype(InterfaceProgram[] program) { if (program instanceof AbstractGPNode[]) { this.m_Phenotype = new AbstractGPNode[program.length]; for (int t = 0; t < program.length; t++) { - this.m_Phenotype[t] = (AbstractGPNode)((AbstractGPNode)program[t]).clone(); + this.m_Phenotype[t] = (AbstractGPNode) ((AbstractGPNode) program[t]).clone(); } } } - /** + /** * Warning - this is not implemented, it only sets the phenotype using SetProgramData. - * @param program The new program. + * + * @param program The new program. */ @Override public void SetProgramGenotype(InterfaceProgram[] program) { @@ -538,13 +558,15 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } } - /** This method allows you to set the function area - * @param area The area contains functions and terminals + /** + * This method allows you to set the function area + * + * @param area The area contains functions and terminals */ @Override public void SetFunctionArea(Object[] area) { if (area instanceof GPArea[]) { - this.m_Area = new GPArea[area.length]; + this.m_Area = new GPArea[area.length]; for (int t = 0; t < this.m_Area.length; t++) { this.m_Area[t] = (GPArea) area[t]; } @@ -552,7 +574,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } } - /** This method allows you to set the function area + /** + * This method allows you to set the function area + * * @return The function area */ @Override @@ -563,15 +587,17 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int /************************************************************************************ * InterfaceEAIndividual methods */ - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof InterfaceProgram) { - this.SetProgramGenotype((InterfaceProgram[])obj); + this.SetProgramGenotype((InterfaceProgram[]) obj); } else { this.defaultInit(opt); System.out.println("Initial value for GPIndividualDoubleData is no InterfaceProgram[]!"); @@ -580,8 +606,10 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int this.crossoverOperator.init(this, opt); } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override @@ -589,11 +617,10 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int String result = ""; result += "GEIndividual coding program:\n"; result += "{"; - for (int i = 0; i < this.m_GenotypeLengthPerProgram*this.m_Area.length; i++) { + for (int i = 0; i < this.m_GenotypeLengthPerProgram * this.m_Area.length; i++) { if (this.m_Genotype.get(i)) { result += "1"; - } - else { + } else { result += "0"; } } @@ -609,65 +636,72 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int * InterfaceGAIndividual methods */ - /** This method allows you to read the binary data - * @return BitSet representing the binary data. - */ + /** + * This method allows you to read the binary data + * + * @return BitSet representing the binary data. + */ @Override - public BitSet getBGenotype() { - return this.m_Genotype; - } + public BitSet getBGenotype() { + return this.m_Genotype; + } - /** This method allows you to set the binary data, this can be used for - * memetic algorithms. - * @param binaryData The new binary data. - */ + /** + * This method allows you to set the binary data, this can be used for + * memetic algorithms. + * + * @param binaryData The new binary data. + */ @Override - public void SetBGenotype(BitSet binaryData) { - this.m_Genotype = binaryData; - } + public void SetBGenotype(BitSet binaryData) { + this.m_Genotype = binaryData; + } - /** This method allows the user to read the length of the genotype. - * This may be necessary since BitSet.lenght only returns the index - * of the last significat bit. - * @return The length of the genotype. - */ + /** + * This method allows the user to read the length of the genotype. + * This may be necessary since BitSet.lenght only returns the index + * of the last significat bit. + * + * @return The length of the genotype. + */ @Override - public int getGenotypeLength() { - return this.m_GenotypeLengthPerProgram*this.m_Area.length; - } + public int getGenotypeLength() { + return this.m_GenotypeLengthPerProgram * this.m_Area.length; + } @Override - public void defaultInit(InterfaceOptimizationProblem prob) { - for (int i = 0; i < this.m_GenotypeLengthPerProgram*this.m_Area.length; i++) { - if (RNG.flipCoin(0.5)) { - this.m_Genotype.set(i); - } - else { - this.m_Genotype.clear(i); - } + public void defaultInit(InterfaceOptimizationProblem prob) { + for (int i = 0; i < this.m_GenotypeLengthPerProgram * this.m_Area.length; i++) { + if (RNG.flipCoin(0.5)) { + this.m_Genotype.set(i); + } else { + this.m_Genotype.clear(i); } } + } - /** This method performs a simple one point mutation in the genotype - */ + /** + * This method performs a simple one point mutation in the genotype + */ @Override - public void defaultMutate() { - int mutationIndex = RNG.randomInt(0, this.m_GenotypeLengthPerProgram*this.m_Area.length); - //if (mutationIndex > 28) System.out.println("Mutate: " + this.getSolutionRepresentationFor()); - if (this.m_Genotype.get(mutationIndex)) { - this.m_Genotype.clear(mutationIndex); - } - else { - this.m_Genotype.set(mutationIndex); - } - //if (mutationIndex > 28) System.out.println(this.getSolutionRepresentationFor()); + public void defaultMutate() { + int mutationIndex = RNG.randomInt(0, this.m_GenotypeLengthPerProgram * this.m_Area.length); + //if (mutationIndex > 28) System.out.println("Mutate: " + this.getSolutionRepresentationFor()); + if (this.m_Genotype.get(mutationIndex)) { + this.m_Genotype.clear(mutationIndex); + } else { + this.m_Genotype.set(mutationIndex); } + //if (mutationIndex > 28) System.out.println(this.getSolutionRepresentationFor()); + } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -675,50 +709,64 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int return "GE individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a GE individual suited to optimize programs."; } - /** This method allows you to set the length of the binary genotype - * @param size The length + /** + * This method allows you to set the length of the binary genotype + * + * @param size The length */ public void setGenotypeLengthPerProgram(int size) { this.m_GenotypeLengthPerProgram = size; } + public int getGenotypeLengthPerProgram() { return this.m_GenotypeLengthPerProgram; } + public String genotypeLengthPerProgramTipText() { return "Choose the length of the genotype."; } - /** This method allows you to set the maximum number of + /** + * This method allows you to set the maximum number of * nodes allowed for the program. - * @param nodes The maximum number of nodes + * + * @param nodes The maximum number of nodes */ public void setMaxNumberOfNodes(int nodes) { this.m_MaxNumberOfNodes = nodes; } + public int getMaxNumberOfNodes() { return this.m_MaxNumberOfNodes; } + public String maxNumberOfNodesTipText() { return "Set the maximum number of nodes for the program."; } - /** This method allows you to set the number of bits per int value + /** + * This method allows you to set the number of bits per int value * stored on the BitSet - * @param length The number of bits per int. + * + * @param length The number of bits per int. */ public void setNumberOfBitPerInt(int length) { this.m_NumberOfBitPerInt = length; } + public int getNumberOfBitPerInt() { return this.m_NumberOfBitPerInt; } + public String numberOfBitPerIntTipText() { return "Choose the number of bits ber int."; } diff --git a/src/eva2/optimization/individuals/GIIndividualIntegerData.java b/src/eva2/optimization/individuals/GIIndividualIntegerData.java index 3228bd7a..a3c8a276 100644 --- a/src/eva2/optimization/individuals/GIIndividualIntegerData.java +++ b/src/eva2/optimization/individuals/GIIndividualIntegerData.java @@ -7,7 +7,8 @@ import eva2.optimization.problems.InterfaceHasInitRange; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; -/** This individual uses a integer genotype to code for integer values. +/** + * This individual uses a integer genotype to code for integer values. * Created by IntelliJ IDEA. * User: streiche * Date: 18.05.2005 @@ -16,49 +17,49 @@ import eva2.tools.math.RNG; */ public class GIIndividualIntegerData extends AbstractEAIndividual implements InterfaceGIIndividual, InterfaceDataTypeInteger, java.io.Serializable { - private int[] m_Phenotype; - private int[][] m_Range; - protected int[] m_Genotype; + private int[] m_Phenotype; + private int[][] m_Range; + protected int[] m_Genotype; public GIIndividualIntegerData() { this.mutationProbability = 0.2; this.mutationOperator = new MutateDefault(); this.crossoverProbability = 0.7; this.crossoverOperator = new CrossoverGIDefault(); - this.m_Range = new int[10][2]; + this.m_Range = new int[10][2]; for (int i = 0; i < this.m_Range.length; i++) { - this.m_Range[i][0] = 0; - this.m_Range[i][1] = 7; + this.m_Range[i][0] = 0; + this.m_Range[i][1] = 7; } - this.m_Genotype = new int[10]; + this.m_Genotype = new int[10]; } public GIIndividualIntegerData(int[][] theRange) { - this(); - SetIntRange(theRange); + this(); + SetIntRange(theRange); } - + public GIIndividualIntegerData(GIIndividualIntegerData individual) { if (individual.m_Phenotype != null) { - this.m_Phenotype = new int[individual.m_Phenotype.length]; + this.m_Phenotype = new int[individual.m_Phenotype.length]; System.arraycopy(individual.m_Phenotype, 0, this.m_Phenotype, 0, this.m_Phenotype.length); } if (individual.m_Genotype != null) { - this.m_Genotype = new int[individual.m_Genotype.length]; + this.m_Genotype = new int[individual.m_Genotype.length]; System.arraycopy(individual.m_Genotype, 0, this.m_Genotype, 0, this.m_Genotype.length); } - this.m_Range = new int[individual.m_Range.length][2]; + this.m_Range = new int[individual.m_Range.length][2]; for (int i = 0; i < this.m_Range.length; i++) { - this.m_Range[i][0] = individual.m_Range[i][0]; - this.m_Range[i][1] = individual.m_Range[i][1]; + this.m_Range[i][0] = individual.m_Range[i][0]; + this.m_Range[i][1] = individual.m_Range[i][1]; } // cloning the members of AbstractEAIndividual this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -77,8 +78,10 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -111,32 +114,36 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int /************************************************************************************ * InterfaceDataTypeInteger methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setIntegerDataLength (int length) { - int[] newDesPa = new int[length]; - int[][] newRange = new int[length][2]; + public void setIntegerDataLength(int length) { + int[] newDesPa = new int[length]; + int[][] newRange = new int[length][2]; // copy the old values for the decision parameters and the range for (int i = 0; ((i < newDesPa.length) && (i < this.m_Genotype.length)); i++) { - newDesPa[i] = this.m_Genotype[i]; - newRange[i][0] = this.m_Range[i][0]; - newRange[i][1] = this.m_Range[i][1]; + newDesPa[i] = this.m_Genotype[i]; + newRange[i][0] = this.m_Range[i][0]; + newRange[i][1] = this.m_Range[i][1]; } // if the new length is bigger than the last value fills the extra elements for (int i = this.m_Genotype.length; (i < newDesPa.length); i++) { - newDesPa[i] = this.m_Genotype[this.m_Genotype.length-1]; - newRange[i][0] = this.m_Range[this.m_Genotype.length-1][0]; - newRange[i][1] = this.m_Range[this.m_Genotype.length-1][1]; + newDesPa[i] = this.m_Genotype[this.m_Genotype.length - 1]; + newRange[i][0] = this.m_Range[this.m_Genotype.length - 1][0]; + newRange[i][1] = this.m_Range[this.m_Genotype.length - 1][1]; } - this.m_Genotype = newDesPa; - this.m_Range = newRange; + this.m_Genotype = newDesPa; + this.m_Range = newRange; } - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of bits stored */ @Override @@ -144,15 +151,17 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Range.length; } - /** This method will set the range of the double attributes. If range.length + /** + * This method will set the range of the double attributes. If range.length * does not equal doubledata.length only range[i] will be used to set all * ranges. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ @Override public void SetIntRange(int[][] range) { if (range.length != this.m_Range.length) { - this.setIntegerDataLength(range.length); + this.setIntegerDataLength(range.length); } for (int i = 0; ((i < this.m_Range.length) && (i < range.length)); i++) { this.m_Range[i][0] = range[i][0]; @@ -160,7 +169,9 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int } } - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ @Override @@ -168,7 +179,9 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Range; } - /** This method allows you to read the double data + /** + * This method allows you to read the double data + * * @return BitSet representing the double data. */ @Override @@ -180,8 +193,10 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Phenotype; } - /** This method allows you to read the int data without + /** + * This method allows you to read the int data without * an update from the genotype + * * @return int[] representing the int data. */ @Override @@ -189,17 +204,21 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Phenotype; } - /** This method allows you to set the double data. - * @param doubleData The new double data. + /** + * This method allows you to set the double data. + * + * @param doubleData The new double data. */ @Override public void SetIntPhenotype(int[] doubleData) { this.m_Phenotype = doubleData; } - /** This method allows you to set the double data, this can be used for + /** + * This method allows you to set the double data, this can be used for * memetic algorithms. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ @Override public void SetIntGenotype(int[] doubleData) { @@ -213,15 +232,17 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int /************************************************************************************ * AbstractEAIndividual methods */ - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof int[]) { - int[] bs = (int[]) obj; + int[] bs = (int[]) obj; if (bs.length != this.m_Range.length) { System.out.println("Init value and requested length doesn't match!"); } @@ -234,15 +255,17 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int this.crossoverOperator.init(this, opt); } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override public String getStringRepresentation() { String result = ""; result += "GIIndividual coding int: ("; - result += "Fitness {"; + result += "Fitness {"; for (int i = 0; i < this.fitness.length; i++) { result += this.fitness[i] + ";"; } @@ -252,14 +275,14 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int } result += "})\n Value: "; result += "["; - int[] d = this.getIntegerData(); + int[] d = this.getIntegerData(); for (int i = 0; i < d.length; i++) { result += d[i] + "; "; } result += "]\n"; result += "CodingRange: ["; for (int i = 0; i < this.m_Range.length; i++) { - result += "("+this.m_Range[i][0]+"; "+this.m_Range[i][1]+"); "; + result += "(" + this.m_Range[i][0] + "; " + this.m_Range[i][1] + "); "; } result += "]\n"; return result; @@ -269,7 +292,9 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int * InterfaceGIIndividual methods */ - /** This method will allow the user to read the GI genotype + /** + * This method will allow the user to read the GI genotype + * * @return BitSet */ @Override @@ -277,20 +302,24 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Genotype; } - /** This method will allow the user to set the current GI genotype. + /** + * This method will allow the user to set the current GI genotype. * Use this method with care, since the object is returned when using * getIGenotype() you can directly alter the genotype without using * this method. - * @param b The new genotype of the Individual + * + * @param b The new genotype of the Individual */ @Override public void SetIGenotype(int[] b) { this.m_Genotype = b; } - /** This method allows the user to read the length of the genotype. + /** + * This method allows the user to read the length of the genotype. * This may be necessary since BitSet.lenght only returns the index * of the last significat bit. + * * @return The length of the genotype. */ @Override @@ -298,34 +327,35 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int return this.m_Genotype.length; } - /** This method performs a simple one point mutation in the genotype + /** + * This method performs a simple one point mutation in the genotype */ @Override public void defaultMutate() { - int mutationIndex = RNG.randomInt(0, this.m_Genotype.length-1); + int mutationIndex = RNG.randomInt(0, this.m_Genotype.length - 1); this.m_Genotype[mutationIndex] = RNG.randomInt(this.m_Range[mutationIndex][0], this.m_Range[mutationIndex][1]); } @Override public void defaultInit(InterfaceOptimizationProblem prob) { - int[][] range = m_Range; - if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange)prob).getInitRange()!=null)) { - Object rng = ((InterfaceHasInitRange)prob).getInitRange(); - if (rng instanceof double[][]) { - double[][] dblRng = (double[][])rng; - range = new int[dblRng.length][dblRng[0].length]; - for (int i=0; i + * /** This method allows you to request a certain amount of int data + * + * @param length The lenght of the int[] that is to be optimized */ @Override - public void setIntegerDataLength (int length) { + public void setIntegerDataLength(int length) { this.m_Integer.setIntegerDataLength(length); } - /** This method returns the length of the int data set + /** + * This method returns the length of the int data set + * * @return The number of integers stored */ @Override @@ -218,17 +234,21 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Integer.size(); } - /** This method will set the range of the int attributes. + /** + * This method will set the range of the int attributes. * Note: range[d][0] gives the lower bound and range[d] gives the upper bound * for dimension d. - * @param range The new range for the int data. + * + * @param range The new range for the int data. */ @Override public void SetIntRange(int[][] range) { this.m_Integer.SetIntRange(range); } - /** This method will return the range for all int attributes. + /** + * This method will return the range for all int attributes. + * * @return The range array. */ @Override @@ -236,7 +256,9 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Integer.getIntRange(); } - /** This method allows you to read the int data + /** + * This method allows you to read the int data + * * @return int[] representing the int data. */ @Override @@ -244,8 +266,10 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Integer.getIntegerData(); } - /** This method allows you to read the int data without + /** + * This method allows you to read the int data without * an update from the genotype + * * @return int[] representing the int data. */ @Override @@ -253,17 +277,21 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Integer.getIntegerDataWithoutUpdate(); } - /** This method allows you to set the int data. - * @param intData The new int data. + /** + * This method allows you to set the int data. + * + * @param intData The new int data. */ @Override public void SetIntPhenotype(int[] intData) { this.m_Integer.SetIntPhenotype(intData); } - /** This method allows you to set the int data, this can be used for + /** + * This method allows you to set the int data, this can be used for * memetic algorithms. - * @param intData The new int data. + * + * @param intData The new int data. */ @Override public void SetIntGenotype(int[] intData) { @@ -273,7 +301,9 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual /********************************************************************************************************************** * These are for InterfaceDataTypePermutation */ - /** setLength sets the length of the permutation. + /** + * setLength sets the length of the permutation. + * * @param length int new length */ @Override @@ -282,7 +312,9 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual this.m_Integer.setIntegerDataLength(length.length); } - /** size returns the size of the permutation. + /** + * size returns the size of the permutation. + * * @return int */ @Override @@ -290,7 +322,9 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Permutation.sizePermutation(); } - /** This method allows you to read the permutation data + /** + * This method allows you to read the permutation data + * * @return int[] represent the permutation. */ @Override @@ -298,8 +332,10 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Permutation.getPermutationData(); } - /** This method allows you to read the permutation data without + /** + * This method allows you to read the permutation data without * an update from the genotype + * * @return int[] representing the permutation. */ @Override @@ -307,17 +343,21 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return this.m_Permutation.getPermutationDataWithoutUpdate(); } - /** This method allows you to set the permutation. - * @param perm The new permutation data. + /** + * This method allows you to set the permutation. + * + * @param perm The new permutation data. */ @Override public void SetPermutationPhenotype(int[][] perm) { this.SetPermutationPhenotype(perm); } - /** This method allows you to set the permutation data, this can be used for + /** + * This method allows you to set the permutation data, this can be used for * memetic algorithms. - * @param perm The new permutation data. + * + * @param perm The new permutation data. */ @Override public void SetPermutationGenotype(int[][] perm) { @@ -332,8 +372,10 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -341,34 +383,45 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual return "GA/ES individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a mixed data type combining an integer vector with a permutation vector."; } - /** This method will allow you to set the inner constants - * @param Numbers The new representation for the inner constants. - */ + /** + * This method will allow you to set the inner constants + * + * @param Numbers The new representation for the inner constants. + */ public void setIntegers(InterfaceDataTypeInteger Numbers) { this.m_Integer = Numbers; } + public InterfaceDataTypeInteger getIntegers() { return this.m_Integer; } + public String integersTipText() { return "Choose the type of inner integers to use."; } - /** This method will allow you to set the inner constants - * @param p The new representation for the inner constants. - */ + + /** + * This method will allow you to set the inner constants + * + * @param p The new representation for the inner constants. + */ public void setPermutations(InterfaceDataTypePermutation p) { this.m_Permutation = p; } + public InterfaceDataTypePermutation getPermutations() { return this.m_Permutation; } + public String permutationsTipText() { return "Choose the type of inner permutation to use."; } diff --git a/src/eva2/optimization/individuals/GPIndividualProgramData.java b/src/eva2/optimization/individuals/GPIndividualProgramData.java index cf075146..7d5959c8 100644 --- a/src/eva2/optimization/individuals/GPIndividualProgramData.java +++ b/src/eva2/optimization/individuals/GPIndividualProgramData.java @@ -1,7 +1,6 @@ package eva2.optimization.individuals; - import eva2.optimization.individuals.codings.gp.AbstractGPNode; import eva2.optimization.individuals.codings.gp.GPArea; import eva2.optimization.individuals.codings.gp.InterfaceProgram; @@ -12,7 +11,8 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.RNG; -/** This individual uses a tree-based genotype to code for program trees. +/** + * This individual uses a tree-based genotype to code for program trees. * Created by IntelliJ IDEA. * User: streiche * Date: 04.04.2003 @@ -21,18 +21,18 @@ import eva2.tools.math.RNG; */ public class GPIndividualProgramData extends AbstractEAIndividual implements InterfaceGPIndividual, InterfaceDataTypeProgram, java.io.Serializable { - protected AbstractGPNode[] m_Genotype; - protected AbstractGPNode[] m_Phenotype; - protected GPArea[] m_Area; - protected double m_InitFullGrowRatio = 0.5; - protected int m_InitDepth = 4; - protected int m_maxAllowedDepth = 8; - protected boolean m_CheckMaxDepth = true; + protected AbstractGPNode[] m_Genotype; + protected AbstractGPNode[] m_Phenotype; + protected GPArea[] m_Area; + protected double m_InitFullGrowRatio = 0.5; + protected int m_InitDepth = 4; + protected int m_maxAllowedDepth = 8; + protected boolean m_CheckMaxDepth = true; public GPIndividualProgramData() { - this.m_Area = new GPArea[1]; + this.m_Area = new GPArea[1]; m_Area[0] = new GPArea(); - this.m_Genotype = new AbstractGPNode[1]; + this.m_Genotype = new AbstractGPNode[1]; this.mutationOperator = new MutateDefault(); this.crossoverOperator = new CrossoverGPDefault(); } @@ -42,33 +42,33 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int this.m_Phenotype = new AbstractGPNode[individual.m_Phenotype.length]; for (int i = 0; i < individual.m_Phenotype.length; i++) { if (individual.m_Phenotype[i] != null) { - this.m_Phenotype[i] = (AbstractGPNode)individual.m_Phenotype[i].clone(); - } - } - } - if (individual.m_Genotype != null) { - this.m_Genotype = new AbstractGPNode[individual.m_Genotype.length]; - this.m_Area = new GPArea[individual.m_Area.length]; - for (int i = 0; i < individual.m_Genotype.length; i++) { - if (individual.m_Genotype[i] != null) { - this.m_Genotype[i] = (AbstractGPNode)individual.m_Genotype[i].clone(); - this.m_Genotype[i].connect(null); - } - if (individual.m_Area[i] != null) { - this.m_Area[i] = (GPArea)individual.m_Area[i].clone(); + this.m_Phenotype[i] = (AbstractGPNode) individual.m_Phenotype[i].clone(); } } } - this.m_InitFullGrowRatio = individual.m_InitFullGrowRatio; - this.m_InitDepth = individual.m_InitDepth; - this.m_maxAllowedDepth = individual.m_maxAllowedDepth; - this.m_CheckMaxDepth = individual.m_CheckMaxDepth; + if (individual.m_Genotype != null) { + this.m_Genotype = new AbstractGPNode[individual.m_Genotype.length]; + this.m_Area = new GPArea[individual.m_Area.length]; + for (int i = 0; i < individual.m_Genotype.length; i++) { + if (individual.m_Genotype[i] != null) { + this.m_Genotype[i] = (AbstractGPNode) individual.m_Genotype[i].clone(); + this.m_Genotype[i].connect(null); + } + if (individual.m_Area[i] != null) { + this.m_Area[i] = (GPArea) individual.m_Area[i].clone(); + } + } + } + this.m_InitFullGrowRatio = individual.m_InitFullGrowRatio; + this.m_InitDepth = individual.m_InitDepth; + this.m_maxAllowedDepth = individual.m_maxAllowedDepth; + this.m_CheckMaxDepth = individual.m_CheckMaxDepth; // cloning the members of AbstractEAIndividual this.age = individual.age; this.crossoverOperator = individual.crossoverOperator; this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); this.mutationProbability = individual.mutationProbability; this.selectionProbability = new double[individual.selectionProbability.length]; for (int i = 0; i < this.selectionProbability.length; i++) { @@ -86,8 +86,10 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int return (Object) new GPIndividualProgramData(this); } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -100,8 +102,7 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int } if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { return false; - } - else { + } else { for (int i = 0; i < this.m_Genotype.length; i++) { if ((this.m_Genotype[i] == null) || (indy.m_Genotype[i] == null) || (!this.m_Genotype[i].equals(indy.m_Genotype[i]))) { return false; @@ -117,39 +118,43 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int /************************************************************************************ * InterfaceDataTypeProgram methods */ - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ @Override - public void setProgramDataLength (int length) { - GPArea[] oldArea = this.m_Area; - AbstractGPNode[] oldProg = this.m_Genotype; - this.m_Area = new GPArea[length]; - this.m_Genotype = new AbstractGPNode[length]; + public void setProgramDataLength(int length) { + GPArea[] oldArea = this.m_Area; + AbstractGPNode[] oldProg = this.m_Genotype; + this.m_Area = new GPArea[length]; + this.m_Genotype = new AbstractGPNode[length]; for (int i = 0; ((i < this.m_Area.length) && (i < oldArea.length)); i++) { - this.m_Area[i] = oldArea[i]; - this.m_Genotype[i] = oldProg[i]; + this.m_Area[i] = oldArea[i]; + this.m_Genotype[i] = oldProg[i]; } for (int i = oldArea.length; i < this.m_Area.length; i++) { - this.m_Area[i] = oldArea[oldArea.length-1]; - this.m_Genotype[i] = oldProg[oldProg.length-1]; + this.m_Area[i] = oldArea[oldArea.length - 1]; + this.m_Genotype[i] = oldProg[oldProg.length - 1]; } } - /** This method allows you to read the program stored as Koza style node tree + /** + * This method allows you to read the program stored as Koza style node tree + * * @return AbstractGPNode representing the binary data. */ @Override public InterfaceProgram[] getProgramData() { this.m_Phenotype = new AbstractGPNode[this.m_Genotype.length]; for (int i = 0; i < this.m_Genotype.length; i++) { - this.m_Phenotype[i] = (AbstractGPNode)this.m_Genotype[i].clone(); + this.m_Phenotype[i] = (AbstractGPNode) this.m_Genotype[i].clone(); // if (!m_Phenotype[0].checkDepth(0)) { // System.err.println("error... " + m_Genotype[0].checkDepth(0)); // } if ((this.m_CheckMaxDepth) && (this.m_Phenotype[i].isMaxDepthViolated(this.m_maxAllowedDepth))) { - System.err.println("Trying to meet the Target Depth! " + this.m_Phenotype[i].isMaxDepthViolated(this.m_maxAllowedDepth) + " "+ m_Phenotype[i].getMaxDepth()); + System.err.println("Trying to meet the Target Depth! " + this.m_Phenotype[i].isMaxDepthViolated(this.m_maxAllowedDepth) + " " + m_Phenotype[i].getMaxDepth()); this.m_Phenotype[i].repairMaxDepth(this.m_Area[i], this.m_maxAllowedDepth); //System.out.println("TragetDepth: " + this.m_TargetDepth + " : " + this.m_Program.getMaxDepth()); } @@ -157,35 +162,40 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int return this.m_Phenotype; } - /** This method allows you to read the Program data without + /** + * This method allows you to read the Program data without * an update from the genotype + * * @return InterfaceProgram[] representing the Program. */ @Override public InterfaceProgram[] getProgramDataWithoutUpdate() { - if (this.m_Phenotype==null) { + if (this.m_Phenotype == null) { return getProgramData(); - } - else { + } else { return this.m_Phenotype; } } - /** This method allows you to set the program phenotype. - * @param program The new program. + /** + * This method allows you to set the program phenotype. + * + * @param program The new program. */ @Override public void SetProgramPhenotype(InterfaceProgram[] program) { if (program instanceof AbstractGPNode[]) { this.m_Phenotype = new AbstractGPNode[program.length]; for (int i = 0; i < this.m_Phenotype.length; i++) { - this.m_Phenotype[i] = (AbstractGPNode)((AbstractGPNode)program[i]).clone(); + this.m_Phenotype[i] = (AbstractGPNode) ((AbstractGPNode) program[i]).clone(); } } } - /** This method allows you to set the program genotype. - * @param program The new program. + /** + * This method allows you to set the program genotype. + * + * @param program The new program. */ @Override public void SetProgramGenotype(InterfaceProgram[] program) { @@ -193,13 +203,15 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int if (program instanceof AbstractGPNode[]) { this.m_Genotype = new AbstractGPNode[program.length]; for (int i = 0; i < this.m_Genotype.length; i++) { - this.m_Genotype[i] = (AbstractGPNode)((AbstractGPNode)program[i]).clone(); + this.m_Genotype[i] = (AbstractGPNode) ((AbstractGPNode) program[i]).clone(); } } } - /** This method allows you to set the function area - * @param area The area contains functions and terminals + /** + * This method allows you to set the function area + * + * @param area The area contains functions and terminals */ @Override public void SetFunctionArea(Object[] area) { @@ -208,7 +220,9 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int } } - /** This method allows you to set the function area + /** + * This method allows you to set the function area + * * @return The function area */ @Override @@ -219,15 +233,17 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int /************************************************************************************ * InterfaceEAIndividual methods */ - /** This method will init the individual with a given value for the + /** + * This method will init the individual with a given value for the * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. */ @Override public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof InterfaceProgram[]) { - this.SetProgramGenotype((InterfaceProgram[])obj); + this.SetProgramGenotype((InterfaceProgram[]) obj); } else { this.defaultInit(opt); System.out.println("Initial value for GPIndividualDoubleData is no InterfaceProgram[]!"); @@ -236,8 +252,10 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int this.crossoverOperator.init(this, opt); } - /** This method will return a string description of the GAIndividal + /** + * This method will return a string description of the GAIndividal * noteably the Genotype. + * * @return A descriptive string */ @Override @@ -266,7 +284,9 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int * InterfaceGPIndividual methods */ - /** This method will allow the user to read the program genotype + /** + * This method will allow the user to read the program genotype + * * @return AbstractGPNode */ @Override @@ -274,28 +294,32 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int return this.m_Genotype; } - /** This method will allow the user to set the current program 'genotype'. - * @param b The new programgenotype of the Individual + /** + * This method will allow the user to set the current program 'genotype'. + * + * @param b The new programgenotype of the Individual */ @Override public void SetPGenotype(AbstractGPNode[] b) { this.m_Genotype = b; - this.m_Phenotype=null; + this.m_Phenotype = null; } - /** This method will allow the user to set the current program 'genotype'. - * @param b The new program genotype of the Individual - * @param i The index where to insert the new program + /** + * This method will allow the user to set the current program 'genotype'. + * + * @param b The new program genotype of the Individual + * @param i The index where to insert the new program */ @Override public void SetPGenotype(AbstractGPNode b, int i) { this.m_Genotype[i] = b; m_Genotype[i].updateDepth(0); // System.out.println("Setting pheno of depth " + b.getMaxDepth() + " " + b.getStringRepresentation()); - this.m_Phenotype=null; + this.m_Phenotype = null; } - /** + /** * This method performs a simple one element mutation on the program */ @Override @@ -306,38 +330,37 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int this.defaultInit(null); } else { AbstractGPNode parent = nodeToMutate.getParent(); - if (m_CheckMaxDepth && (nodeToMutate.getDepth()==m_maxAllowedDepth)) { // mutate with a constant - AbstractGPNode newNode = (AbstractGPNode)(((AbstractGPNode)this.m_Area[i].getRandomNodeWithArity(0).clone())); - newNode.setDepth(nodeToMutate.getDepth()); - parent.setNode(newNode, nodeToMutate); - } else { - AbstractGPNode newNode = (AbstractGPNode)(((AbstractGPNode)this.m_Area[i].getRandomNode().clone())); - newNode.setDepth(nodeToMutate.getDepth()); - newNode.initGrow(this.m_Area[i], this.m_maxAllowedDepth); - parent.setNode(newNode, nodeToMutate); - } + if (m_CheckMaxDepth && (nodeToMutate.getDepth() == m_maxAllowedDepth)) { // mutate with a constant + AbstractGPNode newNode = (AbstractGPNode) (((AbstractGPNode) this.m_Area[i].getRandomNodeWithArity(0).clone())); + newNode.setDepth(nodeToMutate.getDepth()); + parent.setNode(newNode, nodeToMutate); + } else { + AbstractGPNode newNode = (AbstractGPNode) (((AbstractGPNode) this.m_Area[i].getRandomNode().clone())); + newNode.setDepth(nodeToMutate.getDepth()); + newNode.initGrow(this.m_Area[i], this.m_maxAllowedDepth); + parent.setNode(newNode, nodeToMutate); + } //if (!m_Genotype[i].checkDepth(0) || (m_Genotype[i].isMaxDepthViolated(m_maxAllowedDepth))) { // System.err.println("Error in GPIndividualProgramData.defaultMutate!"); //} } } - m_Phenotype=null; // reset pheno + m_Phenotype = null; // reset pheno } @Override public void defaultInit(InterfaceOptimizationProblem prob) { - m_Phenotype=null; // reset pheno + m_Phenotype = null; // reset pheno for (int i = 0; i < this.m_Area.length; i++) { if (this.m_Area[i] == null) { - EVAERROR.errorMsgOnce("Error in GPIndividualProgramData.defaultInit(): Area["+i+"] == null !!"); + EVAERROR.errorMsgOnce("Error in GPIndividualProgramData.defaultInit(): Area[" + i + "] == null !!"); } else { - this.m_Genotype[i] = (AbstractGPNode)(this.m_Area[i].getRandomNonTerminal()).clone(); + this.m_Genotype[i] = (AbstractGPNode) (this.m_Area[i].getRandomNonTerminal()).clone(); this.m_Genotype[i].setDepth(0); int targetDepth = RNG.randomInt(1, this.m_InitDepth); if (RNG.flipCoin(this.m_InitFullGrowRatio)) { this.m_Genotype[i].initFull(this.m_Area[i], targetDepth); - } - else { + } else { this.m_Genotype[i].initGrow(this.m_Area[i], targetDepth); } } @@ -347,8 +370,10 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -356,28 +381,36 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int return "GP individual"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a GP individual suited to optimize Koza style program trees."; } - /** This method will toggle between checking for max depth or not. - * @param b the Switch. + /** + * This method will toggle between checking for max depth or not. + * + * @param b the Switch. */ public void setCheckMaxDepth(boolean b) { this.m_CheckMaxDepth = b; } + public boolean getCheckMaxDepth() { return this.m_CheckMaxDepth; } + public String checkMaxDepthTipText() { return "If activated the maximum depth of the program tree will be enforced."; } - /** This method set/get the init Full Grow Ratio. - * @param b The new init Full Grow Ratio of the GP Tree. + /** + * This method set/get the init Full Grow Ratio. + * + * @param b The new init Full Grow Ratio of the GP Tree. */ public void setInitFullGrowRatio(double b) { if (b < 0) { @@ -388,15 +421,19 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int } this.m_InitFullGrowRatio = b; } + public double getInitFullGrowRatio() { return this.m_InitFullGrowRatio; } + public String initFullGrowRatioTipText() { return "The ratio between the full and the grow init methods (1 uses only full initializing)."; } - /** This method set/get the init depth. - * @param b The new init Depth of the GP Tree. + /** + * This method set/get the init depth. + * + * @param b The new init Depth of the GP Tree. */ public void setInitDepth(int b) { if (b > this.m_maxAllowedDepth) { @@ -405,40 +442,46 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int } this.m_InitDepth = b; } + public int getInitDepth() { return this.m_InitDepth; } + public String initDepthTipText() { return "The initial depth of the GP Tree."; } - /** This method set/get the target depth. - * @param b The new target Depth of the GP Tree. + /** + * This method set/get the target depth. + * + * @param b The new target Depth of the GP Tree. */ public void setMaxAllowedDepth(int b) { this.m_maxAllowedDepth = b; } + @Override public int getMaxAllowedDepth() { return this.m_maxAllowedDepth; } + public String maxAllowedDepthTipText() { return "The maximum depth allowed for the GP tree."; } - + public String[] customPropertyOrder() { - return new String[] {"initDepth", "checkMaxDepth", "maxAllowedDepth"}; + return new String[]{"initDepth", "checkMaxDepth", "maxAllowedDepth"}; } - public void updateDepth() { - for (int i=0; i, Serializable { - private AbstractEAIndividual refIndy=null; - private InterfaceDistanceMetric distMetric = null; - private boolean closerMeansLess = true; - - /** - * Constructor with a reference individual to which the distance is measured and the corresponding desired metric. - * Using closerIsLess it can be switched between increasing and decreasing order. - * - * @param referenceIndy - * @param metric - * @param closerIsLess - */ - public IndividualDistanceComparator(AbstractEAIndividual referenceIndy, InterfaceDistanceMetric metric, boolean closerIsLess) { - refIndy = referenceIndy; - distMetric = metric; - closerMeansLess = closerIsLess; - } + private AbstractEAIndividual refIndy = null; + private InterfaceDistanceMetric distMetric = null; + private boolean closerMeansLess = true; + + /** + * Constructor with a reference individual to which the distance is measured and the corresponding desired metric. + * Using closerIsLess it can be switched between increasing and decreasing order. + * + * @param referenceIndy + * @param metric + * @param closerIsLess + */ + public IndividualDistanceComparator(AbstractEAIndividual referenceIndy, InterfaceDistanceMetric metric, boolean closerIsLess) { + refIndy = referenceIndy; + distMetric = metric; + closerMeansLess = closerIsLess; + } @Override - public int compare(Object o1, Object o2) { - double d1 = distMetric.distance((AbstractEAIndividual)o1, refIndy); - double d2 = distMetric.distance((AbstractEAIndividual)o2, refIndy); + public int compare(Object o1, Object o2) { + double d1 = distMetric.distance((AbstractEAIndividual) o1, refIndy); + double d2 = distMetric.distance((AbstractEAIndividual) o2, refIndy); - if (d1==d2) { - return 0; - } - if (closerMeansLess) { - return ((d1, Serializable { - /** - * Generated serial version identifier - */ - private static final long serialVersionUID = 3182129129041083881L; - /** - * - */ - private double [] fitWeights = null; - - /** - * - * @param weights - */ - public IndividualWeightedFitnessComparator(double[] weights) { - setFitWeights(weights); - } - - /* - * (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof IndividualWeightedFitnessComparator) { - IndividualWeightedFitnessComparator o = (IndividualWeightedFitnessComparator)obj; - if (fitWeights==null && (o.fitWeights==null)) { - return true; - } - if (fitWeights==null || o.fitWeights==null) { + /** + * Generated serial version identifier + */ + private static final long serialVersionUID = 3182129129041083881L; + /** + * + */ + private double[] fitWeights = null; + + /** + * @param weights + */ + public IndividualWeightedFitnessComparator(double[] weights) { + setFitWeights(weights); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof IndividualWeightedFitnessComparator) { + IndividualWeightedFitnessComparator o = (IndividualWeightedFitnessComparator) obj; + if (fitWeights == null && (o.fitWeights == null)) { + return true; + } + if (fitWeights == null || o.fitWeights == null) { + return false; + } + // now both are non null: + if (fitWeights.length == o.fitWeights.length) { + for (int i = 0; i < fitWeights.length; i++) { + if (fitWeights[i] != o.fitWeights[i]) { return false; } - // now both are non null: - if (fitWeights.length==o.fitWeights.length) { - for (int i=0; i score2) { - return 1; - } - else { - return 0; - } - } + public int hashCode() { + if (fitWeights == null) { + return super.hashCode(); + } + int code = 0; + for (int i = 0; i < fitWeights.length; i++) { + code += (int) (fitWeights[i] * 10000) % (10000 * (i + 1)); + } + return code; + } - /** - * - * @param f - * @return - */ - private double calcScore(double[] f) { - if (f==null || fitWeights==null) { - throw new RuntimeException("Error, missing information in " + this.getClass()); - } - if (f.length!=fitWeights.length) { - if (f.length score2) { + return 1; + } else { + return 0; + } + } + + /** + * @param f + * @return + */ + private double calcScore(double[] f) { + if (f == null || fitWeights == null) { + throw new RuntimeException("Error, missing information in " + this.getClass()); + } + if (f.length != fitWeights.length) { + if (f.length < fitWeights.length) { + EVAERROR.errorMsgOnce("Warning, fitness vector has less dimensions than the weights... some weights are ignored, in " + this.getClass()); + } else { + EVAERROR.errorMsgOnce("Warning, fitness vector has more dimensions than the weights... some fitness values are ignored, in " + this.getClass()); + } + } + double s = 0; + for (int i = 0; i < Math.min(f.length, fitWeights.length); i++) { + s += f[i] * fitWeights[i]; + } + return s; + } + + /** + * @param indy + * @return + */ + public double calcScore(AbstractEAIndividual indy) { + double[] f = indy.getFitness(); + return calcScore(f); + } + + /** + * @param dim + * @param v + */ + public void setAllWeights(int dim, double v) { + fitWeights = new double[dim]; + for (int i = 0; i < fitWeights.length; i++) { + fitWeights[i] = v; + } + } + + public void setFitWeights(double[] fitWeights) { + this.fitWeights = fitWeights; + } + + public double[] getFitWeights() { + return fitWeights; + } + + public String fitWeightsTipText() { + return "Weights of the fitness values in the linear combination"; + } - /** - * - * @param dim - * @param v - */ - public void setAllWeights(int dim, double v) { - fitWeights = new double[dim]; - for (int i = 0; i < fitWeights.length; i++) { - fitWeights[i]=v; - } - } - - public void setFitWeights(double [] fitWeights) { - this.fitWeights = fitWeights; - } - public double [] getFitWeights() { - return fitWeights; - } - public String fitWeightsTipText() { - return "Weights of the fitness values in the linear combination"; - } - // public static void main(String[] args) { // TF1Problem prob = new TF1Problem(); // Population pop = new Population(10); diff --git a/src/eva2/optimization/individuals/InterfaceDataTypeBinary.java b/src/eva2/optimization/individuals/InterfaceDataTypeBinary.java index 28287c27..77c1a190 100644 --- a/src/eva2/optimization/individuals/InterfaceDataTypeBinary.java +++ b/src/eva2/optimization/individuals/InterfaceDataTypeBinary.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals; import java.util.BitSet; -/** This interface gives access to a binary phenotype and except +/** + * This interface gives access to a binary phenotype and except * for problem specific operators should only be used by the * optimization problem. * Created by IntelliJ IDEA. @@ -13,35 +14,47 @@ import java.util.BitSet; */ public interface InterfaceDataTypeBinary { - /** This method allows you to request a certain amount of binary data - * @param length The lenght of the BitSet that is to be optimized + /** + * This method allows you to request a certain amount of binary data + * + * @param length The lenght of the BitSet that is to be optimized */ public void setBinaryDataLength(int length); - /** This method returns the length of the binary data set + /** + * This method returns the length of the binary data set + * * @return The number of bits stored */ public int size(); - /** This method allows you to read the binary data + /** + * This method allows you to read the binary data + * * @return BitSet representing the binary data. */ public BitSet getBinaryData(); - /** This method allows you to read the binary data without + /** + * This method allows you to read the binary data without * an update from the genotype + * * @return BitSet representing the binary data. */ public BitSet getBinaryDataWithoutUpdate(); - /** This method allows you to set the binary data. - * @param binaryData The new binary data. + /** + * This method allows you to set the binary data. + * + * @param binaryData The new binary data. */ public void SetBinaryPhenotype(BitSet binaryData); - /** This method allows you to set the binary data, this can be used for + /** + * This method allows you to set the binary data, this can be used for * memetic algorithms. - * @param binaryData The new binary data. + * + * @param binaryData The new binary data. */ public void SetBinaryGenotype(BitSet binaryData); } diff --git a/src/eva2/optimization/individuals/InterfaceDataTypeDouble.java b/src/eva2/optimization/individuals/InterfaceDataTypeDouble.java index 27c8a4f3..43548654 100644 --- a/src/eva2/optimization/individuals/InterfaceDataTypeDouble.java +++ b/src/eva2/optimization/individuals/InterfaceDataTypeDouble.java @@ -1,6 +1,7 @@ package eva2.optimization.individuals; -/** This interface gives access to a double phenotype and except +/** + * This interface gives access to a double phenotype and except * for problemspecific operators should only be used by the * optimization problem. * Created by IntelliJ IDEA. @@ -11,48 +12,64 @@ package eva2.optimization.individuals; */ public interface InterfaceDataTypeDouble { - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ public void setDoubleDataLength(int length); - /** This method returns the length of the double data set + /** + * This method returns the length of the double data set + * * @return The number of doubles stored */ public int size(); - /** This method will set the range of the double attributes. + /** + * This method will set the range of the double attributes. * Note: range[d][0] gives the lower bound and range[d] gives the upper bound * for dimension d. - * @param range The new range for the double data. + * + * @param range The new range for the double data. */ public void SetDoubleRange(double[][] range); - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ public double[][] getDoubleRange(); - /** This method allows you to read the double data + /** + * This method allows you to read the double data + * * @return double[] representing the double data. */ public double[] getDoubleData(); - /** This method allows you to read the double data without + /** + * This method allows you to read the double data without * an update from the genotype + * * @return double[] representing the double data. */ public double[] getDoubleDataWithoutUpdate(); - /** This method allows you to set the double data, usually the phenotype data. Consider using + /** + * This method allows you to set the double data, usually the phenotype data. Consider using * SetDoubleDataLamarckian to set the genotype data. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ public void SetDoublePhenotype(double[] doubleData); - /** This method allows you to set the double data, this can be used for + /** + * This method allows you to set the double data, this can be used for * memetic algorithms. - * @param doubleData The new double data. + * + * @param doubleData The new double data. */ public void SetDoubleGenotype(double[] doubleData); } diff --git a/src/eva2/optimization/individuals/InterfaceDataTypeInteger.java b/src/eva2/optimization/individuals/InterfaceDataTypeInteger.java index fb79dc6b..c0c44a36 100644 --- a/src/eva2/optimization/individuals/InterfaceDataTypeInteger.java +++ b/src/eva2/optimization/individuals/InterfaceDataTypeInteger.java @@ -1,6 +1,7 @@ package eva2.optimization.individuals; -/** This interface gives access to a integer phenotype and except +/** + * This interface gives access to a integer phenotype and except * for problemspecific operators should only be used by the * optimization problem. * Created by IntelliJ IDEA. @@ -11,47 +12,63 @@ package eva2.optimization.individuals; */ public interface InterfaceDataTypeInteger { - /** This method allows you to request a certain amount of int data - * @param length The lenght of the int[] that is to be optimized + /** + * This method allows you to request a certain amount of int data + * + * @param length The lenght of the int[] that is to be optimized */ - public void setIntegerDataLength (int length); + public void setIntegerDataLength(int length); - /** This method returns the length of the int data set + /** + * This method returns the length of the int data set + * * @return The number of integers stored */ public int size(); - /** This method will set the range of the int attributes. + /** + * This method will set the range of the int attributes. * Note: range[d][0] gives the lower bound and range[d] gives the upper bound * for dimension d. - * @param range The new range for the int data. + * + * @param range The new range for the int data. */ public void SetIntRange(int[][] range); - /** This method will return the range for all int attributes. + /** + * This method will return the range for all int attributes. + * * @return The range array. */ public int[][] getIntRange(); - /** This method allows you to read the int data + /** + * This method allows you to read the int data + * * @return int[] representing the int data. */ public int[] getIntegerData(); - /** This method allows you to read the int data without + /** + * This method allows you to read the int data without * an update from the genotype + * * @return int[] representing the int data. */ public int[] getIntegerDataWithoutUpdate(); - /** This method allows you to set the int data. - * @param intData The new int data. + /** + * This method allows you to set the int data. + * + * @param intData The new int data. */ public void SetIntPhenotype(int[] intData); - /** This method allows you to set the int data, this can be used for + /** + * This method allows you to set the int data, this can be used for * memetic algorithms. - * @param intData The new int data. + * + * @param intData The new int data. */ public void SetIntGenotype(int[] intData); } diff --git a/src/eva2/optimization/individuals/InterfaceDataTypePermutation.java b/src/eva2/optimization/individuals/InterfaceDataTypePermutation.java index 03596d3a..b7adafe5 100644 --- a/src/eva2/optimization/individuals/InterfaceDataTypePermutation.java +++ b/src/eva2/optimization/individuals/InterfaceDataTypePermutation.java @@ -1,16 +1,17 @@ package eva2.optimization.individuals; -/** This interface gives access to a permutation phenotype and except +/** + * This interface gives access to a permutation phenotype and except * for problemspecific operators should only be used by the * optimization problem. *

Title: EvA2

- * + *

*

Description:

- * + *

*

Copyright: * (c) 2003

- * + *

*

Company:

* Defines an interface for a datatype of a permutation. * @@ -19,40 +20,48 @@ package eva2.optimization.individuals; */ public interface InterfaceDataTypePermutation { - /** - * setLength sets the length of the permutation. - * - * @param length int new length - */ - public void setPermutationDataLength(int[] length); + /** + * setLength sets the length of the permutation. + * + * @param length int new length + */ + public void setPermutationDataLength(int[] length); - /** - * size returns the size of the permutation. - * - * @return int - */ - public int[] sizePermutation(); + /** + * size returns the size of the permutation. + * + * @return int + */ + public int[] sizePermutation(); - /** This method allows you to read the permutation data + /** + * This method allows you to read the permutation data + * * @return int[] represent the permutation. */ int[][] getPermutationData(); - /** This method allows you to read the permutation data without + /** + * This method allows you to read the permutation data without * an update from the genotype + * * @return int[] representing the permutation. */ public int[][] getPermutationDataWithoutUpdate(); - /** This method allows you to set the permutation. - * @param perm The new permutation data. + /** + * This method allows you to set the permutation. + * + * @param perm The new permutation data. */ void SetPermutationPhenotype(int[][] perm); - /** This method allows you to set the permutation data, this can be used for + /** + * This method allows you to set the permutation data, this can be used for * memetic algorithms. - * @param perm The new permutation data. + * + * @param perm The new permutation data. */ void SetPermutationGenotype(int[][] perm); diff --git a/src/eva2/optimization/individuals/InterfaceDataTypeProgram.java b/src/eva2/optimization/individuals/InterfaceDataTypeProgram.java index c804c092..5dcc46ac 100644 --- a/src/eva2/optimization/individuals/InterfaceDataTypeProgram.java +++ b/src/eva2/optimization/individuals/InterfaceDataTypeProgram.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals; import eva2.optimization.individuals.codings.gp.InterfaceProgram; -/** This interface gives access to a program phenotype and except +/** + * This interface gives access to a program phenotype and except * for problemspecific operators should only be used by the * optimization problem. * Created by IntelliJ IDEA. @@ -13,39 +14,53 @@ import eva2.optimization.individuals.codings.gp.InterfaceProgram; */ public interface InterfaceDataTypeProgram { - /** This method allows you to request a certain amount of double data - * @param length The lenght of the double[] that is to be optimized + /** + * This method allows you to request a certain amount of double data + * + * @param length The lenght of the double[] that is to be optimized */ - public void setProgramDataLength (int length); + public void setProgramDataLength(int length); - /** This method allows you to read the program stored as Koza style node tree + /** + * This method allows you to read the program stored as Koza style node tree + * * @return AbstractGPNode representing the binary data. */ public InterfaceProgram[] getProgramData(); - /** This method allows you to read the Program data without + /** + * This method allows you to read the Program data without * an update from the genotype + * * @return InterfaceProgram[] representing the Program. */ public InterfaceProgram[] getProgramDataWithoutUpdate(); - /** This method allows you to set the program. - * @param program The new program. + /** + * This method allows you to set the program. + * + * @param program The new program. */ public void SetProgramPhenotype(InterfaceProgram[] program); - /** This method allows you to set the program. - * @param program The new program. + /** + * This method allows you to set the program. + * + * @param program The new program. */ public void SetProgramGenotype(InterfaceProgram[] program); - - /** This method allows you to set the function area - * @param area The area contains functions and terminals + + /** + * This method allows you to set the function area + * + * @param area The area contains functions and terminals */ public void SetFunctionArea(Object[] area); - /** This method allows you to get the function area - * @return The area contains functions and terminals + /** + * This method allows you to get the function area + * + * @return The area contains functions and terminals */ public Object[] getFunctionArea(); } diff --git a/src/eva2/optimization/individuals/InterfaceESIndividual.java b/src/eva2/optimization/individuals/InterfaceESIndividual.java index 5436e0f1..08c20a78 100644 --- a/src/eva2/optimization/individuals/InterfaceESIndividual.java +++ b/src/eva2/optimization/individuals/InterfaceESIndividual.java @@ -1,6 +1,7 @@ package eva2.optimization.individuals; -/** This interface gives access to a real-valued genotype and should +/** + * This interface gives access to a real-valued genotype and should * only be used by mutation and crossover operators. Onyl exception are * data type specific optimization strategies like PSO or DE. * Created by IntelliJ IDEA. @@ -11,13 +12,17 @@ package eva2.optimization.individuals; */ public interface InterfaceESIndividual { - /** This method will allow the user to read the ES 'genotype' + /** + * This method will allow the user to read the ES 'genotype' + * * @return BitSet */ public double[] getDGenotype(); - /** This method will allow the user to set the current ES 'genotype'. - * @param b The new genotype of the Individual + /** + * This method will allow the user to set the current ES 'genotype'. + * + * @param b The new genotype of the Individual */ public void SetDGenotype(double[] b); // @@ -28,7 +33,9 @@ public interface InterfaceESIndividual { // */ // public void SetDoubleRange(double[][] range); - /** This method will return the range for all double attributes. + /** + * This method will return the range for all double attributes. + * * @return The range array. */ public double[][] getDoubleRange(); diff --git a/src/eva2/optimization/individuals/InterfaceGAIndividual.java b/src/eva2/optimization/individuals/InterfaceGAIndividual.java index f26db072..e7171449 100644 --- a/src/eva2/optimization/individuals/InterfaceGAIndividual.java +++ b/src/eva2/optimization/individuals/InterfaceGAIndividual.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals; import java.util.BitSet; -/** This interface gives access to a binary genotype and should +/** + * This interface gives access to a binary genotype and should * only be used by mutation and crossover operators. Exceptions are * data type specific optimization strategies like CHC or PBIL. * Created by IntelliJ IDEA. @@ -11,26 +12,30 @@ import java.util.BitSet; * Time: 14:25:24 * To change this template use Options | File Templates. */ -public interface InterfaceGAIndividual { +public interface InterfaceGAIndividual { - /** + /** * This method will allow the user to read the GA genotype. + * * @return BitSet */ public BitSet getBGenotype(); - /** + /** * This method will allow the user to set the current GA genotype. * Use this method with care, since the object is returned when using * getBinaryData() you can directly alter the genotype without using * this method. - * @param b The new genotype of the Individual + * + * @param b The new genotype of the Individual */ public void SetBGenotype(BitSet b); - /** This method allows the user to read the length of the genotype. + /** + * This method allows the user to read the length of the genotype. * This may be necessary since BitSet.lenght only returns the index * of the last significat bit. + * * @return The length of the genotype. */ public int getGenotypeLength(); diff --git a/src/eva2/optimization/individuals/InterfaceGIIndividual.java b/src/eva2/optimization/individuals/InterfaceGIIndividual.java index 8fb4a855..f9a18cc3 100644 --- a/src/eva2/optimization/individuals/InterfaceGIIndividual.java +++ b/src/eva2/optimization/individuals/InterfaceGIIndividual.java @@ -1,7 +1,8 @@ package eva2.optimization.individuals; -/** This interface gives access to a integer genotype and should +/** + * This interface gives access to a integer genotype and should * only be used by mutation and crossover operators. * Created by IntelliJ IDEA. * User: streiche @@ -10,40 +11,52 @@ package eva2.optimization.individuals; * To change this template use File | Settings | File Templates. */ public interface InterfaceGIIndividual { - - /** This method allows you to request a certain amount of int data - * @param length The lenght of the int[] that is to be optimized - */ - public void setIntegerDataLength (int length); - /** This method will return the range for all int attributes. + /** + * This method allows you to request a certain amount of int data + * + * @param length The lenght of the int[] that is to be optimized + */ + public void setIntegerDataLength(int length); + + /** + * This method will return the range for all int attributes. + * * @return The range array. */ public int[][] getIntRange(); - /** This method will set the range of the int attributes. + /** + * This method will set the range of the int attributes. * Note: range[d][0] gives the lower bound and range[d] gives the upper bound * for dimension d where both are included. - * @param range The new range for the int data. + * + * @param range The new range for the int data. */ public void SetIntRange(int[][] range); - /** This method will allow the user to read the GI genotype + /** + * This method will allow the user to read the GI genotype + * * @return BitSet */ public int[] getIGenotype(); - /** This method will allow the user to set the current GI genotype. + /** + * This method will allow the user to set the current GI genotype. * Use this method with care, since the object is returned when using * getIGenotype() you can directly alter the genotype without using * this method. - * @param b The new genotype of the Individual + * + * @param b The new genotype of the Individual */ public void SetIGenotype(int[] b); - /** This method allows the user to read the length of the genotype. + /** + * This method allows the user to read the length of the genotype. * This may be necessary since BitSet.lenght only returns the index * of the last significat bit. + * * @return The length of the genotype. */ public int getGenotypeLength(); diff --git a/src/eva2/optimization/individuals/InterfaceGPIndividual.java b/src/eva2/optimization/individuals/InterfaceGPIndividual.java index d093ddfd..9804924b 100644 --- a/src/eva2/optimization/individuals/InterfaceGPIndividual.java +++ b/src/eva2/optimization/individuals/InterfaceGPIndividual.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals; import eva2.optimization.individuals.codings.gp.AbstractGPNode; -/** This interface gives access to a tree-based genotype and should +/** + * This interface gives access to a tree-based genotype and should * only be used by mutation and crossover operators. * Created by IntelliJ IDEA. * User: streiche @@ -12,29 +13,38 @@ import eva2.optimization.individuals.codings.gp.AbstractGPNode; */ public interface InterfaceGPIndividual { - /** This method will allow the user to read the program 'genotype' + /** + * This method will allow the user to read the program 'genotype' + * * @return AbstractGPNode */ public AbstractGPNode[] getPGenotype(); - /** This method will allow the user to set the current program 'genotype'. - * @param b The new program genotype of the Individual + /** + * This method will allow the user to set the current program 'genotype'. + * + * @param b The new program genotype of the Individual */ public void SetPGenotype(AbstractGPNode[] b); - /** This method will allow the user to set the current program 'genotype'. - * @param b The new program genotype of the Individual - * @param i The index where to insert the new program + /** + * This method will allow the user to set the current program 'genotype'. + * + * @param b The new program genotype of the Individual + * @param i The index where to insert the new program */ public void SetPGenotype(AbstractGPNode b, int i); - /** This method allows you to get the function area + /** + * This method allows you to get the function area + * * @return area The area contains functions and terminals */ public Object[] getFunctionArea(); /** * Return the maximal allowed depth of a GP tree (or -1 if it does not apply). + * * @return */ public int getMaxAllowedDepth(); diff --git a/src/eva2/optimization/individuals/InterfaceOBGAIndividual.java b/src/eva2/optimization/individuals/InterfaceOBGAIndividual.java index 219038f8..c2f3aac4 100644 --- a/src/eva2/optimization/individuals/InterfaceOBGAIndividual.java +++ b/src/eva2/optimization/individuals/InterfaceOBGAIndividual.java @@ -1,11 +1,13 @@ package eva2.optimization.individuals; -/** This interface gives access to a permutation genotype and should +/** + * This interface gives access to a permutation genotype and should * only be used by mutation and crossover operators. *

Title: EvA2

*

Description:

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author planatsc * @version 1.0 */ @@ -13,18 +15,18 @@ package eva2.optimization.individuals; public interface InterfaceOBGAIndividual { - /** - * getOBGenotype gets the genotype. - * - * @return int[] genotype - */ - public int[][] getOBGenotype(); + /** + * getOBGenotype gets the genotype. + * + * @return int[] genotype + */ + public int[][] getOBGenotype(); - /** - * SetOBGenotype sets the genotype of the individual. - * - * @param b int[] new genotype - */ - public void SetOBGenotype(int[][] b); + /** + * SetOBGenotype sets the genotype of the individual. + * + * @param b int[] new genotype + */ + public void SetOBGenotype(int[][] b); } diff --git a/src/eva2/optimization/individuals/OBGAIndividualPermutationData.java b/src/eva2/optimization/individuals/OBGAIndividualPermutationData.java index bd79634d..43e04592 100644 --- a/src/eva2/optimization/individuals/OBGAIndividualPermutationData.java +++ b/src/eva2/optimization/individuals/OBGAIndividualPermutationData.java @@ -6,66 +6,72 @@ import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.operator.mutation.MutateOBGAFlip; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.ArrayList; -/** This individual uses a permutation based genotype to code for +/** + * This individual uses a permutation based genotype to code for * permutations. *

Title: EvA2

*

Description:

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author planatsc * @version 1.0 */ public class OBGAIndividualPermutationData extends AbstractEAIndividual implements InterfaceDataTypePermutation, InterfaceOBGAIndividual, java.io.Serializable { - int[][] m_Phenotype; - int[][] m_Genotype; - int[] firstindex; + int[][] m_Phenotype; + int[][] m_Genotype; + int[] firstindex; - public OBGAIndividualPermutationData() { - this.mutationProbability = 0.2; - this.mutationOperator = new MutateOBGAFlip(); - this.crossoverProbability = 1.0; - this.crossoverOperator = new CrossoverOBGAPMX(); - this.setPermutationDataLength(new int[]{20}); - firstindex = new int[]{0}; - } - - public OBGAIndividualPermutationData(OBGAIndividualPermutationData individual) { - if (individual.m_Phenotype != null) { - this.m_Phenotype = new int[individual.m_Phenotype.length][]; - for (int i = 0; i < m_Phenotype.length; i++) { - this.m_Phenotype[i] =new int[ individual.m_Phenotype[i].length]; - System.arraycopy(individual.m_Phenotype[i], 0, this.m_Phenotype[i], 0, this.m_Phenotype[i].length); - } - } - this.m_Genotype = new int[individual.m_Genotype.length][]; - for (int i = 0; i < m_Genotype.length; i++) { - this.m_Genotype[i] =new int[ individual.m_Genotype[i].length]; - System.arraycopy(individual.m_Genotype[i], 0, this.m_Genotype[i], 0, this.m_Genotype[i].length); - } - - System.arraycopy(individual.m_Genotype, 0, this.m_Genotype, 0, this.m_Genotype.length); - this.firstindex = individual.firstindex; - this.age = individual.age; - this.crossoverOperator = individual.crossoverOperator; - this.crossoverProbability = individual.crossoverProbability; - this.mutationOperator = (InterfaceMutation)individual.mutationOperator.clone(); - this.mutationProbability = individual.mutationProbability; - this.selectionProbability = new double[individual.selectionProbability.length]; - for (int i = 0; i < this.selectionProbability.length; i++) { - this.selectionProbability[i] = individual.selectionProbability[i]; } - this.fitness = new double[individual.fitness.length]; - for (int i = 0; i < this.fitness.length; i++) { - this.fitness[i] = individual.fitness[i]; + public OBGAIndividualPermutationData() { + this.mutationProbability = 0.2; + this.mutationOperator = new MutateOBGAFlip(); + this.crossoverProbability = 1.0; + this.crossoverOperator = new CrossoverOBGAPMX(); + this.setPermutationDataLength(new int[]{20}); + firstindex = new int[]{0}; } - this.cloneAEAObjects(individual); - } - /** This method checks on equality regarding genotypic equality - * @param individual The individual to compare to. + public OBGAIndividualPermutationData(OBGAIndividualPermutationData individual) { + if (individual.m_Phenotype != null) { + this.m_Phenotype = new int[individual.m_Phenotype.length][]; + for (int i = 0; i < m_Phenotype.length; i++) { + this.m_Phenotype[i] = new int[individual.m_Phenotype[i].length]; + System.arraycopy(individual.m_Phenotype[i], 0, this.m_Phenotype[i], 0, this.m_Phenotype[i].length); + } + } + this.m_Genotype = new int[individual.m_Genotype.length][]; + for (int i = 0; i < m_Genotype.length; i++) { + this.m_Genotype[i] = new int[individual.m_Genotype[i].length]; + System.arraycopy(individual.m_Genotype[i], 0, this.m_Genotype[i], 0, this.m_Genotype[i].length); + } + + System.arraycopy(individual.m_Genotype, 0, this.m_Genotype, 0, this.m_Genotype.length); + this.firstindex = individual.firstindex; + this.age = individual.age; + this.crossoverOperator = individual.crossoverOperator; + this.crossoverProbability = individual.crossoverProbability; + this.mutationOperator = (InterfaceMutation) individual.mutationOperator.clone(); + this.mutationProbability = individual.mutationProbability; + this.selectionProbability = new double[individual.selectionProbability.length]; + for (int i = 0; i < this.selectionProbability.length; i++) { + this.selectionProbability[i] = individual.selectionProbability[i]; + } + this.fitness = new double[individual.fitness.length]; + for (int i = 0; i < this.fitness.length; i++) { + this.fitness[i] = individual.fitness[i]; + } + this.cloneAEAObjects(individual); + } + + /** + * This method checks on equality regarding genotypic equality + * + * @param individual The individual to compare to. * @return boolean if equal true else false. */ @Override @@ -79,7 +85,7 @@ public class OBGAIndividualPermutationData extends AbstractEAIndividual implemen return false; } for (int i = 0; i < this.m_Genotype.length; i++) { - if (this.m_Genotype[i].length != indy.m_Genotype[i].length) { + if (this.m_Genotype[i].length != indy.m_Genotype[i].length) { for (int j = 0; j < this.m_Genotype[i].length; j++) { if (this.m_Genotype[i][j] != indy.m_Genotype[i][j]) { return false; @@ -94,78 +100,85 @@ public class OBGAIndividualPermutationData extends AbstractEAIndividual implemen } } - /************************************************************************************ - * AbstractEAIndividual methods - */ + /************************************************************************************ + * AbstractEAIndividual methods + */ - /** This method will init the individual with a given value for the - * phenotype. - * @param obj The initial value for the phenotype - * @param opt The optimization problem that is to be solved. - */ + /** + * This method will init the individual with a given value for the + * phenotype. + * + * @param obj The initial value for the phenotype + * @param opt The optimization problem that is to be solved. + */ @Override - public void initByValue(Object obj, InterfaceOptimizationProblem opt) { - if (obj instanceof int[]) { - this.SetPermutationGenotype((int[][]) obj); - } else { - this.defaultInit(opt); - System.out.println("Initial value for OBGAIndividualBinaryData is no Permutation!"); - } - this.mutationOperator.init(this, opt); - this.crossoverOperator.init(this, opt); - } + public void initByValue(Object obj, InterfaceOptimizationProblem opt) { + if (obj instanceof int[]) { + this.SetPermutationGenotype((int[][]) obj); + } else { + this.defaultInit(opt); + System.out.println("Initial value for OBGAIndividualBinaryData is no Permutation!"); + } + this.mutationOperator.init(this, opt); + this.crossoverOperator.init(this, opt); + } - /** This method can be used to read the current fitness of the individual. - * Please note that the fitness can be based on multiple criteria therefore - * double[] is used instead of a single double. - * @return The complete fitness array - */ + /** + * This method can be used to read the current fitness of the individual. + * Please note that the fitness can be based on multiple criteria therefore + * double[] is used instead of a single double. + * + * @return The complete fitness array + */ @Override - public double[] getFitness() { - return this.fitness; - } + public double[] getFitness() { + return this.fitness; + } - /** This method will return a string description of the GAIndividal - * noteably the Genotype. - * @return A descriptive string - */ + /** + * This method will return a string description of the GAIndividal + * noteably the Genotype. + * + * @return A descriptive string + */ @Override - public String getStringRepresentation() { - String result = ""; - result += "OBGAIndividual: ("; - result += "Fitness {"; - for (int i = 0; i < this.fitness.length; i++) { + public String getStringRepresentation() { + String result = ""; + result += "OBGAIndividual: ("; + result += "Fitness {"; + for (int i = 0; i < this.fitness.length; i++) { result += this.fitness[i] + ";"; } - result += "}/SelProb{"; - for (int i = 0; i < this.selectionProbability.length; i++) { + result += "}/SelProb{"; + for (int i = 0; i < this.selectionProbability.length; i++) { result += this.selectionProbability[i] + ";"; } - result += "})\n Value: "; - result += "{"; - int[] sizes = this.sizePermutation(); + result += "})\n Value: "; + result += "{"; + int[] sizes = this.sizePermutation(); - for (int i = 0; i < sizes.length; i++) { + for (int i = 0; i < sizes.length; i++) { result += "Permutation " + i + ":"; for (int j = 0; j < sizes[i]; j++) { - result += " " + this.getPermutationData()[i][j] + " "; + result += " " + this.getPermutationData()[i][j] + " "; } - result += "\n"; - } - result += "}"; - result += "\n Mutation ("+this.mutationProbability +"):" + this.mutationOperator.getStringRepresentation(); - return result; + result += "\n"; + } + result += "}"; + result += "\n Mutation (" + this.mutationProbability + "):" + this.mutationOperator.getStringRepresentation(); + return result; - } + } @Override - public Object clone() { - return new OBGAIndividualPermutationData(this); - } + public Object clone() { + return new OBGAIndividualPermutationData(this); + } - /************************************************************************************ - * InterfaceOBGAIndividual methods - */ + /** + * ********************************************************************************* + * InterfaceOBGAIndividual methods + */ @Override public int[][] getOBGenotype() { @@ -178,93 +191,95 @@ public class OBGAIndividualPermutationData extends AbstractEAIndividual implemen } @Override - public void defaultMutate(){ - int[][] permmatrix = this.getPermutationData(); - for (int i = 0; i < permmatrix.length; i++) { - int[] perm = permmatrix[i]; - int p1 = RNG.randomInt(0,perm.length-1); - int p2 = RNG.randomInt(0,perm.length-1); - int temp = perm[p1]; - perm[p1] = perm[p2]; - perm[p2] = temp; - } + public void defaultMutate() { + int[][] permmatrix = this.getPermutationData(); + for (int i = 0; i < permmatrix.length; i++) { + int[] perm = permmatrix[i]; + int p1 = RNG.randomInt(0, perm.length - 1); + int p2 = RNG.randomInt(0, perm.length - 1); + int temp = perm[p1]; + perm[p1] = perm[p2]; + perm[p2] = temp; + } - this.SetPermutationGenotype(permmatrix); - } + this.SetPermutationGenotype(permmatrix); + } @Override - public void defaultInit(InterfaceOptimizationProblem prob){ - //System.out.println("Default Init!"); - int[][] perm = new int[this.m_Genotype.length][]; - for (int p = 0; p < perm.length; p++) { - perm[p] = new int[this.m_Genotype[p].length]; - ArrayList pot = new ArrayList(); - for (int i = 0; i < this.sizePermutation()[p]; i++) { - pot.add(new Integer(firstindex[p] + i)); - } - int i = 0; - while (!pot.isEmpty()) { - perm[p][i] = ((Integer) (pot.remove(RNG.randomInt(0, pot.size() - 1)))).intValue(); - i++; - } + public void defaultInit(InterfaceOptimizationProblem prob) { + //System.out.println("Default Init!"); + int[][] perm = new int[this.m_Genotype.length][]; + for (int p = 0; p < perm.length; p++) { + perm[p] = new int[this.m_Genotype[p].length]; + ArrayList pot = new ArrayList(); + for (int i = 0; i < this.sizePermutation()[p]; i++) { + pot.add(new Integer(firstindex[p] + i)); + } + int i = 0; + while (!pot.isEmpty()) { + perm[p][i] = ((Integer) (pot.remove(RNG.randomInt(0, pot.size() - 1)))).intValue(); + i++; + } + } + this.SetPermutationGenotype(perm); + // System.out.println(getStringRepresentation()); } - this.SetPermutationGenotype(perm); - // System.out.println(getStringRepresentation()); - } - - /************************************************************************************ - * InterfaceDataTypePermutation methods - */ + /** + * ********************************************************************************* + * InterfaceDataTypePermutation methods + */ @Override - public void setPermutationDataLength(int[] length){ - this.m_Genotype = new int[length.length][]; - for (int i = 0; i < length.length; i++) { - this.m_Genotype[i] = new int[length[i]]; - } + public void setPermutationDataLength(int[] length) { + this.m_Genotype = new int[length.length][]; + for (int i = 0; i < length.length; i++) { + this.m_Genotype[i] = new int[length[i]]; + } } @Override public int[] sizePermutation() { - int[] res = new int[m_Genotype.length]; - for (int i = 0; i = 1) { //System.out.println(tmpV); if ((tmpV % 2) == 1) { @@ -138,35 +143,34 @@ public class GAStandardCodingDouble implements InterfaceGADoubleCoding, java.io. for (int i = 0; i < m_length; i++) { if (tmpBitSet.get(i)) { refBitSet.set(m_start + m_length - 1 - i); - } - else { + } else { refBitSet.clear(m_start + m_length - 1 - i); } } } - /** A simple test function without arguments - * + /** + * A simple test function without arguments + * * @param args */ public static void main(String[] args) { GAStandardCodingDouble t = new GAStandardCodingDouble(); - String test = "01100010001000110010000011111101"; + String test = "01100010001000110010000011111101"; //String test = "11000000000000000000000000000000"; //String test = "11000000000000000000000000000000"; double value; - BitSet tmpBitSet = new BitSet(); - int[] locus = new int[2]; + BitSet tmpBitSet = new BitSet(); + int[] locus = new int[2]; locus[0] = 10; locus[1] = 12; double[] range = new double[2]; - range[0] = -110; - range[1] = 1000; + range[0] = -110; + range[1] = 1000; for (int i = 0; i < test.length(); i++) { if (test.charAt(i) == '1') { tmpBitSet.set(i); - } - else { + } else { tmpBitSet.clear(i); } } @@ -181,34 +185,37 @@ public class GAStandardCodingDouble implements InterfaceGADoubleCoding, java.io. // value = t.decodeValue(tmpBitSet, range, locus, false); // System.out.println("Value: " + value); // System.out.println("BitSet: " + t.printBitSet(tmpBitSet, 32)); - for (int i=0; i<1000; i++) { - value = t.decodeValueOld(tmpBitSet, range, locus, false); - System.out.println("Value def: " + value); - value = t.decodeValue(tmpBitSet, range, locus, false); - System.out.println("Value alt: " + value); + for (int i = 0; i < 1000; i++) { + value = t.decodeValueOld(tmpBitSet, range, locus, false); + System.out.println("Value def: " + value); + value = t.decodeValue(tmpBitSet, range, locus, false); + System.out.println("Value alt: " + value); } } - - /** Perhaps a special output is necessary. - * @param b The BitString. - * @return A printable String. + + /** + * Perhaps a special output is necessary. + * + * @param b The BitString. + * @return A printable String. */ public String printBitSet(BitSet b) { return this.printBitSet(b, b.size()); } - /** Perhaps a special output is necessary. - * @param b The BitString. - * @return A printable String. + /** + * Perhaps a special output is necessary. + * + * @param b The BitString. + * @return A printable String. */ public String printBitSet(BitSet b, int length) { - String output = "{"; + String output = "{"; for (int i = 0; i < length; i++) { if (b.get(i)) { output += "1"; - } - else { + } else { output += "0"; } } diff --git a/src/eva2/optimization/individuals/codings/ga/GAStandardCodingInteger.java b/src/eva2/optimization/individuals/codings/ga/GAStandardCodingInteger.java index 0cf7883a..0bff52f2 100644 --- a/src/eva2/optimization/individuals/codings/ga/GAStandardCodingInteger.java +++ b/src/eva2/optimization/individuals/codings/ga/GAStandardCodingInteger.java @@ -2,10 +2,12 @@ package eva2.optimization.individuals.codings.ga; import eva2.tools.math.RNG; + import java.util.BitSet; -/** The traditional binary coding for integer number, no variable number of bits here, sorry. +/** + * The traditional binary coding for integer number, no variable number of bits here, sorry. * Created by IntelliJ IDEA. * User: streiche * Date: 24.03.2003 @@ -14,31 +16,33 @@ import java.util.BitSet; */ public class GAStandardCodingInteger implements InterfaceGAIntegerCoding, java.io.Serializable { - /** This method decodes a part of a given BitSet into a int value. This method may change the contens + /** + * This method decodes a part of a given BitSet into a int value. This method may change the contens * of the BitSet if it doesn't describe a valid value. * The method checks wether or not the value is within the given range. - * @param refBitSet The BitSet where the integer value is stored. - * @param range The allowed range of the value. - * @param locus The position and length on the BitSet that is to be decoded. - * @param correction Enable automatic correction is enabled. + * + * @param refBitSet The BitSet where the integer value is stored. + * @param range The allowed range of the value. + * @param locus The position and length on the BitSet that is to be decoded. + * @param correction Enable automatic correction is enabled. * @return The int value. */ @Override public int decodeValue(BitSet refBitSet, int[] range, int[] locus, boolean correction) { - int u_max, u_min, m_max, m_min; - int m_start, m_length, counter = 0; - long tmpV; - BitSet tmpBitSet; - String output = ""; + int u_max, u_min, m_max, m_min; + int m_start, m_length, counter = 0; + long tmpV; + BitSet tmpBitSet; + String output = ""; - u_min = range[0]; - u_max = range[1]; - m_start = locus[0]; - m_length = locus[1]; - m_max = (int)Math.pow(2, m_length) - 1; - m_min = 0; - tmpBitSet = new BitSet(m_length); - tmpV = 0; + u_min = range[0]; + u_max = range[1]; + m_start = locus[0]; + m_length = locus[1]; + m_max = (int) Math.pow(2, m_length) - 1; + m_min = 0; + tmpBitSet = new BitSet(m_length); + tmpV = 0; for (int i = 0; i < m_length; i++) { if (refBitSet.get(m_start + m_length - 1 - i)) { tmpV += Math.pow(2, i); @@ -58,38 +62,40 @@ public class GAStandardCodingInteger implements InterfaceGAIntegerCoding, java.i // a new value within the bounds is generated tmpV = RNG.randomInt(u_min, u_max); //System.out.println("zu: " + tmpV); - codeValue((int)tmpV, range, refBitSet, locus); + codeValue((int) tmpV, range, refBitSet, locus); } else { tmpV = u_max; //System.out.println("zu max: " + tmpV); } } //System.out.println("INT Value decoded : " + (int)tmpV + " " + this.printBitSet(tmpBitSet, m_length)); - return (int)tmpV; + return (int) tmpV; } - /** This method codes a given int value directly into a BitSet at + /** + * This method codes a given int value directly into a BitSet at * the position which is specified by locus. * The method checks wether or not the value is within the given range. - * @param value The value to be coded. - * @param range The allowed range of the value. - * @param refBitSet The BitSet where the questioned value is stored. - * @param locus The position and length on the BitSet that is to be coded. + * + * @param value The value to be coded. + * @param range The allowed range of the value. + * @param refBitSet The BitSet where the questioned value is stored. + * @param locus The position and length on the BitSet that is to be coded. */ @Override public void codeValue(int value, int[] range, BitSet refBitSet, int[] locus) { - int u_max, u_min, m_max, m_min; - int m_start, m_length, counter = 0; - long tmpV; - BitSet tmpBitSet; + int u_max, u_min, m_max, m_min; + int m_start, m_length, counter = 0; + long tmpV; + BitSet tmpBitSet; - u_min = range[0]; - u_max = range[1]; - m_start = locus[0]; - m_length = locus[1]; - m_max = (int)Math.pow(2, m_length) - 1; - m_min = 0; - tmpV = value - u_min; + u_min = range[0]; + u_max = range[1]; + m_start = locus[0]; + m_length = locus[1]; + m_max = (int) Math.pow(2, m_length) - 1; + m_min = 0; + tmpV = value - u_min; long tmpOut = tmpV;// damit ist tmpV im range m_Min m_Max if (tmpV > m_max) { tmpV = m_max; @@ -117,55 +123,58 @@ public class GAStandardCodingInteger implements InterfaceGAIntegerCoding, java.i for (int i = 0; i < m_length; i++) { if (tmpBitSet.get(i)) { refBitSet.set(m_start + m_length - 1 - i); - } - else { + } else { refBitSet.clear(m_start + m_length - 1 - i); } } for (int i = 0; i < m_length; i++) { if (refBitSet.get(m_start + m_length - 1 - i)) { tmpBitSet.set(m_length - 1 - i); - } - else { + } else { tmpBitSet.clear(m_start + m_length - 1 - i); } } //System.out.println("INT Value coded : " + value + " " + this.printBitSet(tmpBitSet, m_length)); } - /** This method will calculate how many bits are to be used to code a given value - * @param range The range for the value. + /** + * This method will calculate how many bits are to be used to code a given value + * + * @param range The range for the value. */ @Override public int calculateNecessaryBits(int[] range) { int result = 0; - double maxStore = 1. + range[1] -range[0]; + double maxStore = 1. + range[1] - range[0]; while (Math.pow(2, result) < maxStore) result++; return result; } - /** Perhaps a special output is necessary. - * @param b The BitString. - * @return A printable String. + /** + * Perhaps a special output is necessary. + * + * @param b The BitString. + * @return A printable String. */ public String printBitSet(BitSet b) { return this.printBitSet(b, b.size()); } - /** Perhaps a special output is necessary. - * @param b The BitString. - * @return A printable String. + /** + * Perhaps a special output is necessary. + * + * @param b The BitString. + * @return A printable String. */ public String printBitSet(BitSet b, int length) { - String output = "{"; + String output = "{"; for (int i = 0; i < length; i++) { if (b.get(i)) { output += "1"; - } - else { + } else { output += "0"; } } diff --git a/src/eva2/optimization/individuals/codings/ga/InterfaceGADoubleCoding.java b/src/eva2/optimization/individuals/codings/ga/InterfaceGADoubleCoding.java index 10c2e7ad..c744f854 100644 --- a/src/eva2/optimization/individuals/codings/ga/InterfaceGADoubleCoding.java +++ b/src/eva2/optimization/individuals/codings/ga/InterfaceGADoubleCoding.java @@ -10,24 +10,28 @@ import java.util.BitSet; * To change this template use Options | File Templates. */ public interface InterfaceGADoubleCoding { - /** This method decodes a part of a given BitSet into a double value. This method may change the contens + /** + * This method decodes a part of a given BitSet into a double value. This method may change the contens * of the BitSet if it doesn't describe a valid value. * The method checks whether or not the value is within the given range. - * @param refBitSet The BitSet where the questioned value is stored. - * @param range The allowed range of the value. - * @param locus The position and length on the BitSet that is to be decoded. - * @param correction Enable automatic correction is enabled. - * @return The float value. + * + * @param refBitSet The BitSet where the questioned value is stored. + * @param range The allowed range of the value. + * @param locus The position and length on the BitSet that is to be decoded. + * @param correction Enable automatic correction is enabled. + * @return The float value. */ public double decodeValue(BitSet refBitSet, double[] range, int[] locus, boolean correction); - /** This method codes a given double value directly into a BitSet at + /** + * This method codes a given double value directly into a BitSet at * the position which is specified by locus. * The method checks whether or not the value is within the given range. - * @param value The value to be coded. - * @param range The allowed range of the value. - * @param refBitSet The BitSet where the questioned value is stored. - * @param locus The position and length on the BitSet that is to be coded. + * + * @param value The value to be coded. + * @param range The allowed range of the value. + * @param refBitSet The BitSet where the questioned value is stored. + * @param locus The position and length on the BitSet that is to be coded. */ public void codeValue(double value, double[] range, BitSet refBitSet, int[] locus); } diff --git a/src/eva2/optimization/individuals/codings/ga/InterfaceGAIntegerCoding.java b/src/eva2/optimization/individuals/codings/ga/InterfaceGAIntegerCoding.java index c98fddce..a9bdc232 100644 --- a/src/eva2/optimization/individuals/codings/ga/InterfaceGAIntegerCoding.java +++ b/src/eva2/optimization/individuals/codings/ga/InterfaceGAIntegerCoding.java @@ -11,29 +11,35 @@ import java.util.BitSet; */ public interface InterfaceGAIntegerCoding { - /** This method decodes a part of a given BitSet into a int value. This method may change the contens + /** + * This method decodes a part of a given BitSet into a int value. This method may change the contens * of the BitSet if it doesn't describe a valid value. * The method checks wether or not the value is within the given range. - * @param refBitSet The BitSet where the questioned value is stored. - * @param range The allowed range of the value. - * @param locus The position and length on the BitSet that is to be decoded. - * @param correction Enable automatic correction is enabled. - * @return The float value. + * + * @param refBitSet The BitSet where the questioned value is stored. + * @param range The allowed range of the value. + * @param locus The position and length on the BitSet that is to be decoded. + * @param correction Enable automatic correction is enabled. + * @return The float value. */ public int decodeValue(BitSet refBitSet, int[] range, int[] locus, boolean correction); - /** This method codes a given int value directly into a BitSet at + /** + * This method codes a given int value directly into a BitSet at * the position which is specified by locus. * The method checks wether or not the value is within the given range. - * @param value The value to be coded. - * @param range The allowed range of the value. - * @param refBitSet The BitSet where the questioned value is stored. - * @param locus The position and length on the BitSet that is to be coded. + * + * @param value The value to be coded. + * @param range The allowed range of the value. + * @param refBitSet The BitSet where the questioned value is stored. + * @param locus The position and length on the BitSet that is to be coded. */ public void codeValue(int value, int[] range, BitSet refBitSet, int[] locus); - /** This method will calculate how many bits are to be used to code a given value - * @param range The range for the value. + /** + * This method will calculate how many bits are to be used to code a given value + * + * @param range The range for the value. */ - public int calculateNecessaryBits(int[] range); + public int calculateNecessaryBits(int[] range); } diff --git a/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java b/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java index 3b5a0af7..1289f711 100644 --- a/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java +++ b/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java @@ -9,12 +9,14 @@ import eva2.tools.Pair; import eva2.tools.ReflectPackage; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Vector; -/** This gives an abstract node, with default functionality for get and set methods. +/** + * This gives an abstract node, with default functionality for get and set methods. * Created by IntelliJ IDEA. * User: streiche * Date: 04.04.2003 @@ -22,402 +24,421 @@ import java.util.Vector; * To change this template use Options | File Templates. */ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serializable { - protected AbstractGPNode m_Parent; - protected AbstractGPNode[] m_Nodes = new AbstractGPNode[0]; - protected int m_Depth = 0; - private static final boolean TRACE=false; - - /** This method allows you to clone the Nodes + protected AbstractGPNode m_Parent; + protected AbstractGPNode[] m_Nodes = new AbstractGPNode[0]; + protected int m_Depth = 0; + private static final boolean TRACE = false; + + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override public abstract Object clone(); - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ public abstract String getName(); - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override public abstract Object evaluate(InterfaceProgramProblem environment); - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ public abstract int getArity(); - /** This method returns a string representation + /** + * This method returns a string representation + * * @return string */ @Override public String getStringRepresentation() { - StringBuffer sb = new StringBuffer(); - AbstractGPNode.appendStringRepresentation(this, sb); - return sb.toString(); + StringBuffer sb = new StringBuffer(); + AbstractGPNode.appendStringRepresentation(this, sb); + return sb.toString(); } - + /** * Recursively perform deep cloning of the members of this instance and all sub-nodes. * * @param node the node to clone values from - **/ + */ protected void cloneMembers(AbstractGPNode node) { - this.m_Depth = node.m_Depth; - this.m_Parent = node.m_Parent; - this.m_Nodes = new AbstractGPNode[node.m_Nodes.length]; + this.m_Depth = node.m_Depth; + this.m_Parent = node.m_Parent; + this.m_Nodes = new AbstractGPNode[node.m_Nodes.length]; for (int i = 0; i < node.m_Nodes.length; i++) { this.m_Nodes[i] = (AbstractGPNode) node.m_Nodes[i].clone(); } } - + private static void appendStringRepresentation(AbstractGPNode node, StringBuffer sbuf) { - String op = node.getOpIdentifier(); - sbuf.append(op); - if (node.getArity()>0) { - sbuf.append("("); - for (int i = 0; i < node.m_Nodes.length; i++) { - sbuf.append(node.m_Nodes[i].getStringRepresentation()); - if (i 0) { + sbuf.append("("); + for (int i = 0; i < node.m_Nodes.length; i++) { + sbuf.append(node.m_Nodes[i].getStringRepresentation()); + if (i < node.m_Nodes.length - 1) { + sbuf.append(", "); + } + } + sbuf.append(")"); + } } - - /** - * This method returns a string identifier of the operator name - it should be unique. - * + + /** + * This method returns a string identifier of the operator name - it should be unique. + * * @return string */ public abstract String getOpIdentifier(); - + /** - * Small parser for GP nodes from a String. Format must be (nearly) equivalent to what + * Small parser for GP nodes from a String. Format must be (nearly) equivalent to what * makeStringRepresentation produces. * This mainly means prefix notation with braces and commata, such as in: - * AbstractGPNode node = AbstractGPNode.parseFromString("+(2.0,cos(*(pi,pi)))"); - * System.out.println("Parsed GPNode: " + node.getStringRepresentation()); - * node = AbstractGPNode.parseFromString(node.getStringRepresentation()); + * AbstractGPNode node = AbstractGPNode.parseFromString("+(2.0,cos(*(pi,pi)))"); + * System.out.println("Parsed GPNode: " + node.getStringRepresentation()); + * node = AbstractGPNode.parseFromString(node.getStringRepresentation()); + * * @param str * @param nodeTypes * @return */ - public static Pair parseFromString(String str, Vector nodeTypes) { - if (nodeTypes == null) { - nodeTypes = getNodeTypes(); - } - if (nodeTypes.size()>0) { - Vector matchSet=AbstractGPNode.match(nodeTypes, str, true, true); - if (matchSet.size()==0) { - // try to read constant - Pair nextState=readDouble(str, true); - if (nextState != null) { - return new Pair(new GPNodeConst(nextState.head().doubleValue()), nextState.tail()); - } else { - System.err.println("String has unknown prefix: " + str); - } - } - else if (matchSet.size()>1) { + public static Pair parseFromString(String str, Vector nodeTypes) { + if (nodeTypes == null) { + nodeTypes = getNodeTypes(); + } + if (nodeTypes.size() > 0) { + Vector matchSet = AbstractGPNode.match(nodeTypes, str, true, true); + if (matchSet.size() == 0) { + // try to read constant + Pair nextState = readDouble(str, true); + if (nextState != null) { + return new Pair(new GPNodeConst(nextState.head().doubleValue()), nextState.tail()); + } else { + System.err.println("String has unknown prefix: " + str); + } + } else if (matchSet.size() > 1) { System.err.println("String has ambiguous prefix: " + str + " -- " + BeanInspector.toString(matchSet)); - } - else { // exactly one match: - AbstractGPNode currentNode = (AbstractGPNode)matchSet.get(0).clone(); - if (TRACE) { - System.out.println("Found match: " + currentNode.getOpIdentifier() + "/" + currentNode.getArity()); + } else { // exactly one match: + AbstractGPNode currentNode = (AbstractGPNode) matchSet.get(0).clone(); + if (TRACE) { + System.out.println("Found match: " + currentNode.getOpIdentifier() + "/" + currentNode.getArity()); + } + int cutFront = currentNode.getOpIdentifier().length(); + String restStr; + if (currentNode.getArity() == 0) { + restStr = str.substring(cutFront).trim(); + if (currentNode instanceof GPNodeInput) { + Pair nextState = readDouble(restStr, false); + if (nextState != null) { + ((GPNodeInput) currentNode).setIdentifier(currentNode.getOpIdentifier() + ((int) nextState.head().doubleValue())); + restStr = nextState.tail(); + } else { + ((GPNodeInput) currentNode).setIdentifier(currentNode.getOpIdentifier()); + } } - int cutFront=currentNode.getOpIdentifier().length(); - String restStr; - if (currentNode.getArity()==0) { - restStr = str.substring(cutFront).trim(); - if (currentNode instanceof GPNodeInput) { - Pair nextState=readDouble(restStr, false); - if (nextState!=null) { - ((GPNodeInput)currentNode).setIdentifier(currentNode.getOpIdentifier()+((int)nextState.head().doubleValue())); - restStr = nextState.tail(); - } else { - ((GPNodeInput)currentNode).setIdentifier(currentNode.getOpIdentifier()); - } - } - return new Pair(currentNode,restStr); - } else { - restStr = str.substring(cutFront+1).trim(); // cut this op and front brace - currentNode.m_Nodes = new AbstractGPNode[currentNode.getArity()]; - for (int i=0; i nextState = parseFromString(restStr, nodeTypes); - currentNode.m_Nodes[i]=nextState.head(); - try { - restStr=nextState.tail().substring(1).trim(); // cut comma or brace - } catch (StringIndexOutOfBoundsException e) { - System.err.println("Error: parsing failed for node " + currentNode.getOpIdentifier() + "/" + currentNode.getArity() + ", depth " + currentNode.getDepth()); - System.err.println("String was " + str); - e.printStackTrace(); - } - } - if (TRACE) { - System.out.println("read " + currentNode.getName() + ", rest: " + restStr); - } - return new Pair(currentNode, restStr); - } - } - } return null; + return new Pair(currentNode, restStr); + } else { + restStr = str.substring(cutFront + 1).trim(); // cut this op and front brace + currentNode.m_Nodes = new AbstractGPNode[currentNode.getArity()]; + for (int i = 0; i < currentNode.getArity(); i++) { + Pair nextState = parseFromString(restStr, nodeTypes); + currentNode.m_Nodes[i] = nextState.head(); + try { + restStr = nextState.tail().substring(1).trim(); // cut comma or brace + } catch (StringIndexOutOfBoundsException e) { + System.err.println("Error: parsing failed for node " + currentNode.getOpIdentifier() + "/" + currentNode.getArity() + ", depth " + currentNode.getDepth()); + System.err.println("String was " + str); + e.printStackTrace(); + } + } + if (TRACE) { + System.out.println("read " + currentNode.getName() + ", rest: " + restStr); + } + return new Pair(currentNode, restStr); + } + } + } + return null; } /** * Return all available node types as AbstractGPNode list. * Using getOpIdentifier on all elements gives an overview of the operators * that can be used. - * + * * @return a list of available AbstractGPNode implementations */ - public static Vector getNodeTypes() { - ArrayListcls = GenericObjectEditor.getClassesFromClassPath(AbstractGPNode.class.getCanonicalName(), null); - Vector nodeTypes = new Vector(cls.size()); - for (int i=0; i getNodeTypes() { + ArrayList cls = GenericObjectEditor.getClassesFromClassPath(AbstractGPNode.class.getCanonicalName(), null); + Vector nodeTypes = new Vector(cls.size()); + for (int i = 0; i < cls.size(); i++) { + try { + AbstractGPNode node = (AbstractGPNode) Class.forName((String) cls.get(i)).newInstance(); + nodeTypes.add(node); + } catch (Exception e) { + } + } // nodeTypes.add(new GPNodeInput("X")); - nodeTypes.add(new GPNodeInput("N")); - return nodeTypes; - } - - private static Pair readDouble(String str, boolean expect) { - String firstArg; - int argLen = str.indexOf(','); - if (argLen<0) { - argLen = str.indexOf(')'); - } - else { - int firstBrace = str.indexOf(')'); - if ((firstBrace >= 0) && (firstBrace0) { - firstArg=str.substring(0,argLen); - } - else { - firstArg=str.trim(); - } - try { - Double d=Double.parseDouble(firstArg); - return new Pair(d, str.substring(firstArg.length())); - } catch(NumberFormatException e) { - if (expect) { - System.err.println("String has unknown prefix: " + str); - } - return null; - } - } + nodeTypes.add(new GPNodeInput("N")); + return nodeTypes; + } - /** + private static Pair readDouble(String str, boolean expect) { + String firstArg; + int argLen = str.indexOf(','); + if (argLen < 0) { + argLen = str.indexOf(')'); + } else { + int firstBrace = str.indexOf(')'); + if ((firstBrace >= 0) && (firstBrace < argLen)) { + argLen = firstBrace; + } + } + if (argLen > 0) { + firstArg = str.substring(0, argLen); + } else { + firstArg = str.trim(); + } + try { + Double d = Double.parseDouble(firstArg); + return new Pair(d, str.substring(firstArg.length())); + } catch (NumberFormatException e) { + if (expect) { + System.err.println("String has unknown prefix: " + str); + } + return null; + } + } + + /** * This method returns a string representation + * * @return string */ public static String makeStringRepresentation(AbstractGPNode[] nodes, String op) { - if (nodes.length==0) { + if (nodes.length == 0) { return op; - } - else if (nodes.length==1) { - return op+"(" + nodes[0].getStringRepresentation()+")"; - } - else { - String result = "( "+nodes[0].getStringRepresentation(); - for (int i = 1; i < nodes.length; i++) { - result += " " + op + " " + nodes[i].getStringRepresentation(); + } else if (nodes.length == 1) { + return op + "(" + nodes[0].getStringRepresentation() + ")"; + } else { + String result = "( " + nodes[0].getStringRepresentation(); + for (int i = 1; i < nodes.length; i++) { + result += " " + op + " " + nodes[i].getStringRepresentation(); } - result += ")"; - return result; - } + result += ")"; + return result; + } } - + /** * Match available nodes by their operator identifier string. Allows the option "first longest match" only * for ambiguous situations where several operators match. - * + * * @param nodeTypes * @param str * @param firstLongestOnly * @return */ private static Vector match( - Vector nodeTypes, String str, boolean firstLongestOnly, boolean ignoreCase) { - Vector matching = new Vector(); - for (int i=0; i0) { - reqPrefix+="("; - } - if (str.startsWith(reqPrefix)) { - matching.add(nodeTypes.get(i)); - } - else if (ignoreCase && str.toLowerCase().startsWith(reqPrefix.toLowerCase())) { - matching.add(nodeTypes.get(i)); - } - } - if (matching.size()>1 && firstLongestOnly) { // allow only the longest match (or first longest) - int maxLen = matching.get(0).getOpIdentifier().length(); - AbstractGPNode longest=matching.get(0); - Vector longestList = new Vector(); - longestList.add(longest); - for (int i=1; imaxLen) { - longest = matching.get(i); - maxLen = longest.getOpIdentifier().length(); - longestList.clear(); - longestList.add(longest); - } else if (matching.get(i).getOpIdentifier().length()==maxLen) { - longestList.add(matching.get(i)); - } - } - matching.clear(); - matching.addAll(longestList); - // TODO test if arities are different! - } - return matching; - } + Vector nodeTypes, String str, boolean firstLongestOnly, boolean ignoreCase) { + Vector matching = new Vector(); + for (int i = 0; i < nodeTypes.size(); i++) { + String reqPrefix = nodeTypes.get(i).getOpIdentifier(); + if (nodeTypes.get(i).getArity() > 0) { + reqPrefix += "("; + } + if (str.startsWith(reqPrefix)) { + matching.add(nodeTypes.get(i)); + } else if (ignoreCase && str.toLowerCase().startsWith(reqPrefix.toLowerCase())) { + matching.add(nodeTypes.get(i)); + } + } + if (matching.size() > 1 && firstLongestOnly) { // allow only the longest match (or first longest) + int maxLen = matching.get(0).getOpIdentifier().length(); + AbstractGPNode longest = matching.get(0); + Vector longestList = new Vector(); + longestList.add(longest); + for (int i = 1; i < matching.size(); i++) { + if (matching.get(i).getOpIdentifier().length() > maxLen) { + longest = matching.get(i); + maxLen = longest.getOpIdentifier().length(); + longestList.clear(); + longestList.add(longest); + } else if (matching.get(i).getOpIdentifier().length() == maxLen) { + longestList.add(matching.get(i)); + } + } + matching.clear(); + matching.addAll(longestList); + // TODO test if arities are different! + } + return matching; + } public static AbstractGPNode parseFromString(String str) { // System.out.println("Parsing " + str); - Pair result = AbstractGPNode.parseFromString(str, null); - return result.head(); + Pair result = AbstractGPNode.parseFromString(str, null); + return result.head(); } - - public static void main(String[] args) { + + public static void main(String[] args) { // Double d = Double.parseDouble("2.58923 + 3"); // AbstractGPNode node = AbstractGPNode.parseFromString("-23421"); - AbstractGPNode node = AbstractGPNode.parseFromString("+(-23421,cOs(*(pI,x)))"); - AbstractGPNode.parseFromString("+(+(85.334407,*(0.0056858,*(x1,x4))), +(*(0.00026,*(x0,x3)),*(-0.0022053,*(x2,x4))))"); - AbstractGPNode.parseFromString("+(+(80.51249,*(0.0071317,*(x1,x4))), +(*(0.0029955,*(x0,x1)),*(0.0021813,*(x2,x2))))"); - AbstractGPNode.parseFromString("+(+(9.300961,*(0.0047026,*(x2,x4))), +(*(0.0012547,*(x0,x2)),*(0.0019085,*(x2,x3))))"); + AbstractGPNode node = AbstractGPNode.parseFromString("+(-23421,cOs(*(pI,x)))"); + AbstractGPNode.parseFromString("+(+(85.334407,*(0.0056858,*(x1,x4))), +(*(0.00026,*(x0,x3)),*(-0.0022053,*(x2,x4))))"); + AbstractGPNode.parseFromString("+(+(80.51249,*(0.0071317,*(x1,x4))), +(*(0.0029955,*(x0,x1)),*(0.0021813,*(x2,x2))))"); + AbstractGPNode.parseFromString("+(+(9.300961,*(0.0047026,*(x2,x4))), +(*(0.0012547,*(x0,x2)),*(0.0019085,*(x2,x3))))"); - System.out.println("Parsed GPNode: " + node.getStringRepresentation()); - node = AbstractGPNode.parseFromString(node.getStringRepresentation()); + System.out.println("Parsed GPNode: " + node.getStringRepresentation()); + node = AbstractGPNode.parseFromString(node.getStringRepresentation()); - double[] sol= new double[]{4.755837346122817, 0.0, 1.618818602745894, 7.941611605461133, 7.949805645271173, 7.9567145687445695, 4.8033535294211225, 7.96718976492528, 1.641971622483205, 7.973813526015599, 7.980394418430633, 7.98301197251176, 7.98590997257042, 1.6493767411801206, 7.994756424330215, 7.994983501150322, 7.9971658558418035, 8.00273733683876, 8.00492865462689, 8.006601147955184}; - double[] sol2={7.897269942114308, 0.0, 7.939346674715275, 1.6272963933436047, 7.952303730484389, 7.960893192129872, 4.804987144876599, 7.9682843963405805, 7.977546251710085, 7.981109017707746, 1.642081396353059, 7.985246784301232, 4.827113167927753, 1.6448751122424057, 7.997468593784776, 8.00165633007073, 8.000613763831703, 8.003920903217887, 8.005789437120203, 8.012425280944097}; - double[] sol3={4.705970234231343, 4.71343334004773, 7.845971927185614, 4.708648989456629, 4.723918978896874, 7.864710619970946, 1.5776948341096448, 7.854961967305262, 7.858760422458277, 1.5743212019457036, 7.8488102514506, 1.5637070804731334, 1.5778078319616269, 1.5757833862993071, 4.711995406637344, 4.715448624806491, 7.8434193487088155, 4.7036514083601535, 7.848371610694223, 7.856489370257257}; - test("-(0.75,prod(x))", sol3); - test("-(sum(x),*(7.5,n))", sol3); + double[] sol = new double[]{4.755837346122817, 0.0, 1.618818602745894, 7.941611605461133, 7.949805645271173, 7.9567145687445695, 4.8033535294211225, 7.96718976492528, 1.641971622483205, 7.973813526015599, 7.980394418430633, 7.98301197251176, 7.98590997257042, 1.6493767411801206, 7.994756424330215, 7.994983501150322, 7.9971658558418035, 8.00273733683876, 8.00492865462689, 8.006601147955184}; + double[] sol2 = {7.897269942114308, 0.0, 7.939346674715275, 1.6272963933436047, 7.952303730484389, 7.960893192129872, 4.804987144876599, 7.9682843963405805, 7.977546251710085, 7.981109017707746, 1.642081396353059, 7.985246784301232, 4.827113167927753, 1.6448751122424057, 7.997468593784776, 8.00165633007073, 8.000613763831703, 8.003920903217887, 8.005789437120203, 8.012425280944097}; + double[] sol3 = {4.705970234231343, 4.71343334004773, 7.845971927185614, 4.708648989456629, 4.723918978896874, 7.864710619970946, 1.5776948341096448, 7.854961967305262, 7.858760422458277, 1.5743212019457036, 7.8488102514506, 1.5637070804731334, 1.5778078319616269, 1.5757833862993071, 4.711995406637344, 4.715448624806491, 7.8434193487088155, 4.7036514083601535, 7.848371610694223, 7.856489370257257}; + test("-(0.75,prod(x))", sol3); + test("-(sum(x),*(7.5,n))", sol3); // test("+(*(1000,+(sin(-(-0.25,x2)),sin(-(-0.25,x3)))), -(894.8,x0))", new double[]{1.,2,0,0,}); - double[] solG5lit = new double[]{679.9453, 1026.067, 0.1188764, -0.3962336}; - double[] solG5 = new double[] {891.702675571982, 808.9201991846442, -0.028381806025171354, -0.4684444512076402}; - test("-(x2,+(x3,0.55))", solG5); - test("-(x3,+(x2,0.55))", solG5); - test("+(*(1000,+(sin(-(-0.25,x2)),sin(-(-0.25,x3)))), -(894.8,x0))", solG5); - test("+(*(1000,+(sin(+(-0.25,x2)),sin(-(x2,+(x3,0.25))))), -(894.8,x1))", solG5); - test("+(*(1000,+(sin(+(-0.25,x3)),sin(-(x3,+(x2,0.25))))), 1294.8)", solG5); - - double[] solG13lit = new double[] {-1.717143,1.595709,1.827247,-0.7636413,-0.763645}; + double[] solG5lit = new double[]{679.9453, 1026.067, 0.1188764, -0.3962336}; + double[] solG5 = new double[]{891.702675571982, 808.9201991846442, -0.028381806025171354, -0.4684444512076402}; + test("-(x2,+(x3,0.55))", solG5); + test("-(x3,+(x2,0.55))", solG5); + test("+(*(1000,+(sin(-(-0.25,x2)),sin(-(-0.25,x3)))), -(894.8,x0))", solG5); + test("+(*(1000,+(sin(+(-0.25,x2)),sin(-(x2,+(x3,0.25))))), -(894.8,x1))", solG5); + test("+(*(1000,+(sin(+(-0.25,x3)),sin(-(x3,+(x2,0.25))))), 1294.8)", solG5); + + double[] solG13lit = new double[]{-1.717143, 1.595709, 1.827247, -0.7636413, -0.763645}; // double[] solG13 = new double[] {-0.999977165120676, -0.03949641197962931, 2.9901909235593664, 0.11170038214968671, -0.21164083835675082}; //NMS: double[] solG13 = new double[] {-1.20317028354022, 0.9052295512320271, 2.580255691052748, 0.5210663754783309, 0.8965551458319728}; - double[] solG13 = {-1.717136209326236, 1.5957142570821299, -1.8272614459011625, -0.7636708932891901, 0.7636501970281446}; - test("-(+(+(pow2(x0),pow2(x1)),+(pow2(x2),+(pow2(x3),pow2(x4)))),10)", solG13); - test("-(*(x1,x2),*(5,*(x3,x4)))", solG13); - test("+(pow3(x0),+(pow3(x1),1))", solG13); - System.out.println("" + Math.exp(Mathematics.product(solG13))); - test("+(sum(x),abs(sin(*(x0,x3))))", solG5); - test("-(abs(sum(x)),*(abs(-7.5),n))", solG5); - - GPNodeConst n1 = new GPNodeConst(3.); - GPNodeConst n2 = new GPNodeConst(7.); - GPNodeAdd n3 = new GPNodeAdd(); - System.out.println(n1.equals(n2)); - System.out.println(n2.equals(n1)); - System.out.println(n1.equals(n3)); - - System.out.println(createNodeList()); - } - - /** - * Print all operator identifiers with arities. - * - * @return - */ - public static String createNodeList() { - String ret = new String(); - - Class cls = AbstractGPNode.class; - Class[] nodes = ReflectPackage.getAssignableClassesInPackage(cls.getPackage().getName(), AbstractGPNode.class, true, false); - for (Class c : nodes) { - if (Modifier.isAbstract(c.getModifiers()) || c.isInterface()) { - continue; - } - AbstractGPNode node; - try { - node = (AbstractGPNode)c.newInstance(); - ret = ret + " (" + node.getOpIdentifier() + "," + node.getArity() + ")"; - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - return ret; - } + double[] solG13 = {-1.717136209326236, 1.5957142570821299, -1.8272614459011625, -0.7636708932891901, 0.7636501970281446}; + test("-(+(+(pow2(x0),pow2(x1)),+(pow2(x2),+(pow2(x3),pow2(x4)))),10)", solG13); + test("-(*(x1,x2),*(5,*(x3,x4)))", solG13); + test("+(pow3(x0),+(pow3(x1),1))", solG13); + System.out.println("" + Math.exp(Mathematics.product(solG13))); + test("+(sum(x),abs(sin(*(x0,x3))))", solG5); + test("-(abs(sum(x)),*(abs(-7.5),n))", solG5); - public static void test(String constr, double[] pos) { - AbstractGPNode node = AbstractGPNode.parseFromString(constr); - GPFunctionProblem func = new GPFunctionProblem(node, null, pos.length, 0., 0.); - double[] ret = func.eval(pos); - System.out.println("testing " + constr + " evaluated to " + BeanInspector.toString(ret)); - } - - /** This method returns the depth of the current node + GPNodeConst n1 = new GPNodeConst(3.); + GPNodeConst n2 = new GPNodeConst(7.); + GPNodeAdd n3 = new GPNodeAdd(); + System.out.println(n1.equals(n2)); + System.out.println(n2.equals(n1)); + System.out.println(n1.equals(n3)); + + System.out.println(createNodeList()); + } + + /** + * Print all operator identifiers with arities. + * + * @return + */ + public static String createNodeList() { + String ret = new String(); + + Class cls = AbstractGPNode.class; + Class[] nodes = ReflectPackage.getAssignableClassesInPackage(cls.getPackage().getName(), AbstractGPNode.class, true, false); + for (Class c : nodes) { + if (Modifier.isAbstract(c.getModifiers()) || c.isInterface()) { + continue; + } + AbstractGPNode node; + try { + node = (AbstractGPNode) c.newInstance(); + ret = ret + " (" + node.getOpIdentifier() + "," + node.getArity() + ")"; + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + return ret; + } + + public static void test(String constr, double[] pos) { + AbstractGPNode node = AbstractGPNode.parseFromString(constr); + GPFunctionProblem func = new GPFunctionProblem(node, null, pos.length, 0., 0.); + double[] ret = func.eval(pos); + System.out.println("testing " + constr + " evaluated to " + BeanInspector.toString(ret)); + } + + /** + * This method returns the depth of the current node + * * @return The depth. */ public int getDepth() { return this.m_Depth; } - /** This method allows you to set the depth of the current node - * @param depth The depth of the node + /** + * This method allows you to set the depth of the current node + * + * @param depth The depth of the node */ public void setDepth(int depth) { this.m_Depth = depth; } - /** This method allows you to fetch a certain node given by the index. - * @param index Index specifing the requested node. + /** + * This method allows you to fetch a certain node given by the index. + * + * @param index Index specifing the requested node. * @return The requested node. */ public AbstractGPNode getNode(int index) { return this.m_Nodes[index]; } - /** This method allows you to set a node specified by the index - * @param node The new node - * @param index The position where it is to be inserted. + /** + * This method allows you to set a node specified by the index + * + * @param node The new node + * @param index The position where it is to be inserted. */ public void setNode(AbstractGPNode node, int index) { node.setParent(this); - node.setDepth(this.m_Depth+1); + node.setDepth(this.m_Depth + 1); this.m_Nodes[index] = node; } - /** + /** * This method allows you to set a node specified by the reference. - * @param newnode The new node. - * @param oldnode The old node. + * + * @param newnode The new node. + * @param oldnode The old node. */ public void setNode(AbstractGPNode newnode, AbstractGPNode oldnode) { newnode.setParent(this); - newnode.updateDepth(this.m_Depth+1); + newnode.updateDepth(this.m_Depth + 1); for (int i = 0; i < this.m_Nodes.length; i++) { - if (this.m_Nodes[i] == oldnode) { - this.m_Nodes[i] = newnode; + if (this.m_Nodes[i] == oldnode) { + this.m_Nodes[i] = newnode; // System.out.println("SWITCHED " + i); - } + } } } - /** This method returns all nodes begining with the current node. - * @param ListOfNodes This ArrayList will contain all nodes + + /** + * This method returns all nodes begining with the current node. + * + * @param ListOfNodes This ArrayList will contain all nodes */ public void addNodesTo(ArrayList ListOfNodes) { ListOfNodes.add(this); @@ -428,49 +449,55 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial /** * Return a shallow reference to a random node within this tree. + * * @return */ public AbstractGPNode getRandomNode() { - ArrayList allNodes = new ArrayList(10); + ArrayList allNodes = new ArrayList(10); addNodesTo(allNodes); return (AbstractGPNode) allNodes.get(RNG.randomInt(allNodes.size())); } - + /** * Return a shallow reference to a random leaf of this tree. + * * @return */ public AbstractGPNode getRandomLeaf() { - if (m_Nodes.length>0) { - int k=RNG.randomInt(m_Nodes.length); - return m_Nodes[k].getRandomLeaf(); - } else { + if (m_Nodes.length > 0) { + int k = RNG.randomInt(m_Nodes.length); + return m_Nodes[k].getRandomLeaf(); + } else { return this; } } - - /** This method allows you to set the parent of the node - * @param parent The new parent + + /** + * This method allows you to set the parent of the node + * + * @param parent The new parent */ public void setParent(AbstractGPNode parent) { this.m_Parent = parent; } - /** This method allows you to get the parent of the node + /** + * This method allows you to get the parent of the node */ public AbstractGPNode getParent() { return this.m_Parent; } - /** This method allows to fully connect a following nodes to thier parents - * @param parent The parent + /** + * This method allows to fully connect a following nodes to thier parents + * + * @param parent The parent */ public void connect(AbstractGPNode parent) { this.m_Parent = parent; if (parent != null) { - this.m_Depth = this.m_Parent.getDepth()+1; - } - else { + this.m_Depth = this.m_Parent.getDepth() + 1; + } else { this.m_Depth = 0; } for (int i = 0; i < this.m_Nodes.length; i++) { @@ -478,51 +505,56 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial } } - /** This method will simply init the array of nodes + /** + * This method will simply init the array of nodes */ public void initNodeArray() { this.m_Nodes = new AbstractGPNode[this.getArity()]; } - /** This method performs a full init but with max depth + /** + * This method performs a full init but with max depth + * * @param area The allowed function area. * @param depth The absolute target depth. */ public void initFull(GPArea area, int depth) { this.m_Nodes = new AbstractGPNode[this.getArity()]; for (int i = 0; i < this.m_Nodes.length; i++) { - if (this.m_Depth+1 >= depth) { - this.m_Nodes[i] = (AbstractGPNode)area.getRandomNodeWithArity(0).clone(); + if (this.m_Depth + 1 >= depth) { + this.m_Nodes[i] = (AbstractGPNode) area.getRandomNodeWithArity(0).clone(); + } else { + this.m_Nodes[i] = (AbstractGPNode) area.getRandomNonTerminal().clone(); } - else { - this.m_Nodes[i] = (AbstractGPNode)area.getRandomNonTerminal().clone(); - } - this.m_Nodes[i].setDepth(this.m_Depth+1); + this.m_Nodes[i].setDepth(this.m_Depth + 1); this.m_Nodes[i].setParent(this); this.m_Nodes[i].initFull(area, depth); } } - /** This method performs a grow init but with max depth + /** + * This method performs a grow init but with max depth + * * @param area The allowed function area. * @param depth The absolute target depth. */ public void initGrow(GPArea area, int depth) { this.m_Nodes = new AbstractGPNode[this.getArity()]; for (int i = 0; i < this.m_Nodes.length; i++) { - if (this.m_Depth+1 >= depth) { - this.m_Nodes[i] = (AbstractGPNode)area.getRandomNodeWithArity(0).clone(); + if (this.m_Depth + 1 >= depth) { + this.m_Nodes[i] = (AbstractGPNode) area.getRandomNodeWithArity(0).clone(); + } else { + this.m_Nodes[i] = (AbstractGPNode) area.getRandomNode().clone(); } - else { - this.m_Nodes[i] = (AbstractGPNode)area.getRandomNode().clone(); - } - this.m_Nodes[i].setDepth(this.m_Depth+1); + this.m_Nodes[i].setDepth(this.m_Depth + 1); this.m_Nodes[i].setParent(this); this.m_Nodes[i].initGrow(area, depth); } } - /** This method allows you to get the overall number of nodes + /** + * This method allows you to get the overall number of nodes + * * @return Number of nodes. */ public int getNumberOfNodes() { @@ -535,6 +567,7 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial /** * Return the maximal depth of the tree starting here, but relating to the whole tree. + * * @return The max depth. */ public int getMaxDepth() { @@ -549,23 +582,24 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial /** * Return the depth of the subtree only. - * + * * @return */ public int getSubtreeDepth() { int maxDepth = getMaxDepth(); - return maxDepth-m_Depth; + return maxDepth - m_Depth; } - - /** This method will check if maxdepth is violated - * @param maxDepth The max depth. + + /** + * This method will check if maxdepth is violated + * + * @param maxDepth The max depth. * @return True if MaxDepth is violated */ public boolean isMaxDepthViolated(int maxDepth) { if (maxDepth < this.getMaxDepth()) { return true; - } - else { + } else { return false; } // if (depth > this.m_Depth) return false; @@ -578,18 +612,20 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial // } } - /** This method will repair the maxDepth constraint - * @param depth The max depth. + /** + * This method will repair the maxDepth constraint + * + * @param depth The max depth. */ public void repairMaxDepth(GPArea area, int depth) { - if (this.m_Depth == depth-1) { + if (this.m_Depth == depth - 1) { // in this case i need to check whether or not my // follow-up nodes are terminals for (int i = 0; i < this.m_Nodes.length; i++) { if (this.m_Nodes[i].getArity() != 0) { // replace this node with a new node - this.m_Nodes[i] = (AbstractGPNode)area.getRandomNodeWithArity(0).clone(); - this.m_Nodes[i].setDepth(this.m_Depth+1); + this.m_Nodes[i] = (AbstractGPNode) area.getRandomNodeWithArity(0).clone(); + this.m_Nodes[i].setDepth(this.m_Depth + 1); this.m_Nodes[i].setParent(this); } } @@ -602,16 +638,18 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial } - /** This method allows you to determine whether or not two subtrees + /** + * This method allows you to determine whether or not two subtrees * are actually the same. - * @param obj The other subtree. + * + * @param obj The other subtree. * @return boolean if equal true else false. */ @Override public boolean equals(Object obj) { if (obj.getClass().equals(this.getClass())) { - AbstractGPNode node = (AbstractGPNode)obj; - if (this.getArity()!=node.getArity()) { + AbstractGPNode node = (AbstractGPNode) obj; + if (this.getArity() != node.getArity()) { return false; } if (this.m_Nodes.length != node.m_Nodes.length) { @@ -627,34 +665,34 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial return false; } } - + /** * Update the depth of this node tree starting with the given initial depth of the root. - * + * * @param myDepth */ - public void updateDepth(int myDepth) { - m_Depth=myDepth; - for (int i=0; i m_CompleteList = new ArrayList(); - private ArrayList m_ReducedList = new ArrayList(); - private ArrayList m_BlackList = new ArrayList(); + /** + * Handles property change notification + */ + private transient PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + + private ArrayList m_CompleteList = new ArrayList(); + private ArrayList m_ReducedList = new ArrayList(); + private ArrayList m_BlackList = new ArrayList(); public GPArea() { @@ -29,13 +33,13 @@ public class GPArea implements java.io.Serializable { public GPArea(GPArea g) { if (g.m_BlackList != null) { - this.m_BlackList = (ArrayList)g.m_BlackList.clone(); + this.m_BlackList = (ArrayList) g.m_BlackList.clone(); } if (g.m_ReducedList != null) { - this.m_ReducedList = (ArrayList)g.m_ReducedList.clone(); + this.m_ReducedList = (ArrayList) g.m_ReducedList.clone(); } if (g.m_CompleteList != null) { - this.m_CompleteList = (ArrayList)g.m_CompleteList.clone(); + this.m_CompleteList = (ArrayList) g.m_CompleteList.clone(); } } @@ -44,7 +48,9 @@ public class GPArea implements java.io.Serializable { return new GPArea(this); } - /** Add a Node to the list of possible operators + /** + * Add a Node to the list of possible operators + * * @param n The Node that is to be added */ public void add2CompleteList(AbstractGPNode n) { @@ -52,7 +58,9 @@ public class GPArea implements java.io.Serializable { this.m_BlackList.add(new Boolean(true)); } - /** Add a Node to the list of possible operators + /** + * Add a Node to the list of possible operators + * * @param n The Node that is to be added * @param b The initial BlacklLst value */ @@ -61,128 +69,145 @@ public class GPArea implements java.io.Serializable { this.m_BlackList.add(new Boolean(b)); } - /** This method allows you to fetch the black list + /** + * This method allows you to fetch the black list + * * @return blacklist */ public ArrayList getBlackList() { return this.m_BlackList; } - /** This method allows you to set the black list + + /** + * This method allows you to set the black list + * * @param a blacklist */ public void SetBlackList(ArrayList a) { this.m_BlackList = a; } - /** This method allows you to set a BlackList element - * @param i the index - * @param b the boolean value + + /** + * This method allows you to set a BlackList element + * + * @param i the index + * @param b the boolean value */ public void setBlackListElement(int i, boolean b) { this.m_BlackList.set(i, new Boolean(b)); } - /** This method allows you to fetch the CompleteList + /** + * This method allows you to fetch the CompleteList + * * @return blacklist */ public ArrayList getCompleteList() { return this.m_CompleteList; } - /** This method allows you to fetch the CompleteList + /** + * This method allows you to fetch the CompleteList + * * @return blacklist */ public ArrayList getReducedList() { return this.m_ReducedList; } - /** This method allows you to set the CompleteList + /** + * This method allows you to set the CompleteList + * * @param a blacklist */ public void SetCompleteList(ArrayList a) { this.m_CompleteList = a; - m_Support.firePropertyChange("GPArea", null, this); + m_Support.firePropertyChange("GPArea", null, this); } - /** This method compiles the Complete List to the allowed list using the BlackList + /** + * This method compiles the Complete List to the allowed list using the BlackList */ public void compileReducedList() { this.m_ReducedList = new ArrayList(); for (int i = 0; i < this.m_CompleteList.size(); i++) { - if (((Boolean)(this.m_BlackList.get(i))).booleanValue()) { + if (((Boolean) (this.m_BlackList.get(i))).booleanValue()) { this.m_ReducedList.add(this.m_CompleteList.get(i)); } } - m_Support.firePropertyChange("GPArea", null, this); + m_Support.firePropertyChange("GPArea", null, this); } - /** This method allows you to fetch a random node of a given arity - * @param targetarity The target arity. + /** + * This method allows you to fetch a random node of a given arity + * + * @param targetarity The target arity. */ public AbstractGPNode getRandomNodeWithArity(int targetarity) { - ArrayList tmpArray = new ArrayList(); + ArrayList tmpArray = new ArrayList(); for (int i = 0; i < this.m_ReducedList.size(); i++) { - if (((AbstractGPNode)this.m_ReducedList.get(i)).getArity() == targetarity) { + if (((AbstractGPNode) this.m_ReducedList.get(i)).getArity() == targetarity) { tmpArray.add(this.m_ReducedList.get(i)); } } if (tmpArray.size() == 0) { return null; - } - else { - return (AbstractGPNode)tmpArray.get(RNG.randomInt(0, tmpArray.size()-1)); + } else { + return (AbstractGPNode) tmpArray.get(RNG.randomInt(0, tmpArray.size() - 1)); } } - /** This method will return a random node. + /** + * This method will return a random node. */ public AbstractGPNode getRandomNode() { if (this.m_ReducedList.size() == 0) { return null; - } - else { - return (AbstractGPNode)this.m_ReducedList.get(RNG.randomInt(0, this.m_ReducedList.size()-1)); + } else { + return (AbstractGPNode) this.m_ReducedList.get(RNG.randomInt(0, this.m_ReducedList.size() - 1)); } } - /** This method will return a non terminal + /** + * This method will return a non terminal */ public AbstractGPNode getRandomNonTerminal() { - ArrayList tmpArray = new ArrayList(); + ArrayList tmpArray = new ArrayList(); for (int i = 0; i < this.m_ReducedList.size(); i++) { - if (((AbstractGPNode)this.m_ReducedList.get(i)).getArity() > 0) { + if (((AbstractGPNode) this.m_ReducedList.get(i)).getArity() > 0) { tmpArray.add(this.m_ReducedList.get(i)); } } if (tmpArray.size() == 0) { return null; - } - else { - return (AbstractGPNode)tmpArray.get(RNG.randomInt(0, tmpArray.size()-1)); + } else { + return (AbstractGPNode) tmpArray.get(RNG.randomInt(0, tmpArray.size() - 1)); } } - public boolean isEmpty() { - return (m_CompleteList==null) || (m_CompleteList.size()==0); - } - - public void clear() { - m_CompleteList = new ArrayList(); - m_ReducedList = new ArrayList(); - m_BlackList = new ArrayList(); - m_Support.firePropertyChange("GPArea", null, this); - } - + public boolean isEmpty() { + return (m_CompleteList == null) || (m_CompleteList.size() == 0); + } + + public void clear() { + m_CompleteList = new ArrayList(); + m_ReducedList = new ArrayList(); + m_BlackList = new ArrayList(); + m_Support.firePropertyChange("GPArea", null, this); + } + public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support==null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } m_Support.addPropertyChangeListener(l); } + /** * */ public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support==null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } m_Support.removePropertyChangeListener(l); diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeAbs.java b/src/eva2/optimization/individuals/codings/gp/GPNodeAbs.java index 425082d8..cbfb3c0b 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeAbs.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeAbs.java @@ -3,19 +3,21 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** +/** * A node for retrieving the absolute value - * */ public class GPNodeAbs extends AbstractGPNode implements java.io.Serializable { public GPNodeAbs() { } + public GPNodeAbs(GPNodeAbs node) { this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -23,7 +25,9 @@ public class GPNodeAbs extends AbstractGPNode implements java.io.Serializable { return "Abs"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -31,7 +35,9 @@ public class GPNodeAbs extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeAbs(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -39,7 +45,9 @@ public class GPNodeAbs extends AbstractGPNode implements java.io.Serializable { return 1; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -49,20 +57,19 @@ public class GPNodeAbs extends AbstractGPNode implements java.io.Serializable { tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result += ((Double)tmpObj).doubleValue(); + result += ((Double) tmpObj).doubleValue(); } Double ret = new Double(result); - - if (ret<0) { + + if (ret < 0) { return -ret; - } - else { + } else { return ret; } } @Override public String getOpIdentifier() { - return "abs"; + return "abs"; } } diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeAdd.java b/src/eva2/optimization/individuals/codings/gp/GPNodeAdd.java index 031d4c07..190ea794 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeAdd.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeAdd.java @@ -1,10 +1,10 @@ package eva2.optimization.individuals.codings.gp; - import eva2.optimization.problems.InterfaceProgramProblem; -/** A simple add node with two arguments. +/** + * A simple add node with two arguments. * Created by IntelliJ IDEA. * User: streiche * Date: 04.04.2003 @@ -17,10 +17,12 @@ public class GPNodeAdd extends AbstractGPNode implements java.io.Serializable { } public GPNodeAdd(GPNodeAdd node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -28,7 +30,9 @@ public class GPNodeAdd extends AbstractGPNode implements java.io.Serializable { return "Add"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -36,7 +40,9 @@ public class GPNodeAdd extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeAdd(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -44,7 +50,9 @@ public class GPNodeAdd extends AbstractGPNode implements java.io.Serializable { return 2; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -55,7 +63,7 @@ public class GPNodeAdd extends AbstractGPNode implements java.io.Serializable { for (int i = 0; i < this.m_Nodes.length; i++) { tmpObj = this.m_Nodes[i].evaluate(environment); if (tmpObj instanceof Double) { - result += ((Double)tmpObj).doubleValue(); + result += ((Double) tmpObj).doubleValue(); } } return new Double(result); @@ -63,6 +71,6 @@ public class GPNodeAdd extends AbstractGPNode implements java.io.Serializable { @Override public String getOpIdentifier() { - return "+"; + return "+"; } } diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeConst.java b/src/eva2/optimization/individuals/codings/gp/GPNodeConst.java index 66ada5e7..8ae1563d 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeConst.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeConst.java @@ -6,38 +6,43 @@ import eva2.optimization.problems.InterfaceProgramProblem; * A simple constant node with the value 1. */ public class GPNodeConst extends AbstractGPNode implements java.io.Serializable { - double value = 1.; - - public GPNodeConst() { } - + double value = 1.; + + public GPNodeConst() { + } + public GPNodeConst(double val) { - value = val; + value = val; } public GPNodeConst(GPNodeConst node) { - value = node.value; - this.cloneMembers(node); + value = node.value; + this.cloneMembers(node); } @Override - public boolean equals(Object obj) { - if (obj instanceof GPNodeConst) { - GPNodeConst node = (GPNodeConst)obj; - return (node.value==this.value); - } else { - return false; - } - } + public boolean equals(Object obj) { + if (obj instanceof GPNodeConst) { + GPNodeConst node = (GPNodeConst) obj; + return (node.value == this.value); + } else { + return false; + } + } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override public String getName() { - return ""+value; + return "" + value; } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -45,7 +50,9 @@ public class GPNodeConst extends AbstractGPNode implements java.io.Serializable return 0; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -55,7 +62,7 @@ public class GPNodeConst extends AbstractGPNode implements java.io.Serializable @Override public String getOpIdentifier() { - return getName(); + return getName(); } // /** This method returns a string representation // * @return string @@ -64,8 +71,8 @@ public class GPNodeConst extends AbstractGPNode implements java.io.Serializable // return getName(); // } - @Override - public Object clone() { - return new GPNodeConst(this); - } + @Override + public Object clone() { + return new GPNodeConst(this); + } } diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeCos.java b/src/eva2/optimization/individuals/codings/gp/GPNodeCos.java index a0317226..d3d7fb5a 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeCos.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeCos.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** A cos node with on argument. +/** + * A cos node with on argument. * Created by IntelliJ IDEA. * User: streiche * Date: 27.06.2003 @@ -13,11 +14,14 @@ public class GPNodeCos extends AbstractGPNode implements java.io.Serializable { public GPNodeCos() { } + public GPNodeCos(GPNodeCos node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -25,7 +29,9 @@ public class GPNodeCos extends AbstractGPNode implements java.io.Serializable { return "Cos"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -33,7 +39,9 @@ public class GPNodeCos extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeCos(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -41,7 +49,9 @@ public class GPNodeCos extends AbstractGPNode implements java.io.Serializable { return 1; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -51,13 +61,13 @@ public class GPNodeCos extends AbstractGPNode implements java.io.Serializable { tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result = Math.sin(((Double)tmpObj).doubleValue()); + result = Math.sin(((Double) tmpObj).doubleValue()); } return new Double(result); } - + @Override public String getOpIdentifier() { - return "cos"; + return "cos"; } } diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeDiv.java b/src/eva2/optimization/individuals/codings/gp/GPNodeDiv.java index 81214e79..66688e8d 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeDiv.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeDiv.java @@ -3,7 +3,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** A division node with two arguments and secure division. If +/** + * A division node with two arguments and secure division. If * the second argument is absolute smaller than 0.00000001 the * result is 1. * Created by IntelliJ IDEA. @@ -13,7 +14,7 @@ import eva2.optimization.problems.InterfaceProgramProblem; * To change this template use Options | File Templates. */ public class GPNodeDiv extends AbstractGPNode implements java.io.Serializable { - private double m_LowerBorderForSec = 0.00000001; + private double m_LowerBorderForSec = 0.00000001; public GPNodeDiv() { @@ -25,7 +26,9 @@ public class GPNodeDiv extends AbstractGPNode implements java.io.Serializable { this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -33,7 +36,9 @@ public class GPNodeDiv extends AbstractGPNode implements java.io.Serializable { return "Div"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -41,7 +46,9 @@ public class GPNodeDiv extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeDiv(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -49,42 +56,43 @@ public class GPNodeDiv extends AbstractGPNode implements java.io.Serializable { return 2; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override public Object evaluate(InterfaceProgramProblem environment) { Object tmpObj; - double result = 1; + double result = 1; double tmpValue = 0; tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result = ((Double)tmpObj).doubleValue(); + result = ((Double) tmpObj).doubleValue(); } for (int i = 1; i < this.m_Nodes.length; i++) { tmpObj = this.m_Nodes[i].evaluate(environment); if (tmpObj instanceof Double) { - tmpValue = ((Double)tmpObj).doubleValue(); + tmpValue = ((Double) tmpObj).doubleValue(); } - if (Math.abs(tmpValue) < this.m_LowerBorderForSec) { - if (tmpValue < 0) { - tmpValue = -this.m_LowerBorderForSec; - } - else { - tmpValue = this.m_LowerBorderForSec; - } + if (Math.abs(tmpValue) < this.m_LowerBorderForSec) { + if (tmpValue < 0) { + tmpValue = -this.m_LowerBorderForSec; + } else { + tmpValue = this.m_LowerBorderForSec; } - result /= tmpValue; + } + result /= tmpValue; } return new Double(result); } - + @Override public String getOpIdentifier() { - return "/"; + return "/"; } - + // /** This method returns a string representation // * @return string // */ diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeExp.java b/src/eva2/optimization/individuals/codings/gp/GPNodeExp.java index 4a07dd74..5549773e 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeExp.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeExp.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** An exponent node with one argument. +/** + * An exponent node with one argument. * Created by IntelliJ IDEA. * User: streiche * Date: 27.06.2003 @@ -13,11 +14,14 @@ public class GPNodeExp extends AbstractGPNode implements java.io.Serializable { public GPNodeExp() { } + public GPNodeExp(GPNodeExp node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -25,7 +29,9 @@ public class GPNodeExp extends AbstractGPNode implements java.io.Serializable { return "Exp"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -33,7 +39,9 @@ public class GPNodeExp extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeExp(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -41,7 +49,9 @@ public class GPNodeExp extends AbstractGPNode implements java.io.Serializable { return 1; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -51,14 +61,14 @@ public class GPNodeExp extends AbstractGPNode implements java.io.Serializable { tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result = Math.exp(((Double)tmpObj).doubleValue()); + result = Math.exp(((Double) tmpObj).doubleValue()); } return new Double(result); } @Override public String getOpIdentifier() { - return "exp"; + return "exp"; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec2.java b/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec2.java index cb3799a9..f953256a 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec2.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec2.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** This nodes executes both arguments. +/** + * This nodes executes both arguments. * Created by IntelliJ IDEA. * User: streiche * Date: 16.06.2003 @@ -14,11 +15,14 @@ public class GPNodeFlowExec2 extends AbstractGPNode implements java.io.Serializa public GPNodeFlowExec2() { } + public GPNodeFlowExec2(GPNodeFlowExec2 node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -26,7 +30,9 @@ public class GPNodeFlowExec2 extends AbstractGPNode implements java.io.Serializa return "Exec2"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -34,7 +40,9 @@ public class GPNodeFlowExec2 extends AbstractGPNode implements java.io.Serializa return (Object) new GPNodeFlowExec2(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -42,12 +50,14 @@ public class GPNodeFlowExec2 extends AbstractGPNode implements java.io.Serializa return 2; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override public Object evaluate(InterfaceProgramProblem environment) { - Object[] result = new Object[this.m_Nodes.length]; + Object[] result = new Object[this.m_Nodes.length]; for (int i = 0; i < this.m_Nodes.length; i++) { result[i] = this.m_Nodes[i].evaluate(environment); @@ -57,9 +67,9 @@ public class GPNodeFlowExec2 extends AbstractGPNode implements java.io.Serializa @Override public String getOpIdentifier() { - return "Exec2"; + return "Exec2"; } - + // /** This method returns a string representation // * @return string // */ diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec3.java b/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec3.java index 958020f7..bd8be62f 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec3.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeFlowExec3.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** This node executes all three arguments. +/** + * This node executes all three arguments. * Created by IntelliJ IDEA. * User: streiche * Date: 16.06.2003 @@ -14,11 +15,14 @@ public class GPNodeFlowExec3 extends AbstractGPNode implements java.io.Serializa public GPNodeFlowExec3() { } + public GPNodeFlowExec3(GPNodeFlowExec3 node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -26,7 +30,9 @@ public class GPNodeFlowExec3 extends AbstractGPNode implements java.io.Serializa return "Exec3"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -34,7 +40,9 @@ public class GPNodeFlowExec3 extends AbstractGPNode implements java.io.Serializa return (Object) new GPNodeFlowExec3(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -42,12 +50,14 @@ public class GPNodeFlowExec3 extends AbstractGPNode implements java.io.Serializa return 3; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override public Object evaluate(InterfaceProgramProblem environment) { - Object[] result = new Object[this.m_Nodes.length]; + Object[] result = new Object[this.m_Nodes.length]; for (int i = 0; i < this.m_Nodes.length; i++) { result[i] = this.m_Nodes[i].evaluate(environment); @@ -57,7 +67,7 @@ public class GPNodeFlowExec3 extends AbstractGPNode implements java.io.Serializa @Override public String getOpIdentifier() { - return "Exec3"; + return "Exec3"; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeInput.java b/src/eva2/optimization/individuals/codings/gp/GPNodeInput.java index 4eb407ef..c536c13a 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeInput.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeInput.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** This node is able to read a sensor value from the environment (e.g. the +/** + * This node is able to read a sensor value from the environment (e.g. the * problem) the sensor to read is given by the identifier and has to be * implemented in the problem definition. * Created by IntelliJ IDEA. @@ -12,35 +13,38 @@ import eva2.optimization.problems.InterfaceProgramProblem; * To change this template use Options | File Templates. */ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable { - private String m_Identifier; - private Object lastValue; - - /** This method creates a new GPNodeInput + private String m_Identifier; + private Object lastValue; + + /** + * This method creates a new GPNodeInput */ public GPNodeInput() { - this.m_Identifier = "X"; + this.m_Identifier = "X"; } - /** This method creates a new GPNodeInput - * @param identifier The name of the sensor requested. + /** + * This method creates a new GPNodeInput + * + * @param identifier The name of the sensor requested. */ public GPNodeInput(String identifier) { - this.m_Identifier = identifier; + this.m_Identifier = identifier; } public GPNodeInput(GPNodeInput node) { - this.m_Identifier = node.m_Identifier; + this.m_Identifier = node.m_Identifier; this.cloneMembers(node); } - + public void setIdentifier(String str) { - m_Identifier=str; + m_Identifier = str; } @Override public boolean equals(Object obj) { if (obj instanceof GPNodeInput) { - GPNodeInput node = (GPNodeInput)obj; + GPNodeInput node = (GPNodeInput) obj; if (!this.m_Identifier.equalsIgnoreCase(node.m_Identifier)) { return false; } @@ -50,14 +54,19 @@ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable } } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override public String getName() { - return "Sensor:"+this.m_Identifier; + return "Sensor:" + this.m_Identifier; } - /** This method allows you to clone the Nodes + + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -65,7 +74,9 @@ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable return (Object) new GPNodeInput(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -73,7 +84,9 @@ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable return 0; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -82,21 +95,22 @@ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable return lastValue; } - /** This method returns a string representation + /** + * This method returns a string representation + * * @return string */ @Override public String getOpIdentifier() { if (this.lastValue == null) { return this.m_Identifier; - } - else { + } else { if (this.lastValue instanceof Double) { - double tmpD = ((Double)this.lastValue).doubleValue(); - tmpD = ((long)(tmpD*10000.0 + ((tmpD>=0.0)?0.5:-0.5)))/10000.0; - return ("S:" +this.m_Identifier + " = " + tmpD); + double tmpD = ((Double) this.lastValue).doubleValue(); + tmpD = ((long) (tmpD * 10000.0 + ((tmpD >= 0.0) ? 0.5 : -0.5))) / 10000.0; + return ("S:" + this.m_Identifier + " = " + tmpD); } else { - return ("S:" +this.m_Identifier + " = " + this.lastValue.toString()); + return ("S:" + this.m_Identifier + " = " + this.lastValue.toString()); } } } diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeMult.java b/src/eva2/optimization/individuals/codings/gp/GPNodeMult.java index d4df4c42..80b989af 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeMult.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeMult.java @@ -3,7 +3,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** A multiplicator node taking two arguments. +/** + * A multiplicator node taking two arguments. * Created by IntelliJ IDEA. * User: streiche * Date: 04.04.2003 @@ -14,11 +15,14 @@ public class GPNodeMult extends AbstractGPNode implements java.io.Serializable { public GPNodeMult() { } + public GPNodeMult(GPNodeMult node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -26,7 +30,9 @@ public class GPNodeMult extends AbstractGPNode implements java.io.Serializable { return "Mult"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -34,7 +40,9 @@ public class GPNodeMult extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeMult(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -42,7 +50,9 @@ public class GPNodeMult extends AbstractGPNode implements java.io.Serializable { return 2; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -53,10 +63,9 @@ public class GPNodeMult extends AbstractGPNode implements java.io.Serializable { for (int i = 0; i < this.m_Nodes.length; i++) { tmpObj = this.m_Nodes[i].evaluate(environment); if (tmpObj instanceof Double) { - result *= ((Double)tmpObj).doubleValue(); - } - else { - System.err.println("Unexpected type returned in evaluate for "+this.getClass().getSimpleName()); + result *= ((Double) tmpObj).doubleValue(); + } else { + System.err.println("Unexpected type returned in evaluate for " + this.getClass().getSimpleName()); } } return new Double(result); @@ -64,7 +73,7 @@ public class GPNodeMult extends AbstractGPNode implements java.io.Serializable { @Override public String getOpIdentifier() { - return "*"; + return "*"; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeNeg.java b/src/eva2/optimization/individuals/codings/gp/GPNodeNeg.java index c3baf8c0..0de10350 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeNeg.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeNeg.java @@ -3,7 +3,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** A substraction node using two arguments. +/** + * A substraction node using two arguments. * Created by IntelliJ IDEA. * User: streiche * Date: 04.04.2003 @@ -14,11 +15,14 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { public GPNodeNeg() { } + public GPNodeNeg(GPNodeNeg node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -26,7 +30,9 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { return "Neg"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -34,7 +40,9 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodeNeg(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -42,7 +50,9 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { return 1; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -52,12 +62,12 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result += ((Double)tmpObj).doubleValue(); + result += ((Double) tmpObj).doubleValue(); } for (int i = 1; i < this.m_Nodes.length; i++) { tmpObj = this.m_Nodes[i].evaluate(environment); if (tmpObj instanceof Double) { - result -= ((Double)tmpObj).doubleValue(); + result -= ((Double) tmpObj).doubleValue(); } } return new Double(result); @@ -65,7 +75,7 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { @Override public String getOpIdentifier() { - return "neg"; + return "neg"; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeOne.java b/src/eva2/optimization/individuals/codings/gp/GPNodeOne.java index aa18f141..02ad9979 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeOne.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeOne.java @@ -6,14 +6,16 @@ package eva2.optimization.individuals.codings.gp; */ public class GPNodeOne extends GPNodeConst implements java.io.Serializable { public GPNodeOne() { - super(1.); + super(1.); } - + public GPNodeOne(GPNodeOne node) { - super(node); - } - - /** This method allows you to clone the Nodes + super(node); + } + + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeOutput.java b/src/eva2/optimization/individuals/codings/gp/GPNodeOutput.java index d9d5a72a..0642dbba 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeOutput.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeOutput.java @@ -2,10 +2,11 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** The node allows the program to give an output or to perform an action +/** + * The node allows the program to give an output or to perform an action * in the enviroment simulated in the problem. The type of action is given * by the identifier and has to be implemented by the problem definition. - * See the artificial ant problem for an example. + * See the artificial ant problem for an example. * Created by IntelliJ IDEA. * User: streiche * Date: 16.06.2003 @@ -14,28 +15,30 @@ import eva2.optimization.problems.InterfaceProgramProblem; */ public class GPNodeOutput extends AbstractGPNode implements java.io.Serializable { - private String m_Identifier; - + private String m_Identifier; + public GPNodeOutput() { - this.m_Identifier = "Y"; + this.m_Identifier = "Y"; } - - /** This method creates a new GPNodeInput - * @param identifier The name of the sensor requested. + + /** + * This method creates a new GPNodeInput + * + * @param identifier The name of the sensor requested. */ public GPNodeOutput(String identifier) { - this.m_Identifier = identifier; + this.m_Identifier = identifier; } public GPNodeOutput(GPNodeOutput node) { - this.m_Identifier = node.m_Identifier; + this.m_Identifier = node.m_Identifier; this.cloneMembers(node); } @Override public boolean equals(Object obj) { if (obj instanceof GPNodeOutput) { - GPNodeOutput node = (GPNodeOutput)obj; + GPNodeOutput node = (GPNodeOutput) obj; if (!this.m_Identifier.equalsIgnoreCase(node.m_Identifier)) { return false; } @@ -45,15 +48,19 @@ public class GPNodeOutput extends AbstractGPNode implements java.io.Serializable } } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override public String getName() { - return "Actuator:" +this.m_Identifier; + return "Actuator:" + this.m_Identifier; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -61,7 +68,9 @@ public class GPNodeOutput extends AbstractGPNode implements java.io.Serializable return (Object) new GPNodeOutput(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -69,7 +78,9 @@ public class GPNodeOutput extends AbstractGPNode implements java.io.Serializable return 0; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -80,7 +91,7 @@ public class GPNodeOutput extends AbstractGPNode implements java.io.Serializable @Override public String getOpIdentifier() { - return "OUT:"+m_Identifier; + return "OUT:" + m_Identifier; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodePi.java b/src/eva2/optimization/individuals/codings/gp/GPNodePi.java index b4fe7a17..5e85b163 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodePi.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodePi.java @@ -6,22 +6,26 @@ package eva2.optimization.individuals.codings.gp; */ public class GPNodePi extends GPNodeConst implements java.io.Serializable { public GPNodePi() { - super(Math.PI); + super(Math.PI); } - - public GPNodePi(GPNodePi node) { - super(node); - } - /** This method allows you to clone the Nodes + public GPNodePi(GPNodePi node) { + super(node); + } + + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override public Object clone() { return (Object) new GPNodePi(this); } - - /** This method will be used to identify the node in the GPAreaEditor + + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodePow2.java b/src/eva2/optimization/individuals/codings/gp/GPNodePow2.java index e8ada1f7..10dd905c 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodePow2.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodePow2.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** This node puts the argument to the power of two. +/** + * This node puts the argument to the power of two. * Created by IntelliJ IDEA. * User: streiche * Date: 30.09.2003 @@ -13,11 +14,14 @@ public class GPNodePow2 extends AbstractGPNode implements java.io.Serializable { public GPNodePow2() { } + public GPNodePow2(GPNodePow2 node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -25,7 +29,9 @@ public class GPNodePow2 extends AbstractGPNode implements java.io.Serializable { return "Pow2"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -33,7 +39,9 @@ public class GPNodePow2 extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodePow2(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -41,7 +49,9 @@ public class GPNodePow2 extends AbstractGPNode implements java.io.Serializable { return 1; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -51,14 +61,14 @@ public class GPNodePow2 extends AbstractGPNode implements java.io.Serializable { tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result = Math.pow(((Double)tmpObj).doubleValue(), 2); + result = Math.pow(((Double) tmpObj).doubleValue(), 2); } return new Double(result); } @Override public String getOpIdentifier() { - return "pow2"; + return "pow2"; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodePow3.java b/src/eva2/optimization/individuals/codings/gp/GPNodePow3.java index b0c594a0..96aa18bf 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodePow3.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodePow3.java @@ -2,7 +2,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; -/** This argument puts the argument to the power of three. +/** + * This argument puts the argument to the power of three. * Created by IntelliJ IDEA. * User: streiche * Date: 30.09.2003 @@ -13,11 +14,14 @@ public class GPNodePow3 extends AbstractGPNode implements java.io.Serializable { public GPNodePow3() { } + public GPNodePow3(GPNodePow3 node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -25,7 +29,9 @@ public class GPNodePow3 extends AbstractGPNode implements java.io.Serializable { return "Pow3"; } - /** This method allows you to clone the Nodes + /** + * This method allows you to clone the Nodes + * * @return the clone */ @Override @@ -33,7 +39,9 @@ public class GPNodePow3 extends AbstractGPNode implements java.io.Serializable { return (Object) new GPNodePow3(this); } - /** This method will return the current arity + /** + * This method will return the current arity + * * @return Arity. */ @Override @@ -41,7 +49,9 @@ public class GPNodePow3 extends AbstractGPNode implements java.io.Serializable { return 1; } - /** This method will evaluate a given node + /** + * This method will evaluate a given node + * * @param environment */ @Override @@ -51,14 +61,14 @@ public class GPNodePow3 extends AbstractGPNode implements java.io.Serializable { tmpObj = this.m_Nodes[0].evaluate(environment); if (tmpObj instanceof Double) { - result = Math.pow(((Double)tmpObj).doubleValue(), 3); + result = Math.pow(((Double) tmpObj).doubleValue(), 3); } return new Double(result); } @Override public String getOpIdentifier() { - return "pow3"; + return "pow3"; } // /** This method returns a string representation // * @return string diff --git a/src/eva2/optimization/individuals/codings/gp/GPNodeProd.java b/src/eva2/optimization/individuals/codings/gp/GPNodeProd.java index b8056741..875a2592 100644 --- a/src/eva2/optimization/individuals/codings/gp/GPNodeProd.java +++ b/src/eva2/optimization/individuals/codings/gp/GPNodeProd.java @@ -4,9 +4,8 @@ package eva2.optimization.individuals.codings.gp; import eva2.optimization.problems.InterfaceProgramProblem; import eva2.tools.math.Mathematics; -/** +/** * A simple product node with a single, possibly vectorial (array), argument. - * */ public class GPNodeProd extends AbstractGPNode implements java.io.Serializable { @@ -14,10 +13,12 @@ public class GPNodeProd extends AbstractGPNode implements java.io.Serializable { } public GPNodeProd(GPNodeProd node) { - this.cloneMembers(node); + this.cloneMembers(node); } - /** This method will be used to identify the node in the GPAreaEditor + /** + * This method will be used to identify the node in the GPAreaEditor + * * @return The name. */ @Override @@ -43,15 +44,14 @@ public class GPNodeProd extends AbstractGPNode implements java.io.Serializable { for (int i = 0; i < this.m_Nodes.length; i++) { tmpObj = this.m_Nodes[i].evaluate(environment); if (tmpObj instanceof double[]) { - result*=Mathematics.product((double[])tmpObj); - } - else if (tmpObj instanceof Double[]) { - Double[] vals = (Double[])tmpObj; - for (int j=0; j 0) { pop = m_Mocco.m_State.getSelectedPopulations(); m_Mocco.m_State.m_Optimizer.initByPopulation(pop, false); - if (pop.size() == 0) { + if (pop.size() == 0) { m_Mocco.m_State.m_Optimizer.init(); } } diff --git a/src/eva2/optimization/mocco/MOCCOParameterizeRefPoint.java b/src/eva2/optimization/mocco/MOCCOParameterizeRefPoint.java index d89d49bb..3dce7710 100644 --- a/src/eva2/optimization/mocco/MOCCOParameterizeRefPoint.java +++ b/src/eva2/optimization/mocco/MOCCOParameterizeRefPoint.java @@ -12,6 +12,7 @@ import eva2.optimization.strategies.IslandModelEA; import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGOEProperty; import eva2.tools.math.RNG; + import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -31,20 +32,21 @@ import javax.swing.JTextField; */ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfaceProcessElement { - private double[] m_RefPoint; - private MOSOLpMetric m_LpMetric; - private IslandModelEA m_Island; - private GeneralGOEProperty m_EMOSO, m_EIMEA; - private int m_Perturbations = 4; - private double m_Perturbation = 0.01; - private JTextField m_NumPer, m_SizePer; - JPanel m_Parameters; + private double[] m_RefPoint; + private MOSOLpMetric m_LpMetric; + private IslandModelEA m_Island; + private GeneralGOEProperty m_EMOSO, m_EIMEA; + private int m_Perturbations = 4; + private double m_Perturbation = 0.01; + private JTextField m_NumPer, m_SizePer; + JPanel m_Parameters; public MOCCOParameterizeRefPoint(MOCCOStandalone mocco) { this.m_Mocco = mocco; } - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public void initProcessElementParametrization() { @@ -82,34 +84,34 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr private void installChoice() { this.m_Parameters.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weightx = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 0; + gbc.weightx = 2; this.m_Parameters.add(new JLabel("Choose number of Perturbations k:"), gbc); - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 1; - this.m_NumPer = new JTextField(""+this.m_Perturbations); + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 1; + this.m_NumPer = new JTextField("" + this.m_Perturbations); this.m_Parameters.add(this.m_NumPer, gbc); - gbc.gridx = 0; - gbc.gridy = 1; - gbc.weightx = 2; + gbc.gridx = 0; + gbc.gridy = 1; + gbc.weightx = 2; this.m_Parameters.add(new JLabel("Choose amount of Perturbation:"), gbc); - gbc.gridx = 1; - gbc.gridy = 1; - gbc.weightx = 1; - this.m_SizePer = new JTextField(""+this.m_Perturbation); + gbc.gridx = 1; + gbc.gridy = 1; + gbc.weightx = 1; + this.m_SizePer = new JTextField("" + this.m_Perturbation); this.m_Parameters.add(this.m_SizePer, gbc); // lpmetric - this.m_EMOSO = new GeneralGOEProperty(); + this.m_EMOSO = new GeneralGOEProperty(); this.m_LpMetric = new MOSOLpMetric(); this.m_LpMetric.getReference().setDoubleArray(this.m_RefPoint); - this.m_EMOSO.m_Name = "Lp-Metric"; + this.m_EMOSO.m_Name = "Lp-Metric"; try { - this.m_EMOSO.m_Value = this.m_LpMetric; - this.m_EMOSO.m_Editor = PropertyEditorProvider.findEditor(this.m_EMOSO.m_Value.getClass()); + this.m_EMOSO.m_Value = this.m_LpMetric; + this.m_EMOSO.m_Editor = PropertyEditorProvider.findEditor(this.m_EMOSO.m_Value.getClass()); if (this.m_EMOSO.m_Editor == null) { this.m_EMOSO.m_Editor = PropertyEditorProvider.findEditor(MOSOLpMetric.class); } @@ -124,17 +126,17 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 2; - gbc.weightx = 2; - this.m_Parameters.add(new JLabel(""+this.m_EMOSO.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 2; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 2; + gbc.weightx = 2; + this.m_Parameters.add(new JLabel("" + this.m_EMOSO.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 2; + gbc.weightx = 1; this.m_Parameters.add(this.m_EMOSO.m_View, gbc); // IslandModelEA - this.m_EIMEA = new GeneralGOEProperty(); - this.m_Island = new IslandModelEA(); + this.m_EIMEA = new GeneralGOEProperty(); + this.m_Island = new IslandModelEA(); this.m_Island.setHeterogenuousProblems(true); this.m_Island.setLocalOnly(true); this.m_Island.setMigrationRate(2); @@ -142,10 +144,10 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr this.m_Island.setNumberLocalCPUs(this.m_Perturbations); this.m_Island.setProblem(this.m_Mocco.m_State.m_CurrentProblem); this.m_Mocco.m_State.m_Optimizer = this.m_Island; - this.m_EIMEA.m_Name = "Island Model EA"; + this.m_EIMEA.m_Name = "Island Model EA"; try { - this.m_EIMEA.m_Value = this.m_Island; - this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(this.m_EIMEA.m_Value.getClass()); + this.m_EIMEA.m_Value = this.m_Island; + this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(this.m_EIMEA.m_Value.getClass()); if (this.m_EIMEA.m_Editor == null) { this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(IslandModelEA.class); } @@ -160,20 +162,20 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 3; - gbc.weightx = 2; - this.m_Parameters.add(new JLabel(""+this.m_EIMEA.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 3; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 3; + gbc.weightx = 2; + this.m_Parameters.add(new JLabel("" + this.m_EIMEA.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 3; + gbc.weightx = 1; this.m_Parameters.add(this.m_EIMEA.m_View, gbc); // Terminator - GeneralGOEProperty editor = new GeneralGOEProperty(); - editor.m_Name = "Terminator"; + GeneralGOEProperty editor = new GeneralGOEProperty(); + editor.m_Name = "Terminator"; try { - editor.m_Value = this.m_Mocco.m_State.m_Terminator; - editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); + editor.m_Value = this.m_Mocco.m_State.m_Terminator; + editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); if (editor.m_Editor == null) { editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); } @@ -188,19 +190,21 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 4; - gbc.weightx = 2; - this.m_Parameters.add(new JLabel(""+editor.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 4; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 4; + gbc.weightx = 2; + this.m_Parameters.add(new JLabel("" + editor.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 4; + gbc.weightx = 1; this.m_Parameters.add(editor.m_View, gbc); } - /** Method method allows mocco to set the previously selected + /** + * Method method allows mocco to set the previously selected * reference point - * @param point the reference point + * + * @param point the reference point */ public void setReferencePoint(double[] point) { this.m_RefPoint = point; @@ -228,12 +232,12 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr System.out.println("Can't read amount of perturbation."); } if (m_EIMEA.m_Value instanceof IslandModelEA) { - m_Island = (IslandModelEA)m_EIMEA.m_Value; + m_Island = (IslandModelEA) m_EIMEA.m_Value; } else { System.out.println("The selected optimizer does not allow heterogenuous multi-starts!"); } if (m_EMOSO.m_Value instanceof MOSOLpMetric) { - m_LpMetric = (MOSOLpMetric)m_EMOSO.m_Value; + m_LpMetric = (MOSOLpMetric) m_EMOSO.m_Value; } else { System.out.println("The selected MOSO conversion is not suited for the reference point approach!"); } @@ -259,16 +263,15 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr for (int j = 0; j < tmpD.length; j++) { if (i > 0) { tmpD[j] = m_RefPoint[j] + RNG.gaussianDouble(m_Perturbation); - } - else { + } else { tmpD[j] = m_RefPoint[j]; } } - tmpLPs[i] = (MOSOLpMetric)m_LpMetric.clone(); + tmpLPs[i] = (MOSOLpMetric) m_LpMetric.clone(); // I've to set this before I change the parameters, because the problem sets the // output dimension based on the AbstractMultiObjectiveOptimizationProblem and // that one has not the faintest idea about the true output dimension - ((AbstractMultiObjectiveOptimizationProblem)m_Island.getOptimizers()[i].getProblem()).setMOSOConverter(tmpLPs[i]); + ((AbstractMultiObjectiveOptimizationProblem) m_Island.getOptimizers()[i].getProblem()).setMOSOConverter(tmpLPs[i]); tmpLPs[i].setOutputDimension(tmpD.length); tmpLPs[i].getReference().setDoubleArray(tmpD); } diff --git a/src/eva2/optimization/mocco/MOCCOParameterizeSO.java b/src/eva2/optimization/mocco/MOCCOParameterizeSO.java index f9cc0afd..248e4ba0 100644 --- a/src/eva2/optimization/mocco/MOCCOParameterizeSO.java +++ b/src/eva2/optimization/mocco/MOCCOParameterizeSO.java @@ -10,6 +10,7 @@ import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.MultiObjectiveEA; import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGOEProperty; + import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -34,7 +35,8 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE this.m_Mocco = mocco; } - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public void initProcessElementParametrization() { @@ -60,10 +62,10 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE private void init() { if (this.m_Mocco.m_State.m_Optimizer instanceof MultiObjectiveEA) { JOptionPane.showMessageDialog(this.m_Mocco.m_JFrame, - "The current "+this.m_Mocco.m_State.m_Optimizer.getName() + - " is no single-objective optimizer. I'm defaulting to " + - "a Genetic Algorithms, please parameterize accordingly.", - "Warning", JOptionPane.WARNING_MESSAGE); + "The current " + this.m_Mocco.m_State.m_Optimizer.getName() + + " is no single-objective optimizer. I'm defaulting to " + + "a Genetic Algorithms, please parameterize accordingly.", + "Warning", JOptionPane.WARNING_MESSAGE); this.m_Mocco.m_State.m_Optimizer = new GeneticAlgorithm(); this.m_Mocco.m_State.m_Optimizer.setProblem(this.m_Mocco.m_State.m_CurrentProblem); } @@ -72,14 +74,14 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE JPanel tmpP = new JPanel(); tmpP.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; - GeneralGOEProperty editor = new GeneralGOEProperty(); - editor.m_Name = "Optimizer"; + GeneralGOEProperty editor = new GeneralGOEProperty(); + editor.m_Name = "Optimizer"; try { - editor.m_Value = this.m_Mocco.m_State.m_Optimizer; - editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); + editor.m_Value = this.m_Mocco.m_State.m_Optimizer; + editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); if (editor.m_Editor == null) { editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizer.class); } @@ -94,20 +96,20 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weightx = 1; - tmpP.add(new JLabel(""+editor.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 2; + gbc.gridx = 0; + gbc.gridy = 0; + gbc.weightx = 1; + tmpP.add(new JLabel("" + editor.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 2; tmpP.add(editor.m_View, gbc); - editor = new GeneralGOEProperty(); - editor.m_Name = "Terminator"; + editor = new GeneralGOEProperty(); + editor.m_Name = "Terminator"; try { - editor.m_Value = this.m_Mocco.m_State.m_Terminator; - editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); + editor.m_Value = this.m_Mocco.m_State.m_Terminator; + editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); if (editor.m_Editor == null) { editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); } @@ -122,13 +124,13 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 1; - gbc.weightx = 1; - tmpP.add(new JLabel(""+editor.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 1; - gbc.weightx = 2; + gbc.gridx = 0; + gbc.gridy = 1; + gbc.weightx = 1; + tmpP.add(new JLabel("" + editor.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 1; + gbc.weightx = 2; tmpP.add(editor.m_View, gbc); this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.CENTER); this.m_Mocco.m_JPanelParameters.add(this.makeInformationText("Single-Objective Optimiaztion", "" + diff --git a/src/eva2/optimization/mocco/MOCCOParameterizeSTEP.java b/src/eva2/optimization/mocco/MOCCOParameterizeSTEP.java index 3b8df6c9..669713f9 100644 --- a/src/eva2/optimization/mocco/MOCCOParameterizeSTEP.java +++ b/src/eva2/optimization/mocco/MOCCOParameterizeSTEP.java @@ -15,6 +15,7 @@ import eva2.optimization.strategies.GeneticAlgorithm; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGOEProperty; + import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -37,18 +38,19 @@ import javax.swing.JTextField; */ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProcessElement { - private AbstractEAIndividual m_RefSolution; - private JTextField[] m_RefSol, m_Relax, m_Weight; - private JCheckBox[] m_Satisfied; - JPanel m_Choice; - private InterfaceOptimizer m_Opt; - private GeneralGOEProperty m_EOpt; + private AbstractEAIndividual m_RefSolution; + private JTextField[] m_RefSol, m_Relax, m_Weight; + private JCheckBox[] m_Satisfied; + JPanel m_Choice; + private InterfaceOptimizer m_Opt; + private GeneralGOEProperty m_EOpt; public MOCCOParameterizeSTEP(MOCCOStandalone mocco) { this.m_Mocco = mocco; } - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public void initProcessElementParametrization() { @@ -75,8 +77,8 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces tmpP.setLayout(new BorderLayout()); this.m_Choice = new JPanel(); //this.m_Choice.setBorder(BorderFactory.createCompoundBorder( - // BorderFactory.createTitledBorder("Step Method:"), - // BorderFactory.createEmptyBorder(0, 5, 5, 5))); + // BorderFactory.createTitledBorder("Step Method:"), + // BorderFactory.createEmptyBorder(0, 5, 5, 5))); tmpP.add(this.m_Choice, BorderLayout.CENTER); this.installChoice(); this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.CENTER); @@ -88,98 +90,96 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces this.m_Choice.setLayout(new GridBagLayout()); JPanel panelSTEP = new JPanel(); panelSTEP.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Parameterize Perferences:"), - BorderFactory.createEmptyBorder(0, 5, 5, 5))); + BorderFactory.createTitledBorder("Parameterize Perferences:"), + BorderFactory.createEmptyBorder(0, 5, 5, 5))); panelSTEP.setLayout(new GridBagLayout()); - InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); - this.m_RefSol = new JTextField[obj.length]; - this.m_Relax = new JTextField[obj.length]; - this.m_Weight = new JTextField[obj.length]; - this.m_Satisfied = new JCheckBox[obj.length]; + InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); + this.m_RefSol = new JTextField[obj.length]; + this.m_Relax = new JTextField[obj.length]; + this.m_Weight = new JTextField[obj.length]; + this.m_Satisfied = new JCheckBox[obj.length]; GridBagConstraints gbc = new GridBagConstraints(); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weightx = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 0; + gbc.weightx = 2; panelSTEP.add(new JLabel("Objective:"), gbc); - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 1; + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 1; panelSTEP.add(new JLabel(""), gbc); - gbc.gridx = 2; - gbc.gridy = 0; - gbc.weightx = 2; + gbc.gridx = 2; + gbc.gridy = 0; + gbc.weightx = 2; panelSTEP.add(new JLabel("Value"), gbc); - gbc.gridx = 3; - gbc.gridy = 0; - gbc.weightx = 1; + gbc.gridx = 3; + gbc.gridy = 0; + gbc.weightx = 1; panelSTEP.add(new JLabel("Satis.?"), gbc); - gbc.gridx = 4; - gbc.gridy = 0; + gbc.gridx = 4; + gbc.gridy = 0; panelSTEP.add(new JLabel("Weight"), gbc); - gbc.gridx = 5; - gbc.gridy = 0; + gbc.gridx = 5; + gbc.gridy = 0; panelSTEP.add(new JLabel("Relax."), gbc); for (int i = 0; i < obj.length; i++) { - gbc.gridx = 0; - gbc.gridy = i+1; - gbc.weightx = 2; - panelSTEP.add(new JLabel(""+obj[i].getIdentName()), gbc); - gbc.gridx = 1; - gbc.gridy = i+1; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = i + 1; + gbc.weightx = 2; + panelSTEP.add(new JLabel("" + obj[i].getIdentName()), gbc); + gbc.gridx = 1; + gbc.gridy = i + 1; + gbc.weightx = 1; if (obj[i].is2BMinimized()) { panelSTEP.add(new JLabel("min"), gbc); - } - else { + } else { panelSTEP.add(new JLabel("max"), gbc); } - gbc.gridx = 2; - gbc.gridy = i+1; - this.m_RefSol[i] = new JTextField(""+((Double)m_RefSolution.getData(obj[i].getIdentName())).doubleValue()); + gbc.gridx = 2; + gbc.gridy = i + 1; + this.m_RefSol[i] = new JTextField("" + ((Double) m_RefSolution.getData(obj[i].getIdentName())).doubleValue()); this.m_RefSol[i].setEditable(false); panelSTEP.add(this.m_RefSol[i], gbc); - gbc.gridx = 3; - gbc.gridy = i+1; + gbc.gridx = 3; + gbc.gridy = i + 1; this.m_Satisfied[i] = new JCheckBox(); this.m_Satisfied[i].addActionListener(satisfiedChanged); panelSTEP.add(this.m_Satisfied[i], gbc); - gbc.gridx = 4; - gbc.gridy = i+1; + gbc.gridx = 4; + gbc.gridy = i + 1; this.m_Weight[i] = new JTextField("1.0"); if (obj[i].getOptimizationMode().contains("Objective")) { this.m_Weight[i].setEditable(true); - } - else { + } else { this.m_Weight[i].setEditable(false); } //this.m_Satisfied[i].addActionListener(valueChanged); panelSTEP.add(this.m_Weight[i], gbc); - gbc.gridx = 5; - gbc.gridy = i+1; + gbc.gridx = 5; + gbc.gridy = i + 1; this.m_Relax[i] = new JTextField("0.0"); this.m_Relax[i].setEditable(false); //this.m_Satisfied[i].addActionListener(valueChanged); panelSTEP.add(this.m_Relax[i], gbc); } - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridwidth = 2; - gbc.gridy = 0; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridwidth = 2; + gbc.gridy = 0; this.m_Choice.add(panelSTEP, gbc); // the optimizer - gbc.gridwidth = 1; - this.m_EOpt = new GeneralGOEProperty(); - this.m_Opt = new GeneticAlgorithm(); + gbc.gridwidth = 1; + this.m_EOpt = new GeneralGOEProperty(); + this.m_Opt = new GeneticAlgorithm(); this.m_Opt.setProblem(this.m_Mocco.m_State.m_CurrentProblem); this.m_Mocco.m_State.m_Optimizer = this.m_Opt; - this.m_EOpt.m_Name = "Island Model EA"; + this.m_EOpt.m_Name = "Island Model EA"; try { - this.m_EOpt.m_Value = this.m_Opt; - this.m_EOpt.m_Editor = PropertyEditorProvider.findEditor(this.m_EOpt.m_Value.getClass()); + this.m_EOpt.m_Value = this.m_Opt; + this.m_EOpt.m_Editor = PropertyEditorProvider.findEditor(this.m_EOpt.m_Value.getClass()); if (this.m_EOpt.m_Editor == null) { this.m_EOpt.m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizer.class); } @@ -194,20 +194,20 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 2; - gbc.weightx = 2; - this.m_Choice.add(new JLabel(""+this.m_EOpt.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 2; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 2; + gbc.weightx = 2; + this.m_Choice.add(new JLabel("" + this.m_EOpt.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 2; + gbc.weightx = 1; this.m_Choice.add(this.m_EOpt.m_View, gbc); // Terminator - GeneralGOEProperty editor = new GeneralGOEProperty(); - editor.m_Name = "Terminator"; + GeneralGOEProperty editor = new GeneralGOEProperty(); + editor.m_Name = "Terminator"; try { - editor.m_Value = this.m_Mocco.m_State.m_Terminator; - editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); + editor.m_Value = this.m_Mocco.m_State.m_Terminator; + editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); if (editor.m_Editor == null) { editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); } @@ -222,19 +222,21 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 3; - gbc.weightx = 2; - this.m_Choice.add(new JLabel(""+editor.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 3; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 3; + gbc.weightx = 2; + this.m_Choice.add(new JLabel("" + editor.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 3; + gbc.weightx = 1; this.m_Choice.add(editor.m_View, gbc); } - /** Method method allows mocco to set the previously selected + /** + * Method method allows mocco to set the previously selected * reference solution - * @param indy the reference solution + * + * @param indy the reference solution */ public void setReferenceSolution(AbstractEAIndividual indy) { this.m_RefSolution = indy; @@ -243,7 +245,7 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces ActionListener satisfiedChanged = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem)m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem) m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); for (int i = 0; i < m_Satisfied.length; i++) { if (obj[i].getOptimizationMode().contains("Objective")) { if (m_Satisfied[i].isSelected()) { @@ -256,7 +258,7 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces } else { m_Relax[i].setEditable(false); m_Weight[i].setEditable(false); - } + } } m_Choice.validate(); } @@ -266,11 +268,11 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces @Override public void actionPerformed(ActionEvent event) { // first fetch the data from the choice and set constraints - InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem)m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem) m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); double[] weights, relax; weights = new double[m_RefSol.length]; - relax = new double[m_RefSol.length]; + relax = new double[m_RefSol.length]; for (int i = 0; i < m_RefSol.length; i++) { weights[i] = new Double(m_Weight[i].getText()).doubleValue(); relax[i] = new Double(m_Relax[i].getText()).doubleValue(); @@ -278,11 +280,11 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces weights[i] = 0; if (obj[i].is2BMinimized()) { // check this sounds wierd => sounds correct if objectives are used above stupid! - relax[i] = ((Double)m_RefSolution.getData(obj[i].getIdentName())).doubleValue() - + Math.abs(relax[i]); + relax[i] = ((Double) m_RefSolution.getData(obj[i].getIdentName())).doubleValue() + + Math.abs(relax[i]); } else { - relax[i] = ((Double)m_RefSolution.getData(obj[i].getIdentName())).doubleValue() - - Math.abs(relax[i]); + relax[i] = ((Double) m_RefSolution.getData(obj[i].getIdentName())).doubleValue() + - Math.abs(relax[i]); } obj[i].SetConstraintGoal(relax[i]); obj[i].SetOptimizationMode("Constraint"); @@ -309,7 +311,7 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces // } // } MOSOWeightedFitness wf = new MOSOWeightedFitness(); - ((AbstractMultiObjectiveOptimizationProblem)m_Mocco.m_State.m_CurrentProblem).setMOSOConverter(wf); + ((AbstractMultiObjectiveOptimizationProblem) m_Mocco.m_State.m_CurrentProblem).setMOSOConverter(wf); double[] setWeights = mapObjectives2Fitness(weights); PropertyDoubleArray da = new PropertyDoubleArray(setWeights); wf.setWeights(da); @@ -323,15 +325,17 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces } }; - /** This method maps a double[] vector of length of the objectives to + /** + * This method maps a double[] vector of length of the objectives to * an double[] vector of length of the fitness values. This is necessary * since previous objectives could have turned into constraints. - * @param d The input vector + * + * @param d The input vector * @return The potentially reduced output vector. */ public double[] mapObjectives2Fitness(double[] d) { ArrayList tmpA = new ArrayList(); - InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Mocco.m_State.m_CurrentProblem).getProblemObjectives(); System.out.println("Calling mapObjectives2Fitness"); System.out.println("obj.length = " + obj.length); System.out.println("d.length = " + d.length); @@ -343,7 +347,7 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces double[] result = new double[tmpA.size()]; for (int i = 0; i < result.length; i++) { - result[i] = ((Double)tmpA.get(i)).doubleValue(); + result[i] = ((Double) tmpA.get(i)).doubleValue(); } return result; } diff --git a/src/eva2/optimization/mocco/MOCCOParameterizeTchebycheff.java b/src/eva2/optimization/mocco/MOCCOParameterizeTchebycheff.java index a4765663..44be9b50 100644 --- a/src/eva2/optimization/mocco/MOCCOParameterizeTchebycheff.java +++ b/src/eva2/optimization/mocco/MOCCOParameterizeTchebycheff.java @@ -12,6 +12,7 @@ import eva2.optimization.strategies.IslandModelEA; import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGOEProperty; import eva2.tools.math.RNG; + import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -33,19 +34,20 @@ import javax.swing.JTextField; */ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements InterfaceProcessElement { - private double[] m_RefPoint; - private IslandModelEA m_Island; - private GeneralGOEProperty m_EIMEA; - private int m_Perturbations = 4; - private JTextField m_NumPer; - JPanel m_Parameters; - private JTextField[] m_UpperLimit, m_LowerLimit; + private double[] m_RefPoint; + private IslandModelEA m_Island; + private GeneralGOEProperty m_EIMEA; + private int m_Perturbations = 4; + private JTextField m_NumPer; + JPanel m_Parameters; + private JTextField[] m_UpperLimit, m_LowerLimit; public MOCCOParameterizeTchebycheff(MOCCOStandalone mocco) { this.m_Mocco = mocco; } - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public void initProcessElementParametrization() { @@ -83,30 +85,30 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac private void installChoice() { this.m_Parameters.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weightx = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 0; + gbc.weightx = 2; this.m_Parameters.add(new JLabel("Choose number of Perturbations k:"), gbc); - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 1; - this.m_NumPer = new JTextField(""+this.m_Perturbations); + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 1; + this.m_NumPer = new JTextField("" + this.m_Perturbations); this.m_Parameters.add(this.m_NumPer, gbc); // weight constraints JComponent tmpP = this.makeLimits4Weigths(); tmpP.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Choose Weight Bounds (0,1)"), - BorderFactory.createEmptyBorder(0, 5, 5, 5))); - gbc.gridx = 0; - gbc.gridwidth = 2; - gbc.gridy = 1; - gbc.weightx = 2; + BorderFactory.createTitledBorder("Choose Weight Bounds (0,1)"), + BorderFactory.createEmptyBorder(0, 5, 5, 5))); + gbc.gridx = 0; + gbc.gridwidth = 2; + gbc.gridy = 1; + gbc.weightx = 2; this.m_Parameters.add(tmpP, gbc); // IslandModelEA - this.m_EIMEA = new GeneralGOEProperty(); - this.m_Island = new IslandModelEA(); + this.m_EIMEA = new GeneralGOEProperty(); + this.m_Island = new IslandModelEA(); this.m_Island.setHeterogenuousProblems(true); this.m_Island.setLocalOnly(true); this.m_Island.setMigrationRate(2); @@ -114,10 +116,10 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac this.m_Island.setNumberLocalCPUs(this.m_Perturbations); this.m_Island.setProblem(this.m_Mocco.m_State.m_CurrentProblem); this.m_Mocco.m_State.m_Optimizer = this.m_Island; - this.m_EIMEA.m_Name = "Island Model EA"; + this.m_EIMEA.m_Name = "Island Model EA"; try { - this.m_EIMEA.m_Value = this.m_Island; - this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(this.m_EIMEA.m_Value.getClass()); + this.m_EIMEA.m_Value = this.m_Island; + this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(this.m_EIMEA.m_Value.getClass()); if (this.m_EIMEA.m_Editor == null) { this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(IslandModelEA.class); } @@ -132,20 +134,20 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 2; - gbc.weightx = 2; - this.m_Parameters.add(new JLabel(""+this.m_EIMEA.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 2; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 2; + gbc.weightx = 2; + this.m_Parameters.add(new JLabel("" + this.m_EIMEA.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 2; + gbc.weightx = 1; this.m_Parameters.add(this.m_EIMEA.m_View, gbc); // Terminator - GeneralGOEProperty editor = new GeneralGOEProperty(); - editor.m_Name = "Terminator"; + GeneralGOEProperty editor = new GeneralGOEProperty(); + editor.m_Name = "Terminator"; try { - editor.m_Value = this.m_Mocco.m_State.m_Terminator; - editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); + editor.m_Value = this.m_Mocco.m_State.m_Terminator; + editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); if (editor.m_Editor == null) { editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); } @@ -160,55 +162,55 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac } catch (Exception e) { System.out.println("Darn can't read the value..."); } - gbc.gridx = 0; - gbc.gridy = 3; - gbc.weightx = 2; - this.m_Parameters.add(new JLabel(""+editor.m_Name), gbc); - gbc.gridx = 1; - gbc.gridy = 3; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = 3; + gbc.weightx = 2; + this.m_Parameters.add(new JLabel("" + editor.m_Name), gbc); + gbc.gridx = 1; + gbc.gridy = 3; + gbc.weightx = 1; this.m_Parameters.add(editor.m_View, gbc); } private JComponent makeLimits4Weigths() { JPanel result = new JPanel(); result.setLayout(new GridBagLayout()); - this.m_UpperLimit = new JTextField[this.m_RefPoint.length]; - this.m_LowerLimit = new JTextField[this.m_RefPoint.length]; + this.m_UpperLimit = new JTextField[this.m_RefPoint.length]; + this.m_LowerLimit = new JTextField[this.m_RefPoint.length]; GridBagConstraints gbc = new GridBagConstraints(); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 0; + gbc.weightx = 1; result.add(new JLabel("Objective"), gbc); - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 2; + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 2; result.add(new JLabel("Ideal Value"), gbc); - gbc.gridx = 2; - gbc.gridy = 0; - gbc.weightx = 1; + gbc.gridx = 2; + gbc.gridy = 0; + gbc.weightx = 1; result.add(new JLabel("Lower"), gbc); - gbc.gridx = 3; - gbc.gridy = 0; + gbc.gridx = 3; + gbc.gridy = 0; result.add(new JLabel("Upper"), gbc); for (int i = 0; i < this.m_RefPoint.length; i++) { - gbc.gridx = 0; - gbc.gridy = i+1; - gbc.weightx = 1; - result.add(new JLabel("Fitness "+i), gbc); - gbc.gridx = 1; - gbc.gridy = i+1; - gbc.weightx = 2; - result.add(new JLabel(""+this.m_RefPoint[i]), gbc); - gbc.gridx = 2; - gbc.gridy = i+1; - gbc.weightx = 1; + gbc.gridx = 0; + gbc.gridy = i + 1; + gbc.weightx = 1; + result.add(new JLabel("Fitness " + i), gbc); + gbc.gridx = 1; + gbc.gridy = i + 1; + gbc.weightx = 2; + result.add(new JLabel("" + this.m_RefPoint[i]), gbc); + gbc.gridx = 2; + gbc.gridy = i + 1; + gbc.weightx = 1; this.m_LowerLimit[i] = new JTextField("0.0"); result.add(this.m_LowerLimit[i], gbc); - gbc.gridx = 3; - gbc.gridy = i+1; + gbc.gridx = 3; + gbc.gridy = i + 1; this.m_UpperLimit[i] = new JTextField("1.0"); result.add(this.m_UpperLimit[i], gbc); @@ -216,9 +218,11 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac return result; } - /** Method method allows mocco to set the previously selected + /** + * Method method allows mocco to set the previously selected * reference point - * @param point the reference point + * + * @param point the reference point */ public void setReferencePoint(double[] point) { this.m_RefPoint = point; @@ -234,7 +238,7 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac System.out.println("Can't read k."); } if (m_EIMEA.m_Value instanceof IslandModelEA) { - m_Island = (IslandModelEA)m_EIMEA.m_Value; + m_Island = (IslandModelEA) m_EIMEA.m_Value; } else { System.out.println("The selected optimizer does not allow heterogenuous multi-starts!"); } @@ -253,8 +257,8 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac m_Mocco.m_State.m_Optimizer = m_Island; m_Mocco.m_State.m_Optimizer.setProblem(m_Mocco.m_State.m_CurrentProblem); m_Island.init(); - double[] tmpD; - double sum = 0, l = 0, u = 1; + double[] tmpD; + double sum = 0, l = 0, u = 1; MOSOWeightedLPTchebycheff[] tmpLPs = new MOSOWeightedLPTchebycheff[m_Perturbations]; for (int i = 0; i < m_Perturbations; i++) { tmpD = new double[m_RefPoint.length]; @@ -262,10 +266,12 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac for (int j = 0; j < tmpD.length; j++) { try { l = new Double(m_LowerLimit[j].getText()).doubleValue(); - } catch (NumberFormatException e) {} + } catch (NumberFormatException e) { + } try { u = new Double(m_UpperLimit[j].getText()).doubleValue(); - } catch (NumberFormatException e) {} + } catch (NumberFormatException e) { + } if (l < 0) { l = 0; } @@ -280,13 +286,13 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac } if (u < l) { double t = u; - u = l; l = t; + u = l; + l = t; } if (i > 0) { - tmpD[j] = RNG.randomDouble(l,u); - } - else { + tmpD[j] = RNG.randomDouble(l, u); + } else { tmpD[j] = 1; } sum += tmpD[j]; @@ -298,10 +304,10 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac // I've to set this before I change the parameters, because the problem sets the // output dimension based on the AbstractMultiObjectiveOptimizationProblem and // that one has not the faintest idea about the true output dimension - ((AbstractMultiObjectiveOptimizationProblem)m_Island.getOptimizers()[i].getProblem()).setMOSOConverter(tmpLPs[i]); + ((AbstractMultiObjectiveOptimizationProblem) m_Island.getOptimizers()[i].getProblem()).setMOSOConverter(tmpLPs[i]); tmpLPs[i].setOutputDimension(tmpD.length); - tmpLPs[i].getIdealPWeights().m_IdealValue = m_RefPoint; - tmpLPs[i].getIdealPWeights().m_Weights = tmpD; + tmpLPs[i].getIdealPWeights().m_IdealValue = m_RefPoint; + tmpLPs[i].getIdealPWeights().m_Weights = tmpD; } m_Mocco.m_View.removeReferencePoint(); m_Mocco.m_JPanelControl.removeAll(); diff --git a/src/eva2/optimization/mocco/MOCCOPhase.java b/src/eva2/optimization/mocco/MOCCOPhase.java index c3e6489f..893c1ae5 100644 --- a/src/eva2/optimization/mocco/MOCCOPhase.java +++ b/src/eva2/optimization/mocco/MOCCOPhase.java @@ -1,6 +1,7 @@ package eva2.optimization.mocco; import eva2.optimization.go.MOCCOStandalone; + import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; @@ -19,15 +20,18 @@ import javax.swing.JTextArea; */ public abstract class MOCCOPhase implements InterfaceProcessElement { - public MOCCOStandalone m_Mocco; - public volatile boolean m_Finished = false; + public MOCCOStandalone m_Mocco; + public volatile boolean m_Finished = false; - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public abstract void initProcessElementParametrization(); - /** This method will wait for the parametrisation result + /** + * This method will wait for the parametrisation result + * * @return boolean Result */ @Override @@ -35,8 +39,8 @@ public abstract class MOCCOPhase implements InterfaceProcessElement { return this.m_Finished; } - /** Save the stuff to *.ser file for offline optimization - * + /** + * Save the stuff to *.ser file for offline optimization */ ActionListener saveState2FileForOfflineOptimization = new ActionListener() { @Override @@ -45,33 +49,37 @@ public abstract class MOCCOPhase implements InterfaceProcessElement { } }; - /** This method makes a helptext element similar to that used in EvA - * @param help The text to display + /** + * This method makes a helptext element similar to that used in EvA + * + * @param help The text to display * @return the helptext component */ public JComponent makeHelpText(String help) { return this.makeInformationText("Info", help); } - /** This method makes a helptext element similar to that used in EvA - * @param title The title of the help text + /** + * This method makes a helptext element similar to that used in EvA + * + * @param title The title of the help text * @param help The text to display - * @return the helptext component + * @return the helptext component */ public JComponent makeInformationText(String title, String help) { - JPanel result = new JPanel(); - JTextArea jt = new JTextArea(); - jt.setFont(new Font("SansSerif", Font.PLAIN,12)); - jt.setEditable(false); - jt.setLineWrap(true); - jt.setWrapStyleWord(true); - jt.setText(help); + JPanel result = new JPanel(); + JTextArea jt = new JTextArea(); + jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); + jt.setEditable(false); + jt.setLineWrap(true); + jt.setWrapStyleWord(true); + jt.setText(help); jt.setBackground(result.getBackground()); - result.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder(title), - BorderFactory.createEmptyBorder(0, 5, 5, 5))); - result.setLayout(new BorderLayout()); - result.add(jt, BorderLayout.CENTER); + result.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createTitledBorder(title), + BorderFactory.createEmptyBorder(0, 5, 5, 5))); + result.setLayout(new BorderLayout()); + result.add(jt, BorderLayout.CENTER); return result; } } diff --git a/src/eva2/optimization/mocco/MOCCOProblemInitialization.java b/src/eva2/optimization/mocco/MOCCOProblemInitialization.java index 51013979..3d807d49 100644 --- a/src/eva2/optimization/mocco/MOCCOProblemInitialization.java +++ b/src/eva2/optimization/mocco/MOCCOProblemInitialization.java @@ -4,6 +4,7 @@ import eva2.gui.JParaPanel; import eva2.optimization.go.MOCCOStandalone; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.ReflectPackage; + import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -20,13 +21,14 @@ import javax.swing.*; */ public class MOCCOProblemInitialization extends MOCCOPhase implements InterfaceProcessElement { - private JComboBox m_ProblemChooser; + private JComboBox m_ProblemChooser; public MOCCOProblemInitialization(MOCCOStandalone mocco) { this.m_Mocco = mocco; } - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public void initProcessElementParametrization() { @@ -47,32 +49,32 @@ public class MOCCOProblemInitialization extends MOCCOPhase implements InterfaceP private void initProblemDefinition() { this.m_Mocco.m_JPanelParameters.removeAll(); - this.m_ProblemChooser = new JComboBox(); - JComponent tmpC = new JPanel(); + this.m_ProblemChooser = new JComboBox(); + JComponent tmpC = new JPanel(); tmpC.setLayout(new BorderLayout()); - + Class[] altern = null; - try { - altern = ReflectPackage.getAssignableClassesInPackage("eva2.optimization.problems", Class.forName("eva2.optimization.problems.InterfaceMultiObjectiveDeNovoProblem"), true, true); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } + try { + altern = ReflectPackage.getAssignableClassesInPackage("eva2.optimization.problems", Class.forName("eva2.optimization.problems.InterfaceMultiObjectiveDeNovoProblem"), true, true); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } this.m_ProblemChooser.setModel(new DefaultComboBoxModel(altern)); - + String objectName = (this.m_Mocco.m_State.m_OriginalProblem.getClass().getName()); this.m_ProblemChooser.getModel().setSelectedItem(objectName); this.m_ProblemChooser.addActionListener(problemChanged); JPanel tmpP = new JPanel(); tmpP.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.gridx = 0; - gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.gridx = 0; + gbc.gridy = 0; tmpP.add(this.makeHelpText("Choose and parameterize the optimization problem to solve by means of MOCCO. " + "Please note that it is not necessary to include MOSO converters yet and that only problems complying " + - "with the InterfaceMultiObjectiveDeNovoProblem can be optimized using the MOCCO approach."),gbc); - gbc.gridx = 0; - gbc.gridy = 1; + "with the InterfaceMultiObjectiveDeNovoProblem can be optimized using the MOCCO approach."), gbc); + gbc.gridx = 0; + gbc.gridy = 1; tmpP.add(this.m_ProblemChooser, gbc); this.m_Mocco.m_JPanelParameters.setLayout(new BorderLayout()); this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH); @@ -93,11 +95,11 @@ public class MOCCOProblemInitialization extends MOCCOPhase implements InterfaceP ActionListener problemChanged = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - String className = (String)m_ProblemChooser.getSelectedItem(); + String className = (String) m_ProblemChooser.getSelectedItem(); m_Mocco.m_JPanelParameters.removeAll(); Object n = null; try { - n = (Object)Class.forName(className).newInstance(); + n = (Object) Class.forName(className).newInstance(); } catch (Exception ex) { } m_Mocco.m_State.m_OriginalProblem = (InterfaceOptimizationProblem) n; diff --git a/src/eva2/optimization/mocco/MOCCOProblemRedefinition.java b/src/eva2/optimization/mocco/MOCCOProblemRedefinition.java index 375254ea..4d52248a 100644 --- a/src/eva2/optimization/mocco/MOCCOProblemRedefinition.java +++ b/src/eva2/optimization/mocco/MOCCOProblemRedefinition.java @@ -4,6 +4,7 @@ package eva2.optimization.mocco; import eva2.gui.JParaPanel; import eva2.optimization.go.MOCCOStandalone; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -22,10 +23,11 @@ public class MOCCOProblemRedefinition extends MOCCOPhase implements InterfacePro public MOCCOProblemRedefinition(MOCCOStandalone mocco) { this.m_Mocco = mocco; - this.m_Problem = (InterfaceOptimizationProblem)this.m_Mocco.m_State.m_CurrentProblem.clone(); + this.m_Problem = (InterfaceOptimizationProblem) this.m_Mocco.m_State.m_CurrentProblem.clone(); } - /** This method will call the init method and will go to stall + /** + * This method will call the init method and will go to stall */ @Override public void initProcessElementParametrization() { @@ -39,23 +41,23 @@ public class MOCCOProblemRedefinition extends MOCCOPhase implements InterfacePro // the parameter panel this.m_Mocco.m_JPanelParameters.removeAll(); - JComponent tmpC = new JPanel(); + JComponent tmpC = new JPanel(); tmpC.setLayout(new BorderLayout()); JPanel tmpP = new JPanel(); tmpP.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.weightx = 100; - gbc.gridx = 0; - gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.weightx = 100; + gbc.gridx = 0; + gbc.gridy = 0; tmpP.add(this.makeHelpText("Choose and parameterize the optimization problem to solve by means of MOCCO. " + "Please note that here you got the opportunity to reduce the problem dimension by means of" + " weight aggregation, contraints or even by removing secondary objectives completely. Whenever" + " possbile make use of this chance. This not only reduces the complexity of the optimization " + "problem by also reduces the complecity of the decision process, when it comes to select from " + "the solution alternatives."), gbc); - gbc.gridx = 0; - gbc.gridy = 1; + gbc.gridx = 0; + gbc.gridy = 1; tmpB = new JButton("Reevaluate Problem"); tmpB.addActionListener(reevaluate); tmpP.add(tmpB, gbc); @@ -73,7 +75,7 @@ public class MOCCOProblemRedefinition extends MOCCOPhase implements InterfacePro ActionListener continue2 = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_Mocco.m_State.m_CurrentProblem = (InterfaceOptimizationProblem)m_Problem.clone(); + m_Mocco.m_State.m_CurrentProblem = (InterfaceOptimizationProblem) m_Problem.clone(); m_Mocco.m_JPanelParameters.removeAll(); m_Mocco.m_JPanelControl.removeAll(); m_Mocco.m_JPanelControl.validate(); @@ -83,7 +85,7 @@ public class MOCCOProblemRedefinition extends MOCCOPhase implements InterfacePro ActionListener reevaluate = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_Mocco.m_State.m_CurrentProblem = (InterfaceOptimizationProblem)m_Problem.clone(); + m_Mocco.m_State.m_CurrentProblem = (InterfaceOptimizationProblem) m_Problem.clone(); m_Mocco.m_State.m_CurrentProblem = m_Problem; m_Mocco.m_State.makeFitnessCache(true); m_Mocco.m_View.problemChanged(true); diff --git a/src/eva2/optimization/mocco/MOCCOState.java b/src/eva2/optimization/mocco/MOCCOState.java index 65c38641..f32d1995 100644 --- a/src/eva2/optimization/mocco/MOCCOState.java +++ b/src/eva2/optimization/mocco/MOCCOState.java @@ -11,6 +11,7 @@ import eva2.optimization.problems.InterfaceOptimizationObjective; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.MultiObjectiveEA; + import java.awt.Color; import java.util.ArrayList; @@ -23,24 +24,24 @@ import java.util.ArrayList; */ public class MOCCOState { - public transient boolean isVisible = false; - public InterfaceOptimizer m_Optimizer = new MultiObjectiveEA(); - public InterfaceOptimizer m_BackupOptimizer; - public InterfaceTerminator m_Terminator = new EvaluationTerminator(); - public InterfaceOptimizationProblem m_OriginalProblem = null; - public InterfaceOptimizationProblem m_CurrentProblem; - public InterfaceOptimizationProblem m_BackupProblem; - public int m_InitialPopulationSize = 50; + public transient boolean isVisible = false; + public InterfaceOptimizer m_Optimizer = new MultiObjectiveEA(); + public InterfaceOptimizer m_BackupOptimizer; + public InterfaceTerminator m_Terminator = new EvaluationTerminator(); + public InterfaceOptimizationProblem m_OriginalProblem = null; + public InterfaceOptimizationProblem m_CurrentProblem; + public InterfaceOptimizationProblem m_BackupProblem; + public int m_InitialPopulationSize = 50; // the population history - public Population m_ParetoFront; - public Population[] m_PopulationHistory = new Population[0]; - public boolean[] m_Show; - public boolean[] m_Use; - public Color[] m_Color; + public Population m_ParetoFront; + public Population[] m_PopulationHistory = new Population[0]; + public boolean[] m_Show; + public boolean[] m_Use; + public Color[] m_Color; // the fitness cache for fast plotting - public ArrayList m_FitnessCache = new ArrayList(); - public ArrayList m_ObjectiveCache = new ArrayList(); - public ArrayList m_ConstraintCache = new ArrayList(); + public ArrayList m_FitnessCache = new ArrayList(); + public ArrayList m_ObjectiveCache = new ArrayList(); + public ArrayList m_ConstraintCache = new ArrayList(); public MOCCOState() { } @@ -61,13 +62,13 @@ public class MOCCOState { } public void makeBackup() { - this.m_BackupProblem = (InterfaceOptimizationProblem)this.m_CurrentProblem.clone(); - this.m_BackupOptimizer = (InterfaceOptimizer)this.m_Optimizer.clone(); + this.m_BackupProblem = (InterfaceOptimizationProblem) this.m_CurrentProblem.clone(); + this.m_BackupOptimizer = (InterfaceOptimizer) this.m_Optimizer.clone(); this.m_BackupOptimizer.setProblem(null); } public void addPopulation2History(Population pop) { - InterfaceOptimizationObjective[] tmpObj = null; + InterfaceOptimizationObjective[] tmpObj = null; if (this.m_Show == null) { this.m_Use = new boolean[1]; @@ -77,46 +78,46 @@ public class MOCCOState { this.m_Color = new Color[1]; this.m_Color[0] = this.getColor4Index(0); } else { - boolean[] newUse = new boolean[this.m_Show.length +1]; - boolean[] newShow = new boolean[this.m_Show.length +1]; - Color[] newColor = new Color[this.m_Show.length +1]; + boolean[] newUse = new boolean[this.m_Show.length + 1]; + boolean[] newShow = new boolean[this.m_Show.length + 1]; + Color[] newColor = new Color[this.m_Show.length + 1]; for (int i = 0; i < this.m_Show.length; i++) { - newUse[i] = this.m_Use[i]; - newShow[i] = this.m_Show[i]; + newUse[i] = this.m_Use[i]; + newShow[i] = this.m_Show[i]; newColor[i] = this.m_Color[i]; } - newUse[m_Show.length] = true; - newShow[m_Show.length] = true; + newUse[m_Show.length] = true; + newShow[m_Show.length] = true; newColor[m_Show.length] = this.getColor4Index(this.m_PopulationHistory.length); - this.m_Use = newUse; - this.m_Show = newShow; - this.m_Color = newColor; + this.m_Use = newUse; + this.m_Show = newShow; + this.m_Color = newColor; } - Population[] newPop = new Population[this.m_PopulationHistory.length +1]; + Population[] newPop = new Population[this.m_PopulationHistory.length + 1]; for (int i = 0; i < this.m_PopulationHistory.length; i++) { - newPop[i] = this.m_PopulationHistory[i]; + newPop[i] = this.m_PopulationHistory[i]; } - newPop[newPop.length-1] = (Population)pop.clone(); - newPop[newPop.length-1].addPopulation(newPop[newPop.length-1].getArchive()); - newPop[newPop.length-1].SetArchive(null); - this.m_PopulationHistory = newPop; + newPop[newPop.length - 1] = (Population) pop.clone(); + newPop[newPop.length - 1].addPopulation(newPop[newPop.length - 1].getArchive()); + newPop[newPop.length - 1].SetArchive(null); + this.m_PopulationHistory = newPop; ArrayList fitness = new ArrayList(); ArrayList objectives = new ArrayList(); ArrayList constraint = new ArrayList(); if (this.m_CurrentProblem instanceof InterfaceMultiObjectiveDeNovoProblem) { - tmpObj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_CurrentProblem).getProblemObjectives(); + tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_CurrentProblem).getProblemObjectives(); } - for (int j = 0; j < newPop[newPop.length-1].size(); j++) { + for (int j = 0; j < newPop[newPop.length - 1].size(); j++) { if (tmpObj != null) { double[] tmoF = new double[tmpObj.length]; for (int k = 0; k < tmpObj.length; k++) { - tmoF[k] = ((Double)((AbstractEAIndividual)newPop[newPop.length-1].get(j)).getData(tmpObj[k].getIdentName())).doubleValue(); + tmoF[k] = ((Double) ((AbstractEAIndividual) newPop[newPop.length - 1].get(j)).getData(tmpObj[k].getIdentName())).doubleValue(); } objectives.add(tmoF); } - fitness.add(((AbstractEAIndividual)newPop[newPop.length-1].get(j)).getFitness()); - constraint.add(new Double(((AbstractEAIndividual)newPop[newPop.length-1].get(j)).getConstraintViolation())); + fitness.add(((AbstractEAIndividual) newPop[newPop.length - 1].get(j)).getFitness()); + constraint.add(new Double(((AbstractEAIndividual) newPop[newPop.length - 1].get(j)).getConstraintViolation())); } if (this.m_ObjectiveCache != null) { this.m_ObjectiveCache.add(objectives); @@ -125,18 +126,26 @@ public class MOCCOState { this.m_ConstraintCache.add(constraint); } - /** Simple method to choose a color - * @param i The index to choose a color for + /** + * Simple method to choose a color + * + * @param i The index to choose a color for * @return A nice color... */ public Color getColor4Index(int i) { - switch (i%6) { - case 0: return Color.RED; - case 1: return Color.BLUE; - case 2: return Color.GREEN; - case 3: return Color.CYAN; - case 4: return Color.MAGENTA; - case 5: return Color.ORANGE; + switch (i % 6) { + case 0: + return Color.RED; + case 1: + return Color.BLUE; + case 2: + return Color.GREEN; + case 3: + return Color.CYAN; + case 4: + return Color.MAGENTA; + case 5: + return Color.ORANGE; } return Color.RED; } @@ -149,7 +158,9 @@ public class MOCCOState { this.makeFitnessCache(false); } - /** This method return the currently selected populations + /** + * This method return the currently selected populations + * * @return the selected populations */ public Population getSelectedPopulations() { @@ -163,8 +174,10 @@ public class MOCCOState { return result; } - /** This method establishes a fitness cache to give the plot methods + /** + * This method establishes a fitness cache to give the plot methods * easier and faster access to the data + * * @param reevaluate */ public void makeFitnessCache(boolean reevaluate) { @@ -184,17 +197,17 @@ public class MOCCOState { } this.m_CurrentProblem.evaluate(pop); } - this.m_FitnessCache = new ArrayList(); - this.m_ObjectiveCache = null; - this.m_ConstraintCache = new ArrayList(); + this.m_FitnessCache = new ArrayList(); + this.m_ObjectiveCache = null; + this.m_ConstraintCache = new ArrayList(); if (this.m_CurrentProblem instanceof InterfaceMultiObjectiveDeNovoProblem) { - this.m_ObjectiveCache = new ArrayList(); - tmpObj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_CurrentProblem).getProblemObjectives(); + this.m_ObjectiveCache = new ArrayList(); + tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_CurrentProblem).getProblemObjectives(); } this.m_ParetoFront = new Population(); for (int i = 0; i < this.m_PopulationHistory.length; i++) { if (reevaluate) { - ((AbstractMultiObjectiveOptimizationProblem)this.m_CurrentProblem).resetParetoFront(); + ((AbstractMultiObjectiveOptimizationProblem) this.m_CurrentProblem).resetParetoFront(); this.m_CurrentProblem.evaluate(this.m_PopulationHistory[i]); } this.m_ParetoFront.addPopulation(this.m_PopulationHistory[i]); @@ -206,20 +219,20 @@ public class MOCCOState { double[] tmoF = new double[tmpObj.length]; for (int k = 0; k < tmpObj.length; k++) { if (this.m_PopulationHistory[i].get(j) == null) { - System.out.println("Individual "+i+" == null!"); + System.out.println("Individual " + i + " == null!"); } if (tmpObj[k] == null) { - System.out.println("Objective "+k+" == null!"); + System.out.println("Objective " + k + " == null!"); } - if (((AbstractEAIndividual)this.m_PopulationHistory[i].get(j)).getData(tmpObj[k].getIdentName()) == null) { - System.out.println("User Data "+k+" "+tmpObj[k].getIdentName()+" == null!"); + if (((AbstractEAIndividual) this.m_PopulationHistory[i].get(j)).getData(tmpObj[k].getIdentName()) == null) { + System.out.println("User Data " + k + " " + tmpObj[k].getIdentName() + " == null!"); } - tmoF[k] = ((Double)((AbstractEAIndividual)this.m_PopulationHistory[i].get(j)).getData(tmpObj[k].getIdentName())).doubleValue(); + tmoF[k] = ((Double) ((AbstractEAIndividual) this.m_PopulationHistory[i].get(j)).getData(tmpObj[k].getIdentName())).doubleValue(); } objectives.add(tmoF); } - fitness.add(((AbstractEAIndividual)this.m_PopulationHistory[i].get(j)).getFitness()); - constraint.add(new Double(((AbstractEAIndividual)this.m_PopulationHistory[i].get(j)).getConstraintViolation())); + fitness.add(((AbstractEAIndividual) this.m_PopulationHistory[i].get(j)).getFitness()); + constraint.add(new Double(((AbstractEAIndividual) this.m_PopulationHistory[i].get(j)).getConstraintViolation())); } if (this.m_ObjectiveCache != null) { this.m_ObjectiveCache.add(objectives); diff --git a/src/eva2/optimization/mocco/paretofrontviewer/InterfaceParetoFrontView.java b/src/eva2/optimization/mocco/paretofrontviewer/InterfaceParetoFrontView.java index 36ef7252..648d86bf 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/InterfaceParetoFrontView.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/InterfaceParetoFrontView.java @@ -9,7 +9,8 @@ package eva2.optimization.mocco.paretofrontviewer; */ public interface InterfaceParetoFrontView { - /** This method notifies the Pareto front view that + /** + * This method notifies the Pareto front view that * the data has changed most likely due to changes in * the problem definition */ diff --git a/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefPointListener.java b/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefPointListener.java index f477164f..a5a9c784 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefPointListener.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefPointListener.java @@ -9,8 +9,10 @@ package eva2.optimization.mocco.paretofrontviewer; */ public interface InterfaceRefPointListener { - /** This method will notify the listener that a point has been selected - * @param point The selected point, most likely 2d + /** + * This method will notify the listener that a point has been selected + * + * @param point The selected point, most likely 2d */ - public void refPointGiven(double[] point); + public void refPointGiven(double[] point); } diff --git a/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefSolutionListener.java b/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefSolutionListener.java index 9a13f84e..e1b78c8f 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefSolutionListener.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/InterfaceRefSolutionListener.java @@ -11,9 +11,11 @@ import eva2.optimization.individuals.AbstractEAIndividual; */ public interface InterfaceRefSolutionListener { - /** This method will notify the listener that an + /** + * This method will notify the listener that an * Individual has been selected - * @param indy The selected individual + * + * @param indy The selected individual */ public void individualSelected(AbstractEAIndividual indy); } diff --git a/src/eva2/optimization/mocco/paretofrontviewer/MOCCOViewer.java b/src/eva2/optimization/mocco/paretofrontviewer/MOCCOViewer.java index e5f91611..b9a652c7 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/MOCCOViewer.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/MOCCOViewer.java @@ -13,6 +13,7 @@ import eva2.tools.chart2d.Chart2DDPointContentSelectable; import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.ScaledBorder; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -34,44 +35,44 @@ import javax.swing.*; */ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, InterfaceRefPointListener { - public MOCCOStandalone m_MOCCO; - public MOCCOViewer m_self; - private InterfaceParetoFrontView m_View; - private FunctionArea m_1DView; - public JSplitPane m_JSplit; - public JPanel m_ViewPanel, m_Choices; - private InterfaceRefSolutionListener m_RefSolutionListener; - private InterfaceRefPointListener m_RefPointListener; - public double[] m_ReferencePoint = null; - public boolean m_SelectUniqueSolution = true; - public boolean m_RefPointSelectable = false; - public boolean m_RefSolutionSelectable = false; + public MOCCOStandalone m_MOCCO; + public MOCCOViewer m_self; + private InterfaceParetoFrontView m_View; + private FunctionArea m_1DView; + public JSplitPane m_JSplit; + public JPanel m_ViewPanel, m_Choices; + private InterfaceRefSolutionListener m_RefSolutionListener; + private InterfaceRefPointListener m_RefPointListener; + public double[] m_ReferencePoint = null; + public boolean m_SelectUniqueSolution = true; + public boolean m_RefPointSelectable = false; + public boolean m_RefSolutionSelectable = false; public MOCCOViewer(MOCCOStandalone t) { - this.m_MOCCO = t; - this.m_self = this; + this.m_MOCCO = t; + this.m_self = this; this.init(); } public void init() { this.setLayout(new BorderLayout()); // the view - this.m_ViewPanel = new JPanel(); + this.m_ViewPanel = new JPanel(); this.m_ViewPanel.setLayout(new BorderLayout()); - this.m_View = new ParetoFrontView2D(this); - this.m_ViewPanel.add((JPanel)this.m_View, BorderLayout.CENTER); + this.m_View = new ParetoFrontView2D(this); + this.m_ViewPanel.add((JPanel) this.m_View, BorderLayout.CENTER); // the parameters this.m_Choices = new JPanel(); JPanel tmpP = new JPanel(); - this.m_Choices.setLayout(new GridLayout(1,2)); + this.m_Choices.setLayout(new GridLayout(1, 2)); this.m_Choices.add(tmpP); tmpP.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 0; + gbc.weightx = 1; tmpP.add(new JLabel("Choose View:"), gbc); String[] tmpList = new String[2]; tmpList[0] = "2D Pareto Front"; @@ -81,11 +82,11 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, JComboBox tmpC = new JComboBox(tmpList); tmpC.setSelectedIndex(0); tmpC.addActionListener(paretoFrontViewChanged); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.gridy = 0; - gbc.weightx = 3; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 3; tmpP.add(tmpC, gbc); JButton JBSaveParetoFront = new JButton("Save Pareto Front"); JBSaveParetoFront.addActionListener(this.saveParetoFront); @@ -156,34 +157,34 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, ActionListener paretoFrontViewChanged = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - JComboBox tmpC = (JComboBox)event.getSource(); + JComboBox tmpC = (JComboBox) event.getSource(); int index = tmpC.getSelectedIndex(); switch (index) { case 0: { m_ViewPanel.removeAll(); m_View = new ParetoFrontView2D(m_self); - m_ViewPanel.add((JPanel)m_View, BorderLayout.CENTER); + m_ViewPanel.add((JPanel) m_View, BorderLayout.CENTER); //problemChanged(false); break; } case 1: { m_ViewPanel.removeAll(); m_View = new ParetoFrontViewScatterPlot(m_self); - m_ViewPanel.add((JPanel)m_View, BorderLayout.CENTER); + m_ViewPanel.add((JPanel) m_View, BorderLayout.CENTER); //problemChanged(false); break; } case 2: { m_ViewPanel.removeAll(); m_View = new ParetoFrontViewParallelAxsis(m_self); - m_ViewPanel.add((JPanel)m_View, BorderLayout.CENTER); + m_ViewPanel.add((JPanel) m_View, BorderLayout.CENTER); //problemChanged(false); break; } case 3: { m_ViewPanel.removeAll(); - m_View = ((InterfaceMultiObjectiveDeNovoProblem)m_MOCCO.m_State.m_CurrentProblem).getParetoFrontViewer4MOCCO(m_self); - m_ViewPanel.add((JComponent)m_View, BorderLayout.CENTER); + m_View = ((InterfaceMultiObjectiveDeNovoProblem) m_MOCCO.m_State.m_CurrentProblem).getParetoFrontViewer4MOCCO(m_self); + m_ViewPanel.add((JComponent) m_View, BorderLayout.CENTER); //problemChanged(false); break; } @@ -197,39 +198,48 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, public void actionPerformed(ActionEvent event) { SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_'HH.mm.ss"); String m_StartDate = formatter.format(new Date()); - BufferedWriter out = null; - Population pop; + BufferedWriter out = null; + Population pop; - String name = "MOCCO_"+m_StartDate+"_PF_Iteration_"+m_MOCCO.m_Iteration+".dat", tmp; + String name = "MOCCO_" + m_StartDate + "_PF_Iteration_" + m_MOCCO.m_Iteration + ".dat", tmp; pop = m_MOCCO.m_State.m_ParetoFront; try { - out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (name))); + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: " + name); return; } - InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem)m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] obj = ((InterfaceMultiObjectiveDeNovoProblem) m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); tmp = ""; for (int j = 0; j < obj.length; j++) { - tmp += obj[j].getIdentName() +"\t"; + tmp += obj[j].getIdentName() + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } for (int i = 0; i < pop.size(); i++) { - if (!((AbstractEAIndividual)pop.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) pop.get(i)).violatesConstraint()) { // write - tmp =""; - double[] fit = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmp = ""; + double[] fit = ((AbstractEAIndividual) pop.get(i)).getFitness(); for (int j = 0; j < fit.length; j++) { - tmp += fit[j] +"\t"; + tmp += fit[j] + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } } } - try { out.close(); } catch(java.io.IOException e) {} - - name = "MOCCO_"+m_StartDate+"_All_Iteration_"+m_MOCCO.m_Iteration+".dat"; try { - out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (name))); + out.close(); + } catch (java.io.IOException e) { + } + + name = "MOCCO_" + m_StartDate + "_All_Iteration_" + m_MOCCO.m_Iteration + ".dat"; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: " + name); return; @@ -238,28 +248,37 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, for (int i = 0; i < m_MOCCO.m_State.m_PopulationHistory.length; i++) { pop.addPopulation(m_MOCCO.m_State.m_PopulationHistory[i]); } - obj = ((InterfaceMultiObjectiveDeNovoProblem)m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + obj = ((InterfaceMultiObjectiveDeNovoProblem) m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); tmp = ""; for (int j = 0; j < obj.length; j++) { - tmp += obj[j].getIdentName() +"\t"; + tmp += obj[j].getIdentName() + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } for (int i = 0; i < pop.size(); i++) { - if (!((AbstractEAIndividual)pop.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) pop.get(i)).violatesConstraint()) { // write - tmp =""; - double[] fit = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmp = ""; + double[] fit = ((AbstractEAIndividual) pop.get(i)).getFitness(); for (int j = 0; j < fit.length; j++) { - tmp += fit[j] +"\t"; + tmp += fit[j] + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } } } - try { out.close(); } catch(java.io.IOException e) {} - - name = "MOCCO_"+m_StartDate+"_Infeasible_Iteration_"+m_MOCCO.m_Iteration+".dat"; try { - out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (name))); + out.close(); + } catch (java.io.IOException e) { + } + + name = "MOCCO_" + m_StartDate + "_Infeasible_Iteration_" + m_MOCCO.m_Iteration + ".dat"; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: " + name); return; @@ -268,72 +287,99 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, for (int i = 0; i < m_MOCCO.m_State.m_PopulationHistory.length; i++) { pop.addPopulation(m_MOCCO.m_State.m_PopulationHistory[i]); } - obj = ((InterfaceMultiObjectiveDeNovoProblem)m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + obj = ((InterfaceMultiObjectiveDeNovoProblem) m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); tmp = ""; for (int j = 0; j < obj.length; j++) { - tmp += obj[j].getIdentName() +"\t"; + tmp += obj[j].getIdentName() + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } for (int i = 0; i < pop.size(); i++) { - if (((AbstractEAIndividual)pop.get(i)).violatesConstraint()) { + if (((AbstractEAIndividual) pop.get(i)).violatesConstraint()) { // write - tmp =""; - double[] fit = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmp = ""; + double[] fit = ((AbstractEAIndividual) pop.get(i)).getFitness(); for (int j = 0; j < fit.length; j++) { - tmp += fit[j] +"\t"; + tmp += fit[j] + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } } } - try { out.close(); } catch(java.io.IOException e) {} - - name = "MOCCO_"+m_StartDate+"_RefSolutions_Iteration_"+m_MOCCO.m_Iteration+".dat"; try { - out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (name))); + out.close(); + } catch (java.io.IOException e) { + } + + name = "MOCCO_" + m_StartDate + "_RefSolutions_Iteration_" + m_MOCCO.m_Iteration + ".dat"; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: " + name); return; } pop = m_MOCCO.m_State.m_ParetoFront.getMarkedIndividuals(); - obj = ((InterfaceMultiObjectiveDeNovoProblem)m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + obj = ((InterfaceMultiObjectiveDeNovoProblem) m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); tmp = ""; for (int j = 0; j < obj.length; j++) { - tmp += obj[j].getIdentName() +"\t"; + tmp += obj[j].getIdentName() + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } for (int i = 0; i < pop.size(); i++) { // write - tmp =""; - double[] fit = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmp = ""; + double[] fit = ((AbstractEAIndividual) pop.get(i)).getFitness(); for (int j = 0; j < fit.length; j++) { - tmp += fit[j] +"\t"; + tmp += fit[j] + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } } - try { out.close(); } catch(java.io.IOException e) {} - - name = "MOCCO_"+m_StartDate+"_RefPoint_Iteration_"+m_MOCCO.m_Iteration+".dat"; try { - out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (name))); + out.close(); + } catch (java.io.IOException e) { + } + + name = "MOCCO_" + m_StartDate + "_RefPoint_Iteration_" + m_MOCCO.m_Iteration + ".dat"; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: " + name); return; } pop = m_MOCCO.m_State.m_ParetoFront.getMarkedIndividuals(); - obj = ((InterfaceMultiObjectiveDeNovoProblem)m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + obj = ((InterfaceMultiObjectiveDeNovoProblem) m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); tmp = ""; for (int j = 0; j < obj.length; j++) { - tmp += obj[j].getIdentName() +"\t"; + tmp += obj[j].getIdentName() + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } tmp = ""; if (m_ReferencePoint != null) { for (int j = 0; j < m_ReferencePoint.length; j++) { - tmp += m_ReferencePoint[j] +"\t"; + tmp += m_ReferencePoint[j] + "\t"; + } + try { + out.write(tmp + "\n"); + } catch (java.io.IOException e) { } - try { out.write(tmp+"\n"); } catch (java.io.IOException e) { } } - try { out.close(); } catch(java.io.IOException e) {} + try { + out.close(); + } catch (java.io.IOException e) { + } } }; @@ -343,7 +389,7 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, if (this.m_MOCCO.m_State.m_CurrentProblem.isMultiObjective()) { if (this.m_1DView != null) { this.m_ViewPanel.removeAll(); - this.m_ViewPanel.add((JPanel)m_View, BorderLayout.CENTER); + this.m_ViewPanel.add((JPanel) m_View, BorderLayout.CENTER); } this.m_View.updateView(); this.m_1DView = null; @@ -352,7 +398,7 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, if (this.m_1DView == null) { this.m_ViewPanel.removeAll(); this.m_ViewPanel.setLayout(new BorderLayout()); - this.m_1DView = new FunctionArea("?","?"); + this.m_1DView = new FunctionArea("?", "?"); this.m_1DView.setPreferredSize(new Dimension(450, 450)); this.m_1DView.setMinimumSize(new Dimension(450, 450)); ScaledBorder areaBorder = new ScaledBorder(); @@ -367,8 +413,8 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, } - /** This method will plot a simple fitness plot, using the iterations a x-axis - * + /** + * This method will plot a simple fitness plot, using the iterations a x-axis */ public void plot1DFitnessPlot() { double xmin = 0, ymin = Double.POSITIVE_INFINITY, xmax = Double.NEGATIVE_INFINITY, ymax = Double.NEGATIVE_INFINITY, fitness; @@ -376,20 +422,20 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, if ((pops == null) || (pops.length < 1)) { return; } - GraphPointSet mySet; - DPoint myPoint; - DPointIcon icon; + GraphPointSet mySet; + DPoint myPoint; + DPointIcon icon; this.m_1DView.removeAll(); mySet = new GraphPointSet(1, this.m_1DView); mySet.setConnectedMode(true); mySet.setColor(Color.BLACK); for (int i = 0; i < pops.length; i++) { fitness = pops[i].getBestEAIndividual().getFitness()[0]; - myPoint = new DPoint(i+1, fitness); + myPoint = new DPoint(i + 1, fitness); icon = new Chart2DDPointContentSelectable(); //if (this.m_MOCCOViewer.m_RefSolutionSelectable) ((Chart2DDPointContentSelectable)icon).addSelectionListener(this.m_MOCCOViewer); - ((InterfaceDPointWithContent)icon).setProblem(this.m_MOCCO.m_State.m_CurrentProblem); - ((InterfaceDPointWithContent)icon).setEAIndividual(pops[i].getBestEAIndividual()); + ((InterfaceDPointWithContent) icon).setProblem(this.m_MOCCO.m_State.m_CurrentProblem); + ((InterfaceDPointWithContent) icon).setEAIndividual(pops[i].getBestEAIndividual()); myPoint.setIcon(icon); mySet.addDPoint(myPoint); if (fitness < ymin) { @@ -406,7 +452,7 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, yrange = 0.00001; } mySet.addDPoint(0, ymin - 0.1 * yrange); - mySet.addDPoint(pops.length+2, ymax + 0.1 * yrange); + mySet.addDPoint(pops.length + 2, ymax + 0.1 * yrange); this.m_ViewPanel.validate(); } @@ -415,16 +461,17 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, * InterfaceSelectionListener */ - /** This method will notify the listener that an + /** + * This method will notify the listener that an * Individual has been selected - * @param indy The selected individual + * + * @param indy The selected individual */ @Override public void individualSelected(AbstractEAIndividual indy) { if (indy.isMarked()) { indy.unmark(); - } - else { + } else { if (this.m_SelectUniqueSolution) { this.m_MOCCO.m_State.m_ParetoFront.unmarkAllIndividuals(); } @@ -436,14 +483,18 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, } } - /** This method allows to toggle unique selection mode + /** + * This method allows to toggle unique selection mode + * * @param t */ public void setUniquelySelectable(boolean t) { this.m_SelectUniqueSolution = t; } - /** This method allows to toggle selection mode + /** + * This method allows to toggle selection mode + * * @param t */ public void setRefSolutionSelectable(boolean t) { @@ -451,22 +502,27 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, this.m_View.updateView(); } - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ public void addRefSolutionSelectionListener(InterfaceRefSolutionListener a) { this.m_RefSolutionListener = a; } - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfaceSelectionListener */ public InterfaceRefSolutionListener getRefSolutionSelectionListener() { return this.m_RefSolutionListener; } - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ public void removeRefSolutionSelectionListeners() { this.m_RefSolutionListener = null; @@ -476,8 +532,10 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, * InterfaceReferenceListener */ - /** This method will notify the listener that a point has been selected - * @param point The selected point, most likely 2d + /** + * This method will notify the listener that a point has been selected + * + * @param point The selected point, most likely 2d */ @Override public void refPointGiven(double[] point) { @@ -488,13 +546,15 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, this.m_View.updateView(); } - /** This method allows to toggle unique selection mode + /** + * This method allows to toggle unique selection mode + * * @param t */ public void setRefPointSelectable(boolean t) { this.m_RefPointSelectable = t; if (this.m_RefPointSelectable) { - int dim = ((AbstractEAIndividual)this.m_MOCCO.m_State.m_ParetoFront.get(0)).getFitness().length; + int dim = ((AbstractEAIndividual) this.m_MOCCO.m_State.m_ParetoFront.get(0)).getFitness().length; this.m_ReferencePoint = new double[dim]; for (int i = 0; i < dim; i++) { this.m_ReferencePoint[i] = 0; @@ -505,29 +565,34 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, this.m_View.updateView(); } - /** This method removes the reference point - * + /** + * This method removes the reference point */ public void removeReferencePoint() { this.m_ReferencePoint = null; } - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ public void addRefPointSelectionListener(InterfaceRefPointListener a) { this.m_RefPointListener = a; } - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfaceSelectionListener */ public InterfaceRefPointListener getRefPointSelectionListener() { return this.m_RefPointListener; } - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ public void removeRefPointSelectionListeners() { this.m_RefPointListener = null; diff --git a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java index 2455bd02..a68e9a95 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java @@ -14,6 +14,7 @@ import eva2.tools.chart2d.Chart2DDPointIconPoint; import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.ScaledBorder; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -30,13 +31,13 @@ import javax.swing.*; */ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontView, InterfaceRefPointListener { - public MOCCOViewer m_MOCCOViewer; - private JPanel m_JPMain; - private JPanel m_JPTop; - private JComboBox m_JCObjective1, m_JCObjective2, m_JCFitObj; + public MOCCOViewer m_MOCCOViewer; + private JPanel m_JPMain; + private JPanel m_JPTop; + private JComboBox m_JCObjective1, m_JCObjective2, m_JCFitObj; private FunctionArea m_Area; - private ScaledBorder m_AreaBorder; - private InterfaceRefPointListener m_RefPointListener; + private ScaledBorder m_AreaBorder; + private InterfaceRefPointListener m_RefPointListener; public ParetoFrontView2D(MOCCOViewer t) { this.m_MOCCOViewer = t; @@ -48,7 +49,7 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie this.m_JPMain.setLayout(new BorderLayout()); this.setLayout(new BorderLayout()); this.add(this.m_JPMain, BorderLayout.CENTER); - this.m_Area = new FunctionArea("?","?"); + this.m_Area = new FunctionArea("?", "?"); this.m_Area.setPreferredSize(new Dimension(450, 450)); this.m_Area.setMinimumSize(new Dimension(450, 450)); this.m_AreaBorder = new ScaledBorder(); @@ -58,11 +59,11 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie this.m_Area.setBackground(Color.WHITE); this.m_JPMain.add(this.m_Area, BorderLayout.CENTER); this.m_JPTop = new JPanel(); - this.m_JPTop.setLayout(new GridLayout(1,5)); + this.m_JPTop.setLayout(new GridLayout(1, 5)); String[] tmp = new String[2]; tmp[0] = "Fitness"; tmp[1] = "Objective"; - this.m_JCFitObj = new JComboBox(tmp); + this.m_JCFitObj = new JComboBox(tmp); this.m_JCFitObj.setSelectedIndex(0); this.m_JCFitObj.addActionListener(this.jcombobox2Listener); this.m_JCObjective1 = new JComboBox(this.getAvailableObjectiveNames()); @@ -84,6 +85,7 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie this.m_JPMain.add(this.m_JPTop, BorderLayout.NORTH); this.updateView(); } + ActionListener jcomboboxListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { @@ -126,7 +128,7 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie return result; } if (this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem instanceof InterfaceMultiObjectiveDeNovoProblem) { - InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem)this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem) this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); result = new String[tmp.length]; for (int i = 0; i < tmp.length; i++) { result[i] = tmp[i].getIdentName(); @@ -141,14 +143,15 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie } result = new String[tmpList.size()]; for (int i = 0; i < tmpList.size(); i++) { - result[i] = (String)tmpList.get(i); + result[i] = (String) tmpList.get(i); } } } return result; } - /** This method notifies the Pareto front view that + /** + * This method notifies the Pareto front view that * the data has changed most likely due to changes in * the problem definition */ @@ -164,7 +167,7 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie } boolean equal = true; for (int i = 0; i < tmpS.length; i++) { - if (!tmpS[i].equalsIgnoreCase((String)this.m_JCObjective1.getItemAt(i))) { + if (!tmpS[i].equalsIgnoreCase((String) this.m_JCObjective1.getItemAt(i))) { equal = false; } } @@ -174,8 +177,8 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie if (this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem instanceof InterfaceMultiObjectiveDeNovoProblem) { //InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem)this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); String[] objectives = this.getAvailableObjectiveNames(); - this.m_AreaBorder.x_label = ""+ objectives[this.m_JCObjective1.getSelectedIndex()]; - this.m_AreaBorder.y_label = ""+ objectives[this.m_JCObjective2.getSelectedIndex()]; + this.m_AreaBorder.x_label = "" + objectives[this.m_JCObjective1.getSelectedIndex()]; + this.m_AreaBorder.y_label = "" + objectives[this.m_JCObjective2.getSelectedIndex()]; } if ((this.m_MOCCOViewer.m_MOCCO.m_State.m_ParetoFront != null) && (this.m_MOCCOViewer.m_MOCCO.m_State.m_ParetoFront.size() > 0)) { this.plot2DParetoFront(); @@ -183,17 +186,17 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie this.validate(); } - /** This method will plot a simple fitness plot, using the iterations a x-axis - * + /** + * This method will plot a simple fitness plot, using the iterations a x-axis */ public void plot2DParetoFront() { double xmin = Double.POSITIVE_INFINITY, ymin = Double.POSITIVE_INFINITY, xmax = Double.NEGATIVE_INFINITY, ymax = Double.NEGATIVE_INFINITY; this.m_Area.clearAll(); this.m_Area.setBackground(Color.WHITE); - GraphPointSet mySet; - DPoint myPoint; - double[] fitness; - int indexX, indexY; + GraphPointSet mySet; + DPoint myPoint; + double[] fitness; + int indexX, indexY; indexX = this.m_JCObjective1.getSelectedIndex(); indexY = this.m_JCObjective2.getSelectedIndex(); // first plot the populations @@ -201,18 +204,17 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie for (int i = 0; i < this.m_MOCCOViewer.m_MOCCO.m_State.m_PopulationHistory.length; i++) { //System.out.println("Population " + i+" show " +this.m_MOCCOViewer.m_MOCCO.m_State.m_Show[i]); if (this.m_MOCCOViewer.m_MOCCO.m_State.m_Show[i]) { - mySet = new GraphPointSet(i+10, this.m_Area); + mySet = new GraphPointSet(i + 10, this.m_Area); mySet.setConnectedMode(false); mySet.setColor(this.m_MOCCOViewer.m_MOCCO.m_State.m_Color[i]); //System.out.println(((ArrayList)this.m_Boss.m_FitnessCache.get(i)).size()+"/"+((ArrayList)this.m_Boss.m_ObjectiveCache.get(i)).size()); if (this.m_JCFitObj.getSelectedIndex() == 0) { - for (int j = 0; j < ((ArrayList)this.m_MOCCOViewer.m_MOCCO.m_State.m_FitnessCache.get(i)).size(); j++) { - fitness = (double[])((ArrayList)this.m_MOCCOViewer.m_MOCCO.m_State.m_FitnessCache.get(i)).get(j); + for (int j = 0; j < ((ArrayList) this.m_MOCCOViewer.m_MOCCO.m_State.m_FitnessCache.get(i)).size(); j++) { + fitness = (double[]) ((ArrayList) this.m_MOCCOViewer.m_MOCCO.m_State.m_FitnessCache.get(i)).get(j); myPoint = new DPoint(fitness[indexX], fitness[indexY]); - if (((Double)((ArrayList)this.m_MOCCOViewer.m_MOCCO.m_State.m_ConstraintCache.get(i)).get(j)).doubleValue() == 0) { + if (((Double) ((ArrayList) this.m_MOCCOViewer.m_MOCCO.m_State.m_ConstraintCache.get(i)).get(j)).doubleValue() == 0) { myPoint.setIcon(new Chart2DDPointIconCross()); - } - else { + } else { myPoint.setIcon(new Chart2DDPointIconPoint()); } mySet.addDPoint(myPoint); @@ -230,13 +232,12 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie } } } else { - for (int j = 0; j < ((ArrayList)this.m_MOCCOViewer.m_MOCCO.m_State.m_ObjectiveCache.get(i)).size(); j++) { - fitness = (double[])((ArrayList)this.m_MOCCOViewer.m_MOCCO.m_State.m_ObjectiveCache.get(i)).get(j); + for (int j = 0; j < ((ArrayList) this.m_MOCCOViewer.m_MOCCO.m_State.m_ObjectiveCache.get(i)).size(); j++) { + fitness = (double[]) ((ArrayList) this.m_MOCCOViewer.m_MOCCO.m_State.m_ObjectiveCache.get(i)).get(j); myPoint = new DPoint(fitness[indexX], fitness[indexY]); - if (((Double)((ArrayList)this.m_MOCCOViewer.m_MOCCO.m_State.m_ConstraintCache.get(i)).get(j)).doubleValue() == 0) { + if (((Double) ((ArrayList) this.m_MOCCOViewer.m_MOCCO.m_State.m_ConstraintCache.get(i)).get(j)).doubleValue() == 0) { myPoint.setIcon(new Chart2DDPointIconCross()); - } - else { + } else { myPoint.setIcon(new Chart2DDPointIconPoint()); } mySet.addDPoint(myPoint); @@ -260,28 +261,28 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie // now mark the ParetoFront Population pf = this.m_MOCCOViewer.m_MOCCO.m_State.m_ParetoFront; if (pf.size() > 0) { - DPoint point; - DPointIcon icon; + DPoint point; + DPointIcon icon; mySet = new GraphPointSet(1, this.m_Area); mySet.setConnectedMode(false); mySet.setColor(Color.BLACK); for (int i = 0; i < pf.size(); i++) { if (this.m_JCFitObj.getSelectedIndex() == 0) { - fitness = ((AbstractEAIndividual)pf.get(i)).getFitness(); + fitness = ((AbstractEAIndividual) pf.get(i)).getFitness(); } else { - InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); fitness = new double[tmpObj.length]; for (int k = 0; k < tmpObj.length; k++) { - fitness[k] = ((Double)((AbstractEAIndividual)pf.get(i)).getData(tmpObj[k].getIdentName())).doubleValue(); + fitness[k] = ((Double) ((AbstractEAIndividual) pf.get(i)).getData(tmpObj[k].getIdentName())).doubleValue(); } - } + } point = new DPoint(fitness[indexX], fitness[indexY]); icon = new Chart2DDPointContentSelectable(); if (this.m_MOCCOViewer.m_RefSolutionSelectable) { - ((Chart2DDPointContentSelectable)icon).addSelectionListener(this.m_MOCCOViewer); + ((Chart2DDPointContentSelectable) icon).addSelectionListener(this.m_MOCCOViewer); } - ((InterfaceDPointWithContent)icon).setProblem(this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem); - ((InterfaceDPointWithContent)icon).setEAIndividual((AbstractEAIndividual)pf.get(i)); + ((InterfaceDPointWithContent) icon).setProblem(this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem); + ((InterfaceDPointWithContent) icon).setEAIndividual((AbstractEAIndividual) pf.get(i)); point.setIcon(icon); mySet.addDPoint(point); if (fitness[indexX] < xmin) { @@ -306,38 +307,38 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie mySet.addDPoint(0, 0); mySet.addDPoint(1, 1); } else { - mySet.addDPoint(xmin - 0.1*xrange, ymin - 0.1*yrange); - mySet.addDPoint(xmin - 0.1*xrange, ymin - 0.1*yrange); - mySet.addDPoint(xmax + 0.1*xrange, ymax + 0.1*yrange); - mySet.addDPoint(xmax + 0.1*xrange, ymax + 0.1*yrange); + mySet.addDPoint(xmin - 0.1 * xrange, ymin - 0.1 * yrange); + mySet.addDPoint(xmin - 0.1 * xrange, ymin - 0.1 * yrange); + mySet.addDPoint(xmax + 0.1 * xrange, ymax + 0.1 * yrange); + mySet.addDPoint(xmax + 0.1 * xrange, ymax + 0.1 * yrange); } // now lets prepare the contraints or goals if any... if ((this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem instanceof InterfaceMultiObjectiveDeNovoProblem) && - (this.m_JCFitObj.getSelectedIndex() == 1)){ - InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem)this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + (this.m_JCFitObj.getSelectedIndex() == 1)) { + InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem) this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); for (int i = 0; i < tmp.length; i++) { if ((!(tmp[i].getOptimizationMode().equalsIgnoreCase("Objective"))) && - ((this.m_JCObjective1.getSelectedIndex() == i) || - (this.m_JCObjective2.getSelectedIndex() == i))) { + ((this.m_JCObjective1.getSelectedIndex() == i) || + (this.m_JCObjective2.getSelectedIndex() == i))) { double tmpD = tmp[i].getConstraintGoal(); if (!(new Double(tmpD)).isNaN()) { // draw a line indicating the constraint/goals - mySet = new GraphPointSet(500+i, this.m_Area); + mySet = new GraphPointSet(500 + i, this.m_Area); mySet.setConnectedMode(true); if (this.m_JCObjective1.getSelectedIndex() == i) { - if ((tmpD > xmin - 0.1*xrange) && (tmpD < xmax + 0.1*xrange)) { - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); + if ((tmpD > xmin - 0.1 * xrange) && (tmpD < xmax + 0.1 * xrange)) { + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); } } else { - if ((tmpD > ymin - 0.1*yrange) && (tmpD < ymax + 0.1*yrange)) { - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); + if ((tmpD > ymin - 0.1 * yrange) && (tmpD < ymax + 0.1 * yrange)) { + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); } } } @@ -359,21 +360,21 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie mySet.setConnectedMode(true); mySet.setColor(Color.RED); double tmpD = this.m_MOCCOViewer.m_ReferencePoint[this.m_JCObjective1.getSelectedIndex()]; - if ((tmpD > xmin - 0.1*xrange) && (tmpD < xmax + 0.1*xrange)) { - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); + if ((tmpD > xmin - 0.1 * xrange) && (tmpD < xmax + 0.1 * xrange)) { + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); } mySet = new GraphPointSet(1002, this.m_Area); mySet.setConnectedMode(true); mySet.setColor(Color.RED); tmpD = this.m_MOCCOViewer.m_ReferencePoint[this.m_JCObjective2.getSelectedIndex()]; - if ((tmpD > ymin - 0.1*yrange) && (tmpD < ymax + 0.1*yrange)) { - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); + if ((tmpD > ymin - 0.1 * yrange) && (tmpD < ymax + 0.1 * yrange)) { + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); } } } @@ -382,17 +383,19 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie * InterfaceReferenceListener */ - /** This method will notify the listener that a point has been selected + /** + * This method will notify the listener that a point has been selected * It has to be noted though that at this point the reference point is not * a full vector since it is only 2d - * @param point The selected point, most likely 2d + * + * @param point The selected point, most likely 2d */ @Override public void refPointGiven(double[] point) { if (this.m_JCFitObj.getSelectedIndex() == 1) { JOptionPane.showMessageDialog(this.m_MOCCOViewer.m_MOCCO.m_JFrame, - "Reference point needs to be selected in fitness space!", - "Warning", JOptionPane.WARNING_MESSAGE); + "Reference point needs to be selected in fitness space!", + "Warning", JOptionPane.WARNING_MESSAGE); } else { double[] tmpD = this.m_MOCCOViewer.m_ReferencePoint; tmpD[this.m_JCObjective1.getSelectedIndex()] = point[0]; @@ -401,22 +404,27 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie } } - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ public void addRefPointSelectionListener(InterfaceRefPointListener a) { this.m_RefPointListener = a; } - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfaceSelectionListener */ public InterfaceRefPointListener getRefPointSelectionListener() { return this.m_RefPointListener; } - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ public void removeRefPointSelectionListeners() { this.m_RefPointListener = null; diff --git a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewParallelAxsis.java b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewParallelAxsis.java index 5972c447..eac883d0 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewParallelAxsis.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewParallelAxsis.java @@ -11,13 +11,14 @@ import javax.swing.*; */ public class ParetoFrontViewParallelAxsis extends JPanel implements InterfaceParetoFrontView { - public MOCCOViewer m_MOCCOViewer; + public MOCCOViewer m_MOCCOViewer; public ParetoFrontViewParallelAxsis(MOCCOViewer t) { this.m_MOCCOViewer = t; } - /** This method notifies the Pareto front view that + /** + * This method notifies the Pareto front view that * the data has changed most likely due to changes in * the problem definition */ diff --git a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java index 865f2f07..23873153 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java @@ -12,6 +12,7 @@ import eva2.tools.chart2d.Chart2DDPointContentSelectable; import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.ScaledBorder; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -27,12 +28,12 @@ import javax.swing.*; class SimpleView extends JComponent implements InterfaceRefPointListener { - private InterfaceRefPointListener m_RefPointListener; + private InterfaceRefPointListener m_RefPointListener; private FunctionArea m_Area = null; - private ScaledBorder m_AreaBorder; - ParetoFrontViewScatterPlot m_Dad; - int m_Obj1, m_Obj2; - JLabel m_JLabel; + private ScaledBorder m_AreaBorder; + ParetoFrontViewScatterPlot m_Dad; + int m_Obj1, m_Obj2; + JLabel m_JLabel; public SimpleView(ParetoFrontViewScatterPlot dad, int obj1, int obj2) { this.m_Dad = dad; @@ -44,28 +45,28 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { private void init() { this.setLayout(new BorderLayout()); if (this.m_Obj1 == this.m_Obj2) { - this.m_JLabel = new JLabel(""+((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj1].getIdentName()); + this.m_JLabel = new JLabel("" + ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj1].getIdentName()); this.add(this.m_JLabel, BorderLayout.CENTER); } else { - this.m_Area = new FunctionArea("?","?"); + this.m_Area = new FunctionArea("?", "?"); this.m_Area.setPreferredSize(new Dimension(200, 200)); this.m_Area.setMinimumSize(new Dimension(200, 200)); this.m_AreaBorder = new ScaledBorder(); - this.m_AreaBorder.x_label = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj1].getIdentName(); - this.m_AreaBorder.y_label = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj2].getIdentName(); + this.m_AreaBorder.x_label = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj1].getIdentName(); + this.m_AreaBorder.y_label = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj2].getIdentName(); this.m_Area.setBorder(this.m_AreaBorder); this.m_Area.setBackground(Color.WHITE); this.add(this.m_Area, BorderLayout.CENTER); } } - private double[] fetchPlotValueFor (AbstractEAIndividual indy) { + private double[] fetchPlotValueFor(AbstractEAIndividual indy) { double[] result = new double[2]; if (this.m_Dad.m_JCFitObj.getSelectedIndex() == 0) { // now this is tricky isn't // first findout whether a objective is constraint only // and second since some objectives are ommited find the one fitness value that is the correct one - InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); if (tmpObj[this.m_Obj1].getOptimizationMode().equalsIgnoreCase("Constraint")) { result[0] = 0; } else { @@ -94,9 +95,9 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { result[1] = indy.getFitness(index); } } else { - InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); - result[0] = ((Double)indy.getData(tmpObj[this.m_Obj1].getIdentName())).doubleValue(); - result[1] = ((Double)indy.getData(tmpObj[this.m_Obj2].getIdentName())).doubleValue(); + InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + result[0] = ((Double) indy.getData(tmpObj[this.m_Obj1].getIdentName())).doubleValue(); + result[1] = ((Double) indy.getData(tmpObj[this.m_Obj2].getIdentName())).doubleValue(); } return result; } @@ -106,34 +107,34 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { // System.out.println("Plotting ("+this.m_Obj1+"/"+this.m_Obj2+") of " + tmpObj.length +" objectives."); // System.out.println(" ("+tmpObj[this.m_Obj1].getIdentName()+"/"+tmpObj[this.m_Obj2].getIdentName()+") which is of mode: ("+tmpObj[this.m_Obj1].getOptimizationMode()+"/"+tmpObj[this.m_Obj2].getOptimizationMode()+")"); if (this.m_Obj1 == this.m_Obj2) { - this.m_JLabel.setText(""+((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj1].getIdentName()); + this.m_JLabel.setText("" + ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives()[this.m_Obj1].getIdentName()); } else { // plot the objectives Population pf = this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_ParetoFront; double xmin = Double.POSITIVE_INFINITY, ymin = Double.POSITIVE_INFINITY, xmax = Double.NEGATIVE_INFINITY, ymax = Double.NEGATIVE_INFINITY; this.m_Area.clearAll(); this.m_Area.setBackground(Color.WHITE); - GraphPointSet mySet; - DPoint myPoint; + GraphPointSet mySet; + DPoint myPoint; //double[] fitness; - double[] plotValue; + double[] plotValue; // now mark the ParetoFront if (pf.size() > 0) { - DPoint point; - DPointIcon icon; + DPoint point; + DPointIcon icon; mySet = new GraphPointSet(1, this.m_Area); mySet.setConnectedMode(false); mySet.setColor(Color.BLACK); for (int i = 0; i < pf.size(); i++) { - plotValue = this.fetchPlotValueFor((AbstractEAIndividual)pf.get(i)); + plotValue = this.fetchPlotValueFor((AbstractEAIndividual) pf.get(i)); point = new DPoint(plotValue[0], plotValue[1]); icon = new Chart2DDPointContentSelectable(); if (this.m_Dad.m_MOCCOViewer.m_RefSolutionSelectable) { - ((Chart2DDPointContentSelectable)icon).addSelectionListener(this.m_Dad.m_MOCCOViewer); + ((Chart2DDPointContentSelectable) icon).addSelectionListener(this.m_Dad.m_MOCCOViewer); } - ((InterfaceDPointWithContent)icon).setProblem(this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem); - ((InterfaceDPointWithContent)icon).setEAIndividual((AbstractEAIndividual)pf.get(i)); + ((InterfaceDPointWithContent) icon).setProblem(this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem); + ((InterfaceDPointWithContent) icon).setEAIndividual((AbstractEAIndividual) pf.get(i)); point.setIcon(icon); mySet.addDPoint(point); if (plotValue[0] < xmin) { @@ -162,39 +163,39 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { mySet.addDPoint(0, 0); mySet.addDPoint(1, 1); } else { - mySet.addDPoint(xmin - 0.1*xrange, ymin - 0.1*yrange); - mySet.addDPoint(xmin - 0.1*xrange, ymin - 0.1*yrange); - mySet.addDPoint(xmax + 0.1*xrange, ymax + 0.1*yrange); - mySet.addDPoint(xmax + 0.1*xrange, ymax + 0.1*yrange); + mySet.addDPoint(xmin - 0.1 * xrange, ymin - 0.1 * yrange); + mySet.addDPoint(xmin - 0.1 * xrange, ymin - 0.1 * yrange); + mySet.addDPoint(xmax + 0.1 * xrange, ymax + 0.1 * yrange); + mySet.addDPoint(xmax + 0.1 * xrange, ymax + 0.1 * yrange); } // now lets prepare the contraints or goals if any... if ((this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem instanceof InterfaceMultiObjectiveDeNovoProblem) && - (this.m_Dad.m_JCFitObj.getSelectedIndex() == 1)) { - InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem)this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + (this.m_Dad.m_JCFitObj.getSelectedIndex() == 1)) { + InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem) this.m_Dad.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); if (tmp[this.m_Obj1].getOptimizationMode().equalsIgnoreCase("Objective")) { double tmpD = tmp[this.m_Obj1].getConstraintGoal(); if (!(new Double(tmpD)).isNaN()) { - mySet = new GraphPointSet(500+1, this.m_Area); + mySet = new GraphPointSet(500 + 1, this.m_Area); mySet.setConnectedMode(true); - if ((tmpD > xmin - 0.1*xrange) && (tmpD < xmax + 0.1*xrange)) { - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); + if ((tmpD > xmin - 0.1 * xrange) && (tmpD < xmax + 0.1 * xrange)) { + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); } } } if (tmp[this.m_Obj2].getOptimizationMode().equalsIgnoreCase("Objective")) { double tmpD = tmp[this.m_Obj2].getConstraintGoal(); if (!(new Double(tmpD)).isNaN()) { - mySet = new GraphPointSet(500+2, this.m_Area); + mySet = new GraphPointSet(500 + 2, this.m_Area); mySet.setConnectedMode(true); - if ((tmpD > ymin - 0.1*yrange) && (tmpD < ymax + 0.1*yrange)) { - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); + if ((tmpD > ymin - 0.1 * yrange) && (tmpD < ymax + 0.1 * yrange)) { + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); } } } @@ -205,21 +206,21 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { mySet.setConnectedMode(true); mySet.setColor(Color.RED); double tmpD = this.m_Dad.m_MOCCOViewer.m_ReferencePoint[this.m_Obj1]; - if ((tmpD > xmin - 0.1*xrange) && (tmpD < xmax + 0.1*xrange)) { - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymin - 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); - mySet.addDPoint(tmpD, ymax + 0.1*yrange); + if ((tmpD > xmin - 0.1 * xrange) && (tmpD < xmax + 0.1 * xrange)) { + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymin - 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); + mySet.addDPoint(tmpD, ymax + 0.1 * yrange); } mySet = new GraphPointSet(1002, this.m_Area); mySet.setConnectedMode(true); mySet.setColor(Color.RED); tmpD = this.m_Dad.m_MOCCOViewer.m_ReferencePoint[this.m_Obj2]; - if ((tmpD > ymin - 0.1*yrange) && (tmpD < ymax + 0.1*yrange)) { - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmin - 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); - mySet.addDPoint(xmax + 0.1*xrange, tmpD); + if ((tmpD > ymin - 0.1 * yrange) && (tmpD < ymax + 0.1 * yrange)) { + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmin - 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); + mySet.addDPoint(xmax + 0.1 * xrange, tmpD); } } } @@ -241,17 +242,19 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { * InterfaceReferenceListener */ - /** This method will notify the listener that a point has been selected + /** + * This method will notify the listener that a point has been selected * It has to be noted though that at this point the reference point is not * a full vector since it is only 2d - * @param point The selected point, most likely 2d + * + * @param point The selected point, most likely 2d */ @Override public void refPointGiven(double[] point) { if (this.m_Dad.m_JCFitObj.getSelectedIndex() == 1) { JOptionPane.showMessageDialog(this.m_Dad.m_MOCCOViewer.m_MOCCO.m_JFrame, - "Reference point needs to be selected in fitness space!", - "Warning", JOptionPane.WARNING_MESSAGE); + "Reference point needs to be selected in fitness space!", + "Warning", JOptionPane.WARNING_MESSAGE); } else { double[] tmpD = this.m_Dad.m_MOCCOViewer.m_ReferencePoint; tmpD[this.m_Obj1] = point[0]; @@ -260,22 +263,27 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { } } - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ public void addRefPointSelectionListener(InterfaceRefPointListener a) { this.m_RefPointListener = a; } - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfaceSelectionListener */ public InterfaceRefPointListener getRefPointSelectionListener() { return this.m_RefPointListener; } - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ public void removeRefPointSelectionListeners() { this.m_RefPointListener = null; @@ -284,15 +292,15 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParetoFrontView { - public MOCCOViewer m_MOCCOViewer; - private JPanel m_JPMain; - private JPanel m_JPCenter; - private JPanel m_JPTop; - public JComboBox m_JCFitObj; + public MOCCOViewer m_MOCCOViewer; + private JPanel m_JPMain; + private JPanel m_JPCenter; + private JPanel m_JPTop; + public JComboBox m_JCFitObj; - private InterfaceRefPointListener m_RefPointListener; - private SimpleView[][] m_Scatter; + private InterfaceRefPointListener m_RefPointListener; + private SimpleView[][] m_Scatter; public ParetoFrontViewScatterPlot(MOCCOViewer t) { this.m_MOCCOViewer = t; @@ -307,11 +315,11 @@ public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParet this.m_JPCenter = new JPanel(); this.m_JPMain.add(new JScrollPane(this.m_JPCenter), BorderLayout.CENTER); this.m_JPTop = new JPanel(); - this.m_JPTop.setLayout(new GridLayout(1,2)); + this.m_JPTop.setLayout(new GridLayout(1, 2)); String[] tmp = new String[2]; tmp[0] = "Fitness"; tmp[1] = "Objective"; - this.m_JCFitObj = new JComboBox(tmp); + this.m_JCFitObj = new JComboBox(tmp); this.m_JCFitObj.setSelectedIndex(0); this.m_JCFitObj.addActionListener(this.jcomboboxListener); this.m_JPTop.add(new JLabel("Showing:")); @@ -319,6 +327,7 @@ public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParet this.m_JPMain.add(this.m_JPTop, BorderLayout.NORTH); this.updateView(); } + ActionListener jcomboboxListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { @@ -327,7 +336,7 @@ public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParet }; private void makeScatter() { - InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem)this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem) this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); this.m_Scatter = new SimpleView[tmp.length][tmp.length]; this.m_JPCenter.removeAll(); this.m_JPCenter.setLayout(new GridLayout(tmp.length, tmp.length)); @@ -339,7 +348,8 @@ public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParet } } - /** This method notifies the Pareto front view that + /** + * This method notifies the Pareto front view that * the data has changed most likely due to changes in * the problem definition */ @@ -354,7 +364,7 @@ public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParet } // first set the names of the objectives - InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem)this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); + InterfaceOptimizationObjective[] tmp = ((InterfaceMultiObjectiveDeNovoProblem) this.m_MOCCOViewer.m_MOCCO.m_State.m_CurrentProblem).getProblemObjectives(); if (this.m_Scatter == null) { this.makeScatter(); } @@ -372,42 +382,48 @@ public class ParetoFrontViewScatterPlot extends JPanel implements InterfaceParet } - /*************************************************************************** * InterfaceReferenceListener */ - /** This method will notify the listener that a point has been selected + /** + * This method will notify the listener that a point has been selected * It has to be noted though that at this point the reference point is not * a full vector since it is only 2d - * @param point The selected point, most likely 2d + * + * @param point The selected point, most likely 2d */ public void refPointGiven(double[] point) { if (this.m_JCFitObj.getSelectedIndex() == 1) { JOptionPane.showMessageDialog(this.m_MOCCOViewer.m_MOCCO.m_JFrame, - "Reference point needs to be selected in fitness space!", - "Warning", JOptionPane.WARNING_MESSAGE); + "Reference point needs to be selected in fitness space!", + "Warning", JOptionPane.WARNING_MESSAGE); } else { this.m_MOCCOViewer.refPointGiven(point); } } - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ public void addRefPointSelectionListener(InterfaceRefPointListener a) { this.m_RefPointListener = a; } - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfaceSelectionListener */ public InterfaceRefPointListener getRefPointSelectionListener() { return this.m_RefPointListener; } - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ public void removeRefPointSelectionListeners() { this.m_RefPointListener = null; diff --git a/src/eva2/optimization/modules/AbstractModuleAdapter.java b/src/eva2/optimization/modules/AbstractModuleAdapter.java index 57acf72c..ccc2fc03 100644 --- a/src/eva2/optimization/modules/AbstractModuleAdapter.java +++ b/src/eva2/optimization/modules/AbstractModuleAdapter.java @@ -9,17 +9,17 @@ package eva2.optimization.modules; * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ * $Author: mkron $ */ + import eva2.optimization.go.InterfaceOptimizationParameters; import eva2.optimization.go.InterfaceProcessor; import eva2.optimization.OptimizationStateListener; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * The module server expects a constructor with two arguments: String adapterName and MainAdapterClient client. - * - * */ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializable { @@ -50,7 +50,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab /** * Get the name of the current adapter. - * + * * @return The adapter name */ @Override @@ -85,7 +85,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab /** * Returns whether the current optimization provides post processing. - * + * * @return true if post processing is available */ @Override @@ -95,7 +95,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab /** * Starts post processing if available. - * + * * @return true if post processing was performed, false otherwise. */ @Override @@ -148,7 +148,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab /** * Returns whether the module has a connection. - * + * * @return true if the adapter has a connection. */ @Override @@ -166,7 +166,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab /** * Returns the host name. - * + * * @return The host name */ @Override diff --git a/src/eva2/optimization/modules/AbstractOptimizationParameters.java b/src/eva2/optimization/modules/AbstractOptimizationParameters.java index 6e42ee85..9788df92 100644 --- a/src/eva2/optimization/modules/AbstractOptimizationParameters.java +++ b/src/eva2/optimization/modules/AbstractOptimizationParameters.java @@ -11,6 +11,7 @@ import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.Serializer; + import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.Serializable; @@ -22,76 +23,76 @@ import java.util.logging.Logger; public abstract class AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable { protected static final Logger LOGGER = Logger.getLogger(AbstractOptimizationParameters.class.getName()); - protected long randomSeed = (long)0.0; + protected long randomSeed = (long) 0.0; - // Opt. Algorithms and Parameters - protected InterfaceOptimizer optimizer; - protected InterfaceOptimizationProblem problem; - protected InterfaceTerminator terminator; - protected InterfacePostProcessParams postProcessing = new PostProcessParams(false); - transient protected InterfacePopulationChangedEventListener populationChangedEventListener; - transient private List toInformAboutInformers = null; - - protected AbstractOptimizationParameters() { - } + // Opt. Algorithms and Parameters + protected InterfaceOptimizer optimizer; + protected InterfaceOptimizationProblem problem; + protected InterfaceTerminator terminator; + protected InterfacePostProcessParams postProcessing = new PostProcessParams(false); + transient protected InterfacePopulationChangedEventListener populationChangedEventListener; + transient private List toInformAboutInformers = null; - protected AbstractOptimizationParameters(AbstractOptimizationParameters optimizationParameters) { - this(); - this.optimizer = optimizationParameters.optimizer; - this.problem = optimizationParameters.problem; - this.terminator = optimizationParameters.terminator; - this.optimizer.setProblem(this.problem); - this.randomSeed = optimizationParameters.randomSeed; - this.postProcessing = optimizationParameters.postProcessing; - } - - public AbstractOptimizationParameters(InterfaceOptimizer opt, InterfaceOptimizationProblem prob, InterfaceTerminator term) { - this(); - optimizer = opt; - problem = prob; - terminator = term; - postProcessing = new PostProcessParams(false); - opt.setProblem(prob); - } + protected AbstractOptimizationParameters() { + } - /** - * Apply the given GO parameter settings to this instance. This maintains the listeners etc. - * - * @param parameters - */ - public void setSameParams(AbstractOptimizationParameters parameters) { - setOptimizer(parameters.optimizer); - setProblem(parameters.problem); - setTerminator(parameters.terminator); - this.optimizer.setProblem(this.problem); - setSeed(parameters.randomSeed); - setPostProcessParams(parameters.postProcessing); - } - - /** - * Add a listener to the current optimizer. - * - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.populationChangedEventListener = ea; - if (this.optimizer != null) { + protected AbstractOptimizationParameters(AbstractOptimizationParameters optimizationParameters) { + this(); + this.optimizer = optimizationParameters.optimizer; + this.problem = optimizationParameters.problem; + this.terminator = optimizationParameters.terminator; + this.optimizer.setProblem(this.problem); + this.randomSeed = optimizationParameters.randomSeed; + this.postProcessing = optimizationParameters.postProcessing; + } + + public AbstractOptimizationParameters(InterfaceOptimizer opt, InterfaceOptimizationProblem prob, InterfaceTerminator term) { + this(); + optimizer = opt; + problem = prob; + terminator = term; + postProcessing = new PostProcessParams(false); + opt.setProblem(prob); + } + + /** + * Apply the given GO parameter settings to this instance. This maintains the listeners etc. + * + * @param parameters + */ + public void setSameParams(AbstractOptimizationParameters parameters) { + setOptimizer(parameters.optimizer); + setProblem(parameters.problem); + setTerminator(parameters.terminator); + this.optimizer.setProblem(this.problem); + setSeed(parameters.randomSeed); + setPostProcessParams(parameters.postProcessing); + } + + /** + * Add a listener to the current optimizer. + * + * @param ea + */ + public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { + this.populationChangedEventListener = ea; + if (this.optimizer != null) { this.optimizer.addPopulationChangedEventListener(this.populationChangedEventListener); } - } + } - public boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - if (populationChangedEventListener ==ea) { - populationChangedEventListener =null; - if (this.optimizer !=null) { + public boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { + if (populationChangedEventListener == ea) { + populationChangedEventListener = null; + if (this.optimizer != null) { this.optimizer.removePopulationChangedEventListener(ea); } return true; } else { return false; } - } - + } + /** * */ @@ -103,165 +104,177 @@ public abstract class AbstractOptimizationParameters implements InterfaceOptimiz LOGGER.log(Level.WARNING, "Could not store instance object.", ex); } } - + @Override public void saveInstance() { String fileName = this.getClass().getSimpleName() + ".ser"; saveInstance(fileName); } - - @Override - public String toString() { - StringBuilder sBuilder = new StringBuilder(getName()); - sBuilder.append("\n"); - sBuilder.append("seed="); - sBuilder.append(randomSeed); - sBuilder.append("\nProblem: "); - sBuilder.append(BeanInspector.toString(problem)); - sBuilder.append("\nOptimizer: "); - sBuilder.append(BeanInspector.toString(optimizer)); - sBuilder.append("\nTerminator: "); - sBuilder.append(BeanInspector.toString(terminator)); - sBuilder.append("\n"); - return sBuilder.toString(); - } @Override - public void addInformableInstance(InterfaceNotifyOnInformers o) { - if (toInformAboutInformers==null) { - toInformAboutInformers=new LinkedList(); - } - if (!toInformAboutInformers.contains(o)) { - toInformAboutInformers.add(o); - } - o.setInformers(getInformerList()); - } - - @Override - public boolean removeInformableInstance(InterfaceNotifyOnInformers o) { - if (toInformAboutInformers==null) { - return false; - } - else { - return toInformAboutInformers.remove(o); - } - } - - private void fireNotifyOnInformers() { - if (toInformAboutInformers!=null) { - for (InterfaceNotifyOnInformers listener : toInformAboutInformers) { -listener.setInformers(getInformerList()); -} } - } + public String toString() { + StringBuilder sBuilder = new StringBuilder(getName()); + sBuilder.append("\n"); + sBuilder.append("seed="); + sBuilder.append(randomSeed); + sBuilder.append("\nProblem: "); + sBuilder.append(BeanInspector.toString(problem)); + sBuilder.append("\nOptimizer: "); + sBuilder.append(BeanInspector.toString(optimizer)); + sBuilder.append("\nTerminator: "); + sBuilder.append(BeanInspector.toString(terminator)); + sBuilder.append("\n"); + return sBuilder.toString(); + } @Override - public void setOptimizer(InterfaceOptimizer optimizer) { - this.optimizer = optimizer; - this.optimizer.setProblem(this.problem); - if (this.populationChangedEventListener != null) { - this.optimizer.addPopulationChangedEventListener(this.populationChangedEventListener); + public void addInformableInstance(InterfaceNotifyOnInformers o) { + if (toInformAboutInformers == null) { + toInformAboutInformers = new LinkedList(); + } + if (!toInformAboutInformers.contains(o)) { + toInformAboutInformers.add(o); + } + o.setInformers(getInformerList()); + } + + @Override + public boolean removeInformableInstance(InterfaceNotifyOnInformers o) { + if (toInformAboutInformers == null) { + return false; + } else { + return toInformAboutInformers.remove(o); + } + } + + private void fireNotifyOnInformers() { + if (toInformAboutInformers != null) { + for (InterfaceNotifyOnInformers listener : toInformAboutInformers) { + listener.setInformers(getInformerList()); } - fireNotifyOnInformers(); - } - - private List getInformerList() { - LinkedList ret = new LinkedList(); - if (problem instanceof InterfaceAdditionalPopulationInformer) { - ret.add(problem); - } - if (optimizer instanceof InterfaceAdditionalPopulationInformer) { - ret.add((InterfaceAdditionalPopulationInformer) optimizer); - } - return ret; - } + } + } @Override - public InterfaceOptimizer getOptimizer() { - return this.optimizer; - } - public String optimizerTipText() { - return "Choose an optimization strategy."; - } + public void setOptimizer(InterfaceOptimizer optimizer) { + this.optimizer = optimizer; + this.optimizer.setProblem(this.problem); + if (this.populationChangedEventListener != null) { + this.optimizer.addPopulationChangedEventListener(this.populationChangedEventListener); + } + fireNotifyOnInformers(); + } + + private List getInformerList() { + LinkedList ret = new LinkedList(); + if (problem instanceof InterfaceAdditionalPopulationInformer) { + ret.add(problem); + } + if (optimizer instanceof InterfaceAdditionalPopulationInformer) { + ret.add((InterfaceAdditionalPopulationInformer) optimizer); + } + return ret; + } @Override - public String getName() { - return "Optimization parameters"; - } + public InterfaceOptimizer getOptimizer() { + return this.optimizer; + } - /** - * This method will set the problem that is to be optimized. - * @param problem - */ - @Override - public void setProblem (InterfaceOptimizationProblem problem) { - this.problem = problem; - this.optimizer.setProblem(this.problem); - fireNotifyOnInformers(); - } - - @Override - public InterfaceOptimizationProblem getProblem() { - return this.problem; - } - @Override - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } + public String optimizerTipText() { + return "Choose an optimization strategy."; + } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ @Override - public void setSeed(long x) { - randomSeed = x; - } - - /** + public String getName() { + return "Optimization parameters"; + } + + /** + * This method will set the problem that is to be optimized. + * + * @param problem + */ + @Override + public void setProblem(InterfaceOptimizationProblem problem) { + this.problem = problem; + this.optimizer.setProblem(this.problem); + fireNotifyOnInformers(); + } + + @Override + public InterfaceOptimizationProblem getProblem() { + return this.problem; + } + + @Override + public String problemTipText() { + return "Choose the problem that is to optimize and the EA individual parameters."; + } + + /** + * This methods allow you to set and get the Seed for the Random Number Generator. + * + * @param x Long seed. + */ + @Override + public void setSeed(long x) { + randomSeed = x; + } + + /** * Returns the current seed for the random number generator. - * - * @return The current seed for the random number generator. - */ + * + * @return The current seed for the random number generator. + */ @Override - public long getSeed() { - return randomSeed; - } - - @Override - public String seedTipText() { - return "Random number seed, set to zero to use current system time."; - } + public long getSeed() { + return randomSeed; + } - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ @Override - public void setTerminator(InterfaceTerminator term) { - this.terminator = term; - } + public String seedTipText() { + return "Random number seed, set to zero to use current system time."; + } + + /** + * This method allows you to choose a termination criteria for the + * evolutionary algorithm. + * + * @param term The new terminator + */ @Override - public InterfaceTerminator getTerminator() { - return this.terminator; - } + public void setTerminator(InterfaceTerminator term) { + this.terminator = term; + } + @Override - public String terminatorTipText() { - return "Choose a termination criterion."; - } + public InterfaceTerminator getTerminator() { + return this.terminator; + } + + @Override + public String terminatorTipText() { + return "Choose a termination criterion."; + } @Override public InterfacePostProcessParams getPostProcessParams() { - return postProcessing; + return postProcessing; } + @Override public void setPostProcessParams(InterfacePostProcessParams ppp) { - postProcessing = ppp; + postProcessing = ppp; } + @Override public String postProcessParamsTipText() { - return "Parameters for the post processing step"; + return "Parameters for the post processing step"; } + @Override - public void setDoPostProcessing(boolean doPP){ - postProcessing.setDoPostProcessing(doPP); + public void setDoPostProcessing(boolean doPP) { + postProcessing.setDoPostProcessing(doPP); } } diff --git a/src/eva2/optimization/modules/DEParameters.java b/src/eva2/optimization/modules/DEParameters.java index f57188be..02cbbfc0 100644 --- a/src/eva2/optimization/modules/DEParameters.java +++ b/src/eva2/optimization/modules/DEParameters.java @@ -9,12 +9,14 @@ import eva2.optimization.problems.F1Problem; import eva2.optimization.strategies.DifferentialEvolution; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all DE parameters for the EvA +/** + * The class gives access to all DE parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -27,7 +29,7 @@ public class DEParameters extends AbstractOptimizationParameters implements Inte /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static DEParameters getInstance() { @@ -49,11 +51,11 @@ public class DEParameters extends AbstractOptimizationParameters implements Inte * */ public DEParameters() { - super(new DifferentialEvolution(), new F1Problem(), new EvaluationTerminator(1000)); + super(new DifferentialEvolution(), new F1Problem(), new EvaluationTerminator(1000)); } private DEParameters(DEParameters Source) { - super(Source); + super(Source); } @Override @@ -61,14 +63,18 @@ public class DEParameters extends AbstractOptimizationParameters implements Inte return new DEParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a Differential Evolution optimization method, limit DE to real-valued genotypes."; } - /** This method allows you to set the current optimizing algorithm + /** + * This method allows you to set the current optimizing algorithm + * * @param optimizer The new optimizing algorithm */ @Override @@ -76,71 +82,89 @@ public class DEParameters extends AbstractOptimizationParameters implements Inte // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { return ((DifferentialEvolution) this.optimizer).getPopulation(); } - - public void setPopulation(Population pop){ + + public void setPopulation(Population pop) { ((DifferentialEvolution) this.optimizer).setPopulation(pop); } - + public String populationTipText() { return "Edit the properties of the population used."; } - /** This method will set the amplication factor f. + /** + * This method will set the amplication factor f. + * * @param f */ - public void setF (double f) { + public void setF(double f) { ((DifferentialEvolution) this.optimizer).setF(f); } + public double getF() { return ((DifferentialEvolution) this.optimizer).getF(); } + public String fTipText() { return "F is a real and constant factor which controlls the ampllification of the differential variation."; } - /** This method will set the crossover probability + /** + * This method will set the crossover probability + * * @param k */ public void setK(double k) { ((DifferentialEvolution) this.optimizer).setK(k); } + public double getK() { return ((DifferentialEvolution) this.optimizer).getK(); } + public String kTipText() { return "Probability of alteration through DE1."; } - /** This method will set greediness to move towards the best + /** + * This method will set greediness to move towards the best + * * @param l */ - public void setLambda (double l) { + public void setLambda(double l) { ((DifferentialEvolution) this.optimizer).setLambda(l); } + public double getLambda() { return ((DifferentialEvolution) this.optimizer).getLambda(); } + public String lambdaTipText() { return "Enhance greediness through amplification of the differential vector to the best individual for DE2."; } - /** This method allows you to choose the type of Differential Evolution. - * @param s The type. + /** + * This method allows you to choose the type of Differential Evolution. + * + * @param s The type. */ public void setDEType(DETypeEnum s) { ((DifferentialEvolution) this.optimizer).setDEType(s); } + public DETypeEnum getDEType() { return ((DifferentialEvolution) this.optimizer).getDEType(); } + public String dETypeTipText() { return "Choose the type of Differential Evolution."; } diff --git a/src/eva2/optimization/modules/EPParameters.java b/src/eva2/optimization/modules/EPParameters.java index 244a6ed5..4a82af5b 100644 --- a/src/eva2/optimization/modules/EPParameters.java +++ b/src/eva2/optimization/modules/EPParameters.java @@ -9,13 +9,15 @@ import eva2.optimization.problems.F1Problem; import eva2.optimization.strategies.EvolutionaryProgramming; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; -/** The class gives access to all EP parameters for the EvA +/** + * The class gives access to all EP parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -27,10 +29,10 @@ public class EPParameters extends AbstractOptimizationParameters implements Inte private static final Logger LOGGER = Logger.getLogger(EPParameters.class.getName()); - + /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static EPParameters getInstance() { @@ -52,14 +54,14 @@ public class EPParameters extends AbstractOptimizationParameters implements Inte * */ public EPParameters() { - super(new EvolutionaryProgramming(), new F1Problem(), new EvaluationTerminator()); + super(new EvolutionaryProgramming(), new F1Problem(), new EvaluationTerminator()); } /** * */ private EPParameters(EPParameters Source) { - super(Source); + super(Source); } /** @@ -70,7 +72,9 @@ public class EPParameters extends AbstractOptimizationParameters implements Inte return new EPParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -83,30 +87,38 @@ public class EPParameters extends AbstractOptimizationParameters implements Inte // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((EvolutionaryProgramming)this.optimizer).getPopulation(); + return ((EvolutionaryProgramming) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((EvolutionaryProgramming)this.optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((EvolutionaryProgramming) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the population used."; } - /** Choose the type of environment selection to use. + /** + * Choose the type of environment selection to use. + * * @param selection */ public void setEnvironmentSelection(InterfaceSelection selection) { - ((EvolutionaryProgramming)this.optimizer).setEnvironmentSelection(selection); + ((EvolutionaryProgramming) this.optimizer).setEnvironmentSelection(selection); } + public InterfaceSelection getEnvironmentSelection() { - return ((EvolutionaryProgramming)this.optimizer).getEnvironmentSelection(); + return ((EvolutionaryProgramming) this.optimizer).getEnvironmentSelection(); } + public String environmentSelectionTipText() { return "Choose a method for selecting the reduced population."; } diff --git a/src/eva2/optimization/modules/GAParameters.java b/src/eva2/optimization/modules/GAParameters.java index 930e7cc1..9db11218 100644 --- a/src/eva2/optimization/modules/GAParameters.java +++ b/src/eva2/optimization/modules/GAParameters.java @@ -8,13 +8,15 @@ import eva2.optimization.problems.B1Problem; import eva2.optimization.strategies.GeneticAlgorithm; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; -/** The class gives access to all GA parameters for the EvA +/** + * The class gives access to all GA parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -23,12 +25,12 @@ import java.util.logging.Logger; * To change this template use File | Settings | File Templates. */ public class GAParameters extends AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable { - + private static final Logger LOGGER = Logger.getLogger(GAParameters.class.getName()); - + /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static GAParameters getInstance() { @@ -50,14 +52,14 @@ public class GAParameters extends AbstractOptimizationParameters implements Inte * */ public GAParameters() { - super(new GeneticAlgorithm(), new B1Problem(), new EvaluationTerminator()); + super(new GeneticAlgorithm(), new B1Problem(), new EvaluationTerminator()); } /** * */ private GAParameters(GAParameters Source) { - super(Source); + super(Source); } /** @@ -67,7 +69,10 @@ public class GAParameters extends AbstractOptimizationParameters implements Inte public Object clone() { return new GAParameters(this); } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -80,17 +85,21 @@ public class GAParameters extends AbstractOptimizationParameters implements Inte // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((GeneticAlgorithm)this.optimizer).getPopulation(); + return ((GeneticAlgorithm) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((GeneticAlgorithm)this.optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((GeneticAlgorithm) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the population used."; } @@ -108,57 +117,73 @@ public class GAParameters extends AbstractOptimizationParameters implements Inte // return "Select the normation method."; // } - /** Choose a parent selection method. + /** + * Choose a parent selection method. + * * @param selection */ public void setParentSelection(InterfaceSelection selection) { - ((GeneticAlgorithm)this.optimizer).setParentSelection(selection); + ((GeneticAlgorithm) this.optimizer).setParentSelection(selection); } + public InterfaceSelection getParentSelection() { - return ((GeneticAlgorithm)this.optimizer).getParentSelection(); + return ((GeneticAlgorithm) this.optimizer).getParentSelection(); } + public String parentSelectionTipText() { return "Choose a parent selection method."; } - /** Enable/disable elitism. + /** + * Enable/disable elitism. + * * @param elitism */ - public void setElitism (boolean elitism) { - ((GeneticAlgorithm)this.optimizer).setElitism(elitism); + public void setElitism(boolean elitism) { + ((GeneticAlgorithm) this.optimizer).setElitism(elitism); } + public boolean getElitism() { - return ((GeneticAlgorithm)this.optimizer).getElitism(); + return ((GeneticAlgorithm) this.optimizer).getElitism(); } + public String elitismTipText() { return "Enable/disable elitism."; } - /** The number of mating partners needed to create offsprings. + /** + * The number of mating partners needed to create offsprings. + * * @param partners */ public void setNumberOfPartners(int partners) { if (partners < 0) { partners = 0; } - ((GeneticAlgorithm)this.optimizer).setNumberOfPartners(partners); + ((GeneticAlgorithm) this.optimizer).setNumberOfPartners(partners); } + public int getNumberOfPartners() { - return ((GeneticAlgorithm)this.optimizer).getNumberOfPartners(); + return ((GeneticAlgorithm) this.optimizer).getNumberOfPartners(); } + public String numberOfPartnersTipText() { return "The number of mating partners needed to create offsprings."; } - /** Choose a selection method for selecting recombination partners for given parents. + /** + * Choose a selection method for selecting recombination partners for given parents. + * * @param selection */ public void setPartnerSelection(InterfaceSelection selection) { - ((GeneticAlgorithm)this.optimizer).setPartnerSelection(selection); + ((GeneticAlgorithm) this.optimizer).setPartnerSelection(selection); } + public InterfaceSelection getPartnerSelection() { - return ((GeneticAlgorithm)this.optimizer).getPartnerSelection(); + return ((GeneticAlgorithm) this.optimizer).getPartnerSelection(); } + public String partnerSelectionTipText() { return "Choose a selection method for selecting recombination partners for given parents."; } diff --git a/src/eva2/optimization/modules/GOModuleAdapter.java b/src/eva2/optimization/modules/GOModuleAdapter.java index 1bc90f09..69779598 100644 --- a/src/eva2/optimization/modules/GOModuleAdapter.java +++ b/src/eva2/optimization/modules/GOModuleAdapter.java @@ -1,6 +1,7 @@ package eva2.optimization.modules; import eva2.optimization.go.InterfaceOptimizationParameters; + import java.io.Serializable; @@ -21,8 +22,8 @@ public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapt /** * Starts a statistics GUI and the GOProcessor thread. * - * @param AdapterName the title of the ModulAdapter - * @param Client the client instance + * @param AdapterName the title of the ModulAdapter + * @param Client the client instance */ public GOModuleAdapter(String adapterName) { super(adapterName, "", OptimizationParameters.getInstance(), false); @@ -31,8 +32,8 @@ public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapt /** * Starts a statistics GUI and the GOProcessor thread with a given OptimizationParameters file. * - * @param AdapterName the title of the ModulAdapter - * @param Client the client instance + * @param AdapterName the title of the ModulAdapter + * @param Client the client instance */ public GOModuleAdapter(String adapterName, InterfaceOptimizationParameters goParams, String noGuiLogFile) { super(adapterName, "", goParams, false, noGuiLogFile); diff --git a/src/eva2/optimization/modules/GenericModuleAdapter.java b/src/eva2/optimization/modules/GenericModuleAdapter.java index c2b8d9e8..4ff2d45b 100644 --- a/src/eva2/optimization/modules/GenericModuleAdapter.java +++ b/src/eva2/optimization/modules/GenericModuleAdapter.java @@ -18,70 +18,70 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria public String helperFilename; JParaPanel jobPanel = null, paramPanel = null; - /** + /** * Constructor of the ModuleAdapter * - * @param adapterName The AdapterName - * @param helperFName Name of a HTML help file name - * @param params A parameter set describing the optimizer module + * @param adapterName The AdapterName + * @param helperFName Name of a HTML help file name + * @param params A parameter set describing the optimizer module * @param optimizerExpert Set to true if setting the optimizer is an expert option being hidden - * from the gui - * @param noGUIStatOut If null, statistics with GUI are used, else the standalone statistics - * with given output filename. + * from the gui + * @param noGUIStatOut If null, statistics with GUI are used, else the standalone statistics + * with given output filename. */ public GenericModuleAdapter(String adapterName, String helperFName, InterfaceOptimizationParameters params, boolean optimizerExpert, String noGUIStatOut) { remoteModuleAdapter = this; this.adapterName = adapterName; helperFilename = helperFName; - if (noGUIStatOut==null) { - statisticsModule = new StatisticsWithGUI(); + if (noGUIStatOut == null) { + statisticsModule = new StatisticsWithGUI(); } else { - statisticsModule = new StatisticsStandalone(noGUIStatOut); + statisticsModule = new StatisticsStandalone(noGUIStatOut); } processor = new Processor(statisticsModule, this, params); - + // the statistics want to be informed if the strategy or the optimizer (which provide statistical data as InterfaceAdditionalInformer) change. // THIS is now done directly in the constructor of a Processor // if (m_StatisticsModul.getStatisticsParameter() instanceof InterfaceNotifyOnInformers) // params.addInformableInstance((InterfaceNotifyOnInformers)m_StatisticsModul.getStatisticsParameter()); // this prevents the optimizer property to be shown by the GOE if optimizerExpert is true - GenericObjectEditor.setExpertProperty(params.getClass(), "optimizer", optimizerExpert); - - ((Processor) processor).start(); + GenericObjectEditor.setExpertProperty(params.getClass(), "optimizer", optimizerExpert); + + ((Processor) processor).start(); } - - /** + + /** * Constructor of the ModuleAdapter. Convenience constructor with GUI. - * - * @param adapterName The AdapterName - * @param helperFName name of a html help file name - * @param Client The client to serve - * @param params a parameter set describing the optimizer module - * @param optimizerExpert set to true if setting the optimizer is an expert option being hidden from the gui + * + * @param adapterName The AdapterName + * @param helperFName name of a html help file name + * @param Client The client to serve + * @param params a parameter set describing the optimizer module + * @param optimizerExpert set to true if setting the optimizer is an expert option being hidden from the gui */ public GenericModuleAdapter(String adapterName, String helperFName, InterfaceOptimizationParameters params, boolean optimizerExpert) { - this(adapterName, helperFName, params, optimizerExpert, null); + this(adapterName, helperFName, params, optimizerExpert, null); } - - /** + + /** * This method returns a newly created GUI element containing the EvA button panel - * and two JParaPanel instances representing the module parameters (e.g. GO) + * and two JParaPanel instances representing the module parameters (e.g. GO) * and the statistics parameters. * If the statistics are not of type StatisticsWithGUI, it is assumed that no GUI is * desired (and this method should not be called). - * + * + * @return the EvATabbedFrameMaker * @see JParaPanel * @see EvAModuleButtonPanelMaker * @see StatisticsWithGUI - * @return the EvATabbedFrameMaker */ @Override public EvATabbedFrameMaker getModuleFrame() { - if (!(statisticsModule instanceof StatisticsWithGUI)) { - System.err.println("Error: Unable to create Frame when startet with noGUI option (GenericModuleAdapter)!"); - return null; - } + if (!(statisticsModule instanceof StatisticsWithGUI)) { + System.err.println("Error: Unable to create Frame when startet with noGUI option (GenericModuleAdapter)!"); + return null; + } EvATabbedFrameMaker frmMkr = new EvATabbedFrameMaker(); InterfaceStatisticsParameter Stat = ((StatisticsWithGUI) statisticsModule).getStatisticsParameter(); @@ -89,17 +89,17 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria ButtonPanel.setHelperFilename(helperFilename); frmMkr.addPanelMaker(ButtonPanel); InterfaceOptimizationParameters goParams = ((Processor) processor).getGOParams(); - - frmMkr.addPanelMaker(paramPanel = new JParaPanel(goParams, goParams.getName())); - frmMkr.addPanelMaker(new JParaPanel(Stat, Stat.getName())); + frmMkr.addPanelMaker(paramPanel = new JParaPanel(goParams, goParams.getName())); + + frmMkr.addPanelMaker(new JParaPanel(Stat, Stat.getName())); jobList = new OptimizationJobList(new OptimizationJob[]{}); jobList.setModule(this); jobList.addTextListener((AbstractStatistics) ((Processor) processor).getStatistics()); - - jobPanel = new JParaPanel(jobList, jobList.getName()); + + jobPanel = new JParaPanel(jobList, jobList.getName()); frmMkr.addPanelMaker(jobPanel); diff --git a/src/eva2/optimization/modules/HCModuleAdapter.java b/src/eva2/optimization/modules/HCModuleAdapter.java index fb12fe2c..eed283fc 100644 --- a/src/eva2/optimization/modules/HCModuleAdapter.java +++ b/src/eva2/optimization/modules/HCModuleAdapter.java @@ -11,7 +11,7 @@ public class HCModuleAdapter extends GenericModuleAdapter implements ModuleAdapt * Constructor of the ModuleAdapter * * @param AdapterName The AdapterName - * @param Client The client to serve + * @param Client The client to serve */ public HCModuleAdapter(String adapterName) { super(adapterName, "HC.html", HCParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/HCParameters.java b/src/eva2/optimization/modules/HCParameters.java index 633b152a..8202c36e 100644 --- a/src/eva2/optimization/modules/HCParameters.java +++ b/src/eva2/optimization/modules/HCParameters.java @@ -7,13 +7,15 @@ import eva2.optimization.problems.B1Problem; import eva2.optimization.strategies.HillClimbing; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all HC parameters for the EvA +/** + * The class gives access to all HC parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -25,7 +27,7 @@ public class HCParameters extends AbstractOptimizationParameters implements Inte /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static HCParameters getInstance() { @@ -42,12 +44,12 @@ public class HCParameters extends AbstractOptimizationParameters implements Inte } return instance; } - + /** * */ public HCParameters() { - super(new HillClimbing(), new B1Problem(), new EvaluationTerminator()); + super(new HillClimbing(), new B1Problem(), new EvaluationTerminator()); } /** @@ -56,6 +58,7 @@ public class HCParameters extends AbstractOptimizationParameters implements Inte private HCParameters(HCParameters Source) { super(Source); } + /** * */ @@ -63,7 +66,10 @@ public class HCParameters extends AbstractOptimizationParameters implements Inte public Object clone() { return new HCParameters(this); } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -76,17 +82,21 @@ public class HCParameters extends AbstractOptimizationParameters implements Inte // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { return ((HillClimbing) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ + + public void setPopulation(Population pop) { ((HillClimbing) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the population used."; } diff --git a/src/eva2/optimization/modules/MCModuleAdapter.java b/src/eva2/optimization/modules/MCModuleAdapter.java index 1e8b9831..d4382a61 100644 --- a/src/eva2/optimization/modules/MCModuleAdapter.java +++ b/src/eva2/optimization/modules/MCModuleAdapter.java @@ -11,7 +11,7 @@ public class MCModuleAdapter extends GenericModuleAdapter implements ModuleAdapt * Constructor of the ModuleAdapter. * * @param adapterName The AdapterName - * @param client The client to serve + * @param client The client to serve */ public MCModuleAdapter(String adapterName) { super(adapterName, "MC.html", MCParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/MCParameters.java b/src/eva2/optimization/modules/MCParameters.java index 74f5100d..8088d738 100644 --- a/src/eva2/optimization/modules/MCParameters.java +++ b/src/eva2/optimization/modules/MCParameters.java @@ -7,12 +7,14 @@ import eva2.optimization.problems.B1Problem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.MonteCarloSearch; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all HC parameters for the EvA +/** + * The class gives access to all HC parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -21,10 +23,10 @@ import java.util.logging.Level; * To change this template use File | Settings | File Templates. */ public class MCParameters extends AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable { - + /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static MCParameters getInstance() { @@ -41,16 +43,16 @@ public class MCParameters extends AbstractOptimizationParameters implements Inte } return instance; } - + /** * */ - public MCParameters() { - super(new MonteCarloSearch(), new B1Problem(), new EvaluationTerminator()); + public MCParameters() { + super(new MonteCarloSearch(), new B1Problem(), new EvaluationTerminator()); } private MCParameters(MCParameters Source) { - super(Source); + super(Source); } /** @@ -61,7 +63,9 @@ public class MCParameters extends AbstractOptimizationParameters implements Inte return new MCParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -74,17 +78,21 @@ public class MCParameters extends AbstractOptimizationParameters implements Inte } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((MonteCarloSearch)this.optimizer).getPopulation(); + return ((MonteCarloSearch) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((MonteCarloSearch)this.optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((MonteCarloSearch) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the population used."; } diff --git a/src/eva2/optimization/modules/MOEAModuleAdapter.java b/src/eva2/optimization/modules/MOEAModuleAdapter.java index 7be4eb51..f84558e0 100644 --- a/src/eva2/optimization/modules/MOEAModuleAdapter.java +++ b/src/eva2/optimization/modules/MOEAModuleAdapter.java @@ -14,7 +14,7 @@ public class MOEAModuleAdapter extends GenericModuleAdapter implements Serializa * Constructor of the ModuleAdapter. * * @param AdapterName The AdapterName - * @param Client The client to serve + * @param Client The client to serve */ public MOEAModuleAdapter(String adapterName) { super(adapterName, "MOEA.html", MOEAParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/MOEAParameters.java b/src/eva2/optimization/modules/MOEAParameters.java index 6a1abf59..168b429c 100644 --- a/src/eva2/optimization/modules/MOEAParameters.java +++ b/src/eva2/optimization/modules/MOEAParameters.java @@ -9,12 +9,14 @@ import eva2.optimization.problems.TF1Problem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.MultiObjectiveEA; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all MOEA parameters for the EvA +/** + * The class gives access to all MOEA parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -26,7 +28,7 @@ public class MOEAParameters extends AbstractOptimizationParameters implements In /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static MOEAParameters getInstance() { @@ -45,11 +47,11 @@ public class MOEAParameters extends AbstractOptimizationParameters implements In } public MOEAParameters() { - super(new MultiObjectiveEA(), new TF1Problem(), new EvaluationTerminator(1000)); + super(new MultiObjectiveEA(), new TF1Problem(), new EvaluationTerminator(1000)); } private MOEAParameters(MOEAParameters Source) { - super(Source); + super(Source); } @Override @@ -57,89 +59,111 @@ public class MOEAParameters extends AbstractOptimizationParameters implements In return new MOEAParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a multi-objective evoluationary algorithm, limit MOEA to multi-objective problems (due to the given framework only the fitness of objective one will be plotted)."; } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((MultiObjectiveEA)this.optimizer).getPopulation(); + return ((MultiObjectiveEA) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((MultiObjectiveEA)this.optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((MultiObjectiveEA) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the Population used."; } - /** This method allows you to set/get the optimizing technique to use. + /** + * This method allows you to set/get the optimizing technique to use. + * * @return The current optimizing method */ @Override public InterfaceOptimizer getOptimizer() { - return ((MultiObjectiveEA)this.optimizer).getOptimizer(); + return ((MultiObjectiveEA) this.optimizer).getOptimizer(); } + @Override - public void setOptimizer(InterfaceOptimizer b){ - ((MultiObjectiveEA)this.optimizer).setOptimizer(b); + public void setOptimizer(InterfaceOptimizer b) { + ((MultiObjectiveEA) this.optimizer).setOptimizer(b); } + @Override public String optimizerTipText() { return "Choose a population based optimizing technique to use."; } - /** This method allows you to set/get the archiving strategy to use. + /** + * This method allows you to set/get the archiving strategy to use. + * * @return The current optimizing method */ public InterfaceArchiving getArchivingStrategy() { - return ((MultiObjectiveEA)this.optimizer).getArchivingStrategy(); + return ((MultiObjectiveEA) this.optimizer).getArchivingStrategy(); } - public void setArchivingStrategy(InterfaceArchiving b){ - ((MultiObjectiveEA)this.optimizer).setArchivingStrategy(b); + + public void setArchivingStrategy(InterfaceArchiving b) { + ((MultiObjectiveEA) this.optimizer).setArchivingStrategy(b); } + public String archivingStrategyTipText() { return "Choose the archiving strategy."; } - /** This method allows you to set/get the Information Retrieval strategy to use. + /** + * This method allows you to set/get the Information Retrieval strategy to use. + * * @return The current optimizing method */ public InterfaceInformationRetrieval getInformationRetrieval() { - return ((MultiObjectiveEA)this.optimizer).getInformationRetrieval(); + return ((MultiObjectiveEA) this.optimizer).getInformationRetrieval(); } - public void setInformationRetrieval(InterfaceInformationRetrieval b){ - ((MultiObjectiveEA)this.optimizer).setInformationRetrieval(b); + + public void setInformationRetrieval(InterfaceInformationRetrieval b) { + ((MultiObjectiveEA) this.optimizer).setInformationRetrieval(b); } + public String informationRetrievalTipText() { return "Choose the Information Retrieval strategy."; } - /** This method allows you to set/get the size of the archive. + /** + * This method allows you to set/get the size of the archive. + * * @return The current optimizing method */ public int getArchiveSize() { - Population archive = ((MultiObjectiveEA)this.optimizer).getPopulation().getArchive(); + Population archive = ((MultiObjectiveEA) this.optimizer).getPopulation().getArchive(); if (archive == null) { archive = new Population(); - ((MultiObjectiveEA)this.optimizer).getPopulation().SetArchive(archive); + ((MultiObjectiveEA) this.optimizer).getPopulation().SetArchive(archive); } - return ((MultiObjectiveEA)this.optimizer).getArchiveSize(); + return ((MultiObjectiveEA) this.optimizer).getArchiveSize(); } - public void setArchiveSize(int b){ - Population archive = ((MultiObjectiveEA)this.optimizer).getPopulation().getArchive(); + + public void setArchiveSize(int b) { + Population archive = ((MultiObjectiveEA) this.optimizer).getPopulation().getArchive(); if (archive == null) { archive = new Population(); - ((MultiObjectiveEA)this.optimizer).getPopulation().SetArchive(archive); + ((MultiObjectiveEA) this.optimizer).getPopulation().SetArchive(archive); } - ((MultiObjectiveEA)this.optimizer).getPopulation().getArchive().setTargetSize(b); + ((MultiObjectiveEA) this.optimizer).getPopulation().getArchive().setTargetSize(b); } + public String archiveSizeTipText() { return "Choose the size of the archive."; } diff --git a/src/eva2/optimization/modules/ModuleAdapter.java b/src/eva2/optimization/modules/ModuleAdapter.java index c98c9fa3..9a7e8db4 100644 --- a/src/eva2/optimization/modules/ModuleAdapter.java +++ b/src/eva2/optimization/modules/ModuleAdapter.java @@ -9,6 +9,7 @@ package eva2.optimization.modules; * $Date: 2007-11-21 18:06:36 +0100 (Wed, 21 Nov 2007) $ * $Author: mkron $ */ + import eva2.gui.EvATabbedFrameMaker; import eva2.optimization.OptimizationStateListener; import eva2.optimization.stat.OptimizationJob; diff --git a/src/eva2/optimization/modules/OptimizationParameters.java b/src/eva2/optimization/modules/OptimizationParameters.java index cd047021..5bf6bf0b 100644 --- a/src/eva2/optimization/modules/OptimizationParameters.java +++ b/src/eva2/optimization/modules/OptimizationParameters.java @@ -8,6 +8,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.optimization.strategies.GeneticAlgorithm; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; @@ -18,10 +19,11 @@ import java.util.logging.Level; * Created by IntelliJ IDEA. * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture + * * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 306 $ - * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ - * $Author: mkron $ + * @version: $Revision: 306 $ + * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ + * $Author: mkron $ */ public class OptimizationParameters extends AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable { @@ -31,9 +33,9 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple /** * Create an instance from a given serialized parameter file. - * + * * @param serParamFile - * @param casually if true, standard parameters are used quietly if the params cannot be loaded + * @param casually if true, standard parameters are used quietly if the params cannot be loaded * @return a OptimizationParameters instance */ public static OptimizationParameters getInstance(String serParamFile, final boolean casually) { @@ -52,19 +54,20 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple } public OptimizationParameters() { - super(new GeneticAlgorithm(), new F1Problem(), new EvaluationTerminator(1000)); + super(new GeneticAlgorithm(), new F1Problem(), new EvaluationTerminator(1000)); } - + public OptimizationParameters(InterfaceOptimizer opt, InterfaceOptimizationProblem prob, InterfaceTerminator term) { - super(opt, prob, term); + super(opt, prob, term); } - + /** * */ private OptimizationParameters(OptimizationParameters parameters) { - super(parameters); + super(parameters); } + /** * */ @@ -72,6 +75,7 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple public String getName() { return "Optimization parameters"; } + /** * */ @@ -79,8 +83,10 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple public Object clone() { return new OptimizationParameters(this); } - - /** This method returns a global info string. + + /** + * This method returns a global info string. + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/modules/PBILModuleAdapter.java b/src/eva2/optimization/modules/PBILModuleAdapter.java index 6ef34edb..a62b47d0 100644 --- a/src/eva2/optimization/modules/PBILModuleAdapter.java +++ b/src/eva2/optimization/modules/PBILModuleAdapter.java @@ -12,7 +12,7 @@ public class PBILModuleAdapter extends GenericModuleAdapter implements ModuleAda * Constructor of the ModuleAdapter * * @param AdapterName The AdapterName - * @param Client The client to serve + * @param Client The client to serve */ public PBILModuleAdapter(String adapterName) { super(adapterName, "PBIL.html", PBILParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/PBILParameters.java b/src/eva2/optimization/modules/PBILParameters.java index c7642033..70eee77e 100644 --- a/src/eva2/optimization/modules/PBILParameters.java +++ b/src/eva2/optimization/modules/PBILParameters.java @@ -8,13 +8,15 @@ import eva2.optimization.problems.B1Problem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.PopulationBasedIncrementalLearning; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all PBIL parameters for the EvA +/** + * The class gives access to all PBIL parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -26,7 +28,7 @@ public class PBILParameters extends AbstractOptimizationParameters implements In /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static PBILParameters getInstance() { @@ -45,135 +47,165 @@ public class PBILParameters extends AbstractOptimizationParameters implements In } public PBILParameters() { - super(new PopulationBasedIncrementalLearning(), new B1Problem(), new EvaluationTerminator(1000)); + super(new PopulationBasedIncrementalLearning(), new B1Problem(), new EvaluationTerminator(1000)); } private PBILParameters(PBILParameters Source) { - super(Source); + super(Source); } + @Override public Object clone() { return new PBILParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ // public static String globalInfo() { // return ((PopulationBasedIncrementalLearning)this.optimizer).globalInfo(); // } - @Override public void setOptimizer(InterfaceOptimizer optimizer) { // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getPopulation(); + return ((PopulationBasedIncrementalLearning) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((PopulationBasedIncrementalLearning)this.optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((PopulationBasedIncrementalLearning) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the population used."; } - /** This method will set the selection method that is to be used + /** + * This method will set the selection method that is to be used + * * @param selection */ public void setSelectionMethod(InterfaceSelection selection) { - ((PopulationBasedIncrementalLearning)this.optimizer).setSelectionMethod(selection); + ((PopulationBasedIncrementalLearning) this.optimizer).setSelectionMethod(selection); } + public InterfaceSelection getSelectionMethod() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getSelectionMethod(); + return ((PopulationBasedIncrementalLearning) this.optimizer).getSelectionMethod(); } + public String selectionMethodTipText() { return "Choose a selection method."; } - /** Enable/disable elitism. + /** + * Enable/disable elitism. + * * @param elitism */ - public void setElitism (boolean elitism) { - ((PopulationBasedIncrementalLearning)this.optimizer).setElitism(elitism); + public void setElitism(boolean elitism) { + ((PopulationBasedIncrementalLearning) this.optimizer).setElitism(elitism); } + public boolean getElitism() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getElitism(); + return ((PopulationBasedIncrementalLearning) this.optimizer).getElitism(); } + public String elitismTipText() { return "Enable/disable elitism."; } - /** This method will set the learning rate for PBIL + /** + * This method will set the learning rate for PBIL + * * @param LearningRate */ - public void setLearningRate (double LearningRate) { + public void setLearningRate(double LearningRate) { if (LearningRate < 0) { LearningRate = 0; } - ((PopulationBasedIncrementalLearning)this.optimizer).setLearningRate(LearningRate); + ((PopulationBasedIncrementalLearning) this.optimizer).setLearningRate(LearningRate); } + public double getLearningRate() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getLearningRate(); + return ((PopulationBasedIncrementalLearning) this.optimizer).getLearningRate(); } + public String learningRateTipText() { return "The learing rate of PBIL."; } - /** This method will set the mutation rate for PBIL + /** + * This method will set the mutation rate for PBIL + * * @param m */ - public void setMutationRate (double m) { + public void setMutationRate(double m) { if (m < 0) { m = 0; } if (m > 1) { m = 1; } - ((PopulationBasedIncrementalLearning)this.optimizer).setMutationRate(m); + ((PopulationBasedIncrementalLearning) this.optimizer).setMutationRate(m); - } - public double getMutationRate() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getMutationRate(); } + + public double getMutationRate() { + return ((PopulationBasedIncrementalLearning) this.optimizer).getMutationRate(); + } + public String mutationRateTipText() { return "The mutation rate of PBIL."; } - /** This method will set the mutation sigma for PBIL + /** + * This method will set the mutation sigma for PBIL + * * @param m */ - public void setMutateSigma (double m) { + public void setMutateSigma(double m) { if (m < 0) { m = 0; } - ((PopulationBasedIncrementalLearning)this.optimizer).setMutateSigma(m); + ((PopulationBasedIncrementalLearning) this.optimizer).setMutateSigma(m); } + public double getMutateSigma() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getMutateSigma(); + return ((PopulationBasedIncrementalLearning) this.optimizer).getMutateSigma(); } + public String mutateSigmaTipText() { return "Set the sigma for the mutation of the probability vector."; } - /** This method will set the number of positive samples for PBIL + /** + * This method will set the number of positive samples for PBIL + * * @param PositiveSamples */ - public void setPositiveSamples (int PositiveSamples) { + public void setPositiveSamples(int PositiveSamples) { if (PositiveSamples < 1) { PositiveSamples = 1; } - ((PopulationBasedIncrementalLearning)this.optimizer).setPositiveSamples(PositiveSamples); + ((PopulationBasedIncrementalLearning) this.optimizer).setPositiveSamples(PositiveSamples); } + public int getPositiveSamples() { - return ((PopulationBasedIncrementalLearning)this.optimizer).getPositiveSamples(); + return ((PopulationBasedIncrementalLearning) this.optimizer).getPositiveSamples(); } + public String positiveSamplesTipText() { return "The number of positive samples that update the PBIL vector."; } diff --git a/src/eva2/optimization/modules/PSOModuleAdapter.java b/src/eva2/optimization/modules/PSOModuleAdapter.java index 24de1fe4..9c9d9ed2 100644 --- a/src/eva2/optimization/modules/PSOModuleAdapter.java +++ b/src/eva2/optimization/modules/PSOModuleAdapter.java @@ -12,7 +12,7 @@ public class PSOModuleAdapter extends GenericModuleAdapter implements ModuleAdap * Constructor of the ModulAdapter. * * @param AdapterName The AdapterName - * @param Client The client to serve + * @param Client The client to serve */ public PSOModuleAdapter(String adapterName) { super(adapterName, "PSO.html", PSOParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/PSOParameters.java b/src/eva2/optimization/modules/PSOParameters.java index f318c02f..632841ee 100644 --- a/src/eva2/optimization/modules/PSOParameters.java +++ b/src/eva2/optimization/modules/PSOParameters.java @@ -11,12 +11,14 @@ import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.ParticleSwarmOptimization; import eva2.tools.SelectedTag; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all PSO parameters for the EvA +/** + * The class gives access to all PSO parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -28,7 +30,7 @@ public class PSOParameters extends AbstractOptimizationParameters implements Int /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static PSOParameters getInstance() { @@ -45,16 +47,16 @@ public class PSOParameters extends AbstractOptimizationParameters implements Int } return instance; } - + /** * */ public PSOParameters() { - super(new ParticleSwarmOptimization(), new F1Problem(), new EvaluationTerminator()); + super(new ParticleSwarmOptimization(), new F1Problem(), new EvaluationTerminator()); } private PSOParameters(PSOParameters Source) { - super(Source); + super(Source); } @Override @@ -62,207 +64,250 @@ public class PSOParameters extends AbstractOptimizationParameters implements Int return new PSOParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return ParticleSwarmOptimization.globalInfo(); } - /** - * Take care that all properties which may be hidden (and currently are) send a "hide" message to the Java Bean properties. - * This is called by PropertySheetPanel in use with the GenericObjectEditor. - */ - public void hideHideable() { - setCheckSpeedLimit(isCheckSpeedLimit()); - setTopology(getTopology()); - } + /** + * Take care that all properties which may be hidden (and currently are) send a "hide" message to the Java Bean properties. + * This is called by PropertySheetPanel in use with the GenericObjectEditor. + */ + public void hideHideable() { + setCheckSpeedLimit(isCheckSpeedLimit()); + setTopology(getTopology()); + } @Override public void setOptimizer(InterfaceOptimizer optimizer) { // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((ParticleSwarmOptimization)this.optimizer).getPopulation(); + return ((ParticleSwarmOptimization) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((ParticleSwarmOptimization)this.optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((ParticleSwarmOptimization) this.optimizer).setPopulation(pop); } + public String populationTipText() { return "Edit the properties of the population used."; } - /** This method will set the initial velocity + /** + * This method will set the initial velocity + * * @param f */ - public void setInitialVelocity (double f) { - ((ParticleSwarmOptimization)this.optimizer).setInitialVelocity(f); - } - public double getInitialVelocity() { - return ((ParticleSwarmOptimization)this.optimizer).getInitialVelocity(); - } - public String initialVelocityTipText() { - return ((ParticleSwarmOptimization)this.optimizer).initialVelocityTipText(); + public void setInitialVelocity(double f) { + ((ParticleSwarmOptimization) this.optimizer).setInitialVelocity(f); } - /** This method will set the speed limit + public double getInitialVelocity() { + return ((ParticleSwarmOptimization) this.optimizer).getInitialVelocity(); + } + + public String initialVelocityTipText() { + return ((ParticleSwarmOptimization) this.optimizer).initialVelocityTipText(); + } + + /** + * This method will set the speed limit + * * @param k */ - public void setSpeedLimit (double k) { - ((ParticleSwarmOptimization)this.optimizer).setSpeedLimit(k); - } - public double getSpeedLimit() { - return ((ParticleSwarmOptimization)this.optimizer).getSpeedLimit(); - } - public String speedLimitTipText() { - return ((ParticleSwarmOptimization)this.optimizer).speedLimitTipText(); + public void setSpeedLimit(double k) { + ((ParticleSwarmOptimization) this.optimizer).setSpeedLimit(k); } - /** This method will set the inertness + public double getSpeedLimit() { + return ((ParticleSwarmOptimization) this.optimizer).getSpeedLimit(); + } + + public String speedLimitTipText() { + return ((ParticleSwarmOptimization) this.optimizer).speedLimitTipText(); + } + + /** + * This method will set the inertness + * * @param k */ public void setInertnessOrChi(double k) { // if (k < 0) k = 0; // if (k > 1) k = 1; - ((ParticleSwarmOptimization)this.optimizer).setInertnessOrChi(k); + ((ParticleSwarmOptimization) this.optimizer).setInertnessOrChi(k); } - + public double getInertnessOrChi() { - return ((ParticleSwarmOptimization)this.optimizer).getInertnessOrChi(); + return ((ParticleSwarmOptimization) this.optimizer).getInertnessOrChi(); } - + public String inertnessOrChiTipText() { - return ((ParticleSwarmOptimization)this.optimizer).inertnessOrChiTipText(); + return ((ParticleSwarmOptimization) this.optimizer).inertnessOrChiTipText(); } - /** This method will set greediness to move towards the best solution + /** + * This method will set greediness to move towards the best solution * based on the cognition model + * * @param l */ - public void setPhi1 (double l) { - ((ParticleSwarmOptimization)this.optimizer).setPhi1(l); + public void setPhi1(double l) { + ((ParticleSwarmOptimization) this.optimizer).setPhi1(l); } + public double getPhi1() { - return ((ParticleSwarmOptimization)this.optimizer).getPhi1(); - } - public String phi1TipText() { - return ((ParticleSwarmOptimization)this.optimizer).phi1TipText(); + return ((ParticleSwarmOptimization) this.optimizer).getPhi1(); } - /** This method will set greediness to move towards the best solution + public String phi1TipText() { + return ((ParticleSwarmOptimization) this.optimizer).phi1TipText(); + } + + /** + * This method will set greediness to move towards the best solution * based on the social model + * * @param l */ - public void setPhi2 (double l) { - ((ParticleSwarmOptimization)this.optimizer).setPhi2(l); - } - public double getPhi2() { - return ((ParticleSwarmOptimization)this.optimizer).getPhi2(); - } - public String phi2TipText() { - return ((ParticleSwarmOptimization)this.optimizer).phi2TipText(); + public void setPhi2(double l) { + ((ParticleSwarmOptimization) this.optimizer).setPhi2(l); } - - /** Toggle Check Constraints. - * @param s Check Constraints. - */ - public void setCheckRange(boolean s) { - ((ParticleSwarmOptimization)this.optimizer).setCheckRange(s); - } - public boolean isCheckRange() { - return ((ParticleSwarmOptimization)this.optimizer).isCheckRange(); - } - public String checkConstraintsTipText() { - return ((ParticleSwarmOptimization)this.optimizer).checkRangeTipText(); - } - - /** This method allows you to choose the topology type. - * @param t The type. + public double getPhi2() { + return ((ParticleSwarmOptimization) this.optimizer).getPhi2(); + } + + public String phi2TipText() { + return ((ParticleSwarmOptimization) this.optimizer).phi2TipText(); + } + + + /** + * Toggle Check Constraints. + * + * @param s Check Constraints. + */ + public void setCheckRange(boolean s) { + ((ParticleSwarmOptimization) this.optimizer).setCheckRange(s); + } + + public boolean isCheckRange() { + return ((ParticleSwarmOptimization) this.optimizer).isCheckRange(); + } + + public String checkConstraintsTipText() { + return ((ParticleSwarmOptimization) this.optimizer).checkRangeTipText(); + } + + /** + * This method allows you to choose the topology type. + * + * @param t The type. */ public void setTopology(PSOTopologyEnum t) { - ((ParticleSwarmOptimization)this.optimizer).setTopology(t); - ((ParticleSwarmOptimization)this.optimizer).setGOEShowProperties(getClass()); - } - public PSOTopologyEnum getTopology() { - return ((ParticleSwarmOptimization)this.optimizer).getTopology(); - } - public String topologyTipText() { - return ((ParticleSwarmOptimization)this.optimizer).topologyTipText(); + ((ParticleSwarmOptimization) this.optimizer).setTopology(t); + ((ParticleSwarmOptimization) this.optimizer).setGOEShowProperties(getClass()); } - /** The range of the local neighbourhood. - * @param s The range. + public PSOTopologyEnum getTopology() { + return ((ParticleSwarmOptimization) this.optimizer).getTopology(); + } + + public String topologyTipText() { + return ((ParticleSwarmOptimization) this.optimizer).topologyTipText(); + } + + /** + * The range of the local neighbourhood. + * + * @param s The range. */ public void setTopologyRange(int s) { - ((ParticleSwarmOptimization)this.optimizer).setTopologyRange(s); + ((ParticleSwarmOptimization) this.optimizer).setTopologyRange(s); } + public int getTopologyRange() { - return ((ParticleSwarmOptimization)this.optimizer).getTopologyRange(); + return ((ParticleSwarmOptimization) this.optimizer).getTopologyRange(); } + public String topologyRangeTipText() { - return ((ParticleSwarmOptimization)this.optimizer).topologyRangeTipText(); + return ((ParticleSwarmOptimization) this.optimizer).topologyRangeTipText(); } - - public double getSubSwarmRadius() { - return ((ParticleSwarmOptimization)this.optimizer).getSubSwarmRadius(); - } - public void setSubSwarmRadius(double radius) { - ((ParticleSwarmOptimization)this.optimizer).setSubSwarmRadius(radius); - } - public String subSwarmRadiusTipText() { - return ((ParticleSwarmOptimization)this.optimizer).subSwarmRadiusTipText(); - } - - public int getMaxSubSwarmSize() { - return ((ParticleSwarmOptimization)this.optimizer).getMaxSubSwarmSize(); - } - public void setMaxSubSwarmSize(int subSize) { - ((ParticleSwarmOptimization)this.optimizer).setMaxSubSwarmSize(subSize); - } - public String maxSubSwarmSizeTipText() { - return ((ParticleSwarmOptimization)this.optimizer).maxSubSwarmSizeTipText(); - } - - /** - * @return the checkSpeedLimit - **/ - public boolean isCheckSpeedLimit() { - return ((ParticleSwarmOptimization)this.optimizer).isCheckSpeedLimit(); - } - /** - * @param checkSpeedLimit the checkSpeedLimit to set - **/ - public void setCheckSpeedLimit(boolean checkSpeedLimit) { - ((ParticleSwarmOptimization)this.optimizer).setCheckSpeedLimit(checkSpeedLimit); - GenericObjectEditor.setHideProperty(getClass(), "speedLimit", !checkSpeedLimit); - } - - public String checkSpeedLimitTipText() { - return ((ParticleSwarmOptimization)this.optimizer).checkSpeedLimitTipText(); - } - - /** This method allows you to choose the algorithm type. - * @param s The type. + + public double getSubSwarmRadius() { + return ((ParticleSwarmOptimization) this.optimizer).getSubSwarmRadius(); + } + + public void setSubSwarmRadius(double radius) { + ((ParticleSwarmOptimization) this.optimizer).setSubSwarmRadius(radius); + } + + public String subSwarmRadiusTipText() { + return ((ParticleSwarmOptimization) this.optimizer).subSwarmRadiusTipText(); + } + + public int getMaxSubSwarmSize() { + return ((ParticleSwarmOptimization) this.optimizer).getMaxSubSwarmSize(); + } + + public void setMaxSubSwarmSize(int subSize) { + ((ParticleSwarmOptimization) this.optimizer).setMaxSubSwarmSize(subSize); + } + + public String maxSubSwarmSizeTipText() { + return ((ParticleSwarmOptimization) this.optimizer).maxSubSwarmSizeTipText(); + } + + /** + * @return the checkSpeedLimit + */ + public boolean isCheckSpeedLimit() { + return ((ParticleSwarmOptimization) this.optimizer).isCheckSpeedLimit(); + } + + /** + * @param checkSpeedLimit the checkSpeedLimit to set + */ + public void setCheckSpeedLimit(boolean checkSpeedLimit) { + ((ParticleSwarmOptimization) this.optimizer).setCheckSpeedLimit(checkSpeedLimit); + GenericObjectEditor.setHideProperty(getClass(), "speedLimit", !checkSpeedLimit); + } + + public String checkSpeedLimitTipText() { + return ((ParticleSwarmOptimization) this.optimizer).checkSpeedLimitTipText(); + } + + /** + * This method allows you to choose the algorithm type. + * + * @param s The type. */ public void setAlgoType(SelectedTag s) { - ((ParticleSwarmOptimization)this.optimizer).setAlgoType(s); + ((ParticleSwarmOptimization) this.optimizer).setAlgoType(s); } - + public SelectedTag getAlgoType() { - return ((ParticleSwarmOptimization)this.optimizer).getAlgoType(); + return ((ParticleSwarmOptimization) this.optimizer).getAlgoType(); } - + public String algoTypeTipText() { - return ((ParticleSwarmOptimization)this.optimizer).algoTypeTipText(); + return ((ParticleSwarmOptimization) this.optimizer).algoTypeTipText(); } - + // /** // * @return the treeBranchDeg // */ @@ -280,23 +325,23 @@ public class PSOParameters extends AbstractOptimizationParameters implements Int // public String treeBranchDegreeTipText() { // return ((ParticleSwarmOptimization)this.optimizer).treeBranchDegreeTipText(); // } - - /** - * @return the wrapTopology - */ - public boolean isWrapTopology() { - return ((ParticleSwarmOptimization)this.optimizer).isWrapTopology(); - } - /** - * @param wrapTopology the wrapTopology to set - */ - public void setWrapTopology(boolean wrapTopology) { - ((ParticleSwarmOptimization)this.optimizer).setWrapTopology(wrapTopology); - } - - public String wrapTopologyTipText() { - return ((ParticleSwarmOptimization)this.optimizer).wrapTopologyTipText(); - } + /** + * @return the wrapTopology + */ + public boolean isWrapTopology() { + return ((ParticleSwarmOptimization) this.optimizer).isWrapTopology(); + } + + /** + * @param wrapTopology the wrapTopology to set + */ + public void setWrapTopology(boolean wrapTopology) { + ((ParticleSwarmOptimization) this.optimizer).setWrapTopology(wrapTopology); + } + + public String wrapTopologyTipText() { + return ((ParticleSwarmOptimization) this.optimizer).wrapTopologyTipText(); + } } \ No newline at end of file diff --git a/src/eva2/optimization/modules/Processor.java b/src/eva2/optimization/modules/Processor.java index ecc07fc0..e3845402 100644 --- a/src/eva2/optimization/modules/Processor.java +++ b/src/eva2/optimization/modules/Processor.java @@ -23,6 +23,7 @@ import eva2.tools.EVAERROR; import eva2.tools.EVAHELP; import eva2.tools.StringTools; import eva2.tools.math.RNG; + import java.util.ArrayList; import java.util.List; import java.util.logging.Level; @@ -32,7 +33,7 @@ import javax.swing.JOptionPane; /** * The Processor may run as a thread permanently (GenericModuleAdapter) and is * then stopped and started by a switch in startOpt/stopOpt. - * + *

* Processor also handles adaptive parameter control by checking for the method * getParamControl in (so far) Optimizer and Problem instances. The return-value * may be InterfaceParameterControl or an array of Objects. If it is a control @@ -41,7 +42,6 @@ import javax.swing.JOptionPane; * getParamControl, thus recursive controllable structures are possible. * * @author mkron - * */ public class Processor extends Thread implements InterfaceProcessor, InterfacePopulationChangedEventListener { @@ -62,7 +62,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo LOGGER.log( Level.FINEST, "Processor: setting module as listener: " + ((module == null) - ? "null" : module.toString())); + ? "null" : module.toString())); optimizationStateListener = module; } @@ -252,7 +252,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo EVAHELP.clearLog(popLog); } - do { // main loop + do { // main loop maybeUpdateParamCtrl(goParams); this.goParams.getOptimizer().optimize(); @@ -261,7 +261,8 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo if (popLog != null) { EVAHELP.logString(this.goParams.getOptimizer().getPopulation().getIndyList(), popLog); } - } while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions())); + } + while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions())); runCounter++; maybeFinishParamCtrl(goParams); userAborted = !isOptRunning(); // stop is "normal" if opt wasnt set false by the user (and thus still true) @@ -334,11 +335,9 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo InterfaceOptimizer optimizer = goParams.getOptimizer(); if (terminator instanceof GenerationTerminator) { args = new Object[]{optimizer, optimizer.getPopulation(), optimizer.getPopulation().getGeneration(), ((GenerationTerminator) terminator).getGenerations()}; - } - else if (terminator instanceof EvaluationTerminator) { + } else if (terminator instanceof EvaluationTerminator) { args = new Object[]{optimizer, optimizer.getPopulation(), optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator) terminator).getFitnessCalls()}; - } - else { + } else { args = new Object[]{optimizer}; } @@ -379,7 +378,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo * Send some information to the statistics module and update the progress. * * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. + * @param name Could be used to indicate the nature of the event. */ @Override public void registerPopulationStateChanged(Object source, String name) { @@ -391,9 +390,9 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo if (optimizationStateListener != null) { optimizationStateListener.updateProgress( getStatusPercent( - goParams.getOptimizer().getPopulation(), - runCounter, - m_Statistics.getStatisticsParameter().getMultiRuns()), + goParams.getOptimizer().getPopulation(), + runCounter, + m_Statistics.getStatisticsParameter().getMultiRuns()), null); } } diff --git a/src/eva2/optimization/modules/SAModuleAdapter.java b/src/eva2/optimization/modules/SAModuleAdapter.java index 9eaeea68..53d5c2bf 100644 --- a/src/eva2/optimization/modules/SAModuleAdapter.java +++ b/src/eva2/optimization/modules/SAModuleAdapter.java @@ -12,7 +12,7 @@ public class SAModuleAdapter extends GenericModuleAdapter implements ModuleAdapt * Constructor of the ModulAdapter. * * @param AdapterName The AdapterName - * @param Client The client to serve + * @param Client The client to serve */ public SAModuleAdapter(String adapterName) { super(adapterName, "SA.html", SAParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/SAParameters.java b/src/eva2/optimization/modules/SAParameters.java index 48cac06e..b428882e 100644 --- a/src/eva2/optimization/modules/SAParameters.java +++ b/src/eva2/optimization/modules/SAParameters.java @@ -10,12 +10,14 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.SimulatedAnnealing; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all SA parameters for the EvA +/** + * The class gives access to all SA parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -25,16 +27,16 @@ import java.util.logging.Level; */ public class SAParameters extends AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable { // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new SimulatedAnnealing(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); + private InterfaceOptimizer m_Optimizer = new SimulatedAnnealing(); + private InterfaceOptimizationProblem m_Problem = new B1Problem(); //private int functionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; + private InterfaceTerminator m_Terminator = new EvaluationTerminator(); + // private String m_OutputFileName = "none"; transient private InterfacePopulationChangedEventListener m_Listener; /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static SAParameters getInstance() { @@ -51,23 +53,26 @@ public class SAParameters extends AbstractOptimizationParameters implements Inte } return instance; } - + /** * */ public SAParameters() { - super(new SimulatedAnnealing(),new B1Problem(),new EvaluationTerminator()); + super(new SimulatedAnnealing(), new B1Problem(), new EvaluationTerminator()); } private SAParameters(SAParameters Source) { - super(Source); + super(Source); } + @Override public Object clone() { return new SAParameters(this); } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -79,48 +84,60 @@ public class SAParameters extends AbstractOptimizationParameters implements Inte // *pff* i'll ignore that! } - /** Assuming that all optimizer will store thier data in a population + /** + * Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { - return ((SimulatedAnnealing)this.m_Optimizer).getPopulation(); + return ((SimulatedAnnealing) this.m_Optimizer).getPopulation(); } - public void setPopulation(Population pop){ - ((SimulatedAnnealing)this.m_Optimizer).setPopulation(pop); + + public void setPopulation(Population pop) { + ((SimulatedAnnealing) this.m_Optimizer).setPopulation(pop); } + public String populationTipText() { return "Change the number of best individuals stored (MS-SA)."; } - /** This methods allow you to set/get the temperatur of the simulated + /** + * This methods allow you to set/get the temperatur of the simulated * annealing procedure + * * @return The initial temperature. */ public double getInitialTemperature() { - return ((SimulatedAnnealing)this.m_Optimizer).getInitialTemperature(); + return ((SimulatedAnnealing) this.m_Optimizer).getInitialTemperature(); } - public void setInitialTemperature(double pop){ - ((SimulatedAnnealing)this.m_Optimizer).setInitialTemperature(pop); + + public void setInitialTemperature(double pop) { + ((SimulatedAnnealing) this.m_Optimizer).setInitialTemperature(pop); } + public String initialTemperatureTipText() { return "Set the initial temperature."; } - /** This methods allow you to set/get the temperatur of the simulated + /** + * This methods allow you to set/get the temperatur of the simulated * annealing procedure + * * @return The initial temperature. */ public double getAlpha() { - return ((SimulatedAnnealing)this.m_Optimizer).getAlpha(); + return ((SimulatedAnnealing) this.m_Optimizer).getAlpha(); } - public void setAlpha(double a){ + + public void setAlpha(double a) { if (a > 1) { a = 1.0; } - ((SimulatedAnnealing)this.m_Optimizer).setAlpha(a); + ((SimulatedAnnealing) this.m_Optimizer).setAlpha(a); } + public String alphaTipText() { return "Set alpha, which is used to degrade the temperaure."; } diff --git a/src/eva2/optimization/modules/SSGAModuleAdapter.java b/src/eva2/optimization/modules/SSGAModuleAdapter.java index 39378c2e..88514f54 100644 --- a/src/eva2/optimization/modules/SSGAModuleAdapter.java +++ b/src/eva2/optimization/modules/SSGAModuleAdapter.java @@ -12,7 +12,7 @@ public class SSGAModuleAdapter extends GenericModuleAdapter implements ModuleAda * Constructor of the ModuleAdapter. * * @param AdapterName The AdapterName - * @param Client The client to serve + * @param Client The client to serve */ public SSGAModuleAdapter(String adapterName) { super(adapterName, "SSGA.html", SSGAParameters.getInstance(), true); diff --git a/src/eva2/optimization/modules/SSGAParameters.java b/src/eva2/optimization/modules/SSGAParameters.java index 777ed97a..c65bed0e 100644 --- a/src/eva2/optimization/modules/SSGAParameters.java +++ b/src/eva2/optimization/modules/SSGAParameters.java @@ -9,12 +9,14 @@ import eva2.optimization.problems.B1Problem; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.SteadyStateGA; import eva2.tools.Serializer; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.logging.Level; -/** The class gives access to all SSGA parameters for the EvA +/** + * The class gives access to all SSGA parameters for the EvA * top level GUI. * Created by IntelliJ IDEA. * User: streiche @@ -26,7 +28,7 @@ public class SSGAParameters extends AbstractOptimizationParameters implements In /** * Load or create a new instance of the class. - * + * * @return A loaded (from file) or new instance of the class. */ public static SSGAParameters getInstance() { @@ -43,14 +45,14 @@ public class SSGAParameters extends AbstractOptimizationParameters implements In } return instance; } - + /** * */ - public SSGAParameters() { - super(new SteadyStateGA(), new B1Problem(), new EvaluationTerminator()); + public SSGAParameters() { + super(new SteadyStateGA(), new B1Problem(), new EvaluationTerminator()); } - + private SSGAParameters(SSGAParameters Source) { super(Source); } @@ -60,8 +62,9 @@ public class SSGAParameters extends AbstractOptimizationParameters implements In return new SSGAParameters(this); } - /** + /** * This method returns a global info string. + * * @return description */ public static String globalInfo() { @@ -73,16 +76,18 @@ public class SSGAParameters extends AbstractOptimizationParameters implements In // *pff* i'll ignore that! } - /** Assuming that all optimizer will store their data in a population + /** + * Assuming that all optimizer will store their data in a population * we will allow access to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ public Population getPopulation() { return ((SteadyStateGA) this.optimizer).getPopulation(); } - public void setPopulation(Population pop){ + public void setPopulation(Population pop) { ((SteadyStateGA) this.optimizer).setPopulation(pop); } @@ -103,7 +108,9 @@ public class SSGAParameters extends AbstractOptimizationParameters implements In // return "Select the normation method."; // } - /** Choose a parent selection method. + /** + * Choose a parent selection method. + * * @param selection */ public void setParentSelection(InterfaceSelection selection) { @@ -130,36 +137,45 @@ public class SSGAParameters extends AbstractOptimizationParameters implements In } ((SteadyStateGA) this.optimizer).setNumberOfPartners(partners); } - + public int getNumberOfPartners() { return ((SteadyStateGA) this.optimizer).getNumberOfPartners(); } + public String numberOfPartnersTipText() { return "The number of mating partners needed to create offsprings."; } - /** Choose a selection method for selecting recombination partners for given parents. + /** + * Choose a selection method for selecting recombination partners for given parents. + * * @param selection */ public void setPartnerSelection(InterfaceSelection selection) { - ((SteadyStateGA)this.optimizer).setPartnerSelection(selection); + ((SteadyStateGA) this.optimizer).setPartnerSelection(selection); } + public InterfaceSelection getPartnerSelection() { - return ((SteadyStateGA)this.optimizer).getPartnerSelection(); + return ((SteadyStateGA) this.optimizer).getPartnerSelection(); } + public String partnerSelectionTipText() { return "Choose a selection method for selecting recombination partners for given parents."; } - /** Choose a replacement strategy. - * @param s A InterfaceReplacement strategy. + /** + * Choose a replacement strategy. + * + * @param s A InterfaceReplacement strategy. */ public void setReplacementSelection(InterfaceReplacement s) { - ((SteadyStateGA)this.optimizer).setReplacementSelection(s); + ((SteadyStateGA) this.optimizer).setReplacementSelection(s); } + public InterfaceReplacement getReplacementSelection() { - return ((SteadyStateGA)this.optimizer).getReplacementSelection(); + return ((SteadyStateGA) this.optimizer).getReplacementSelection(); } + public String replacementSelectionTipText() { return "Choose a replacement strategy."; } diff --git a/src/eva2/optimization/operator/archiving/AbstractArchiving.java b/src/eva2/optimization/operator/archiving/AbstractArchiving.java index 1d33098e..3938e2f5 100644 --- a/src/eva2/optimization/operator/archiving/AbstractArchiving.java +++ b/src/eva2/optimization/operator/archiving/AbstractArchiving.java @@ -8,7 +8,8 @@ import eva2.tools.chart2d.Chart2DDPointIconCross; import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; -/** This is an abstract archiving strategy giving default implementation of determining +/** + * This is an abstract archiving strategy giving default implementation of determining * dominance, inserting individuals in exsisting Pareto front (removing now dominated solutions) * and some plot methods typically used for debugging. * Created by IntelliJ IDEA. @@ -19,32 +20,36 @@ import eva2.tools.chart2d.DPointIcon; */ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.Serializable { transient protected Plot m_Plot = null; - protected int p = 0; + protected int p = 0; public boolean obeyDebsConstViolationPrinciple = true; - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override public abstract Object clone(); - /** This method will test if a given individual is dominant within + /** + * This method will test if a given individual is dominant within * a given population - * @param indy The individual that is to be tested. - * @param pop The population that the individual is to be tested against. + * + * @param indy The individual that is to be tested. + * @param pop The population that the individual is to be tested against. * @return True if the individual is dominating */ public boolean isDominant(AbstractEAIndividual indy, Population pop) { if (this.obeyDebsConstViolationPrinciple) { for (int i = 0; i < pop.size(); i++) { - if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominatingDebConstraints(indy))) { + if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual) pop.get(i)).isDominatingDebConstraints(indy))) { return false; } } } else { for (int i = 0; i < pop.size(); i++) { - if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominating(indy))) { + if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual) pop.get(i)).isDominating(indy))) { return false; } } @@ -52,24 +57,25 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S return true; } - /** This method will add a given Individual to the archive and will remove + /** + * This method will add a given Individual to the archive and will remove * all individuals that are dominated by the new individual. - * @param indy The individual that is to be tested. - * @param archive The population that the individual is to be inserted to. + * + * @param indy The individual that is to be tested. + * @param archive The population that the individual is to be inserted to. */ public void addIndividualToArchive(AbstractEAIndividual indy, Population archive) { - double[] indyFitness = indy.getFitness(), tmpFitness; - boolean isDominating; + double[] indyFitness = indy.getFitness(), tmpFitness; + boolean isDominating; for (int i = 0; i < archive.size(); i++) { isDominating = true; - tmpFitness = ((AbstractEAIndividual)archive.get(i)).getFitness(); + tmpFitness = ((AbstractEAIndividual) archive.get(i)).getFitness(); try { for (int j = 0; j < indyFitness.length; j++) { if (indyFitness[j] <= tmpFitness[j]) { isDominating &= true; - } - else { + } else { isDominating &= false; } } @@ -84,44 +90,48 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S archive.add(indy); } - /** This method allows you to plot a pareto front of a given population. + /** + * This method allows you to plot a pareto front of a given population. * Here default icons will be used. - * @param pop The population to plot - * @param plot The plot to use - **/ - public void plotParetoFront(Population pop, Plot plot) { + * + * @param pop The population to plot + * @param plot The plot to use + */ + public void plotParetoFront(Population pop, Plot plot) { DPointIcon[] icons = new DPointIcon[pop.size()]; for (int i = 0; i < icons.length; i++) { - icons[i] = new Chart2DDPointIconCross(); - } + icons[i] = new Chart2DDPointIconCross(); + } this.plotParetoFront(pop, icons, plot); } - /** This method allows you to plot a pareto front of a given population - * @param pop The population to plot - * @param plot The plot to use - * @param icons The icons to use, perhaps with additional information + /** + * This method allows you to plot a pareto front of a given population + * + * @param pop The population to plot + * @param plot The plot to use + * @param icons The icons to use, perhaps with additional information */ public void plotParetoFront(Population pop, DPointIcon[] icons, Plot plot) { - GraphPointSet mySet = new GraphPointSet(10, plot.getFunctionArea()); - DPoint myPoint; + GraphPointSet mySet = new GraphPointSet(10, plot.getFunctionArea()); + DPoint myPoint; AbstractEAIndividual tmpIndy; - double[][] tmpFit; - int index; - double curVal; - double[] lastValue = null, tmpD; + double[][] tmpFit; + int index; + double curVal; + double[] lastValue = null, tmpD; mySet.setConnectedMode(false); this.p++; - mySet = new GraphPointSet(10000+p, plot.getFunctionArea()); + mySet = new GraphPointSet(10000 + p, plot.getFunctionArea()); mySet.setConnectedMode(false); lastValue = null; // first prepare the tmpFit tmpFit = new double[pop.size()][]; for (int j = 0; j < pop.size(); j++) { - tmpIndy = ((AbstractEAIndividual)pop.get(j)); + tmpIndy = ((AbstractEAIndividual) pop.get(j)); if (tmpIndy.getFitness().length <= 1) { - tmpD = (double[])tmpIndy.getData("MOFitness"); + tmpD = (double[]) tmpIndy.getData("MOFitness"); tmpFit[j] = new double[tmpD.length]; System.arraycopy(tmpD, 0, tmpFit[j], 0, tmpD.length); } else { @@ -141,18 +151,18 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S } myPoint = new DPoint(tmpFit[index][0], tmpFit[index][1]); if (lastValue != null) { - plot.setConnectedPoint(lastValue[0], lastValue[1], 20000+p); - plot.setConnectedPoint(tmpFit[index][0], lastValue[1], 20000+p); - plot.setConnectedPoint(tmpFit[index][0], tmpFit[index][1], 20000+p); + plot.setConnectedPoint(lastValue[0], lastValue[1], 20000 + p); + plot.setConnectedPoint(tmpFit[index][0], lastValue[1], 20000 + p); + plot.setConnectedPoint(tmpFit[index][0], tmpFit[index][1], 20000 + p); } lastValue = new double[tmpFit[index].length]; System.arraycopy(tmpFit[index], 0, lastValue, 0, lastValue.length); tmpFit[index][0] = Double.POSITIVE_INFINITY; myPoint.setIcon(icons[index]); mySet.addDPoint(myPoint); - } - if (lastValue != null) { - plot.setConnectedPoint(lastValue[0], lastValue[1], 20000+p); + } + if (lastValue != null) { + plot.setConnectedPoint(lastValue[0], lastValue[1], 20000 + p); } p++; } @@ -174,16 +184,20 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S // return "Toggles the debug mode."; // } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ public void setObeyDebsConstViolationPrinciple(boolean b) { this.obeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.obeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's constraint violation principle."; } diff --git a/src/eva2/optimization/operator/archiving/ArchivingAllDominating.java b/src/eva2/optimization/operator/archiving/ArchivingAllDominating.java index 17edba38..a9a4e81f 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingAllDominating.java +++ b/src/eva2/optimization/operator/archiving/ArchivingAllDominating.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.operator.selection.SelectBestIndividuals; import eva2.optimization.population.Population; -/** This simple strategy simply archives all Pareto optimal solutions. This method is +/** + * This simple strategy simply archives all Pareto optimal solutions. This method is * very prone to OutOfMemory errors! * Created by IntelliJ IDEA. * User: streiche @@ -27,10 +28,12 @@ public class ArchivingAllDominating extends AbstractArchiving implements java.io return (Object) new ArchivingAllDominating(this); } - /** This method allows you to merge to populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge to populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ @Override public void addElementsToArchive(Population pop) { @@ -42,9 +45,9 @@ public class ArchivingAllDominating extends AbstractArchiving implements java.io if (this.obeyDebsConstViolationPrinciple) { for (int i = 0; i < pop.size(); i++) { //System.out.println("i:"+ i+" "+pop.size()+"_"+((AbstractEAIndividual)pop.get(0)).getFitness().length); - if ((((AbstractEAIndividual)pop.get(i)).getConstraintViolation() == 0) && (this.isDominant((AbstractEAIndividual)pop.get(i), pop.getArchive()))) { + if ((((AbstractEAIndividual) pop.get(i)).getConstraintViolation() == 0) && (this.isDominant((AbstractEAIndividual) pop.get(i), pop.getArchive()))) { //System.out.println("Adding ("+((AbstractEAIndividual)pop.get(i)).getFitness()[0] +"/"+((AbstractEAIndividual)pop.get(i)).getFitness()[1]+") to archive."); - this.addIndividualToArchive((AbstractEAIndividual)((AbstractEAIndividual)pop.get(i)).clone(), pop.getArchive()); + this.addIndividualToArchive((AbstractEAIndividual) ((AbstractEAIndividual) pop.get(i)).clone(), pop.getArchive()); } } if ((pop.getArchive().size() == 0) && (pop.size() > 0)) { @@ -57,9 +60,9 @@ public class ArchivingAllDominating extends AbstractArchiving implements java.io // is dominating a element in the archive for (int i = 0; i < pop.size(); i++) { //System.out.println("i:"+ i+" "+pop.size()+"_"+((AbstractEAIndividual)pop.get(0)).getFitness().length); - if (this.isDominant((AbstractEAIndividual)pop.get(i), pop.getArchive())) { + if (this.isDominant((AbstractEAIndividual) pop.get(i), pop.getArchive())) { //System.out.println("Adding ("+((AbstractEAIndividual)pop.get(i)).getFitness()[0] +"/"+((AbstractEAIndividual)pop.get(i)).getFitness()[1]+") to archive."); - this.addIndividualToArchive((AbstractEAIndividual)((AbstractEAIndividual)pop.get(i)).clone(), pop.getArchive()); + this.addIndividualToArchive((AbstractEAIndividual) ((AbstractEAIndividual) pop.get(i)).clone(), pop.getArchive()); } } } @@ -68,13 +71,18 @@ public class ArchivingAllDominating extends AbstractArchiving implements java.io /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a straightforward strategy, which selects all dominating individuals (very prone to generate OutOfMemory errors)."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/archiving/ArchivingMaxiMin.java b/src/eva2/optimization/operator/archiving/ArchivingMaxiMin.java index e6cee397..7b312e36 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingMaxiMin.java +++ b/src/eva2/optimization/operator/archiving/ArchivingMaxiMin.java @@ -9,7 +9,8 @@ import eva2.tools.chart2d.Chart2DDPointIconCross; import eva2.tools.chart2d.DPointIcon; -/** Another simple archiving strategy not based on dominance but on the MaxiMin +/** + * Another simple archiving strategy not based on dominance but on the MaxiMin * criterion. Doesn't work well on non-convex Pareto fronts. * Created by IntelliJ IDEA. * User: streiche @@ -19,17 +20,17 @@ import eva2.tools.chart2d.DPointIcon; */ public class ArchivingMaxiMin implements InterfaceArchiving, java.io.Serializable { - private MOSOMaxiMin m_MaxiMin = new MOSOMaxiMin(); - private InterfaceSelection m_Selection = new SelectBestIndividuals(); - private boolean m_ObeyDebsConstViolationPrinciple = true; + private MOSOMaxiMin m_MaxiMin = new MOSOMaxiMin(); + private InterfaceSelection m_Selection = new SelectBestIndividuals(); + private boolean m_ObeyDebsConstViolationPrinciple = true; public ArchivingMaxiMin() { } public ArchivingMaxiMin(ArchivingMaxiMin a) { - this.m_MaxiMin = new MOSOMaxiMin(); - this.m_Selection = (InterfaceSelection)a.m_Selection.clone(); - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_MaxiMin = new MOSOMaxiMin(); + this.m_Selection = (InterfaceSelection) a.m_Selection.clone(); + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @Override @@ -37,23 +38,25 @@ public class ArchivingMaxiMin implements InterfaceArchiving, java.io.Serializabl return (Object) new ArchivingMaxiMin(this); } - /** This method allows you to merge to populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge to populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ @Override public void addElementsToArchive(Population pop) { - Population archive; - double[] tmpD; + Population archive; + double[] tmpD; if (pop.getArchive() == null) { pop.SetArchive(new Population()); } // First merge the current population and the archive Population tmpPop = new Population(); - tmpPop.addPopulation((Population)pop.getClone()); - tmpPop.addPopulation((Population)pop.getArchive().getClone()); + tmpPop.addPopulation((Population) pop.getClone()); + tmpPop.addPopulation((Population) pop.getArchive().getClone()); tmpPop.removeRedundantIndiesUsingFitness(); // Now calculate the MaxiMin Criterium @@ -65,14 +68,16 @@ public class ArchivingMaxiMin implements InterfaceArchiving, java.io.Serializabl // now unconvert from SO to MO for (int i = 0; i < archive.size(); i++) { - tmpD = (double[])((AbstractEAIndividual)archive.get(i)).getData("MOFitness"); - ((AbstractEAIndividual)archive.get(i)).setFitness(tmpD); + tmpD = (double[]) ((AbstractEAIndividual) archive.get(i)).getData("MOFitness"); + ((AbstractEAIndividual) archive.get(i)).setFitness(tmpD); } pop.SetArchive(archive); } - /** This method allows you to determine an icon for a given individual + /** + * This method allows you to determine an icon for a given individual + * * @param pop The population * @param index The identifier for the individual */ @@ -83,43 +88,56 @@ public class ArchivingMaxiMin implements InterfaceArchiving, java.io.Serializabl /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Maxi Min Archiving."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MaxiMin"; } - /** Since SelectMOMaxiMin relies on a MOSO conversion + /** + * Since SelectMOMaxiMin relies on a MOSO conversion * a single criterion selection method must be used. - * @param pop The selection method used. + * + * @param pop The selection method used. */ public void setSelectionMethod(InterfaceSelection pop) { this.m_Selection = pop; } + public InterfaceSelection getSelectionMethod() { return this.m_Selection; } + public String selectionMethodTipText() { return "Choose the selection method (single-criteria ones please)."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/archiving/ArchivingNSGA.java b/src/eva2/optimization/operator/archiving/ArchivingNSGA.java index bbefaa7f..444f1508 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingNSGA.java +++ b/src/eva2/optimization/operator/archiving/ArchivingNSGA.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** The non dominated sorting GA archiving method, based on dominace sorting. +/** + * The non dominated sorting GA archiving method, based on dominace sorting. * Created by IntelliJ IDEA. * User: streiche * Date: 27.02.2004 @@ -18,7 +19,7 @@ public class ArchivingNSGA extends AbstractArchiving implements java.io.Serializ } public ArchivingNSGA(ArchivingNSGA a) { - this.m_Cleaner = (InterfaceRemoveSurplusIndividuals) a.m_Cleaner.clone(); + this.m_Cleaner = (InterfaceRemoveSurplusIndividuals) a.m_Cleaner.clone(); } @Override @@ -26,28 +27,30 @@ public class ArchivingNSGA extends AbstractArchiving implements java.io.Serializ return (Object) new ArchivingNSGA(this); } - /** This method allows you to merge to populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge to populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ @Override public void addElementsToArchive(Population pop) { if (pop.getArchive() == null) { pop.SetArchive(new Population()); - } + } // test for each element in population if it // is dominating a element in the archive for (int i = 0; i < pop.size(); i++) { - if (this.isDominant((AbstractEAIndividual)pop.get(i), pop.getArchive())) { - this.addIndividualToArchive((AbstractEAIndividual)((AbstractEAIndividual)pop.get(i)).clone(), pop.getArchive()); + if (this.isDominant((AbstractEAIndividual) pop.get(i), pop.getArchive())) { + this.addIndividualToArchive((AbstractEAIndividual) ((AbstractEAIndividual) pop.get(i)).clone(), pop.getArchive()); } } // Now clear the archive of surplus individuals - Population archive = pop.getArchive(); + Population archive = pop.getArchive(); this.m_Cleaner.removeSurplusIndividuals(archive); } @@ -56,29 +59,38 @@ public class ArchivingNSGA extends AbstractArchiving implements java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Non-dominating sorting GA revision 1.0."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "NSGA"; } - - /** This method allows you to toggle between hypercube resambling and + + /** + * This method allows you to toggle between hypercube resambling and * static mode for hybercube sampling - * @param s The design mode. + * + * @param s The design mode. */ public void setCleaner(InterfaceRemoveSurplusIndividuals s) { this.m_Cleaner = s; } + public InterfaceRemoveSurplusIndividuals getCleaner() { return this.m_Cleaner; } + public String cleanerTipText() { return "Choose the method to remove surplus individuals from the archive."; } diff --git a/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java b/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java index 7ce9aa12..1e9bb946 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java +++ b/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java @@ -4,10 +4,12 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.chart2d.Chart2DDPointIconCross; import eva2.tools.chart2d.DPointIcon; + import java.util.ArrayList; -/** The secon verison of the non dominace sorting GA. +/** + * The secon verison of the non dominace sorting GA. * Created by IntelliJ IDEA. * User: streiche * Date: 04.08.2003 @@ -27,10 +29,12 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab return (Object) new ArchivingNSGAII(this); } - /** This method allows you to merge to populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge to populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ @Override public void addElementsToArchive(Population pop) { @@ -41,8 +45,8 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab // First merge the current population and the archive Population tmpPop = new Population(); - tmpPop.addPopulation((Population)pop.getClone()); - tmpPop.addPopulation((Population)pop.getArchive().getClone()); + tmpPop.addPopulation((Population) pop.getClone()); + tmpPop.addPopulation((Population) pop.getArchive().getClone()); tmpPop.removeRedundantIndiesUsingFitness(); // Now fetch the n pareto-fronts @@ -78,49 +82,52 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab fronts = null; pop.SetArchive(archive); } - + /** * Return the pareto front from a given population. + * * @param pop * @return */ public static Population getNonDominatedSortedFront(Population pop) { - ArchivingNSGAII arch = new ArchivingNSGAII(); - Population[] fronts = arch.getNonDominatedSortedFronts(pop); - return fronts[0]; + ArchivingNSGAII arch = new ArchivingNSGAII(); + Population[] fronts = arch.getNonDominatedSortedFronts(pop); + return fronts[0]; } - /** This method will dissect a given population into n pareto-fronts - * @param pop The population to analyse + /** + * This method will dissect a given population into n pareto-fronts + * + * @param pop The population to analyse * @return Population[] the n pareto-fronts */ public Population[] getNonDominatedSortedFronts(Population pop) { - Population tmpPop, tmpDom, tmpNonDom; - Population[] result = null; - ArrayList tmpResult = new ArrayList(); - int level = 1; + Population tmpPop, tmpDom, tmpNonDom; + Population[] result = null; + ArrayList tmpResult = new ArrayList(); + int level = 1; tmpPop = new Population(); tmpPop.addPopulation(pop); while (tmpPop.size() > 0) { - tmpDom = new Population(); - tmpNonDom = new Population(); + tmpDom = new Population(); + tmpNonDom = new Population(); for (int i = 0; i < tmpPop.size(); i++) { if (this.isDominant((AbstractEAIndividual) tmpPop.get(i), tmpPop)) { - ((AbstractEAIndividual)tmpPop.get(i)).putData("ParetoLevel", new Integer(level)); + ((AbstractEAIndividual) tmpPop.get(i)).putData("ParetoLevel", new Integer(level)); tmpDom.add(tmpPop.get(i)); } else { tmpNonDom.add(tmpPop.get(i)); } } - tmpPop = tmpNonDom; + tmpPop = tmpNonDom; if (tmpDom.size() < 1) { System.out.println("Problem NSGA II at level " + level + "."); tmpDom.addPopulation(tmpNonDom); for (int i = 0; i < tmpDom.size(); i++) { - ((AbstractEAIndividual)tmpDom.get(i)).putData("ParetoLevel", new Integer(level)); + ((AbstractEAIndividual) tmpDom.get(i)).putData("ParetoLevel", new Integer(level)); } tmpPop.clear(); // System.out.println(""+tmpPop.getStringRepresentation()); @@ -135,28 +142,33 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab } return result; } - /** This method will cacluated the NSGAII crowding distance + + /** + * This method will cacluated the NSGAII crowding distance * for all individuals - * @param fronts The pareto fronts + * + * @param fronts The pareto fronts */ public void calculateCrowdingDistance(Population[] fronts) { RemoveSurplusIndividualsDynamicHyperCube heidi = new RemoveSurplusIndividualsDynamicHyperCube(); - double[][] fitness; - double[] hyperCube; + double[][] fitness; + double[] hyperCube; for (int i = 0; i < fronts.length; i++) { - fitness = new double[fronts[i].size()][]; - hyperCube = new double[fronts[i].size()]; + fitness = new double[fronts[i].size()][]; + hyperCube = new double[fronts[i].size()]; for (int j = 0; j < fronts[i].size(); j++) { - fitness[j] = ((AbstractEAIndividual)fronts[i].get(j)).getFitness(); + fitness[j] = ((AbstractEAIndividual) fronts[i].get(j)).getFitness(); } hyperCube = heidi.calculateHyperCubeVolumes(fitness); for (int j = 0; j < fronts[i].size(); j++) { - ((AbstractEAIndividual)fronts[i].get(j)).putData("HyperCube", new Double(hyperCube[j])); + ((AbstractEAIndividual) fronts[i].get(j)).putData("HyperCube", new Double(hyperCube[j])); } } } - /** This method allows you to determine an icon for a given individual + /** + * This method allows you to determine an icon for a given individual + * * @param pop The population * @param index The identifier for the individual */ @@ -167,13 +179,18 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Non-dominating sorting GA revision 2.0."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ @Override diff --git a/src/eva2/optimization/operator/archiving/ArchivingNSGAIISMeasure.java b/src/eva2/optimization/operator/archiving/ArchivingNSGAIISMeasure.java index b712fd15..f4694dc4 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingNSGAIISMeasure.java +++ b/src/eva2/optimization/operator/archiving/ArchivingNSGAIISMeasure.java @@ -3,107 +3,105 @@ package eva2.optimization.operator.archiving; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.AbstractEAIndividualComparator; import eva2.optimization.population.Population; + import java.util.Arrays; public class ArchivingNSGAIISMeasure extends ArchivingNSGAII { - /** This method will cacluated the NSGAII crowding distance - * for all individuals - * @param fronts The pareto fronts - */ + /** + * This method will cacluated the NSGAII crowding distance + * for all individuals + * + * @param fronts The pareto fronts + */ @Override - public void calculateCrowdingDistance(Population[] fronts) { - //TODO Dimension der Zielfunktion checken + public void calculateCrowdingDistance(Population[] fronts) { + //TODO Dimension der Zielfunktion checken - for (int rank = 0; rank < fronts.length; rank++) - { - calculateCrowdingDistance(fronts[rank]); - } - } + for (int rank = 0; rank < fronts.length; rank++) { + calculateCrowdingDistance(fronts[rank]); + } + } - /** This mehtod will test if a given individual is dominant within - * a given population - * @param indy The individual that is to be tested. - * @param pop The population that the individual is to be tested against. - * @return True if the individual is dominating - */ - @Override - public boolean isDominant(AbstractEAIndividual indy, Population pop) { - if (this.obeyDebsConstViolationPrinciple) { - for (int i = 0; i < pop.size(); i++) { - if (!(indy.equals(pop.get(i))||indy.equalFitness((AbstractEAIndividual) pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominatingDebConstraints(indy))) { - return false; - } - } - } else { - for (int i = 0; i < pop.size(); i++) { - if (!(indy.equals(pop.get(i))||indy.equalFitness((AbstractEAIndividual) pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominating(indy))) { - return false; - } - } - } - return true; - } + /** + * This mehtod will test if a given individual is dominant within + * a given population + * + * @param indy The individual that is to be tested. + * @param pop The population that the individual is to be tested against. + * @return True if the individual is dominating + */ + @Override + public boolean isDominant(AbstractEAIndividual indy, Population pop) { + if (this.obeyDebsConstViolationPrinciple) { + for (int i = 0; i < pop.size(); i++) { + if (!(indy.equals(pop.get(i)) || indy.equalFitness((AbstractEAIndividual) pop.get(i))) && (((AbstractEAIndividual) pop.get(i)).isDominatingDebConstraints(indy))) { + return false; + } + } + } else { + for (int i = 0; i < pop.size(); i++) { + if (!(indy.equals(pop.get(i)) || indy.equalFitness((AbstractEAIndividual) pop.get(i))) && (((AbstractEAIndividual) pop.get(i)).isDominating(indy))) { + return false; + } + } + } + return true; + } - public void calculateCrowdingDistance(Population front) { + public void calculateCrowdingDistance(Population front) { - Object[] frontArray= front.toArray(); - boolean[] assigned=new boolean[frontArray.length]; + Object[] frontArray = front.toArray(); + boolean[] assigned = new boolean[frontArray.length]; - double[] v=new double[frontArray.length]; - int i, left, right; + double[] v = new double[frontArray.length]; + int i, left, right; - // initialization of assignment vector - for (i = 0; i < frontArray.length; i++) - { - assigned[ i ] = false; + // initialization of assignment vector + for (i = 0; i < frontArray.length; i++) { + assigned[i] = false; - } + } - Arrays.sort(frontArray,new AbstractEAIndividualComparator(0)); + Arrays.sort(frontArray, new AbstractEAIndividualComparator(0)); - ((AbstractEAIndividual)frontArray[0]).putData("HyperCube",Double.MAX_VALUE); //die beiden aussen bekommen maximal wert als smeasure - ((AbstractEAIndividual)frontArray[frontArray.length-1]).putData("HyperCube",Double.MAX_VALUE); - v[0]=Double.MAX_VALUE; - v[frontArray.length-1]=Double.MAX_VALUE; + ((AbstractEAIndividual) frontArray[0]).putData("HyperCube", Double.MAX_VALUE); //die beiden aussen bekommen maximal wert als smeasure + ((AbstractEAIndividual) frontArray[frontArray.length - 1]).putData("HyperCube", Double.MAX_VALUE); + v[0] = Double.MAX_VALUE; + v[frontArray.length - 1] = Double.MAX_VALUE; - for (int e = 1; e < frontArray.length - 1; e++) - { // loop over all non-border elements - for (i = 1; (assigned[ i ]); i++); // determine 1st not assigned, non-border element + for (int e = 1; e < frontArray.length - 1; e++) { // loop over all non-border elements + for (i = 1; (assigned[i]); i++) ; // determine 1st not assigned, non-border element - for (left = 0; i < frontArray.length - 1;) - { // loop over all not assigned elements - // determine right not assigned neighbor - for (right = i + 1; (assigned[ right]); right++); + for (left = 0; i < frontArray.length - 1; ) { // loop over all not assigned elements + // determine right not assigned neighbor + for (right = i + 1; (assigned[right]); right++) ; - v[i] = (((AbstractEAIndividual)frontArray[right]).getFitness(0) - ((AbstractEAIndividual)frontArray[i]).getFitness(0)) * - (((AbstractEAIndividual)frontArray[left]).getFitness(1) - ((AbstractEAIndividual)frontArray[i]).getFitness(1)); + v[i] = (((AbstractEAIndividual) frontArray[right]).getFitness(0) - ((AbstractEAIndividual) frontArray[i]).getFitness(0)) * + (((AbstractEAIndividual) frontArray[left]).getFitness(1) - ((AbstractEAIndividual) frontArray[i]).getFitness(1)); - left = i; - i = right; - } + left = i; + i = right; + } - int minIndex = 0; - double min=v[minIndex]; - for (int f = 1; f < frontArray.length - 1; f++) - { - if (!assigned[ f ]) { - if (v[f] < min) - { - min = v[f]; - minIndex = f; - } - } - } - assigned[ minIndex ] = true; - ((AbstractEAIndividual)frontArray[ minIndex]).putData("HyperCube",new Double(e)); - } + int minIndex = 0; + double min = v[minIndex]; + for (int f = 1; f < frontArray.length - 1; f++) { + if (!assigned[f]) { + if (v[f] < min) { + min = v[f]; + minIndex = f; + } + } + } + assigned[minIndex] = true; + ((AbstractEAIndividual) frontArray[minIndex]).putData("HyperCube", new Double(e)); + } - - } + } } diff --git a/src/eva2/optimization/operator/archiving/ArchivingPESAII.java b/src/eva2/optimization/operator/archiving/ArchivingPESAII.java index f7c3693e..6768f1e6 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingPESAII.java +++ b/src/eva2/optimization/operator/archiving/ArchivingPESAII.java @@ -6,7 +6,8 @@ import eva2.tools.math.RNG; import java.util.ArrayList; -/** The Pareto envelope sorting algorithm using a hybergrid and +/** + * The Pareto envelope sorting algorithm using a hybergrid and * the so called squezze factor. * Created by IntelliJ IDEA. * User: streiche @@ -16,13 +17,13 @@ import java.util.ArrayList; */ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serializable { - private int m_GridSize = 4; + private int m_GridSize = 4; public ArchivingPESAII() { } public ArchivingPESAII(ArchivingPESAII a) { - this.m_GridSize = a.m_GridSize; + this.m_GridSize = a.m_GridSize; } @Override @@ -30,10 +31,12 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial return (Object) new ArchivingPESAII(this); } - /** This method allows you to merge to populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge to populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ @Override public void addElementsToArchive(Population pop) { @@ -41,13 +44,13 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial if (pop.getArchive() == null) { pop.SetArchive(new Population()); } - Population archive = pop.getArchive(); + Population archive = pop.getArchive(); // test for each element in population if it // is dominating a element in the archive for (int i = 0; i < pop.size(); i++) { - if (this.isDominant((AbstractEAIndividual)pop.get(i), pop.getArchive())) { - this.addIndividualToArchive((AbstractEAIndividual)((AbstractEAIndividual)pop.get(i)).clone(), pop.getArchive()); + if (this.isDominant((AbstractEAIndividual) pop.get(i), pop.getArchive())) { + this.addIndividualToArchive((AbstractEAIndividual) ((AbstractEAIndividual) pop.get(i)).clone(), pop.getArchive()); } } @@ -55,10 +58,10 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial // Now check whether there are individuals to remove - int bigSqueeze, index; - int[] squeezeFactor; - while(archive.targetSizeExceeded()) { - squeezeFactor = this.calculateSqueezeFactor(archive); + int bigSqueeze, index; + int[] squeezeFactor; + while (archive.targetSizeExceeded()) { + squeezeFactor = this.calculateSqueezeFactor(archive); bigSqueeze = 0; index = -1; for (int i = 0; i < squeezeFactor.length; i++) { @@ -74,29 +77,30 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial } } - /** This method will calculate the squeeze factor for a population + /** + * This method will calculate the squeeze factor for a population * and will return the squeeze factor - * @param pop The population. * + * @param pop The population. */ public int[] calculateSqueezeFactor(Population pop) { - int[] result = new int[pop.size()]; - double[][] bounds; - double[] tmpFit; + int[] result = new int[pop.size()]; + double[][] bounds; + double[] tmpFit; AbstractEAIndividual tmpIndy; // boolean debug = true; // first calculate the bounds of the search space - bounds = new double[((AbstractEAIndividual)pop.get(0)).getFitness().length][2]; + bounds = new double[((AbstractEAIndividual) pop.get(0)).getFitness().length][2]; for (int i = 0; i < bounds.length; i++) { bounds[i][0] = Double.POSITIVE_INFINITY; bounds[i][1] = Double.NEGATIVE_INFINITY; } // if (debug) System.out.println("The individuals:"); for (int i = 0; i < pop.size(); i++) { - tmpFit = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmpFit = ((AbstractEAIndividual) pop.get(i)).getFitness(); // if (debug) System.out.println("Individual "+i+": "+tmpFit[0] +"/"+tmpFit[1]); - result[i] = 0; + result[i] = 0; for (int j = 0; j < tmpFit.length; j++) { if (tmpFit[j] < bounds[j][0]) { bounds[j][0] = tmpFit[j]; @@ -112,20 +116,20 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial // } // now that i got the bounds i can calculate the squeeze grid - int[] curGrid = new int[bounds.length], tmpGrid = new int[bounds.length]; - double[] grid = new double[bounds.length]; - ArrayList coll; - boolean sameGrid; + int[] curGrid = new int[bounds.length], tmpGrid = new int[bounds.length]; + double[] grid = new double[bounds.length]; + ArrayList coll; + boolean sameGrid; for (int i = 0; i < pop.size(); i++) { if (result[i] == 0) { curGrid = new int[bounds.length]; // haven't calculated the squeeze factor for this guy yet // first i'll calculate the grid position this guy is in - tmpFit = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmpFit = ((AbstractEAIndividual) pop.get(i)).getFitness(); coll = new ArrayList(); for (int j = 0; j < tmpFit.length; j++) { - grid[j] = (bounds[j][1] - bounds[j][0])/this.m_GridSize; - curGrid[j] = (int)((tmpFit[j]-bounds[j][0])/grid[j]); + grid[j] = (bounds[j][1] - bounds[j][0]) / this.m_GridSize; + curGrid[j] = (int) ((tmpFit[j] - bounds[j][0]) / grid[j]); } // if (debug) { // System.out.println("Indy "+i+" ("+tmpFit[0] +"/"+tmpFit[1]+") unassigned is in grid ["+curGrid[0]+"/"+curGrid[1]+"]"); @@ -133,18 +137,17 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial // System.out.println("Checking for individuals in the same grid"); // } coll.add(new Integer(i)); - for (int j = i+1; j < pop.size(); j++) { + for (int j = i + 1; j < pop.size(); j++) { if (result[j] == 0) { // check whether this guy is in the same grid as the // first guy... - tmpFit = ((AbstractEAIndividual)pop.get(j)).getFitness(); + tmpFit = ((AbstractEAIndividual) pop.get(j)).getFitness(); sameGrid = true; for (int k = 0; k < tmpFit.length; k++) { - tmpGrid[k] = (int)((tmpFit[k]-bounds[k][0])/grid[k]); + tmpGrid[k] = (int) ((tmpFit[k] - bounds[k][0]) / grid[k]); if (curGrid[k] == tmpGrid[k]) { sameGrid &= true; - } - else { + } else { sameGrid &= false; } } @@ -159,8 +162,8 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial // now i got all the boogies of the same grid element // lets assign them thier squeeze factor for (int j = 0; j < coll.size(); j++) { - result[((Integer)coll.get(j)).intValue()] = coll.size(); - tmpIndy = (AbstractEAIndividual)pop.get(((Integer)coll.get(j)).intValue()); + result[((Integer) coll.get(j)).intValue()] = coll.size(); + tmpIndy = (AbstractEAIndividual) pop.get(((Integer) coll.get(j)).intValue()); tmpIndy.putData("SqueezeFactor", new Integer(coll.size())); tmpIndy.putData("GridBox", curGrid); } @@ -174,28 +177,37 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Pareto Envelope-based Selection Algorithm revision 2.0."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "PESA II"; } - /** This method allows you to choose the grid width. - * @param b The new size of a grid element. + /** + * This method allows you to choose the grid width. + * + * @param b The new size of a grid element. */ public void setGridSize(int b) { this.m_GridSize = b; } + public int getGridSize() { return this.m_GridSize; } + public String gridSizeTipText() { return "Choose the number of a grid elements per dimension."; } diff --git a/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java b/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java index d541fbd7..4673874f 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java +++ b/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java @@ -11,7 +11,8 @@ import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; -/** The strength Pareto EA in it's second version, which is based on +/** + * The strength Pareto EA in it's second version, which is based on * dominance counts. * Created by IntelliJ IDEA. * User: streiche @@ -19,16 +20,16 @@ import eva2.tools.chart2d.DPoint; * Time: 15:01:06 * To change this template use File | Settings | File Templates. */ -public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serializable { +public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serializable { - private InterfaceDistanceMetric m_Metric = new ObjectiveSpaceMetric(); - private boolean soutDebug = false; + private InterfaceDistanceMetric m_Metric = new ObjectiveSpaceMetric(); + private boolean soutDebug = false; public ArchivingSPEAII() { } public ArchivingSPEAII(ArchivingSPEAII a) { - this.m_Metric = (InterfaceDistanceMetric)a.m_Metric.clone(); + this.m_Metric = (InterfaceDistanceMetric) a.m_Metric.clone(); } @Override @@ -36,10 +37,12 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial return (Object) new ArchivingSPEAII(this); } - /** This method allows you to merge two populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge two populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ @Override public void addElementsToArchive(Population pop) { @@ -50,13 +53,13 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial // First merge the current population and the archive Population tmpPop = new Population(); - tmpPop.addPopulation((Population)pop.getClone()); - tmpPop.addPopulation((Population)pop.getArchive().getClone()); + tmpPop.addPopulation((Population) pop.getClone()); + tmpPop.addPopulation((Population) pop.getArchive().getClone()); tmpPop.removeRedundantIndiesUsingFitness(); // double[][] d = this.showMay(tmpPop); - double[] RawFitness = this.calculateRawFitness(tmpPop); - double[] kthDistance = this.calculateKthDistance(tmpPop, Math.max(2,(int)Math.sqrt(tmpPop.size()))); + double[] RawFitness = this.calculateRawFitness(tmpPop); + double[] kthDistance = this.calculateKthDistance(tmpPop, Math.max(2, (int) Math.sqrt(tmpPop.size()))); // // set these values to the individuals // for (int i = 0; i < tmpPop.size(); i++) { // ((AbstractEAIndividual)tmpPop.get(i)).SetData("RavFitness", new Double(RawFitness[i])); @@ -82,7 +85,7 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial while (!archive.targetSizeReached()) { currentLevel++; for (int i = 0; i < RawFitness.length; i++) { - if ((RawFitness[i] >= currentLevel) && (RawFitness[i] < currentLevel +1)) { + if ((RawFitness[i] >= currentLevel) && (RawFitness[i] < currentLevel + 1)) { archive.add(tmpPop.get(i)); } } @@ -91,26 +94,26 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial // Here i want to remove surplus individuals *pff* // So the basic idea is to search on the highes level of // RawFitness for the lowest kthDistance()!!! - int ICurSma; - double curSmall, highestLevel; + int ICurSma; + double curSmall, highestLevel; while (archive.targetSizeExceeded()) { - highestLevel = 0; - RawFitness = this.calculateRawFitness(archive); + highestLevel = 0; + RawFitness = this.calculateRawFitness(archive); for (int i = 0; i < RawFitness.length; i++) { if (RawFitness[i] > highestLevel) { highestLevel = RawFitness[i]; } } - kthDistance = this.calculateKthDistance(archive, Math.max(2,(int)Math.sqrt(archive.size()))); - ICurSma = -1; - curSmall = Double.MAX_VALUE; + kthDistance = this.calculateKthDistance(archive, Math.max(2, (int) Math.sqrt(archive.size()))); + ICurSma = -1; + curSmall = Double.MAX_VALUE; for (int i = 0; i < kthDistance.length; i++) { if ((highestLevel == (RawFitness[i]) && (curSmall > kthDistance[i]))) { - curSmall = kthDistance[i]; - ICurSma = i; + curSmall = kthDistance[i]; + ICurSma = i; } } - archive.remove(ICurSma); + archive.remove(ICurSma); } pop.SetArchive(archive); @@ -126,7 +129,7 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial double[][] fitness = new double[tmp.size()][]; for (int i = 0; i < tmp.size(); i++) { - fitness[i] = ((AbstractEAIndividual)tmp.get(i)).getFitness(); + fitness[i] = ((AbstractEAIndividual) tmp.get(i)).getFitness(); } double[] minY, maxY; minY = fitness[0]; @@ -146,73 +149,75 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial return result; } - /** This method will calculate the raw fitness - * @param pop The population to evaluate + /** + * This method will calculate the raw fitness + * + * @param pop The population to evaluate * @return The raw fitness for all individuals */ private double[] calculateRawFitness(Population pop) { - double[] result = new double[pop.size()]; - int[] SPEAStrength; + double[] result = new double[pop.size()]; + int[] SPEAStrength; AbstractEAIndividual tmpIndy; - SPEAStrength = new int[pop.size()]; + SPEAStrength = new int[pop.size()]; // first calculate the SPEAStrength for (int i = 0; i < pop.size(); i++) { - result[i] = 0; + result[i] = 0; SPEAStrength[i] = 0; - tmpIndy = (AbstractEAIndividual)pop.get(i); + tmpIndy = (AbstractEAIndividual) pop.get(i); for (int j = 0; j < pop.size(); j++) { - if ((i!=j) && (!this.isEqualTo(tmpIndy, (AbstractEAIndividual)pop.get(j))) && (tmpIndy.isDominating((AbstractEAIndividual) pop.get(j)))) { + if ((i != j) && (!this.isEqualTo(tmpIndy, (AbstractEAIndividual) pop.get(j))) && (tmpIndy.isDominating((AbstractEAIndividual) pop.get(j)))) { SPEAStrength[i]++; } } } if (this.soutDebug) { for (int i = 0; i < SPEAStrength.length; i++) { - System.out.println("SPEAStrength "+i+": "+SPEAStrength[i]); + System.out.println("SPEAStrength " + i + ": " + SPEAStrength[i]); } } // now calculate the SPEAFitness for (int i = 0; i < pop.size(); i++) { for (int j = 0; j < pop.size(); j++) { - if ((i != j) && (!this.isEqualTo((AbstractEAIndividual)pop.get(i), (AbstractEAIndividual)pop.get(j))) && (((AbstractEAIndividual)pop.get(i)).isDominating(((AbstractEAIndividual)pop.get(j))))) { + if ((i != j) && (!this.isEqualTo((AbstractEAIndividual) pop.get(i), (AbstractEAIndividual) pop.get(j))) && (((AbstractEAIndividual) pop.get(i)).isDominating(((AbstractEAIndividual) pop.get(j))))) { result[j] += SPEAStrength[i]; if (this.soutDebug) { if (i == 14) { double[] f1, f2; - f1 = ((AbstractEAIndividual)pop.get(i)).getFitness(); - f2 = ((AbstractEAIndividual)pop.get(j)).getFitness(); + f1 = ((AbstractEAIndividual) pop.get(i)).getFitness(); + f2 = ((AbstractEAIndividual) pop.get(j)).getFitness(); for (int n = 0; n < f1.length; n++) { - System.out.println(""+Math.abs(f1[n]- f2[n])); + System.out.println("" + Math.abs(f1[n] - f2[n])); } } - System.out.println("Adding: " + SPEAStrength[i] + " to " + j +" because "+ i + " is dominating!"); + System.out.println("Adding: " + SPEAStrength[i] + " to " + j + " because " + i + " is dominating!"); } } } } if (this.soutDebug) { for (int i = 0; i < result.length; i++) { - System.out.println("Result "+i+": "+result[i]); + System.out.println("Result " + i + ": " + result[i]); } this.m_Plot = new Plot("Debug SPEAII", "Y1", "Y2", true); this.m_Plot.setUnconnectedPoint(0, 0, 11); this.m_Plot.setUnconnectedPoint(1.2, 2.0, 11); - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); + GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); double[][] trueFitness; trueFitness = new double[pop.size()][]; for (int i = 0; i < pop.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)pop.get(i)).getFitness(); - System.out.println("Fitness: ("+trueFitness[i][0]+"/"+trueFitness[i][1]+")"); + trueFitness[i] = ((AbstractEAIndividual) pop.get(i)).getFitness(); + System.out.println("Fitness: (" + trueFitness[i][0] + "/" + trueFitness[i][1] + ")"); } - DPoint myPoint; + DPoint myPoint; Chart2DDPointIconText tmp; mySet.setConnectedMode(false); for (int i = 0; i < trueFitness.length; i++) { myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp = new Chart2DDPointIconText(""+SPEAStrength[i]+"/"+result[i]); + tmp = new Chart2DDPointIconText("" + SPEAStrength[i] + "/" + result[i]); tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); @@ -226,53 +231,54 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial f1 = a1.getFitness(); f2 = a2.getFitness(); for (int i = 0; i < f1.length; i++) { - if (Math.abs(f1[i]- f2[i]) > 0.00000001) { + if (Math.abs(f1[i] - f2[i]) > 0.00000001) { return false; } } return false; } - /** This method will calculate the distance to the k-th neighbour. - * @param pop The population to compute. - * @param k The index k. + /** + * This method will calculate the distance to the k-th neighbour. + * + * @param pop The population to compute. + * @param k The index k. * @return The distance for each individual. */ public double[] calculateKthDistance(Population pop, int k) { - double[] result = new double[pop.size()]; - double[][] distMatrix = new double[pop.size()][pop.size()]; + double[] result = new double[pop.size()]; + double[][] distMatrix = new double[pop.size()][pop.size()]; // first let's compute the complete distance matrix for (int i = 0; i < pop.size(); i++) { distMatrix[i][i] = 0.0; - for (int j = i+1; j < pop.size(); j++) { - distMatrix[i][j] = this.m_Metric.distance((AbstractEAIndividual)pop.get(i), (AbstractEAIndividual)pop.get(j)); + for (int j = i + 1; j < pop.size(); j++) { + distMatrix[i][j] = this.m_Metric.distance((AbstractEAIndividual) pop.get(i), (AbstractEAIndividual) pop.get(j)); distMatrix[j][i] = distMatrix[i][j]; } } // now let's search for the k-th distance // for each individual - int current; - double currentSmallest; + int current; + double currentSmallest; for (int i = 0; i < result.length; i++) { // for the k-th distance for (int j = 0; j < k; j++) { // search for the smallest distance and set it to max - current = -1; + current = -1; currentSmallest = Double.MAX_VALUE; for (int n = 0; n < result.length; n++) { - if ((i!=n)&& (currentSmallest > distMatrix[i][n])) { - current = n; + if ((i != n) && (currentSmallest > distMatrix[i][n])) { + current = n; currentSmallest = distMatrix[i][n]; } } if (current >= 0) { result[i] = distMatrix[i][current]; - } - else { + } else { System.out.println("Error no smallest found in calculateKthDistance()."); } - distMatrix[i][current] = Double.MAX_VALUE; + distMatrix[i][current] = Double.MAX_VALUE; } } // double[] result = new double[pop.size()]; @@ -291,25 +297,26 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial } - /** This method will calculate the SPEA strength and the raw fitness for all + /** + * This method will calculate the SPEA strength and the raw fitness for all * individuals */ public double[] calculateSPEA(Population pop) { - int[] SPEAStrength, SPEAFitness; - double[] SPEAResult; - double[][] trueFitness; + int[] SPEAStrength, SPEAFitness; + double[] SPEAResult; + double[][] trueFitness; AbstractEAIndividual tmpIndy; - SPEAStrength = new int[pop.size()]; - SPEAFitness = new int[pop.size()]; - SPEAResult = new double[pop.size()]; - trueFitness = new double[pop.size()][]; + SPEAStrength = new int[pop.size()]; + SPEAFitness = new int[pop.size()]; + SPEAResult = new double[pop.size()]; + trueFitness = new double[pop.size()][]; // first calculate the SPEAStrength for (int i = 0; i < pop.size(); i++) { - tmpIndy = (AbstractEAIndividual)pop.get(i); + tmpIndy = (AbstractEAIndividual) pop.get(i); trueFitness[i] = tmpIndy.getFitness(); - for (int j = i+1; j < pop.size(); j++) { + for (int j = i + 1; j < pop.size(); j++) { if (tmpIndy.isDominating((AbstractEAIndividual) pop.get(j))) { SPEAStrength[i]++; } else { @@ -324,7 +331,7 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial for (int i = 0; i < pop.size(); i++) { for (int j = 0; j < pop.size(); j++) { if (i != j) { - if (((AbstractEAIndividual)pop.get(i)).isDominating(((AbstractEAIndividual)pop.get(j)))) { + if (((AbstractEAIndividual) pop.get(i)).isDominating(((AbstractEAIndividual) pop.get(j)))) { SPEAFitness[j] += SPEAStrength[i]; } } @@ -333,21 +340,21 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial // now i'll calculate the distance to the k'th neighbour // first let's calculate the complete distance matrix - double[][] distMatrix = new double[pop.size()][pop.size()]; - int k = (int)Math.sqrt(pop.size()); + double[][] distMatrix = new double[pop.size()][pop.size()]; + int k = (int) Math.sqrt(pop.size()); for (int i = 0; i < pop.size(); i++) { distMatrix[i][i] = 0.0; - for (int j = i+1; j < pop.size(); j++) { - distMatrix[i][j] = this.m_Metric.distance((AbstractEAIndividual)pop.get(i), (AbstractEAIndividual)pop.get(j)); + for (int j = i + 1; j < pop.size(); j++) { + distMatrix[i][j] = this.m_Metric.distance((AbstractEAIndividual) pop.get(i), (AbstractEAIndividual) pop.get(j)); distMatrix[j][i] = distMatrix[i][j]; } } // now find the k'th distance *grml grml* what a mess! double[] tmpD = new double[pop.size()]; - double[] D = new double[pop.size()]; + double[] D = new double[pop.size()]; for (int i = 0; i < tmpD.length; i++) { tmpD[i] = Double.POSITIVE_INFINITY; - D[i] = Double.NEGATIVE_INFINITY; + D[i] = Double.NEGATIVE_INFINITY; } for (int i = 0; i < k; i++) { for (int j = 0; j < tmpD.length; j++) { @@ -365,12 +372,12 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial // now set the SPEAFitness for (int i = 0; i < SPEAResult.length; i++) { - if (1/(2+D[i]) >= 1) { - System.out.println("d " +1/(2+D[i])); + if (1 / (2 + D[i]) >= 1) { + System.out.println("d " + 1 / (2 + D[i])); } - SPEAResult[i] = SPEAFitness[i] + (1/(2+D[i])); - ((AbstractEAIndividual)pop.get(i)).putData("RawFit", new Double(SPEAFitness[i])); - ((AbstractEAIndividual)pop.get(i)).putData("SPEAFit", new Double(SPEAResult[i])); + SPEAResult[i] = SPEAFitness[i] + (1 / (2 + D[i])); + ((AbstractEAIndividual) pop.get(i)).putData("RawFit", new Double(SPEAFitness[i])); + ((AbstractEAIndividual) pop.get(i)).putData("SPEAFit", new Double(SPEAResult[i])); } // Puh! @@ -380,13 +387,18 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Strength Pareto EA revision 2.0. The variable k to calculate the k-th distance is given by max(2, sqrt(archive.size()))."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/archiving/InformationRetrievalInserting.java b/src/eva2/optimization/operator/archiving/InformationRetrievalInserting.java index 9278558c..f2dbe62c 100644 --- a/src/eva2/optimization/operator/archiving/InformationRetrievalInserting.java +++ b/src/eva2/optimization/operator/archiving/InformationRetrievalInserting.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.population.Population; -/** This information retrieval inserts the retrieved +/** + * This information retrieval inserts the retrieved * solutions, by removing random individuals from the * population. * Created by IntelliJ IDEA. @@ -24,9 +25,11 @@ public class InformationRetrievalInserting implements InterfaceInformationRetrie return (Object) new InformationRetrievalInserting(this); } - /** This method will allow Information Retrieval from a archive onto + /** + * This method will allow Information Retrieval from a archive onto * an already existing population. - * @param pop The population. + * + * @param pop The population. */ @Override public void retrieveInformationFrom(Population pop) { @@ -37,24 +40,29 @@ public class InformationRetrievalInserting implements InterfaceInformationRetrie } if (archive.size() < pop.getTargetSize()) { // remove archive size individuals from pop - pop.removeNIndividuals(archive.size()-(pop.getTargetSize()-pop.size())); + pop.removeNIndividuals(archive.size() - (pop.getTargetSize() - pop.size())); } else { pop.clear(); } - pop.addPopulation((Population)archive.getClone()); + pop.addPopulation((Population) archive.getClone()); } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This Information Retrieval will insert the archive into current population by replacing random individuals if necessary."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/archiving/InformationRetrievalNone.java b/src/eva2/optimization/operator/archiving/InformationRetrievalNone.java index 1ff02505..632c3b92 100644 --- a/src/eva2/optimization/operator/archiving/InformationRetrievalNone.java +++ b/src/eva2/optimization/operator/archiving/InformationRetrievalNone.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.population.Population; -/** This class allows no information retrieval and thus no elitism +/** + * This class allows no information retrieval and thus no elitism * for MOEAs. * Created by IntelliJ IDEA. * User: streiche @@ -23,9 +24,11 @@ public class InformationRetrievalNone implements InterfaceInformationRetrieval, return (Object) new InformationRetrievalNone(this); } - /** This method will allow Information Retrieval from a archive onto + /** + * This method will allow Information Retrieval from a archive onto * an already existing population. - * @param pop The population. + * + * @param pop The population. */ @Override public void retrieveInformationFrom(Population pop) { @@ -35,13 +38,18 @@ public class InformationRetrievalNone implements InterfaceInformationRetrieval, /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This implements a deactivated Information Retrieval."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/archiving/InformationRetrievalReplacing.java b/src/eva2/optimization/operator/archiving/InformationRetrievalReplacing.java index 73ced066..468a7583 100644 --- a/src/eva2/optimization/operator/archiving/InformationRetrievalReplacing.java +++ b/src/eva2/optimization/operator/archiving/InformationRetrievalReplacing.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** This information retrieval method simply add the retrieved solutions +/** + * This information retrieval method simply add the retrieved solutions * to the current population. * Created by IntelliJ IDEA. * User: streiche @@ -24,9 +25,11 @@ public class InformationRetrievalReplacing implements InterfaceInformationRetrie return (Object) new InformationRetrievalReplacing(this); } - /** This method will allow Information Retrieval from a archive onto + /** + * This method will allow Information Retrieval from a archive onto * an already existing population. - * @param pop The population. + * + * @param pop The population. */ @Override public void retrieveInformationFrom(Population pop) { @@ -38,7 +41,7 @@ public class InformationRetrievalReplacing implements InterfaceInformationRetrie tmp.addPopulation(archive); while (tmp.size() < archive.getTargetSize()) { - tmp.add(pop.get(RNG.randomInt(0,pop.size()-1))); + tmp.add(pop.get(RNG.randomInt(0, pop.size() - 1))); } pop.clear(); @@ -48,13 +51,18 @@ public class InformationRetrievalReplacing implements InterfaceInformationRetrie /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This Information Retrieval will replace the current population by the archive."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/archiving/InterfaceArchiving.java b/src/eva2/optimization/operator/archiving/InterfaceArchiving.java index bdee1719..498e4664 100644 --- a/src/eva2/optimization/operator/archiving/InterfaceArchiving.java +++ b/src/eva2/optimization/operator/archiving/InterfaceArchiving.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.population.Population; -/** This Interface give the general methods required for a archiving method. +/** + * This Interface give the general methods required for a archiving method. * Created by IntelliJ IDEA. * User: streiche * Date: 05.06.2003 @@ -11,15 +12,19 @@ import eva2.optimization.population.Population; */ public interface InterfaceArchiving { - /** This method allows you to make a deep clone of the object + /** + * This method allows you to make a deep clone of the object + * * @return the deep clone */ public Object clone(); - /** This method allows you to merge to populations into an archive. - * This method will add elements from pop to the archive but will also - * remove elements from the archive if the archive target size is exceeded. - * @param pop The population that may add Individuals to the archive. + /** + * This method allows you to merge to populations into an archive. + * This method will add elements from pop to the archive but will also + * remove elements from the archive if the archive target size is exceeded. + * + * @param pop The population that may add Individuals to the archive. */ public void addElementsToArchive(Population pop); } diff --git a/src/eva2/optimization/operator/archiving/InterfaceInformationRetrieval.java b/src/eva2/optimization/operator/archiving/InterfaceInformationRetrieval.java index ba74479d..a1169aaf 100644 --- a/src/eva2/optimization/operator/archiving/InterfaceInformationRetrieval.java +++ b/src/eva2/optimization/operator/archiving/InterfaceInformationRetrieval.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.population.Population; -/** This interface gives the necessary methods for an information +/** + * This interface gives the necessary methods for an information * retrieval algorithm. * Created by IntelliJ IDEA. * User: streiche @@ -12,15 +13,19 @@ import eva2.optimization.population.Population; */ public interface InterfaceInformationRetrieval { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method will allow Information Retrieval from a archive onto + /** + * This method will allow Information Retrieval from a archive onto * an already existing population. - * @param pop The population. + * + * @param pop The population. */ public void retrieveInformationFrom(Population pop); } diff --git a/src/eva2/optimization/operator/archiving/InterfaceRemoveSurplusIndividuals.java b/src/eva2/optimization/operator/archiving/InterfaceRemoveSurplusIndividuals.java index 9d16b7cd..555ebc5c 100644 --- a/src/eva2/optimization/operator/archiving/InterfaceRemoveSurplusIndividuals.java +++ b/src/eva2/optimization/operator/archiving/InterfaceRemoveSurplusIndividuals.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.archiving; import eva2.optimization.population.Population; -/** This interface gives the method necessary for an aglorithm +/** + * This interface gives the method necessary for an aglorithm * which is use to reduce the size of an archive. * Created by IntelliJ IDEA. * User: streiche @@ -11,15 +12,19 @@ import eva2.optimization.population.Population; * To change this template use File | Settings | File Templates. */ public interface InterfaceRemoveSurplusIndividuals { - - /** This method allows you to make a deep clone of + + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method will remove surplus individuals + /** + * This method will remove surplus individuals * from a given archive. Note archive will be altered! + * * @param archive */ public void removeSurplusIndividuals(Population archive); diff --git a/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsDynamicHyperCube.java b/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsDynamicHyperCube.java index 08bb2c60..b323b21f 100644 --- a/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsDynamicHyperCube.java +++ b/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsDynamicHyperCube.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** This class removes surplus individuals based on bounding +/** + * This class removes surplus individuals based on bounding * hybercube, which can be calculated in objective or decision * space. But i guess currently you can't toggel that. But here * the hybercubes are dynamic, e.g. theey are recalculated after @@ -28,22 +29,24 @@ public class RemoveSurplusIndividualsDynamicHyperCube implements InterfaceRemove return (Object) new RemoveSurplusIndividualsDynamicHyperCube(this); } - /** This method will remove surplus individuals + /** + * This method will remove surplus individuals * from a given archive. Note archive will be altered! + * * @param archive */ @Override public void removeSurplusIndividuals(Population archive) { - double[][] fitness; - double[] space; - int indexSmallHyperCube; - while(archive.targetSizeExceeded()) { + double[][] fitness; + double[] space; + int indexSmallHyperCube; + while (archive.targetSizeExceeded()) { // select the individual with the least space around him // to do this i got to find the next smaller and the next bigger one fitness = new double[archive.size()][]; - space = new double[archive.size()]; + space = new double[archive.size()]; for (int i = 0; i < archive.size(); i++) { - fitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); + fitness[i] = ((AbstractEAIndividual) archive.get(i)).getFitness(); } space = this.calculateHyperCubeVolumes(fitness); // now find the individual with the smallest hypervolume @@ -51,26 +54,27 @@ public class RemoveSurplusIndividualsDynamicHyperCube implements InterfaceRemove for (int i = 1; i < archive.size(); i++) { if (space[i] < space[indexSmallHyperCube]) { indexSmallHyperCube = i; - } - else { + } else { // if they are equal give them a fair chance to exchange between them if ((space[i] == space[indexSmallHyperCube]) && (RNG.flipCoin(0.5))) { indexSmallHyperCube = i; } - } + } } archive.remove(indexSmallHyperCube); } } - /** This method calculates the surrounding hypervolumes for a given array of fitness values - * @param fitness The array of multi dimensional fitness values. + /** + * This method calculates the surrounding hypervolumes for a given array of fitness values + * + * @param fitness The array of multi dimensional fitness values. * @return An array of hypercube volumes, */ public double[] calculateHyperCubeVolumes(double[][] fitness) { - double[] result = new double[fitness.length]; - int upperI, lowerI; - double upperX, lowerX; + double[] result = new double[fitness.length]; + int upperI, lowerI; + double upperX, lowerX; for (int i = 0; i < fitness.length; i++) { result[i] = 1; @@ -98,8 +102,7 @@ public class RemoveSurplusIndividualsDynamicHyperCube implements InterfaceRemove // now i should have the lower and the upperbound if ((upperI == -1) || (lowerI == -1)) { result[i] *= Double.POSITIVE_INFINITY; - } - else { + } else { result[i] *= Math.abs(Math.abs(fitness[upperI][y] - fitness[lowerI][y])); } } diff --git a/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsSMetric.java b/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsSMetric.java index 14541200..41b7dfe0 100644 --- a/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsSMetric.java +++ b/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsSMetric.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** This class removes surplus individuals based on bounding +/** + * This class removes surplus individuals based on bounding * hybercube, which can be calculated in objective or decision * space. But i guess currently you can't toggel that. But here * the hybercubes are dynamic, e.g. theey are recalculated after @@ -28,22 +29,24 @@ public class RemoveSurplusIndividualsSMetric implements InterfaceRemoveSurplusIn return (Object) new RemoveSurplusIndividualsSMetric(this); } - /** This method will remove surplus individuals + /** + * This method will remove surplus individuals * from a given archive. Note archive will be altered! + * * @param archive */ @Override public void removeSurplusIndividuals(Population archive) { - double[][] fitness; - double[] space; - int indexSmallHyperCube; - while(archive.targetSizeExceeded()) { + double[][] fitness; + double[] space; + int indexSmallHyperCube; + while (archive.targetSizeExceeded()) { // select the individual with the least space around him // to do this i got to find the next smaller and the next bigger one fitness = new double[archive.size()][]; - space = new double[archive.size()]; + space = new double[archive.size()]; for (int i = 0; i < archive.size(); i++) { - fitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); + fitness[i] = ((AbstractEAIndividual) archive.get(i)).getFitness(); } space = this.calculateContributingHypervolume(fitness); // now find the individual with the smallest hypervolume @@ -51,136 +54,123 @@ public class RemoveSurplusIndividualsSMetric implements InterfaceRemoveSurplusIn for (int i = 1; i < archive.size(); i++) { if (space[i] < space[indexSmallHyperCube]) { indexSmallHyperCube = i; - } - else { + } else { // if they are equal give them a fair chance to exchange between them if ((space[i] == space[indexSmallHyperCube]) && (RNG.flipCoin(0.5))) { indexSmallHyperCube = i; } - } + } } archive.remove(indexSmallHyperCube); } } public double[] calculateContributingHypervolume(double[][] fitness) { - - + + int counter; - // Vector< Integer > sort=new Vector(); - // Vector< Integer > global=new Vector(); - // Vector< Boolean > assigned=new Vector(); - int size=fitness.length;//TODO size bestimmen (anzahl individuen?) - double result[]=new double[size]; - int[] sort=new int[size]; - int[] global=new int[size]; - boolean[] assigned=new boolean[size]; + // Vector< Integer > sort=new Vector(); + // Vector< Integer > global=new Vector(); + // Vector< Boolean > assigned=new Vector(); + int size = fitness.length;//TODO size bestimmen (anzahl individuen?) + double result[] = new double[size]; + int[] sort = new int[size]; + int[] global = new int[size]; + boolean[] assigned = new boolean[size]; double temp1; double temp2; double v; int i, left, right; - - + // Initialize sharing values - // setMOOShare(0.0); - - + // setMOOShare(0.0); - // gather individuals with the same rank into a sub population - // PopulationMOO subpop( numberOfMOORank( rank ) ); - counter = 0; - for (i = 0; i < fitness.length; i++) - { - global[ counter ] = i; - counter++; + // gather individuals with the same rank into a sub population + // PopulationMOO subpop( numberOfMOORank( rank ) ); + counter = 0; + for (i = 0; i < fitness.length; i++) { + global[counter] = i; + counter++; + } + + // sort according to 1st objective + int obj = 0; + // initialization of index vector + for (i = 0; i < size; i++) { + sort[i] = i; + assigned[i] = false; + } + // sort + boolean changed; + + + changed = false; + for (i = 0; i < counter - 1; i++) { + + temp1 = fitness[global[sort[i]]][obj]; + temp2 = fitness[global[sort[i + 1]]][obj]; + + if (temp1 > temp2) { + int temp = sort[i]; + sort[i] = sort[i + 1]; + sort[i + 1] = temp; + changed = true; } + } - // sort according to 1st objective - int obj = 0; - // initialization of index vector - for (i = 0; i < size; i++) - { - sort[ i ] = i; assigned[ i ] = false; - } - // sort - boolean changed; - - - changed = false; - for (i = 0; i < counter - 1; i++) - { - - temp1=fitness[ global[ sort[ i ] ]][obj]; - temp2=fitness[ global[ sort[ i+1 ] ]][obj]; - - if (temp1 > temp2) - { - int temp = sort[ i ]; - sort[ i ] = sort[ i + 1 ]; - sort[ i + 1 ] = temp; - changed = true ; + while (changed) { + changed = false; + for (i = 0; i < counter - 1; i++) { + + temp1 = fitness[global[sort[i]]][obj]; + temp2 = fitness[global[sort[i + 1]]][obj]; + + if (temp1 > temp2) { + int temp = sort[i]; + sort[i] = sort[i + 1]; + sort[i + 1] = temp; + changed = true; } } - - while(changed){ - changed = false; - for (i = 0; i < counter - 1; i++) - { - - temp1=fitness[ global[ sort[ i ] ]][obj]; - temp2=fitness[ global[ sort[ i+1 ] ]][obj]; - - if (temp1 > temp2) - { - int temp = sort[ i ]; - sort[ i ] = sort[ i + 1 ]; - sort[ i + 1 ] = temp; - changed = true ; + } + + + result[global[sort[0]]] = Double.MAX_VALUE; //die beiden aussen bekommen maximal wert als smeasure + result[global[sort[counter - 1]]] = Double.MAX_VALUE; + + for (int e = 1; e < counter - 1; e++) { // loop over all non-border elements + for (i = 1; (assigned[sort[i]]); i++) ; // determine 1st not assigned, non-border element + for (left = 0; i < counter - 1; ) { // loop over all not assigned elements + // determine right not assigned neighbor + for (right = i + 1; (assigned[sort[right]]); right++) ; + + + v = (fitness[global[sort[right]]][0] - + fitness[global[sort[i]]][0]) * + (fitness[global[sort[left]]][1] - + fitness[global[sort[i]]][1]); + + result[global[sort[i]]] = v; + + left = i; + i = right; + } + int minIndex = 0; + double min = result[global[sort[minIndex]]]; + for (int f = 1; f < counter - 1; f++) { + if (!assigned[sort[f]]) { + if (result[global[sort[f]]] < min) { + min = result[global[sort[f]]]; + minIndex = f; } } } - - - result[global[ sort[ 0 ] ]]=Double.MAX_VALUE; //die beiden aussen bekommen maximal wert als smeasure - result[global[ sort[ counter - 1 ] ]]=Double.MAX_VALUE; - - for (int e = 1; e < counter - 1; e++) - { // loop over all non-border elements - for (i = 1; (assigned[ sort[ i ] ]); i++); // determine 1st not assigned, non-border element - for (left = 0; i < counter - 1;) - { // loop over all not assigned elements - // determine right not assigned neighbor - for (right = i + 1; (assigned[ sort[ right ] ]); right++); - - - v = (fitness[ global[ sort[ right ] ] ][0] - - fitness[global[ sort[ i ] ] ][0]) * - (fitness[global[ sort[ left ] ] ][1] - - fitness[global[ sort[ i ] ] ][1]); - - result[ global[ sort[ i ] ]]=v; - - left = i; - i = right; - } - int minIndex = 0; - double min = result[ global[ sort[ minIndex ] ]]; - for (int f = 1; f < counter - 1; f++) - { - if (!assigned[ sort[ f ] ]) { - if (result[global[ sort[ f ] ]] < min) - { - min = result[global[ sort[ f ] ]]; - minIndex = f; - } - } - } - assigned[ sort[ minIndex ] ] = true; - result[ global[ sort[ minIndex ] ]]=e; - } - return result; + assigned[sort[minIndex]] = true; + result[global[sort[minIndex]]] = e; + } + return result; } - + } \ No newline at end of file diff --git a/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsStaticHyperCube.java b/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsStaticHyperCube.java index b11271bf..eb6821e7 100644 --- a/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsStaticHyperCube.java +++ b/src/eva2/optimization/operator/archiving/RemoveSurplusIndividualsStaticHyperCube.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** This class removes surplus individuals based on bounding +/** + * This class removes surplus individuals based on bounding * hybercube, which can be calculated in objective or decision * space. But i guess currently you can't toggel that. But here * the hybercubes are static, e.g. theey are not recalculated after @@ -28,41 +29,43 @@ public class RemoveSurplusIndividualsStaticHyperCube extends RemoveSurplusIndivi return (Object) new RemoveSurplusIndividualsStaticHyperCube(this); } - /** This method will remove surplus individuals + /** + * This method will remove surplus individuals * from a given archive. Note archive will be altered! + * * @param archive */ @Override public void removeSurplusIndividuals(Population archive) { - double[][] fitness; - double[] space; - int indexSmallHyperCube; - double smallestHyperCube, tmpS; + double[][] fitness; + double[] space; + int indexSmallHyperCube; + double smallestHyperCube, tmpS; fitness = new double[archive.size()][]; - space = new double[archive.size()]; + space = new double[archive.size()]; for (int i = 0; i < archive.size(); i++) { - fitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); + fitness[i] = ((AbstractEAIndividual) archive.get(i)).getFitness(); } space = this.calculateHyperCubeVolumes(fitness); for (int i = 0; i < archive.size(); i++) { - ((AbstractEAIndividual)archive.get(i)).putData("HyperCube", new Double(space[i])); + ((AbstractEAIndividual) archive.get(i)).putData("HyperCube", new Double(space[i])); } - while(archive.targetSizeExceeded()) { + while (archive.targetSizeExceeded()) { // select the individual with the least space around him // to do this i got to find the next smaller and the next bigger one - smallestHyperCube = ((Double)((AbstractEAIndividual)archive.get(0)).getData("HyperCube")).doubleValue(); + smallestHyperCube = ((Double) ((AbstractEAIndividual) archive.get(0)).getData("HyperCube")).doubleValue(); indexSmallHyperCube = 0; for (int i = 1; i < archive.size(); i++) { - tmpS = ((Double)((AbstractEAIndividual)archive.get(i)).getData("HyperCube")).doubleValue(); + tmpS = ((Double) ((AbstractEAIndividual) archive.get(i)).getData("HyperCube")).doubleValue(); if (tmpS < smallestHyperCube) { - smallestHyperCube = tmpS; + smallestHyperCube = tmpS; indexSmallHyperCube = i; } else { // if they are equal give them a fair chance to exchange between them if ((tmpS == smallestHyperCube) && (RNG.flipCoin(0.5))) { - smallestHyperCube = tmpS; + smallestHyperCube = tmpS; indexSmallHyperCube = i; } } diff --git a/src/eva2/optimization/operator/classification/ClassificationSelfOrganizingMaps.java b/src/eva2/optimization/operator/classification/ClassificationSelfOrganizingMaps.java index 3e7ee291..8a663a2e 100644 --- a/src/eva2/optimization/operator/classification/ClassificationSelfOrganizingMaps.java +++ b/src/eva2/optimization/operator/classification/ClassificationSelfOrganizingMaps.java @@ -2,12 +2,14 @@ package eva2.optimization.operator.classification; import eva2.tools.chart2d.*; import eva2.tools.math.RNG; + import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.*; -/** Self-organizing maps, a simple, but easy to visualize method +/** + * Self-organizing maps, a simple, but easy to visualize method * for classification. The Dikel flag is an undocumented extension, * which seems to work but is not published. * Created by IntelliJ IDEA. @@ -19,29 +21,30 @@ import javax.swing.*; public class ClassificationSelfOrganizingMaps implements java.io.Serializable, InterfaceClassification { /** - * Generated serial version identifer. - */ - private static final long serialVersionUID = 1447707947002269263L; - private int m_Dim1 = 5, m_Dim2 = 15; - private int m_AlternativeClasses; - private double[][][] m_SOM; - private int[][][] m_SOMClass; - private double[][] m_Range; //[dimension][min, max, mean, sigma] - private double m_Alpha = 0.4; - private int m_TrainingCycles = 250; - private int m_NeighborhoodSize = 2; - private boolean m_DikelThis = true; - private boolean debug = false; + * Generated serial version identifer. + */ + private static final long serialVersionUID = 1447707947002269263L; + private int m_Dim1 = 5, m_Dim2 = 15; + private int m_AlternativeClasses; + private double[][][] m_SOM; + private int[][][] m_SOMClass; + private double[][] m_Range; //[dimension][min, max, mean, sigma] + private double m_Alpha = 0.4; + private int m_TrainingCycles = 250; + private int m_NeighborhoodSize = 2; + private boolean m_DikelThis = true; + private boolean debug = false; public ClassificationSelfOrganizingMaps() { } + public ClassificationSelfOrganizingMaps(ClassificationSelfOrganizingMaps a) { - this.m_Dim1 = a.m_Dim1; - this.m_Dim2 = a.m_Dim2; - this.m_AlternativeClasses = a.m_AlternativeClasses; - this.m_NeighborhoodSize = a.m_NeighborhoodSize; - this.m_Alpha = a.m_Alpha; - this.m_DikelThis = a.m_DikelThis; + this.m_Dim1 = a.m_Dim1; + this.m_Dim2 = a.m_Dim2; + this.m_AlternativeClasses = a.m_AlternativeClasses; + this.m_NeighborhoodSize = a.m_NeighborhoodSize; + this.m_Alpha = a.m_Alpha; + this.m_DikelThis = a.m_DikelThis; this.m_TrainingCycles = a.m_TrainingCycles; if (a.m_SOM != null) { this.m_SOM = new double[a.m_SOM.length][a.m_SOM[0].length][a.m_SOM[0][0].length]; @@ -74,8 +77,10 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } } - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override @@ -83,9 +88,11 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I return (Object) new ClassificationSelfOrganizingMaps(this); } - /** This method will init the classificator - * @param space The double[n][d] space - * @param type The classes [0,1,..] + /** + * This method will init the classificator + * + * @param space The double[n][d] space + * @param type The classes [0,1,..] */ @Override public void init(double[][] space, int[] type) { @@ -94,9 +101,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I this.m_AlternativeClasses = Math.max(type[i], this.m_AlternativeClasses); } this.m_AlternativeClasses++; - this.m_SOM = new double[this.m_Dim1][this.m_Dim2][space[0].length]; - this.m_SOMClass = new int[this.m_Dim1][this.m_Dim2][this.m_AlternativeClasses]; - this.m_Range = new double[space[0].length][4]; + this.m_SOM = new double[this.m_Dim1][this.m_Dim2][space[0].length]; + this.m_SOMClass = new int[this.m_Dim1][this.m_Dim2][this.m_AlternativeClasses]; + this.m_Range = new double[space[0].length][4]; for (int i = 0; i < this.m_Range.length; i++) { this.m_Range[i][0] = Double.POSITIVE_INFINITY; this.m_Range[i][1] = Double.NEGATIVE_INFINITY; @@ -111,26 +118,27 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } } for (int i = 0; i < this.m_Range.length; i++) { - this.m_Range[i][2] /= ((double)space.length); + this.m_Range[i][2] /= ((double) space.length); for (int j = 0; j < space.length; j++) { this.m_Range[i][3] += Math.pow((this.m_Range[i][2] - space[j][i]), 2); } - this.m_Range[i][3] = Math.sqrt(this.m_Range[i][3]/((double)space.length)); + this.m_Range[i][3] = Math.sqrt(this.m_Range[i][3] / ((double) space.length)); // System.out.println("Range: ["+this.m_Range[i][0]+", "+this.m_Range[i][1]+"] Mean: "+this.m_Range[i][2]+" Var: "+this.m_Range[i][3]); } this.initSOM(); // if (this.debug) this.drawSOM(space, type); } - /** This method inits the weights of the SOM in the current range + /** + * This method inits the weights of the SOM in the current range */ private void initSOM() { for (int i = 0; i < this.m_SOM.length; i++) { for (int j = 0; j < this.m_SOM[0].length; j++) { for (int k = 0; k < this.m_SOM[0][0].length; k++) { - this.m_SOM[i][j][k] = 0*RNG.randomDouble( - (this.m_Range[k][0] - this.m_Range[k][2])/(1+this.m_Range[k][3]), - (this.m_Range[k][1] - this.m_Range[k][2])/(1+this.m_Range[k][3])); + this.m_SOM[i][j][k] = 0 * RNG.randomDouble( + (this.m_Range[k][0] - this.m_Range[k][2]) / (1 + this.m_Range[k][3]), + (this.m_Range[k][1] - this.m_Range[k][2]) / (1 + this.m_Range[k][3])); } for (int k = 0; k < this.m_SOMClass[0][0].length; k++) { this.m_SOMClass[i][j][k] = 0; @@ -139,11 +147,13 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } } - /** This method allows you to train the classificator based on + /** + * This method allows you to train the classificator based on * double[d] values and the class. n gives the number of instances * and d gives the dimension of the search space. - * @param space The double[n][d] space - * @param type The int[n] classes [0,1,..] + * + * @param space The double[n][d] space + * @param type The int[n] classes [0,1,..] */ @Override public void train(double[][] space, int[] type) { @@ -156,8 +166,8 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } } // now train the stuff - int[] order; - int[] winner; + int[] order; + int[] winner; for (int t = 0; t < this.m_TrainingCycles; t++) { // train the full set order = RNG.randomPerm(space.length); @@ -165,7 +175,7 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I winner = this.findWinningNeuron(space[order[i]]); // now i got the winning neuron *puh* // update this neuron and the neighbors - this.update(winner, space[order[i]], t/((double)this.m_TrainingCycles)); + this.update(winner, space[order[i]], t / ((double) this.m_TrainingCycles)); } // if (this.debug) this.drawSOM(space, type); @@ -181,15 +191,17 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } } - /** This method updates a given winner neuron and it's neighbours - * @param w The winner coordinates [x,y] - * @param data The current data point - * @param t The current time + /** + * This method updates a given winner neuron and it's neighbours + * + * @param w The winner coordinates [x,y] + * @param data The current data point + * @param t The current time */ private void update(int[] w, double[] data, double t) { - double a = this.m_Alpha*(1-t); - double dist; - int[] tmpI = new int[2]; + double a = this.m_Alpha * (1 - t); + double dist; + int[] tmpI = new int[2]; // move the winner to the data point if (this.m_DikelThis) { @@ -204,20 +216,22 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I // not the original point if ((j != 0) || (i != 0)) { // not outside the array - if ((this.m_SOM.length > w[0]+i) && (w[0]+i>= 0) - && (this.m_SOM[0].length > w[1]+j) && (w[1]+j>= 0)) { - dist = Math.sqrt(i*i + j*j); - tmpI[0] = w[0]+i; - tmpI[1] = w[1]+j; - this.moveNeuronTo(tmpI, data, a/dist); + if ((this.m_SOM.length > w[0] + i) && (w[0] + i >= 0) + && (this.m_SOM[0].length > w[1] + j) && (w[1] + j >= 0)) { + dist = Math.sqrt(i * i + j * j); + tmpI[0] = w[0] + i; + tmpI[1] = w[1] + j; + this.moveNeuronTo(tmpI, data, a / dist); } } } } } - /** This method finds the winning neuron for a given data point - * @param data The data point + /** + * This method finds the winning neuron for a given data point + * + * @param data The data point */ private int[] findWinningNeuron(double[] data) { double minDist = Double.POSITIVE_INFINITY, dist; @@ -238,49 +252,55 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I return result; } - /** This method returns the euclidian distance between a neuron + /** + * This method returns the euclidian distance between a neuron * and a data point - * @param n The neuron - * @param d The data point + * + * @param n The neuron + * @param d The data point * @return The distance between them */ public double distance(double[] n, double[] d) { double result = 0; for (int i = 0; i < n.length; i++) { - result += Math.pow(n[i] - (d[i] - this.m_Range[i][2])/(1+this.m_Range[i][3]), 2); + result += Math.pow(n[i] - (d[i] - this.m_Range[i][2]) / (1 + this.m_Range[i][3]), 2); } result = Math.sqrt(result); return result; } - /** This method moves a neuron to a data point - * @param w The neuron - * @param d The data point - * @param a The scaling factor + /** + * This method moves a neuron to a data point + * + * @param w The neuron + * @param d The data point + * @param a The scaling factor */ public void moveNeuronTo(int[] w, double[] d, double a) { double[] vec = new double[this.m_SOM[w[0]][w[1]].length]; for (int i = 0; i < this.m_SOM[w[0]][w[1]].length; i++) { - vec[i] = (d[i] - this.m_Range[i][2])/(1+this.m_Range[i][3]) - this.m_SOM[w[0]][w[1]][i]; + vec[i] = (d[i] - this.m_Range[i][2]) / (1 + this.m_Range[i][3]) - this.m_SOM[w[0]][w[1]][i]; this.m_SOM[w[0]][w[1]][i] += a * vec[i]; } } - /** This method moves the winner neuro in a wierd way + /** + * This method moves the winner neuro in a wierd way * back and forth again - * @param w The neuron - * @param d The data point - * @param a The scaling factor + * + * @param w The neuron + * @param d The data point + * @param a The scaling factor */ public void drikelWinnerTo(int[] w, double[] d, double a) { double[] vec = new double[this.m_SOM[w[0]][w[1]].length]; double[] nec = new double[this.m_SOM[w[0]][w[1]].length]; for (int i = 0; i < this.m_SOM[w[0]][w[1]].length; i++) { - vec[i] = (d[i] - this.m_Range[i][2])/(1+this.m_Range[i][3]) - this.m_SOM[w[0]][w[1]][i]; + vec[i] = (d[i] - this.m_Range[i][2]) / (1 + this.m_Range[i][3]) - this.m_SOM[w[0]][w[1]][i]; nec[i] = 0; } for (int i = -1; i <= 1; i++) { @@ -288,23 +308,25 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I // not the original point if ((j != 0) || (i != 0)) { // not outside the array - if ((this.m_SOM.length > w[0]+i) && (w[0]+i>= 0) - && (this.m_SOM[0].length > w[1]+j) && (w[1]+j>= 0)) { + if ((this.m_SOM.length > w[0] + i) && (w[0] + i >= 0) + && (this.m_SOM[0].length > w[1] + j) && (w[1] + j >= 0)) { for (int k = 0; k < this.m_SOM[0][0].length; k++) { - nec[k] += (d[k] - this.m_Range[k][2])/(1+this.m_Range[k][3]) - this.m_SOM[w[0]+i][w[1]+j][k]; + nec[k] += (d[k] - this.m_Range[k][2]) / (1 + this.m_Range[k][3]) - this.m_SOM[w[0] + i][w[1] + j][k]; } } } } } for (int i = 0; i < this.m_SOM[w[0]][w[1]].length; i++) { - vec[i] -= (a/2.0)*nec[i]; + vec[i] -= (a / 2.0) * nec[i]; this.m_SOM[w[0]][w[1]][i] += a * vec[i]; } } - /** This method will classify a given data point - * @param point The double[d] data point. + /** + * This method will classify a given data point + * + * @param point The double[d] data point. * @return type The resulting class. */ @Override @@ -315,14 +337,15 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I for (int i = 0; i < this.m_SOMClass[winner[0]][winner[1]].length; i++) { if (mostClasses < this.m_SOMClass[winner[0]][winner[1]][i]) { - result = i; + result = i; mostClasses = this.m_SOMClass[winner[0]][winner[1]][i]; } } return result; } - /** For debugging only + /** + * For debugging only */ private void drawSOM(double[][] data, int[] types) { JFrame frame = new JFrame(); @@ -338,8 +361,8 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I System.exit(0); } }); - DLine tmpL; - double[] pos1, pos2; + DLine tmpL; + double[] pos1, pos2; ScaledBorder myBorder = new ScaledBorder(); DArea area = new DArea(); area.setBorder(myBorder); @@ -347,13 +370,13 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I for (int i = 0; i < this.m_SOM.length; i++) { for (int j = 0; j < this.m_SOM[0].length; j++) { pos1 = this.m_SOM[i][j]; - if ((i+1) < this.m_SOM.length) { - pos2 = this.m_SOM[i+1][j]; + if ((i + 1) < this.m_SOM.length) { + pos2 = this.m_SOM[i + 1][j]; tmpL = new DLine(pos1[0], pos1[1], pos2[0], pos2[1], Color.BLACK); area.addDElement(tmpL); } - if ((j+1) < this.m_SOM[i].length) { - pos2 = this.m_SOM[i][j+1]; + if ((j + 1) < this.m_SOM[i].length) { + pos2 = this.m_SOM[i][j + 1]; tmpL = new DLine(pos1[0], pos1[1], pos2[0], pos2[1], Color.BLACK); area.addDElement(tmpL); } @@ -367,7 +390,7 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I // area.addDElement(tmpP); // } for (int i = 0; i < data.length; i++) { - tmpP = new DPoint((data[i][0] - this.m_Range[0][2])/(1+this.m_Range[0][3]), (data[i][1] - this.m_Range[1][2])/(1+this.m_Range[1][3])); + tmpP = new DPoint((data[i][0] - this.m_Range[0][2]) / (1 + this.m_Range[0][3]), (data[i][1] - this.m_Range[1][2]) / (1 + this.m_Range[1][3])); tmpP.setIcon(new Chart2DDPointIconCross()); tmpP.setColor(this.getColorFor(types[i])); area.addDElement(tmpP); @@ -378,24 +401,25 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I frame.show(); } - /** This method will return a view on the SOM and it classification result + /** + * This method will return a view on the SOM and it classification result */ public JComponent getViewOnSOM() { DArea result = new DArea(); result.setBackground(Color.WHITE); - result.setVisibleRectangle(0,0,this.m_SOM.length, this.m_SOM[0].length); - result.setPreferredSize(new Dimension(this.m_SOM.length*10, this.m_SOM[0].length*10)); - result.setMinimumSize(new Dimension(this.m_SOM.length*2, this.m_SOM[0].length*2)); - DRectangle tmpRect; - int best; - double total; - double currentP; - double lastP; + result.setVisibleRectangle(0, 0, this.m_SOM.length, this.m_SOM[0].length); + result.setPreferredSize(new Dimension(this.m_SOM.length * 10, this.m_SOM[0].length * 10)); + result.setMinimumSize(new Dimension(this.m_SOM.length * 2, this.m_SOM[0].length * 2)); + DRectangle tmpRect; + int best; + double total; + double currentP; + double lastP; for (int i = 0; i < this.m_SOM.length; i++) { for (int j = 0; j < this.m_SOM[i].length; j++) { - total = 0; - currentP = 0; - lastP = 0; + total = 0; + currentP = 0; + lastP = 0; // first determine how many instances have been assigned to for (int k = 0; k < this.m_SOMClass[i][j].length; k++) { total += this.m_SOMClass[i][j][k]; @@ -405,7 +429,7 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I // draw only dominat class tmpRect = new DRectangle(i, j, 1, 1); tmpRect.setColor(Color.BLACK); - best = 0; + best = 0; for (int k = 0; k < this.m_SOMClass[i][j].length; k++) { if (best < this.m_SOMClass[i][j][k]) { best = this.m_SOMClass[i][j][k]; @@ -416,9 +440,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } else { // try to draw the percentage for each element for (int k = 0; k < this.m_SOMClass[i][j].length; k++) { - currentP = this.m_SOMClass[i][j][k]/total; + currentP = this.m_SOMClass[i][j][k] / total; if (currentP > 0) { - tmpRect = new DRectangle(i, j+lastP, 1, currentP); + tmpRect = new DRectangle(i, j + lastP, 1, currentP); tmpRect.setColor(this.getColorFor(k)); tmpRect.setFillColor(this.getColorFor(k)); result.addDElement(tmpRect); @@ -437,17 +461,26 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I return result; } - private Color getColorFor(int i) { + private Color getColorFor(int i) { switch (i) { - case 0 : return Color.BLUE; - case 1 : return Color.RED; - case 2 : return Color.GREEN; - case 3 : return Color.CYAN; - case 4 : return Color.ORANGE; - case 5 : return Color.MAGENTA; - case 6 : return Color.YELLOW; - case 7 : return Color.PINK; - case 8 : return Color.GRAY; + case 0: + return Color.BLUE; + case 1: + return Color.RED; + case 2: + return Color.GREEN; + case 3: + return Color.CYAN; + case 4: + return Color.ORANGE; + case 5: + return Color.MAGENTA; + case 6: + return Color.YELLOW; + case 7: + return Color.PINK; + case 8: + return Color.GRAY; } return Color.LIGHT_GRAY; } @@ -457,15 +490,15 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I som.setSizeX(5); som.setSizeY(25); int num = 25; - double[][] data = new double[num*2][2]; - int[] type = new int[num*2]; + double[][] data = new double[num * 2][2]; + int[] type = new int[num * 2]; for (int i = 0; i < num; i++) { - data[i][0] = -0.8 + RNG.gaussianDouble(0.3); - data[i][1] = -0.5 + RNG.gaussianDouble(0.1); - type[i] = 0; - data[i+num][0] = 0.1 + RNG.gaussianDouble(0.1); - data[i+num][1] = 0.2 + RNG.gaussianDouble(0.1); - type[i+num] = 1; + data[i][0] = -0.8 + RNG.gaussianDouble(0.3); + data[i][1] = -0.5 + RNG.gaussianDouble(0.1); + type[i] = 0; + data[i + num][0] = 0.1 + RNG.gaussianDouble(0.1); + data[i + num][1] = 0.2 + RNG.gaussianDouble(0.1); + type[i + num] = 1; } som.init(data, type); som.train(data, type); @@ -474,23 +507,30 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Self-Organizing Maps"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The Self-Organizing Maps, have been proposed by Kohonen (read this book on SOMs for further details)."; } - /** This method allows you to set the number of neurons + /** + * This method allows you to set the number of neurons * in x dimension - * @param t The number of neurons in x dimension + * + * @param t The number of neurons in x dimension */ public void setSizeX(int t) { if (t < 1) { @@ -498,15 +538,20 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } this.m_Dim1 = t; } + public int getSizeX() { return this.m_Dim1; } + public String sizeXTipText() { return "Set the number of neurons in x dimension."; } - /** This method allows you to set the number of neurons + + /** + * This method allows you to set the number of neurons * in y dimension - * @param t The number of neurons in y dimension + * + * @param t The number of neurons in y dimension */ public void setSizeY(int t) { if (t < 1) { @@ -514,14 +559,19 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } this.m_Dim2 = t; } + public int getSizeY() { return this.m_Dim2; } + public String sizeYTipText() { return "Set the number of neurons in y dimension."; } - /** This method allows you to set the number of training cycles - * @param t The number of training cycles + + /** + * This method allows you to set the number of training cycles + * + * @param t The number of training cycles */ public void setTrainingCycles(int t) { if (t < 1) { @@ -529,14 +579,19 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } this.m_TrainingCycles = t; } + public int getTrainingCycles() { return this.m_TrainingCycles; } + public String trainingCyclesTipText() { return "Set the number of training cycles to perform."; } - /** This method allows you to set the size of the neighorhood - * @param t The size of the neighborhood + + /** + * This method allows you to set the size of the neighorhood + * + * @param t The size of the neighborhood */ public void setNeighborhoodSize(int t) { if (t < 0) { @@ -544,14 +599,19 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } this.m_NeighborhoodSize = t; } + public int getNeighborhoodSize() { return this.m_NeighborhoodSize; } + public String neighborhoodSizeTipText() { return "Set the size of the neighborhood."; } - /** This method allows you to set the initial alpha value - * @param t The initial alpha value + + /** + * This method allows you to set the initial alpha value + * + * @param t The initial alpha value */ public void setAlpha(double t) { if (t < 0) { @@ -562,21 +622,28 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I } this.m_Alpha = t; } + public double getAlpha() { return this.m_Alpha; } + public String AlphaTipText() { return "Choose the initial alpha (0-0.5)."; } - /** Activate attractive neignbors for the winner neuron - * @param t The dikel factor + + /** + * Activate attractive neignbors for the winner neuron + * + * @param t The dikel factor */ public void setDikelThis(boolean t) { this.m_DikelThis = t; } + public boolean getDikelThis() { return this.m_DikelThis; } + public String dikelThisTipText() { return "Activate attractive neignbors for the winner neuron."; } diff --git a/src/eva2/optimization/operator/classification/InterfaceClassification.java b/src/eva2/optimization/operator/classification/InterfaceClassification.java index 75426b13..339eabf7 100644 --- a/src/eva2/optimization/operator/classification/InterfaceClassification.java +++ b/src/eva2/optimization/operator/classification/InterfaceClassification.java @@ -1,6 +1,7 @@ package eva2.optimization.operator.classification; -/** An interface for classification methods, currently under construction. +/** + * An interface for classification methods, currently under construction. * Created by IntelliJ IDEA. * User: streiche * Date: 09.12.2004 @@ -8,28 +9,36 @@ package eva2.optimization.operator.classification; * To change this template use File | Settings | File Templates. */ public interface InterfaceClassification { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method will init the classificator - * @param space The double[n][d] space* - * @param type The classes [0,1,..] + /** + * This method will init the classificator + * + * @param space The double[n][d] space* + * @param type The classes [0,1,..] */ public void init(double[][] space, int[] type); - /** This method allows you to train the classificator based on + /** + * This method allows you to train the classificator based on * double[d] values and the class. n gives the number of instances * and d gives the dimension of the search space. - * @param space The double[n][d] space - * @param type The int[n] classes [0,1,..] + * + * @param space The double[n][d] space + * @param type The int[n] classes [0,1,..] */ public void train(double[][] space, int[] type); - /** This method will classify a given data point - * @param point The double[d] data point. + /** + * This method will classify a given data point + * + * @param point The double[d] data point. * @return type The resulting class. */ public int getClassFor(double[] point); diff --git a/src/eva2/optimization/operator/cluster/ClusterAll.java b/src/eva2/optimization/operator/cluster/ClusterAll.java index 972adc23..d8ac35cc 100644 --- a/src/eva2/optimization/operator/cluster/ClusterAll.java +++ b/src/eva2/optimization/operator/cluster/ClusterAll.java @@ -1,23 +1,23 @@ package eva2.optimization.operator.cluster; import eva2.optimization.population.Population; + import java.io.Serializable; import java.util.Arrays; /** * Dummy class which assigns all individuals to a single cluster only. - * - * @author mkron * + * @author mkron */ public class ClusterAll implements InterfaceClustering, Serializable { - - private boolean assignLoners = false; // should loners be assigned? - + + private boolean assignLoners = false; // should loners be assigned? + @Override - public Object clone() { - return new ClusterAll(); - } + public Object clone() { + return new ClusterAll(); + } /** * Try to associate a set of loners with a given set of species. Return a list @@ -29,64 +29,63 @@ public class ClusterAll implements InterfaceClustering, Serializable { * which is the reference population to consider the measures of. This is for cases * where, e.g., subsets of a Population are to be clustered using measures of the * original population. - * + * * @param loners * @param species * @param referenceSet a reference population for dynamic measures * @return associative list matching loners to species. */ @Override - public int[] associateLoners(Population loners, Population[] species, - Population referenceSet) { - if (loners!=null && (loners.size()>0)) { - int[] indices = new int[loners.size()]; - if (assignLoners) { - Arrays.fill(indices, 0); - } - else { - Arrays.fill(indices, -1); - } - return indices; - } else { - return null; - } - } + public int[] associateLoners(Population loners, Population[] species, + Population referenceSet) { + if (loners != null && (loners.size() > 0)) { + int[] indices = new int[loners.size()]; + if (assignLoners) { + Arrays.fill(indices, 0); + } else { + Arrays.fill(indices, -1); + } + return indices; + } else { + return null; + } + } - /* - * (non-Javadoc) - * @see eva2.optimization.operators.cluster.InterfaceClustering#cluster(eva2.optimization.populations.Population, eva2.optimization.populations.Population) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.operators.cluster.InterfaceClustering#cluster(eva2.optimization.populations.Population, eva2.optimization.populations.Population) + */ @Override - public Population[] cluster(Population pop, Population referenceSet) { - // first pop is empty (there are no loners), second pop is complete - return new Population[]{pop.cloneWithoutInds(), pop.cloneShallowInds()}; - } + public Population[] cluster(Population pop, Population referenceSet) { + // first pop is empty (there are no loners), second pop is complete + return new Population[]{pop.cloneWithoutInds(), pop.cloneShallowInds()}; + } - /* - * (non-Javadoc) - * @see eva2.optimization.operators.cluster.InterfaceClustering#initClustering(eva2.optimization.populations.Population) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.operators.cluster.InterfaceClustering#initClustering(eva2.optimization.populations.Population) + */ @Override - public String initClustering(Population pop) { - return null; - } + public String initClustering(Population pop) { + return null; + } - /* - * (non-Javadoc) - * @see eva2.optimization.operators.cluster.InterfaceClustering#mergingSpecies(eva2.optimization.populations.Population, eva2.optimization.populations.Population, eva2.optimization.populations.Population) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.operators.cluster.InterfaceClustering#mergingSpecies(eva2.optimization.populations.Population, eva2.optimization.populations.Population, eva2.optimization.populations.Population) + */ @Override - public boolean mergingSpecies(Population species1, Population species2, - Population referenceSet) { - return true; - } - - public static String globalInfo() { - return "A dummy clustering implementation which assigns all elements to a single cluster."; - } - - public String getName() { - return "Cluster-all"; - } + public boolean mergingSpecies(Population species1, Population species2, + Population referenceSet) { + return true; + } + + public static String globalInfo() { + return "A dummy clustering implementation which assigns all elements to a single cluster."; + } + + public String getName() { + return "Cluster-all"; + } } diff --git a/src/eva2/optimization/operator/cluster/ClusteringDensityBased.java b/src/eva2/optimization/operator/cluster/ClusteringDensityBased.java index e50e3f84..f2453628 100644 --- a/src/eva2/optimization/operator/cluster/ClusteringDensityBased.java +++ b/src/eva2/optimization/operator/cluster/ClusteringDensityBased.java @@ -5,10 +5,12 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric; import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.population.Population; import eva2.tools.Pair; + import java.util.ArrayList; -/** The DBSCAN method. As far as I recall this is an hierachical +/** + * The DBSCAN method. As far as I recall this is an hierachical * clustering method like the single-link method. * Created by IntelliJ IDEA. * User: streiche @@ -18,57 +20,59 @@ import java.util.ArrayList; */ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, InterfaceClusteringMetricBased, java.io.Serializable { - private InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); - private double m_ClusterDistance = 0.1; - private int m_MinimumGroupSize = 3; - private boolean[][] ConnectionMatrix; - private boolean[] Clustered; - private boolean m_TestConvergingSpeciesOnBestOnly = true; + private InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); + private double m_ClusterDistance = 0.1; + private int m_MinimumGroupSize = 3; + private boolean[][] ConnectionMatrix; + private boolean[] Clustered; + private boolean m_TestConvergingSpeciesOnBestOnly = true; public ClusteringDensityBased() { } - + /** * Directly set the minimum cluster distance sigma. + * * @param sigma the minimum cluster distance */ public ClusteringDensityBased(double sigma) { - m_ClusterDistance = sigma; + m_ClusterDistance = sigma; } - + /** * Directly set the minimum cluster distance sigma and minimum group size. + * * @param sigma the minimum cluster distance */ public ClusteringDensityBased(double sigma, int minGSize) { - m_ClusterDistance = sigma; - m_MinimumGroupSize = minGSize; + m_ClusterDistance = sigma; + m_MinimumGroupSize = minGSize; } - + /** * Directly set the minimum cluster distance sigma and minimum group size. + * * @param sigma the minimum cluster distance */ public ClusteringDensityBased(double sigma, int minGSize, InterfaceDistanceMetric metric) { - m_ClusterDistance = sigma; - m_MinimumGroupSize = minGSize; - m_Metric = metric; + m_ClusterDistance = sigma; + m_MinimumGroupSize = minGSize; + m_Metric = metric; } - + public ClusteringDensityBased(ClusteringDensityBased a) { if (a.m_Metric != null) { - this.m_Metric = (InterfaceDistanceMetric)a.m_Metric.clone(); + this.m_Metric = (InterfaceDistanceMetric) a.m_Metric.clone(); } - this.m_TestConvergingSpeciesOnBestOnly = a.m_TestConvergingSpeciesOnBestOnly; - this.m_ClusterDistance = a.m_ClusterDistance; - this.m_MinimumGroupSize = a.m_MinimumGroupSize; + this.m_TestConvergingSpeciesOnBestOnly = a.m_TestConvergingSpeciesOnBestOnly; + this.m_ClusterDistance = a.m_ClusterDistance; + this.m_MinimumGroupSize = a.m_MinimumGroupSize; if (a.Clustered != null) { this.Clustered = new boolean[a.Clustered.length]; for (int i = 0; i < this.Clustered.length; i++) { if (a.Clustered[i]) { this.Clustered[i] = true; - } - else { + } else { this.Clustered[i] = false; } } @@ -79,8 +83,7 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, for (int j = 0; j < this.ConnectionMatrix[i].length; j++) { if (a.ConnectionMatrix[i][j]) { this.ConnectionMatrix[i][j] = true; - } - else { + } else { this.ConnectionMatrix[i][j] = false; } } @@ -88,8 +91,10 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, } } - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override @@ -99,27 +104,27 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, @Override public Population[] cluster(Population pop, Population referencePop) { - ConnectionMatrix = new boolean[pop.size()][pop.size()]; - Clustered = new boolean[pop.size()]; - AbstractEAIndividual tmpIndy1, tmpIndy2; - Population PopulationOfUnclustered, Cluster, template; - ArrayList ClusteredPopulations = new ArrayList(); + ConnectionMatrix = new boolean[pop.size()][pop.size()]; + Clustered = new boolean[pop.size()]; + AbstractEAIndividual tmpIndy1, tmpIndy2; + Population PopulationOfUnclustered, Cluster, template; + ArrayList ClusteredPopulations = new ArrayList(); - template = (Population)pop.clone(); + template = (Population) pop.clone(); template.clear(); - PopulationOfUnclustered = (Population)template.clone(); + PopulationOfUnclustered = (Population) template.clone(); ClusteredPopulations.add(PopulationOfUnclustered); // Build the connection Matrix for (int i = 0; i < pop.size(); i++) { - tmpIndy1 = (AbstractEAIndividual)pop.get(i); + tmpIndy1 = (AbstractEAIndividual) pop.get(i); ConnectionMatrix[i][i] = true; - for (int j = i+1; j < pop.size(); j++) { - tmpIndy2 = (AbstractEAIndividual)pop.get(j); - if (tmpIndy1==null || (tmpIndy2==null)) { - System.err.println("Warning: Individual should not be null (ClusteringDensityBased)!"); + for (int j = i + 1; j < pop.size(); j++) { + tmpIndy2 = (AbstractEAIndividual) pop.get(j); + if (tmpIndy1 == null || (tmpIndy2 == null)) { + System.err.println("Warning: Individual should not be null (ClusteringDensityBased)!"); } - if ((tmpIndy1!=null) && (tmpIndy2!=null) && (this.m_Metric.distance(tmpIndy1, tmpIndy2) < this.m_ClusterDistance)) { + if ((tmpIndy1 != null) && (tmpIndy2 != null) && (this.m_Metric.distance(tmpIndy1, tmpIndy2) < this.m_ClusterDistance)) { ConnectionMatrix[i][j] = true; ConnectionMatrix[j][i] = true; } else { @@ -136,12 +141,11 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, // Now identify clusters within pop and add them to the result for (int i = 0; i < ConnectionMatrix.length; i++) { if (!Clustered[i]) { - Cluster = (Population)template.clone(); + Cluster = (Population) template.clone(); this.addRowToPopulation(i, Cluster, pop); if (Cluster.size() >= this.m_MinimumGroupSize) { ClusteredPopulations.add(Cluster); - } - else { + } else { PopulationOfUnclustered.addPopulation(Cluster); } } @@ -154,11 +158,13 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, return result; } - /** This method adds all Connected and !Clustered Individuals form row index + /** + * This method adds all Connected and !Clustered Individuals form row index * to pop - * @param index The index of the row that is to be computed. - * @param cluster The Cluster to which the individuals are to be added - * @param source The source which is to be clustered. + * + * @param index The index of the row that is to be computed. + * @param cluster The Cluster to which the individuals are to be added + * @param source The source which is to be clustered. */ private void addRowToPopulation(int index, Population cluster, Population source) { for (int i = 0; i < ConnectionMatrix[index].length; i++) { @@ -172,25 +178,26 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, } } - /** This method allows you to decide if two species converge. - * @param species1 The first species. - * @param species2 The second species. + /** + * This method allows you to decide if two species converge. + * + * @param species1 The first species. + * @param species2 The second species. * @return True if species converge, else False. */ @Override public boolean mergingSpecies(Population species1, Population species2, Population referencePop) { if (m_TestConvergingSpeciesOnBestOnly) { - double specDist = this.m_Metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()); + double specDist = this.m_Metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()); // System.out.println("Dist between species is " + specDist); return (specDist < this.m_ClusterDistance); } else { - Population tmpPop = new Population(species1.size()+species2.size()); + Population tmpPop = new Population(species1.size() + species2.size()); tmpPop.addPopulation(species1); tmpPop.addPopulation(species2); if (this.cluster(tmpPop, referencePop).length <= 2) { return true; - } - else { + } else { return false; } } @@ -212,100 +219,115 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, // else return false; // } // } - + /** * Try to associate a set of loners with a given set of species. Return a list * of indices assigning loner i with species j for all loners. If no species can * be associated, -1 is returned as individual entry. * Note that the last cluster threshold is used which may have depended on the last * generation. - * + * * @param loners * @param species * @return associative list matching loners to species. */ @Override public int[] associateLoners(Population loners, Population[] species, Population referencePop) { - int[] res = new int[loners.size()]; - for (int l=0; l iDist = Population.getClosestFarthestIndy(loners.getEAIndividual(l), species[spI], m_Metric, true); - if (iDist.tail() < m_ClusterDistance) { // its close enough to be added - // set SP ID only if its the closest species which is still below cluster distance - if (minDist<0 || (iDist.tail() < minDist)) { - res[l]=spI; - } - } - } // end for all species - } // end for all loners - return res; + int[] res = new int[loners.size()]; + for (int l = 0; l < loners.size(); l++) { + double minDist = -1; + res[l] = -1; + for (int spI = 0; spI < species.length; spI++) { // O(species.length^2) + Pair iDist = Population.getClosestFarthestIndy(loners.getEAIndividual(l), species[spI], m_Metric, true); + if (iDist.tail() < m_ClusterDistance) { // its close enough to be added + // set SP ID only if its the closest species which is still below cluster distance + if (minDist < 0 || (iDist.tail() < minDist)) { + res[l] = spI; + } + } + } // end for all species + } // end for all loners + return res; } - + /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "A density-based clustering algorithm (DBSCAN)."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "DBSCAN"; } - /** This method allows you to set/get the distance metric used by the DBSCAN method. + /** + * This method allows you to set/get the distance metric used by the DBSCAN method. + * * @return The currently used distance metric. */ @Override public InterfaceDistanceMetric getMetric() { return this.m_Metric; } + @Override - public void setMetric(InterfaceDistanceMetric m){ + public void setMetric(InterfaceDistanceMetric m) { this.m_Metric = m; } + public String metricTipText() { return "Choose the distance metric to use."; } - /** This method allows you to set/get the minimal group size of the DBSCAN method. + /** + * This method allows you to set/get the minimal group size of the DBSCAN method. + * * @return The currently used minimal group size. */ public int getMinimumGroupSize() { return this.m_MinimumGroupSize; } - public void setMinimumGroupSize(int m){ + + public void setMinimumGroupSize(int m) { if (m < 1) { m = 1; } this.m_MinimumGroupSize = m; } + public String minimumGroupSizeTipText() { return "Set the minimum group size for the DBSCAN method."; } @Override - public String initClustering(Population pop) { - return null; - } + public String initClustering(Population pop) { + return null; + } @Override - public double getClustDistParam() { - return this.m_ClusterDistance; - } + public double getClustDistParam() { + return this.m_ClusterDistance; + } + @Override - public void setClustDistParam(double m) { + public void setClustDistParam(double m) { if (m < 0) { - m = 0; - } + m = 0; + } this.m_ClusterDistance = m; - } + } + public String clustDistTipText() { return "Set the distance threshhold for the DBSCAN method."; } diff --git a/src/eva2/optimization/operator/cluster/ClusteringDynPeakIdent.java b/src/eva2/optimization/operator/cluster/ClusteringDynPeakIdent.java index 54b55db9..5641703f 100644 --- a/src/eva2/optimization/operator/cluster/ClusteringDynPeakIdent.java +++ b/src/eva2/optimization/operator/cluster/ClusteringDynPeakIdent.java @@ -9,227 +9,230 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric; import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.population.Population; import eva2.tools.Pair; + import java.util.ArrayList; /** * Clustering using the DPI mechanism (dynamic peak identification). * Collect a number of peaks, which are the fittest individuals * which are not dominated by other individuals within a certain distance. - * The remaining individuals are assigned to the closest peak up to a maximum + * The remaining individuals are assigned to the closest peak up to a maximum * niche count. If more individuals would be assigned to one peak, the best ones are * chosen and remaining ones are assumed unclustered. - * For the strict radius case, individuals are only assigned to a peak if they - * have a distance smaller than the niche radius to that peak. - * The number of expected peaks (clusters) must be predefined. + * For the strict radius case, individuals are only assigned to a peak if they + * have a distance smaller than the niche radius to that peak. + * The number of expected peaks (clusters) must be predefined. * Note that the returned number of clusters may be smaller than q. - * - * @author mkron * + * @author mkron */ public class ClusteringDynPeakIdent implements InterfaceClustering, java.io.Serializable { - private static final boolean TRACE=false; - private int numNiches; - private double nicheRadius; - private int maxNicheCount; // maximum number of individuals per peak - private boolean strictNicheRadius=true; // if false, all individuals are clustered to the closest niche, otherwise some remain unclustered (those which are further than the nicheRadius from any peak) + private static final boolean TRACE = false; + private int numNiches; + private double nicheRadius; + private int maxNicheCount; // maximum number of individuals per peak + private boolean strictNicheRadius = true; // if false, all individuals are clustered to the closest niche, otherwise some remain unclustered (those which are further than the nicheRadius from any peak) - InterfaceDistanceMetric metric = new PhenotypeMetric(); + InterfaceDistanceMetric metric = new PhenotypeMetric(); - /** - * Uses the alternative metric if it is non null. In case it is null, the last metric is used or, if - * none was set, the default PhenotypeMetric() is used. - * - * @param numNs - * @param numIndiesPerPeak - * @param nicheRad - * @param strictRad - * @param alternativeMetric - */ - public ClusteringDynPeakIdent(int numNs, int numIndiesPerPeak, double nicheRad, boolean strictRad, InterfaceDistanceMetric alternativeMetric) { - this.numNiches = numNs; - this.maxNicheCount = numIndiesPerPeak; - this.nicheRadius = nicheRad; - this.strictNicheRadius = strictRad; - if (metric==null && (alternativeMetric==null)) { - metric=new PhenotypeMetric(); - } - else if (alternativeMetric!=null) { - metric=alternativeMetric; - } - } + /** + * Uses the alternative metric if it is non null. In case it is null, the last metric is used or, if + * none was set, the default PhenotypeMetric() is used. + * + * @param numNs + * @param numIndiesPerPeak + * @param nicheRad + * @param strictRad + * @param alternativeMetric + */ + public ClusteringDynPeakIdent(int numNs, int numIndiesPerPeak, double nicheRad, boolean strictRad, InterfaceDistanceMetric alternativeMetric) { + this.numNiches = numNs; + this.maxNicheCount = numIndiesPerPeak; + this.nicheRadius = nicheRad; + this.strictNicheRadius = strictRad; + if (metric == null && (alternativeMetric == null)) { + metric = new PhenotypeMetric(); + } else if (alternativeMetric != null) { + metric = alternativeMetric; + } + } - public ClusteringDynPeakIdent(ClusteringDynPeakIdent o) { - this(o.numNiches, o.maxNicheCount, o.nicheRadius, o.strictNicheRadius, o.metric); - } + public ClusteringDynPeakIdent(ClusteringDynPeakIdent o) { + this(o.numNiches, o.maxNicheCount, o.nicheRadius, o.strictNicheRadius, o.metric); + } @Override - public Object clone() { - return new ClusteringDynPeakIdent(this); - } - + public Object clone() { + return new ClusteringDynPeakIdent(this); + } + @Override - public int[] associateLoners(Population loners, Population[] species, - Population referenceSet) { - Population bests = new Population(species.length); - for (int i=0; i closestInfo = Population.getClosestFarthestIndy(loners.getEAIndividual(i), bests, metric, true); - // we have now the info about the closest best individual. If its closer than the threshold, we can assign the loner to that index - if (!strictNicheRadius || (closestInfo.tail() closestInfo = Population.getClosestFarthestIndy(loners.getEAIndividual(i), bests, metric, true); + // we have now the info about the closest best individual. If its closer than the threshold, we can assign the loner to that index + if (!strictNicheRadius || (closestInfo.tail() < nicheRadius)) { + assoc[i] = closestInfo.head(); + } else { + assoc[i] = -1; + } + } + return assoc; + } @Override - public Population[] cluster(Population pop, Population referenceSet) { + public Population[] cluster(Population pop, Population referenceSet) { // boolean TRACE_METH=false; // if (TRACE_METH) System.out.println("A1 " + System.currentTimeMillis()); - AbstractEAIndividualComparator eaComparator = new AbstractEAIndividualComparator(-1); - Population sorted = pop.getSortedBestFirst(eaComparator); + AbstractEAIndividualComparator eaComparator = new AbstractEAIndividualComparator(-1); + Population sorted = pop.getSortedBestFirst(eaComparator); // if (TRACE_METH) System.out.println("A2 " + System.currentTimeMillis()); - Population peaks = performDynPeakIdent(metric, sorted, numNiches, nicheRadius); + Population peaks = performDynPeakIdent(metric, sorted, numNiches, nicheRadius); // System.out.println("peak measures: " + BeanInspector.toString(peaks.getPopulationMeasures())); // if (TRACE_METH) System.out.println("A3 " + System.currentTimeMillis()); - Population[] clusters = new Population[peaks.size()+1]; - for (int i=0; i0) { - clusters[i].add(peaks.getEAIndividual(i-1)); - } // add peaks to clusters! - } + Population[] clusters = new Population[peaks.size() + 1]; + for (int i = 0; i < clusters.length; i++) { + clusters[i] = referenceSet.cloneWithoutInds(); + if (i > 0) { + clusters[i].add(peaks.getEAIndividual(i - 1)); + } // add peaks to clusters! + } // if (TRACE_METH) System.out.println("A4 " + System.currentTimeMillis()); - Population rest = pop.filter(peaks); + Population rest = pop.filter(peaks); // if (TRACE_METH) System.out.println("A4a " + System.currentTimeMillis()); - if (pop.getRedundancyCount()>0) { - // happens e.g. on the bounds of the domain - System.err.println("warning, found redundant indies: " + pop.getRedundancyCount()); - rest.removeRedundantIndies(); - } - if ((rest.size()+peaks.size())+pop.getRedundancyCount()!=pop.size()) { - System.err.println("Warning, inconsistent filtering in ClusteringDynPeakIdent! Redundant: " + pop.getRedundancyCount() ); - } - int[] assoc = assignLeaders(rest, peaks); + if (pop.getRedundancyCount() > 0) { + // happens e.g. on the bounds of the domain + System.err.println("warning, found redundant indies: " + pop.getRedundancyCount()); + rest.removeRedundantIndies(); + } + if ((rest.size() + peaks.size()) + pop.getRedundancyCount() != pop.size()) { + System.err.println("Warning, inconsistent filtering in ClusteringDynPeakIdent! Redundant: " + pop.getRedundancyCount()); + } + int[] assoc = assignLeaders(rest, peaks); // if (TRACE_METH) System.out.println("A5 " + System.currentTimeMillis()); - for (int i=0; i=0) { // it can be assigned to a peak - clusters[assoc[i]+1].add(rest.getEAIndividual(i)); - } else { // its a loner - clusters[0].add(rest.getEAIndividual(i)); - } - } -// if (TRACE_METH) System.out.println("A6 " + System.currentTimeMillis()); - int cnt = clusters[0].size(); - for (int i=1; i0) { // check for too large species - for (int i=1; imaxNicheCount) { -// Population overhead = clusters[i].getSortedNIndividuals(clusters[i].size()-maxNicheCount, false); - ArrayList overhd = clusters[i].getSorted(new IndividualDistanceComparator(peaks.getEAIndividual(i-1), new EuclideanMetric(), true)); - Population overhead = new Population(); - overhead.addAll(overhead.toTail(clusters[i].size()-maxNicheCount, overhd)); // add only the front maxNicheCount individuals - clusters[i].removeMembers(overhead, true); - clusters[0].addPopulation(overhead); - } - } - } -// if (TRACE_METH) System.out.println("-- " + System.currentTimeMillis()); - return clusters; - } - - @Override - public String initClustering(Population pop) { - return null; - } - - @Override - public boolean mergingSpecies(Population species1, Population species2, - Population referenceSet) { - // in our case just return true if the leaders are close enough - return (metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual())= 0) { // it can be assigned to a peak + clusters[assoc[i] + 1].add(rest.getEAIndividual(i)); + } else { // its a loner + clusters[0].add(rest.getEAIndividual(i)); } - while (i 0) { // check for too large species + for (int i = 1; i < clusters.length; i++) { + if (clusters[i].size() > maxNicheCount) { +// Population overhead = clusters[i].getSortedNIndividuals(clusters[i].size()-maxNicheCount, false); + ArrayList overhd = clusters[i].getSorted(new IndividualDistanceComparator(peaks.getEAIndividual(i - 1), new EuclideanMetric(), true)); + Population overhead = new Population(); + overhead.addAll(overhead.toTail(clusters[i].size() - maxNicheCount, overhd)); // add only the front maxNicheCount individuals + clusters[i].removeMembers(overhead, true); + clusters[0].addPopulation(overhead); + } + } + } +// if (TRACE_METH) System.out.println("-- " + System.currentTimeMillis()); + return clusters; + } + + @Override + public String initClustering(Population pop) { + return null; + } + + @Override + public boolean mergingSpecies(Population species1, Population species2, + Population referenceSet) { + // in our case just return true if the leaders are close enough + return (metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < nicheRadius); + } + + + /** + * The DPI mechanism. Collect a number of peaks, which are the fittest individuals + * which are not dominated by other individuals within distance rho. + * Note that the returned set may be smaller than q. + * + * @param pop + * @param q the number of peaks to be identified + * @param rho the niche radius + * @return the dynamic peak set + */ + public static Population performDynPeakIdent(InterfaceDistanceMetric metric, Population sortedPop, int q, double rho) { + int i = 0; + Population peaks = new Population(q); + if (TRACE) { + System.out.print("Adding peaks: "); + } + while (i < sortedPop.size() && (peaks.size() < q)) { + if ((peaks.size() == 0) || (!peaks.isWithinPopDist((AbstractEAIndividual) sortedPop.get(i), rho, metric))) { + peaks.add(sortedPop.get(i)); + if (TRACE) { + System.out.print(" " + sortedPop.getEAIndividual(i).getFitness(0)); + } + } + i++; + } + if (TRACE) { + System.out.println("\nFound " + peaks.size() + " peaks, "); // for (int k=0; k 1) { - newC[i][j] /= (double)numbOfAssigned[i]; + newC[i][j] /= (double) numbOfAssigned[i]; } //else System.out.println("Someone was not assigned any data!? "+ i +" "+numbOfAssigned[i] + ": Data.size()="+data.length); } } if (this.m_Debug) { // let's see how they arrive here - Plot plot; - double[] tmpD = new double[2]; + Plot plot; + double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; plot = new Plot("Debugging K-Means Clustering", "Y1", "Y2", tmpD, tmpD); for (int i = 0; i < pop.size(); i++) { - double[] x = ((InterfaceDataTypeDouble)pop.get(i)).getDoubleData(); + double[] x = ((InterfaceDataTypeDouble) pop.get(i)).getDoubleData(); plot.setUnconnectedPoint(x[0], x[1], 1); } // now add the c - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; for (int i = 0; i < this.m_C.length; i++) { - mySet = new GraphPointSet(10+i, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + i, plot.getFunctionArea()); mySet.setConnectedMode(true); myPoint = new DPoint(this.m_C[i][0], this.m_C[i][1]); - tmp = new Chart2DDPointIconText("Old: "+i); + tmp = new Chart2DDPointIconText("Old: " + i); tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); myPoint = new DPoint(newC[i][0], newC[i][1]); - tmp = new Chart2DDPointIconText("New: "+i); + tmp = new Chart2DDPointIconText("New: " + i); tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); @@ -179,20 +183,20 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab } if (this.m_Debug) { // let's see how they arrive here - Plot plot; - double[] tmpD = new double[2]; + Plot plot; + double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; plot = new Plot("Debugging Cluster", "Y1", "Y2", tmpD, tmpD); - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; for (int i = 0; i < pop.size(); i++) { - mySet = new GraphPointSet(10+1, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + 1, plot.getFunctionArea()); mySet.setConnectedMode(false); - double[] x = pop.getEAIndividual(i).getDoublePosition(); + double[] x = pop.getEAIndividual(i).getDoublePosition(); myPoint = new DPoint(x[0], x[1]); - tmp = new Chart2DDPointIconText(""+assignment[i]); + tmp = new Chart2DDPointIconText("" + assignment[i]); if (assignment[i] % 2 == 0) { tmp.setIcon(new Chart2DDPointIconCircle()); } @@ -217,21 +221,21 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab // result[assignment[i]].add(pop.get(i)); if (this.m_Debug) { // let's see how they arrive here - Plot plot; - double[] tmpD = new double[2]; + Plot plot; + double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; plot = new Plot("Debugging Clustering Separation", "Y1", "Y2", tmpD, tmpD); - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; for (int i = 0; i < result.length; i++) { - mySet = new GraphPointSet(10+1, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + 1, plot.getFunctionArea()); mySet.setConnectedMode(false); for (int j = 0; j < result[i].size(); j++) { - double[] x = ((InterfaceDataTypeDouble)result[i].get(j)).getDoubleData(); + double[] x = ((InterfaceDataTypeDouble) result[i].get(j)).getDoubleData(); myPoint = new DPoint(x[0], x[1]); - tmp = new Chart2DDPointIconText(""+i); + tmp = new Chart2DDPointIconText("" + i); if (i % 2 == 0) { tmp.setIcon(new Chart2DDPointIconCircle()); } @@ -240,53 +244,54 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab } } } - + // now expand to the expected format (unclustered indies at pop of index 0) int largeEnough = 0; // count clusters that are large enough - for (int i=0; i=getMinClustSize()) { + for (int i = 0; i < result.length; i++) { + if (result[i].size() >= getMinClustSize()) { largeEnough++; } } - Population[] resExpanded = new Population[largeEnough+1]; - resExpanded[0]=pop.cloneWithoutInds(); + Population[] resExpanded = new Population[largeEnough + 1]; + resExpanded[0] = pop.cloneWithoutInds(); int lastIndex = 1; - for (int i=0; i=getMinClustSize()) { - resExpanded[lastIndex]=result[i]; - lastIndex++; - } else { + for (int i = 0; i < result.length; i++) { + if (result[i].size() >= getMinClustSize()) { + resExpanded[lastIndex] = result[i]; + lastIndex++; + } else { resExpanded[0].addPopulation(result[i]); } } - tmpIndy=null; + tmpIndy = null; return resExpanded; } - /** + /** * This method allows you to cluster a population using m_C. The minimal cluster * size is _not_ regarded here. - * @param pop The population - * @param c The centroids + * + * @param pop The population + * @param c The centroids * @return The clusters as populations */ public Population[] cluster(Population pop, double[][] c) { - if (tmpIndy==null) { - tmpIndy=(AbstractEAIndividual)pop.getEAIndividual(0).clone(); + if (tmpIndy == null) { + tmpIndy = (AbstractEAIndividual) pop.getEAIndividual(0).clone(); } // nec. only because the method is public... - Population[] result = new Population[c.length]; + Population[] result = new Population[c.length]; // double[][] data = this.extractClusterDataFrom(pop); - int clusterAssigned; + int clusterAssigned; try { - for (int i = 0; i < result.length; i++) { - result[i] = pop.getClass().newInstance(); - result[i].setSameParams(pop); - } - } catch(Exception e) { - System.err.println("problems instantiating " + pop.getClass().getName() + " for clustering!"); - e.printStackTrace(); + for (int i = 0; i < result.length; i++) { + result[i] = pop.getClass().newInstance(); + result[i].setSameParams(pop); + } + } catch (Exception e) { + System.err.println("problems instantiating " + pop.getClass().getName() + " for clustering!"); + e.printStackTrace(); } // let's assign the elements of the population to a c for (int i = 0; i < pop.size(); i++) { @@ -302,25 +307,28 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab return result; } - /** This method calculates the distance between two double values + /** + * This method calculates the distance between two double values + * * @param d1 * @param d2 * @return The scalar distances between d1 and d2 */ private double distance(AbstractEAIndividual indy, double[] p) { if (m_UseSearchSpace) { - ((InterfaceDataTypeDouble)tmpIndy).SetDoubleGenotype(p); - } - else { + ((InterfaceDataTypeDouble) tmpIndy).SetDoubleGenotype(p); + } else { tmpIndy.setFitness(p); } - + return metric.distance(indy, tmpIndy); } - - /** This method extracts the double data to cluster from the + + /** + * This method extracts the double data to cluster from the * population - * @param pop The population + * + * @param pop The population * @return The double[][] data to cluster */ private double[][] extractClusterDataFrom(Population pop) { @@ -331,28 +339,29 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab // @todo: i case of repair i would need to set the phenotype! if (this.m_UseSearchSpace && (pop.get(0) instanceof InterfaceDataTypeDouble)) { for (int i = 0; i < pop.size(); i++) { - data[i] = ((InterfaceDataTypeDouble)pop.get(i)).getDoubleData(); + data[i] = ((InterfaceDataTypeDouble) pop.get(i)).getDoubleData(); } } else { for (int i = 0; i < pop.size(); i++) { - data[i] = ((AbstractEAIndividual)pop.get(i)).getFitness(); + data[i] = ((AbstractEAIndividual) pop.get(i)).getFitness(); } } return data; } - /** This method allows you to decied if two species converge. - * @param species1 The first species. - * @param species2 The second species. + /** + * This method allows you to decied if two species converge. + * + * @param species1 The first species. + * @param species2 The second species. * @return True if species converge, else False. */ @Override public boolean mergingSpecies(Population species1, Population species2, Population referencePop) { // TODO i could use the BIC metric from X-means to calculate this - if (metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) * A tree is produced by assigning each individual the closest individual with better fitness. * Connections with a distance above a certain threshold are cut. After that, each interconnected subtree forms a cluster. - * In the paper, the threshold is deduced as 2*d_p for d_p: the mean distance in the population. - * - * @author mkron + * In the paper, the threshold is deduced as 2*d_p for d_p: the mean distance in the population. * + * @author mkron */ public class ClusteringNearestBetter implements InterfaceClustering, Serializable { - private static final long serialVersionUID = 1L; - private InterfaceDistanceMetric metric = new PhenotypeMetric(); - private double absoluteDistThreshold = 0.5; - private boolean thresholdMultipleOfMeanDist = true; - private double meanDistFactor = 2.; // recommended setting - private double currentMeanDistance = -1.; - private int minimumGroupSize = 3; - private boolean testConvergingSpeciesOnBestOnly = true; // if two species are tested for convergence, only the best indies may be compared regarding the distance threshold - protected ParameterControlManager paramControl = new ParameterControlManager(); - - private int[] uplink; - private double[] uplinkDist; - private AbstractEAIndividualComparator comparator = new AbstractEAIndividualComparator(); - private Vector[] children; - private static final String initializedForKey = "initializedClustNearestBetterOnHash"; - private static final String initializedRefData = "initializedClustNearestBetterData"; - - private static boolean TRACE = false; + private static final long serialVersionUID = 1L; + private InterfaceDistanceMetric metric = new PhenotypeMetric(); + private double absoluteDistThreshold = 0.5; + private boolean thresholdMultipleOfMeanDist = true; + private double meanDistFactor = 2.; // recommended setting + private double currentMeanDistance = -1.; + private int minimumGroupSize = 3; + private boolean testConvergingSpeciesOnBestOnly = true; // if two species are tested for convergence, only the best indies may be compared regarding the distance threshold + protected ParameterControlManager paramControl = new ParameterControlManager(); - public ClusteringNearestBetter() { - } + private int[] uplink; + private double[] uplinkDist; + private AbstractEAIndividualComparator comparator = new AbstractEAIndividualComparator(); + private Vector[] children; + private static final String initializedForKey = "initializedClustNearestBetterOnHash"; + private static final String initializedRefData = "initializedClustNearestBetterData"; + + private static boolean TRACE = false; + + public ClusteringNearestBetter() { + } public ClusteringNearestBetter(ClusteringNearestBetter o) { - this.metric = o.metric; - this.absoluteDistThreshold = o.absoluteDistThreshold; - this.thresholdMultipleOfMeanDist = o.thresholdMultipleOfMeanDist; - this.meanDistFactor = o.meanDistFactor; - this.currentMeanDistance = o.currentMeanDistance; - this.minimumGroupSize = o.minimumGroupSize; - this.comparator = (AbstractEAIndividualComparator)o.comparator.clone(); - this.testConvergingSpeciesOnBestOnly = o.testConvergingSpeciesOnBestOnly; - } - + this.metric = o.metric; + this.absoluteDistThreshold = o.absoluteDistThreshold; + this.thresholdMultipleOfMeanDist = o.thresholdMultipleOfMeanDist; + this.meanDistFactor = o.meanDistFactor; + this.currentMeanDistance = o.currentMeanDistance; + this.minimumGroupSize = o.minimumGroupSize; + this.comparator = (AbstractEAIndividualComparator) o.comparator.clone(); + this.testConvergingSpeciesOnBestOnly = o.testConvergingSpeciesOnBestOnly; + } + /** * Set the mean distance factor in the adaptive case or the absolute distance * threshold in the non-adaptive case. - * + * * @param adaptive * @param thresholdOrFactor - * */ public ClusteringNearestBetter(boolean adaptive, double thresholdOrFactor) { - setAdaptiveThreshold(adaptive); - if (adaptive) { + setAdaptiveThreshold(adaptive); + if (adaptive) { setMeanDistFactor(thresholdOrFactor); - } - else { + } else { setDistThreshold(thresholdOrFactor); } - } - - public void hideHideable() { - setAdaptiveThreshold(isAdaptiveThreshold()); } - - public ParameterControlManager getParamControl() { - return paramControl; - } - - public ParamAdaption[] getParameterControl() { - return paramControl.getSingleAdapters(); - } - - public void setParameterControl(ParamAdaption[] paramControl) { - this.paramControl.setSingleAdapters(paramControl); - } - /** This method allows you to make a deep clone of + public void hideHideable() { + setAdaptiveThreshold(isAdaptiveThreshold()); + } + + public ParameterControlManager getParamControl() { + return paramControl; + } + + public ParamAdaption[] getParameterControl() { + return paramControl.getSingleAdapters(); + } + + public void setParameterControl(ParamAdaption[] paramControl) { + this.paramControl.setSingleAdapters(paramControl); + } + + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override public Object clone() { return (Object) new ClusteringNearestBetter(this); } - + /** * Try to associate a set of loners with a given set of species. Return a list * of indices assigning loner i with species j for all loners. If no species can * be associated, -1 is returned as individual entry. * Note that the last cluster threshold is used which may have depended on the last * generation. - * + * * @param loners * @param species * @return associative list matching loners to species. @@ -116,35 +116,35 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl @Override public int[] associateLoners(Population loners, Population[] species, Population referenceSet) { // Pair[][] closestPerSpecList = new Pair[loners.size()][species.length]; - int[] res = new int[loners.size()]; - getRefData(referenceSet, loners); - for (int l=0; l sorted = pop.getSorted(comparator); - if (uplink==null || (uplink.length!=pop.size())) { + if (this.isAdaptiveThreshold()) { + ArrayList sorted = pop.getSorted(comparator); + if (uplink == null || (uplink.length != pop.size())) { uplink = new int[pop.size()]; } // parent index of all indys - if (uplinkDist==null || (uplinkDist.length!=pop.size())) { + if (uplinkDist == null || (uplinkDist.length != pop.size())) { uplinkDist = new double[pop.size()]; } // parent distance for all indys - if (children==null || (children.length!=pop.size())) { + if (children == null || (children.length != pop.size())) { children = new Vector[pop.size()]; } // list of children for all indies - else if (children.length==pop.size()) { - for (int i=0; i sorted = pop.getSorted(comparator); + if (uplink == null || (uplink.length != pop.size())) { + uplink = new int[pop.size()]; + } // parent index of all indys + if (uplinkDist == null || (uplinkDist.length != pop.size())) { + uplinkDist = new double[pop.size()]; + } // parent distance for all indys + if (children == null || (children.length != pop.size())) { + children = new Vector[pop.size()]; + } // list of children for all indies + else if (children.length == pop.size()) { + for (int i = 0; i < pop.size(); i++) { + children[i] = null; } - ArrayList sorted = pop.getSorted(comparator); - if (uplink==null || (uplink.length!=pop.size())) { - uplink = new int[pop.size()]; - } // parent index of all indys - if (uplinkDist==null || (uplinkDist.length!=pop.size())) { - uplinkDist = new double[pop.size()]; - } // parent distance for all indys - if (children==null || (children.length!=pop.size())) { - children = new Vector[pop.size()]; - } // list of children for all indies - else if (children.length==pop.size()) { - for (int i=0; i allClusters = new LinkedList(); - while (current finalClusts = new ArrayList(allClusters.size()); - finalClusts.add(pop.cloneWithoutInds()); - for (Population clust : allClusters) { - if (clust.size() allClusters = new LinkedList(); + while (current < sorted.size()) { + Population currentClust = pop.cloneWithoutInds(); + currentClust.add(sorted.get(current)); + clustered[current] = true; + addChildren(current, clustered, sorted, currentClust); + // currentClust now recursively contains all children - the cluster is complete + // now jump to the next best unclustered indy + allClusters.add(currentClust); + while (current < sorted.size() && (clustered[current])) current++; + } + + ArrayList finalClusts = new ArrayList(allClusters.size()); + finalClusts.add(pop.cloneWithoutInds()); + for (Population clust : allClusters) { + if (clust.size() < minimumGroupSize) { // add to loner population + finalClusts.get(0).addPopulation(clust); + } else { // add to cluster list + finalClusts.add(clust); } - Double refDat = (Double)referenceSet.getData(initializedRefData); - if (refDat!=null) { - if (TRACE) { // check hash - Integer hash=(Integer)referenceSet.getData(initializedForKey); - if ((hash==null) || (hash!=referenceSet.hashCode())) { - System.err.println("Warning, missing initialization before clustering for ClusteringNearestBetter!"); - return false; - } - } - currentMeanDistance = refDat.doubleValue(); - return true; - } else { - System.err.println("Warning, missing reference data - forgot reference set initialization? " + this.getClass()); - return false; - } - } + } + Population[] finalArr = new Population[finalClusts.size()]; + return finalClusts.toArray(finalArr); + } - private double createClusterTreeFromSortedPop(ArrayList sorted) { - double edgeLengthSum=0; int edgeCnt = 0; - for (int i=sorted.size()-1; i>=1; i--) { // start with worst indies - // search for closest indy which is better - uplink[i]=-1; - uplinkDist[i] = -1; - for (int j=i-1; j>=0; j--) { // look at all which are better - // if the j-th indy is closer, reset the index - double curDist = metric.distance(sorted.get(i), sorted.get(j)); - if (uplinkDist[i]<0 || (curDist < uplinkDist[i])) { - uplink[i] = j; - uplinkDist[i] = curDist; - } - } - // the closest best for indy i is now known. connect them in the graph. - if (children[uplink[i]]==null) { - children[uplink[i]]=new Vector(); - } - children[uplink[i]].add(i); - edgeLengthSum+=uplinkDist[i]; - edgeCnt++; - } + /** + * Get the reference data from a population instance that should have been initialized. + * If the reference set is null, the backup is treated as reference set. + * + * @param referenceSet + * @param backup + */ + private boolean getRefData(Population referenceSet, Population backup) { + if (referenceSet == null) { + referenceSet = backup; + } + Double refDat = (Double) referenceSet.getData(initializedRefData); + if (refDat != null) { + if (TRACE) { // check hash + Integer hash = (Integer) referenceSet.getData(initializedForKey); + if ((hash == null) || (hash != referenceSet.hashCode())) { + System.err.println("Warning, missing initialization before clustering for ClusteringNearestBetter!"); + return false; + } + } + currentMeanDistance = refDat.doubleValue(); + return true; + } else { + System.err.println("Warning, missing reference data - forgot reference set initialization? " + this.getClass()); + return false; + } + } + + private double createClusterTreeFromSortedPop(ArrayList sorted) { + double edgeLengthSum = 0; + int edgeCnt = 0; + for (int i = sorted.size() - 1; i >= 1; i--) { // start with worst indies + // search for closest indy which is better + uplink[i] = -1; + uplinkDist[i] = -1; + for (int j = i - 1; j >= 0; j--) { // look at all which are better + // if the j-th indy is closer, reset the index + double curDist = metric.distance(sorted.get(i), sorted.get(j)); + if (uplinkDist[i] < 0 || (curDist < uplinkDist[i])) { + uplink[i] = j; + uplinkDist[i] = curDist; + } + } + // the closest best for indy i is now known. connect them in the graph. + if (children[uplink[i]] == null) { + children[uplink[i]] = new Vector(); + } + children[uplink[i]].add(i); + edgeLengthSum += uplinkDist[i]; + edgeCnt++; + } // currentMeanDistance = pop.getPopulationMeasures(metric)[0]; - return edgeLengthSum/((double)edgeCnt); // the average edge length - } + return edgeLengthSum / ((double) edgeCnt); // the average edge length + } - /** - * Add the next layer of children to the clustered population. - * - * @param current - * @param clustered - * @param sorted - * @param currentClust - */ - private void addChildren(int current, boolean[] clustered, ArrayList sorted, Population currentClust) { - if (children[current]!=null && (children[current].size()>0)) { - for (int i=0; i sorted, Population currentClust) { + if (children[current] != null && (children[current].size() > 0)) { + for (int i = 0; i < children[current].size(); i++) { + if ((!clustered[children[current].get(i)]) && (uplinkDist[children[current].get(i)] < currentDistThreshold())) { + // the first child is not clustered yet and below distance threshold. + // so add it to the cluster, mark it, and proceed recursively. + currentClust.add(sorted.get(children[current].get(i))); + clustered[children[current].get(i)] = true; + if (TRACE) { + System.out.println("Assigned " + current); + } + addChildren(children[current].get(i), clustered, sorted, currentClust); + } else { + if (TRACE) { + System.out.println("Not assigned " + current); + } + } } - else { - return absoluteDistThreshold; - } - } + } else { + // nothing more to do + } + } - /** This method allows you to decide if two species converge. - * @param species1 The first species. - * @param species2 The second species. + private double currentDistThreshold() { + if (thresholdMultipleOfMeanDist) { + return meanDistFactor * currentMeanDistance; + } else { + return absoluteDistThreshold; + } + } + + /** + * This method allows you to decide if two species converge. + * + * @param species1 The first species. + * @param species2 The second species. * @return True if species converge, else False. */ @Override public boolean mergingSpecies(Population species1, Population species2, Population referenceSet) { - getRefData(referenceSet, species1); + getRefData(referenceSet, species1); if (testConvergingSpeciesOnBestOnly) { if (this.metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < this.currentDistThreshold()) { return true; - } - else { + } else { return false; } } else { - Population tmpPop = new Population(species1.size()+species2.size()); + Population tmpPop = new Population(species1.size() + species2.size()); tmpPop.addPopulation(species1); tmpPop.addPopulation(species2); if (this.cluster(tmpPop, referenceSet).length <= 2) { return true; - } - else { + } else { return false; } } } - - public static String globalInfo() { - return "A tree is produced by assigning each individual the closest individual with better fitness. Connections with a distance above a certain threshold are cut. After that, each interconnected subtree forms a cluster."; + + public static String globalInfo() { + return "A tree is produced by assigning each individual the closest individual with better fitness. Connections with a distance above a certain threshold are cut. After that, each interconnected subtree forms a cluster."; } public String metricTipText() { - return "The metric to use during clustering."; + return "The metric to use during clustering."; } + public InterfaceDistanceMetric getMetric() { - return metric; - } - public void setMetric(InterfaceDistanceMetric metric) { - this.metric = metric; - } + return metric; + } - public String distThresholdTipText() { - return "In the non-adaptive case the absolute threshold below which clusters are connected."; - } - public double getDistThreshold() { - return absoluteDistThreshold; - } - public void setDistThreshold(double distThreshold) { - this.absoluteDistThreshold = distThreshold; - } + public void setMetric(InterfaceDistanceMetric metric) { + this.metric = metric; + } - public String minimumGroupSizeTipText() { - return "Minimum group size that makes an own cluster."; - } - public int getMinimumGroupSize() { - return minimumGroupSize; - } - public void setMinimumGroupSize(int minimumGroupSize) { - this.minimumGroupSize = minimumGroupSize; - } + public String distThresholdTipText() { + return "In the non-adaptive case the absolute threshold below which clusters are connected."; + } - public String comparatorTipText() { - return "Define the comparator by which the population is sorted before clustering."; - } - public AbstractEAIndividualComparator getComparator() { - return comparator; - } + public double getDistThreshold() { + return absoluteDistThreshold; + } + + public void setDistThreshold(double distThreshold) { + this.absoluteDistThreshold = distThreshold; + } + + public String minimumGroupSizeTipText() { + return "Minimum group size that makes an own cluster."; + } + + public int getMinimumGroupSize() { + return minimumGroupSize; + } + + public void setMinimumGroupSize(int minimumGroupSize) { + this.minimumGroupSize = minimumGroupSize; + } + + public String comparatorTipText() { + return "Define the comparator by which the population is sorted before clustering."; + } + + public AbstractEAIndividualComparator getComparator() { + return comparator; + } // public void setComparator(AbstractEAIndividualComparator comparator) { // this.comparator = comparator; // } - - public String adaptiveThresholdTipText() { - return "Activate adaptive threshold which is calculated from mean distance in the population and a constant factor."; - } + + public String adaptiveThresholdTipText() { + return "Activate adaptive threshold which is calculated from mean distance in the population and a constant factor."; + } + public boolean isAdaptiveThreshold() { - return thresholdMultipleOfMeanDist; - } - public void setAdaptiveThreshold(boolean thresholdMultipleOfMeanDist) { - this.thresholdMultipleOfMeanDist = thresholdMultipleOfMeanDist; - GenericObjectEditor.setHideProperty(this.getClass(), "meanDistFactor", !thresholdMultipleOfMeanDist); - GenericObjectEditor.setHideProperty(this.getClass(), "distThreshold", thresholdMultipleOfMeanDist); - } + return thresholdMultipleOfMeanDist; + } - public String meanDistFactorTipText() { - return "Factor producing the distance threshold from population mean distance."; - } - public double getMeanDistFactor() { - return meanDistFactor; - } - public void setMeanDistFactor(double meanDistFactor) { - this.meanDistFactor = meanDistFactor; - } + public void setAdaptiveThreshold(boolean thresholdMultipleOfMeanDist) { + this.thresholdMultipleOfMeanDist = thresholdMultipleOfMeanDist; + GenericObjectEditor.setHideProperty(this.getClass(), "meanDistFactor", !thresholdMultipleOfMeanDist); + GenericObjectEditor.setHideProperty(this.getClass(), "distThreshold", thresholdMultipleOfMeanDist); + } + + public String meanDistFactorTipText() { + return "Factor producing the distance threshold from population mean distance."; + } + + public double getMeanDistFactor() { + return meanDistFactor; + } + + public void setMeanDistFactor(double meanDistFactor) { + this.meanDistFactor = meanDistFactor; + } + + public String testConvergingSpeciesOnBestOnlyTipText() { + return "Only the best individuals may be compared when testing whether to merge two species."; + } - public String testConvergingSpeciesOnBestOnlyTipText() { - return "Only the best individuals may be compared when testing whether to merge two species."; - } public boolean isTestConvergingSpeciesOnBestOnly() { - return testConvergingSpeciesOnBestOnly; - } - public void SetTestConvergingSpeciesOnBestOnly( - boolean testConvergingSpeciesOnBestOnly) { - this.testConvergingSpeciesOnBestOnly = testConvergingSpeciesOnBestOnly; - } + return testConvergingSpeciesOnBestOnly; + } + + public void SetTestConvergingSpeciesOnBestOnly( + boolean testConvergingSpeciesOnBestOnly) { + this.testConvergingSpeciesOnBestOnly = testConvergingSpeciesOnBestOnly; + } } diff --git a/src/eva2/optimization/operator/cluster/ClusteringXMeans.java b/src/eva2/optimization/operator/cluster/ClusteringXMeans.java index 725a75b0..4e2e49f1 100644 --- a/src/eva2/optimization/operator/cluster/ClusteringXMeans.java +++ b/src/eva2/optimization/operator/cluster/ClusteringXMeans.java @@ -11,9 +11,11 @@ import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; import eva2.tools.math.RNG; + import java.util.Arrays; -/** The x-means clustering method should be able to determine a +/** + * The x-means clustering method should be able to determine a * suiteable value for k automatically, simply by evaluating all * alternatives. * Created by IntelliJ IDEA. @@ -24,23 +26,25 @@ import java.util.Arrays; */ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializable { - public int m_MaxK = 5; - public double[][] m_C; - public boolean m_UseSearchSpace = false; - public boolean m_Debug = false; + public int m_MaxK = 5; + public double[][] m_C; + public boolean m_UseSearchSpace = false; + public boolean m_Debug = false; public ClusteringXMeans() { } public ClusteringXMeans(ClusteringXMeans a) { - this.m_Debug = a.m_Debug; - this.m_MaxK = a.m_MaxK; - this.m_UseSearchSpace = a.m_UseSearchSpace; + this.m_Debug = a.m_Debug; + this.m_MaxK = a.m_MaxK; + this.m_UseSearchSpace = a.m_UseSearchSpace; } - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override @@ -48,55 +52,57 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab return (Object) new ClusteringXMeans(this); } - /** This method allows you to search for clusters in a given population. The method + /** + * This method allows you to search for clusters in a given population. The method * returns Number of populations. The first population contains all individuals that * could not be asociated with any cluster and may be empty. * All other populations group individuals into clusters. - * @param pop The population of individuals that is to be clustered. + * + * @param pop The population of individuals that is to be clustered. * @return Population[] */ @Override public Population[] cluster(Population pop, Population referencePop) { - ClusteringKMeans kmeans = new ClusteringKMeans(); - Population[][] tmpResults = new Population[this.m_MaxK][]; - double[][][] tmpC = new double[this.m_MaxK][][]; - double[][] data = this.extractClusterDataFrom(pop); + ClusteringKMeans kmeans = new ClusteringKMeans(); + Population[][] tmpResults = new Population[this.m_MaxK][]; + double[][][] tmpC = new double[this.m_MaxK][][]; + double[][] data = this.extractClusterDataFrom(pop); // the first result is the unclustered population - tmpResults[0] = new Population[1]; - tmpResults[0][0] = pop; - tmpC[0] = new double[1][]; - tmpC[0][0] = this.calculateMean(data); + tmpResults[0] = new Population[1]; + tmpResults[0][0] = pop; + tmpC[0] = new double[1][]; + tmpC[0][0] = this.calculateMean(data); // the other solutions are kmeans results for (int i = 1; i < this.m_MaxK; i++) { kmeans.setUseSearchSpace(this.m_UseSearchSpace); - kmeans.setK(i+1); - tmpResults[i] = kmeans.cluster(pop, (Population)null); - tmpC[i] = kmeans.getC(); + kmeans.setK(i + 1); + tmpResults[i] = kmeans.cluster(pop, (Population) null); + tmpC[i] = kmeans.getC(); } - double bestBIC = Double.NEGATIVE_INFINITY, tmpBIC; - int index = 0; + double bestBIC = Double.NEGATIVE_INFINITY, tmpBIC; + int index = 0; for (int i = 0; i < tmpResults.length; i++) { tmpBIC = this.calculateBIC(tmpResults[i], tmpC[i]); if (this.m_Debug) { - Plot plot; - double[] tmpD = new double[2], x; + Plot plot; + double[] tmpD = new double[2], x; tmpD[0] = 0; tmpD[1] = 0; - plot = new Plot("K="+(i+1)+" reaches BIC = "+tmpBIC, "Y1", "Y2", tmpD, tmpD); - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + plot = new Plot("K=" + (i + 1) + " reaches BIC = " + tmpBIC, "Y1", "Y2", tmpD, tmpD); + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; for (int k = 0; k < tmpResults[i].length; k++) { - mySet = new GraphPointSet(10+k, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + k, plot.getFunctionArea()); mySet.setConnectedMode(false); // for each population for (int l = 0; l < tmpResults[i][k].size(); l++) { - x = ((InterfaceDataTypeDouble)tmpResults[i][k].get(l)).getDoubleData(); + x = ((InterfaceDataTypeDouble) tmpResults[i][k].get(l)).getDoubleData(); myPoint = new DPoint(x[0], x[1]); - tmp = new Chart2DDPointIconText(""+k); + tmp = new Chart2DDPointIconText("" + k); if (k % 2 == 0) { tmp.setIcon(new Chart2DDPointIconCircle()); } @@ -108,7 +114,7 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab mySet.setConnectedMode(false); for (int k = 0; k < tmpC[i].length; k++) { myPoint = new DPoint(tmpC[i][k][0], tmpC[i][k][1]); - tmp = new Chart2DDPointIconText("C/"+k); + tmp = new Chart2DDPointIconText("C/" + k); if (k % 2 == 0) { tmp.setIcon(new Chart2DDPointIconCircle()); } @@ -121,42 +127,42 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab index = i; } } - System.out.println("XMeans results in "+ (index+1) +" clusters."); + System.out.println("XMeans results in " + (index + 1) + " clusters."); Population[] result = tmpResults[index]; this.m_C = tmpC[index]; return result; } - /** This method should calculate the BIC - * + /** + * This method should calculate the BIC */ private double calculateBIC(Population[] pop, double[][] C) { - double result = 0; - double[][] data; - double[] mean; - double RM, R = 0, M = 0, K, sigma; + double result = 0; + double[][] data; + double[] mean; + double RM, R = 0, M = 0, K, sigma; for (int i = 0; i < pop.length; i++) { R += pop[i].size(); } K = pop.length; - for (int i = 0; i < pop.length; i++) { - data = this.extractClusterDataFrom(pop[i]); - RM = data.length; + for (int i = 0; i < pop.length; i++) { + data = this.extractClusterDataFrom(pop[i]); + RM = data.length; if (data.length > 0) { - M = data[0].length; - mean = this.calculateMean(data); - sigma = this.calculateSigma(data, mean); - result += - (RM/2.0)*Math.log(2*Math.PI); - result += - 0.5*RM*M*Math.log(sigma); - result += - 0.5*(RM-K); - result += RM*Math.log(RM); - result += RM*Math.log(R); + M = data[0].length; + mean = this.calculateMean(data); + sigma = this.calculateSigma(data, mean); + result += -(RM / 2.0) * Math.log(2 * Math.PI); + result += -0.5 * RM * M * Math.log(sigma); + result += -0.5 * (RM - K); + result += RM * Math.log(RM); + result += RM * Math.log(R); } } - result += - ((K-1)+(M*K)+1)*Math.log(R); + result += -((K - 1) + (M * K) + 1) * Math.log(R); return result; } @@ -169,7 +175,7 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab } } for (int j = 0; j < result.length; j++) { - result[j] /= ((double)data.length); + result[j] /= ((double) data.length); } return result; } @@ -183,12 +189,14 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab for (int i = 0; i < data.length; i++) { result += Math.pow(this.distance(data[i], mean), 2); } - result /= ((double)data.length); + result /= ((double) data.length); return result; } - /** This method calculates the distance between two double values + /** + * This method calculates the distance between two double values + * * @param d1 * @param d2 * @return The scalar distances between d1 and d2 @@ -204,9 +212,11 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab } - /** This method extracts the double data to cluster from the + /** + * This method extracts the double data to cluster from the * population - * @param pop The population + * + * @param pop The population * @return The double[][] data to cluster */ private double[][] extractClusterDataFrom(Population pop) { @@ -217,19 +227,21 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab // @todo: i case of repair i would need to set the phenotype! if (this.m_UseSearchSpace && (pop.get(0) instanceof InterfaceDataTypeDouble)) { for (int i = 0; i < pop.size(); i++) { - data[i] = ((InterfaceDataTypeDouble)pop.get(i)).getDoubleData(); + data[i] = ((InterfaceDataTypeDouble) pop.get(i)).getDoubleData(); } } else { for (int i = 0; i < pop.size(); i++) { - data[i] = ((AbstractEAIndividual)pop.get(i)).getFitness(); + data[i] = ((AbstractEAIndividual) pop.get(i)).getFitness(); } } return data; } - /** This method allows you to decied if two species converge. - * @param species1 The first species. - * @param species2 The second species. + /** + * This method allows you to decied if two species converge. + * + * @param species1 The first species. + * @param species2 The second species. * @return True if species converge, else False. */ @Override @@ -249,29 +261,33 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab // } @Override - public int[] associateLoners(Population loners, Population[] species, Population referencePop) { - int[] res=new int[loners.size()]; - System.err.println("Warning, associateLoners not implemented for " + this.getClass()); - Arrays.fill(res, -1); - return res; - } - - /** This method allows you to recieve the c centroids + public int[] associateLoners(Population loners, Population[] species, Population referencePop) { + int[] res = new int[loners.size()]; + System.err.println("Warning, associateLoners not implemented for " + this.getClass()); + Arrays.fill(res, -1); + return res; + } + + /** + * This method allows you to recieve the c centroids + * * @return The centroids */ public double[][] getC() { return this.m_C; } - /** This mehtod allows you to cluster a population using m_C - * @param pop The population - * @param c The centroids + /** + * This mehtod allows you to cluster a population using m_C + * + * @param pop The population + * @param c The centroids * @return The clusters as populations */ public Population[] cluster(Population pop, double[][] c) { - Population[] result = new Population[c.length]; - double[][] data = this.extractClusterDataFrom(pop); - int clusterAssigned; + Population[] result = new Population[c.length]; + double[][] data = this.extractClusterDataFrom(pop); + int clusterAssigned; for (int i = 0; i < result.length; i++) { result[i] = new Population(); @@ -289,7 +305,7 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab } return result; - } + } public static void main(String[] args) { ClusteringXMeans ckm = new ClusteringXMeans(); @@ -301,33 +317,33 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab f1.setProblemDimension(2); f1.setEAIndividual(new ESIndividualDoubleData()); if (true) { - int k = 3; - double[] x; + int k = 3; + double[] x; f1.initializePopulation(pop); for (int i = 0; i < pop.size(); i++) { - x = ((InterfaceDataTypeDouble)pop.get(i)).getDoubleData(); - switch (i%k) { - case 0 : { + x = ((InterfaceDataTypeDouble) pop.get(i)).getDoubleData(); + switch (i % k) { + case 0: { x[0] = 0 + RNG.gaussianDouble(1.2); x[1] = -1 + RNG.gaussianDouble(1.5); break; } - case 1 : { + case 1: { x[0] = 3 + RNG.gaussianDouble(1.8); x[1] = 8 + RNG.gaussianDouble(0.9); break; } - case 2 : { + case 2: { x[0] = -4 + RNG.gaussianDouble(1.2); x[1] = -8 + RNG.gaussianDouble(1.2); break; } - case 3 : { + case 3: { x[0] = 7 + RNG.gaussianDouble(1.1); x[1] = -5 + RNG.gaussianDouble(1.0); break; } - default : { + default: { x[0] = -2 + RNG.gaussianDouble(1.2); x[1] = 5 + RNG.gaussianDouble(1.2); } @@ -340,64 +356,77 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab x[0] = 10; x[1] = 10; } - ((InterfaceDataTypeDouble)pop.get(i)).SetDoubleGenotype(x); + ((InterfaceDataTypeDouble) pop.get(i)).SetDoubleGenotype(x); } } else { f1.initializePopulation(pop); } - ckm.cluster(pop, (Population)null); + ckm.cluster(pop, (Population) null); } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Oldy but goldy: K-Means clustering."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "K-Means"; } - /** This method allows you to set/get the number of + /** + * This method allows you to set/get the number of * clusters tofind + * * @return The current number of clusters to find. */ public int getMaxK() { return this.m_MaxK; } - public void setMaxK(int m){ + + public void setMaxK(int m) { if (m < 1) { m = 1; } this.m_MaxK = m; } + public String maxKTipText() { return "Choose the max number of clusters to find."; } - /** This method allows you to choose between using geno- + /** + * This method allows you to choose between using geno- * or phenotypic distance. + * * @return The distance type to use. */ public boolean getUseSearchSpace() { return this.m_UseSearchSpace; } - public void setUseSearchSpace(boolean m){ + + public void setUseSearchSpace(boolean m) { this.m_UseSearchSpace = m; } + public String useSearchSpaceTipText() { return "Toggle between search/objective space distance."; } @Override - public String initClustering(Population pop) { - return null; - } + public String initClustering(Population pop) { + return null; + } } diff --git a/src/eva2/optimization/operator/cluster/InterfaceClustering.java b/src/eva2/optimization/operator/cluster/InterfaceClustering.java index 9cbf86e3..4912094a 100644 --- a/src/eva2/optimization/operator/cluster/InterfaceClustering.java +++ b/src/eva2/optimization/operator/cluster/InterfaceClustering.java @@ -2,7 +2,7 @@ package eva2.optimization.operator.cluster; import eva2.optimization.population.Population; -/** +/** * This the interface to clustering algorithms, but since there * is no true concept on how to calculate a possibly problem * specific distance between two individuals, this is still to @@ -15,13 +15,15 @@ import eva2.optimization.population.Population; */ public interface InterfaceClustering { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** + /** * This method allows you to search for clusters in a given population. The method * returns Number of populations. The first population contains all individuals that * could not be associated with any cluster and may be empty. @@ -35,8 +37,8 @@ public interface InterfaceClustering { * Note that the clustered individuals should only be shallow instances of the members * of the given population pop. The sum of sizes of all returned individuals must be * equal to pop.size(). - * - * @param pop The population of individuals that is to be clustered. + * + * @param pop The population of individuals that is to be clustered. * @param referenceSet a reference population for dynamic measures * @return Population[] */ @@ -47,10 +49,10 @@ public interface InterfaceClustering { * If the clustering depends on population measures, a reference set may be given * which is the reference population to consider the measures of. This is for cases * where, e.g., subsets of a Population are to be clustered using measures of the - * original population. - * - * @param species1 The first species. - * @param species2 The second species. + * original population. + * + * @param species1 The first species. + * @param species2 The second species. * @param referenceSet a reference population for dynamic measures * @return True if species converge, else False. */ @@ -59,7 +61,7 @@ public interface InterfaceClustering { /** * Do some pre-calculations on a population for clustering. If additional population data * is set, return the associated key, otherwise null. - * + * * @param pop */ public String initClustering(Population pop); @@ -67,16 +69,16 @@ public interface InterfaceClustering { /** * This method decides if an unclustered individual belongs to an already established species. * For some clustering methods this can only be decided in reference to the complete population. - * + * * @param indy A unclustered individual. * @param species A species. - * @param pop The complete population as a reference. + * @param pop The complete population as a reference. * @return True or False. */ //Removed since for some clustering methods its not feasible to associate loners sequentially. Instead, a whole set of // lone individuals can now be associated to a given set of clusters //public boolean belongsToSpecies(AbstractEAIndividual indy, Population species); - + /** * Try to associate a set of loners with a given set of species. Return a list * of indices assigning loner i with species j for all loners. If no species can @@ -87,7 +89,7 @@ public interface InterfaceClustering { * which is the reference population to consider the measures of. This is for cases * where, e.g., subsets of a Population are to be clustered using measures of the * original population. - * + * * @param loners * @param species * @param referenceSet a reference population for dynamic measures diff --git a/src/eva2/optimization/operator/cluster/InterfaceClusteringDistanceParam.java b/src/eva2/optimization/operator/cluster/InterfaceClusteringDistanceParam.java index 82925e3f..dd38816b 100644 --- a/src/eva2/optimization/operator/cluster/InterfaceClusteringDistanceParam.java +++ b/src/eva2/optimization/operator/cluster/InterfaceClusteringDistanceParam.java @@ -2,11 +2,11 @@ package eva2.optimization.operator.cluster; /** * A clustering method which has a cluster parameter - the niche radius for example. - * - * @author mkron * + * @author mkron */ public interface InterfaceClusteringDistanceParam extends InterfaceClustering { - public double getClustDistParam(); - public void setClustDistParam(double param); + public double getClustDistParam(); + + public void setClustDistParam(double param); } diff --git a/src/eva2/optimization/operator/cluster/InterfaceClusteringMetricBased.java b/src/eva2/optimization/operator/cluster/InterfaceClusteringMetricBased.java index b1f8105a..dc5cfc55 100644 --- a/src/eva2/optimization/operator/cluster/InterfaceClusteringMetricBased.java +++ b/src/eva2/optimization/operator/cluster/InterfaceClusteringMetricBased.java @@ -4,11 +4,11 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric; /** * A clustering method which is associated with a metric. - * - * @author mkron * + * @author mkron */ public interface InterfaceClusteringMetricBased { public InterfaceDistanceMetric getMetric(); + public void setMetric(InterfaceDistanceMetric m); } diff --git a/src/eva2/optimization/operator/constraint/AbstractConstraint.java b/src/eva2/optimization/operator/constraint/AbstractConstraint.java index bc8af1d6..14d1bf42 100644 --- a/src/eva2/optimization/operator/constraint/AbstractConstraint.java +++ b/src/eva2/optimization/operator/constraint/AbstractConstraint.java @@ -9,251 +9,249 @@ import eva2.gui.editor.GenericObjectEditor; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.problems.AbstractProblemDouble; import eva2.tools.EVAERROR; + import java.io.Serializable; /** * An abstract constraint contains a penalty factor with control strategy (for dynamic penalties) * and a relation. - * - * @author mkron * + * @author mkron */ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, Serializable { -// private transient GPFunctionProblem func = null; - protected ConstraintRelationEnum relation = ConstraintRelationEnum.lessEqZero; - protected ConstraintHandlingEnum handling = ConstraintHandlingEnum.specificTag; - protected static boolean TRACE = false; - protected double equalityEpsilon = 0.0001; // threshold below which equality constraints are seen as satisfied - private AbstractEAIndividual currentIndy = null; - - private double penaltyFactor = 1.; -// protected ParamAdaption penaltyFactAdaption = new NoParamAdaption(); - protected ParameterControlManager paramCtrl = new ParameterControlManager(new NoParamAdaption()); - private static String penaltyPropName = "penaltyFactor"; - - public AbstractConstraint() { - relation = ConstraintRelationEnum.lessEqZero; - penaltyFactor = 1.; - paramCtrl = new ParameterControlManager(new NoParamAdaption()); + // private transient GPFunctionProblem func = null; + protected ConstraintRelationEnum relation = ConstraintRelationEnum.lessEqZero; + protected ConstraintHandlingEnum handling = ConstraintHandlingEnum.specificTag; + protected static boolean TRACE = false; + protected double equalityEpsilon = 0.0001; // threshold below which equality constraints are seen as satisfied + private AbstractEAIndividual currentIndy = null; + + private double penaltyFactor = 1.; + // protected ParamAdaption penaltyFactAdaption = new NoParamAdaption(); + protected ParameterControlManager paramCtrl = new ParameterControlManager(new NoParamAdaption()); + private static String penaltyPropName = "penaltyFactor"; + + public AbstractConstraint() { + relation = ConstraintRelationEnum.lessEqZero; + penaltyFactor = 1.; + paramCtrl = new ParameterControlManager(new NoParamAdaption()); // penaltyFactAdaption = new NoParamAdaption(); - } - - public AbstractConstraint(AbstractConstraint o) { + } + + public AbstractConstraint(AbstractConstraint o) { // penaltyFactAdaption = (ParamAdaption)o.penaltyFactAdaption.clone(); - paramCtrl = new ParameterControlManager(o.paramCtrl); - penaltyFactor = o.penaltyFactor; - relation = o.relation; - } - - public void hideHideable() { - setRelation(getRelation()); - } - + paramCtrl = new ParameterControlManager(o.paramCtrl); + penaltyFactor = o.penaltyFactor; + relation = o.relation; + } + + public void hideHideable() { + setRelation(getRelation()); + } + @Override - public abstract Object clone(); - - public InterfaceParameterControl getParamControl() { - return paramCtrl; - } + public abstract Object clone(); - /** - * Return the raw degree of violation - usually the function value of the constraint function. - */ - protected abstract double getRawViolationValue(double[] indyX); - - /** - * Return the absolute (positive) degree of violation or zero if the constraint is fulfilled. - */ + public InterfaceParameterControl getParamControl() { + return paramCtrl; + } + + /** + * Return the raw degree of violation - usually the function value of the constraint function. + */ + protected abstract double getRawViolationValue(double[] indyX); + + /** + * Return the absolute (positive) degree of violation or zero if the constraint is fulfilled. + */ @Override - public double getViolation(double[] indyX) { - double viol = getRawViolationValue(indyX); - return getViolationConsideringRelation(viol); - } + public double getViolation(double[] indyX) { + double viol = getRawViolationValue(indyX); + return getViolationConsideringRelation(viol); + } - /** - * Check whether the given individual violates the constraint and immediately add - * the penalty and violation if it is the case. Expect that the fitness has already been set. - * This regards the handling strategy and adds the violation to the fitness (in each dimension) or - * sets the individual constraint violation. - * - * @param indy the individual to check for constraint violation. - */ - public void addViolation(AbstractEAIndividual indy, double[] indyX) { - currentIndy=indy; - double v = getViolation(indyX); - switch (handling) { - case penaltyAdditive: - if (v>0) { - indy.SetMarkPenalized(true); - for (int i=0; i0) { - indy.SetMarkPenalized(true); - for (int i=0; i0) { - indy.addConstraintViolation(v); - } - break; - } - currentIndy=null; - } - - /** - * Some constraints require further information on the individual or work on the - * raw fitness which can be requested using this method. - * - * @return - */ - protected double[] getIndyRawFit(String key) { - return getIndyDblData(AbstractProblemDouble.rawFitKey); - } - - /** - * Some constraints require further information on the individual, such as - * additional individual data. This method uses getData of AbstractEAIndividual - * to try to retrieve a double array. - * - * @return - */ - protected double[] getIndyDblData(String key) { - if (currentIndy!=null) { - Object dat = currentIndy.getData(key); - if (dat!=null && (dat instanceof double[])) { - return (double[])dat; + /** + * Check whether the given individual violates the constraint and immediately add + * the penalty and violation if it is the case. Expect that the fitness has already been set. + * This regards the handling strategy and adds the violation to the fitness (in each dimension) or + * sets the individual constraint violation. + * + * @param indy the individual to check for constraint violation. + */ + public void addViolation(AbstractEAIndividual indy, double[] indyX) { + currentIndy = indy; + double v = getViolation(indyX); + switch (handling) { + case penaltyAdditive: + if (v > 0) { + indy.SetMarkPenalized(true); + for (int i = 0; i < indy.getFitness().length; i++) { + indy.SetFitness(i, indy.getFitness(i) + v + penaltyFactor); } - else { - System.err.println("Error, invalid call to AbstractConstraint.getRawFitness(). Individual had no raw fitness set."); - return null; - } - } else { - System.err.println("Error, invalid call to AbstractConstraint.getRawFitness(). Individual was unknown."); - return null; - } - } - - /** - * Some constraints require further information on the individual, such as - * additional individual data. This method uses getData of AbstractEAIndividual - * to try to retrieve a stored object. - * - * @return - */ - protected Object getIndyData(String key) { - if (currentIndy!=null) { - return currentIndy.getData(key); - } else { - System.err.println("Error, invalid call to AbstractConstraint.getRawFitness(). Individual was unknown."); - return null; - } - } - - private double getViolationConsideringRelation(double val) { -// System.out.println("Penalty is " + penaltyFactor); - val *= penaltyFactor; - switch (relation) { -// case linearLessEqZero: - case lessEqZero: - return (val <= 0.) ? 0 : val; - case eqZero: - val = Math.abs(val); - if (val<=equalityEpsilon) { - return 0.; - } - else { - return val; - } - case greaterEqZero: - return (val >= 0.) ? 0. : -val; - } - System.err.println("Unknown relation!"); - return 0.; - } + } + break; + case penaltyMultiplicative: + if (v > 0) { + indy.SetMarkPenalized(true); + for (int i = 0; i < indy.getFitness().length; i++) { + indy.SetFitness(i, indy.getFitness(i) * (v + penaltyFactor)); + } + } + case specificTag: + if (v > 0) { + indy.addConstraintViolation(v); + } + break; + } + currentIndy = null; + } - public boolean isViolated(double[] pos) { - return (getViolation(pos)>0); - } + /** + * Some constraints require further information on the individual or work on the + * raw fitness which can be requested using this method. + * + * @return + */ + protected double[] getIndyRawFit(String key) { + return getIndyDblData(AbstractProblemDouble.rawFitKey); + } + + /** + * Some constraints require further information on the individual, such as + * additional individual data. This method uses getData of AbstractEAIndividual + * to try to retrieve a double array. + * + * @return + */ + protected double[] getIndyDblData(String key) { + if (currentIndy != null) { + Object dat = currentIndy.getData(key); + if (dat != null && (dat instanceof double[])) { + return (double[]) dat; + } else { + System.err.println("Error, invalid call to AbstractConstraint.getRawFitness(). Individual had no raw fitness set."); + return null; + } + } else { + System.err.println("Error, invalid call to AbstractConstraint.getRawFitness(). Individual was unknown."); + return null; + } + } + + /** + * Some constraints require further information on the individual, such as + * additional individual data. This method uses getData of AbstractEAIndividual + * to try to retrieve a stored object. + * + * @return + */ + protected Object getIndyData(String key) { + if (currentIndy != null) { + return currentIndy.getData(key); + } else { + System.err.println("Error, invalid call to AbstractConstraint.getRawFitness(). Individual was unknown."); + return null; + } + } + + private double getViolationConsideringRelation(double val) { +// System.out.println("Penalty is " + penaltyFactor); + val *= penaltyFactor; + switch (relation) { +// case linearLessEqZero: + case lessEqZero: + return (val <= 0.) ? 0 : val; + case eqZero: + val = Math.abs(val); + if (val <= equalityEpsilon) { + return 0.; + } else { + return val; + } + case greaterEqZero: + return (val >= 0.) ? 0. : -val; + } + System.err.println("Unknown relation!"); + return 0.; + } + + public boolean isViolated(double[] pos) { + return (getViolation(pos) > 0); + } @Override - public boolean isSatisfied(double[] pos) { - return (getViolation(pos)==0.); - } - - public ConstraintRelationEnum getRelation() { - return relation; - } + public boolean isSatisfied(double[] pos) { + return (getViolation(pos) == 0.); + } - public void setRelation(ConstraintRelationEnum relation) { - this.relation = relation; - GenericObjectEditor.setShowProperty(this.getClass(), "equalityEpsilon", relation==ConstraintRelationEnum.eqZero); - } + public ConstraintRelationEnum getRelation() { + return relation; + } - public ParamAdaption getPenaltyFactControl() { - return paramCtrl.getSingleAdapters()[0]; - } + public void setRelation(ConstraintRelationEnum relation) { + this.relation = relation; + GenericObjectEditor.setShowProperty(this.getClass(), "equalityEpsilon", relation == ConstraintRelationEnum.eqZero); + } - public void setPenaltyFactControl(ParamAdaption penaltyAdaption) { + public ParamAdaption getPenaltyFactControl() { + return paramCtrl.getSingleAdapters()[0]; + } + + public void setPenaltyFactControl(ParamAdaption penaltyAdaption) { // this.penaltyFactAdaption = penaltyFact; - if (!(penaltyAdaption instanceof NoParamAdaption)) { - if (penaltyAdaption instanceof GenericParamAdaption) { - ((GenericParamAdaption)penaltyAdaption).setControlledParam(penaltyPropName); - } else { - if (!penaltyPropName.equals(penaltyAdaption.getControlledParam())) { - System.err.println("Warning: penalty factor control may have different target"); - } - } - } - paramCtrl.setSingleAdapters(new ParamAdaption[]{penaltyAdaption}); - } - - public String penaltyFactControlTipText() { - return "Adaptive penalty may used. For generic adaption mechanisms, the target string will be set automatically."; - } - - public double getPenaltyFactor() { - return penaltyFactor; - } - - public void setPenaltyFactor(double penaltyFactor) { - if (penaltyFactor<0) { - EVAERROR.errorMsgOnce("Error: a negative penalty factor is not allowed!"); - } else { - this.penaltyFactor = penaltyFactor; + if (!(penaltyAdaption instanceof NoParamAdaption)) { + if (penaltyAdaption instanceof GenericParamAdaption) { + ((GenericParamAdaption) penaltyAdaption).setControlledParam(penaltyPropName); + } else { + if (!penaltyPropName.equals(penaltyAdaption.getControlledParam())) { + System.err.println("Warning: penalty factor control may have different target"); + } } - } - - public String penaltyFactorTipText() { - return "Penalty factor by which a constraint violation is multiplied."; - } + } + paramCtrl.setSingleAdapters(new ParamAdaption[]{penaltyAdaption}); + } - public ConstraintHandlingEnum getHandlingMethod() { - return handling; - } + public String penaltyFactControlTipText() { + return "Adaptive penalty may used. For generic adaption mechanisms, the target string will be set automatically."; + } - public void setHandlingMethod(ConstraintHandlingEnum handling) { - this.handling = handling; - } - - public String handlingMethodTipText() { - return "Select the method the constraint is handled."; - } + public double getPenaltyFactor() { + return penaltyFactor; + } - public double getEqualityEpsilon() { - return equalityEpsilon; - } + public void setPenaltyFactor(double penaltyFactor) { + if (penaltyFactor < 0) { + EVAERROR.errorMsgOnce("Error: a negative penalty factor is not allowed!"); + } else { + this.penaltyFactor = penaltyFactor; + } + } - public void setEqualityEpsilon(double equalityEpsilon) { - this.equalityEpsilon = equalityEpsilon; - } - - public String equalityEpsilonTipText() { - return "The threshold below which equality constraints are said to be satisfied."; - } + public String penaltyFactorTipText() { + return "Penalty factor by which a constraint violation is multiplied."; + } + + public ConstraintHandlingEnum getHandlingMethod() { + return handling; + } + + public void setHandlingMethod(ConstraintHandlingEnum handling) { + this.handling = handling; + } + + public String handlingMethodTipText() { + return "Select the method the constraint is handled."; + } + + public double getEqualityEpsilon() { + return equalityEpsilon; + } + + public void setEqualityEpsilon(double equalityEpsilon) { + this.equalityEpsilon = equalityEpsilon; + } + + public String equalityEpsilonTipText() { + return "The threshold below which equality constraints are said to be satisfied."; + } } diff --git a/src/eva2/optimization/operator/constraint/ConstBelongsToDifferentClass.java b/src/eva2/optimization/operator/constraint/ConstBelongsToDifferentClass.java index 5b2f4998..f8494d23 100644 --- a/src/eva2/optimization/operator/constraint/ConstBelongsToDifferentClass.java +++ b/src/eva2/optimization/operator/constraint/ConstBelongsToDifferentClass.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.constraint; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeDouble; -/** This area constraint for parallelization is based on +/** + * This area constraint for parallelization is based on * the class type an individual belongs to. * Created by IntelliJ IDEA. * User: streiche @@ -13,20 +14,21 @@ import eva2.optimization.individuals.InterfaceDataTypeDouble; */ public class ConstBelongsToDifferentClass implements InterfaceConstraint, java.io.Serializable { - private double[] m_Class; - private double[][] m_OtherClasses; - private boolean m_UsePhenotype = false; + private double[] m_Class; + private double[][] m_OtherClasses; + private boolean m_UsePhenotype = false; public ConstBelongsToDifferentClass() { } + public ConstBelongsToDifferentClass(double[] m, double[][] b, boolean p) { - this.m_Class = m; - this.m_OtherClasses = b; - this.m_UsePhenotype = p; + this.m_Class = m; + this.m_OtherClasses = b; + this.m_UsePhenotype = p; } public ConstBelongsToDifferentClass(ConstBelongsToDifferentClass a) { - this.m_UsePhenotype = a.m_UsePhenotype; + this.m_UsePhenotype = a.m_UsePhenotype; if (a.m_Class != null) { this.m_Class = new double[a.m_Class.length]; System.arraycopy(a.m_Class, 0, this.m_Class, 0, a.m_Class.length); @@ -45,18 +47,20 @@ public class ConstBelongsToDifferentClass implements InterfaceConstraint, java.i return (Object) new ConstBelongsToDifferentClass(this); } - /** This method allows you wether or not a given individual + /** + * This method allows you wether or not a given individual * violates the constraints. - * @param indy The individual to check. + * + * @param indy The individual to check. * @return true if valid false else. */ @Override public boolean isValid(AbstractEAIndividual indy) { double[] data; if (this.m_UsePhenotype && (indy instanceof InterfaceDataTypeDouble)) { - data = ((InterfaceDataTypeDouble)indy).getDoubleData(); + data = ((InterfaceDataTypeDouble) indy).getDoubleData(); } else { - data = ((AbstractEAIndividual)indy).getFitness(); + data = ((AbstractEAIndividual) indy).getFitness(); } double distanceToMyClass = this.distance(data, this.m_Class); for (int i = 0; i < this.m_OtherClasses.length; i++) { @@ -67,7 +71,9 @@ public class ConstBelongsToDifferentClass implements InterfaceConstraint, java.i return true; } - /** This method calculates the distance between two double values + /** + * This method calculates the distance between two double values + * * @param d1 * @param d2 * @return The scalar distances between d1 and d2 diff --git a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanLinear.java b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanLinear.java index 3164edaa..fd0cd9dc 100644 --- a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanLinear.java +++ b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanLinear.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.constraint; import eva2.optimization.individuals.AbstractEAIndividual; -/** This area constraint for parallelization is based on +/** + * This area constraint for parallelization is based on * a line constraint * Created by IntelliJ IDEA. * User: streiche @@ -12,18 +13,19 @@ import eva2.optimization.individuals.AbstractEAIndividual; */ public class ConstObjectivesInEqualityBiggerThanLinear implements InterfaceConstraint, java.io.Serializable { - private double m = 1.0, b = 0.0; + private double m = 1.0, b = 0.0; public ConstObjectivesInEqualityBiggerThanLinear() { } + public ConstObjectivesInEqualityBiggerThanLinear(double m, double b) { - this.m = m; - this.b = b; + this.m = m; + this.b = b; } public ConstObjectivesInEqualityBiggerThanLinear(ConstObjectivesInEqualityBiggerThanLinear a) { - this.b = a.b; - this.m = a.m; + this.b = a.b; + this.m = a.m; } @Override @@ -31,9 +33,11 @@ public class ConstObjectivesInEqualityBiggerThanLinear implements InterfaceConst return (Object) new ConstObjectivesInEqualityBiggerThanLinear(this); } - /** This method allows you wether or not a given individual + /** + * This method allows you wether or not a given individual * violates the constraints. - * @param indy The individual to check. + * + * @param indy The individual to check. * @return true if valid false else. */ @Override @@ -42,10 +46,9 @@ public class ConstObjectivesInEqualityBiggerThanLinear implements InterfaceConst if (d.length != 2) { return true; } - if ((this.m*d[0] + this.b) < d[1]) { + if ((this.m * d[0] + this.b) < d[1]) { return true; - } - else { + } else { return false; } } diff --git a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanSurface.java b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanSurface.java index ef87a50e..2ef0e9da 100644 --- a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanSurface.java +++ b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityBiggerThanSurface.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.constraint; import eva2.optimization.individuals.AbstractEAIndividual; -/** This area constraint for parallelization is based on +/** + * This area constraint for parallelization is based on * a surface constraint * Created by IntelliJ IDEA. * User: streiche @@ -12,18 +13,19 @@ import eva2.optimization.individuals.AbstractEAIndividual; */ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceConstraint, java.io.Serializable { - private double[] base, norm; + private double[] base, norm; public ConstObjectivesInEqualityBiggerThanSurface() { } + public ConstObjectivesInEqualityBiggerThanSurface(double[] base, double[] norm) { - this.base = base; - this.norm = norm; + this.base = base; + this.norm = norm; } public ConstObjectivesInEqualityBiggerThanSurface(ConstObjectivesInEqualityBiggerThanSurface a) { - this.base = a.base; - this.norm = a.norm; + this.base = a.base; + this.norm = a.norm; } @Override @@ -31,9 +33,11 @@ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceCons return (Object) new ConstObjectivesInEqualityBiggerThanSurface(this); } - /** This method allows you wether or not a given individual + /** + * This method allows you wether or not a given individual * violates the constraints. - * @param indy The individual to check. + * + * @param indy The individual to check. * @return true if valid false else. */ @Override @@ -41,8 +45,7 @@ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceCons double[] d = indy.getFitness(); if (this.getScalarProduct(norm, this.getSubstraction(d, base)) >= 0) { return true; - } - else { + } else { return false; } } @@ -55,17 +58,21 @@ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceCons return result; } - /** This method returns the scalar product of two vectors + /** + * This method returns the scalar product of two vectors + * * @param a The first vector * @param b The second vector * @return The scalar product of a and b */ private double getScalarProduct(double[] a, double[] b) { - return (a[0]*b[0] + a[1]*b[1] + a[2]*b[2]); + return (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]); } - /** This method will return a normalized vector - * @param a The vector to normalize + /** + * This method will return a normalized vector + * + * @param a The vector to normalize * @return A normalized version of the input vector */ private double[] getNormalized(double[] a) { @@ -76,7 +83,7 @@ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceCons } sum = Math.sqrt(sum); for (int i = 0; i < a.length; i++) { - result[i] = a[i]/sum; + result[i] = a[i] / sum; } return result; } diff --git a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityLesserThanLinear.java b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityLesserThanLinear.java index f203fd32..a727e73c 100644 --- a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityLesserThanLinear.java +++ b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualityLesserThanLinear.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.constraint; import eva2.optimization.individuals.AbstractEAIndividual; -/** This area constraint for parallelization is based on +/** + * This area constraint for parallelization is based on * a line constraint * Created by IntelliJ IDEA. * User: streiche @@ -12,18 +13,19 @@ import eva2.optimization.individuals.AbstractEAIndividual; */ public class ConstObjectivesInEqualityLesserThanLinear implements InterfaceConstraint, java.io.Serializable { - private double m, b; + private double m, b; public ConstObjectivesInEqualityLesserThanLinear() { } + public ConstObjectivesInEqualityLesserThanLinear(double m, double b) { - this.m = m; - this.b = b; + this.m = m; + this.b = b; } public ConstObjectivesInEqualityLesserThanLinear(ConstObjectivesInEqualityLesserThanLinear a) { - this.b = a.b; - this.m = a.m; + this.b = a.b; + this.m = a.m; } @Override @@ -31,9 +33,11 @@ public class ConstObjectivesInEqualityLesserThanLinear implements InterfaceConst return (Object) new ConstObjectivesInEqualityLesserThanLinear(this); } - /** This method allows you wether or not a given individual + /** + * This method allows you wether or not a given individual * violates the constraints. - * @param indy The individual to check. + * + * @param indy The individual to check. * @return true if valid false else. */ @Override @@ -42,10 +46,9 @@ public class ConstObjectivesInEqualityLesserThanLinear implements InterfaceConst if (d.length != 2) { return true; } - if ((this.m*d[0] + this.b) > d[1]) { + if ((this.m * d[0] + this.b) > d[1]) { return true; - } - else { + } else { return false; } } diff --git a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualitySmallerThanSurface.java b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualitySmallerThanSurface.java index fb1bd422..e1cbccd2 100644 --- a/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualitySmallerThanSurface.java +++ b/src/eva2/optimization/operator/constraint/ConstObjectivesInEqualitySmallerThanSurface.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.constraint; import eva2.optimization.individuals.AbstractEAIndividual; -/** This area constraint for parallelization is based on +/** + * This area constraint for parallelization is based on * a surface constraint * Created by IntelliJ IDEA. * User: streiche @@ -12,18 +13,19 @@ import eva2.optimization.individuals.AbstractEAIndividual; */ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceConstraint, java.io.Serializable { - private double[] base, norm; + private double[] base, norm; public ConstObjectivesInEqualitySmallerThanSurface() { } + public ConstObjectivesInEqualitySmallerThanSurface(double[] base, double[] norm) { - this.base = base; - this.norm = norm; + this.base = base; + this.norm = norm; } public ConstObjectivesInEqualitySmallerThanSurface(ConstObjectivesInEqualitySmallerThanSurface a) { - this.base = a.base; - this.norm = a.norm; + this.base = a.base; + this.norm = a.norm; } @Override @@ -31,9 +33,11 @@ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceCon return (Object) new ConstObjectivesInEqualitySmallerThanSurface(this); } - /** This method allows you wether or not a given individual + /** + * This method allows you wether or not a given individual * violates the constraints. - * @param indy The individual to check. + * + * @param indy The individual to check. * @return true if valid false else. */ @Override @@ -41,8 +45,7 @@ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceCon double[] d = indy.getFitness(); if (this.getScalarProduct(norm, this.getSubstraction(d, base)) < 0) { return true; - } - else { + } else { return false; } } @@ -55,17 +58,21 @@ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceCon return result; } - /** This method returns the scalar product of two vectors + /** + * This method returns the scalar product of two vectors + * * @param a The first vector * @param b The second vector * @return The scalar product of a and b */ private double getScalarProduct(double[] a, double[] b) { - return (a[0]*b[0] + a[1]*b[1] + a[2]*b[2]); + return (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]); } - /** This method will return a normalized vector - * @param a The vector to normalize + /** + * This method will return a normalized vector + * + * @param a The vector to normalize * @return A normalized version of the input vector */ private double[] getNormalized(double[] a) { @@ -76,7 +83,7 @@ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceCon } sum = Math.sqrt(sum); for (int i = 0; i < a.length; i++) { - result[i] = a[i]/sum; + result[i] = a[i] / sum; } return result; } diff --git a/src/eva2/optimization/operator/constraint/ConstraintCollection.java b/src/eva2/optimization/operator/constraint/ConstraintCollection.java index 1ba6fd34..2befd017 100644 --- a/src/eva2/optimization/operator/constraint/ConstraintCollection.java +++ b/src/eva2/optimization/operator/constraint/ConstraintCollection.java @@ -1,77 +1,76 @@ package eva2.optimization.operator.constraint; /** - * To handle a set of constraints with a single parameter adaption mechanism. - * Single constraints are - * - * @author mkron + * To handle a set of constraints with a single parameter adaption mechanism. + * Single constraints are * + * @author mkron */ public class ConstraintCollection extends AbstractConstraint { - private AbstractConstraint[] constraintArray = new AbstractConstraint[]{}; + private AbstractConstraint[] constraintArray = new AbstractConstraint[]{}; - public ConstraintCollection() { - super(); - constraintArray = new AbstractConstraint[]{}; - } - - public ConstraintCollection(AbstractConstraint[] constrArr) { - super(); - constraintArray = constrArr; - } - - public ConstraintCollection(AbstractConstraint[] constrArr, ConstraintHandlingEnum handling, double penaltyFact) { - this(constrArr); - setHandlingMethod(handling); - setPenaltyFactor(penaltyFact); - } - - public ConstraintCollection(ConstraintCollection o) { - super(o); - constraintArray = o.constraintArray.clone(); - for (int i=0; i=indyX.length) { - System.err.println("Error in ImplicitConstraint!"); - return 0.; - } - return indyX[index]; - } + public ImplicitConstraint() { + } - public String getName() { - return "ImplicitCnstr-"+index; - } + public ImplicitConstraint(int cIndex) { + index = cIndex; + } - public static String globalInfo() { - return "Similar to a multi-objective translation into fitness, this class allows to interpret fitness criteria as constraints."; - } - - public int getIndex() { - return index; - } + @Override + public Object clone() { + return new ImplicitConstraint(index); + } - public void setIndex(int index) { - if (index>0) { - this.index = index; - } - else { - System.err.println("Error, invalid index (<=0) in ImplicitConstraint."); - } - } - - public String indexTipText() { - return "Set the index of the fitness criterion to be translated into a constraint, must be > 0"; - } + @Override + protected double getRawViolationValue(double[] indyX) { + if (index < 0 || index >= indyX.length) { + System.err.println("Error in ImplicitConstraint!"); + return 0.; + } + return indyX[index]; + } + + public String getName() { + return "ImplicitCnstr-" + index; + } + + public static String globalInfo() { + return "Similar to a multi-objective translation into fitness, this class allows to interpret fitness criteria as constraints."; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + if (index > 0) { + this.index = index; + } else { + System.err.println("Error, invalid index (<=0) in ImplicitConstraint."); + } + } + + public String indexTipText() { + return "Set the index of the fitness criterion to be translated into a constraint, must be > 0"; + } } diff --git a/src/eva2/optimization/operator/constraint/InterfaceConstraint.java b/src/eva2/optimization/operator/constraint/InterfaceConstraint.java index 199d7ccb..e9a4c646 100644 --- a/src/eva2/optimization/operator/constraint/InterfaceConstraint.java +++ b/src/eva2/optimization/operator/constraint/InterfaceConstraint.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.constraint; import eva2.optimization.individuals.AbstractEAIndividual; -/** This is a interface for area constraint for parallel MOEAs +/** + * This is a interface for area constraint for parallel MOEAs * giving area constraints on the separated parts for the Pareto front. * Created by IntelliJ IDEA. * User: streiche @@ -11,15 +12,19 @@ import eva2.optimization.individuals.AbstractEAIndividual; * To change this template use File | Settings | File Templates. */ public interface InterfaceConstraint { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method allows you wether or not a given individual + /** + * This method allows you wether or not a given individual * violates the constraints. - * @param indy The individual to check. + * + * @param indy The individual to check. * @return true if valid false else. */ public boolean isValid(AbstractEAIndividual indy); diff --git a/src/eva2/optimization/operator/constraint/InterfaceDoubleConstraint.java b/src/eva2/optimization/operator/constraint/InterfaceDoubleConstraint.java index 8578e3b9..5a17cb12 100644 --- a/src/eva2/optimization/operator/constraint/InterfaceDoubleConstraint.java +++ b/src/eva2/optimization/operator/constraint/InterfaceDoubleConstraint.java @@ -1,28 +1,29 @@ package eva2.optimization.operator.constraint; -/** +/** * A constraint delivering a double valued degree of violation. */ public interface InterfaceDoubleConstraint { - /** + /** * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); /** * Returns the boolean information whether the constraint is satisfied. - * + * * @param indy * @return */ public boolean isSatisfied(double[] indyX); - - /** + + /** * Return the absolute (positive) degree of violation or zero if the constraint * is fulfilled. - * + * * @param indy The individual to check. * @param indyX possibly the decoded individual position * @return true if valid false else. diff --git a/src/eva2/optimization/operator/constraint/IntervalConstraint.java b/src/eva2/optimization/operator/constraint/IntervalConstraint.java index 2da4f8a7..ccb5af84 100644 --- a/src/eva2/optimization/operator/constraint/IntervalConstraint.java +++ b/src/eva2/optimization/operator/constraint/IntervalConstraint.java @@ -3,134 +3,132 @@ package eva2.optimization.operator.constraint; import eva2.gui.editor.GenericObjectEditor; import eva2.tools.EVAERROR; import eva2.tools.math.Mathematics; + import java.io.Serializable; /** * A constraint for a parameter or a generic function to lie within certain bounds. - * @author mkron * + * @author mkron */ -public class IntervalConstraint extends AbstractConstraint implements InterfaceDoubleConstraint, Serializable{ - double lower=0; - double upper=1; - int index = 0; - GenericConstraint genericConstr = null; - - public IntervalConstraint() { - this(0,0.,1.); - genericConstr = null; - } - +public class IntervalConstraint extends AbstractConstraint implements InterfaceDoubleConstraint, Serializable { + double lower = 0; + double upper = 1; + int index = 0; + GenericConstraint genericConstr = null; + + public IntervalConstraint() { + this(0, 0., 1.); + genericConstr = null; + } + @Override - public void hideHideable() { - GenericObjectEditor.setHideProperty(this.getClass(), "relation", true); - } - - public IntervalConstraint(int index, double lowerBnd, double upperBnd) { - this.index=index; - this.lower=lowerBnd; - this.upper=upperBnd; - setRelation(ConstraintRelationEnum.lessEqZero); - genericConstr = null; - } - - public IntervalConstraint(String genericFunctionString, double lowerBnd, double upperBnd) { - this(0, lowerBnd, upperBnd); - setGenericFunction(genericFunctionString); - } - - public IntervalConstraint(IntervalConstraint o) { - this(o.index, o.lower, o.upper); - genericConstr = o.genericConstr; - } + public void hideHideable() { + GenericObjectEditor.setHideProperty(this.getClass(), "relation", true); + } - @Override - public Object clone() { - return new IntervalConstraint(this); - } + public IntervalConstraint(int index, double lowerBnd, double upperBnd) { + this.index = index; + this.lower = lowerBnd; + this.upper = upperBnd; + setRelation(ConstraintRelationEnum.lessEqZero); + genericConstr = null; + } - @Override - protected double getRawViolationValue(double[] indyX) { - if (genericConstr!=null) { - double constrFuncValue = genericConstr.getRawViolationValue(indyX); - return distanceToInterval(constrFuncValue); - } else { - if (index<0) { - double violSum=0; - for (int i=0;i=indyX.length) { - EVAERROR.errorMsgOnce("Error, invalid index for " + this.getClass().getSimpleName()); - return 0.; - } else { - return violInDim(index, indyX); - } - } - } - } - - public String getName() { - String clsName=this.getClass().getSimpleName(); - if (genericConstr!=null) { - return clsName+"/"+genericConstr.getConstraintString()+ " in ["+lower+","+upper+"]"; + public IntervalConstraint(String genericFunctionString, double lowerBnd, double upperBnd) { + this(0, lowerBnd, upperBnd); + setGenericFunction(genericFunctionString); + } + + public IntervalConstraint(IntervalConstraint o) { + this(o.index, o.lower, o.upper); + genericConstr = o.genericConstr; + } + + @Override + public Object clone() { + return new IntervalConstraint(this); + } + + @Override + protected double getRawViolationValue(double[] indyX) { + if (genericConstr != null) { + double constrFuncValue = genericConstr.getRawViolationValue(indyX); + return distanceToInterval(constrFuncValue); + } else { + if (index < 0) { + double violSum = 0; + for (int i = 0; i < indyX.length; i++) { + violSum += violInDim(i, indyX); + } + return violSum; + } else { + if (index >= indyX.length) { + EVAERROR.errorMsgOnce("Error, invalid index for " + this.getClass().getSimpleName()); + return 0.; + } else { + return violInDim(index, indyX); + } } - else { - if (index<0) { - return clsName+"/x_i in ["+lower+","+upper+"]"; - } - else { - return clsName+"/x_" + index + " in ["+lower+","+upper+"]"; - } - } - } + } + } - /** - * Return zero if the position respects the range, else the positive distance. - * - * @param i - * @param pos - * @return - */ - private double violInDim(int i, double[] pos) { - return distanceToInterval(pos[i]); - } - - /** - * Return zero if the position respects the range, else the positive distance. - * - * @param i - * @param pos - * @return - */ - private double distanceToInterval(double v) { - double tmp=Mathematics.projectValue(v, lower, upper); - return Math.abs(tmp-v); - } + public String getName() { + String clsName = this.getClass().getSimpleName(); + if (genericConstr != null) { + return clsName + "/" + genericConstr.getConstraintString() + " in [" + lower + "," + upper + "]"; + } else { + if (index < 0) { + return clsName + "/x_i in [" + lower + "," + upper + "]"; + } else { + return clsName + "/x_" + index + " in [" + lower + "," + upper + "]"; + } + } + } - public void setGenericFunction(String str) { - if (str!=null && (str.length()>0)) { - genericConstr = new GenericConstraint(str); - if (!genericConstr.checkValid()) { - genericConstr=null; - } - } else { - genericConstr=null; - } - } + /** + * Return zero if the position respects the range, else the positive distance. + * + * @param i + * @param pos + * @return + */ + private double violInDim(int i, double[] pos) { + return distanceToInterval(pos[i]); + } - public String getGenericFunction() { - if (genericConstr==null) { - return ""; + /** + * Return zero if the position respects the range, else the positive distance. + * + * @param i + * @param pos + * @return + */ + private double distanceToInterval(double v) { + double tmp = Mathematics.projectValue(v, lower, upper); + return Math.abs(tmp - v); + } + + public void setGenericFunction(String str) { + if (str != null && (str.length() > 0)) { + genericConstr = new GenericConstraint(str); + if (!genericConstr.checkValid()) { + genericConstr = null; } - else { - return genericConstr.getConstraintString(); - } - } - - public String genericConstrTipText() { - return "A generic function can be used as in GenericConstraint - it has priority."; - } + } else { + genericConstr = null; + } + } + + public String getGenericFunction() { + if (genericConstr == null) { + return ""; + } else { + return genericConstr.getConstraintString(); + } + } + + public String genericConstrTipText() { + return "A generic function can be used as in GenericConstraint - it has priority."; + } } diff --git a/src/eva2/optimization/operator/crossover/AdaptiveCrossoverEAMixer.java b/src/eva2/optimization/operator/crossover/AdaptiveCrossoverEAMixer.java index 27394425..b245f42a 100644 --- a/src/eva2/optimization/operator/crossover/AdaptiveCrossoverEAMixer.java +++ b/src/eva2/optimization/operator/crossover/AdaptiveCrossoverEAMixer.java @@ -7,104 +7,104 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; /** * A modified version of the CrossoverEAMixer that adapts the weights with which the crossover-methods are chosen - * - * @author Alex * + * @author Alex */ public class AdaptiveCrossoverEAMixer extends CrossoverEAMixer implements InterfaceAdaptOperatorGenerational { - private Population pop = new Population(); - private boolean initialized = false; - private double lastFitness = Double.MAX_VALUE; - private int[] used; - private InterfaceOptimizationProblem opt; + private Population pop = new Population(); + private boolean initialized = false; + private double lastFitness = Double.MAX_VALUE; + private int[] used; + private InterfaceOptimizationProblem opt; - public AdaptiveCrossoverEAMixer(){ - super(); - } + public AdaptiveCrossoverEAMixer() { + super(); + } - public AdaptiveCrossoverEAMixer(AdaptiveCrossoverEAMixer mutator) { - super(mutator); - this.pop = (Population) mutator.pop.clone(); // TODO !Make a deep copy!? - this.initialized = mutator.initialized; - this.lastFitness = mutator.lastFitness; - this.used = mutator.used; - this.opt = mutator.opt; - } - - /** + public AdaptiveCrossoverEAMixer(AdaptiveCrossoverEAMixer mutator) { + super(mutator); + this.pop = (Population) mutator.pop.clone(); // TODO !Make a deep copy!? + this.initialized = mutator.initialized; + this.lastFitness = mutator.lastFitness; + this.used = mutator.used; + this.opt = mutator.opt; + } + + /** * Create a mutation mixer with equal weights of the given mutation operators. + * * @param mutators */ - public AdaptiveCrossoverEAMixer(InterfaceCrossover ... crossovers) { + public AdaptiveCrossoverEAMixer(InterfaceCrossover... crossovers) { this.m_Crossers = new PropertyCrossoverMixer(crossovers); this.m_Crossers.m_SelectedTargets = m_Crossers.m_AvailableTargets.clone(); } - @Override - protected void maybeAdaptWeights(AbstractEAIndividual[] indies) { - if(initialized){ - AbstractEAIndividual indy = indies[0]; - this.opt.evaluate(indy); - this.pop.incrFunctionCalls(); - if(indy.getFitness(0)0); - if(indy1 instanceof InterfaceDataTypeBinary && partners.getEAIndividual(0) instanceof InterfaceDataTypeBinary){ - BitSet data = ((InterfaceDataTypeBinary) indy1).getBinaryData(); - BitSet dataSave = (BitSet) data.clone(); - BitSet data2 = ((InterfaceDataTypeBinary) partners.getEAIndividual(0)).getBinaryData(); - double f1 = indy1.getFitness(0); - double f2 = partners.getEAIndividual(0).getFitness(0); - double min = Math.min(f1, f2); - int different = 0; - boolean foundBetter = false; - for(int i=0; i 0){ - dataSave.flip(i); - } - } - } - ((InterfaceDataTypeBinary) indy1).SetBinaryGenotype(data); - } - result[0] = indy1; - return result; - } + private InterfaceOptimizationProblem m_OptimizationProblem; + private int evaluations = 0; + + public CM7() { + + } + + public CM7(CM7 c) { + this.m_OptimizationProblem = c.m_OptimizationProblem; + this.evaluations = c.evaluations; + } @Override - public void init(AbstractEAIndividual individual, - InterfaceOptimizationProblem opt) { - this.m_OptimizationProblem = opt; - } + public Object clone() { + return new CM7(this); + } @Override - public String getStringRepresentation() { - return getName(); - } - + public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, + Population partners) { + AbstractEAIndividual[] result = null; + result = new AbstractEAIndividual[1]; + if (partners.size() > 0) ; + if (indy1 instanceof InterfaceDataTypeBinary && partners.getEAIndividual(0) instanceof InterfaceDataTypeBinary) { + BitSet data = ((InterfaceDataTypeBinary) indy1).getBinaryData(); + BitSet dataSave = (BitSet) data.clone(); + BitSet data2 = ((InterfaceDataTypeBinary) partners.getEAIndividual(0)).getBinaryData(); + double f1 = indy1.getFitness(0); + double f2 = partners.getEAIndividual(0).getFitness(0); + double min = Math.min(f1, f2); + int different = 0; + boolean foundBetter = false; + for (int i = 0; i < data.size(); i++) { + if (data.get(i) != data2.get(i)) { + different++; + data.flip(i); + ((InterfaceDataTypeBinary) indy1).SetBinaryGenotype(data); + this.m_OptimizationProblem.evaluate(indy1); + this.evaluations++; + if (indy1.getFitness(0) < min) { + foundBetter = true; + i = data.size(); + } + } + } + if (!foundBetter) { + for (int i = 0; i < dataSave.size(); i++) { + if (dataSave.get(i) != data2.get(i) && different > 0) { + dataSave.flip(i); + } + } + } + ((InterfaceDataTypeBinary) indy1).SetBinaryGenotype(data); + } + result[0] = indy1; + return result; + } + @Override - public int getEvaluations(){ - return this.evaluations; - } - - /***************************************************** - * GUI - */ - - public String getName(){ - return "Combination Method 7"; - } - - public static String globalInfo() { - //TODO + public void init(AbstractEAIndividual individual, + InterfaceOptimizationProblem opt) { + this.m_OptimizationProblem = opt; + } + + @Override + public String getStringRepresentation() { + return getName(); + } + + @Override + public int getEvaluations() { + return this.evaluations; + } + + /** + * ************************************************** + * GUI + */ + + public String getName() { + return "Combination Method 7"; + } + + public static String globalInfo() { + //TODO return ""; } @Override - public void resetEvaluations() { - this.evaluations = 0; - } + public void resetEvaluations() { + this.evaluations = 0; + } } diff --git a/src/eva2/optimization/operator/crossover/CrossoverEAMixer.java b/src/eva2/optimization/operator/crossover/CrossoverEAMixer.java index e505e78b..69354d5e 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverEAMixer.java +++ b/src/eva2/optimization/operator/crossover/CrossoverEAMixer.java @@ -5,6 +5,7 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.ArrayList; @@ -15,61 +16,63 @@ import java.util.ArrayList; * Time: 11:36:38 * To change this template use File | Settings | File Templates. */ -public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluatingCrossoverOperator, java.io.Serializable { - public static final String CROSSOVER_EA_MIXER_OPERATOR_KEY = "CrossoverEAMixerOperatorKey"; - - protected PropertyCrossoverMixer m_Crossers; - protected boolean m_UseSelfAdaption = false; - protected double m_Tau1 = 0.15; - protected double m_LowerLimitChance = 0.05; - protected int lastOperatorIndex = -1; +public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluatingCrossoverOperator, java.io.Serializable { + public static final String CROSSOVER_EA_MIXER_OPERATOR_KEY = "CrossoverEAMixerOperatorKey"; - public CrossoverEAMixer() { - InterfaceCrossover[] tmpList; - ArrayList crossers = GenericObjectEditor.getClassesFromProperties(InterfaceCrossover.class.getCanonicalName(), null); - tmpList = new InterfaceCrossover[crossers.size()]; - for (int i = 0; i < crossers.size(); i++) { - Class clz=null; - try { - clz = (Class)Class.forName((String)crossers.get(i)); - } catch (ClassNotFoundException e1) { - continue; - } - if (clz.isAssignableFrom(this.getClass())) { - // Do not instanciate this class or its subclasses or die of an infinite loop + protected PropertyCrossoverMixer m_Crossers; + protected boolean m_UseSelfAdaption = false; + protected double m_Tau1 = 0.15; + protected double m_LowerLimitChance = 0.05; + protected int lastOperatorIndex = -1; + + public CrossoverEAMixer() { + InterfaceCrossover[] tmpList; + ArrayList crossers = GenericObjectEditor.getClassesFromProperties(InterfaceCrossover.class.getCanonicalName(), null); + tmpList = new InterfaceCrossover[crossers.size()]; + for (int i = 0; i < crossers.size(); i++) { + Class clz = null; + try { + clz = (Class) Class.forName((String) crossers.get(i)); + } catch (ClassNotFoundException e1) { + continue; + } + if (clz.isAssignableFrom(this.getClass())) { + // Do not instanciate this class or its subclasses or die of an infinite loop // System.out.println("Skipping " + clz.getClass().getName()); - continue; - } else { + continue; + } else { // System.out.println("Taking " + clz.getClass().getName()); - } - try { - tmpList[i] = (InterfaceCrossover)Class.forName((String)crossers.get(i)).newInstance(); - } catch (java.lang.ClassNotFoundException e) { - System.out.println("Could not find class for " +(String)crossers.get(i) ); - } catch (java.lang.InstantiationException k) { - System.out.println("Instantiation exception for " +(String)crossers.get(i) ); - } catch (java.lang.IllegalAccessException a) { - System.out.println("Illegal access exception for " +(String)crossers.get(i) ); - } - } - this.m_Crossers = new PropertyCrossoverMixer(tmpList); - tmpList = new InterfaceCrossover[2]; - tmpList[0] = new CrossoverESArithmetical(); - tmpList[1] = new CrossoverESSBX(); - this.m_Crossers.setSelectedCrossers(tmpList); - this.m_Crossers.normalizeWeights(); - this.m_Crossers.setDescriptiveString("Combining alternative mutation operators, please norm the weights!"); - this.m_Crossers.setWeightsLabel("Weigths"); - } + } + try { + tmpList[i] = (InterfaceCrossover) Class.forName((String) crossers.get(i)).newInstance(); + } catch (java.lang.ClassNotFoundException e) { + System.out.println("Could not find class for " + (String) crossers.get(i)); + } catch (java.lang.InstantiationException k) { + System.out.println("Instantiation exception for " + (String) crossers.get(i)); + } catch (java.lang.IllegalAccessException a) { + System.out.println("Illegal access exception for " + (String) crossers.get(i)); + } + } + this.m_Crossers = new PropertyCrossoverMixer(tmpList); + tmpList = new InterfaceCrossover[2]; + tmpList[0] = new CrossoverESArithmetical(); + tmpList[1] = new CrossoverESSBX(); + this.m_Crossers.setSelectedCrossers(tmpList); + this.m_Crossers.normalizeWeights(); + this.m_Crossers.setDescriptiveString("Combining alternative mutation operators, please norm the weights!"); + this.m_Crossers.setWeightsLabel("Weigths"); + } public CrossoverEAMixer(CrossoverEAMixer mutator) { - this.m_Crossers = (PropertyCrossoverMixer)mutator.m_Crossers.clone(); - this.m_UseSelfAdaption = mutator.m_UseSelfAdaption; - this.m_Tau1 = mutator.m_Tau1; + this.m_Crossers = (PropertyCrossoverMixer) mutator.m_Crossers.clone(); + this.m_UseSelfAdaption = mutator.m_UseSelfAdaption; + this.m_Tau1 = mutator.m_Tau1; this.m_LowerLimitChance = mutator.m_LowerLimitChance; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -77,14 +80,16 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating return new CrossoverEAMixer(this); } - /** This method allows you to evaluate whether two mutation operators + /** + * This method allows you to evaluate whether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof CrossoverEAMixer) { - CrossoverEAMixer mut = (CrossoverEAMixer)mutator; + CrossoverEAMixer mut = (CrossoverEAMixer) mutator; return true; } else { @@ -92,27 +97,31 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating } } - /** This method allows you to init the crossover operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the crossover operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ - InterfaceCrossover[] crossers = this.m_Crossers.getSelectedCrossers(); + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { + InterfaceCrossover[] crossers = this.m_Crossers.getSelectedCrossers(); for (int i = 0; i < crossers.length; i++) { crossers[i].init(individual, opt); } } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { this.m_Crossers.normalizeWeights(); - double[] probs = this.m_Crossers.getWeights(); + double[] probs = this.m_Crossers.getWeights(); if (this.m_UseSelfAdaption) { for (int i = 0; i < probs.length; i++) { probs[i] *= Math.exp(this.m_Tau1 * RNG.gaussianDouble(1)); @@ -126,42 +135,44 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating this.m_Crossers.normalizeWeights(); } - InterfaceCrossover[] crossover = this.m_Crossers.getSelectedCrossers(); - double pointer = RNG.randomFloat(0, 1); - double dum = probs[0]; - lastOperatorIndex = 0; - while ((pointer > dum) && (lastOperatorIndex < probs.length-1)) { - lastOperatorIndex++; + InterfaceCrossover[] crossover = this.m_Crossers.getSelectedCrossers(); + double pointer = RNG.randomFloat(0, 1); + double dum = probs[0]; + lastOperatorIndex = 0; + while ((pointer > dum) && (lastOperatorIndex < probs.length - 1)) { + lastOperatorIndex++; dum += probs[lastOperatorIndex]; } if (lastOperatorIndex == probs.length) { - lastOperatorIndex = RNG.randomInt(0, probs.length-1); + lastOperatorIndex = RNG.randomInt(0, probs.length - 1); } // System.out.println("Using : " + mutators[index].getStringRepresentation()); // for (int i = 0; i < probs.length; i++) { // System.out.println(""+mutators[i].getStringRepresentation()+" : "+ probs[i]); // } // System.out.println(""); - + indy1.putData(CROSSOVER_EA_MIXER_OPERATOR_KEY, lastOperatorIndex); - for (int i=0; i * Created by IntelliJ IDEA. * User: streiche * Date: 25.07.2003 @@ -20,70 +20,76 @@ import eva2.tools.math.RNG; */ public class CrossoverESArithmetical implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverESArithmetical() { } public CrossoverESArithmetical(CrossoverESArithmetical c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override public Object clone() { return new CrossoverESArithmetical(this); } - /** This method performs crossover on two individuals. If the individuals do + + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - double intermediate; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + double intermediate; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } - double[] alpha = new double[parents.length]; - double sum = 0; + double[] alpha = new double[parents.length]; + double sum = 0; for (int i = 0; i < children.length; i++) { sum = 0; for (int j = 0; j < alpha.length; j++) { - alpha[j] = RNG.randomDouble(0,1); + alpha[j] = RNG.randomDouble(0, 1); sum += alpha[j]; } - for (int j = 0; j * User: streiche * Date: 25.03.2003 * Time: 11:16:39 * To change this template use Options | File Templates. */ public class CrossoverESDefault implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverESDefault() { } + public CrossoverESDefault(CrossoverESDefault c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -31,55 +35,56 @@ public class CrossoverESDefault implements InterfaceCrossover, java.io.Serializa return new CrossoverESDefault(this); } - /** + /** * This method performs crossover on two individuals. If the individuals do * not implement InterfaceESIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); - if (partners==null || (partners.size()==0)) { - throw new RuntimeException("Error, empty partner population for crossover!"); + if (partners == null || (partners.size() == 0)) { + throw new RuntimeException("Error, empty partner population for crossover!"); } if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - int crossoverpoint = RNG.randomInt(0,((InterfaceESIndividual)indy1).getDGenotype().length-1); + int crossoverpoint = RNG.randomInt(0, ((InterfaceESIndividual) indy1).getDGenotype().length - 1); boolean switcher = RNG.randomBoolean(); - parents = new double[result.length][]; - children = new double[result.length][]; + parents = new double[result.length][]; + children = new double[result.length][]; for (int i = 0; i < result.length; i++) { - // first clone all data arrays - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + // first clone all data arrays + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < children[0].length; i++) { - if ((i < crossoverpoint)^(switcher)) { + if ((i < crossoverpoint) ^ (switcher)) { // do nothing } else { // exchange circular among the parents - for (int j = 0; j < children.length-1; j++) { - children[j][i] = parents[j+1][i]; + for (int j = 0; j < children.length - 1; j++) { + children[j][i] = parents[j + 1][i]; } - children[children.length-1][i] = parents[0][i]; + children[children.length - 1][i] = parents[0][i]; } } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successful lets give the mutation operators a chance to mate the strategy parameters @@ -90,26 +95,29 @@ public class CrossoverESDefault implements InterfaceCrossover, java.io.Serializa return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESDefault) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -121,17 +129,22 @@ public class CrossoverESDefault implements InterfaceCrossover, java.io.Serializa return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES discrete one-point crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverESFlat.java b/src/eva2/optimization/operator/crossover/CrossoverESFlat.java index a903ce86..04b44c33 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESFlat.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESFlat.java @@ -11,10 +11,10 @@ import eva2.tools.math.RNG; * The flat crossover inits values randomly within the extreme values of * all parents, namely * c[i]=rand(min_j(p_ij), max_j(p_ij)). - * + *

* where c[i] is the i-th child component and p_ij is the i-th component * of parent j. - * + *

* Created by IntelliJ IDEA. * User: streiche * Date: 02.12.2003 @@ -22,15 +22,19 @@ import eva2.tools.math.RNG; * To change this template use Options | File Templates. */ public class CrossoverESFlat implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverESFlat() { } + public CrossoverESFlat(CrossoverESFlat c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -38,37 +42,39 @@ public class CrossoverESFlat implements InterfaceCrossover, java.io.Serializable return new CrossoverESFlat(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; - double[][] extremeValues; + AbstractEAIndividual[] result = null; + double[][] parents, children; + double[][] extremeValues; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; - extremeValues = new double[((InterfaceESIndividual)result[0]).getDGenotype().length][2]; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; + extremeValues = new double[((InterfaceESIndividual) result[0]).getDGenotype().length][2]; for (int i = 0; i < extremeValues.length; i++) { extremeValues[i][0] = Double.MAX_VALUE; extremeValues[i][1] = Double.MIN_VALUE; } for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); for (int j = 0; j < parents[i].length; j++) { extremeValues[j][0] = Math.min(extremeValues[j][0], parents[i][j]); extremeValues[j][1] = Math.max(extremeValues[j][1], parents[i][j]); @@ -76,13 +82,13 @@ public class CrossoverESFlat implements InterfaceCrossover, java.io.Serializable } for (int i = 0; i < children.length; i++) { - for(int j = 0; j < children[i].length; j++) { + for (int j = 0; j < children[i].length; j++) { children[i][j] = RNG.randomDouble(extremeValues[j][0], extremeValues[j][1]); } } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -93,26 +99,29 @@ public class CrossoverESFlat implements InterfaceCrossover, java.io.Serializable return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESFlat) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -124,17 +133,22 @@ public class CrossoverESFlat implements InterfaceCrossover, java.io.Serializable return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES flat crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverESIntermediate.java b/src/eva2/optimization/operator/crossover/CrossoverESIntermediate.java index 4055a0c6..f48c73c3 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESIntermediate.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESIntermediate.java @@ -13,15 +13,19 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * To change this template use Options | File Templates. */ public class CrossoverESIntermediate implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverESIntermediate() { } + public CrossoverESIntermediate(CrossoverESIntermediate c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -29,32 +33,34 @@ public class CrossoverESIntermediate implements InterfaceCrossover, java.io.Seri return new CrossoverESIntermediate(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - double intermediate; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + double intermediate; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < children[0].length; i++) { @@ -69,9 +75,9 @@ public class CrossoverESIntermediate implements InterfaceCrossover, java.io.Seri } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } - } + } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters for (int i = 0; i < result.length; i++) { result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); @@ -80,26 +86,29 @@ public class CrossoverESIntermediate implements InterfaceCrossover, java.io.Seri return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESIntermediate) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -111,17 +120,22 @@ public class CrossoverESIntermediate implements InterfaceCrossover, java.io.Seri return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES intermediate crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscrete.java b/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscrete.java index 0ca9c62b..acd23d08 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscrete.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscrete.java @@ -14,18 +14,21 @@ import eva2.tools.math.RNG; * To change this template use Options | File Templates. */ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private int m_NumberOfCrossovers = 3; + private InterfaceOptimizationProblem m_OptimizationProblem; + private int m_NumberOfCrossovers = 3; public CrossoverESNPointDiscrete() { } + public CrossoverESNPointDiscrete(CrossoverESNPointDiscrete mutator) { - this.m_OptimizationProblem = mutator.m_OptimizationProblem; - this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; + this.m_OptimizationProblem = mutator.m_OptimizationProblem; + this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; } - /** This method will enable you to clone a given crossover operator + /** + * This method will enable you to clone a given crossover operator + * * @return The clone */ @Override @@ -33,38 +36,40 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se return new CrossoverESNPointDiscrete(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - int length = ((InterfaceESIndividual)result[0]).getDGenotype().length; - int mixer = RNG.randomInt(0, partners.size()); - int[] crossoverPoints = new int[this.m_NumberOfCrossovers]; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + int length = ((InterfaceESIndividual) result[0]).getDGenotype().length; + int mixer = RNG.randomInt(0, partners.size()); + int[] crossoverPoints = new int[this.m_NumberOfCrossovers]; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < this.m_NumberOfCrossovers; i++) { - crossoverPoints[i] = RNG.randomInt(0, length-1); + crossoverPoints[i] = RNG.randomInt(0, length - 1); } for (int i = 0; i < length; i++) { for (int j = 0; j < this.m_NumberOfCrossovers; j++) { @@ -73,13 +78,13 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se } } for (int j = 0; j < children.length; j++) { - children[j][i] = parents[(j + mixer) % parents.length][i]; + children[j][i] = parents[(j + mixer) % parents.length][i]; } } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -90,30 +95,33 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESNPointDiscrete) { - CrossoverESNPointDiscrete cross = (CrossoverESNPointDiscrete)crossover; + CrossoverESNPointDiscrete cross = (CrossoverESNPointDiscrete) crossover; if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { return false; } return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -128,23 +136,30 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES discrete n-point crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a discrete n-point crossover between m ES individuals."; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param crossovers The number of crossovers. + * + * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { if (crossovers < 0) { @@ -152,9 +167,11 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se } this.m_NumberOfCrossovers = crossovers; } + public int getNumberOfCrossovers() { return this.m_NumberOfCrossovers; } + public String numberOfCrossoversTipText() { return "The number of crossoverpoints."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscreteDislocation.java b/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscreteDislocation.java index f461bdd8..21654ec0 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscreteDislocation.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESNPointDiscreteDislocation.java @@ -14,18 +14,21 @@ import eva2.tools.math.RNG; * To change this template use File | Settings | File Templates. */ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private int m_NumberOfCrossovers = 3; + private InterfaceOptimizationProblem m_OptimizationProblem; + private int m_NumberOfCrossovers = 3; public CrossoverESNPointDiscreteDislocation() { } + public CrossoverESNPointDiscreteDislocation(CrossoverESNPointDiscreteDislocation mutator) { - this.m_OptimizationProblem = mutator.m_OptimizationProblem; - this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; + this.m_OptimizationProblem = mutator.m_OptimizationProblem; + this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; } - /** This method will enable you to clone a given crossover operator + /** + * This method will enable you to clone a given crossover operator + * * @return The clone */ @Override @@ -33,42 +36,44 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, return new CrossoverESNPointDiscreteDislocation(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - int length = ((InterfaceESIndividual)result[0]).getDGenotype().length; - int mixer = RNG.randomInt(0, partners.size()); - int[] crossoverPoints = new int[this.m_NumberOfCrossovers+1]; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + int length = ((InterfaceESIndividual) result[0]).getDGenotype().length; + int mixer = RNG.randomInt(0, partners.size()); + int[] crossoverPoints = new int[this.m_NumberOfCrossovers + 1]; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < crossoverPoints.length; i++) { - crossoverPoints[i] = RNG.randomInt(0, length-1); + crossoverPoints[i] = RNG.randomInt(0, length - 1); } - crossoverPoints[RNG.randomInt(0,this.m_NumberOfCrossovers)] = 0; - int parIndex = 0; - int chiIndex = 0; + crossoverPoints[RNG.randomInt(0, this.m_NumberOfCrossovers)] = 0; + int parIndex = 0; + int chiIndex = 0; boolean bol; for (int i = 0; i < crossoverPoints.length; i++) { parIndex = crossoverPoints[i]; @@ -94,7 +99,7 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -105,14 +110,16 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESNPointDiscreteDislocation) { - CrossoverESNPointDiscreteDislocation cross = (CrossoverESNPointDiscreteDislocation)crossover; + CrossoverESNPointDiscreteDislocation cross = (CrossoverESNPointDiscreteDislocation) crossover; if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { return false; } @@ -122,12 +129,14 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -142,23 +151,30 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES discrete n-point crossover with dislocation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a discrete n-point crossover between m ES individuals with dislocation."; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param crossovers The number of crossovers. + * + * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { if (crossovers < 0) { @@ -166,9 +182,11 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, } this.m_NumberOfCrossovers = crossovers; } + public int getNumberOfCrossovers() { return this.m_NumberOfCrossovers; } + public String numberOfCrossoversTipText() { return "The number of crossoverpoints."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverESPCX.java b/src/eva2/optimization/operator/crossover/CrossoverESPCX.java index b37d209c..72ea11a6 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESPCX.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESPCX.java @@ -10,6 +10,7 @@ import eva2.optimization.problems.F1Problem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.util.ArrayList; /** @@ -21,19 +22,23 @@ import java.util.ArrayList; */ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private double m_Eta = 0.2; - private double m_Zeta = 0.2; + private InterfaceOptimizationProblem m_OptimizationProblem; + private double m_Eta = 0.2; + private double m_Zeta = 0.2; public CrossoverESPCX() { } + public CrossoverESPCX(CrossoverESPCX c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; - this.m_Eta = c.m_Eta; - this.m_Zeta = c.m_Zeta; + this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_Eta = c.m_Eta; + this.m_Zeta = c.m_Zeta; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -41,37 +46,39 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable return new CrossoverESPCX(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - double intermediate; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + double intermediate; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } - double[] g = Mathematics.meanVect(parents), tmpD; - double w, v; - ArrayList subSpace; + double[] g = Mathematics.meanVect(parents), tmpD; + double w, v; + ArrayList subSpace; // now determine the offsprings for (int i = 0; i < children.length; i++) { // direction vector @@ -99,11 +106,11 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable // first the parent and the d for (int j = 0; j < parents[i].length; j++) { children[i][j] = parents[i][j]; - children[i][j] += RNG.gaussianDouble(this.m_Zeta)*tmpD[j]; + children[i][j] += RNG.gaussianDouble(this.m_Zeta) * tmpD[j]; } // then the other parents for (int j = 1; j < subSpace.size(); j++) { - tmpD = (double[])subSpace.get(j); + tmpD = (double[]) subSpace.get(j); w = RNG.gaussianDouble(this.m_Zeta); children[i] = Mathematics.vvAdd(children[i], Mathematics.svMult(w, tmpD)); } @@ -111,7 +118,7 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -123,9 +130,9 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable } private ArrayList getCoordinates(double[] mean, int index, double[][] parents) { - ArrayList result = new ArrayList(); - double[] tmpVec, toro; - double tmpD; + ArrayList result = new ArrayList(); + double[] tmpVec, toro; + double tmpD; tmpVec = Mathematics.vvSub(parents[index], mean); result.add(tmpVec); @@ -137,7 +144,7 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable // apply the infamous Gram-Schmidt for (int j = 0; j < result.size(); j++) { toro = (double[]) result.get(j); - tmpD = Mathematics.vvMult(toro, tmpVec)/Mathematics.vvMult(toro, toro); + tmpD = Mathematics.vvMult(toro, tmpVec) / Mathematics.vvMult(toro, toro); toro = Mathematics.svMult(tmpD, toro); tmpVec = Mathematics.vvSub(tmpVec, toro); } @@ -159,7 +166,7 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable tmpMean += Math.abs(Mathematics.vvMult(toro, Mathematics.vvSub(parents[j], mean))); } } - tmpMean /= ((double)(result.size()-1)); + tmpMean /= ((double) (result.size() - 1)); toro = Mathematics.svMult(tmpMean, toro); result.set(i, toro); } @@ -173,7 +180,7 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable if (Double.isNaN(d[i])) { return false; } - sum += Math.pow(d[i],2); + sum += Math.pow(d[i], 2); } if (Double.isNaN(sum)) { return false; @@ -184,26 +191,29 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable return true; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESUNDX) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -211,13 +221,13 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable } public static void main(String[] args) { - boolean plotFlag = true; - Plot plot = null; - Population pop = new Population(); - double[] tmpD = new double[2]; - ESIndividualDoubleData indy1, indy2, indy3, indy4; - F1Problem prob = new F1Problem(); - int n = 2; + boolean plotFlag = true; + Plot plot = null; + Population pop = new Population(); + double[] tmpD = new double[2]; + ESIndividualDoubleData indy1, indy2, indy3, indy4; + F1Problem prob = new F1Problem(); + int n = 2; //RNG.setseed(1); // init individual @@ -225,14 +235,14 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable double[][] range = new double[n][2]; for (int i = 0; i < range.length; i++) { range[i][0] = -2; - range[i][1] = 2; + range[i][1] = 2; } indy1.setDoubleDataLength(n); indy1.SetDoubleRange(range); // init values - indy2 = (ESIndividualDoubleData)indy1.clone(); - indy3 = (ESIndividualDoubleData)indy1.clone(); - indy4 = (ESIndividualDoubleData)indy1.clone(); + indy2 = (ESIndividualDoubleData) indy1.clone(); + indy3 = (ESIndividualDoubleData) indy1.clone(); + indy4 = (ESIndividualDoubleData) indy1.clone(); if (false) { // random init indy1.defaultInit(prob); @@ -244,18 +254,18 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable tmpD[0] = 0; tmpD[1] = 1; indy1.initByValue(tmpD, prob); - tmpD[0] = -1; - tmpD[1] = 1; + tmpD[0] = -1; + tmpD[1] = 1; indy2.initByValue(tmpD, prob); tmpD[0] = 1; tmpD[1] = -1; indy3.initByValue(tmpD, prob); tmpD[0] = 0.5; - tmpD[1] = 1; + tmpD[1] = 1; indy4.initByValue(tmpD, prob); } // set the parents - pop= new Population(); + pop = new Population(); pop.add(indy2); pop.add(indy3); //pop.add(indy4); @@ -276,13 +286,13 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable plot.setUnconnectedPoint(2, 2, 0); } CrossoverESPCX cross = new CrossoverESPCX(); - cross.m_Eta = 0.2; - cross.m_Zeta = 0.2; + cross.m_Eta = 0.2; + cross.m_Zeta = 0.2; AbstractEAIndividual[] offsprings; for (int i = 0; i < 1; i++) { offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { - tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); + tmpD = ((ESIndividualDoubleData) offsprings[j]).getDoubleData(); if (plotFlag) { plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); } @@ -297,43 +307,54 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES PCX crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is the Parent Centric Crossover (PCX)."; } + public void setEta(double a) { if (a < 0) { a = 0; } this.m_Eta = a; } + public double getEta() { return this.m_Eta; } + public String etaTipText() { return "The Eta of PCX."; } + public void setZeta(double a) { if (a < 0) { a = 0; } this.m_Zeta = a; } + public double getZeta() { return this.m_Zeta; } + public String zetaTipText() { return "The Zeta of PCX."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverESSBX.java b/src/eva2/optimization/operator/crossover/CrossoverESSBX.java index 574f43d3..45f60097 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESSBX.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESSBX.java @@ -18,22 +18,25 @@ import eva2.tools.math.RNG; */ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private double m_Eta = 0.2; + private InterfaceOptimizationProblem m_OptimizationProblem; + private double m_Eta = 0.2; public CrossoverESSBX() { } - + public CrossoverESSBX(double eta) { - m_Eta=eta; + m_Eta = eta; } - + public CrossoverESSBX(CrossoverESSBX c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; - this.m_Eta = c.m_Eta; + this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_Eta = c.m_Eta; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -41,47 +44,49 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable return new CrossoverESSBX(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; - double beta, u; + AbstractEAIndividual[] result = null; + double[][] parents, children; + double beta, u; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < children[0].length; i++) { - u = RNG.randomDouble(0,1); + u = RNG.randomDouble(0, 1); if (u <= 0.5) { - beta = Math.pow((2*u), 1/(this.m_Eta + 1)); + beta = Math.pow((2 * u), 1 / (this.m_Eta + 1)); } else { - beta = Math.pow((0.5/(1-u)), 1/(this.m_Eta + 1)); + beta = Math.pow((0.5 / (1 - u)), 1 / (this.m_Eta + 1)); } - children[0][i] = 0.5 * ( (1 + beta)*parents[0][i] + (1 - beta)*parents[1][i] ); - children[1][i] = 0.5 * ( (1 - beta)*parents[0][i] + (1 + beta)*parents[1][i] ); + children[0][i] = 0.5 * ((1 + beta) * parents[0][i] + (1 - beta) * parents[1][i]); + children[1][i] = 0.5 * ((1 - beta) * parents[0][i] + (1 + beta) * parents[1][i]); } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -92,30 +97,33 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESSBX) { - CrossoverESSBX cross = (CrossoverESSBX)crossover; + CrossoverESSBX cross = (CrossoverESSBX) crossover; if (this.m_Eta != cross.m_Eta) { return false; } return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -123,23 +131,23 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable } public static void main(String[] args) { - Population pop = new Population(); - double[] tmpD = new double[2]; - ESIndividualDoubleData indy1, indy2, indy3; - F1Problem prob = new F1Problem(); + Population pop = new Population(); + double[] tmpD = new double[2]; + ESIndividualDoubleData indy1, indy2, indy3; + F1Problem prob = new F1Problem(); // init individual indy1 = new ESIndividualDoubleData(); double[][] range = new double[2][2]; range[0][0] = -2.0; - range[0][1] = 2.0; + range[0][1] = 2.0; range[1][0] = -2.0; - range[1][1] = 2.0; + range[1][1] = 2.0; indy1.setDoubleDataLength(2); indy1.SetDoubleRange(range); // init values - indy2 = (ESIndividualDoubleData)indy1.clone(); - indy3 = (ESIndividualDoubleData)indy1.clone(); + indy2 = (ESIndividualDoubleData) indy1.clone(); + indy3 = (ESIndividualDoubleData) indy1.clone(); if (false) { // random init indy1.defaultInit(prob); @@ -150,11 +158,11 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable tmpD[0] = 0.5; tmpD[1] = -0.5; indy1.initByValue(tmpD, prob); - tmpD[0] = -0.5; - tmpD[1] = 0.5; + tmpD[0] = -0.5; + tmpD[1] = 0.5; indy2.initByValue(tmpD, prob); tmpD[0] = -0.5; - tmpD[1] = 1; + tmpD[1] = 1; indy3.initByValue(tmpD, prob); } // set the parents @@ -174,12 +182,12 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable plot.setUnconnectedPoint(2, 2, 0); CrossoverESSBX cross = new CrossoverESSBX(); - cross.m_Eta = 0.2; + cross.m_Eta = 0.2; AbstractEAIndividual[] offsprings; for (int i = 0; i < 5000; i++) { offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { - tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); + tmpD = ((ESIndividualDoubleData) offsprings[j]).getDoubleData(); plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); //range = ((ESIndividualDoubleData)offsprings[j]).getDoubleRange(); //System.out.println("["+range[0][0]+"/"+range[0][1]+";"+range[1][0]+"/"+range[1][1]+"]"); @@ -192,26 +200,33 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES SBX crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The SBX crossover simulates a binary crossover (works only for two partners!)."; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param a The number of crossovers. + * + * @param a The number of crossovers. */ public void setEta(double a) { if (a < 0) { @@ -219,9 +234,11 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable } this.m_Eta = a; } + public double getEta() { return this.m_Eta; } + public String etaTipText() { return "Set the Eta_c value (the larger the value, the more restricted the search)."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverESSPX.java b/src/eva2/optimization/operator/crossover/CrossoverESSPX.java index 87d4a7bf..5c53145f 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESSPX.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESSPX.java @@ -19,17 +19,21 @@ import eva2.tools.math.RNG; */ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private double m_Epsilon = 1.2; + private InterfaceOptimizationProblem m_OptimizationProblem; + private double m_Epsilon = 1.2; public CrossoverESSPX() { } + public CrossoverESSPX(CrossoverESSPX c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; - this.m_Epsilon = c.m_Epsilon; + this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_Epsilon = c.m_Epsilon; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -37,37 +41,39 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable return new CrossoverESSPX(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceESIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - double intermediate; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + double intermediate; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } - double r; - double[] g = Mathematics.meanVect(parents); - double[][] Y = new double[parents.length][], C; + double r; + double[] g = Mathematics.meanVect(parents); + double[][] Y = new double[parents.length][], C; // calculate the Y vectors for (int i = 0; i < parents.length; i++) { @@ -79,19 +85,19 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable C = new double[Y.length][]; C[0] = Mathematics.zeroes(parents[0].length); for (int j = 1; j < Y.length; j++) { - r = Math.pow(RNG.randomDouble(0, 1), 1/((double)j)); - C[j] = Mathematics.vvAdd(Y[j-1], C[j-1]); - C[j] = Mathematics.vvSub(C[j], Y[j]); - C[j] = Mathematics.svMult(r, C[j]); + r = Math.pow(RNG.randomDouble(0, 1), 1 / ((double) j)); + C[j] = Mathematics.vvAdd(Y[j - 1], C[j - 1]); + C[j] = Mathematics.vvSub(C[j], Y[j]); + C[j] = Mathematics.svMult(r, C[j]); //C[j] = this.scalarMultVector(r, this.subVector(Y[j-1], this.addVector(Y[j], C[j-1]))); } // now the children results from - children[i] = Mathematics.vvAdd(Y[Y.length-1], C[C.length-1]); + children[i] = Mathematics.vvAdd(Y[Y.length - 1], C[C.length - 1]); } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -103,26 +109,29 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESSPX) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -130,13 +139,13 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable } public static void main(String[] args) { - boolean plotFlag = true; - Plot plot = null; - Population pop = new Population(); - double[] tmpD = new double[2]; - ESIndividualDoubleData indy1, indy2, indy3, indy4; - F1Problem prob = new F1Problem(); - int n = 2; + boolean plotFlag = true; + Plot plot = null; + Population pop = new Population(); + double[] tmpD = new double[2]; + ESIndividualDoubleData indy1, indy2, indy3, indy4; + F1Problem prob = new F1Problem(); + int n = 2; RNG.setRandomSeed(1); // init individual @@ -144,14 +153,14 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable double[][] range = new double[n][2]; for (int i = 0; i < range.length; i++) { range[i][0] = -2.0; - range[i][1] = 2.0; + range[i][1] = 2.0; } indy1.setDoubleDataLength(n); indy1.SetDoubleRange(range); // init values - indy2 = (ESIndividualDoubleData)indy1.clone(); - indy3 = (ESIndividualDoubleData)indy1.clone(); - indy4 = (ESIndividualDoubleData)indy1.clone(); + indy2 = (ESIndividualDoubleData) indy1.clone(); + indy3 = (ESIndividualDoubleData) indy1.clone(); + indy4 = (ESIndividualDoubleData) indy1.clone(); if (false) { // random init indy1.defaultInit(prob); @@ -163,18 +172,18 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable tmpD[0] = -1; tmpD[1] = -0.5; indy1.initByValue(tmpD, prob); - tmpD[0] = -0.5; - tmpD[1] = 0.5; + tmpD[0] = -0.5; + tmpD[1] = 0.5; indy2.initByValue(tmpD, prob); tmpD[0] = 0.5; - tmpD[1] = -1; + tmpD[1] = -1; indy3.initByValue(tmpD, prob); tmpD[0] = 0.5; - tmpD[1] = 1; + tmpD[1] = 1; indy4.initByValue(tmpD, prob); } // set the parents - pop= new Population(); + pop = new Population(); pop.add(indy2); pop.add(indy3); //pop.add(indy4); @@ -195,12 +204,12 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable plot.setUnconnectedPoint(2, 2, 0); } CrossoverESSPX cross = new CrossoverESSPX(); - cross.m_Epsilon = 1.2; + cross.m_Epsilon = 1.2; AbstractEAIndividual[] offsprings; for (int i = 0; i < 500; i++) { offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { - tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); + tmpD = ((ESIndividualDoubleData) offsprings[j]).getDoubleData(); if (plotFlag) { plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); } @@ -215,17 +224,22 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES SPX crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -238,9 +252,11 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable } this.m_Epsilon = a; } + public double getEpsilon() { return this.m_Epsilon; } + public String epsilonTipText() { return "The epsilon of SPX."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverESUNDX.java b/src/eva2/optimization/operator/crossover/CrossoverESUNDX.java index a77eb221..afae7d92 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESUNDX.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESUNDX.java @@ -10,46 +10,50 @@ import eva2.optimization.problems.F1Problem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.util.ArrayList; /** * This is the Unimodal Normal Distribution Crossover by Ono and Kobayashi, 1997. Cf.: - * - * @INPROCEEDINGS{Ono1997, - * author = {Ono, Isao and Kobayashi, Shigenobu}, - * title = {{A Real Coded Genetic Algorithm for Function Optimization Using Unimodal Normal Distributed Crossover}}, - * booktitle = {ICGA}, - * year = {1997}, - * pages = {246--253}, - * abstract = {This paper presents a new genetic algorithm for function optimization. - * In function optimization, it is said to be difficult to optimize - * functions that have strong epistasis among parameters. This is because - * many of the conventional genetic algorithms work without adapting - * to the landscape of functions. In this paper, we employ the real - * number vector representation and propose a new crossover named the - * unimodal normal distribution crossover (UNDX), considering epistasis - * among parameters. The UNDX can optimize functions efficiently by - * adapting the distribution of children to the landscape of functions. - * By applying the proposed method to several benchmark problems, we - * show its effectiveness.}, - * url = {http://garage.cse.msu.edu/icga97/Abstracts.html#092} - * } + * + * @INPROCEEDINGS{Ono1997, author = {Ono, Isao and Kobayashi, Shigenobu}, + * title = {{A Real Coded Genetic Algorithm for Function Optimization Using Unimodal Normal Distributed Crossover}}, + * booktitle = {ICGA}, + * year = {1997}, + * pages = {246--253}, + * abstract = {This paper presents a new genetic algorithm for function optimization. + * In function optimization, it is said to be difficult to optimize + * functions that have strong epistasis among parameters. This is because + * many of the conventional genetic algorithms work without adapting + * to the landscape of functions. In this paper, we employ the real + * number vector representation and propose a new crossover named the + * unimodal normal distribution crossover (UNDX), considering epistasis + * among parameters. The UNDX can optimize functions efficiently by + * adapting the distribution of children to the landscape of functions. + * By applying the proposed method to several benchmark problems, we + * show its effectiveness.}, + * url = {http://garage.cse.msu.edu/icga97/Abstracts.html#092} + * } */ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private double m_Eta = 0.2; - private double m_Zeta = 0.2; + private InterfaceOptimizationProblem m_OptimizationProblem; + private double m_Eta = 0.2; + private double m_Zeta = 0.2; public CrossoverESUNDX() { } + public CrossoverESUNDX(CrossoverESUNDX c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; - this.m_Eta = c.m_Eta; - this.m_Zeta = c.m_Zeta; + this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_Eta = c.m_Eta; + this.m_Zeta = c.m_Zeta; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -57,42 +61,44 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable return new CrossoverESUNDX(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceESIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - double intermediate; - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + double intermediate; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } - double[][] nParents = new double[parents.length-1][]; + double[][] nParents = new double[parents.length - 1][]; for (int i = 1; i < parents.length; i++) { - nParents[i-1] = parents[i]; + nParents[i - 1] = parents[i]; } double[] g = Mathematics.meanVect(nParents), tmpD; double w, v; - ArrayList givenCoordinates = this.getGivenCoordinates(g, nParents); - ArrayList missingCorrdinates = this.getMissingCoordinates(g, parents[0], givenCoordinates); + ArrayList givenCoordinates = this.getGivenCoordinates(g, nParents); + ArrayList missingCorrdinates = this.getMissingCoordinates(g, parents[0], givenCoordinates); // now determine the offsprings for (int i = 0; i < children.length; i++) { @@ -102,13 +108,13 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable } // then the given coordinates for (int j = 0; j < givenCoordinates.size(); j++) { - tmpD = (double[])givenCoordinates.get(j); + tmpD = (double[]) givenCoordinates.get(j); w = RNG.gaussianDouble(this.m_Zeta); children[i] = Mathematics.vvAdd(children[i], Mathematics.svMult(w, tmpD)); } // now the missing stuff for (int j = 0; j < missingCorrdinates.size(); j++) { - tmpD = (double[])missingCorrdinates.get(j); + tmpD = (double[]) missingCorrdinates.get(j); w = RNG.gaussianDouble(this.m_Eta); children[i] = Mathematics.vvAdd(children[i], Mathematics.svMult(w, tmpD)); } @@ -116,7 +122,7 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -128,9 +134,9 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable } private ArrayList getGivenCoordinates(double[] mean, double[][] parents) { - ArrayList result = new ArrayList(); - double[] tmpVec, toro; - double tmpD; + ArrayList result = new ArrayList(); + double[] tmpVec, toro; + double tmpD; for (int i = 0; i < parents.length; i++) { tmpVec = Mathematics.vvSub(parents[i], mean); @@ -141,7 +147,7 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable // apply the infamous Gram-Schmidt for (int j = 0; j < result.size(); j++) { toro = (double[]) result.get(j); - tmpD = Mathematics.vvMult(toro, tmpVec)/Mathematics.vvMult(toro, toro); + tmpD = Mathematics.vvMult(toro, tmpVec) / Mathematics.vvMult(toro, toro); toro = Mathematics.svMult(tmpD, toro); tmpVec = Mathematics.vvSub(tmpVec, toro); } @@ -156,9 +162,9 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable } private ArrayList getMissingCoordinates(double[] mean, double[] theOther, ArrayList given) { - ArrayList result = new ArrayList(), completeList; - double[] tmpVec, toro; - double tmpD; + ArrayList result = new ArrayList(), completeList; + double[] tmpVec, toro; + double tmpD; completeList = new ArrayList(); for (int i = 0; i < given.size(); i++) { @@ -171,7 +177,7 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable // apply the infamous Gram-Schmidt for (int j = 0; j < completeList.size(); j++) { toro = (double[]) completeList.get(j); - tmpD = Mathematics.vvMult(toro, tmpVec)/Mathematics.vvMult(toro, toro); + tmpD = Mathematics.vvMult(toro, tmpVec) / Mathematics.vvMult(toro, toro); toro = Mathematics.svMult(tmpD, toro); tmpVec = Mathematics.vvSub(tmpVec, toro); } @@ -187,26 +193,29 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable return result; } - /** This method allows you to evaluate whether two crossover operators + /** + * This method allows you to evaluate whether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESUNDX) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -214,13 +223,13 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable } public static void main(String[] args) { - boolean plotFlag = true; - Plot plot = null; - Population pop = new Population(); - double[] tmpD = new double[2]; - ESIndividualDoubleData indy1, indy2, indy3, indy4; - F1Problem prob = new F1Problem(); - int n = 2; + boolean plotFlag = true; + Plot plot = null; + Population pop = new Population(); + double[] tmpD = new double[2]; + ESIndividualDoubleData indy1, indy2, indy3, indy4; + F1Problem prob = new F1Problem(); + int n = 2; RNG.setRandomSeed(1); // init individual @@ -228,14 +237,14 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable double[][] range = new double[n][2]; for (int i = 0; i < range.length; i++) { range[i][0] = -2.0; - range[i][1] = 2.0; + range[i][1] = 2.0; } indy1.setDoubleDataLength(n); indy1.SetDoubleRange(range); // init values - indy2 = (ESIndividualDoubleData)indy1.clone(); - indy3 = (ESIndividualDoubleData)indy1.clone(); - indy4 = (ESIndividualDoubleData)indy1.clone(); + indy2 = (ESIndividualDoubleData) indy1.clone(); + indy3 = (ESIndividualDoubleData) indy1.clone(); + indy4 = (ESIndividualDoubleData) indy1.clone(); if (false) { // random init indy1.defaultInit(prob); @@ -244,21 +253,21 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable indy4.defaultInit(prob); } else { // value init - tmpD[0] = -1.9; - tmpD[1] = -1.8; + tmpD[0] = -1.9; + tmpD[1] = -1.8; indy1.initByValue(tmpD, prob); - tmpD[0] = 1; - tmpD[1] = 1; + tmpD[0] = 1; + tmpD[1] = 1; indy2.initByValue(tmpD, prob); tmpD[0] = -1; tmpD[1] = -1; indy3.initByValue(tmpD, prob); tmpD[0] = 0.5; - tmpD[1] = 1; + tmpD[1] = 1; indy4.initByValue(tmpD, prob); } // set the parents - pop= new Population(); + pop = new Population(); pop.add(indy2); pop.add(indy3); //pop.add(indy4); @@ -279,13 +288,13 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable plot.setUnconnectedPoint(2, 2, 0); } CrossoverESUNDX cross = new CrossoverESUNDX(); - cross.m_Eta = 0.2; - cross.m_Zeta = 0.2; + cross.m_Eta = 0.2; + cross.m_Zeta = 0.2; AbstractEAIndividual[] offsprings; for (int i = 0; i < 500; i++) { offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { - tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); + tmpD = ((ESIndividualDoubleData) offsprings[j]).getDoubleData(); if (plotFlag) { plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); } @@ -300,43 +309,54 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable return this.getName(); } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES UNDX crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is the Unimodal Normally Distributed crossover (UNDX) by Ono and Kobayashi, 1997, typically uses more than two parents."; } + public void setEta(double a) { if (a < 0) { a = 0; } this.m_Eta = a; } + public double getEta() { return this.m_Eta; } + public String etaTipText() { return "The Eta of UNDX (=0,35/Math,sqrt(n-l-2))."; } + public void setZeta(double a) { if (a < 0) { a = 0; } this.m_Zeta = a; } + public double getZeta() { return this.m_Zeta; } + public String zetaTipText() { return "The Zeta of UNDX (=1/Math,sqrt(l-2))."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverESUniformDiscrete.java b/src/eva2/optimization/operator/crossover/CrossoverESUniformDiscrete.java index 0b45227e..eaf29f58 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverESUniformDiscrete.java +++ b/src/eva2/optimization/operator/crossover/CrossoverESUniformDiscrete.java @@ -14,16 +14,19 @@ import eva2.tools.math.RNG; * To change this template use Options | File Templates. */ public class CrossoverESUniformDiscrete implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverESUniformDiscrete() { } + public CrossoverESUniformDiscrete(CrossoverESUniformDiscrete c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given crossover operator + /** + * This method will enable you to clone a given crossover operator + * * @return The clone */ @Override @@ -31,47 +34,49 @@ public class CrossoverESUniformDiscrete implements InterfaceCrossover, java.io.S return new CrossoverESUniformDiscrete(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - double[][] parents, children; + AbstractEAIndividual[] result = null; + double[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceESIndividual) && (partners.get(0) instanceof InterfaceESIndividual)) { - int length = ((InterfaceESIndividual)result[0]).getDGenotype().length; - int mixer = RNG.randomInt(0, partners.size()); + int length = ((InterfaceESIndividual) result[0]).getDGenotype().length; + int mixer = RNG.randomInt(0, partners.size()); - parents = new double[partners.size()+1][]; - children = new double[partners.size()+1][]; + parents = new double[partners.size() + 1][]; + children = new double[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new double[((InterfaceESIndividual)result[i]).getDGenotype().length]; + parents[i] = new double[((InterfaceESIndividual) result[i]).getDGenotype().length]; children[i] = new double[parents[i].length]; - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceESIndividual)result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceESIndividual) result[i]).getDGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < length; i++) { - mixer = RNG.randomInt(0, children.length-1); + mixer = RNG.randomInt(0, children.length - 1); for (int j = 0; j < children.length; j++) { - children[j][i] = parents[(j + mixer) % parents.length][i]; + children[j][i] = parents[(j + mixer) % parents.length][i]; } } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceESIndividual)result[i]).SetDGenotype(children[i]); + ((InterfaceESIndividual) result[i]).SetDGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -82,26 +87,29 @@ public class CrossoverESUniformDiscrete implements InterfaceCrossover, java.io.S return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESUniformDiscrete) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -111,19 +119,24 @@ public class CrossoverESUniformDiscrete implements InterfaceCrossover, java.io.S @Override public String getStringRepresentation() { return this.getName(); - } + } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES discrete n-point crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverGABitSimulated.java b/src/eva2/optimization/operator/crossover/CrossoverGABitSimulated.java index 4db6f391..27b6de75 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGABitSimulated.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGABitSimulated.java @@ -6,6 +6,7 @@ import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** @@ -16,15 +17,19 @@ import java.util.BitSet; * To change this template use Options | File Templates. */ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverGABitSimulated() { } + public CrossoverGABitSimulated(CrossoverGABitSimulated c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -32,34 +37,36 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri return new CrossoverGABitSimulated(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; + result = new AbstractEAIndividual[partners.size() + 1]; result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } if (partners.size() == 0) { return result; } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceGAIndividual) && (partners.get(0) instanceof InterfaceGAIndividual)) { - int length = ((InterfaceGAIndividual)indy1).getGenotypeLength(); - double current; - BitSet[][] tmpBitSet = new BitSet[2][partners.size()+1]; + int length = ((InterfaceGAIndividual) indy1).getGenotypeLength(); + double current; + BitSet[][] tmpBitSet = new BitSet[2][partners.size() + 1]; - tmpBitSet[0][0] = ((InterfaceGAIndividual)indy1).getBGenotype(); - tmpBitSet[1][0] = ((InterfaceGAIndividual)result[0]).getBGenotype(); + tmpBitSet[0][0] = ((InterfaceGAIndividual) indy1).getBGenotype(); + tmpBitSet[1][0] = ((InterfaceGAIndividual) result[0]).getBGenotype(); for (int i = 0; i < partners.size(); i++) { - tmpBitSet[0][i+1] = ((InterfaceGAIndividual)partners.get(i)).getBGenotype(); - tmpBitSet[1][i+1] = ((InterfaceGAIndividual)result[i+1]).getBGenotype(); - length = Math.max(length, ((InterfaceGAIndividual)partners.get(i)).getGenotypeLength()); + tmpBitSet[0][i + 1] = ((InterfaceGAIndividual) partners.get(i)).getBGenotype(); + tmpBitSet[1][i + 1] = ((InterfaceGAIndividual) result[i + 1]).getBGenotype(); + length = Math.max(length, ((InterfaceGAIndividual) partners.get(i)).getGenotypeLength()); } for (int i = 0; i < length; i++) { @@ -69,19 +76,18 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri current++; } } - current /= (double)(tmpBitSet[0].length); + current /= (double) (tmpBitSet[0].length); for (int j = 0; j < tmpBitSet[0].length; j++) { if (RNG.flipCoin(current)) { tmpBitSet[1][j].set(i); - } - else { + } else { tmpBitSet[1][j].clear(i); } } } for (int i = 0; i < result.length; i++) { - ((InterfaceGAIndividual)result[i]).SetBGenotype(tmpBitSet[1][i]); + ((InterfaceGAIndividual) result[i]).SetBGenotype(tmpBitSet[1][i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -92,26 +98,29 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverGABitSimulated) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -121,19 +130,24 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri @Override public String getStringRepresentation() { return this.getName(); - } + } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GA bit simulated crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverGADefault.java b/src/eva2/optimization/operator/crossover/CrossoverGADefault.java index 7425be1d..647b225f 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGADefault.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGADefault.java @@ -6,162 +6,154 @@ import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** * This operator performs one-point crossover. - * + *

* Created by IntelliJ IDEA. User: streiche Date: 03.04.2003 Time: 10:34:17 To * change this template use Options | File Templates. */ public class CrossoverGADefault implements InterfaceCrossover, - java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + java.io.Serializable { + private InterfaceOptimizationProblem m_OptimizationProblem; - public CrossoverGADefault() { + public CrossoverGADefault() { - } + } - public CrossoverGADefault(CrossoverGADefault c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; - } + public CrossoverGADefault(CrossoverGADefault c) { + this.m_OptimizationProblem = c.m_OptimizationProblem; + } - /** - * This method will enable you to clone a given mutation operator - * - * @return The clone - */ + /** + * This method will enable you to clone a given mutation operator + * + * @return The clone + */ @Override - public Object clone() { - return new CrossoverGADefault(this); - } + public Object clone() { + return new CrossoverGADefault(this); + } - /** - * This method performs crossover on two individuals. If the individuals do - * not implement InterfaceGAIndividual, then nothing will happen. - * - * @param indy1 - * The first individual - * @param partners - * The second individual - */ + /** + * This method performs crossover on two individuals. If the individuals do + * not implement InterfaceGAIndividual, then nothing will happen. + * + * @param indy1 The first individual + * @param partners The second individual + */ @Override - public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, - Population partners) { - AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size() + 1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); - for (int i = 0; i < partners.size(); i++) { + public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, + Population partners) { + AbstractEAIndividual[] result = null; + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); + for (int i = 0; i < partners.size(); i++) { result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners - .get(i)).clone(); + .get(i)).clone(); } - // for (int i = 0; i < result.length; i++) System.out.println("Before - // Crossover: " +result[i].getSolutionRepresentationFor()); - if (partners.size() == 0) { - return result; + // for (int i = 0; i < result.length; i++) System.out.println("Before + // Crossover: " +result[i].getSolutionRepresentationFor()); + if (partners.size() == 0) { + return result; + } + if ((indy1 instanceof InterfaceGAIndividual) + && (partners.get(0) instanceof InterfaceGAIndividual)) { + // Currently we will only handle two parents + int crossoverpoint = RNG.randomInt(0, + ((InterfaceGAIndividual) indy1).getGenotypeLength() - 1); + boolean tmpValue; + BitSet[] tmpBitSets = new BitSet[2]; + tmpBitSets[0] = ((InterfaceGAIndividual) result[0]).getBGenotype(); + tmpBitSets[1] = ((InterfaceGAIndividual) result[1]).getBGenotype(); + for (int i = crossoverpoint; i < ((InterfaceGAIndividual) result[0]) + .getGenotypeLength(); i++) { + if (tmpBitSets[0].get(i)) { + tmpValue = true; + } else { + tmpValue = false; } - if ((indy1 instanceof InterfaceGAIndividual) - && (partners.get(0) instanceof InterfaceGAIndividual)) { - // Currently we will only handle two parents - int crossoverpoint = RNG.randomInt(0, - ((InterfaceGAIndividual) indy1).getGenotypeLength() - 1); - boolean tmpValue; - BitSet[] tmpBitSets = new BitSet[2]; - tmpBitSets[0] = ((InterfaceGAIndividual) result[0]).getBGenotype(); - tmpBitSets[1] = ((InterfaceGAIndividual) result[1]).getBGenotype(); - for (int i = crossoverpoint; i < ((InterfaceGAIndividual) result[0]) - .getGenotypeLength(); i++) { - if (tmpBitSets[0].get(i)) { - tmpValue = true; - } - else { - tmpValue = false; - } - if (tmpBitSets[1].get(i)) { - tmpBitSets[0].set(i); - } - else { - tmpBitSets[0].clear(i); - } - if (tmpValue) { - tmpBitSets[1].set(i); - } - else { - tmpBitSets[1].clear(i); - } - } - ((InterfaceGAIndividual) result[0]).SetBGenotype(tmpBitSets[0]); - ((InterfaceGAIndividual) result[1]).SetBGenotype(tmpBitSets[1]); - } - // in case the crossover was successfull lets give the mutation operators a - // chance to mate the strategy parameters - for (int i = 0; i < result.length; i++) { - result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, - partners); + if (tmpBitSets[1].get(i)) { + tmpBitSets[0].set(i); + } else { + tmpBitSets[0].clear(i); + } + if (tmpValue) { + tmpBitSets[1].set(i); + } else { + tmpBitSets[1].clear(i); + } + } + ((InterfaceGAIndividual) result[0]).SetBGenotype(tmpBitSets[0]); + ((InterfaceGAIndividual) result[1]).SetBGenotype(tmpBitSets[1]); } - // for (int i = 0; i < result.length; i++) System.out.println("After - // Crossover: " +result[i].getSolutionRepresentationFor()); - return result; - } + // in case the crossover was successfull lets give the mutation operators a + // chance to mate the strategy parameters + for (int i = 0; i < result.length; i++) { + result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, + partners); + } + // for (int i = 0; i < result.length; i++) System.out.println("After + // Crossover: " +result[i].getSolutionRepresentationFor()); + return result; + } - /** - * This method allows you to evaluate weather two crossover operators are - * actually the same. - * - * @param crossover - * The other crossover operator - */ + /** + * This method allows you to evaluate weather two crossover operators are + * actually the same. + * + * @param crossover The other crossover operator + */ @Override - public boolean equals(Object crossover) { - if (crossover instanceof CrossoverGADefault) { - return true; - } - else { - return false; - } - } + public boolean equals(Object crossover) { + if (crossover instanceof CrossoverGADefault) { + return true; + } else { + return false; + } + } - /** - * This method will allow the crossover operator to be initialized depending - * on the individual and the optimization problem. The optimization problem is - * to be stored since it is to be called during crossover to calculate the - * exogene parameters for the offsprings. - * - * @param individual - * The individual that will be mutated. - * @param opt - * The optimization problem. - */ + /** + * This method will allow the crossover operator to be initialized depending + * on the individual and the optimization problem. The optimization problem is + * to be stored since it is to be called during crossover to calculate the + * exogene parameters for the offsprings. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. + */ @Override - public void init(AbstractEAIndividual individual, - InterfaceOptimizationProblem opt) { - this.m_OptimizationProblem = opt; - } + public void init(AbstractEAIndividual individual, + InterfaceOptimizationProblem opt) { + this.m_OptimizationProblem = opt; + } @Override - public String getStringRepresentation() { - return this.getName(); - } + public String getStringRepresentation() { + return this.getName(); + } - /***************************************************************************** - * These are for GUI - */ - /** - * This method allows the CommonJavaObjectEditorPanel to read the name to the - * current object. - * - * @return The name. - */ - public String getName() { - return "GA default crossover"; - } + /***************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the name to the + * current object. + * + * @return The name. + */ + public String getName() { + return "GA default crossover"; + } - /** - * This method returns a global info string - * - * @return description - */ - public static String globalInfo() { - return "This is a one-point crossover between two individuals."; - } + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "This is a one-point crossover between two individuals."; + } } diff --git a/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java b/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java index cb78117a..13d2e5c4 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java @@ -8,88 +8,91 @@ import eva2.optimization.individuals.InterfaceGIIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** * The famous n-point crossover operator on a binary and integer genotype. Genotypes of * parent individuals are recombined by exchanging subsegments within randomly * selected points. Therefore, far-away allels (larger GA schemas) are more likely to be split - * between individuals. - * + * between individuals. + * * @author mkron, streiche */ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializable { -// private InterfaceOptimizationProblem m_OptimizationProblem; - private int m_NumberOfCrossovers = 3; - private static boolean TRACE=false; - + // private InterfaceOptimizationProblem m_OptimizationProblem; + private int m_NumberOfCrossovers = 3; + private static boolean TRACE = false; + public CrossoverGAGINPoint() { } - + public CrossoverGAGINPoint(int nPoints) { - this(); - setNumberOfCrossovers(nPoints); - } - - public CrossoverGAGINPoint(CrossoverGAGINPoint mutator) { -// this.m_OptimizationProblem = mutator.m_OptimizationProblem; - this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; + this(); + setNumberOfCrossovers(nPoints); } - /** This method will enable you to clone a given crossover operator + public CrossoverGAGINPoint(CrossoverGAGINPoint mutator) { +// this.m_OptimizationProblem = mutator.m_OptimizationProblem; + this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; + } + + /** + * This method will enable you to clone a given crossover operator + * * @return The clone */ @Override public Object clone() { return new CrossoverGAGINPoint(this); } - + protected Object getGenotype(AbstractEAIndividual individual) { - Object genotype=null; - if (individual instanceof InterfaceGAIndividual) { - genotype = ((InterfaceGAIndividual)individual).getBGenotype(); - } else { - genotype = ((InterfaceGIIndividual)individual).getIGenotype(); - } - return genotype; + Object genotype = null; + if (individual instanceof InterfaceGAIndividual) { + genotype = ((InterfaceGAIndividual) individual).getBGenotype(); + } else { + genotype = ((InterfaceGIIndividual) individual).getIGenotype(); + } + return genotype; } @Override public AbstractEAIndividual[] mate(AbstractEAIndividual individual, Population partners) { AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; + result = new AbstractEAIndividual[partners.size() + 1]; result[0] = (AbstractEAIndividual) (individual).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } if (partners.size() == 0) { return result; } - - if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { - int length = getGenotypeLength(individual); + + if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { + int length = getGenotypeLength(individual); // Object[][] tmpGenotypes = new Object[2][partners.size()+1]; - Object[] origGenotypes = new Object[partners.size()+1]; - Object[] newGenotypes = new Object[partners.size()+1]; - + Object[] origGenotypes = new Object[partners.size() + 1]; + Object[] newGenotypes = new Object[partners.size() + 1]; + origGenotypes[0] = getGenotype(individual); newGenotypes[0] = getGenotype(result[0]); - + for (int i = 0; i < partners.size(); i++) { // clone all individuals - origGenotypes[i+1] = getGenotype(partners.getEAIndividual(i)); - newGenotypes[i+1] = getGenotype(result[i+1]); + origGenotypes[i + 1] = getGenotype(partners.getEAIndividual(i)); + newGenotypes[i + 1] = getGenotype(result[i + 1]); length = Math.max(length, getGenotypeLength(partners.getEAIndividual(i))); } if (TRACE) { - System.out.println("Before CO: " + BeanInspector.toString(newGenotypes)); - } - int mixer = RNG.randomInt(0, partners.size()); // partner index with which to exchange genes - int[] crossoverPoints=getCrossoverPoints(length, m_NumberOfCrossovers); + System.out.println("Before CO: " + BeanInspector.toString(newGenotypes)); + } + int mixer = RNG.randomInt(0, partners.size()); // partner index with which to exchange genes + int[] crossoverPoints = getCrossoverPoints(length, m_NumberOfCrossovers); if (TRACE) { - System.out.println("CO points: " + BeanInspector.toString(crossoverPoints)); - } + System.out.println("CO points: " + BeanInspector.toString(crossoverPoints)); + } for (int i = 0; i < length; i++) { // loop positions for (int j = 0; j < this.m_NumberOfCrossovers; j++) { if (i == crossoverPoints[j]) { @@ -97,59 +100,59 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ } // possibly switch partner to exchange with } for (int j = 0; j < origGenotypes.length; j++) { // loop individuals - // exchange values at position i between indies - exchangePos(origGenotypes, newGenotypes, (j+mixer) % origGenotypes.length, j, i); + // exchange values at position i between indies + exchangePos(origGenotypes, newGenotypes, (j + mixer) % origGenotypes.length, j, i); } } for (int i = 0; i < result.length; i++) { - writeBack(result[i], newGenotypes[i]); + writeBack(result[i], newGenotypes[i]); } if (TRACE) { - System.out.println("After CO: " + BeanInspector.toString(newGenotypes)); - } - } - return result; + System.out.println("After CO: " + BeanInspector.toString(newGenotypes)); + } + } + return result; } private void writeBack(AbstractEAIndividual indy, - Object newGenotype) { - if (indy instanceof InterfaceGAIndividual) { - ((InterfaceGAIndividual)indy).SetBGenotype((BitSet)newGenotype); - } else { - ((InterfaceGIIndividual)indy).SetIGenotype((int[])newGenotype); - } - } - - protected void exchangePos(Object[] origGenotypes, Object[] newGenotypes, int a, int b, int position) { - setVal(newGenotypes[a], position, getVal(origGenotypes[b], position)); - setVal(newGenotypes[b], position, getVal(origGenotypes[a], position)); - + Object newGenotype) { + if (indy instanceof InterfaceGAIndividual) { + ((InterfaceGAIndividual) indy).SetBGenotype((BitSet) newGenotype); + } else { + ((InterfaceGIIndividual) indy).SetIGenotype((int[]) newGenotype); + } } - + + protected void exchangePos(Object[] origGenotypes, Object[] newGenotypes, int a, int b, int position) { + setVal(newGenotypes[a], position, getVal(origGenotypes[b], position)); + setVal(newGenotypes[b], position, getVal(origGenotypes[a], position)); + + } + private void setVal(Object genotype, int position, Object val) { - if (genotype instanceof BitSet) { - ((BitSet)genotype).set(position, (Boolean)val); - } else { - ((int[])genotype)[position]=(Integer)val; - } - } + if (genotype instanceof BitSet) { + ((BitSet) genotype).set(position, (Boolean) val); + } else { + ((int[]) genotype)[position] = (Integer) val; + } + } - private Object getVal(Object genotype, int position) { - if (genotype instanceof BitSet) { - return ((BitSet)genotype).get(position); - } else { - return ((int[])genotype)[position]; - } - } + private Object getVal(Object genotype, int position) { + if (genotype instanceof BitSet) { + return ((BitSet) genotype).get(position); + } else { + return ((int[]) genotype)[position]; + } + } - protected int getGenotypeLength(AbstractEAIndividual individual) { - if (individual instanceof InterfaceGAIndividual) { - return ((InterfaceGAIndividual)individual).getGenotypeLength(); - } else { - return((InterfaceGIIndividual)individual).getGenotypeLength(); - } - } + protected int getGenotypeLength(AbstractEAIndividual individual) { + if (individual instanceof InterfaceGAIndividual) { + return ((InterfaceGAIndividual) individual).getGenotypeLength(); + } else { + return ((InterfaceGIIndividual) individual).getGenotypeLength(); + } + } // /** This method performs crossover on multiple individuals. If the individuals do // * not implement InterfaceGAIndividual, then nothing will happen. @@ -204,26 +207,29 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ /** * Select the crossover points within the genotype of given length. + * * @param length * @param numberOfCrossovers * @return */ protected int[] getCrossoverPoints(int length, int numberOfCrossovers) { - int[] crossoverPoints = new int[numberOfCrossovers]; + int[] crossoverPoints = new int[numberOfCrossovers]; for (int i = 0; i < numberOfCrossovers; i++) { - crossoverPoints[i] = RNG.randomInt(0, length-1); + crossoverPoints[i] = RNG.randomInt(0, length - 1); } - return crossoverPoints; - } + return crossoverPoints; + } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverGAGINPoint) { - CrossoverGAGINPoint cross = (CrossoverGAGINPoint)crossover; + CrossoverGAGINPoint cross = (CrossoverGAGINPoint) crossover; if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { return false; } @@ -233,12 +239,14 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -248,28 +256,35 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ @Override public String getStringRepresentation() { return this.getName(); - } + } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GA-GI N-Point Crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is an n-point crossover between m individuals which may be binary or integer based."; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param crossovers The number of crossovers. + * + * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { if (crossovers < 0) { @@ -277,9 +292,11 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ } this.m_NumberOfCrossovers = crossovers; } + public int getNumberOfCrossovers() { return this.m_NumberOfCrossovers; } + public String numberOfCrossoversTipText() { return "The number of crossoverpoints."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverGAGINPointSegmentwise.java b/src/eva2/optimization/operator/crossover/CrossoverGAGINPointSegmentwise.java index de93a98a..56111d3a 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGAGINPointSegmentwise.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGAGINPointSegmentwise.java @@ -6,69 +6,70 @@ import eva2.tools.math.RNG; * A variation of the GA n-point crossover. Restricts crossover to segment bounds * of fixed length, so crossings occur at multiples of the segment length only. Segments * will not be destroyed. - * - * @author mkron * + * @author mkron */ public class CrossoverGAGINPointSegmentwise extends CrossoverGAGINPoint { - int segmentLength=8; - - public CrossoverGAGINPointSegmentwise() { - super(); - } - - public CrossoverGAGINPointSegmentwise(CrossoverGAGINPointSegmentwise o) { - super(o); - this.segmentLength=o.segmentLength; - } - - public CrossoverGAGINPointSegmentwise(int nPoints, int segmentLen) { - super(nPoints); - setSegmentLength(segmentLen); + int segmentLength = 8; + + public CrossoverGAGINPointSegmentwise() { + super(); } - - @Override - public Object clone() { - return new CrossoverGAGINPointSegmentwise(this); - } - - @Override - public boolean equals(Object crossover) { - if (super.equals(crossover) && (crossover instanceof CrossoverGAGINPointSegmentwise)) { - return ((CrossoverGAGINPointSegmentwise)crossover).segmentLength==this.segmentLength; - } else { - return false; - } - } - @Override - protected int[] getCrossoverPoints(int length, int numberOfCrossovers) { - int[] cPoints = new int[numberOfCrossovers]; - int i=0; - while (i * User: mkron, streiche * Date: 18.05.2005 * Time: 17:10:28 @@ -16,15 +16,19 @@ import eva2.tools.math.RNG; */ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverGIDefault() { } + public CrossoverGIDefault(CrossoverGIDefault c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -32,57 +36,59 @@ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializa return new CrossoverGIDefault(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - int[][] parents, children; + AbstractEAIndividual[] result = null; + int[][] parents, children; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceGIIndividual) && (partners.get(0) instanceof InterfaceGIIndividual)) { - if (((InterfaceGIIndividual)indy1).getIGenotype().length <= 1) { + if (((InterfaceGIIndividual) indy1).getIGenotype().length <= 1) { return result; } - int crossoverpoint = RNG.randomInt(0,((InterfaceGIIndividual)indy1).getIGenotype().length-1); + int crossoverpoint = RNG.randomInt(0, ((InterfaceGIIndividual) indy1).getIGenotype().length - 1); boolean switcher = RNG.randomBoolean(); - parents = new int[partners.size()+1][]; - children = new int[partners.size()+1][]; + parents = new int[partners.size() + 1][]; + children = new int[partners.size() + 1][]; for (int i = 0; i < result.length; i++) { - parents[i] = new int[((InterfaceGIIndividual)result[i]).getIGenotype().length]; + parents[i] = new int[((InterfaceGIIndividual) result[i]).getIGenotype().length]; children[i] = new int[parents[i].length]; - System.arraycopy(((InterfaceGIIndividual)result[i]).getIGenotype(), 0, parents[i], 0, parents[i].length); - System.arraycopy(((InterfaceGIIndividual)result[i]).getIGenotype(), 0, children[i], 0, parents[i].length); + System.arraycopy(((InterfaceGIIndividual) result[i]).getIGenotype(), 0, parents[i], 0, parents[i].length); + System.arraycopy(((InterfaceGIIndividual) result[i]).getIGenotype(), 0, children[i], 0, parents[i].length); } for (int i = 0; i < children[0].length; i++) { - if ((i < crossoverpoint)^(switcher)) { + if ((i < crossoverpoint) ^ (switcher)) { // do nothing } else { // exchange - for (int j = 0; j < children.length-1; j++) { - if ((i < children[j].length) && (i < parents[j+1].length)) { - children[j][i] = parents[j+1][i]; + for (int j = 0; j < children.length - 1; j++) { + if ((i < children[j].length) && (i < parents[j + 1].length)) { + children[j][i] = parents[j + 1][i]; } } - if ((i < children[children.length-1].length) && (i < parents[0].length)) { - children[children.length-1][i] = parents[0][i]; + if ((i < children[children.length - 1].length) && (i < parents[0].length)) { + children[children.length - 1][i] = parents[0][i]; } } } // write the result back for (int i = 0; i < result.length; i++) { - ((InterfaceGIIndividual)result[i]).SetIGenotype(children[i]); + ((InterfaceGIIndividual) result[i]).SetIGenotype(children[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -93,26 +99,29 @@ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializa return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverESDefault) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -123,18 +132,23 @@ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializa public String getStringRepresentation() { return this.getName(); } - - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the + + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI discrete one-point crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverGINPoint.java b/src/eva2/optimization/operator/crossover/CrossoverGINPoint.java index ab7f9557..54d1a072 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGINPoint.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGINPoint.java @@ -14,18 +14,21 @@ import eva2.tools.math.RNG; * To change this template use File | Settings | File Templates. */ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private int m_NumberOfCrossovers = 3; + private InterfaceOptimizationProblem m_OptimizationProblem; + private int m_NumberOfCrossovers = 3; public CrossoverGINPoint() { } + public CrossoverGINPoint(CrossoverGINPoint mutator) { - this.m_OptimizationProblem = mutator.m_OptimizationProblem; - this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; + this.m_OptimizationProblem = mutator.m_OptimizationProblem; + this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; } - /** This method will enable you to clone a given crossover operator + /** + * This method will enable you to clone a given crossover operator + * * @return The clone */ @Override @@ -33,40 +36,42 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab return new CrossoverGINPoint(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; + result = new AbstractEAIndividual[partners.size() + 1]; result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } if (partners.size() == 0) { return result; } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceGIIndividual) && (partners.get(0) instanceof InterfaceGIIndividual)) { - int length = ((InterfaceGIIndividual)indy1).getGenotypeLength(); - int mixer = RNG.randomInt(0, partners.size()); - int[] crossoverPoints = new int[this.m_NumberOfCrossovers]; - int[][][] tmpInts = new int[2][partners.size()+1][]; + int length = ((InterfaceGIIndividual) indy1).getGenotypeLength(); + int mixer = RNG.randomInt(0, partners.size()); + int[] crossoverPoints = new int[this.m_NumberOfCrossovers]; + int[][][] tmpInts = new int[2][partners.size() + 1][]; - tmpInts[0][0] = ((InterfaceGIIndividual)indy1).getIGenotype(); - tmpInts[1][0] = ((InterfaceGIIndividual)result[0]).getIGenotype(); + tmpInts[0][0] = ((InterfaceGIIndividual) indy1).getIGenotype(); + tmpInts[1][0] = ((InterfaceGIIndividual) result[0]).getIGenotype(); for (int i = 0; i < partners.size(); i++) { - length = Math.max(length, ((InterfaceGIIndividual)partners.get(i)).getGenotypeLength()); - tmpInts[0][i+1] = ((InterfaceGIIndividual)partners.get(i)).getIGenotype(); - tmpInts[1][i+1] = ((InterfaceGIIndividual)result[i+1]).getIGenotype(); - length = Math.max(length, ((InterfaceGIIndividual)partners.get(i)).getGenotypeLength()); + length = Math.max(length, ((InterfaceGIIndividual) partners.get(i)).getGenotypeLength()); + tmpInts[0][i + 1] = ((InterfaceGIIndividual) partners.get(i)).getIGenotype(); + tmpInts[1][i + 1] = ((InterfaceGIIndividual) result[i + 1]).getIGenotype(); + length = Math.max(length, ((InterfaceGIIndividual) partners.get(i)).getGenotypeLength()); } for (int i = 0; i < this.m_NumberOfCrossovers; i++) { - crossoverPoints[i] = RNG.randomInt(0, length-1); + crossoverPoints[i] = RNG.randomInt(0, length - 1); //System.out.println("crpoint: "+crossoverPoints[i]); } for (int i = 0; i < length; i++) { @@ -77,14 +82,14 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab } for (int j = 0; j < tmpInts[0].length; j++) { if ((tmpInts[0][(j + mixer) % tmpInts[0].length].length > i) && - (tmpInts[1][j].length > i)) { + (tmpInts[1][j].length > i)) { tmpInts[1][j][i] = tmpInts[0][(j + mixer) % tmpInts[0].length][i]; } } } for (int i = 0; i < result.length; i++) { - ((InterfaceGIIndividual)result[i]).SetIGenotype(tmpInts[1][i]); + ((InterfaceGIIndividual) result[i]).SetIGenotype(tmpInts[1][i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -95,14 +100,16 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverGINPoint) { - CrossoverGINPoint cross = (CrossoverGINPoint)crossover; + CrossoverGINPoint cross = (CrossoverGINPoint) crossover; if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { return false; } @@ -112,12 +119,14 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -132,23 +141,30 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI N-Point Crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is an n-point crossover between m individuals."; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param crossovers The number of crossovers. + * + * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { if (crossovers < 0) { @@ -156,9 +172,11 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab } this.m_NumberOfCrossovers = crossovers; } + public int getNumberOfCrossovers() { return this.m_NumberOfCrossovers; } + public String numberOfCrossoversTipText() { return "The number of crossoverpoints."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverGINPointVL.java b/src/eva2/optimization/operator/crossover/CrossoverGINPointVL.java index a0648ebd..07acf241 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGINPointVL.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGINPointVL.java @@ -5,6 +5,7 @@ import eva2.optimization.individuals.InterfaceGIIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** @@ -15,18 +16,21 @@ import java.util.BitSet; * To change this template use File | Settings | File Templates. */ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; - private int m_NumberOfCrossovers = 3; + private InterfaceOptimizationProblem m_OptimizationProblem; + private int m_NumberOfCrossovers = 3; public CrossoverGINPointVL() { } + public CrossoverGINPointVL(CrossoverGINPointVL mutator) { - this.m_OptimizationProblem = mutator.m_OptimizationProblem; - this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; + this.m_OptimizationProblem = mutator.m_OptimizationProblem; + this.m_NumberOfCrossovers = mutator.m_NumberOfCrossovers; } - /** This method will enable you to clone a given crossover operator + /** + * This method will enable you to clone a given crossover operator + * * @return The clone */ @Override @@ -34,60 +38,62 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ return new CrossoverGINPointVL(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; + result = new AbstractEAIndividual[partners.size() + 1]; result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } if (partners.size() == 0) { return result; } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceGIIndividual) && (partners.get(0) instanceof InterfaceGIIndividual)) { - int[] length = new int[partners.size()+1]; - int mixer = RNG.randomInt(0, partners.size()); - int[][] crossoverPoints = new int[length.length][this.m_NumberOfCrossovers]; - int[][] parents = new int[partners.size()+1][]; - int[][] offsprings = new int[partners.size()+1][]; + int[] length = new int[partners.size() + 1]; + int mixer = RNG.randomInt(0, partners.size()); + int[][] crossoverPoints = new int[length.length][this.m_NumberOfCrossovers]; + int[][] parents = new int[partners.size() + 1][]; + int[][] offsprings = new int[partners.size() + 1][]; - length[0] = ((InterfaceGIIndividual)indy1).getGenotypeLength(); - parents[0] = ((InterfaceGIIndividual)indy1).getIGenotype(); + length[0] = ((InterfaceGIIndividual) indy1).getGenotypeLength(); + parents[0] = ((InterfaceGIIndividual) indy1).getIGenotype(); for (int i = 0; i < partners.size(); i++) { - length[i+1] = ((InterfaceGIIndividual)partners.get(i)).getGenotypeLength(); - parents[i+1] = ((InterfaceGIIndividual)partners.get(i)).getIGenotype(); + length[i + 1] = ((InterfaceGIIndividual) partners.get(i)).getGenotypeLength(); + parents[i + 1] = ((InterfaceGIIndividual) partners.get(i)).getIGenotype(); } - int[][][] fragments = this.getNFragmentsFrom(parents); - int index, tmpLen; + int[][][] fragments = this.getNFragmentsFrom(parents); + int index, tmpLen; for (int i = 0; i < offsprings.length; i++) { - index = 0; - tmpLen = 0; + index = 0; + tmpLen = 0; for (int j = 0; j < this.m_NumberOfCrossovers; j++) { - tmpLen += fragments[(i+j)%fragments.length][index].length; + tmpLen += fragments[(i + j) % fragments.length][index].length; index++; } - offsprings[i] = new int[tmpLen]; - index = 0; - tmpLen = 0; + offsprings[i] = new int[tmpLen]; + index = 0; + tmpLen = 0; for (int j = 0; j < this.m_NumberOfCrossovers; j++) { - System.arraycopy(fragments[(i+j)%fragments.length][index], 0, offsprings[i], tmpLen, fragments[(i+j)%fragments.length][index].length); - tmpLen += fragments[(i+j)%fragments.length][index].length; + System.arraycopy(fragments[(i + j) % fragments.length][index], 0, offsprings[i], tmpLen, fragments[(i + j) % fragments.length][index].length); + tmpLen += fragments[(i + j) % fragments.length][index].length; index++; } } for (int i = 0; i < result.length; i++) { - ((InterfaceGIIndividual)result[i]).setIntegerDataLength(offsprings[i].length); - ((InterfaceGIIndividual)result[i]).SetIGenotype(offsprings[i]); + ((InterfaceGIIndividual) result[i]).setIntegerDataLength(offsprings[i].length); + ((InterfaceGIIndividual) result[i]).SetIGenotype(offsprings[i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -98,11 +104,11 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ return result; } - /** This method will return n fragments from the int arrays - * + /** + * This method will return n fragments from the int arrays */ private int[][][] getNFragmentsFrom(int[][] parents) { - int[][][] result = new int[parents.length][this.m_NumberOfCrossovers][]; + int[][][] result = new int[parents.length][this.m_NumberOfCrossovers][]; for (int i = 0; i < parents.length; i++) { // for each parents get n fragments @@ -112,11 +118,11 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ System.arraycopy(parents[i], 0, result[i][j], 0, parents[i].length); } } else { - int[] crossoverpoints = this.getCrossoverPoints(parents[i].length); - int lastPoint = 0; + int[] crossoverpoints = this.getCrossoverPoints(parents[i].length); + int lastPoint = 0; for (int j = 0; j < this.m_NumberOfCrossovers; j++) { - result[i][j] = new int[crossoverpoints[j]-lastPoint]; - System.arraycopy(parents[i], lastPoint, result[i][j], 0, crossoverpoints[j]-lastPoint); + result[i][j] = new int[crossoverpoints[j] - lastPoint]; + System.arraycopy(parents[i], lastPoint, result[i][j], 0, crossoverpoints[j] - lastPoint); lastPoint = crossoverpoints[j]; } } @@ -125,8 +131,10 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ return result; } - /** This method will return a number of n sorted crossover points - * @param length The length of the int array + /** + * This method will return a number of n sorted crossover points + * + * @param length The length of the int array * @return int[] the list of crossover points */ private int[] getCrossoverPoints(int length) { @@ -134,7 +142,7 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ BitSet bitset = new BitSet(length); while (bitset.cardinality() < this.m_NumberOfCrossovers) { - bitset.set(RNG.randomInt(1, length-2)); + bitset.set(RNG.randomInt(1, length - 2)); } int index = 0; for (int i = 0; i < length; i++) { @@ -147,14 +155,16 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverGINPointVL) { - CrossoverGINPointVL cross = (CrossoverGINPointVL)crossover; + CrossoverGINPointVL cross = (CrossoverGINPointVL) crossover; if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { return false; } @@ -164,12 +174,14 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -184,23 +196,30 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI var. length N-Point Crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a variable length n-point crossover between m individuals."; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param crossovers The number of crossovers. + * + * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { if (crossovers < 0) { @@ -208,9 +227,11 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ } this.m_NumberOfCrossovers = crossovers; } + public int getNumberOfCrossovers() { return this.m_NumberOfCrossovers; } + public String numberOfCrossoversTipText() { return "The number of crossoverpoints."; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverGIUniform.java b/src/eva2/optimization/operator/crossover/CrossoverGIUniform.java index 507dca96..592f331f 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGIUniform.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGIUniform.java @@ -1,7 +1,6 @@ package eva2.optimization.operator.crossover; - import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceGIIndividual; import eva2.optimization.population.Population; @@ -17,15 +16,19 @@ import eva2.tools.math.RNG; */ public class CrossoverGIUniform implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; public CrossoverGIUniform() { } + public CrossoverGIUniform(CrossoverGIUniform c) { - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -33,49 +36,51 @@ public class CrossoverGIUniform implements InterfaceCrossover, java.io.Serializa return new CrossoverGIUniform(this); } - /** This method performs crossover on two individuals. If the individuals do + /** + * This method performs crossover on two individuals. If the individuals do * not implement InterfaceGAIndividual, then nothing will happen. - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; + result = new AbstractEAIndividual[partners.size() + 1]; result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } if (partners.size() == 0) { return result; } //for (int i = 0; i < result.length; i++) System.out.println("Before Crossover: " +result[i].getSolutionRepresentationFor()); if ((indy1 instanceof InterfaceGIIndividual) && (partners.get(0) instanceof InterfaceGIIndividual)) { - int length = ((InterfaceGIIndividual)indy1).getGenotypeLength(); - int mixer = RNG.randomInt(0, partners.size()); - int[][][] tmpInts = new int[2][partners.size()+1][]; + int length = ((InterfaceGIIndividual) indy1).getGenotypeLength(); + int mixer = RNG.randomInt(0, partners.size()); + int[][][] tmpInts = new int[2][partners.size() + 1][]; - tmpInts[0][0] = ((InterfaceGIIndividual)indy1).getIGenotype(); - tmpInts[1][0] = ((InterfaceGIIndividual)result[0]).getIGenotype(); + tmpInts[0][0] = ((InterfaceGIIndividual) indy1).getIGenotype(); + tmpInts[1][0] = ((InterfaceGIIndividual) result[0]).getIGenotype(); for (int i = 0; i < partners.size(); i++) { - length = Math.max(length, ((InterfaceGIIndividual)partners.get(i)).getGenotypeLength()); - tmpInts[0][i+1] = ((InterfaceGIIndividual)partners.get(i)).getIGenotype(); - tmpInts[1][i+1] = ((InterfaceGIIndividual)result[i+1]).getIGenotype(); - length = Math.max(length, ((InterfaceGIIndividual)partners.get(i)).getGenotypeLength()); + length = Math.max(length, ((InterfaceGIIndividual) partners.get(i)).getGenotypeLength()); + tmpInts[0][i + 1] = ((InterfaceGIIndividual) partners.get(i)).getIGenotype(); + tmpInts[1][i + 1] = ((InterfaceGIIndividual) result[i + 1]).getIGenotype(); + length = Math.max(length, ((InterfaceGIIndividual) partners.get(i)).getGenotypeLength()); } for (int i = 0; i < length; i++) { mixer = RNG.randomInt(0, partners.size()); for (int j = 0; j < tmpInts[0].length; j++) { if ((tmpInts[0][(j + mixer) % tmpInts[0].length].length > i) && - (tmpInts[1][j].length > i)) { + (tmpInts[1][j].length > i)) { tmpInts[1][j][i] = tmpInts[0][(j + mixer) % tmpInts[0].length][i]; } } } for (int i = 0; i < result.length; i++) { - ((InterfaceGIIndividual)result[i]).SetIGenotype(tmpInts[1][i]); + ((InterfaceGIIndividual) result[i]).SetIGenotype(tmpInts[1][i]); } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters @@ -86,26 +91,29 @@ public class CrossoverGIUniform implements InterfaceCrossover, java.io.Serializa return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverGIUniform) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -120,14 +128,19 @@ public class CrossoverGIUniform implements InterfaceCrossover, java.io.Serializa /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI uniform crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java b/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java index 20207376..6bdcab1c 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java @@ -1,7 +1,6 @@ package eva2.optimization.operator.crossover; - import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.GPIndividualProgramData; import eva2.optimization.individuals.InterfaceGPIndividual; @@ -19,20 +18,24 @@ import eva2.tools.math.RNG; */ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializable { /** - * - */ - private static final long serialVersionUID = 8900427365914281930L; - private InterfaceOptimizationProblem m_OptimizationProblem; + * + */ + private static final long serialVersionUID = 8900427365914281930L; + private InterfaceOptimizationProblem m_OptimizationProblem; private boolean maintainMaxDepth = true; - private static final boolean TRACE=false; + private static final boolean TRACE = false; public CrossoverGPDefault() { } + public CrossoverGPDefault(CrossoverGPDefault c) { - this.maintainMaxDepth = c.maintainMaxDepth; - this.m_OptimizationProblem = c.m_OptimizationProblem; + this.maintainMaxDepth = c.maintainMaxDepth; + this.m_OptimizationProblem = c.m_OptimizationProblem; } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -40,115 +43,117 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa return new CrossoverGPDefault(this); } - /** + /** * Exchange subtrees of two GP nodes. Allows to keep the depth restriction. - * - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - if (partners.size()>1) { + if (partners.size() > 1) { System.err.println("Warning, crossover may not work on more than one partner! " + this.getClass()); } AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; + result = new AbstractEAIndividual[partners.size() + 1]; result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } if (TRACE) { for (int i = 0; i < result.length; i++) { - System.out.println("Before Crossover: " +result[i].getStringRepresentation()); - } } + System.out.println("Before Crossover: " + result[i].getStringRepresentation()); + } + } if (partners.size() == 0) { return result; } if ((indy1 instanceof InterfaceGPIndividual) && (partners.get(0) instanceof InterfaceGPIndividual)) { - int allowedDepth = ((InterfaceGPIndividual)indy1).getMaxAllowedDepth(); - - AbstractGPNode[] nodes = ((InterfaceGPIndividual)result[0]).getPGenotype(); + int allowedDepth = ((InterfaceGPIndividual) indy1).getMaxAllowedDepth(); + + AbstractGPNode[] nodes = ((InterfaceGPIndividual) result[0]).getPGenotype(); for (int t = 0; t < nodes.length; t++) { // for each of the genotypes (multiploidy??) - ((InterfaceGPIndividual)result[0]).getPGenotype()[t].getRandomNode(); - AbstractGPNode selNodeThis = ((InterfaceGPIndividual)result[0]).getPGenotype()[t].getRandomNode(); - AbstractGPNode selNodeOther = ((InterfaceGPIndividual)result[1]).getPGenotype()[t].getRandomNode(); + ((InterfaceGPIndividual) result[0]).getPGenotype()[t].getRandomNode(); + AbstractGPNode selNodeThis = ((InterfaceGPIndividual) result[0]).getPGenotype()[t].getRandomNode(); + AbstractGPNode selNodeOther = ((InterfaceGPIndividual) result[1]).getPGenotype()[t].getRandomNode(); if (maintainMaxDepth) {//System.err.print("."); - int maxTries=10; - // if the echange would violate the depth restriction, choose new nodes for a few times... - while (maxTries>=0 && ((selNodeOther.getSubtreeDepth()+selNodeThis.getDepth()>allowedDepth) || - (selNodeThis.getSubtreeDepth()+selNodeOther.getDepth()>allowedDepth))) { - if (RNG.flipCoin(0.5)) { - selNodeThis = ((InterfaceGPIndividual)result[0]).getPGenotype()[t].getRandomNode(); - } - else { - selNodeOther = ((InterfaceGPIndividual)result[1]).getPGenotype()[t].getRandomNode(); - } - maxTries--; - } - if (maxTries<0) { // on a failure, at least exchange two leaves, which always works + int maxTries = 10; + // if the echange would violate the depth restriction, choose new nodes for a few times... + while (maxTries >= 0 && ((selNodeOther.getSubtreeDepth() + selNodeThis.getDepth() > allowedDepth) || + (selNodeThis.getSubtreeDepth() + selNodeOther.getDepth() > allowedDepth))) { + if (RNG.flipCoin(0.5)) { + selNodeThis = ((InterfaceGPIndividual) result[0]).getPGenotype()[t].getRandomNode(); + } else { + selNodeOther = ((InterfaceGPIndividual) result[1]).getPGenotype()[t].getRandomNode(); + } + maxTries--; + } + if (maxTries < 0) { // on a failure, at least exchange two leaves, which always works // System.err.println("Unable to select fitting nodes! Just switch leaves..."); - selNodeThis = ((InterfaceGPIndividual)result[0]).getPGenotype()[t].getRandomLeaf(); - selNodeOther = ((InterfaceGPIndividual)result[1]).getPGenotype()[t].getRandomLeaf(); - } + selNodeThis = ((InterfaceGPIndividual) result[0]).getPGenotype()[t].getRandomLeaf(); + selNodeOther = ((InterfaceGPIndividual) result[1]).getPGenotype()[t].getRandomLeaf(); + } } if (TRACE) { - System.out.println("Selected t " + selNodeThis.getStringRepresentation()); - System.out.println("Selected o " + selNodeOther.getStringRepresentation()); + System.out.println("Selected t " + selNodeThis.getStringRepresentation()); + System.out.println("Selected o " + selNodeOther.getStringRepresentation()); } - + AbstractGPNode selNodeThisParent, selNodeOtherParent; selNodeThisParent = selNodeThis.getParent(); selNodeOtherParent = selNodeOther.getParent(); - + // actually switch individuals! if (selNodeThisParent == null) { - ((InterfaceGPIndividual)result[0]).SetPGenotype((AbstractGPNode)selNodeOther.clone(), t); - } - else { - selNodeThisParent.setNode((AbstractGPNode)selNodeOther.clone(), selNodeThis); + ((InterfaceGPIndividual) result[0]).SetPGenotype((AbstractGPNode) selNodeOther.clone(), t); + } else { + selNodeThisParent.setNode((AbstractGPNode) selNodeOther.clone(), selNodeThis); } // for (int i = 0; i < result.length; i++) System.out.println("-- Betw Crossover: " +result[i].getStringRepresentation()); if (selNodeOtherParent == null) { - ((InterfaceGPIndividual)result[1]).SetPGenotype((AbstractGPNode)selNodeThis.clone(), t); - } - else { - selNodeOtherParent.setNode((AbstractGPNode)selNodeThis.clone(), selNodeOther); + ((InterfaceGPIndividual) result[1]).SetPGenotype((AbstractGPNode) selNodeThis.clone(), t); + } else { + selNodeOtherParent.setNode((AbstractGPNode) selNodeThis.clone(), selNodeOther); } } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters for (int i = 0; i < result.length; i++) { - ((GPIndividualProgramData)result[i]).checkDepth(); - result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); + ((GPIndividualProgramData) result[i]).checkDepth(); + result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); } if (TRACE) { for (int i = 0; i < result.length; i++) { - System.out.println("After Crossover: " +result[i].getStringRepresentation()); - } } + System.out.println("After Crossover: " + result[i].getStringRepresentation()); + } + } return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverGPDefault) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -163,14 +168,19 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GP default crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverOBGAPMX.java b/src/eva2/optimization/operator/crossover/CrossoverOBGAPMX.java index be5aa31a..f026ac14 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverOBGAPMX.java +++ b/src/eva2/optimization/operator/crossover/CrossoverOBGAPMX.java @@ -11,6 +11,7 @@ import eva2.tools.math.RNG; *

Description: PMX-Crossover as defined in http://www.cs.rit.edu/usr/local/pub/pga/Genetic/Slides_etc/ga_5_og.pdf

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author planatsc * @version 1.0 */ @@ -20,9 +21,13 @@ public class CrossoverOBGAPMX implements InterfaceCrossover, java.io.Serializabl public CrossoverOBGAPMX() { } + public CrossoverOBGAPMX(CrossoverOBGAPMX c) { } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -31,74 +36,75 @@ public class CrossoverOBGAPMX implements InterfaceCrossover, java.io.Serializabl } @Override - public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size()+1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); - for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { + AbstractEAIndividual[] result = null; + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); + for (int i = 0; i < partners.size(); i++) { + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } - if ((indy1 instanceof InterfaceOBGAIndividual) && (partners.get(0) instanceof InterfaceOBGAIndividual)) { - int[][] pperm1; - int[][] pperm2; - pperm1 = new int[((InterfaceOBGAIndividual) result[0]).getOBGenotype().length][]; - pperm2 = new int[((InterfaceOBGAIndividual) result[1]).getOBGenotype().length][]; + if ((indy1 instanceof InterfaceOBGAIndividual) && (partners.get(0) instanceof InterfaceOBGAIndividual)) { + int[][] pperm1; + int[][] pperm2; + pperm1 = new int[((InterfaceOBGAIndividual) result[0]).getOBGenotype().length][]; + pperm2 = new int[((InterfaceOBGAIndividual) result[1]).getOBGenotype().length][]; - for (int i = 0; i < ((InterfaceOBGAIndividual) result[0]).getOBGenotype().length; i++) { + for (int i = 0; i < ((InterfaceOBGAIndividual) result[0]).getOBGenotype().length; i++) { - int[] perm1 = (int[])((InterfaceOBGAIndividual) result[0]).getOBGenotype()[i].clone(); - int[] perm2 = (int[])((InterfaceOBGAIndividual) result[1]).getOBGenotype()[i].clone(); - int begin = RNG.randomInt(0,perm1.length-2); - int end = RNG.randomInt(begin,perm1.length-1); - for (int pos = begin; pos <= end; pos++) { - int crosspoint = pos; - int p1inp2 = 0; - int p2inp1 = 0; - while (perm1[p2inp1] != perm2[crosspoint]) p2inp1++; - while (perm2[p1inp2] != perm1[crosspoint]) p1inp2++; - perm1[crosspoint] = perm2[crosspoint]; - perm2[crosspoint] = perm2[p1inp2]; - perm1[p2inp1] = perm2[crosspoint]; - perm2[p1inp2] = perm1[crosspoint]; + int[] perm1 = (int[]) ((InterfaceOBGAIndividual) result[0]).getOBGenotype()[i].clone(); + int[] perm2 = (int[]) ((InterfaceOBGAIndividual) result[1]).getOBGenotype()[i].clone(); + int begin = RNG.randomInt(0, perm1.length - 2); + int end = RNG.randomInt(begin, perm1.length - 1); + for (int pos = begin; pos <= end; pos++) { + int crosspoint = pos; + int p1inp2 = 0; + int p2inp1 = 0; + while (perm1[p2inp1] != perm2[crosspoint]) p2inp1++; + while (perm2[p1inp2] != perm1[crosspoint]) p1inp2++; + perm1[crosspoint] = perm2[crosspoint]; + perm2[crosspoint] = perm2[p1inp2]; + perm1[p2inp1] = perm2[crosspoint]; + perm2[p1inp2] = perm1[crosspoint]; + } + pperm1[i] = perm1; + pperm2[i] = perm2; + } + + ((InterfaceOBGAIndividual) result[0]).SetOBGenotype(pperm1); + ((InterfaceOBGAIndividual) result[1]).SetOBGenotype(pperm2); + //((InterfaceDataTypePermutation) result[0]).SetPermutationDataLamarckian(pperm1); + //((InterfaceDataTypePermutation) result[1]).SetPermutationDataLamarckian(pperm2); } - pperm1[i] = perm1; - pperm2[i] = perm2; - } - - ((InterfaceOBGAIndividual) result[0]).SetOBGenotype(pperm1); - ((InterfaceOBGAIndividual) result[1]).SetOBGenotype(pperm2); - //((InterfaceDataTypePermutation) result[0]).SetPermutationDataLamarckian(pperm1); - //((InterfaceDataTypePermutation) result[1]).SetPermutationDataLamarckian(pperm2); - } - //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters - for (int i = 0; i < result.length; i++) { + //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters + for (int i = 0; i < result.length; i++) { result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); } - return result; + return result; - } + } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverOBGAPMX) { return true; - } - else { + } else { return false; } } @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - // nothing to init! - } + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { + // nothing to init! + } @Override public String getStringRepresentation() { @@ -108,14 +114,19 @@ public class CrossoverOBGAPMX implements InterfaceCrossover, java.io.Serializabl /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "OBGA PMX crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverOBGAPMXUniform.java b/src/eva2/optimization/operator/crossover/CrossoverOBGAPMXUniform.java index 987722b0..daf3344f 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverOBGAPMXUniform.java +++ b/src/eva2/optimization/operator/crossover/CrossoverOBGAPMXUniform.java @@ -11,6 +11,7 @@ import eva2.tools.math.RNG; *

Description: PMX-Crossover as defined in http://www.cs.rit.edu/usr/local/pub/pga/Genetic/Slides_etc/ga_5_og.pdf

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author planatsc * @version 1.0 */ @@ -20,9 +21,13 @@ public class CrossoverOBGAPMXUniform implements InterfaceCrossover, java.io.Seri public CrossoverOBGAPMXUniform() { } + public CrossoverOBGAPMXUniform(CrossoverOBGAPMXUniform c) { } - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -32,70 +37,71 @@ public class CrossoverOBGAPMXUniform implements InterfaceCrossover, java.io.Seri @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - AbstractEAIndividual[] result = null; - result = new AbstractEAIndividual[partners.size() + 1]; - result[0] = (AbstractEAIndividual) (indy1).clone(); - for (int i = 0; i < partners.size(); i++) { + AbstractEAIndividual[] result = null; + result = new AbstractEAIndividual[partners.size() + 1]; + result[0] = (AbstractEAIndividual) (indy1).clone(); + for (int i = 0; i < partners.size(); i++) { result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } - if ((indy1 instanceof InterfaceOBGAIndividual) && (partners.get(0) instanceof InterfaceOBGAIndividual)) { - int[][] pperm1; - int[][] pperm2; - pperm1 = new int[((InterfaceOBGAIndividual) result[0]).getOBGenotype().length][]; - pperm2 = new int[((InterfaceOBGAIndividual) result[1]).getOBGenotype().length][]; + if ((indy1 instanceof InterfaceOBGAIndividual) && (partners.get(0) instanceof InterfaceOBGAIndividual)) { + int[][] pperm1; + int[][] pperm2; + pperm1 = new int[((InterfaceOBGAIndividual) result[0]).getOBGenotype().length][]; + pperm2 = new int[((InterfaceOBGAIndividual) result[1]).getOBGenotype().length][]; - for (int i = 0; i < ((InterfaceOBGAIndividual) result[0]).getOBGenotype().length; i++) { - int[] perm1 = (int[])((InterfaceOBGAIndividual) result[0]).getOBGenotype()[i].clone(); - int[] perm2 = (int[])((InterfaceOBGAIndividual) result[1]).getOBGenotype()[i].clone(); + for (int i = 0; i < ((InterfaceOBGAIndividual) result[0]).getOBGenotype().length; i++) { + int[] perm1 = (int[]) ((InterfaceOBGAIndividual) result[0]).getOBGenotype()[i].clone(); + int[] perm2 = (int[]) ((InterfaceOBGAIndividual) result[1]).getOBGenotype()[i].clone(); - int crossnumber = RNG.randomInt(1, perm1.length); + int crossnumber = RNG.randomInt(1, perm1.length); - for (int iter = 0; iter < crossnumber; iter++) { - int crosspoint = RNG.randomInt(0, perm1.length - 1); - int p1inp2 = 0; - int p2inp1 = 0; - while (perm1[p2inp1] != perm2[crosspoint]) p2inp1++; - while (perm2[p1inp2] != perm1[crosspoint]) p1inp2++; - perm1[crosspoint] = perm2[crosspoint]; - perm2[crosspoint] = perm2[p1inp2]; - perm1[p2inp1] = perm2[crosspoint]; - perm2[p1inp2] = perm1[crosspoint]; - } - pperm1[i] = perm1; - pperm2[i] = perm2; + for (int iter = 0; iter < crossnumber; iter++) { + int crosspoint = RNG.randomInt(0, perm1.length - 1); + int p1inp2 = 0; + int p2inp1 = 0; + while (perm1[p2inp1] != perm2[crosspoint]) p2inp1++; + while (perm2[p1inp2] != perm1[crosspoint]) p1inp2++; + perm1[crosspoint] = perm2[crosspoint]; + perm2[crosspoint] = perm2[p1inp2]; + perm1[p2inp1] = perm2[crosspoint]; + perm2[p1inp2] = perm1[crosspoint]; + } + pperm1[i] = perm1; + pperm2[i] = perm2; + } + ((InterfaceOBGAIndividual) result[0]).SetOBGenotype(pperm1); + ((InterfaceOBGAIndividual) result[1]).SetOBGenotype(pperm2); } - ((InterfaceOBGAIndividual) result[0]).SetOBGenotype(pperm1); - ((InterfaceOBGAIndividual) result[1]).SetOBGenotype(pperm2); - } - //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters - for (int i = 0; i < result.length; i++) { + //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters + for (int i = 0; i < result.length; i++) { result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); } - return result; + return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof CrossoverOBGAPMXUniform) { return true; - } - else { + } else { return false; } } @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - // nothing to init! - } + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { + // nothing to init! + } @Override public String getStringRepresentation() { @@ -105,14 +111,19 @@ public class CrossoverOBGAPMXUniform implements InterfaceCrossover, java.io.Seri /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "OBGA PMX uniform crossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/InterfaceCrossover.java b/src/eva2/optimization/operator/crossover/InterfaceCrossover.java index 7a6ce327..5c27063d 100644 --- a/src/eva2/optimization/operator/crossover/InterfaceCrossover.java +++ b/src/eva2/optimization/operator/crossover/InterfaceCrossover.java @@ -14,36 +14,46 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; */ public interface InterfaceCrossover { - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ public Object clone(); - /** This method performs crossover on two individuals. Note: the genotype of the individuals + /** + * This method performs crossover on two individuals. Note: the genotype of the individuals * will be changed, so it would be better to use clones as arguments - * @param indy1 The first individual + * + * @param indy1 The first individual * @param partners The second individual */ public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners); - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt); - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ - public String getStringRepresentation(); + public String getStringRepresentation(); - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover); diff --git a/src/eva2/optimization/operator/crossover/InterfaceEvaluatingCrossoverOperator.java b/src/eva2/optimization/operator/crossover/InterfaceEvaluatingCrossoverOperator.java index 60cc1a18..a872281d 100644 --- a/src/eva2/optimization/operator/crossover/InterfaceEvaluatingCrossoverOperator.java +++ b/src/eva2/optimization/operator/crossover/InterfaceEvaluatingCrossoverOperator.java @@ -2,12 +2,12 @@ package eva2.optimization.operator.crossover; public interface InterfaceEvaluatingCrossoverOperator extends InterfaceCrossover { - /** - * Retrieve the number of evaluations performed during crossover. - * - * @return - */ - public int getEvaluations(); - - public void resetEvaluations(); + /** + * Retrieve the number of evaluations performed during crossover. + * + * @return + */ + public int getEvaluations(); + + public void resetEvaluations(); } diff --git a/src/eva2/optimization/operator/crossover/NoCrossover.java b/src/eva2/optimization/operator/crossover/NoCrossover.java index 2d19c9c5..2aa68f8c 100644 --- a/src/eva2/optimization/operator/crossover/NoCrossover.java +++ b/src/eva2/optimization/operator/crossover/NoCrossover.java @@ -12,17 +12,18 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * To change this template use Options | File Templates. */ public class NoCrossover implements InterfaceCrossover, java.io.Serializable { - private InterfaceOptimizationProblem m_OptimizationProblem; + private InterfaceOptimizationProblem m_OptimizationProblem; /** * A constructor. - * */ public NoCrossover() { } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -30,9 +31,10 @@ public class NoCrossover implements InterfaceCrossover, java.io.Serializable { return new NoCrossover(); } - /** This method performs no crossover on the individuals. - * - * @param indy1 The first individual + /** + * This method performs no crossover on the individuals. + * + * @param indy1 The first individual * @param partners The partner individuals */ @Override @@ -42,35 +44,38 @@ public class NoCrossover implements InterfaceCrossover, java.io.Serializable { result = new AbstractEAIndividual[1 + partners.size()]; /// by MK result[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { - result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); + result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters for (int i = 0; i < result.length; i++) { result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); - } + } return result; } - /** This method allows you to evaluate wether two crossover operators + /** + * This method allows you to evaluate wether two crossover operators * are actually the same. - * @param crossover The other crossover operator + * + * @param crossover The other crossover operator */ @Override public boolean equals(Object crossover) { if (crossover instanceof NoCrossover) { return true; - } - else { + } else { return false; } } - /** This method will allow the crossover operator to be initialized depending on the + /** + * This method will allow the crossover operator to be initialized depending on the * individual and the optimization problem. The optimization problem is to be stored * since it is to be called during crossover to calculate the exogene parameters for * the offsprings. - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -85,14 +90,19 @@ public class NoCrossover implements InterfaceCrossover, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Nocrossover"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/crossover/PropertyCrossoverMixer.java b/src/eva2/optimization/operator/crossover/PropertyCrossoverMixer.java index 7ed5a3c5..b1a22ef9 100644 --- a/src/eva2/optimization/operator/crossover/PropertyCrossoverMixer.java +++ b/src/eva2/optimization/operator/crossover/PropertyCrossoverMixer.java @@ -9,33 +9,34 @@ package eva2.optimization.operator.crossover; */ public class PropertyCrossoverMixer implements java.io.Serializable { - public InterfaceCrossover[] m_AvailableTargets; - public InterfaceCrossover[] m_SelectedTargets; - public double[] m_Weights; - public String m_DescriptiveString = "No Description given."; - public String m_WeightsLabel = "-"; - public boolean m_NormalizationEnabled = true; + public InterfaceCrossover[] m_AvailableTargets; + public InterfaceCrossover[] m_SelectedTargets; + public double[] m_Weights; + public String m_DescriptiveString = "No Description given."; + public String m_WeightsLabel = "-"; + public boolean m_NormalizationEnabled = true; public PropertyCrossoverMixer(InterfaceCrossover[] d) { this.m_Weights = new double[d.length]; for (int i = 0; i < d.length; i++) { - this.m_Weights[i] = 1/((double)d.length); + this.m_Weights[i] = 1 / ((double) d.length); } this.m_AvailableTargets = d; - this.m_SelectedTargets = null; + this.m_SelectedTargets = null; } + public PropertyCrossoverMixer(PropertyCrossoverMixer d) { - this.m_DescriptiveString = d.m_DescriptiveString; - this.m_WeightsLabel = d.m_WeightsLabel; - this.m_NormalizationEnabled = d.m_NormalizationEnabled; - this.m_AvailableTargets = new InterfaceCrossover[d.m_AvailableTargets.length]; + this.m_DescriptiveString = d.m_DescriptiveString; + this.m_WeightsLabel = d.m_WeightsLabel; + this.m_NormalizationEnabled = d.m_NormalizationEnabled; + this.m_AvailableTargets = new InterfaceCrossover[d.m_AvailableTargets.length]; for (int i = 0; i < this.m_AvailableTargets.length; i++) { //this.m_AvailableTargets[i] = (InterfaceMutation)d.m_AvailableTargets[i].clone(); - this.m_AvailableTargets[i] = d.m_AvailableTargets[i]; + this.m_AvailableTargets[i] = d.m_AvailableTargets[i]; } - this.m_SelectedTargets = new InterfaceCrossover[d.m_SelectedTargets.length]; + this.m_SelectedTargets = new InterfaceCrossover[d.m_SelectedTargets.length]; for (int i = 0; i < this.m_SelectedTargets.length; i++) { - this.m_SelectedTargets[i] = (InterfaceCrossover)d.m_SelectedTargets[i].clone(); + this.m_SelectedTargets[i] = (InterfaceCrossover) d.m_SelectedTargets[i].clone(); } if (d.m_Weights != null) { this.m_Weights = new double[d.m_Weights.length]; @@ -48,8 +49,10 @@ public class PropertyCrossoverMixer implements java.io.Serializable { return (Object) new PropertyCrossoverMixer(this); } - /** This method will allow you to set the value of the InterfaceOptimizationTarget array - * @param d The InterfaceOptimizationTarget[] + /** + * This method will allow you to set the value of the InterfaceOptimizationTarget array + * + * @param d The InterfaceOptimizationTarget[] */ public void setSelectedCrossers(InterfaceCrossover[] d) { this.m_SelectedTargets = d; @@ -57,7 +60,7 @@ public class PropertyCrossoverMixer implements java.io.Serializable { if (this.m_Weights == null) { this.m_Weights = new double[d.length]; for (int i = 0; i < this.m_Weights.length; i++) { - this.m_Weights[i] = 1/((double)d.length); + this.m_Weights[i] = 1 / ((double) d.length); } return; } @@ -81,26 +84,33 @@ public class PropertyCrossoverMixer implements java.io.Serializable { } } - /** This method will return the InterfaceOptimizationTarget array + /** + * This method will return the InterfaceOptimizationTarget array + * * @return The InterfaceOptimizationTarget[]. */ public InterfaceCrossover[] getSelectedCrossers() { return this.m_SelectedTargets; } - /** This method will return the InterfaceOptimizationTarget array + /** + * This method will return the InterfaceOptimizationTarget array + * * @return The InterfaceOptimizationTarget[]. */ public InterfaceCrossover[] getAvailableCrossers() { return this.m_AvailableTargets; } - /** This method allows you to read the weights + /** + * This method allows you to read the weights + * * @return the weights */ public double[] getWeights() { return this.m_Weights; } + public void setWeights(double[] d) { this.m_Weights = d; for (int i = 0; i < this.m_Weights.length; i++) { @@ -108,22 +118,28 @@ public class PropertyCrossoverMixer implements java.io.Serializable { } } - /** This method allows you to set/get the descriptive string + /** + * This method allows you to set/get the descriptive string + * * @return the string */ public String getDescriptiveString() { return this.m_DescriptiveString; } + public void setDescriptiveString(String d) { this.m_DescriptiveString = d; } - /** This method allows you to set/get the weights label + /** + * This method allows you to set/get the weights label + * * @return the string */ public String getWeigthsLabel() { return this.m_WeightsLabel; } + public void setWeightsLabel(String d) { this.m_WeightsLabel = d; } @@ -140,16 +156,18 @@ public class PropertyCrossoverMixer implements java.io.Serializable { } } - /** This method allows you to remove a Target from the list - * @param index The index of the target to be removed. + /** + * This method allows you to remove a Target from the list + * + * @param index The index of the target to be removed. */ public void removeCrosser(int index) { if ((index < 0) || (index >= this.m_SelectedTargets.length)) { return; } - InterfaceCrossover[] newList = new InterfaceCrossover[this.m_SelectedTargets.length-1]; - double[] newWeights = new double[this.m_Weights.length - 1]; + InterfaceCrossover[] newList = new InterfaceCrossover[this.m_SelectedTargets.length - 1]; + double[] newWeights = new double[this.m_Weights.length - 1]; int j = 0; for (int i = 0; i < this.m_SelectedTargets.length; i++) { if (index != i) { @@ -158,23 +176,25 @@ public class PropertyCrossoverMixer implements java.io.Serializable { j++; } } - this.m_SelectedTargets = newList; - this.m_Weights = newWeights; + this.m_SelectedTargets = newList; + this.m_Weights = newWeights; } - /** This method allows you to add a new target to the list + /** + * This method allows you to add a new target to the list + * * @param optTarget */ public void addCrossers(InterfaceCrossover optTarget) { - InterfaceCrossover[] newList = new InterfaceCrossover[this.m_SelectedTargets.length+1]; - double[] newWeights = new double[this.m_Weights.length + 1]; + InterfaceCrossover[] newList = new InterfaceCrossover[this.m_SelectedTargets.length + 1]; + double[] newWeights = new double[this.m_Weights.length + 1]; for (int i = 0; i < this.m_SelectedTargets.length; i++) { newList[i] = this.m_SelectedTargets[i]; newWeights[i] = this.m_Weights[i]; } newList[this.m_SelectedTargets.length] = optTarget; newWeights[this.m_SelectedTargets.length] = 1.0; - this.m_SelectedTargets = newList; - this.m_Weights = newWeights; + this.m_SelectedTargets = newList; + this.m_Weights = newWeights; } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/crossover/PropertyCrossoverMixerEditor.java b/src/eva2/optimization/operator/crossover/PropertyCrossoverMixerEditor.java index b137bd96..698b6a55 100644 --- a/src/eva2/optimization/operator/crossover/PropertyCrossoverMixerEditor.java +++ b/src/eva2/optimization/operator/crossover/PropertyCrossoverMixerEditor.java @@ -7,6 +7,7 @@ import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGEOFaker; import eva2.optimization.tools.GeneralGOEProperty; import eva2.tools.BasicResourceLoader; + import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; @@ -47,29 +48,38 @@ import javax.swing.SwingConstants; */ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEditor, java.beans.PropertyChangeListener { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The FilePath that is to be edited*/ - private PropertyCrossoverMixer m_CrossoversWithWeights; + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The FilePath that is to be edited + */ + private PropertyCrossoverMixer m_CrossoversWithWeights; - /** The gaphix stuff */ - private JComponent m_Editor; - private JPanel m_TargetList; - private JTextField[] m_Weights; - private JComponent[] m_Targets; - private JButton[] m_Delete; - private JScrollPane m_ScrollTargets; - private GeneralGOEProperty[] m_Editors; - private GeneralGEOFaker m_Component; - private PropertyChangeListener m_self; + /** + * The gaphix stuff + */ + private JComponent m_Editor; + private JPanel m_TargetList; + private JTextField[] m_Weights; + private JComponent[] m_Targets; + private JButton[] m_Delete; + private JScrollPane m_ScrollTargets; + private GeneralGOEProperty[] m_Editors; + private GeneralGEOFaker m_Component; + private PropertyChangeListener m_self; public PropertyCrossoverMixerEditor() { m_self = this; } - /** This method will init the CustomEditor Panel + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { m_self = this; @@ -78,14 +88,14 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit this.m_Editor.setMinimumSize(new Dimension(450, 200)); // init the editors - InterfaceCrossover[] list = this.m_CrossoversWithWeights.getSelectedCrossers(); + InterfaceCrossover[] list = this.m_CrossoversWithWeights.getSelectedCrossers(); this.m_Editors = new GeneralGOEProperty[list.length]; for (int i = 0; i < list.length; i++) { this.m_Editors[i] = new GeneralGOEProperty(); - this.m_Editors[i].m_Name = list[i].getStringRepresentation(); + this.m_Editors[i].m_Name = list[i].getStringRepresentation(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceCrossover.class); } @@ -103,17 +113,17 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } } this.m_TargetList = new JPanel(); - this.updateTargetList(); + this.updateTargetList(); this.m_ScrollTargets = new JScrollPane(this.m_TargetList); this.m_Editor.setLayout(new BorderLayout()); this.m_Editor.add(this.m_ScrollTargets, BorderLayout.CENTER); // The Button Panel - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new GridLayout(1,2)); - JButton addButton = new JButton("Add Mutator"); - JButton normButton = new JButton("Normalize Propabilities"); + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new GridLayout(1, 2)); + JButton addButton = new JButton("Add Mutator"); + JButton normButton = new JButton("Normalize Propabilities"); normButton.setEnabled(true); normButton.addActionListener(normalizeWeights); addButton.addActionListener(addTarget); @@ -123,89 +133,89 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit this.m_Editor.add(buttonPanel, BorderLayout.SOUTH); // Some description would be nice - JTextArea jt = new JTextArea(); - jt.setFont(new Font("SansSerif", Font.PLAIN,12)); - jt.setEditable(false); - jt.setLineWrap(true); - jt.setWrapStyleWord(true); - jt.setText(this.m_CrossoversWithWeights.getDescriptiveString()); + JTextArea jt = new JTextArea(); + jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); + jt.setEditable(false); + jt.setLineWrap(true); + jt.setWrapStyleWord(true); + jt.setText(this.m_CrossoversWithWeights.getDescriptiveString()); jt.setBackground(getBackground()); - JPanel jp = new JPanel(); - jp.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Info"), - BorderFactory.createEmptyBorder(0, 5, 5, 5) - )); - jp.setLayout(new BorderLayout()); - jp.add(jt, BorderLayout.CENTER); - JPanel p2 = new JPanel(); + JPanel jp = new JPanel(); + jp.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createTitledBorder("Info"), + BorderFactory.createEmptyBorder(0, 5, 5, 5) + )); + jp.setLayout(new BorderLayout()); + jp.add(jt, BorderLayout.CENTER); + JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); JButton help = new JButton("Help"); help.setEnabled(false); p2.add(help, BorderLayout.NORTH); jp.add(p2, BorderLayout.EAST); - GridBagConstraints gbConstraints = new GridBagConstraints(); + GridBagConstraints gbConstraints = new GridBagConstraints(); this.m_Editor.add(jp, BorderLayout.NORTH); this.updateEditor(); } - /** This method updates the server list - * + /** + * This method updates the server list */ private void updateTargetList() { - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes; - InterfaceCrossover[] list = this.m_CrossoversWithWeights.getSelectedCrossers(); - double[] weights = this.m_CrossoversWithWeights.getWeights(); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes; + InterfaceCrossover[] list = this.m_CrossoversWithWeights.getSelectedCrossers(); + double[] weights = this.m_CrossoversWithWeights.getWeights(); this.m_TargetList.removeAll(); this.m_TargetList.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - this.m_Weights = new JTextField[list.length]; - this.m_Targets = new JComponent[list.length]; - this.m_Delete = new JButton[list.length]; - String[] cups = new String[8]; + this.m_Weights = new JTextField[list.length]; + this.m_Targets = new JComponent[list.length]; + this.m_Delete = new JButton[list.length]; + String[] cups = new String[8]; for (int i = 0; i < cups.length; i++) { - cups[i] = ""+(i+1); + cups[i] = "" + (i + 1); } // The head title - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 2; this.m_TargetList.add(new JLabel(this.m_CrossoversWithWeights.getWeigthsLabel()), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.weightx = 10; this.m_TargetList.add(new JLabel("Target"), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 2; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 2; + gbc.weightx = 1; this.m_TargetList.add(new JLabel("Remove"), gbc); for (int i = 0; i < list.length; i++) { // the weight - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 2; - this.m_Weights[i] = new JTextField(""+weights[i]); + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 2; + this.m_Weights[i] = new JTextField("" + weights[i]); this.m_Weights[i].addKeyListener(this.readDoubleArrayAction); this.m_TargetList.add(this.m_Weights[i], gbc); // the status indicator - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.weightx = 10; this.m_Targets[i] = this.m_Editors[i].m_View; this.m_TargetList.add(this.m_Targets[i], gbc); // The delete button - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 2; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 2; + gbc.weightx = 1; bytes = loader.getBytesFromResourceLocation("images/Sub24.gif", true); this.m_Delete[i] = new JButton("", new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); this.m_Delete[i].addActionListener(deleteTarget); @@ -223,7 +233,8 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } } - /** This action listener,... + /** + * This action listener,... */ ActionListener updateTargets = new ActionListener() { @Override @@ -232,12 +243,13 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener addTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_CrossoversWithWeights.addCrossers((InterfaceCrossover)m_CrossoversWithWeights.getAvailableCrossers()[0].clone()); + m_CrossoversWithWeights.addCrossers((InterfaceCrossover) m_CrossoversWithWeights.getAvailableCrossers()[0].clone()); int l = m_CrossoversWithWeights.getSelectedCrossers().length; GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l]; for (int i = 0; i < m_Editors.length; i++) { @@ -245,11 +257,11 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } InterfaceCrossover[] list = m_CrossoversWithWeights.getSelectedCrossers(); l--; - newEdit[l] = new GeneralGOEProperty(); - newEdit[l].m_Name = list[l].getStringRepresentation(); + newEdit[l] = new GeneralGOEProperty(); + newEdit[l].m_Name = list[l].getStringRepresentation(); try { - newEdit[l].m_Value = list[l]; - newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); + newEdit[l].m_Value = list[l]; + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); if (newEdit[l].m_Editor == null) { newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceCrossover.class); } @@ -270,18 +282,18 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener deleteTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int l = m_CrossoversWithWeights.getSelectedCrossers().length, j = 0; - GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l-1]; + GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l - 1]; for (int i = 0; i < m_Delete.length; i++) { if (event.getSource().equals(m_Delete[i])) { m_CrossoversWithWeights.removeCrosser(i); - } - else { + } else { newEdit[j] = m_Editors[i]; j++; } @@ -291,7 +303,8 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener normalizeWeights = new ActionListener() { @Override @@ -301,19 +314,21 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } }; - /** This action listener reads all values + /** + * This action listener reads all values */ KeyListener readDoubleArrayAction = new KeyListener() { @Override public void keyPressed(KeyEvent event) { } + @Override public void keyTyped(KeyEvent event) { } @Override public void keyReleased(KeyEvent event) { - double[] newW = m_CrossoversWithWeights.getWeights(); + double[] newW = m_CrossoversWithWeights.getWeights(); for (int i = 0; i < newW.length; i++) { try { @@ -325,10 +340,11 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } m_CrossoversWithWeights.setWeights(newW); - } + } }; - /** The object may have changed update the editor. + /** + * The object may have changed update the editor. */ private void updateEditor() { if (this.m_Editor != null) { @@ -341,18 +357,22 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit } } - /** This method will set the value of object that is to be edited. + /** + * This method will set the value of object that is to be edited. + * * @param o an object that must be an array. */ @Override public void setValue(Object o) { if (o instanceof PropertyCrossoverMixer) { - this.m_CrossoversWithWeights= (PropertyCrossoverMixer) o; + this.m_CrossoversWithWeights = (PropertyCrossoverMixer) o; this.updateEditor(); } } - /** Returns the current object. + /** + * Returns the current object. + * * @return the current object */ @Override @@ -389,21 +409,27 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit return null; } - /** This is used to hook an action listener to the ok button + /** + * This is used to hook an action listener to the ok button + * * @param a The action listener. */ public void addOkListener(ActionListener a) { //m_OKButton.addActionListener(a); } - /** This is used to remove an action listener from the ok button + /** + * This is used to remove an action listener from the ok button + * * @param a The action listener */ public void removeOkListener(ActionListener a) { //m_OKButton.removeActionListener(a); } - /** Returns true since the Object can be shown + /** + * Returns true since the Object can be shown + * * @return true */ @Override @@ -411,7 +437,8 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit return true; } - /** Paints a representation of the current classifier. + /** + * Paints a representation of the current classifier. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into @@ -421,30 +448,35 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; String rep = "Mixed Mutators"; - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); } - /** Returns true because we do support a custom editor. - * @return true - */ + /** + * Returns true because we do support a custom editor. + * + * @return true + */ @Override public boolean supportsCustomEditor() { return true; } - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override public Component getCustomEditor() { if (this.m_Component == null) { this.initCustomEditor(); - this.m_Component = new GeneralGEOFaker((PropertyEditor)this, (JPanel)this.m_Editor); + this.m_Component = new GeneralGEOFaker((PropertyEditor) this, (JPanel) this.m_Editor); } return this.m_Component; } - /** This method will udate the status of the object taking the values from all + /** + * This method will udate the status of the object taking the values from all * supsequent editors and setting them to my object. */ public void updateCenterComponent(PropertyChangeEvent evt) { @@ -452,39 +484,44 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit this.updateEditor(); } - /********************************* java.beans.PropertyChangeListener *************************/ + /** + * ****************************** java.beans.PropertyChangeListener ************************ + */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.addPropertyChangeListener(l); + m_Support.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); + m_Support.removePropertyChangeListener(l); } - /** This will wait for the GenericObjectEditor to finish + + /** + * This will wait for the GenericObjectEditor to finish * editing an object. + * * @param evt */ @Override - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(PropertyChangeEvent evt) { Object newVal = evt.getNewValue(); Object oldVal = evt.getOldValue(); InterfaceCrossover[] list = this.m_CrossoversWithWeights.getSelectedCrossers(); for (int i = 0; i < list.length; i++) { if (oldVal.equals(list[i])) { - list[i] = (InterfaceCrossover)newVal; - this.m_Editors[i].m_Name = list[i].getStringRepresentation(); + list[i] = (InterfaceCrossover) newVal; + this.m_Editors[i].m_Name = list[i].getStringRepresentation(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceCrossover.class); } diff --git a/src/eva2/optimization/operator/crossover/TestESCrossover.java b/src/eva2/optimization/operator/crossover/TestESCrossover.java index d8d1e18c..e1053cc3 100644 --- a/src/eva2/optimization/operator/crossover/TestESCrossover.java +++ b/src/eva2/optimization/operator/crossover/TestESCrossover.java @@ -9,6 +9,7 @@ import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.population.Population; import eva2.optimization.problems.F1Problem; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -24,28 +25,28 @@ import javax.swing.*; * To change this template use Options | File Templates. */ public class TestESCrossover implements java.io.Serializable { - private JFrame m_Frame; - private JPanel m_MainPanel, m_GraphPanel, m_ButtonPanel; - private JComponent m_OptionsPanel; - private JButton m_InitButton, m_Init2Button, m_Init3Button, m_CrossButton; + private JFrame m_Frame; + private JPanel m_MainPanel, m_GraphPanel, m_ButtonPanel; + private JComponent m_OptionsPanel; + private JButton m_InitButton, m_Init2Button, m_Init3Button, m_CrossButton; private InterfaceOptimizationProblem m_Problem = new F1Problem(); - private InterfaceCrossover m_Crossover = new CrossoverESUNDX(); - private Population m_Partners; - private AbstractEAIndividual m_Daddy; - private AbstractEAIndividual[] m_OffSprings; + private InterfaceCrossover m_Crossover = new CrossoverESUNDX(); + private Population m_Partners; + private AbstractEAIndividual m_Daddy; + private AbstractEAIndividual[] m_OffSprings; - private int m_NumberOfCrossovers = 100; - private int m_Dimension = 2; - private int m_NumberOfPartners = 1; - double[] pff; + private int m_NumberOfCrossovers = 100; + private int m_Dimension = 2; + private int m_NumberOfPartners = 1; + double[] pff; - private Plot m_Plot; + private Plot m_Plot; private void initFrame() { // init the main frame - this.m_Frame = new JFrame(); + this.m_Frame = new JFrame(); this.m_Frame.setTitle("ES Crossover Tester"); this.m_Frame.setSize(300, 400); this.m_Frame.setLocation(530, 50); @@ -56,7 +57,7 @@ public class TestESCrossover implements java.io.Serializable { } }); // build the main panel - this.m_MainPanel = new JPanel(); + this.m_MainPanel = new JPanel(); this.m_Frame.getContentPane().add(this.m_MainPanel); this.m_MainPanel.setLayout(new BorderLayout()); // build the button panel @@ -108,21 +109,21 @@ public class TestESCrossover implements java.io.Serializable { tmpIndyD.setDoubleDataLength(m_Dimension); tmpIndyD.SetDoubleRange(newRange); for (int i = 0; i < m_Partners.getTargetSize(); i++) { - tmpIndyEA = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + tmpIndyEA = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); tmpIndyEA.init(m_Problem); m_Partners.add(tmpIndyEA); } m_Partners.init(); - m_Daddy = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + m_Daddy = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); m_Daddy.init(m_Problem); m_Plot.clearAll(); m_Plot.setUnconnectedPoint(-2, -2, 0); m_Plot.setUnconnectedPoint(2, 2, 0); - double[] x; - x = ((InterfaceDataTypeDouble)m_Daddy).getDoubleData(); + double[] x; + x = ((InterfaceDataTypeDouble) m_Daddy).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 0); for (int i = 0; i < m_Partners.size(); i++) { - x = ((InterfaceDataTypeDouble)m_Partners.get(i)).getDoubleData(); + x = ((InterfaceDataTypeDouble) m_Partners.get(i)).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 0); m_Plot.setUnconnectedPoint(x[0], x[1], 0); pff = x; @@ -150,23 +151,23 @@ public class TestESCrossover implements java.io.Serializable { double[] tmpD = new double[2]; tmpD[0] = 1; tmpD[1] = 1; - ((AbstractEAIndividual)tmpIndyD).initByValue(tmpD, m_Problem); - tmpIndyEA = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + ((AbstractEAIndividual) tmpIndyD).initByValue(tmpD, m_Problem); + tmpIndyEA = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); tmpD = new double[2]; tmpD[0] = -1; tmpD[1] = -1; - ((AbstractEAIndividual)tmpIndyEA).initByValue(tmpD, m_Problem); + ((AbstractEAIndividual) tmpIndyEA).initByValue(tmpD, m_Problem); m_Partners.addIndividual(tmpIndyEA); - m_Daddy = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + m_Daddy = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); m_Plot.clearAll(); m_Plot.setUnconnectedPoint(-2, -2, 0); m_Plot.setUnconnectedPoint(2, 2, 0); - double[] x; - x = ((InterfaceDataTypeDouble)m_Daddy).getDoubleData(); + double[] x; + x = ((InterfaceDataTypeDouble) m_Daddy).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 0); for (int i = 0; i < m_Partners.size(); i++) { - x = ((InterfaceDataTypeDouble)m_Partners.get(i)).getDoubleData(); + x = ((InterfaceDataTypeDouble) m_Partners.get(i)).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 0); m_Plot.setUnconnectedPoint(x[0], x[1], 0); pff = x; @@ -194,29 +195,29 @@ public class TestESCrossover implements java.io.Serializable { double[] tmpD = new double[2]; tmpD[0] = 0.5; tmpD[1] = 1.1; - ((AbstractEAIndividual)tmpIndyD).initByValue(tmpD, m_Problem); - tmpIndyEA = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + ((AbstractEAIndividual) tmpIndyD).initByValue(tmpD, m_Problem); + tmpIndyEA = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); tmpD = new double[2]; tmpD[0] = 0.1; tmpD[1] = -0.65; - ((AbstractEAIndividual)tmpIndyEA).initByValue(tmpD, m_Problem); + ((AbstractEAIndividual) tmpIndyEA).initByValue(tmpD, m_Problem); m_Partners.addIndividual(tmpIndyEA); - tmpIndyEA = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + tmpIndyEA = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); tmpD = new double[2]; tmpD[0] = -0.85; tmpD[1] = 0.3; - ((AbstractEAIndividual)tmpIndyEA).initByValue(tmpD, m_Problem); + ((AbstractEAIndividual) tmpIndyEA).initByValue(tmpD, m_Problem); m_Partners.addIndividual(tmpIndyEA); - m_Daddy = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); + m_Daddy = (AbstractEAIndividual) ((AbstractEAIndividual) tmpIndyD).clone(); m_Plot.clearAll(); m_Plot.setUnconnectedPoint(-2, -2, 2); m_Plot.setUnconnectedPoint(2, 2, 2); - double[] x; - x = ((InterfaceDataTypeDouble)m_Daddy).getDoubleData(); + double[] x; + x = ((InterfaceDataTypeDouble) m_Daddy).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 0); for (int i = 0; i < m_Partners.size(); i++) { - x = ((InterfaceDataTypeDouble)m_Partners.get(i)).getDoubleData(); + x = ((InterfaceDataTypeDouble) m_Partners.get(i)).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 1); m_Plot.setUnconnectedPoint(x[0], x[1], 1); pff = x; @@ -227,12 +228,12 @@ public class TestESCrossover implements java.io.Serializable { ActionListener XListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - double[] x; - AbstractEAIndividual[] result; + double[] x; + AbstractEAIndividual[] result; for (int i = 0; i < m_NumberOfCrossovers; i++) { result = m_Crossover.mate(m_Daddy, m_Partners); for (int j = 0; j < result.length; j++) { - x = ((InterfaceDataTypeDouble)result[j]).getDoubleData(); + x = ((InterfaceDataTypeDouble) result[j]).getDoubleData(); m_Plot.setUnconnectedPoint(x[0], x[1], 0); m_Plot.setUnconnectedPoint(pff[0], pff[1], 1); m_Plot.setUnconnectedPoint(2, 2, 2); @@ -241,7 +242,9 @@ public class TestESCrossover implements java.io.Serializable { } }; - /** This method will test the crossover operator + /** + * This method will test the crossover operator + * * @param args */ public static void main(String[] args) { @@ -253,27 +256,35 @@ public class TestESCrossover implements java.io.Serializable { public void setCrossover(InterfaceCrossover NumberOfCrossovers) { this.m_Crossover = NumberOfCrossovers; } + public InterfaceCrossover getCrossover() { return this.m_Crossover; } + public String crossoverTipText() { return "Choose the crossovers operator."; } + public void setNumberOfCrossovers(int NumberOfCrossovers) { this.m_NumberOfCrossovers = NumberOfCrossovers; } + public int getNumberOfCrossovers() { return this.m_NumberOfCrossovers; } + public String numberOfCrossoversTipText() { return "The number of crossovers, that are to be performed."; } + public void setNumberOfPartners(int NumberOfCrossovers) { this.m_NumberOfPartners = NumberOfCrossovers; } + public int getNumberOfPartners() { return this.m_NumberOfPartners; } + public String numberOfPartnersTipText() { return "The number of partners, that are used."; } diff --git a/src/eva2/optimization/operator/distancemetric/DoubleIntegralMetric.java b/src/eva2/optimization/operator/distancemetric/DoubleIntegralMetric.java index 90635bc5..b1ef6547 100644 --- a/src/eva2/optimization/operator/distancemetric/DoubleIntegralMetric.java +++ b/src/eva2/optimization/operator/distancemetric/DoubleIntegralMetric.java @@ -3,37 +3,37 @@ package eva2.optimization.operator.distancemetric; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.tools.EVAERROR; import eva2.tools.math.Mathematics; + import java.io.Serializable; /** - * Calculate the euclidean difference between discrete integrals, which is - * d(x,y)=sqrt(sum_i=1^n(((sum_j=1^i(x_j))-(sum_j=1^i(y_j)))^2)). - * + * Calculate the euclidean difference between discrete integrals, which is + * d(x,y)=sqrt(sum_i=1^n(((sum_j=1^i(x_j))-(sum_j=1^i(y_j)))^2)). + *

* This can be used with any individual type that implements getDoublePositionShallow. - * - * @see AbstractEAIndividual.getDoublePositionShallow(AbstractEAIndividual) - * - * @author mkron * + * @author mkron + * @see AbstractEAIndividual.getDoublePositionShallow(AbstractEAIndividual) */ public class DoubleIntegralMetric implements InterfaceDistanceMetric, Serializable { - boolean oneNormed = true; // if true, the vectors are normed to unity sum before comparison. + boolean oneNormed = true; // if true, the vectors are normed to unity sum before comparison. // String indyDataKey=null; - - public DoubleIntegralMetric() {} - - public DoubleIntegralMetric(boolean normed) { - oneNormed = normed; - } - + + public DoubleIntegralMetric() { + } + + public DoubleIntegralMetric(boolean normed) { + oneNormed = normed; + } + @Override public Object clone() { - return new DoubleIntegralMetric(oneNormed); + return new DoubleIntegralMetric(oneNormed); } @Override public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double[] dIndy1=null, dIndy2=null; + double[] dIndy1 = null, dIndy2 = null; // String indyDataKey = ParticleSwarmOptimization.partBestPosKey; // if (indyDataKey!=null && (indyDataKey.length()>0)) { // try { @@ -41,53 +41,55 @@ public class DoubleIntegralMetric implements InterfaceDistanceMetric, Serializab // dIndy2 = (double[]) indy2.getData(indyDataKey); // } catch (Exception e) {dIndy1=null;} // } else dIndy1=null; - - if (dIndy1==null|| dIndy2==null) { - dIndy1 = AbstractEAIndividual.getDoublePositionShallow(indy1); - dIndy2 = AbstractEAIndividual.getDoublePositionShallow(indy2); - } - if (oneNormed) { - double l1 = Mathematics.sum(dIndy1); - double l2 = Mathematics.sum(dIndy2); - if (l1!=1. || l2!=1.) { // norming really necessary - if (l1==0 || l2==0) { - EVAERROR.errorMsgOnce("Warning, double vector with zero sum will yield infinite distances in " + this.getClass()); - } - dIndy1 = Mathematics.svDiv(l1, dIndy1); - dIndy2 = Mathematics.svDiv(l2, dIndy2); - } - } - - double sum1=0, sum2=0; - double tmpDiff=0, sqrDiffSum=0; + if (dIndy1 == null || dIndy2 == null) { + dIndy1 = AbstractEAIndividual.getDoublePositionShallow(indy1); + dIndy2 = AbstractEAIndividual.getDoublePositionShallow(indy2); + } + + if (oneNormed) { + double l1 = Mathematics.sum(dIndy1); + double l2 = Mathematics.sum(dIndy2); + if (l1 != 1. || l2 != 1.) { // norming really necessary + if (l1 == 0 || l2 == 0) { + EVAERROR.errorMsgOnce("Warning, double vector with zero sum will yield infinite distances in " + this.getClass()); + } + dIndy1 = Mathematics.svDiv(l1, dIndy1); + dIndy2 = Mathematics.svDiv(l2, dIndy2); + } + } + + double sum1 = 0, sum2 = 0; + double tmpDiff = 0, sqrDiffSum = 0; // System.out.println(Mathematics.sum(dIndy1)); // System.out.println(Mathematics.sum(dIndy2)); - for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { - sum1+=dIndy1[i]; - sum2+=dIndy2[i]; - tmpDiff=(sum1-sum2); - sqrDiffSum+=(tmpDiff*tmpDiff); - } - return Math.sqrt(sqrDiffSum); + for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { + sum1 += dIndy1[i]; + sum2 += dIndy2[i]; + tmpDiff = (sum1 - sum2); + sqrDiffSum += (tmpDiff * tmpDiff); + } + return Math.sqrt(sqrDiffSum); } public String getName() { - return "Real-valued integral metric"; + return "Real-valued integral metric"; } - + public static String globalInfo() { - return "A simple integral metric for real-valued types."; + return "A simple integral metric for real-valued types."; } - + public boolean isOneNormed() { - return oneNormed; - } - public void setOneNormed(boolean normedByLength) { - this.oneNormed = normedByLength; - } - public String oneNormedTipText() { - return "If true, both vectors are normed to unity sum before comparison."; - } - + return oneNormed; + } + + public void setOneNormed(boolean normedByLength) { + this.oneNormed = normedByLength; + } + + public String oneNormedTipText() { + return "If true, both vectors are normed to unity sum before comparison."; + } + } diff --git a/src/eva2/optimization/operator/distancemetric/EuclideanMetric.java b/src/eva2/optimization/operator/distancemetric/EuclideanMetric.java index 7e04f884..e687ff13 100644 --- a/src/eva2/optimization/operator/distancemetric/EuclideanMetric.java +++ b/src/eva2/optimization/operator/distancemetric/EuclideanMetric.java @@ -2,57 +2,57 @@ package eva2.optimization.operator.distancemetric; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeDouble; + import java.io.Serializable; /** * The Euclidean metric just measures the Euclidean distance based on the default double representation * as given by AbstractEAIndividual.getDoublePosition(AbstractEAIndividual). - * - * @see AbstractEAIndividual.getDoublePosition(AbstractEAIndividual) - * @author mkron * + * @author mkron + * @see AbstractEAIndividual.getDoublePosition(AbstractEAIndividual) */ public class EuclideanMetric implements InterfaceDistanceMetric, Serializable { - private boolean normedByDblRange = false; - + private boolean normedByDblRange = false; + @Override - public Object clone() { - return (Object) new EuclideanMetric(this); - } + public Object clone() { + return (Object) new EuclideanMetric(this); + } - public EuclideanMetric(EuclideanMetric a) { - this.setNormedByDblRange(a.isNormedByDblRange()); - } + public EuclideanMetric(EuclideanMetric a) { + this.setNormedByDblRange(a.isNormedByDblRange()); + } - public EuclideanMetric() { - } + public EuclideanMetric() { + } + + public EuclideanMetric(boolean normed) { + setNormedByDblRange(normed); + } - public EuclideanMetric(boolean normed) { - setNormedByDblRange(normed); - } - @Override - public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double[] dIndy1, dIndy2; - double result = 0; - dIndy1 = AbstractEAIndividual.getDoublePositionShallow(indy1); - dIndy2 = AbstractEAIndividual.getDoublePositionShallow(indy2); - if (isNormedByDblRange()) { - double[][] range1 = ((InterfaceDataTypeDouble)indy1).getDoubleRange(); - double[][] range2 = ((InterfaceDataTypeDouble)indy2).getDoubleRange(); - return normedEuclideanDistance(dIndy1, range1, dIndy2, range2); - } else { - for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { - result += Math.pow((dIndy1[i] - dIndy2[i]), 2); - } - return Math.sqrt(result); - } - } - + public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { + double[] dIndy1, dIndy2; + double result = 0; + dIndy1 = AbstractEAIndividual.getDoublePositionShallow(indy1); + dIndy2 = AbstractEAIndividual.getDoublePositionShallow(indy2); + if (isNormedByDblRange()) { + double[][] range1 = ((InterfaceDataTypeDouble) indy1).getDoubleRange(); + double[][] range2 = ((InterfaceDataTypeDouble) indy2).getDoubleRange(); + return normedEuclideanDistance(dIndy1, range1, dIndy2, range2); + } else { + for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { + result += Math.pow((dIndy1[i] - dIndy2[i]), 2); + } + return Math.sqrt(result); + } + } + /** * The euclidean distance normed by the given ranges lying between 0 and sqrt(n) * for n dimensions. - * + * * @param pos1 * @param range1 * @param pos2 @@ -60,54 +60,61 @@ public class EuclideanMetric implements InterfaceDistanceMetric, Serializable { * @return */ public static double normedEuclideanDistance(double[] pos1, double[][] range1, double[] pos2, double[][] range2) { - double tmpResult = 0, tmp=0; + double tmpResult = 0, tmp = 0; - for (int i = 0; (i < pos1.length) && (i < pos2.length); i++) { - tmp=((pos1[i] - range1[i][0])/(range1[i][1] - range1[i][0])) - ((pos2[i] - range2[i][0])/(range2[i][1] - range2[i][0])); - tmpResult += (tmp*tmp); - } - return Math.sqrt(tmpResult); + for (int i = 0; (i < pos1.length) && (i < pos2.length); i++) { + tmp = ((pos1[i] - range1[i][0]) / (range1[i][1] - range1[i][0])) - ((pos2[i] - range2[i][0]) / (range2[i][1] - range2[i][0])); + tmpResult += (tmp * tmp); + } + return Math.sqrt(tmpResult); } - + public static double squaredEuclideanDistance(double[] v1, double[] v2) { - double tmp, result = 0; + double tmp, result = 0; for (int i = 0; (i < v1.length) && (i < v2.length); i++) { - tmp=v1[i] - v2[i]; - result += (tmp*tmp); + tmp = v1[i] - v2[i]; + result += (tmp * tmp); } return result; } - + public static double euclideanDistance(double[] v1, double[] v2) { - double result = 0, tmp=0; + double result = 0, tmp = 0; for (int i = 0; (i < v1.length) && (i < v2.length); i++) { - tmp = v1[i] - v2[i]; - result += (tmp*tmp); + tmp = v1[i] - v2[i]; + result += (tmp * tmp); } return Math.sqrt(result); } - - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "The euclidean metric calculates euclidian distances for individuals which have a real valued interpretation."; - } - /** This method will return a naming String - * @return The name of the algorithm - */ - public String getName() { - return "Euclidean Metric"; - } - public void setNormedByDblRange(boolean normedByDblRange) { - this.normedByDblRange = normedByDblRange; - } - public boolean isNormedByDblRange() { - return normedByDblRange; - } - public String normedByDblRangeTipText() { - return "Set to true to norm the distance by the double range - only possible with InterfaceDataTypeDouble individuals."; - } + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "The euclidean metric calculates euclidian distances for individuals which have a real valued interpretation."; + } + + /** + * This method will return a naming String + * + * @return The name of the algorithm + */ + public String getName() { + return "Euclidean Metric"; + } + + public void setNormedByDblRange(boolean normedByDblRange) { + this.normedByDblRange = normedByDblRange; + } + + public boolean isNormedByDblRange() { + return normedByDblRange; + } + + public String normedByDblRangeTipText() { + return "Set to true to norm the distance by the double range - only possible with InterfaceDataTypeDouble individuals."; + } } diff --git a/src/eva2/optimization/operator/distancemetric/GenotypeMetricBitSet.java b/src/eva2/optimization/operator/distancemetric/GenotypeMetricBitSet.java index 792837a9..f37da77a 100644 --- a/src/eva2/optimization/operator/distancemetric/GenotypeMetricBitSet.java +++ b/src/eva2/optimization/operator/distancemetric/GenotypeMetricBitSet.java @@ -3,9 +3,11 @@ package eva2.optimization.operator.distancemetric; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceGAIndividual; + import java.util.BitSet; -/** Distance based on a bit-set if any. +/** + * Distance based on a bit-set if any. * Created by IntelliJ IDEA. * User: streiche * Date: 27.04.2003 @@ -25,22 +27,24 @@ public class GenotypeMetricBitSet implements InterfaceDistanceMetric, java.io.Se return (Object) new GenotypeMetricBitSet(this); } - /** This method allows you to compute the distance between two individuals. + /** + * This method allows you to compute the distance between two individuals. * Depending on the metric this method may reject some types of individuals. * The default return value would be 1.0. - * @param indy1 The first individual. - * @param indy2 The second individual. + * + * @param indy1 The first individual. + * @param indy2 The second individual. * @return double */ @Override public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - return GenotypeMetricBitSet.dist(indy1, indy2); + return GenotypeMetricBitSet.dist(indy1, indy2); } - + public static double dist(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - BitSet dIndy1, dIndy2; - double result = 0; - int length = 0; + BitSet dIndy1, dIndy2; + double result = 0; + int length = 0; if ((indy1 instanceof InterfaceGAIndividual) && (indy2 instanceof InterfaceGAIndividual)) { dIndy1 = ((InterfaceGAIndividual) indy1).getBGenotype(); @@ -53,23 +57,27 @@ public class GenotypeMetricBitSet implements InterfaceDistanceMetric, java.io.Se for (int i = 0; i < length; i++) { if (dIndy1.get(i) == dIndy2.get(i)) { result += 0; - } - else { + } else { result += 1; } } - return result/(double)length; + return result / (double) length; } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a genotype based distance metric suited for binary data. The hamming distance is computed and normalized by chromosome length."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/distancemetric/IndividualDataMetric.java b/src/eva2/optimization/operator/distancemetric/IndividualDataMetric.java index 55bb27a1..ace5f406 100644 --- a/src/eva2/optimization/operator/distancemetric/IndividualDataMetric.java +++ b/src/eva2/optimization/operator/distancemetric/IndividualDataMetric.java @@ -3,106 +3,112 @@ package eva2.optimization.operator.distancemetric; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.strategies.ParticleSwarmOptimization; import eva2.tools.EVAERROR; + import java.io.Serializable; /** * Define a metric on data stored within individuals, such as the personal best position * in PSO. The metric tries to set the stored data as double position to an indy clone. * On these clones, the base metric is applied. - * - * @author mkron * + * @author mkron */ public class IndividualDataMetric implements InterfaceDistanceMetric, Serializable { - private String dataKey = ParticleSwarmOptimization.partBestPosKey; -// private boolean normedDistance = true; // flag whether to use normed distances (for InterfaceDataTypeDouble) - private InterfaceDistanceMetric baseMetric = new EuclideanMetric(true); - - public IndividualDataMetric() {} - - public IndividualDataMetric(String key) { - dataKey = key; - } - - public IndividualDataMetric(String key, InterfaceDistanceMetric bMetric) { - dataKey = key; - setBaseMetric(bMetric); - } - - public IndividualDataMetric(IndividualDataMetric o) { - this.dataKey = o.dataKey; -// this.normedDistance = o.normedDistance; - this.setBaseMetric(o.getBaseMetric()); - } + private String dataKey = ParticleSwarmOptimization.partBestPosKey; + // private boolean normedDistance = true; // flag whether to use normed distances (for InterfaceDataTypeDouble) + private InterfaceDistanceMetric baseMetric = new EuclideanMetric(true); - /** This method allows you to make a deep clone of + public IndividualDataMetric() { + } + + public IndividualDataMetric(String key) { + dataKey = key; + } + + public IndividualDataMetric(String key, InterfaceDistanceMetric bMetric) { + dataKey = key; + setBaseMetric(bMetric); + } + + public IndividualDataMetric(IndividualDataMetric o) { + this.dataKey = o.dataKey; +// this.normedDistance = o.normedDistance; + this.setBaseMetric(o.getBaseMetric()); + } + + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override public Object clone() { - return new IndividualDataMetric(this); + return new IndividualDataMetric(this); } - + @Override - public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - if (dataKey==null) { - throw new RuntimeException("Error, no data key defined in " + this.getClass().getName() + "::distance()"); - } - else { - Object data1 = indy1.getData(dataKey); - Object data2 = indy2.getData(dataKey); - if (data1 instanceof double[] && (data2 instanceof double[])) { - AbstractEAIndividual dataIndy1 = (AbstractEAIndividual) indy1.clone(); - AbstractEAIndividual.setDoublePosition(dataIndy1, (double[]) data1); - AbstractEAIndividual dataIndy2 = (AbstractEAIndividual) indy2.clone(); - AbstractEAIndividual.setDoublePosition(dataIndy2, (double[]) data2); - return getBaseMetric().distance(dataIndy1, dataIndy2); + public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { + if (dataKey == null) { + throw new RuntimeException("Error, no data key defined in " + this.getClass().getName() + "::distance()"); + } else { + Object data1 = indy1.getData(dataKey); + Object data2 = indy2.getData(dataKey); + if (data1 instanceof double[] && (data2 instanceof double[])) { + AbstractEAIndividual dataIndy1 = (AbstractEAIndividual) indy1.clone(); + AbstractEAIndividual.setDoublePosition(dataIndy1, (double[]) data1); + AbstractEAIndividual dataIndy2 = (AbstractEAIndividual) indy2.clone(); + AbstractEAIndividual.setDoublePosition(dataIndy2, (double[]) data2); + return getBaseMetric().distance(dataIndy1, dataIndy2); // if (normedDistance) { // double[][] range1 = ((InterfaceDataTypeDouble)indy1).getDoubleRange(); // double[][] range2 = ((InterfaceDataTypeDouble)indy2).getDoubleRange(); // return EuclideanMetric.normedEuclideanDistance((double[])data1, range1, (double[])data2, range2); // } else return EuclideanMetric.euclideanDistance((double[])data1, (double[])data2); - } else { - EVAERROR.errorMsgOnce("Error, invalid key data, double array required by " + this.getClass().getName()); - EVAERROR.errorMsgOnce("Using PhenotypeMetric as Backup..."); - return (new PhenotypeMetric().distance(indy1, indy2)); + } else { + EVAERROR.errorMsgOnce("Error, invalid key data, double array required by " + this.getClass().getName()); + EVAERROR.errorMsgOnce("Using PhenotypeMetric as Backup..."); + return (new PhenotypeMetric().distance(indy1, indy2)); // throw new RuntimeException("Invalid data key, double array required by " + this.getClass().getName()); - } - } - } + } + } + } - public String dataKeyTipText() { - return "Name of the data key to use to retrieve individual data (double[] for now)."; - } - public String getDataKey() { - return dataKey; - } - public void setDataKey(String dataKey) { - this.dataKey = dataKey; - } + public String dataKeyTipText() { + return "Name of the data key to use to retrieve individual data (double[] for now)."; + } - public String normedDistanceTipText() { - return "Flag whether to use euclidean distance directly or normed by the double range."; - } + public String getDataKey() { + return dataKey; + } + + public void setDataKey(String dataKey) { + this.dataKey = dataKey; + } + + public String normedDistanceTipText() { + return "Flag whether to use euclidean distance directly or normed by the double range."; + } // public boolean isNormedDistance() { // return normedDistance; // } // public void setNormedDistance(boolean normedDistance) { // this.normedDistance = normedDistance; // } - - public static String globalInfo() { - return "Uses individual object data (so far only double[]) to calculate the distance."; - } - public void setBaseMetric(InterfaceDistanceMetric baseMetric) { - this.baseMetric = baseMetric; - } - public InterfaceDistanceMetric getBaseMetric() { - return baseMetric; - } - public String baseMetricTipText() { - return "The metric to be used on the stored data objects."; - } + public static String globalInfo() { + return "Uses individual object data (so far only double[]) to calculate the distance."; + } + + public void setBaseMetric(InterfaceDistanceMetric baseMetric) { + this.baseMetric = baseMetric; + } + + public InterfaceDistanceMetric getBaseMetric() { + return baseMetric; + } + + public String baseMetricTipText() { + return "The metric to be used on the stored data objects."; + } } diff --git a/src/eva2/optimization/operator/distancemetric/InterfaceDistanceMetric.java b/src/eva2/optimization/operator/distancemetric/InterfaceDistanceMetric.java index debcbacd..7f8890d0 100644 --- a/src/eva2/optimization/operator/distancemetric/InterfaceDistanceMetric.java +++ b/src/eva2/optimization/operator/distancemetric/InterfaceDistanceMetric.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.distancemetric; import eva2.optimization.individuals.AbstractEAIndividual; -/** This metric methods is experimental and should be moved to the +/** + * This metric methods is experimental and should be moved to the * optimization problem to allow problem specific distance metrics * between individuals. * Created by IntelliJ IDEA. @@ -14,17 +15,21 @@ import eva2.optimization.individuals.AbstractEAIndividual; */ public interface InterfaceDistanceMetric { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method allows you to compute the distance between two individuals. + /** + * This method allows you to compute the distance between two individuals. * Depending on the metric this method may reject some types of individuals. * The default return value would be one. - * @param indy1 The first individual. - * @param indy2 The second individual. + * + * @param indy1 The first individual. + * @param indy2 The second individual. * @return double */ public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2); diff --git a/src/eva2/optimization/operator/distancemetric/ObjectiveSpaceMetric.java b/src/eva2/optimization/operator/distancemetric/ObjectiveSpaceMetric.java index 1c354020..2a78a2d0 100644 --- a/src/eva2/optimization/operator/distancemetric/ObjectiveSpaceMetric.java +++ b/src/eva2/optimization/operator/distancemetric/ObjectiveSpaceMetric.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.distancemetric; import eva2.optimization.individuals.AbstractEAIndividual; -/** Objective space metric suited for multi-objective optimization. +/** + * Objective space metric suited for multi-objective optimization. * Created by IntelliJ IDEA. * User: streiche * Date: 04.08.2003 @@ -22,17 +23,19 @@ public class ObjectiveSpaceMetric implements InterfaceDistanceMetric, java.io.Se return (Object) new ObjectiveSpaceMetric(this); } - /** This method allows you to compute the distance between two individuals. + /** + * This method allows you to compute the distance between two individuals. * Depending on the metric this method may reject some types of individuals. * The default return value would be 1.0. - * @param indy1 The first individual. - * @param indy2 The second individual. + * + * @param indy1 The first individual. + * @param indy2 The second individual. * @return double */ @Override public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double[] dIndy1, dIndy2; - double result = 0; + double[] dIndy1, dIndy2; + double result = 0; dIndy1 = indy1.getFitness(); dIndy2 = indy2.getFitness(); @@ -45,13 +48,18 @@ public class ObjectiveSpaceMetric implements InterfaceDistanceMetric, java.io.Se /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The objective space metric calculates euclidian distances on the fitness vectors."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/distancemetric/PhenotypeMetric.java b/src/eva2/optimization/operator/distancemetric/PhenotypeMetric.java index 47fc32de..4546946a 100644 --- a/src/eva2/optimization/operator/distancemetric/PhenotypeMetric.java +++ b/src/eva2/optimization/operator/distancemetric/PhenotypeMetric.java @@ -1,7 +1,6 @@ package eva2.optimization.operator.distancemetric; - import eva2.gui.BeanInspector; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeBinary; @@ -9,18 +8,19 @@ import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.individuals.InterfaceDataTypeInteger; import eva2.optimization.individuals.InterfaceDataTypePermutation; import eva2.optimization.individuals.InterfaceDataTypeProgram; + import java.util.BitSet; -/** +/** * A phenotype metric suited for the most common data types. - * + *

* User: streiche * Date: 19.07.2005 */ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Serializable { - private static PhenotypeMetric pMetric = null; - private static GenotypeMetricBitSet bitMetric = null; - + private static PhenotypeMetric pMetric = null; + private static GenotypeMetricBitSet bitMetric = null; + public PhenotypeMetric() { } @@ -36,26 +36,26 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali return Math.min(Math.min(a, b), c); } - private static int computeLevenshteinDistance (String s, String t) { - int d[][]; // matrix - int n; // length of s - int m; // length of t - int i; // iterates through s - int j; // iterates through t - char s_i; // ith character of s - char t_j; // jth character of t - int cost; // cost + private static int computeLevenshteinDistance(String s, String t) { + int d[][]; // matrix + int n; // length of s + int m; // length of t + int i; // iterates through s + int j; // iterates through t + char s_i; // ith character of s + char t_j; // jth character of t + int cost; // cost // Step 1 - n = s.length (); - m = t.length (); + n = s.length(); + m = t.length(); if (n == 0) { return m; } if (m == 0) { return n; } - d = new int[n+1][m+1]; + d = new int[n + 1][m + 1]; // Step 2 for (i = 0; i <= n; i++) { @@ -67,37 +67,37 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali // Step 3 for (i = 1; i <= n; i++) { - s_i = s.charAt (i - 1); + s_i = s.charAt(i - 1); // Step 4 for (j = 1; j <= m; j++) { - t_j = t.charAt (j - 1); + t_j = t.charAt(j - 1); // Step 5 if (s_i == t_j) { cost = 0; - } - else { + } else { // @todo cost = 1; } // Step 6 - d[i][j] = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost); + d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); } } // Step 7 return d[n][m]; } - /** + /** * This method allows you to compute the distance between two individuals. * Depending on the metric this method may reject some types of individuals. * The default return value would be 1.0. - * @param indy1 The first individual. - * @param indy2 The second individual. + * + * @param indy1 The first individual. + * @param indy2 The second individual. * @return double */ @Override public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double result = 0; + double result = 0; // results are added up because individuals can implement several data types! if ((indy1 instanceof InterfaceDataTypeBinary) && (indy2 instanceof InterfaceDataTypeBinary)) { if (bitMetric == null) { @@ -106,135 +106,143 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali result += bitMetric.distance(indy1, indy2); } if ((indy1 instanceof InterfaceDataTypeInteger) && (indy2 instanceof InterfaceDataTypeInteger)) { - int[] d1,d2; + int[] d1, d2; int[][] r1, r2; - double tmpResult = 0; + double tmpResult = 0; d1 = ((InterfaceDataTypeInteger) indy1).getIntegerData(); r1 = ((InterfaceDataTypeInteger) indy1).getIntRange(); d2 = ((InterfaceDataTypeInteger) indy2).getIntegerData(); r2 = ((InterfaceDataTypeInteger) indy2).getIntRange(); for (int i = 0; (i < d1.length) && (i < d2.length); i++) { - tmpResult += Math.pow(((d1[i] - r1[i][0])/((double)(r1[i][1]-r1[i][0]))) - ( (d2[i] - r2[i][0])/((double)(r2[i][1]-r2[i][0]))), 2); + tmpResult += Math.pow(((d1[i] - r1[i][0]) / ((double) (r1[i][1] - r1[i][0]))) - ((d2[i] - r2[i][0]) / ((double) (r2[i][1] - r2[i][0]))), 2); //tmpResult += Math.abs(d1[i] - d2[i])/((double)(r1[i][1]-r1[i][0])); } result += Math.sqrt(tmpResult); } if ((indy1 instanceof InterfaceDataTypeDouble) && (indy2 instanceof InterfaceDataTypeDouble)) { - double[] d1, d2; - double[][] r1, r2; - double tmpResult = 0, tmp=0; + double[] d1, d2; + double[][] r1, r2; + double tmpResult = 0, tmp = 0; d1 = ((InterfaceDataTypeDouble) indy1).getDoubleData(); // TODO WithoutUpdate would be much quicker - but in which cases is it up to date? r1 = ((InterfaceDataTypeDouble) indy1).getDoubleRange(); d2 = ((InterfaceDataTypeDouble) indy2).getDoubleData(); r2 = ((InterfaceDataTypeDouble) indy2).getDoubleRange(); for (int i = 0; (i < d1.length) && (i < d2.length); i++) { - tmp=((d1[i] - r1[i][0])/(r1[i][1] - r1[i][0])) - ((d2[i] - r2[i][0])/(r2[i][1] - r2[i][0])); - tmpResult += (tmp*tmp); + tmp = ((d1[i] - r1[i][0]) / (r1[i][1] - r1[i][0])) - ((d2[i] - r2[i][0]) / (r2[i][1] - r2[i][0])); + tmpResult += (tmp * tmp); } result += Math.sqrt(tmpResult); } if ((indy1 instanceof InterfaceDataTypePermutation) && (indy2 instanceof InterfaceDataTypePermutation)) { - int[] dIndy1, dIndy2; - String s1 = "", s2 = ""; + int[] dIndy1, dIndy2; + String s1 = "", s2 = ""; // double tmpResult = 0; for (int p = 0; p < ((InterfaceDataTypePermutation) indy1).getPermutationData().length; p++) { - dIndy1 = ((InterfaceDataTypePermutation) indy1).getPermutationData()[p]; - dIndy2 = ((InterfaceDataTypePermutation) indy2).getPermutationData()[p]; - for (int i = 0; i < dIndy1.length; i++) { + dIndy1 = ((InterfaceDataTypePermutation) indy1).getPermutationData()[p]; + dIndy2 = ((InterfaceDataTypePermutation) indy2).getPermutationData()[p]; + for (int i = 0; i < dIndy1.length; i++) { s1 += dIndy1[i]; } - for (int i = 0; i < dIndy2.length; i++) { + for (int i = 0; i < dIndy2.length; i++) { s2 += dIndy2[i]; } - result += PhenotypeMetric.computeLevenshteinDistance(s1, s2)/((double)Math.max(s1.length(), s2.length())); + result += PhenotypeMetric.computeLevenshteinDistance(s1, s2) / ((double) Math.max(s1.length(), s2.length())); } } if ((indy1 instanceof InterfaceDataTypeProgram) && (indy2 instanceof InterfaceDataTypeProgram)) { - String s1, s2; - int l1; - l1 = Math.min(((InterfaceDataTypeProgram)indy1).getProgramData().length, ((InterfaceDataTypeProgram)indy2).getProgramData().length); + String s1, s2; + int l1; + l1 = Math.min(((InterfaceDataTypeProgram) indy1).getProgramData().length, ((InterfaceDataTypeProgram) indy2).getProgramData().length); for (int i = 0; i < l1; i++) { - s1 = ((InterfaceDataTypeProgram)indy1).getProgramData()[i].getStringRepresentation(); - s2 = ((InterfaceDataTypeProgram)indy2).getProgramData()[i].getStringRepresentation(); - result += PhenotypeMetric.computeLevenshteinDistance(s1, s2)/((double)Math.max(s1.length(), s2.length())); + s1 = ((InterfaceDataTypeProgram) indy1).getProgramData()[i].getStringRepresentation(); + s2 = ((InterfaceDataTypeProgram) indy2).getProgramData()[i].getStringRepresentation(); + result += PhenotypeMetric.computeLevenshteinDistance(s1, s2) / ((double) Math.max(s1.length(), s2.length())); } } return result; } - - /** This method allows you to compute the distance between two individuals. + + /** + * This method allows you to compute the distance between two individuals. * Depending on the metric this method may reject some types of individuals. * The default return value would be 1.0. - * @param indy1 The first individual. - * @param indy2 The second individual. + * + * @param indy1 The first individual. + * @param indy2 The second individual. * @return double */ public static double dist(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - if (pMetric == null) { + if (pMetric == null) { pMetric = new PhenotypeMetric(); } - return pMetric.distance(indy1, indy2); + return pMetric.distance(indy1, indy2); } public static double norm(AbstractEAIndividual indy) { - double result = 0; + double result = 0; if (indy instanceof InterfaceDataTypeBinary) { - BitSet bs = (BitSet)((InterfaceDataTypeBinary)indy).getBinaryData(); - for (int i = 0; (i < ((InterfaceDataTypeBinary)indy).size()) ; i++) { + BitSet bs = (BitSet) ((InterfaceDataTypeBinary) indy).getBinaryData(); + for (int i = 0; (i < ((InterfaceDataTypeBinary) indy).size()); i++) { if (bs.get(i)) { - result += 1; - } + result += 1; + } } - result /= ((InterfaceDataTypeBinary)indy).size(); - return result; + result /= ((InterfaceDataTypeBinary) indy).size(); + return result; } if (indy instanceof InterfaceDataTypeInteger) { - int[] d1 = ((InterfaceDataTypeInteger) indy).getIntegerData(); + int[] d1 = ((InterfaceDataTypeInteger) indy).getIntegerData(); for (int i = 0; i < d1.length; i++) { - result += d1[i]; - } - return result/d1.length; + result += d1[i]; + } + return result / d1.length; } if (indy instanceof InterfaceDataTypeDouble) { - result = norm(((InterfaceDataTypeDouble) indy).getDoubleData()); - return result; + result = norm(((InterfaceDataTypeDouble) indy).getDoubleData()); + return result; } if (indy instanceof InterfaceDataTypePermutation) { - // TODO hard to find a norm for permutations. As we use the levenshtein distance metric, - // the normed distance to the empty permutaton is always one... + // TODO hard to find a norm for permutations. As we use the levenshtein distance metric, + // the normed distance to the empty permutaton is always one... return 1; } if (indy instanceof InterfaceDataTypeProgram) { - // TODO same as for permutations + // TODO same as for permutations return 1; } System.err.println("error: unknown individual interface in PhenotypeMetric::norm " + BeanInspector.toString(indy)); return 0; } - + /** * Calculates the 2 norm of a given vector. + * * @param v1 * @return */ public static double norm(double[] v1) { - double result = 0; + double result = 0; for (int i = 0; i < v1.length; i++) { - result += Math.pow(v1[i], 2); + result += Math.pow(v1[i], 2); } return Math.sqrt(result); } - + /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a phenotype based metric which can be applied to binary, integer, double, permutation, and program data types. For the latter two, the Levenshtein distance is computed. All distance values are normed."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/distancemetric/SigmaSingleMetricGlobalMutation.java b/src/eva2/optimization/operator/distancemetric/SigmaSingleMetricGlobalMutation.java index 6d91ea5f..ed6ff897 100644 --- a/src/eva2/optimization/operator/distancemetric/SigmaSingleMetricGlobalMutation.java +++ b/src/eva2/optimization/operator/distancemetric/SigmaSingleMetricGlobalMutation.java @@ -4,8 +4,9 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.operator.mutation.MutateESGlobal; -/** This method includes the sigma as distance element. - * This can be used to make the CBN-EA self-adaptive +/** + * This method includes the sigma as distance element. + * This can be used to make the CBN-EA self-adaptive * at least on real-valued search spaces together * with the correct mutation operator. I guess this * could be a paper, but I'm so lazy right now. @@ -28,18 +29,20 @@ public class SigmaSingleMetricGlobalMutation implements InterfaceDistanceMetric, return (Object) new SigmaSingleMetricGlobalMutation(this); } - /** This method allows you to compute the distance between two individuals. + /** + * This method allows you to compute the distance between two individuals. * Depending on the metric this method may reject some types of individuals. * The default return value would be 1.0. - * @param indy1 The first individual. - * @param indy2 The second individual. + * + * @param indy1 The first individual. + * @param indy2 The second individual. * @return double */ @Override public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double[] dIndy1, dIndy2; - double[][] range1, range2; - double result = 0; + double[] dIndy1, dIndy2; + double[][] range1, range2; + double result = 0; if ((indy1.getMutationOperator() instanceof MutateESGlobal) && (indy2.getMutationOperator() instanceof MutateESGlobal)) { MutateESGlobal mutator1, mutator2; @@ -51,11 +54,11 @@ public class SigmaSingleMetricGlobalMutation implements InterfaceDistanceMetric, dIndy2 = ((InterfaceDataTypeDouble) indy2).getDoubleData(); range2 = ((InterfaceDataTypeDouble) indy2).getDoubleRange(); for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { - result += Math.pow(((dIndy1[i] - range1[i][0])/(range1[i][1] - range1[i][0])) - ((dIndy2[i] - range2[i][0])/(range2[i][1] - range2[i][0])), 2); + result += Math.pow(((dIndy1[i] - range1[i][0]) / (range1[i][1] - range1[i][0])) - ((dIndy2[i] - range2[i][0]) / (range2[i][1] - range2[i][0])), 2); } // this is the normalized distance result = Math.sqrt(result); - if (result < Math.max(mutator1.getMutationStepSize(),mutator2.getMutationStepSize())) { + if (result < Math.max(mutator1.getMutationStepSize(), mutator2.getMutationStepSize())) { return 0.0; } return 1.0; @@ -66,13 +69,18 @@ public class SigmaSingleMetricGlobalMutation implements InterfaceDistanceMetric, /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is an experimental method for individuals using global ES mutation."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/fitnessmodifier/FitnessAdaptiveClustering.java b/src/eva2/optimization/operator/fitnessmodifier/FitnessAdaptiveClustering.java index 2c7baaad..9672c324 100644 --- a/src/eva2/optimization/operator/fitnessmodifier/FitnessAdaptiveClustering.java +++ b/src/eva2/optimization/operator/fitnessmodifier/FitnessAdaptiveClustering.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.cluster.ClusteringDensityBased; import eva2.optimization.operator.cluster.InterfaceClustering; import eva2.optimization.population.Population; -/** The fitness modifier are defunct and are to be moved to +/** + * The fitness modifier are defunct and are to be moved to * the selection operators... * Created by IntelliJ IDEA. * User: streiche @@ -15,9 +16,10 @@ import eva2.optimization.population.Population; */ public class FitnessAdaptiveClustering implements java.io.Serializable, InterfaceFitnessModifier { - private InterfaceClustering m_ClusteringAlgorithm = new ClusteringDensityBased(); + private InterfaceClustering m_ClusteringAlgorithm = new ClusteringDensityBased(); - /** This method allows you to modify the fitness of the individuals + /** + * This method allows you to modify the fitness of the individuals * of a population. Note that by altering the fitness you may require * your problem to store the unaltered fitness somewhere else so that * you may still fetch it! @@ -25,12 +27,12 @@ public class FitnessAdaptiveClustering implements java.io.Serializable, Interfac @Override public void modifyFitness(Population population) { // prepare the calculation - double[][] data = new double[population.size()][]; + double[][] data = new double[population.size()][]; for (int i = 0; i < data.length; i++) { - data[i] = ((AbstractEAIndividual)population.get(i)).getFitness(); + data[i] = ((AbstractEAIndividual) population.get(i)).getFitness(); } - double min = Double.POSITIVE_INFINITY; - double[] result = new double[data.length]; + double min = Double.POSITIVE_INFINITY; + double[] result = new double[data.length]; for (int x = 0; x < data[0].length; x++) { for (int i = 0; i < data.length; i++) { @@ -38,28 +40,28 @@ public class FitnessAdaptiveClustering implements java.io.Serializable, Interfac } for (int i = 0; i < data.length; i++) { if (data[i][x] < min) { - min = data[i][x] ; + min = data[i][x]; } } for (int i = 0; i < data.length; i++) { // This will cause the worst individual to have no chance of being selected // also note that if all individual achieve equal fitness the sum will be zero - result[i] = data[i][x] -min + 0.1; + result[i] = data[i][x] - min + 0.1; } this.m_ClusteringAlgorithm.initClustering(population); // Now search for clusters - Population[] ClusterResult = this.m_ClusteringAlgorithm.cluster(population, population); - Population cluster; + Population[] ClusterResult = this.m_ClusteringAlgorithm.cluster(population, population); + Population cluster; for (int i = 1; i < ClusterResult.length; i++) { cluster = ClusterResult[i]; for (int j = 0; j < cluster.size(); j++) { - result[i] /= ((double)cluster.size()); + result[i] /= ((double) cluster.size()); } } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetFitness(x, result[i]); + ((AbstractEAIndividual) population.get(i)).SetFitness(x, result[i]); } } } @@ -67,23 +69,29 @@ public class FitnessAdaptiveClustering implements java.io.Serializable, Interfac /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a normation method based on Fitness Sharing. It adds a penalty for too similar individuals on the standard Normation method."; } - /** This method allows you to set/get the clustering method on which the + /** + * This method allows you to set/get the clustering method on which the * species convergence is based. + * * @return The current clustering method */ public InterfaceClustering getClusteringAlgorithm() { return this.m_ClusteringAlgorithm; } - public void setClusteringAlgorithm(InterfaceClustering b){ + + public void setClusteringAlgorithm(InterfaceClustering b) { this.m_ClusteringAlgorithm = b; } + public String clusteringAlgorithmTipText() { return "The Cluster Algorithm on which the adaptive fitness sharing is based."; } diff --git a/src/eva2/optimization/operator/fitnessmodifier/FitnessModifierNone.java b/src/eva2/optimization/operator/fitnessmodifier/FitnessModifierNone.java index f3593f5c..a56e2afb 100644 --- a/src/eva2/optimization/operator/fitnessmodifier/FitnessModifierNone.java +++ b/src/eva2/optimization/operator/fitnessmodifier/FitnessModifierNone.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.fitnessmodifier; import eva2.optimization.population.Population; -/** The fitness modifier are defunct and are to be moved to +/** + * The fitness modifier are defunct and are to be moved to * the selection operators... * Created by IntelliJ IDEA. * User: streiche @@ -12,7 +13,8 @@ import eva2.optimization.population.Population; */ public class FitnessModifierNone implements java.io.Serializable, InterfaceFitnessModifier { - /** This method allows you to modify the fitness of the individuals + /** + * This method allows you to modify the fitness of the individuals * of a population. Note that by altering the fitness you may require * your problem to store the unaltered fitness somewhere else so that * you may still fetch it! @@ -25,15 +27,19 @@ public class FitnessModifierNone implements java.io.Serializable, InterfaceFitne /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "No Fitness Modification"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/fitnessmodifier/FitnessSharing.java b/src/eva2/optimization/operator/fitnessmodifier/FitnessSharing.java index 97033ce7..2813c354 100644 --- a/src/eva2/optimization/operator/fitnessmodifier/FitnessSharing.java +++ b/src/eva2/optimization/operator/fitnessmodifier/FitnessSharing.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric; import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.population.Population; -/** The fitness modifier are defunct and are to be moved to +/** + * The fitness modifier are defunct and are to be moved to * the selection operators... * Created by IntelliJ IDEA. * User: streiche @@ -15,10 +16,11 @@ import eva2.optimization.population.Population; */ public class FitnessSharing implements java.io.Serializable, InterfaceFitnessModifier { - private double m_SharingDistance = 0.05; - private InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); + private double m_SharingDistance = 0.05; + private InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); - /** This method allows you to modify the fitness of the individuals + /** + * This method allows you to modify the fitness of the individuals * of a population. Note that by altering the fitness you may require * your problem to store the unaltered fitness somewhere else so that * you may still fetch it! @@ -26,12 +28,12 @@ public class FitnessSharing implements java.io.Serializable, InterfaceFitnessMod @Override public void modifyFitness(Population population) { // prepare the calculation - double[][] data = new double[population.size()][]; + double[][] data = new double[population.size()][]; for (int i = 0; i < data.length; i++) { - data[i] = ((AbstractEAIndividual)population.get(i)).getFitness(); + data[i] = ((AbstractEAIndividual) population.get(i)).getFitness(); } - double min = Double.POSITIVE_INFINITY, fitnessSharing; - double[] result = new double[data.length]; + double min = Double.POSITIVE_INFINITY, fitnessSharing; + double[] result = new double[data.length]; AbstractEAIndividual tmpIndy; for (int x = 0; x < data[0].length; x++) { @@ -47,22 +49,22 @@ public class FitnessSharing implements java.io.Serializable, InterfaceFitnessMod for (int i = 0; i < data.length; i++) { // This will cause the worst individual to have no chance of being selected // also note that if all individual achieve equal fitness the sum will be zero - result[i] = data[i][x] -min + 0.1; + result[i] = data[i][x] - min + 0.1; } for (int i = 0; i < population.size(); i++) { - tmpIndy = (AbstractEAIndividual)population.get(i); + tmpIndy = (AbstractEAIndividual) population.get(i); fitnessSharing = 0; for (int j = 0; j < population.size(); j++) { - if (this.m_SharingDistance < this.m_Metric.distance(tmpIndy, (AbstractEAIndividual)population.get(j))) { - fitnessSharing += 1 - (this.m_Metric.distance(tmpIndy, (AbstractEAIndividual)population.get(j))/this.m_SharingDistance); + if (this.m_SharingDistance < this.m_Metric.distance(tmpIndy, (AbstractEAIndividual) population.get(j))) { + fitnessSharing += 1 - (this.m_Metric.distance(tmpIndy, (AbstractEAIndividual) population.get(j)) / this.m_SharingDistance); } } result[i] /= fitnessSharing; } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetFitness(x, result[i]); + ((AbstractEAIndividual) population.get(i)).SetFitness(x, result[i]); } } } @@ -70,35 +72,45 @@ public class FitnessSharing implements java.io.Serializable, InterfaceFitnessMod /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a normation method based on Fitness Sharing. It adds a penalty for too similar individuals on the standard Normation method."; } - /** These methods allows you to set/get the Sharing Distance + /** + * These methods allows you to set/get the Sharing Distance + * * @param SharingDistance */ public void setSharingDistance(double SharingDistance) { this.m_SharingDistance = SharingDistance; } + public double getSharingDistance() { return this.m_SharingDistance; } + public String sharingDistanceTipText() { return "The threshold for the similarity penalty."; } - /** These methods allows you to set/get the type of Distance Metric. + /** + * These methods allows you to set/get the type of Distance Metric. + * * @param Metric */ public void setMetric(InterfaceDistanceMetric Metric) { this.m_Metric = Metric; } + public InterfaceDistanceMetric getMetric() { return this.m_Metric; } + public String metricTipText() { return "The distance metric used. Note: This depends on the type of EAIndividual used!"; } diff --git a/src/eva2/optimization/operator/fitnessmodifier/InterfaceFitnessModifier.java b/src/eva2/optimization/operator/fitnessmodifier/InterfaceFitnessModifier.java index c69c89bf..0f63bb16 100644 --- a/src/eva2/optimization/operator/fitnessmodifier/InterfaceFitnessModifier.java +++ b/src/eva2/optimization/operator/fitnessmodifier/InterfaceFitnessModifier.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.fitnessmodifier; import eva2.optimization.population.Population; -/** The fitness modifier are defunct and are to be moved to +/** + * The fitness modifier are defunct and are to be moved to * the selection operators... * Created by IntelliJ IDEA. * User: streiche @@ -12,7 +13,8 @@ import eva2.optimization.population.Population; */ public interface InterfaceFitnessModifier { - /** This method allows you to modify the fitness of the individuals + /** + * This method allows you to modify the fitness of the individuals * of a population. Note that by altering the fitness you may require * your problem to store the unaltered fitness somewhere else so that * you may still fetch it! diff --git a/src/eva2/optimization/operator/initialization/DefaultInitialization.java b/src/eva2/optimization/operator/initialization/DefaultInitialization.java index 2f13d3de..309cfc90 100644 --- a/src/eva2/optimization/operator/initialization/DefaultInitialization.java +++ b/src/eva2/optimization/operator/initialization/DefaultInitialization.java @@ -5,30 +5,30 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; /** * A dummy initialization method which only calls the default init method of the individual. - * - * @author mkron * + * @author mkron */ -public class DefaultInitialization implements InterfaceInitialization, java.io.Serializable { - private static final long serialVersionUID = 1L; +public class DefaultInitialization implements InterfaceInitialization, java.io.Serializable { + private static final long serialVersionUID = 1L; + + public DefaultInitialization() { + } - public DefaultInitialization() {} - @Override - public void initialize(AbstractEAIndividual indy, InterfaceOptimizationProblem problem) { - indy.defaultInit(problem); - } - + public void initialize(AbstractEAIndividual indy, InterfaceOptimizationProblem problem) { + indy.defaultInit(problem); + } + @Override - public InterfaceInitialization clone() { - return new DefaultInitialization(); - } - - public String getName() { - return "DefaultInitialization"; - } - - public String globalInfo() { - return "Uses the standard initialization of the individual implementation"; - } + public InterfaceInitialization clone() { + return new DefaultInitialization(); + } + + public String getName() { + return "DefaultInitialization"; + } + + public String globalInfo() { + return "Uses the standard initialization of the individual implementation"; + } } diff --git a/src/eva2/optimization/operator/initialization/GAGIInitializeSegmentwise.java b/src/eva2/optimization/operator/initialization/GAGIInitializeSegmentwise.java index bae50021..82141b76 100644 --- a/src/eva2/optimization/operator/initialization/GAGIInitializeSegmentwise.java +++ b/src/eva2/optimization/operator/initialization/GAGIInitializeSegmentwise.java @@ -6,6 +6,7 @@ import eva2.optimization.individuals.InterfaceGIIndividual; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.RNG; + import java.util.BitSet; /** @@ -15,82 +16,83 @@ import java.util.BitSet; * For binary individuals, this allows to control the number of bits per segment by * setting the target element to '1'. For * integer individuals, it allows to control the number of occurrences of a certain integer - * per segment. It may also be used to initialize with subsets of integers (by setting 0 + * per segment. It may also be used to initialize with subsets of integers (by setting 0 * elements to a certain type and all to a subset of the range). - * + *

* The initialization may be parameterized in two ways, where each takes a fixed * segment length s. Firstly, a fixed number of bits (k<=s) is set per segment, * so each segment has equal cardinality. * Secondly, an int-array can be specified which defines possibly varying k_i for * each segment i, so different segments may have different cardinality. The array * must comply to the binary genotype length of the problem. The array definition - * has strict priority over the fixed cardinality definition. - * + * has strict priority over the fixed cardinality definition. + * * @author mkron */ public class GAGIInitializeSegmentwise implements InterfaceInitialization, java.io.Serializable { - private static final long serialVersionUID = 1L; - protected int[] bitsPerSegmentArray = new int[0]; - private int bitsPerSegment=1; - private int segmentLength=4; - private int targetElement=1; - private int[] otherElements=new int[]{}; - private double disturbanceDegree=0.0; - - public GAGIInitializeSegmentwise() {} - - public GAGIInitializeSegmentwise(GAGIInitializeSegmentwise o) { - bitsPerSegment = o.bitsPerSegment; - segmentLength = o.segmentLength; - targetElement = o.targetElement; - if (o.otherElements!= null) { - otherElements= new int[o.otherElements.length]; - System.arraycopy(o.otherElements, 0, otherElements, 0, otherElements.length); - } - if (o.bitsPerSegmentArray!=null) { - bitsPerSegmentArray = new int[o.bitsPerSegmentArray.length]; - System.arraycopy(o.bitsPerSegmentArray, 0, bitsPerSegmentArray, 0, bitsPerSegmentArray.length); - } - disturbanceDegree=o.disturbanceDegree; - } - - public GAGIInitializeSegmentwise(int segLen, int bitsPerSeg, double disturbanceRatio) { - segmentLength = segLen; - bitsPerSegmentArray = new int[0]; - bitsPerSegment=bitsPerSeg; - disturbanceDegree=disturbanceRatio; - } - - public GAGIInitializeSegmentwise(int segLen, int[] bitsPerSegArr, double disturbanceRatio) { - segmentLength = segLen; - bitsPerSegmentArray = bitsPerSegArr; - disturbanceDegree=disturbanceRatio; - } - - public GAGIInitializeSegmentwise(int segLen, int[] bitsPerSeg) { - this(segLen, bitsPerSeg, 0); - } - - /** - * Constructor for the integer case defining the target element and other elements. - * - * @param segLen - * @param bitsPerSeg - * @param targetElement - * @param otherElements - */ - public GAGIInitializeSegmentwise(int segLen, int[] bitsPerSeg, int targetElement, int[] otherElements, double disturbRatio) { - segmentLength = segLen; - bitsPerSegmentArray = bitsPerSeg; - this.targetElement = targetElement; - this.otherElements = otherElements; - this.disturbanceDegree = disturbRatio; - } - + private static final long serialVersionUID = 1L; + protected int[] bitsPerSegmentArray = new int[0]; + private int bitsPerSegment = 1; + private int segmentLength = 4; + private int targetElement = 1; + private int[] otherElements = new int[]{}; + private double disturbanceDegree = 0.0; + + public GAGIInitializeSegmentwise() { + } + + public GAGIInitializeSegmentwise(GAGIInitializeSegmentwise o) { + bitsPerSegment = o.bitsPerSegment; + segmentLength = o.segmentLength; + targetElement = o.targetElement; + if (o.otherElements != null) { + otherElements = new int[o.otherElements.length]; + System.arraycopy(o.otherElements, 0, otherElements, 0, otherElements.length); + } + if (o.bitsPerSegmentArray != null) { + bitsPerSegmentArray = new int[o.bitsPerSegmentArray.length]; + System.arraycopy(o.bitsPerSegmentArray, 0, bitsPerSegmentArray, 0, bitsPerSegmentArray.length); + } + disturbanceDegree = o.disturbanceDegree; + } + + public GAGIInitializeSegmentwise(int segLen, int bitsPerSeg, double disturbanceRatio) { + segmentLength = segLen; + bitsPerSegmentArray = new int[0]; + bitsPerSegment = bitsPerSeg; + disturbanceDegree = disturbanceRatio; + } + + public GAGIInitializeSegmentwise(int segLen, int[] bitsPerSegArr, double disturbanceRatio) { + segmentLength = segLen; + bitsPerSegmentArray = bitsPerSegArr; + disturbanceDegree = disturbanceRatio; + } + + public GAGIInitializeSegmentwise(int segLen, int[] bitsPerSeg) { + this(segLen, bitsPerSeg, 0); + } + + /** + * Constructor for the integer case defining the target element and other elements. + * + * @param segLen + * @param bitsPerSeg + * @param targetElement + * @param otherElements + */ + public GAGIInitializeSegmentwise(int segLen, int[] bitsPerSeg, int targetElement, int[] otherElements, double disturbRatio) { + segmentLength = segLen; + bitsPerSegmentArray = bitsPerSeg; + this.targetElement = targetElement; + this.otherElements = otherElements; + this.disturbanceDegree = disturbRatio; + } + @Override - public InterfaceInitialization clone() { - return new GAGIInitializeSegmentwise(this); - } + public InterfaceInitialization clone() { + return new GAGIInitializeSegmentwise(this); + } // // public static void main(String[] args) { // GAGIInitializeSegmentwise init = new GAGIInitializeSegmentwise(5, new int[]{5,0}, 0.5); @@ -99,215 +101,223 @@ public class GAGIInitializeSegmentwise implements InterfaceInitialization, java. // indy.init(null); // System.out.println(indy.getStringRepresentation()); // } - - @Override - public void initialize(AbstractEAIndividual indy, - InterfaceOptimizationProblem problem) { - if (indy instanceof InterfaceGAIndividual || indy instanceof InterfaceGIIndividual) { - int genotypeLen=-1; - Object genotype=null; - int[][] intRange=null; // may remain null in the binary case - if (indy instanceof InterfaceGAIndividual) { - genotypeLen = ((InterfaceGAIndividual)indy).getGenotypeLength(); - genotype = ((InterfaceGAIndividual)indy).getBGenotype(); - } else { - genotypeLen = ((InterfaceGIIndividual)indy).getGenotypeLength(); - genotype = ((InterfaceGIIndividual)indy).getIGenotype(); - intRange = ((InterfaceGIIndividual)indy).getIntRange(); - } - if (bitsPerSegmentArray==null || (bitsPerSegmentArray.length==0)) { - // regard only a fixed number of bits per segment - for (int i=0; i0) { - disturb(indy, genotype, genotypeLen, intRange); - } - - // write back the genotype (it may have been cloned, who knows...) - if (indy instanceof InterfaceGAIndividual) { - ((InterfaceGAIndividual)indy).SetBGenotype((BitSet)genotype); - } else { - ((InterfaceGIIndividual)indy).SetIGenotype((int[])genotype); - } + } + } + if (disturbanceDegree > 0) { + disturb(indy, genotype, genotypeLen, intRange); + } + + // write back the genotype (it may have been cloned, who knows...) + if (indy instanceof InterfaceGAIndividual) { + ((InterfaceGAIndividual) indy).SetBGenotype((BitSet) genotype); + } else { + ((InterfaceGIIndividual) indy).SetIGenotype((int[]) genotype); + } // System.out.println(BeanInspector.toString(genotype)); - } else { - throw new RuntimeException("Error: "+ this.getClass() + " must be used with binary or integer individuals!"); - } - } + } else { + throw new RuntimeException("Error: " + this.getClass() + " must be used with binary or integer individuals!"); + } + } - private void disturb(AbstractEAIndividual indy, Object genotype, int genotypeLen, int[][] intRange) { - for (int i=0; i0) { // may choose between target and all other elements - int rnd=RNG.randomInt(0, otherElements.length); // between 0 and length (inclusively) - if (rnd==otherElements.length) { - geno[i]=targetElement; - } - else { - geno[i]=otherElements[rnd]; - } - } else { // or choose a random int within the range - if (range==null) { - System.err.println("Error, missing int range to perform random disturbance in " + this.getClass()); - } - geno[i]=RNG.randomInt(range[i][0], range[i][1]); - } - } - } - - /** - * Treat both the binary and the integer case. - * - * @param nextSeg - * @param genotype - * @param offset - * @param maxLen - * @param intRange - */ - private void setNewVals(BitSet nextSeg, Object genotype, int offset, int maxLen, int[][] intRange) { - // the bits in the nextSeg bitset define the structure of the next segment starting at the offset. - // maxLen is the length of the full data type. - for (int k=offset;k=targetElement) { - newVal++; - } // make sure the elementToSet is not returned but all others may be, including the largest - return newVal; - } else { - // select one randomly from the array - int k=RNG.randomInt(otherElements.length); - return otherElements[k]; - } - } - } + } + } - private boolean getBoolVal(boolean initBit) { - // the new value is TRUE if the nextSeg-bit is set and 1 is set as target value, - // otherwise FALSE (if target value is 0) -- thus target value=1 and - // bitsPerSegment=k is equivalent to target value=0 and bitsPerSegment=segmentLength-k - if (initBit) { - return (targetElement==1); + private void setRandomValue(int i, Object genotype, int[][] range) { + if (genotype instanceof BitSet) { + BitSet geno = (BitSet) genotype; + geno.set(i, RNG.randomBoolean()); + } else if (genotype instanceof int[]) { + int[] geno = (int[]) genotype; + if (otherElements.length > 0) { // may choose between target and all other elements + int rnd = RNG.randomInt(0, otherElements.length); // between 0 and length (inclusively) + if (rnd == otherElements.length) { + geno[i] = targetElement; + } else { + geno[i] = otherElements[rnd]; + } + } else { // or choose a random int within the range + if (range == null) { + System.err.println("Error, missing int range to perform random disturbance in " + this.getClass()); + } + geno[i] = RNG.randomInt(range[i][0], range[i][1]); } - else { - return (targetElement!=1); + } + } + + /** + * Treat both the binary and the integer case. + * + * @param nextSeg + * @param genotype + * @param offset + * @param maxLen + * @param intRange + */ + private void setNewVals(BitSet nextSeg, Object genotype, int offset, int maxLen, int[][] intRange) { + // the bits in the nextSeg bitset define the structure of the next segment starting at the offset. + // maxLen is the length of the full data type. + for (int k = offset; k < offset + segmentLength; k++) { + // transfer the new segment to the genotype + if (k < maxLen) { + if (genotype instanceof BitSet) { // binary case + ((BitSet) genotype).set(k, getBoolVal(nextSeg.get(k - offset))); + } else if (genotype instanceof int[]) { // integer case + ((int[]) genotype)[k] = getIntVal(nextSeg.get(k - offset), k, intRange); + } } - } - - public int[] getTargetElementsPerSegmentArray() { - return bitsPerSegmentArray; - } - public void setTargetElementsPerSegmentArray(int[] bitsPerSegmentArray) { - this.bitsPerSegmentArray = bitsPerSegmentArray; - } - public String targetElementsPerSegmentArrayTipText() { - return "A value per segment defining the number of target elements to set for that segment, or null if fixed"; - } + } + } - public int getTargetElementsPerSegment() { - return bitsPerSegment; - } - public void setTargetElementsPerSegment(int bitsPerSegment) { - this.bitsPerSegment = bitsPerSegment; - } - public String targetElementsPerSegmentTipText() { - return "If not defined as an array, this fixed number of target elements is set per segment"; - } + /** + * Return the integer value selected at the given position. + * + * @param initBit + * @param pos + * @param range + * @return + */ + private int getIntVal(boolean initBit, int pos, int[][] range) { + // if true, the target value is returned, otherwise the non-target value + // or a random value in range + if (initBit) { + return targetElement; + } else { + if ((otherElements == null) || (otherElements.length == 0)) { // all but the one to set + int rangeLenMinusOne = range[pos][1] - range[pos][0]; // bounds are included, so one is missing + int newVal = RNG.randomInt(rangeLenMinusOne); // a random integer with one missing (the largest) + if (newVal >= targetElement) { + newVal++; + } // make sure the elementToSet is not returned but all others may be, including the largest + return newVal; + } else { + // select one randomly from the array + int k = RNG.randomInt(otherElements.length); + return otherElements[k]; + } + } + } - public int getSegmentLength() { - return segmentLength; - } - public void setSegmentLength(int segmentLength) { - this.segmentLength = segmentLength; - } - public String segmentLengthTipText() { - return "The fixed length of a segment, which is a substring of the binary genotype"; - } - - //////// - public String getName() { - return "GA-GI segment-wise init"; - } - - public static String globalInfo() { - return "A method which initializes with a fixed number of occurences per segment, which is a fixed-length" + - " substring of equal length. In the binary case, thus the cardinality of each segment can be predefined."; - } + private boolean getBoolVal(boolean initBit) { + // the new value is TRUE if the nextSeg-bit is set and 1 is set as target value, + // otherwise FALSE (if target value is 0) -- thus target value=1 and + // bitsPerSegment=k is equivalent to target value=0 and bitsPerSegment=segmentLength-k + if (initBit) { + return (targetElement == 1); + } else { + return (targetElement != 1); + } + } - public int getTargetElement() { - return targetElement; - } - public void setTargetElement(int elementToSet) { - this.targetElement = elementToSet; - } - public String targetElementTipText() { - return "The element to set in a defined number per segment"; - } + public int[] getTargetElementsPerSegmentArray() { + return bitsPerSegmentArray; + } - public int[] getOtherElements() { - return otherElements; - } - public void setOtherElements(int[] elementsNotToSet) { - this.otherElements = elementsNotToSet; - } - public String otherElementsTipText() { - return "Set of elements at the rest of instances among which is chosen randomly - if empty, all allowed ones except for the elementToSet are used."; - } + public void setTargetElementsPerSegmentArray(int[] bitsPerSegmentArray) { + this.bitsPerSegmentArray = bitsPerSegmentArray; + } + + public String targetElementsPerSegmentArrayTipText() { + return "A value per segment defining the number of target elements to set for that segment, or null if fixed"; + } + + public int getTargetElementsPerSegment() { + return bitsPerSegment; + } + + public void setTargetElementsPerSegment(int bitsPerSegment) { + this.bitsPerSegment = bitsPerSegment; + } + + public String targetElementsPerSegmentTipText() { + return "If not defined as an array, this fixed number of target elements is set per segment"; + } + + public int getSegmentLength() { + return segmentLength; + } + + public void setSegmentLength(int segmentLength) { + this.segmentLength = segmentLength; + } + + public String segmentLengthTipText() { + return "The fixed length of a segment, which is a substring of the binary genotype"; + } + + //////// + public String getName() { + return "GA-GI segment-wise init"; + } + + public static String globalInfo() { + return "A method which initializes with a fixed number of occurences per segment, which is a fixed-length" + + " substring of equal length. In the binary case, thus the cardinality of each segment can be predefined."; + } + + public int getTargetElement() { + return targetElement; + } + + public void setTargetElement(int elementToSet) { + this.targetElement = elementToSet; + } + + public String targetElementTipText() { + return "The element to set in a defined number per segment"; + } + + public int[] getOtherElements() { + return otherElements; + } + + public void setOtherElements(int[] elementsNotToSet) { + this.otherElements = elementsNotToSet; + } + + public String otherElementsTipText() { + return "Set of elements at the rest of instances among which is chosen randomly - if empty, all allowed ones except for the elementToSet are used."; + } } diff --git a/src/eva2/optimization/operator/initialization/InterfaceInitialization.java b/src/eva2/optimization/operator/initialization/InterfaceInitialization.java index fd164cf0..aa1dbb12 100644 --- a/src/eva2/optimization/operator/initialization/InterfaceInitialization.java +++ b/src/eva2/optimization/operator/initialization/InterfaceInitialization.java @@ -8,24 +8,24 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * to mutation and crossover. It is member of every abstract individual * but the specific implementation may depend on the data type of the * individual. - * - * @author mkron * + * @author mkron */ public interface InterfaceInitialization { - - /** - * Perform initialization of a given individual, which may potentially depend on - * a problem instance. - * - * @param indy the target individual to initialize - * @param problem the problem instance under consideration - */ - public void initialize(AbstractEAIndividual indy, InterfaceOptimizationProblem problem); - /** - * A specific cloning method. - * @return - */ - public InterfaceInitialization clone(); + /** + * Perform initialization of a given individual, which may potentially depend on + * a problem instance. + * + * @param indy the target individual to initialize + * @param problem the problem instance under consideration + */ + public void initialize(AbstractEAIndividual indy, InterfaceOptimizationProblem problem); + + /** + * A specific cloning method. + * + * @return + */ + public InterfaceInitialization clone(); } diff --git a/src/eva2/optimization/operator/migration/InterfaceMigration.java b/src/eva2/optimization/operator/migration/InterfaceMigration.java index 7135435d..e7cabb60 100644 --- a/src/eva2/optimization/operator/migration/InterfaceMigration.java +++ b/src/eva2/optimization/operator/migration/InterfaceMigration.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.migration; import eva2.optimization.strategies.InterfaceOptimizer; -/** The migration methods give the migration topology +/** + * The migration methods give the migration topology * (currently all migration methods are typically fully * connected) and give the selection criteria. While * SOXMigration stands for uni-criterial migration @@ -17,16 +18,19 @@ import eva2.optimization.strategies.InterfaceOptimizer; */ public interface InterfaceMigration { - /** The ever present clone method + /** + * The ever present clone method */ public Object clone(); - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ public void initMigration(InterfaceOptimizer[] islands); - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this diff --git a/src/eva2/optimization/operator/migration/MOBestMigration.java b/src/eva2/optimization/operator/migration/MOBestMigration.java index 0a8e2b13..1c0c37bc 100644 --- a/src/eva2/optimization/operator/migration/MOBestMigration.java +++ b/src/eva2/optimization/operator/migration/MOBestMigration.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.selection.SelectMOMaxiMin; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; -/** Migration based on a Multi-criterial selection mechanism +/** + * Migration based on a Multi-criterial selection mechanism * migrating the n best individuals between all populations. * Created by IntelliJ IDEA. * User: streiche @@ -15,17 +16,19 @@ import eva2.optimization.strategies.InterfaceOptimizer; */ public class MOBestMigration implements InterfaceMigration, java.io.Serializable { - private InterfaceSelection m_Selection = new SelectMOMaxiMin(); - int m_N = 5; + private InterfaceSelection m_Selection = new SelectMOMaxiMin(); + int m_N = 5; - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new MOBestMigration(); } - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ @Override @@ -33,7 +36,8 @@ public class MOBestMigration implements InterfaceMigration, java.io.Serializable // pff at a later stage i could initialize a topology here } - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this @@ -45,15 +49,15 @@ public class MOBestMigration implements InterfaceMigration, java.io.Serializable */ @Override public void migrate(InterfaceOptimizer[] islands) { - Population[] oldIPOP = new Population[islands.length]; - Population[] newIPOP = new Population[islands.length]; - Population[] comSet; - Population selected; + Population[] oldIPOP = new Population[islands.length]; + Population[] newIPOP = new Population[islands.length]; + Population[] comSet; + Population selected; // collect the populations for (int i = 0; i < islands.length; i++) { oldIPOP[i] = islands[i].getPopulation(); - newIPOP[i] = (Population)oldIPOP[i].clone(); + newIPOP[i] = (Population) oldIPOP[i].clone(); } // perform migration for each ipop @@ -63,10 +67,10 @@ public class MOBestMigration implements InterfaceMigration, java.io.Serializable comSet = oldIPOP; // todo: Here i could implement multiple selection and replacement schemes - newIPOP[i].removeNIndividuals(comSet.length*this.m_N); - for(int j = 0; j < comSet.length; j++) { + newIPOP[i].removeNIndividuals(comSet.length * this.m_N); + for (int j = 0; j < comSet.length; j++) { selected = this.m_Selection.selectFrom(comSet[j], this.m_N); - newIPOP[i].addPopulation((Population)selected.clone()); + newIPOP[i].addPopulation((Population) selected.clone()); } } @@ -79,45 +83,58 @@ public class MOBestMigration implements InterfaceMigration, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is multi-objective migration scheme."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MOBestMigration"; - } + } - /** This method allows you to set/get the selection method for migration. + /** + * This method allows you to set/get the selection method for migration. + * * @return The selection method */ public InterfaceSelection getSelection() { return this.m_Selection; } - public void setSelection(InterfaceSelection b){ + + public void setSelection(InterfaceSelection b) { this.m_Selection = b; } + public String selectionTipText() { return "Choose the selection method for migration."; } - /** This method allows you to set/get the number of individuals + /** + * This method allows you to set/get the number of individuals * to migrate per migration event. + * * @return The current number of individuals to migrate */ public int getN() { return this.m_N; } - public void setN(int b){ + + public void setN(int b) { if (b < 1) { b = 1; } this.m_N = b; } + public String nTipText() { return "The number of individuals to migrate per migration event."; } diff --git a/src/eva2/optimization/operator/migration/MOClusteringSeparation.java b/src/eva2/optimization/operator/migration/MOClusteringSeparation.java index c9050d79..a996af20 100644 --- a/src/eva2/optimization/operator/migration/MOClusteringSeparation.java +++ b/src/eva2/optimization/operator/migration/MOClusteringSeparation.java @@ -15,10 +15,12 @@ import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; + import java.io.BufferedWriter; import java.io.IOException; -/** This method implements the clustering based subdivision +/** + * This method implements the clustering based subdivision * scheme, this method rearanges the populations and may * impose area constraints on the subpopulations. This method * is suited for K-means only. @@ -30,39 +32,41 @@ import java.io.IOException; */ public class MOClusteringSeparation implements InterfaceMigration, java.io.Serializable { - public boolean m_Debug = false; - private ClusteringKMeans m_KMeans = new ClusteringKMeans(); - private ArchivingNSGAII m_NSGAII = new ArchivingNSGAII(); - private boolean m_UseConstraints = true; - private boolean m_ReuseC = false; - private InterfaceSelection m_Selection = new SelectRandom(); + public boolean m_Debug = false; + private ClusteringKMeans m_KMeans = new ClusteringKMeans(); + private ArchivingNSGAII m_NSGAII = new ArchivingNSGAII(); + private boolean m_UseConstraints = true; + private boolean m_ReuseC = false; + private InterfaceSelection m_Selection = new SelectRandom(); public MOClusteringSeparation() { } public MOClusteringSeparation(MOClusteringSeparation b) { - this.m_Debug = b.m_Debug; - this.m_UseConstraints = b.m_UseConstraints; + this.m_Debug = b.m_Debug; + this.m_UseConstraints = b.m_UseConstraints; if (b.m_KMeans != null) { - this.m_KMeans = (ClusteringKMeans)b.m_KMeans.clone(); + this.m_KMeans = (ClusteringKMeans) b.m_KMeans.clone(); } if (b.m_NSGAII != null) { - this.m_NSGAII = (ArchivingNSGAII)b.m_NSGAII.clone(); + this.m_NSGAII = (ArchivingNSGAII) b.m_NSGAII.clone(); } if (b.m_Selection != null) { - this.m_Selection = (InterfaceSelection)b.m_Selection.clone(); + this.m_Selection = (InterfaceSelection) b.m_Selection.clone(); } } - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new MOClusteringSeparation(this); } - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ @Override @@ -73,7 +77,8 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria } } - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this @@ -85,21 +90,21 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria */ @Override public void migrate(InterfaceOptimizer[] islands) { - Population[] oldIPOP = new Population[islands.length]; - Population[] newIPOP = new Population[islands.length]; - Population collector = new Population(), memory; - AbstractEAIndividual indy; + Population[] oldIPOP = new Population[islands.length]; + Population[] newIPOP = new Population[islands.length]; + Population collector = new Population(), memory; + AbstractEAIndividual indy; // collect the populations for (int i = 0; i < islands.length; i++) { oldIPOP[i] = islands[i].getPopulation(); if (this.m_Debug) { - System.out.println("Got population from "+i+" of size "+oldIPOP[i].size()); + System.out.println("Got population from " + i + " of size " + oldIPOP[i].size()); } - collector.addPopulation((Population)oldIPOP[i].clone()); + collector.addPopulation((Population) oldIPOP[i].clone()); newIPOP[i] = new Population(); } - memory = (Population)collector.clone(); + memory = (Population) collector.clone(); // if (this.m_Debug) { // // let's see how they arrive here @@ -126,8 +131,8 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria // } // Now lets cluster this stuff - Population[] archives = this.m_NSGAII.getNonDominatedSortedFronts(collector); - Population toCluster = new Population(); + Population[] archives = this.m_NSGAII.getNonDominatedSortedFronts(collector); + Population toCluster = new Population(); int currentFront = 0; toCluster.addPopulation(archives[currentFront]); while (toCluster.size() < islands.length) { @@ -137,36 +142,36 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria // first set the K to the K-Means this.m_KMeans.setK(islands.length); - this.m_KMeans.cluster(toCluster, (Population)null); + this.m_KMeans.cluster(toCluster, (Population) null); double[][] c = this.m_KMeans.getC(); newIPOP = this.m_KMeans.cluster(collector, c); if (this.m_Debug) { - Plot plot; - double[] tmpD = new double[2]; + Plot plot; + double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; plot = new Plot("Debugging Clustering Separation", "Y1", "Y2", tmpD, tmpD); - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; for (int i = 0; i < newIPOP.length; i++) { - mySet = new GraphPointSet(10+1, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + 1, plot.getFunctionArea()); mySet.setConnectedMode(false); for (int j = 0; j < newIPOP[i].size(); j++) { - indy = (AbstractEAIndividual)newIPOP[i].get(j); + indy = (AbstractEAIndividual) newIPOP[i].get(j); myPoint = new DPoint(indy.getFitness()[0], indy.getFitness()[1]); - tmp = new Chart2DDPointIconText(""+i); + tmp = new Chart2DDPointIconText("" + i); //if (i % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } } - mySet = new GraphPointSet(10+2, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + 2, plot.getFunctionArea()); mySet.setConnectedMode(false); for (int i = 0; i < c.length; i++) { myPoint = new DPoint(c[i][0], c[i][1]); - tmp = new Chart2DDPointIconText(""+i); + tmp = new Chart2DDPointIconText("" + i); tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); @@ -181,9 +186,9 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { // set the boundaries to perform the constrained // domain principle introduced by Deb et al. - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.clear(); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.clear(); double[] myClass = c[i]; - double[][] myOtherClass = new double[c.length -1][]; + double[][] myOtherClass = new double[c.length - 1][]; int index = 0; for (int j = 0; j < myOtherClass.length; j++) { if (index == i) { @@ -193,7 +198,7 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria index++; } ConstBelongsToDifferentClass b = new ConstBelongsToDifferentClass(myClass, myOtherClass, this.m_KMeans.getUseSearchSpace()); - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.add(b); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.add(b); // if (this.m_Debug) { // String out = ""; // out += i+ ". MyClass: {"; @@ -221,10 +226,10 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria oldIPOP[i].addPopulation(newIPOP[i]); // todo remove this for nice pictures if (!oldIPOP[i].targetSizeReached()) { - oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getTargetSize()-oldIPOP[i].size())); + oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getTargetSize() - oldIPOP[i].size())); } if (this.m_Debug) { - System.out.println("Setting "+i+" to population size " + oldIPOP[i].size()); + System.out.println("Setting " + i + " to population size " + oldIPOP[i].size()); } islands[i].setPopulation(oldIPOP[i]); } @@ -332,12 +337,14 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria // System.exit(0); // } - /** This method writes Data to file. - * @param line The line that is to be added to the file + /** + * This method writes Data to file. + * + * @param line The line that is to be added to the file */ private void writeToFile(BufferedWriter out, String line) { String write = line + "\n"; - write.replaceAll(",","."); + write.replaceAll(",", "."); if (out == null) { return; } @@ -352,58 +359,75 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is migration scheme, which implements a clustering based partitioning."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MOClusteringSeparation"; } - /** This method allows you to set/get the clustering algorithm. + /** + * This method allows you to set/get the clustering algorithm. + * * @return The clustering algorithm method */ public ClusteringKMeans getKMeans() { return this.m_KMeans; } - public void setKMeans(ClusteringKMeans b){ + + public void setKMeans(ClusteringKMeans b) { this.m_KMeans = b; } + public String kMeansTipText() { return "Choose the clustering algorithm."; } - /** This method allows you to toogle the use of constraints, + /** + * This method allows you to toogle the use of constraints, * which enable the algorithm to limit each island to a * specific area of the search space. + * * @return The modus of constraints. */ public boolean getUseConstraints() { return this.m_UseConstraints; } - public void setUseConstraints(boolean b){ + + public void setUseConstraints(boolean b) { this.m_UseConstraints = b; } + public String useConstraintsTipText() { return "If activated constraints are used to limit each island to a local area."; } - /** This method allows you to toggle reuse of c. + /** + * This method allows you to toggle reuse of c. + * * @return The distance type to use. */ public boolean getReuseC() { this.m_ReuseC = this.m_KMeans.getReuseC(); return this.m_ReuseC; } - public void setReuseC(boolean m){ + + public void setReuseC(boolean m) { this.m_ReuseC = m; this.m_KMeans.setReuseC(this.m_ReuseC); } + public String reuseCTipText() { return "Toggle reuse of previously found cluster centroids."; } diff --git a/src/eva2/optimization/operator/migration/MOConeSeparation.java b/src/eva2/optimization/operator/migration/MOConeSeparation.java index 32b1fc74..12ed6eb6 100644 --- a/src/eva2/optimization/operator/migration/MOConeSeparation.java +++ b/src/eva2/optimization/operator/migration/MOConeSeparation.java @@ -18,10 +18,12 @@ import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; + import java.io.BufferedWriter; import java.io.IOException; -/** This method implements the cone separation subdivision +/** + * This method implements the cone separation subdivision * scheme, this method rearanges the populations and may * impose area constraints on the subpopulations. * Created by IntelliJ IDEA. @@ -32,33 +34,35 @@ import java.io.IOException; */ public class MOConeSeparation implements InterfaceMigration, java.io.Serializable { - public boolean m_Debug = false; - private boolean m_UseAllToDetermineR = false; // since i'm only interessted in the pareto-front this should be set to false!! - private boolean m_UseConstraints = true; - private InterfaceSelection m_Selection = new SelectRandom(); - private double[][] m_3DBounds; + public boolean m_Debug = false; + private boolean m_UseAllToDetermineR = false; // since i'm only interessted in the pareto-front this should be set to false!! + private boolean m_UseConstraints = true; + private InterfaceSelection m_Selection = new SelectRandom(); + private double[][] m_3DBounds; public MOConeSeparation() { } public MOConeSeparation(MOConeSeparation b) { - this.m_Debug = b.m_Debug; - this.m_UseConstraints = b.m_UseConstraints; - this.m_UseAllToDetermineR = b.m_UseAllToDetermineR; + this.m_Debug = b.m_Debug; + this.m_UseConstraints = b.m_UseConstraints; + this.m_UseAllToDetermineR = b.m_UseAllToDetermineR; if (b.m_Selection != null) { - this.m_Selection = (InterfaceSelection)b.m_Selection.clone(); + this.m_Selection = (InterfaceSelection) b.m_Selection.clone(); } } - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new MOConeSeparation(this); } - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ @Override @@ -66,7 +70,8 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl // pff at a later stage i could initialize a topology here } - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this @@ -78,29 +83,29 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl */ @Override public void migrate(InterfaceOptimizer[] islands) { - Population[] oldIPOP = new Population[islands.length]; - Population[] newIPOP = new Population[islands.length]; - Population collector = new Population(), memory; - InterfaceArchiving allDom = new ArchivingAllDominating(); + Population[] oldIPOP = new Population[islands.length]; + Population[] newIPOP = new Population[islands.length]; + Population collector = new Population(), memory; + InterfaceArchiving allDom = new ArchivingAllDominating(); // collect the populations for (int i = 0; i < islands.length; i++) { oldIPOP[i] = islands[i].getPopulation(); if (this.m_Debug) { - System.out.println("Got population from "+i+" of size "+oldIPOP[i].size()); + System.out.println("Got population from " + i + " of size " + oldIPOP[i].size()); } - collector.addPopulation((Population)oldIPOP[i].clone()); + collector.addPopulation((Population) oldIPOP[i].clone()); newIPOP[i] = new Population(); } - memory = (Population)collector.clone(); + memory = (Population) collector.clone(); - if (((AbstractEAIndividual)collector.get(0)).getFitness().length == 2) { + if (((AbstractEAIndividual) collector.get(0)).getFitness().length == 2) { this.coneSeparation2D(collector, newIPOP, islands); } else { - if (((AbstractEAIndividual)collector.get(0)).getFitness().length == 3) { + if (((AbstractEAIndividual) collector.get(0)).getFitness().length == 3) { this.coneSeparation3D(collector, newIPOP, islands); } else { - if (((AbstractEAIndividual)collector.get(0)).getFitness().length >= 4) { + if (((AbstractEAIndividual) collector.get(0)).getFitness().length >= 4) { System.out.println("*Pff*"); } } @@ -111,23 +116,25 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl oldIPOP[i].addPopulation(newIPOP[i]); // todo remove this for nice pictures if (!oldIPOP[i].targetSizeReached()) { - oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getTargetSize()-oldIPOP[i].size())); + oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getTargetSize() - oldIPOP[i].size())); } if (this.m_Debug) { - System.out.println("Setting island "+i+" to population size " + oldIPOP[i].size()); + System.out.println("Setting island " + i + " to population size " + oldIPOP[i].size()); } allDom.addElementsToArchive(oldIPOP[i]); islands[i].setPopulation(oldIPOP[i]); } } - /** This method performs cone separation in 2D - * @param collector This is a aggregated population; - * @param newIPOP The new population on the islands after separation - * @param islands The optimizer required to get the problem to set the constraints. + /** + * This method performs cone separation in 2D + * + * @param collector This is a aggregated population; + * @param newIPOP The new population on the islands after separation + * @param islands The optimizer required to get the problem to set the constraints. */ private void coneSeparation2D(Population collector, Population[] newIPOP, InterfaceOptimizer[] islands) { - AbstractEAIndividual indy; + AbstractEAIndividual indy; // if (this.m_Debug) { // // let's see how they arrive here @@ -159,33 +166,32 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl // now let's find the reference point first just in 2D InterfaceArchiving allDom = new ArchivingAllDominating(); allDom.addElementsToArchive(collector); - int y1Big = 0, y2Big = 0; - Population archive = collector.getArchive(); - Population ref; + int y1Big = 0, y2Big = 0; + Population archive = collector.getArchive(); + Population ref; if (this.m_UseAllToDetermineR) { ref = collector; - } - else { + } else { ref = archive; } for (int i = 1; i < ref.size(); i++) { - if (((AbstractEAIndividual)ref.get(i)).getFitness()[0] > ((AbstractEAIndividual)ref.get(y1Big)).getFitness()[0]) { + if (((AbstractEAIndividual) ref.get(i)).getFitness()[0] > ((AbstractEAIndividual) ref.get(y1Big)).getFitness()[0]) { y1Big = i; } - if (((AbstractEAIndividual)ref.get(i)).getFitness()[1] > ((AbstractEAIndividual)ref.get(y2Big)).getFitness()[1]) { + if (((AbstractEAIndividual) ref.get(i)).getFitness()[1] > ((AbstractEAIndividual) ref.get(y2Big)).getFitness()[1]) { y2Big = i; } } - double[] r = new double[2]; - double alpha = 90.0/(double)islands.length; - double[][] boundaries = new double[islands.length-1][2]; - r[0] = ((AbstractEAIndividual)ref.get(y1Big)).getFitness()[0]; - r[1] = ((AbstractEAIndividual)ref.get(y2Big)).getFitness()[1]; + double[] r = new double[2]; + double alpha = 90.0 / (double) islands.length; + double[][] boundaries = new double[islands.length - 1][2]; + r[0] = ((AbstractEAIndividual) ref.get(y1Big)).getFitness()[0]; + r[1] = ((AbstractEAIndividual) ref.get(y2Big)).getFitness()[1]; for (int i = 0; i < boundaries.length; i++) { - boundaries[i][0] = 1 / Math.tan(Math.toRadians(alpha*(i+1))); - boundaries[i][1] = r[1] - boundaries[i][0]*r[0]; + boundaries[i][0] = 1 / Math.tan(Math.toRadians(alpha * (i + 1))); + boundaries[i][1] = r[1] - boundaries[i][0] * r[0]; // System.out.println("Boundary"+i+" f(x)="+boundaries[i][0]+"*x + "+ boundaries[i][1]); } @@ -194,8 +200,8 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl // Now i got the cone's let's separate for (int i = 0; i < boundaries.length; i++) { for (int j = 0; j < collector.size(); j++) { - indy = (AbstractEAIndividual)collector.get(j); - if (indy.getFitness()[1] < boundaries[i][0]*indy.getFitness()[0]+boundaries[i][1]) { + indy = (AbstractEAIndividual) collector.get(j); + if (indy.getFitness()[1] < boundaries[i][0] * indy.getFitness()[0] + boundaries[i][1]) { // this guy belongs to cone i newIPOP[i].add(indy); collector.remove(j); @@ -204,17 +210,17 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl } } // the rest belongs to newIPOP.length-1 - newIPOP[newIPOP.length-1].addPopulation(collector); + newIPOP[newIPOP.length - 1].addPopulation(collector); if (this.m_Debug) { - Plot plot; - double[] tmpD = new double[2]; + Plot plot; + double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; plot = new Plot("Debugging Cone Separation", "Y1", "Y2", tmpD, tmpD); - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; mySet = new GraphPointSet(9, plot.getFunctionArea()); mySet.setConnectedMode(false); // now plot the region boundaries @@ -223,12 +229,12 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl mySet.addDPoint(myPoint); } for (int i = 0; i < newIPOP.length; i++) { - mySet = new GraphPointSet(10+i, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + i, plot.getFunctionArea()); mySet.setConnectedMode(false); for (int j = 0; j < newIPOP[i].size(); j++) { - indy = (AbstractEAIndividual)newIPOP[i].get(j); + indy = (AbstractEAIndividual) newIPOP[i].get(j); myPoint = new DPoint(indy.getFitness()[0], indy.getFitness()[1]); - tmp = new Chart2DDPointIconText(""+i); + tmp = new Chart2DDPointIconText("" + i); if (i % 2 == 0) { tmp.setIcon(new Chart2DDPointIconCircle()); } @@ -239,7 +245,7 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl mySet = new GraphPointSet(10, plot.getFunctionArea()); mySet.setConnectedMode(false); // now plot the region boundaries - for (int i = 0; i < islands.length-1; i++) { + for (int i = 0; i < islands.length - 1; i++) { myPoint = new DPoint(r[0], r[1]); mySet.addDPoint(myPoint); myPoint = new DPoint(r[0], r[1]); @@ -250,9 +256,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl myPoint = new DPoint(0.0, boundaries[i][1]); mySet.addDPoint(myPoint); } else { - myPoint = new DPoint(-boundaries[i][1]/boundaries[i][0], 0); + myPoint = new DPoint(-boundaries[i][1] / boundaries[i][0], 0); mySet.addDPoint(myPoint); - myPoint = new DPoint(-boundaries[i][1]/boundaries[i][0], 0); + myPoint = new DPoint(-boundaries[i][1] / boundaries[i][0], 0); mySet.addDPoint(myPoint); } } @@ -266,18 +272,18 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { // set the boundaries to perform the constrained // domain principle introduced by Deb et al. - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.clear(); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.clear(); if (i > 0) { // add the lower boundary - ConstObjectivesInEqualityBiggerThanLinear b = new ConstObjectivesInEqualityBiggerThanLinear(boundaries[i-1][0], boundaries[i-1][1]); + ConstObjectivesInEqualityBiggerThanLinear b = new ConstObjectivesInEqualityBiggerThanLinear(boundaries[i - 1][0], boundaries[i - 1][1]); - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.add(b); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.add(b); } - if (i < islands.length-1) { + if (i < islands.length - 1) { // add the upper boundary ConstObjectivesInEqualityLesserThanLinear b = new ConstObjectivesInEqualityLesserThanLinear(boundaries[i][0], boundaries[i][1]); - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.add(b); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.add(b); } islands[i].setProblem(prob); } @@ -285,81 +291,84 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl } } - /** This method performs cone separation in 2D - * @param collector This is a aggregated population; - * @param newIPOP The new population on the islands after separation - * @param islands The optimizer required to get the problem to set the constraints. + /** + * This method performs cone separation in 2D + * + * @param collector This is a aggregated population; + * @param newIPOP The new population on the islands after separation + * @param islands The optimizer required to get the problem to set the constraints. */ private void coneSeparation3D(Population collector, Population[] newIPOP, InterfaceOptimizer[] islands) { - AbstractEAIndividual indy; + AbstractEAIndividual indy; // now let's find the reference point first just in 2D InterfaceArchiving allDom = new ArchivingAllDominating(); allDom.addElementsToArchive(collector); - int y1Big = 0, y2Big = 0, y3Big = 0; - Population archive = collector.getArchive(); - Population ref; + int y1Big = 0, y2Big = 0, y3Big = 0; + Population archive = collector.getArchive(); + Population ref; if (this.m_UseAllToDetermineR) { ref = collector; - } - else { + } else { ref = archive; } for (int i = 1; i < ref.size(); i++) { - if (((AbstractEAIndividual)ref.get(i)).getFitness()[0] > ((AbstractEAIndividual)ref.get(y1Big)).getFitness()[0]) { + if (((AbstractEAIndividual) ref.get(i)).getFitness()[0] > ((AbstractEAIndividual) ref.get(y1Big)).getFitness()[0]) { y1Big = i; } - if (((AbstractEAIndividual)ref.get(i)).getFitness()[1] > ((AbstractEAIndividual)ref.get(y2Big)).getFitness()[1]) { + if (((AbstractEAIndividual) ref.get(i)).getFitness()[1] > ((AbstractEAIndividual) ref.get(y2Big)).getFitness()[1]) { y2Big = i; } - if (((AbstractEAIndividual)ref.get(i)).getFitness()[2] > ((AbstractEAIndividual)ref.get(y3Big)).getFitness()[2]) { + if (((AbstractEAIndividual) ref.get(i)).getFitness()[2] > ((AbstractEAIndividual) ref.get(y3Big)).getFitness()[2]) { y3Big = i; } } // now build a 3D bounding rule - double[] distopian = new double[3], zE = new double[3]; - double[][] normals = new double[islands.length][3]; - double angIncr = 360.0 /(double)islands.length; + double[] distopian = new double[3], zE = new double[3]; + double[][] normals = new double[islands.length][3]; + double angIncr = 360.0 / (double) islands.length; - distopian[0] = ((AbstractEAIndividual)ref.get(y1Big)).getFitness()[0]; - distopian[1] = ((AbstractEAIndividual)ref.get(y2Big)).getFitness()[1]; - distopian[2] = ((AbstractEAIndividual)ref.get(y3Big)).getFitness()[2]; + distopian[0] = ((AbstractEAIndividual) ref.get(y1Big)).getFitness()[0]; + distopian[1] = ((AbstractEAIndividual) ref.get(y2Big)).getFitness()[1]; + distopian[2] = ((AbstractEAIndividual) ref.get(y3Big)).getFitness()[2]; - zE[0] = 0; zE[1] = 0; zE[2] = 1; + zE[0] = 0; + zE[1] = 0; + zE[2] = 1; - double[] firstVec = this.getCrossProduct(distopian, zE); - firstVec = this.getNormalized(firstVec); - double[] normDist = this.getNormalized(distopian); + double[] firstVec = this.getCrossProduct(distopian, zE); + firstVec = this.getNormalized(firstVec); + double[] normDist = this.getNormalized(distopian); - this.m_3DBounds = new double[normals.length+2][3]; - this.m_3DBounds[0] = distopian; + this.m_3DBounds = new double[normals.length + 2][3]; + this.m_3DBounds[0] = distopian; for (int i = 0; i < normals.length; i++) { - normals[i] = this.rotVector(firstVec, normDist, Math.toRadians(i*angIncr)); - this.m_3DBounds[i+1] = normals[i]; + normals[i] = this.rotVector(firstVec, normDist, Math.toRadians(i * angIncr)); + this.m_3DBounds[i + 1] = normals[i]; } // now i got the bounding planes - double[][] lastBoundingPlane = new double[2][3]; // first double[3] gives a point on the plane, the second gives the normal on the plane - double[][] curBoundingPlane = new double[2][3]; - double[] fitness; + double[][] lastBoundingPlane = new double[2][3]; // first double[3] gives a point on the plane, the second gives the normal on the plane + double[][] curBoundingPlane = new double[2][3]; + double[] fitness; InterfaceOptimizationProblem prob; - lastBoundingPlane[0] = distopian; - lastBoundingPlane[1] = normals[normals.length-1]; - curBoundingPlane[0] = distopian; - curBoundingPlane[1] = normals[0]; + lastBoundingPlane[0] = distopian; + lastBoundingPlane[1] = normals[normals.length - 1]; + curBoundingPlane[0] = distopian; + curBoundingPlane[1] = normals[0]; collector.SetArchive(new Population()); // Now i got the cone's let's separate for (int i = 0; i < normals.length; i++) { for (int j = 0; j < collector.size(); j++) { - indy = (AbstractEAIndividual)collector.get(j); + indy = (AbstractEAIndividual) collector.get(j); fitness = indy.getFitness(); if ((this.getScalarProduct(curBoundingPlane[1], this.getVectorSub(fitness, curBoundingPlane[0])) < 0) && - (this.getScalarProduct(lastBoundingPlane[1], this.getVectorSub(fitness, lastBoundingPlane[0])) >= 0)) { + (this.getScalarProduct(lastBoundingPlane[1], this.getVectorSub(fitness, lastBoundingPlane[0])) >= 0)) { // this guy belongs to cone i newIPOP[i].add(indy); // collector.remove(j); @@ -371,11 +380,11 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { // set the boundaries to perform the constrained // domain principle introduced by Deb et al. - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.clear(); - ConstObjectivesInEqualitySmallerThanSurface sts = new ConstObjectivesInEqualitySmallerThanSurface(curBoundingPlane[0], curBoundingPlane[1]); - ConstObjectivesInEqualityBiggerThanSurface bts = new ConstObjectivesInEqualityBiggerThanSurface(lastBoundingPlane[0], lastBoundingPlane[1]); - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.add(sts); - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.add(bts); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.clear(); + ConstObjectivesInEqualitySmallerThanSurface sts = new ConstObjectivesInEqualitySmallerThanSurface(curBoundingPlane[0], curBoundingPlane[1]); + ConstObjectivesInEqualityBiggerThanSurface bts = new ConstObjectivesInEqualityBiggerThanSurface(lastBoundingPlane[0], lastBoundingPlane[1]); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.add(sts); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.add(bts); } islands[i].setProblem(prob); // if (true) { @@ -392,9 +401,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl } lastBoundingPlane[0] = curBoundingPlane[0]; lastBoundingPlane[1] = curBoundingPlane[1]; - curBoundingPlane[0] = distopian; - if (i+1 < normals.length) { - curBoundingPlane[1] = normals[i+1]; + curBoundingPlane[0] = distopian; + if (i + 1 < normals.length) { + curBoundingPlane[1] = normals[i + 1]; } // else curBoundingPlane[1] = normals[0]; } @@ -426,26 +435,30 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl // } } - /** This method returns the scalar product of two vectors + /** + * This method returns the scalar product of two vectors + * * @param a The first vector * @param b The second vector * @return The scalar product of a and b */ private double getScalarProduct(double[] a, double[] b) { - return (a[0]*b[0] + a[1]*b[1] + a[2]*b[2]); + return (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]); } - /** This method returns the cross product of two 3D vectors - * @param a The first vector - * @param b The second vector + /** + * This method returns the cross product of two 3D vectors + * + * @param a The first vector + * @param b The second vector * @return The cross product */ private double[] getCrossProduct(double[] a, double[] b) { double[] result = new double[3]; - result[0] = a[1]*b[2] - a[2]*b[1]; - result[1] = a[2]*b[0] - a[0]*b[2]; - result[2] = a[0]*b[1] - a[1]*b[0]; + result[0] = a[1] * b[2] - a[2] * b[1]; + result[1] = a[2] * b[0] - a[0] * b[2]; + result[2] = a[0] * b[1] - a[1] * b[0]; return result; } @@ -453,9 +466,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl private double[] getVectorAdd(double[] a, double[] b) { double[] result = new double[3]; - result[0] = a[0]+b[0]; - result[1] = a[1]+b[1]; - result[2] = a[2]+b[2]; + result[0] = a[0] + b[0]; + result[1] = a[1] + b[1]; + result[2] = a[2] + b[2]; return result; } @@ -463,9 +476,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl private double[] getVectorSub(double[] a, double[] b) { double[] result = new double[3]; - result[0] = a[0]-b[0]; - result[1] = a[1]-b[1]; - result[2] = a[2]-b[2]; + result[0] = a[0] - b[0]; + result[1] = a[1] - b[1]; + result[2] = a[2] - b[2]; return result; } @@ -473,15 +486,17 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl private double[] getScalarMultiplication(double a, double[] b) { double[] result = new double[3]; - result[0] = a*b[0]; - result[1] = a*b[1]; - result[2] = a*b[2]; + result[0] = a * b[0]; + result[1] = a * b[1]; + result[2] = a * b[2]; return result; } - /** This method will return a normalized vector - * @param a The vector to normalize + /** + * This method will return a normalized vector + * + * @param a The vector to normalize * @return A normalized version of the input vector */ private double[] getNormalized(double[] a) { @@ -492,59 +507,63 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl } sum = Math.sqrt(sum); for (int i = 0; i < a.length; i++) { - result[i] = a[i]/sum; + result[i] = a[i] / sum; } return result; } - /** Quaternion rotation - * @param s The first quaternion - * @param v The second quaternion + /** + * Quaternion rotation + * + * @param s The first quaternion + * @param v The second quaternion * @return The resulting quaternion */ private double[] qMult(double[] s, double[] v) { double[] r = new double[4]; - r[0] = s[0]*v[0] - s[1]*v[1] - s[2]*v[2] - s[3]*v[3]; - r[1] = s[0]*v[1] + s[1]*v[0] + s[2]*v[3] - s[3]*v[2]; - r[2] = s[0]*v[2] - s[1]*v[3] + s[2]*v[0] + s[3]*v[1]; - r[3] = s[0]*v[3] + s[1]*v[2] - s[2]*v[1] + s[3]*v[0]; + r[0] = s[0] * v[0] - s[1] * v[1] - s[2] * v[2] - s[3] * v[3]; + r[1] = s[0] * v[1] + s[1] * v[0] + s[2] * v[3] - s[3] * v[2]; + r[2] = s[0] * v[2] - s[1] * v[3] + s[2] * v[0] + s[3] * v[1]; + r[3] = s[0] * v[3] + s[1] * v[2] - s[2] * v[1] + s[3] * v[0]; return r; } - /** This method will perform a quaterion rotation + /** + * This method will perform a quaterion rotation + * * @param v The vector to rotate * @param u The vector to rotate aroung * @param alpha The rotation angle in RAD! * @return The resulting rotated vector */ private double[] rotQuad(double[] v, double[] u, double alpha) { - double[] result = new double[3]; - double[] q = new double[4]; - double[] qt = new double[4]; - double[] p = new double[4]; - double s, f; + double[] result = new double[3]; + double[] q = new double[4]; + double[] qt = new double[4]; + double[] p = new double[4]; + double s, f; - p[0] = 0; - p[1] = v[0]; - p[2] = v[1]; - p[3] = v[2]; - s = Math.cos(alpha/2.0); - f = Math.sin(alpha/2.0); - q[0] = s; - q[1] = u[0]*f; - q[2] = u[1]*f; - q[3] = u[2]*f; + p[0] = 0; + p[1] = v[0]; + p[2] = v[1]; + p[3] = v[2]; + s = Math.cos(alpha / 2.0); + f = Math.sin(alpha / 2.0); + q[0] = s; + q[1] = u[0] * f; + q[2] = u[1] * f; + q[3] = u[2] * f; // ok bis hier hin - qt[0] = s; - qt[1] = -q[1]; - qt[2] = -q[2]; - qt[3] = -q[3]; - p = this.qMult(q, p); - p = this.qMult(p, qt); - f = 1/(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]); - result[0] = p[1];// * f; - result[1] = p[2]; // * f; - result[2] = p[3]; // * f; + qt[0] = s; + qt[1] = -q[1]; + qt[2] = -q[2]; + qt[3] = -q[3]; + p = this.qMult(q, p); + p = this.qMult(p, qt); + f = 1 / (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]); + result[0] = p[1];// * f; + result[1] = p[2]; // * f; + result[2] = p[3]; // * f; result = this.getNormalized(result); return result; } @@ -554,7 +573,7 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl tmp1 = this.getScalarMultiplication(Math.cos(a), p); tmp2 = this.getScalarMultiplication(this.getScalarProduct(w, p), p); - tmp2 = this.getScalarMultiplication((1-Math.cos(a)), tmp2); + tmp2 = this.getScalarMultiplication((1 - Math.cos(a)), tmp2); tmp3 = this.getScalarMultiplication(Math.sin(a), this.getCrossProduct(w, p)); result = this.getVectorAdd(tmp1, tmp2); result = this.getVectorAdd(result, tmp3); @@ -709,12 +728,14 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl // System.exit(0); // } - /** This method writes Data to file. - * @param line The line that is to be added to the file + /** + * This method writes Data to file. + * + * @param line The line that is to be added to the file */ private void writeToFile(BufferedWriter out, String line) { String write = line + "\n"; - write.replaceAll(",","."); + write.replaceAll(",", "."); if (out == null) { return; } @@ -729,47 +750,60 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is migration scheme, which implements a cone separation based partitioning."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MOConeSeparation"; } - /** This method allows you to toggle which elements are + /** + * This method allows you to toggle which elements are * to be used to calculate the reference point. If false * all individuals are used to calculate the reference point. * This can cause the algorithm to build cone segments, which * are actually all dominated. + * * @return The modus to calculate the reference point. */ public boolean getUseAllToDetermineR() { return this.m_UseAllToDetermineR; } - public void setUseAllToDetermineR(boolean b){ + + public void setUseAllToDetermineR(boolean b) { this.m_UseAllToDetermineR = b; } + public String useAllToDetermineRTipText() { return "If true all individuals are used to calculate the reference point (may reduce efficiency)."; } - /** This method allows you to toogle the use of constraints, + /** + * This method allows you to toogle the use of constraints, * which enable the algorithm to limit each island to a * specific area of the search space. + * * @return The modus of constraints. */ public boolean getUseConstraints() { return this.m_UseConstraints; } - public void setUseConstraints(boolean b){ + + public void setUseConstraints(boolean b) { this.m_UseConstraints = b; } + public String useConstraintsTipText() { return "If activated constraints are used to limit each island to a local area."; } diff --git a/src/eva2/optimization/operator/migration/MOXMeansSeparation.java b/src/eva2/optimization/operator/migration/MOXMeansSeparation.java index 9ca8fde6..66179492 100644 --- a/src/eva2/optimization/operator/migration/MOXMeansSeparation.java +++ b/src/eva2/optimization/operator/migration/MOXMeansSeparation.java @@ -16,11 +16,13 @@ import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; + import java.io.*; -/** This method implements the clustering based subdivision +/** + * This method implements the clustering based subdivision * scheme suited to identify uni- and multi-modal search spaces - * under development and currently defunct. + * under development and currently defunct. * Created by IntelliJ IDEA. * User: streiche * Date: 24.06.2005 @@ -29,38 +31,40 @@ import java.io.*; */ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializable { - public boolean m_Debug = false; - private ClusteringXMeans m_XMeans = new ClusteringXMeans(); - private ArchivingNSGAII m_NSGAII = new ArchivingNSGAII(); - private boolean m_UseConstraints = true; - private InterfaceSelection m_Selection = new SelectRandom(); + public boolean m_Debug = false; + private ClusteringXMeans m_XMeans = new ClusteringXMeans(); + private ArchivingNSGAII m_NSGAII = new ArchivingNSGAII(); + private boolean m_UseConstraints = true; + private InterfaceSelection m_Selection = new SelectRandom(); public MOXMeansSeparation() { } public MOXMeansSeparation(MOXMeansSeparation b) { - this.m_Debug = b.m_Debug; - this.m_UseConstraints = b.m_UseConstraints; + this.m_Debug = b.m_Debug; + this.m_UseConstraints = b.m_UseConstraints; if (b.m_XMeans != null) { - this.m_XMeans = (ClusteringXMeans)b.m_XMeans.clone(); + this.m_XMeans = (ClusteringXMeans) b.m_XMeans.clone(); } if (b.m_NSGAII != null) { - this.m_NSGAII = (ArchivingNSGAII)b.m_NSGAII.clone(); + this.m_NSGAII = (ArchivingNSGAII) b.m_NSGAII.clone(); } if (b.m_Selection != null) { - this.m_Selection = (InterfaceSelection)b.m_Selection.clone(); + this.m_Selection = (InterfaceSelection) b.m_Selection.clone(); } } - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new MOXMeansSeparation(this); } - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ @Override @@ -68,7 +72,8 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa // pff at a later stage i could initialize a topology here } - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this @@ -80,22 +85,22 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa */ @Override public void migrate(InterfaceOptimizer[] islands) { - Population[] oldIPOP = new Population[islands.length]; - Population[] newIPOP = new Population[islands.length]; - Population collector = new Population(), memory; - AbstractEAIndividual indy; + Population[] oldIPOP = new Population[islands.length]; + Population[] newIPOP = new Population[islands.length]; + Population collector = new Population(), memory; + AbstractEAIndividual indy; // collect the populations for (int i = 0; i < islands.length; i++) { oldIPOP[i] = islands[i].getPopulation(); if (this.m_Debug) { - System.out.println("Got population from "+i+" of size "+oldIPOP[i].size()); + System.out.println("Got population from " + i + " of size " + oldIPOP[i].size()); } - collector.addPopulation((Population)oldIPOP[i].clone()); + collector.addPopulation((Population) oldIPOP[i].clone()); //if (oldIPOP[i].getArchive() != null) collector.addPopulation((Population)oldIPOP[i].getArchive().clone()); newIPOP[i] = new Population(); } - memory = (Population)collector.clone(); + memory = (Population) collector.clone(); // if (this.m_Debug) { // // let's see how they arrive here @@ -122,8 +127,8 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa // } // Now lets cluster this stuff - Population[] archives = this.m_NSGAII.getNonDominatedSortedFronts(collector); - Population toCluster = new Population(); + Population[] archives = this.m_NSGAII.getNonDominatedSortedFronts(collector); + Population toCluster = new Population(); int currentFront = 0; toCluster.addPopulation(archives[currentFront]); while (toCluster.size() < islands.length) { @@ -133,7 +138,7 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa // first set the K to the K-Means this.m_XMeans.setMaxK(islands.length); - this.m_XMeans.cluster(toCluster, (Population)null); + this.m_XMeans.cluster(toCluster, (Population) null); double[][] c = this.m_XMeans.getC(); //@todo Hier muss ich mal denk machen und weniger click... newIPOP = this.m_XMeans.cluster(collector, c); @@ -142,31 +147,31 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa islands[i].getPopulation().setTargetSize(0); } if (this.m_Debug) { - Plot plot; - double[] tmpD = new double[2]; + Plot plot; + double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; plot = new Plot("Debugging Clustering Separation", "Y1", "Y2", tmpD, tmpD); - GraphPointSet mySet; - DPoint myPoint; - Chart2DDPointIconText tmp; + GraphPointSet mySet; + DPoint myPoint; + Chart2DDPointIconText tmp; for (int i = 0; i < newIPOP.length; i++) { - mySet = new GraphPointSet(10+1, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + 1, plot.getFunctionArea()); mySet.setConnectedMode(false); for (int j = 0; j < newIPOP[i].size(); j++) { - indy = (AbstractEAIndividual)newIPOP[i].get(j); + indy = (AbstractEAIndividual) newIPOP[i].get(j); myPoint = new DPoint(indy.getFitness()[0], indy.getFitness()[1]); - tmp = new Chart2DDPointIconText(""+i); + tmp = new Chart2DDPointIconText("" + i); //if (i % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } } - mySet = new GraphPointSet(10+2, plot.getFunctionArea()); + mySet = new GraphPointSet(10 + 2, plot.getFunctionArea()); mySet.setConnectedMode(false); for (int i = 0; i < c.length; i++) { myPoint = new DPoint(c[i][0], c[i][1]); - tmp = new Chart2DDPointIconText(""+i); + tmp = new Chart2DDPointIconText("" + i); tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); @@ -182,9 +187,9 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { // set the boundaries to perform the constrained // domain principle introduced by Deb et al. - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.clear(); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.clear(); double[] myClass = c[i]; - double[][] myOtherClass = new double[c.length -1][]; + double[][] myOtherClass = new double[c.length - 1][]; int index = 0; for (int j = 0; j < myOtherClass.length; j++) { if (index == i) { @@ -194,7 +199,7 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa index++; } ConstBelongsToDifferentClass b = new ConstBelongsToDifferentClass(myClass, myOtherClass, this.m_XMeans.getUseSearchSpace()); - ((AbstractMultiObjectiveOptimizationProblem)prob).m_AreaConst4Parallelization.add(b); + ((AbstractMultiObjectiveOptimizationProblem) prob).m_AreaConst4Parallelization.add(b); // if (this.m_Debug) { // String out = ""; // out += i+ ". MyClass: {"; @@ -226,7 +231,7 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getFreeSlots())); } if (this.m_Debug) { - System.out.println("Setting "+i+" to population size " + oldIPOP[i].size()); + System.out.println("Setting " + i + " to population size " + oldIPOP[i].size()); } islands[i].setPopulation(oldIPOP[i]); islands[i].getPopulation().setTargetSize(oldIPOP[i].size()); @@ -335,12 +340,14 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa // System.exit(0); // } - /** This method writes Data to file. - * @param line The line that is to be added to the file + /** + * This method writes Data to file. + * + * @param line The line that is to be added to the file */ private void writeToFile(BufferedWriter out, String line) { String write = line + "\n"; - write.replaceAll(",","."); + write.replaceAll(",", "."); if (out == null) { return; } @@ -355,43 +362,56 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is migration scheme, which implements a clustering based partitioning."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MOClusteringSeparation"; } - /** This method allows you to set/get the clustering algorithm. + /** + * This method allows you to set/get the clustering algorithm. + * * @return The clustering algorithm method */ public ClusteringXMeans getXMeans() { return this.m_XMeans; } - public void setXMeans(ClusteringXMeans b){ + + public void setXMeans(ClusteringXMeans b) { this.m_XMeans = b; } + public String xMeansTipText() { return "Parameterize the clustering algorithm."; } - /** This method allows you to toogle the use of constraints, + /** + * This method allows you to toogle the use of constraints, * which enable the algorithm to limit each island to a * specific area of the search space. + * * @return The modus of constraints. */ public boolean getUseConstraints() { return this.m_UseConstraints; } - public void setUseConstraints(boolean b){ + + public void setUseConstraints(boolean b) { this.m_UseConstraints = b; } + public String useConstraintsTipText() { return "If activated constraints are used to limit each island to a local area."; } diff --git a/src/eva2/optimization/operator/migration/SOBestMigration.java b/src/eva2/optimization/operator/migration/SOBestMigration.java index 45e8aaf8..a5471d0e 100644 --- a/src/eva2/optimization/operator/migration/SOBestMigration.java +++ b/src/eva2/optimization/operator/migration/SOBestMigration.java @@ -6,7 +6,8 @@ import eva2.optimization.operator.selection.SelectBestIndividuals; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; -/** Simple single-objective migration scheme. +/** + * Simple single-objective migration scheme. * Created by IntelliJ IDEA. * User: streiche * Date: 15.09.2004 @@ -15,16 +16,19 @@ import eva2.optimization.strategies.InterfaceOptimizer; */ public class SOBestMigration implements InterfaceMigration, java.io.Serializable { - private InterfaceSelection m_Selection = new SelectBestIndividuals(); - private int m_N = 5; - /** The ever present clone method + private InterfaceSelection m_Selection = new SelectBestIndividuals(); + private int m_N = 5; + + /** + * The ever present clone method */ @Override public Object clone() { return new SOBestMigration(); } - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ @Override @@ -32,7 +36,8 @@ public class SOBestMigration implements InterfaceMigration, java.io.Serializable // pff at a later stage i could initialize a topology here } - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this @@ -44,15 +49,15 @@ public class SOBestMigration implements InterfaceMigration, java.io.Serializable */ @Override public void migrate(InterfaceOptimizer[] islands) { - Population[] oldIPOP = new Population[islands.length]; - Population[] newIPOP = new Population[islands.length]; - Population[] comSet; - Population selected; + Population[] oldIPOP = new Population[islands.length]; + Population[] newIPOP = new Population[islands.length]; + Population[] comSet; + Population selected; // collect the populations for (int i = 0; i < islands.length; i++) { oldIPOP[i] = islands[i].getPopulation(); - newIPOP[i] = (Population)oldIPOP[i].clone(); + newIPOP[i] = (Population) oldIPOP[i].clone(); } // perform migration for each ipop @@ -62,10 +67,10 @@ public class SOBestMigration implements InterfaceMigration, java.io.Serializable comSet = oldIPOP; // todo: Here i could implement multiple selection and replacement schemes - newIPOP[i].removeNIndividuals(comSet.length*this.m_N); - for(int j = 0; j < comSet.length; j++) { + newIPOP[i].removeNIndividuals(comSet.length * this.m_N); + for (int j = 0; j < comSet.length; j++) { selected = this.m_Selection.selectFrom(comSet[j], this.m_N); - newIPOP[i].add(((AbstractEAIndividual)selected.get(0)).clone()); + newIPOP[i].add(((AbstractEAIndividual) selected.get(0)).clone()); } } @@ -77,45 +82,58 @@ public class SOBestMigration implements InterfaceMigration, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a single-objective migration scheme."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "SOBestMigration"; } - /** This method allows you to set/get the selection method for migration. + /** + * This method allows you to set/get the selection method for migration. + * * @return The selection method */ public InterfaceSelection getSelection() { return this.m_Selection; } - public void setSelection(InterfaceSelection b){ + + public void setSelection(InterfaceSelection b) { this.m_Selection = b; } + public String selectionTipText() { return "Choose the selection method for migration."; } - /** This method allows you to set/get the number of individuals + /** + * This method allows you to set/get the number of individuals * to migrate per migration event. + * * @return The current number of individuals to migrate */ public int getN() { return this.m_N; } - public void setN(int b){ + + public void setN(int b) { if (b < 1) { b = 1; } this.m_N = b; } + public String nTipText() { return "The number of individuals to migrate per migration event."; } diff --git a/src/eva2/optimization/operator/migration/SOMONoMigration.java b/src/eva2/optimization/operator/migration/SOMONoMigration.java index 872b4c2a..d6760b19 100644 --- a/src/eva2/optimization/operator/migration/SOMONoMigration.java +++ b/src/eva2/optimization/operator/migration/SOMONoMigration.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.migration; import eva2.optimization.strategies.InterfaceOptimizer; -/** Implements no migration as reference. +/** + * Implements no migration as reference. * Created by IntelliJ IDEA. * User: streiche * Date: 16.09.2004 @@ -11,14 +12,16 @@ import eva2.optimization.strategies.InterfaceOptimizer; */ public class SOMONoMigration implements InterfaceMigration, java.io.Serializable { - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new SOMONoMigration(); } - /** Typically i'll need some initialization method for + /** + * Typically i'll need some initialization method for * every bit of code i write.... */ @Override @@ -26,7 +29,8 @@ public class SOMONoMigration implements InterfaceMigration, java.io.Serializable } - /** The migrate method can be called asychnronously or + /** + * The migrate method can be called asychnronously or * sychronously. Basically it allows migration of individuals * between multiple EA islands and since there are so many * different possible strategies i've introduced this @@ -44,13 +48,18 @@ public class SOMONoMigration implements InterfaceMigration, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is actually no mirgation scheme, because no individuals are exchanged."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/moso/InterfaceMOSOConverter.java b/src/eva2/optimization/operator/moso/InterfaceMOSOConverter.java index 4c5db42a..de785a64 100644 --- a/src/eva2/optimization/operator/moso/InterfaceMOSOConverter.java +++ b/src/eva2/optimization/operator/moso/InterfaceMOSOConverter.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.moso; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** The MOSO converter work on the fitness values only and convert a double[] into +/** + * The MOSO converter work on the fitness values only and convert a double[] into * a single double values, thus allowing weight aggregation, goal programming and * so on. To allow logging the original double[] values are stored in the userData * using the key "MOFitness". @@ -15,24 +16,30 @@ import eva2.optimization.population.Population; */ public interface InterfaceMOSOConverter { - /** This method makes a perfect clone + /** + * This method makes a perfect clone + * * @return the clone */ public Object clone(); - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ public void convertMultiObjective2SingleObjective(Population pop); - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim output dimension + * + * @param dim output dimension */ public void setOutputDimension(int dim); @@ -41,18 +48,24 @@ public interface InterfaceMOSOConverter { // */ // public void setOutputNames(String[] dim); - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ public void convertSingleIndividual(AbstractEAIndividual indy); - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName(); - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ public String getStringRepresentation(); diff --git a/src/eva2/optimization/operator/moso/MOSODynamicallyWeightedFitness.java b/src/eva2/optimization/operator/moso/MOSODynamicallyWeightedFitness.java index c723f51a..3bacc3fb 100644 --- a/src/eva2/optimization/operator/moso/MOSODynamicallyWeightedFitness.java +++ b/src/eva2/optimization/operator/moso/MOSODynamicallyWeightedFitness.java @@ -12,64 +12,72 @@ import eva2.optimization.population.Population; */ public class MOSODynamicallyWeightedFitness implements InterfaceMOSOConverter, java.io.Serializable { - private double m_F = 50; - private int m_CurrentGeneration = 0; - private int m_OutputDimension = 2; + private double m_F = 50; + private int m_CurrentGeneration = 0; + private int m_OutputDimension = 2; public MOSODynamicallyWeightedFitness() { } + public MOSODynamicallyWeightedFitness(MOSODynamicallyWeightedFitness b) { - this.m_CurrentGeneration = b.m_CurrentGeneration; - this.m_F = b.m_F; - this.m_OutputDimension = b.m_OutputDimension; + this.m_CurrentGeneration = b.m_CurrentGeneration; + this.m_F = b.m_F; + this.m_OutputDimension = b.m_OutputDimension; } + @Override public Object clone() { return (Object) new MOSODynamicallyWeightedFitness(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { this.m_CurrentGeneration = pop.getGeneration(); for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; - double[] weights; + double[] resultFit = new double[1]; + double[] tmpFit; + double[] weights; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); weights = new double[tmpFit.length]; // calculate the dynamic weights - weights[0] = Math.pow(Math.sin(2*Math.PI*(double)this.m_CurrentGeneration/this.m_F), 2); + weights[0] = Math.pow(Math.sin(2 * Math.PI * (double) this.m_CurrentGeneration / this.m_F), 2); weights[1] = 1 - weights[0]; - for (int i = 0; (i <2) && (i < tmpFit.length); i++) { - resultFit[0] += tmpFit[i]*weights[i]; + for (int i = 0; (i < 2) && (i < tmpFit.length); i++) { + resultFit[0] += tmpFit[i] * weights[i]; } indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -77,19 +85,24 @@ public class MOSODynamicallyWeightedFitness implements InterfaceMOSOConverter, j // i think as far as i got not solution for the (n>2) dimensional case // i could simply ignore this.... } - /** This method returns a description of the objective + + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -97,22 +110,28 @@ public class MOSODynamicallyWeightedFitness implements InterfaceMOSOConverter, j return "Dynamic Weighted Sum"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method calcuates a dynamic weighted sum over TWO fitness values depending on the current generation."; } - /** This method allows you to choose the frequency for the change of the weights. - * @param f The frequency of change. + /** + * This method allows you to choose the frequency for the change of the weights. + * + * @param f The frequency of change. */ public void setF(double f) { this.m_F = f; } + public double getF() { return this.m_F; } + public String fTipText() { return "Choose the frequency for the fitness value."; } diff --git a/src/eva2/optimization/operator/moso/MOSOEpsilonConstraint.java b/src/eva2/optimization/operator/moso/MOSOEpsilonConstraint.java index 94d810f5..079cb1e3 100644 --- a/src/eva2/optimization/operator/moso/MOSOEpsilonConstraint.java +++ b/src/eva2/optimization/operator/moso/MOSOEpsilonConstraint.java @@ -13,7 +13,7 @@ import eva2.optimization.population.Population; */ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Serializable { - private PropertyEpsilonConstraint m_EpsilonConstraint = null; + private PropertyEpsilonConstraint m_EpsilonConstraint = null; public MOSOEpsilonConstraint() { this.m_EpsilonConstraint = new PropertyEpsilonConstraint(); @@ -27,35 +27,40 @@ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Se public MOSOEpsilonConstraint(MOSOEpsilonConstraint b) { if (b.m_EpsilonConstraint != null) { - this.m_EpsilonConstraint = (PropertyEpsilonConstraint)b.m_EpsilonConstraint.clone(); + this.m_EpsilonConstraint = (PropertyEpsilonConstraint) b.m_EpsilonConstraint.clone(); } } + @Override public Object clone() { return (Object) new MOSOEpsilonConstraint(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); @@ -68,10 +73,12 @@ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Se indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -84,26 +91,30 @@ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Se newTarget[i] = this.m_EpsilonConstraint.m_TargetValue[i]; } if (this.m_EpsilonConstraint.m_OptimizeObjective >= dim) { - this.m_EpsilonConstraint.m_OptimizeObjective = dim-1; + this.m_EpsilonConstraint.m_OptimizeObjective = dim - 1; } this.m_EpsilonConstraint.m_TargetValue = newTarget; } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -111,22 +122,28 @@ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Se return "Epsilon Constraint"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method uses n-1 objected as hard constraints."; } - /** This method allows you to choose the EpsilonThreshold - * @param weights The Epsilon Threshhold for the fitness sum. + /** + * This method allows you to choose the EpsilonThreshold + * + * @param weights The Epsilon Threshhold for the fitness sum. */ public void setEpsilonThreshhold(PropertyEpsilonConstraint weights) { this.m_EpsilonConstraint = weights; } + public PropertyEpsilonConstraint getEpsilonThreshhold() { return this.m_EpsilonConstraint; } + public String epsilonThreshholdTipText() { return "Choose the epsilon constraints for the fitness sum."; } diff --git a/src/eva2/optimization/operator/moso/MOSOEpsilonThreshold.java b/src/eva2/optimization/operator/moso/MOSOEpsilonThreshold.java index a7693290..7e6407c2 100644 --- a/src/eva2/optimization/operator/moso/MOSOEpsilonThreshold.java +++ b/src/eva2/optimization/operator/moso/MOSOEpsilonThreshold.java @@ -13,7 +13,7 @@ import eva2.optimization.population.Population; */ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Serializable { - private PropertyEpsilonThreshold m_EpsilonThreshold = null; + private PropertyEpsilonThreshold m_EpsilonThreshold = null; public MOSOEpsilonThreshold() { this.m_EpsilonThreshold = new PropertyEpsilonThreshold(); @@ -32,35 +32,40 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser public MOSOEpsilonThreshold(MOSOEpsilonThreshold b) { if (b.m_EpsilonThreshold != null) { - this.m_EpsilonThreshold = (PropertyEpsilonThreshold)b.m_EpsilonThreshold.clone(); + this.m_EpsilonThreshold = (PropertyEpsilonThreshold) b.m_EpsilonThreshold.clone(); } } + @Override public Object clone() { return (Object) new MOSOEpsilonThreshold(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); @@ -96,10 +101,12 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -115,27 +122,31 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser newTarget[i] = this.m_EpsilonThreshold.m_TargetValue[i]; } if (this.m_EpsilonThreshold.m_OptimizeObjective >= dim) { - this.m_EpsilonThreshold.m_OptimizeObjective = dim-1; + this.m_EpsilonThreshold.m_OptimizeObjective = dim - 1; } this.m_EpsilonThreshold.m_Punishment = newPunish; this.m_EpsilonThreshold.m_TargetValue = newTarget; } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -143,22 +154,28 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser return "Epsilon Threshold"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method uses n-1 objected as soft constraints."; } - /** This method allows you to choose the EpsilonThreshold - * @param weights The Epsilon Threshhold for the fitness sum. + /** + * This method allows you to choose the EpsilonThreshold + * + * @param weights The Epsilon Threshhold for the fitness sum. */ public void setEpsilonThreshhold(PropertyEpsilonThreshold weights) { this.m_EpsilonThreshold = weights; } + public PropertyEpsilonThreshold getEpsilonThreshhold() { return this.m_EpsilonThreshold; } + public String epsilonThreshholdTipText() { return "Choose the epsilon thresholds for the fitness sum."; } diff --git a/src/eva2/optimization/operator/moso/MOSOGoalProgramming.java b/src/eva2/optimization/operator/moso/MOSOGoalProgramming.java index 957fb385..f6bd4f6d 100644 --- a/src/eva2/optimization/operator/moso/MOSOGoalProgramming.java +++ b/src/eva2/optimization/operator/moso/MOSOGoalProgramming.java @@ -13,7 +13,7 @@ import eva2.optimization.population.Population; */ public class MOSOGoalProgramming implements InterfaceMOSOConverter, java.io.Serializable { - private PropertyDoubleArray m_Goals = null; + private PropertyDoubleArray m_Goals = null; public MOSOGoalProgramming() { double[] tmpD = new double[2]; @@ -22,51 +22,59 @@ public class MOSOGoalProgramming implements InterfaceMOSOConverter, java.io.Seri } this.m_Goals = new PropertyDoubleArray(tmpD); } + public MOSOGoalProgramming(MOSOGoalProgramming b) { if (b.m_Goals != null) { - this.m_Goals = (PropertyDoubleArray)b.m_Goals; + this.m_Goals = (PropertyDoubleArray) b.m_Goals; } } + @Override public Object clone() { return (Object) new MOSOGoalProgramming(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); resultFit[0] = 0; - for (int i = 0; (i < this.m_Goals.getNumRows()) && (i < tmpFit.length) ; i++) { - resultFit[0] += tmpFit[i]-this.m_Goals.getValue(i, 0); + for (int i = 0; (i < this.m_Goals.getNumRows()) && (i < tmpFit.length); i++) { + resultFit[0] += tmpFit[i] - this.m_Goals.getValue(i, 0); } indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -76,26 +84,30 @@ public class MOSOGoalProgramming implements InterfaceMOSOConverter, java.io.Seri newWeights[i] = 0.0; } for (int i = 0; (i < this.m_Goals.getNumRows()) && (i < newWeights.length); i++) { - newWeights[i] = this.m_Goals.getValue(i,0); + newWeights[i] = this.m_Goals.getValue(i, 0); } this.m_Goals.setDoubleArray(newWeights); } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -103,22 +115,28 @@ public class MOSOGoalProgramming implements InterfaceMOSOConverter, java.io.Seri return "Goal Programming"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method minimizes the delta to a given target fitness values."; } - /** This method allows you to choose the goals for goal programming - * @param goals The weights for the fitness sum. + /** + * This method allows you to choose the goals for goal programming + * + * @param goals The weights for the fitness sum. */ public void setGoals(PropertyDoubleArray goals) { this.m_Goals = goals; } + public PropertyDoubleArray getGoals() { return this.m_Goals; } + public String goalsTipText() { return "Choose the goals for the fitness values."; } diff --git a/src/eva2/optimization/operator/moso/MOSOLpMetric.java b/src/eva2/optimization/operator/moso/MOSOLpMetric.java index fccafc03..07f4bcb0 100644 --- a/src/eva2/optimization/operator/moso/MOSOLpMetric.java +++ b/src/eva2/optimization/operator/moso/MOSOLpMetric.java @@ -13,8 +13,8 @@ import eva2.optimization.population.Population; */ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializable { - private PropertyDoubleArray m_Reference = null; - private int m_P = 2; + private PropertyDoubleArray m_Reference = null; + private int m_P = 2; public MOSOLpMetric() { double[] tmpD = new double[2]; @@ -23,38 +23,44 @@ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializabl } this.m_Reference = new PropertyDoubleArray(tmpD); } + public MOSOLpMetric(MOSOLpMetric b) { this.m_P = b.m_P; if (b.m_Reference != null) { - this.m_Reference = (PropertyDoubleArray)b.m_Reference.clone(); + this.m_Reference = (PropertyDoubleArray) b.m_Reference.clone(); } } + @Override public Object clone() { return (Object) new MOSOLpMetric(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); @@ -62,24 +68,26 @@ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializabl // standard Lp Metric resultFit[0] = 0; for (int i = 0; (i < this.m_Reference.getNumRows()) && (i < tmpFit.length); i++) { - resultFit[0] += Math.pow(Math.abs(tmpFit[i]-this.m_Reference.getValue(i,0)), this.m_P); + resultFit[0] += Math.pow(Math.abs(tmpFit[i] - this.m_Reference.getValue(i, 0)), this.m_P); } - resultFit[0] = Math.pow(resultFit[0], 1/((double)this.m_P)); + resultFit[0] = Math.pow(resultFit[0], 1 / ((double) this.m_P)); } else { // Tchebycheff metric resultFit[0] = Double.NEGATIVE_INFINITY; for (int i = 0; (i < this.m_Reference.getNumRows()) && (i < tmpFit.length); i++) { - resultFit[0] += Math.max(Math.abs(tmpFit[i]-this.m_Reference.getValue(i,0)), resultFit[0]); + resultFit[0] += Math.max(Math.abs(tmpFit[i] - this.m_Reference.getValue(i, 0)), resultFit[0]); } } indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -89,23 +97,25 @@ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializabl newWeights[i] = 0.0; } for (int i = 0; (i < this.m_Reference.getNumRows()) && (i < newWeights.length); i++) { - newWeights[i] = this.m_Reference.getValue(i,0); + newWeights[i] = this.m_Reference.getValue(i, 0); } this.m_Reference.setDoubleArray(newWeights); } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { String result = "Lp Metric\n"; - result += " P = "+this.m_P+"\n"; + result += " P = " + this.m_P + "\n"; result += " Ref.Fitness = ("; for (int i = 0; i < m_Reference.getNumRows(); i++) { - result += m_Reference.getValue(i,0); - if (i < (m_Reference.getNumRows()-1)) { + result += m_Reference.getValue(i, 0); + if (i < (m_Reference.getNumRows() - 1)) { result += "; "; } } @@ -116,8 +126,10 @@ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializabl /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -125,35 +137,45 @@ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializabl return "Lp Metric"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method minimizes the Lp metric to a given target fitness values, for (p<1) this equals the Tchebycheff metric."; } - /** This method allows you to choose the reference for the Lp Metric - * @param reference The reference vector. + /** + * This method allows you to choose the reference for the Lp Metric + * + * @param reference The reference vector. */ public void setReference(PropertyDoubleArray reference) { this.m_Reference = reference; } + public PropertyDoubleArray getReference() { return this.m_Reference; } + public String referenceTipText() { return "Choose the reference for the fitness values."; } - /** This method allows you to choose the p for the Lp Metric + /** + * This method allows you to choose the p for the Lp Metric + * * @param p */ public void setP(int p) { this.m_P = Math.max(1, p); } + public int getP() { return this.m_P; } + public String pTipText() { return "Choose the exponent p for the Lp metric, if (p<1) this results in the Tchebycheff metric."; } diff --git a/src/eva2/optimization/operator/moso/MOSOMOGARankBased.java b/src/eva2/optimization/operator/moso/MOSOMOGARankBased.java index a997476b..f68bcaca 100644 --- a/src/eva2/optimization/operator/moso/MOSOMOGARankBased.java +++ b/src/eva2/optimization/operator/moso/MOSOMOGARankBased.java @@ -14,19 +14,23 @@ public class MOSOMOGARankBased implements InterfaceMOSOConverter, java.io.Serial public MOSOMOGARankBased() { } + public MOSOMOGARankBased(MOSOMOGARankBased b) { } + @Override public Object clone() { return (Object) new MOSOMOGARankBased(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { @@ -34,61 +38,69 @@ public class MOSOMOGARankBased implements InterfaceMOSOConverter, java.io.Serial for (int i = 0; i < MOGARank.length; i++) { MOGARank[i] = 1; } - for (int i = 0; i < pop.size()-1; i++) { + for (int i = 0; i < pop.size() - 1; i++) { for (int j = 0; j < pop.size(); j++) { if (i != j) { - if (((AbstractEAIndividual)pop.get(j)).isDominatingDebConstraints((AbstractEAIndividual)pop.get(i))) { + if (((AbstractEAIndividual) pop.get(j)).isDominatingDebConstraints((AbstractEAIndividual) pop.get(i))) { MOGARank[i] += 1; } } } } for (int i = 0; i < pop.size(); i++) { - ((AbstractEAIndividual)pop.get(i)).putData("MOGARank", new Integer(MOGARank[i])); + ((AbstractEAIndividual) pop.get(i)).putData("MOGARank", new Integer(MOGARank[i])); } for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); - resultFit[0] = ((Integer)indy.getData("MOGARank")).doubleValue(); + resultFit[0] = ((Integer) indy.getData("MOGARank")).doubleValue(); indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -96,7 +108,9 @@ public class MOSOMOGARankBased implements InterfaceMOSOConverter, java.io.Serial return "MOGA Rank Based"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSOMaxiMin.java b/src/eva2/optimization/operator/moso/MOSOMaxiMin.java index 1606519d..20546b33 100644 --- a/src/eva2/optimization/operator/moso/MOSOMaxiMin.java +++ b/src/eva2/optimization/operator/moso/MOSOMaxiMin.java @@ -14,44 +14,48 @@ import eva2.tools.math.RNG; */ public class MOSOMaxiMin implements InterfaceMOSOConverter, java.io.Serializable { - private int m_OutputDimension = 2; + private int m_OutputDimension = 2; transient protected Plot m_Plot = null; public MOSOMaxiMin() { } + public MOSOMaxiMin(MOSOMaxiMin b) { - this.m_OutputDimension = b.m_OutputDimension; + this.m_OutputDimension = b.m_OutputDimension; } + @Override public Object clone() { return (Object) new MOSOMaxiMin(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { AbstractEAIndividual tmpIndy; - double[][] fitnessArray, minArray; - double[] result, tmpFit, resultFit; - double tmpResult; + double[][] fitnessArray, minArray; + double[] result, tmpFit, resultFit; + double tmpResult; - tmpIndy = (AbstractEAIndividual) pop.get(0); - fitnessArray = new double[pop.size()][tmpIndy.getFitness().length]; - minArray = new double[pop.size()][tmpIndy.getFitness().length]; - result = new double[pop.size()]; - resultFit = new double[1]; + tmpIndy = (AbstractEAIndividual) pop.get(0); + fitnessArray = new double[pop.size()][tmpIndy.getFitness().length]; + minArray = new double[pop.size()][tmpIndy.getFitness().length]; + result = new double[pop.size()]; + resultFit = new double[1]; for (int i = 0; i < pop.size(); i++) { fitnessArray[i] = ((AbstractEAIndividual) pop.get(i)).getFitness(); } for (int i = 0; i < fitnessArray.length; i++) { result[i] = Double.NEGATIVE_INFINITY; - for (int k = 0; k < fitnessArray.length; k++) { + for (int k = 0; k < fitnessArray.length; k++) { if (i != k) { tmpResult = Double.POSITIVE_INFINITY; for (int j = 0; j < fitnessArray[k].length; j++) { @@ -63,10 +67,10 @@ public class MOSOMaxiMin implements InterfaceMOSOConverter, java.io.Serializable // result[i] is now negative and big for good individuals //result[i] = Math.exp(this.m_ScalingFactor * result[i]); // write the result to the individuals - tmpIndy = (AbstractEAIndividual) pop.get(i); - tmpFit = tmpIndy.getFitness(); + tmpIndy = (AbstractEAIndividual) pop.get(i); + tmpFit = tmpIndy.getFitness(); tmpIndy.putData("MOFitness", tmpFit); - resultFit = new double[1]; + resultFit = new double[1]; resultFit[0] = result[i]; tmpIndy.setFitness(resultFit); } @@ -98,45 +102,53 @@ public class MOSOMaxiMin implements InterfaceMOSOConverter, java.io.Serializable // } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; - tmpFit = indy.getFitness(); + tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); System.err.println("The MaxiMin MOSO can not be applied to single individuals! I default to random criterion."); - resultFit[0] = tmpFit[RNG.randomInt(0, tmpFit.length)]; + resultFit[0] = tmpFit[RNG.randomInt(0, tmpFit.length)]; indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { this.m_OutputDimension = dim; } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -144,7 +156,9 @@ public class MOSOMaxiMin implements InterfaceMOSOConverter, java.io.Serializable return "MaxiMin Criterium"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSONoConvert.java b/src/eva2/optimization/operator/moso/MOSONoConvert.java index b4806c72..e42ab572 100644 --- a/src/eva2/optimization/operator/moso/MOSONoConvert.java +++ b/src/eva2/optimization/operator/moso/MOSONoConvert.java @@ -14,64 +14,76 @@ public class MOSONoConvert implements InterfaceMOSOConverter, java.io.Serializab public MOSONoConvert() { } + public MOSONoConvert(MOSONoConvert b) { } + @Override public Object clone() { return (Object) new MOSONoConvert(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] tmpFit; + double[] tmpFit; - tmpFit = indy.getFitness(); + tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); // resultFit[0] = tmpFit[RNG.randomInt(0, tmpFit.length)]; // indy.SetFitness(resultFit); - } + } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension + * + * @param dim Outputdimension */ @Override public void setOutputDimension(int dim) { // nothing to do here } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -79,7 +91,9 @@ public class MOSONoConvert implements InterfaceMOSOConverter, java.io.Serializab return "No Convert"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSORandomChoice.java b/src/eva2/optimization/operator/moso/MOSORandomChoice.java index db5f7209..5e7bd523 100644 --- a/src/eva2/optimization/operator/moso/MOSORandomChoice.java +++ b/src/eva2/optimization/operator/moso/MOSORandomChoice.java @@ -11,52 +11,60 @@ import eva2.tools.math.RNG; * Time: 17:56:39 * To change this template use File | Settings | File Templates. */ -public class MOSORandomChoice implements InterfaceMOSOConverter, java.io.Serializable { +public class MOSORandomChoice implements InterfaceMOSOConverter, java.io.Serializable { - private int m_OutputDimension = 2; + private int m_OutputDimension = 2; public MOSORandomChoice() { } + public MOSORandomChoice(MOSORandomChoice b) { - this.m_OutputDimension = b.m_OutputDimension; + this.m_OutputDimension = b.m_OutputDimension; } + @Override public Object clone() { return (Object) new MOSORandomChoice(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; - tmpFit = indy.getFitness(); + tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); - resultFit[0] = tmpFit[RNG.randomInt(0, tmpFit.length-1)]; + resultFit[0] = tmpFit[RNG.randomInt(0, tmpFit.length - 1)]; indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -64,22 +72,25 @@ public class MOSORandomChoice implements InterfaceMOSOConverter, java.io.Serial // i think as far as i got not solution for the (n>2) dimensional case // i could simply ignore this.... } - - /** This method returns a description of the objective + + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } - /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -87,7 +98,9 @@ public class MOSORandomChoice implements InterfaceMOSOConverter, java.io.Serial return "Random Choice"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSORandomWeight.java b/src/eva2/optimization/operator/moso/MOSORandomWeight.java index c72a7dcc..0ea234ca 100644 --- a/src/eva2/optimization/operator/moso/MOSORandomWeight.java +++ b/src/eva2/optimization/operator/moso/MOSORandomWeight.java @@ -15,82 +15,94 @@ public class MOSORandomWeight implements InterfaceMOSOConverter, java.io.Seriali public MOSORandomWeight() { } + public MOSORandomWeight(MOSORandomWeight b) { } + @Override public Object clone() { return (Object) new MOSORandomWeight(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit, tmpWeight; - double sum = 0; + double[] resultFit = new double[1]; + double[] tmpFit, tmpWeight; + double sum = 0; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); tmpWeight = new double[tmpFit.length]; for (int i = 0; i < tmpWeight.length; i++) { - tmpWeight[i] = RNG.randomDouble(0,1); + tmpWeight[i] = RNG.randomDouble(0, 1); sum += tmpWeight[i]; } if (sum <= 0.0000001) { for (int i = 0; i < tmpWeight.length; i++) { - tmpWeight[i] = 1/(double)tmpWeight.length; + tmpWeight[i] = 1 / (double) tmpWeight.length; } } else { for (int i = 0; i < tmpWeight.length; i++) { tmpWeight[i] /= sum; } } - for (int i = 0; (i < tmpWeight.length) && (i < tmpFit.length) ; i++) { - resultFit[0] += tmpFit[i]*tmpWeight[i]; + for (int i = 0; (i < tmpWeight.length) && (i < tmpFit.length); i++) { + resultFit[0] += tmpFit[i] * tmpWeight[i]; } indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } - + /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -98,7 +110,9 @@ public class MOSORandomWeight implements InterfaceMOSOConverter, java.io.Seriali return "Randomly Weighted Sum"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSORankbased.java b/src/eva2/optimization/operator/moso/MOSORankbased.java index 4de757b4..798abd64 100644 --- a/src/eva2/optimization/operator/moso/MOSORankbased.java +++ b/src/eva2/optimization/operator/moso/MOSORankbased.java @@ -15,67 +15,79 @@ public class MOSORankbased implements InterfaceMOSOConverter, java.io.Serializab public MOSORankbased() { } + public MOSORankbased(MOSORankbased b) { } + @Override public Object clone() { return (Object) new MOSORankbased(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { ArchivingNSGAII arch = new ArchivingNSGAII(); arch.getNonDominatedSortedFronts(pop); for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); - resultFit[0] = ((Integer)indy.getData("ParetoLevel")).doubleValue(); + resultFit[0] = ((Integer) indy.getData("ParetoLevel")).doubleValue(); indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { } - - /** This method returns a description of the objective + + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -83,7 +95,9 @@ public class MOSORankbased implements InterfaceMOSOConverter, java.io.Serializab return "Rank Based"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSOUtilityFunction.java b/src/eva2/optimization/operator/moso/MOSOUtilityFunction.java index 3c880b5d..30807d4b 100644 --- a/src/eva2/optimization/operator/moso/MOSOUtilityFunction.java +++ b/src/eva2/optimization/operator/moso/MOSOUtilityFunction.java @@ -13,40 +13,46 @@ import eva2.optimization.population.Population; */ public class MOSOUtilityFunction implements InterfaceMOSOConverter, java.io.Serializable { - private int m_OutputDimension = 2; + private int m_OutputDimension = 2; - public MOSOUtilityFunction () { + public MOSOUtilityFunction() { } + public MOSOUtilityFunction(MOSOUtilityFunction b) { System.out.println("Warning no source!"); - this.m_OutputDimension = b.m_OutputDimension; + this.m_OutputDimension = b.m_OutputDimension; } + @Override public Object clone() { return (Object) new MOSOUtilityFunction(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); @@ -65,28 +71,34 @@ public class MOSOUtilityFunction implements InterfaceMOSOConverter, java.io.Seri indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { this.m_OutputDimension = dim; } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } - + /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -94,7 +106,9 @@ public class MOSOUtilityFunction implements InterfaceMOSOConverter, java.io.Seri return "Utility Function"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/moso/MOSOWeightedFitness.java b/src/eva2/optimization/operator/moso/MOSOWeightedFitness.java index 0655ed19..05744c64 100644 --- a/src/eva2/optimization/operator/moso/MOSOWeightedFitness.java +++ b/src/eva2/optimization/operator/moso/MOSOWeightedFitness.java @@ -13,7 +13,7 @@ import eva2.optimization.population.Population; */ public class MOSOWeightedFitness implements InterfaceMOSOConverter, java.io.Serializable { - private PropertyDoubleArray m_Weights = null; + private PropertyDoubleArray m_Weights = null; public MOSOWeightedFitness() { double[][] tmpD = new double[2][1]; @@ -25,49 +25,53 @@ public class MOSOWeightedFitness implements InterfaceMOSOConverter, java.io.Seri this.m_Weights.normalizeColumns(); } } - + public MOSOWeightedFitness(double[][] weights) { - this(); - setWeights(new PropertyDoubleArray(weights)); + this(); + setWeights(new PropertyDoubleArray(weights)); } - + public MOSOWeightedFitness(MOSOWeightedFitness b) { if (b.m_Weights != null) { - this.m_Weights = (PropertyDoubleArray)b.m_Weights; + this.m_Weights = (PropertyDoubleArray) b.m_Weights; } } - + @Override public Object clone() { return (Object) new MOSOWeightedFitness(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); - for (int i = 0; (i < this.m_Weights.getNumRows()) && (i < tmpFit.length) ; i++) { - resultFit[0] += tmpFit[i]*this.m_Weights.getValue(i,0); + for (int i = 0; (i < this.m_Weights.getNumRows()) && (i < tmpFit.length); i++) { + resultFit[0] += tmpFit[i] * this.m_Weights.getValue(i, 0); } indy.setFitness(resultFit); } @@ -75,18 +79,20 @@ public class MOSOWeightedFitness implements InterfaceMOSOConverter, java.io.Seri private void checkingWeights() { String s = "Using Weights: {"; for (int i = 0; i < this.m_Weights.getNumRows(); i++) { - s += this.m_Weights.getValue(i,0); - if (i < this.m_Weights.getNumRows()-1) { - s+= "; "; + s += this.m_Weights.getValue(i, 0); + if (i < this.m_Weights.getNumRows() - 1) { + s += "; "; } } - System.out.println(s+"}"); + System.out.println(s + "}"); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -96,26 +102,30 @@ public class MOSOWeightedFitness implements InterfaceMOSOConverter, java.io.Seri newWeights[i] = 1; } for (int i = 0; (i < this.m_Weights.getNumRows()) && (i < newWeights.length); i++) { - newWeights[i] = this.m_Weights.getValue(i,0); + newWeights[i] = this.m_Weights.getValue(i, 0); } this.m_Weights.setDoubleArray(newWeights); } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { - return this.getName()+"\n"; + return this.getName() + "\n"; } - + /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -123,23 +133,29 @@ public class MOSOWeightedFitness implements InterfaceMOSOConverter, java.io.Seri return "Weighted Sum"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method calcuates the weighted sum over all fitness values."; } - /** This method allows you to choose the weights for the weighted + /** + * This method allows you to choose the weights for the weighted * fitness sum. - * @param weights The weights for the fitness sum. + * + * @param weights The weights for the fitness sum. */ public void setWeights(PropertyDoubleArray weights) { this.m_Weights = weights; } + public PropertyDoubleArray getWeights() { return this.m_Weights; } + public String weightsTipText() { return "Choose the weights for the fitness values."; } diff --git a/src/eva2/optimization/operator/moso/MOSOWeightedLPTchebycheff.java b/src/eva2/optimization/operator/moso/MOSOWeightedLPTchebycheff.java index 8cde84f3..618aca3c 100644 --- a/src/eva2/optimization/operator/moso/MOSOWeightedLPTchebycheff.java +++ b/src/eva2/optimization/operator/moso/MOSOWeightedLPTchebycheff.java @@ -13,10 +13,10 @@ import eva2.optimization.population.Population; */ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.io.Serializable { - private PropertyWeightedLPTchebycheff m_WLPT = null; + private PropertyWeightedLPTchebycheff m_WLPT = null; public MOSOWeightedLPTchebycheff() { - this.m_WLPT = new PropertyWeightedLPTchebycheff(); + this.m_WLPT = new PropertyWeightedLPTchebycheff(); this.m_WLPT.m_P = 0; double[] tmpD = new double[2]; for (int i = 0; i < tmpD.length; i++) { @@ -32,56 +32,63 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i public MOSOWeightedLPTchebycheff(MOSOWeightedLPTchebycheff b) { if (b.m_WLPT != null) { - this.m_WLPT = (PropertyWeightedLPTchebycheff)b.m_WLPT.clone(); + this.m_WLPT = (PropertyWeightedLPTchebycheff) b.m_WLPT.clone(); } } + @Override public Object clone() { return (Object) new MOSOWeightedLPTchebycheff(this); } - /** This method takes a population of individuals with an array of + /** + * This method takes a population of individuals with an array of * fitness values and calculates a single fitness value to replace * the former fitness array. Please note: The orignal fitness values * are lost this way, so please use the individual.setData() method * if you still want to access the original fitness values. - * @param pop The population to process. + * + * @param pop The population to process. */ @Override public void convertMultiObjective2SingleObjective(Population pop) { for (int i = 0; i < pop.size(); i++) { - this.convertSingleIndividual((AbstractEAIndividual)pop.get(i)); + this.convertSingleIndividual((AbstractEAIndividual) pop.get(i)); } } - /** This method processes a single individual - * @param indy The individual to process. + /** + * This method processes a single individual + * + * @param indy The individual to process. */ @Override public void convertSingleIndividual(AbstractEAIndividual indy) { - double[] resultFit = new double[1]; - double[] tmpFit; + double[] resultFit = new double[1]; + double[] tmpFit; tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); resultFit[0] = 0; for (int i = 0; i < tmpFit.length; i++) { if (this.m_WLPT.m_P == 0) { - resultFit[0] = Math.max(resultFit[0], this.m_WLPT.m_Weights[i]*Math.abs(tmpFit[i] - this.m_WLPT.m_IdealValue[i])); + resultFit[0] = Math.max(resultFit[0], this.m_WLPT.m_Weights[i] * Math.abs(tmpFit[i] - this.m_WLPT.m_IdealValue[i])); } else { - resultFit[0] += this.m_WLPT.m_Weights[i]*Math.pow(tmpFit[i] - this.m_WLPT.m_IdealValue[i], this.m_WLPT.m_P); + resultFit[0] += this.m_WLPT.m_Weights[i] * Math.pow(tmpFit[i] - this.m_WLPT.m_IdealValue[i], this.m_WLPT.m_P); } } if (this.m_WLPT.m_P > 0) { - resultFit[0] = Math.pow(resultFit[0], 1/((double)this.m_WLPT.m_P)); + resultFit[0] = Math.pow(resultFit[0], 1 / ((double) this.m_WLPT.m_P)); } indy.setFitness(resultFit); } - /** This method allows the problem to set the current output size of + /** + * This method allows the problem to set the current output size of * the optimization problem. Additional weights will be set to a default * value of one - * @param dim Outputdimension of the problem + * + * @param dim Outputdimension of the problem */ @Override public void setOutputDimension(int dim) { @@ -89,29 +96,31 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i double[] newWeights = new double[dim]; for (int i = 0; i < newTarget.length; i++) { - newTarget[i] = 0; - newWeights[i] = 1.0; + newTarget[i] = 0; + newWeights[i] = 1.0; } for (int i = 0; (i < this.m_WLPT.m_IdealValue.length) && (i < newTarget.length); i++) { - newTarget[i] = this.m_WLPT.m_IdealValue[i]; - newWeights[i] = this.m_WLPT.m_Weights[i]; + newTarget[i] = this.m_WLPT.m_IdealValue[i]; + newWeights[i] = this.m_WLPT.m_Weights[i]; } - this.m_WLPT.m_IdealValue = newTarget; - this.m_WLPT.m_Weights = newWeights; + this.m_WLPT.m_IdealValue = newTarget; + this.m_WLPT.m_Weights = newWeights; } - /** This method returns a description of the objective + /** + * This method returns a description of the objective + * * @return A String */ @Override public String getStringRepresentation() { String result = "Lp Metric\n"; - result += " P = "+this.m_WLPT.m_P+"\n"; + result += " P = " + this.m_WLPT.m_P + "\n"; result += " Ref.Fitness = ("; double[] p = this.m_WLPT.m_IdealValue; for (int i = 0; i < p.length; i++) { result += p[i]; - if (i < (p.length-1)) { + if (i < (p.length - 1)) { result += "; "; } } @@ -120,7 +129,7 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i p = this.m_WLPT.m_Weights; for (int i = 0; i < p.length; i++) { result += p[i]; - if (i < (p.length-1)) { + if (i < (p.length - 1)) { result += "; "; } } @@ -132,8 +141,10 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -141,22 +152,28 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i return "Lp/Tchebycheff"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method implements the Lp-problem and the Tchebycheff metric, the weighted version is also known as compromise programming."; } - /** This method allows you to choose the EpsilonThreshold - * @param weights The Epsilon Threshhold for the fitness sum. + /** + * This method allows you to choose the EpsilonThreshold + * + * @param weights The Epsilon Threshhold for the fitness sum. */ public void setIdealPWeights(PropertyWeightedLPTchebycheff weights) { this.m_WLPT = weights; } + public PropertyWeightedLPTchebycheff getIdealPWeights() { return this.m_WLPT; } + public String idealPWeightsTipText() { return "Set the ideal vector, the weights and p (note: p=0 equals Tchebycheff metric)."; } diff --git a/src/eva2/optimization/operator/mutation/CMAParamSet.java b/src/eva2/optimization/operator/mutation/CMAParamSet.java index b3afd29c..bef10043 100644 --- a/src/eva2/optimization/operator/mutation/CMAParamSet.java +++ b/src/eva2/optimization/operator/mutation/CMAParamSet.java @@ -7,6 +7,7 @@ import eva2.optimization.strategies.EvolutionStrategies; import eva2.tools.EVAERROR; import eva2.tools.math.Jama.Matrix; import eva2.tools.math.Mathematics; + import java.io.Serializable; import java.util.Arrays; @@ -18,218 +19,218 @@ import java.util.Arrays; * CMA parameters must be reinitialized whenever the population itself is initialized, so the reinit * event is caught and handled. As there are numerous mutator instances but only one CMA parameter * set per population, this way is the good one. - * - * @author mkron * + * @author mkron */ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializable { - private static final long serialVersionUID = -1940875082544233819L; - protected double firstSigma = -1.; - protected double sigma; - protected double d_sig, c_sig; - protected double[] meanX, pathC, pathS, eigenvalues; - protected double[] weights = null; - protected double[][] range = null; - protected Matrix mC; - protected Matrix mB; - protected boolean firstAdaptionDone = false; - - public CMAParamSet(CMAParamSet o) { - firstSigma=o.firstSigma; - sigma=o.sigma; - d_sig=o.d_sig; - c_sig=o.c_sig; - meanX=o.meanX.clone(); - pathC=o.pathC.clone(); - pathS=o.pathS.clone(); - eigenvalues=o.eigenvalues.clone(); - weights=o.weights.clone(); - range = o.range; - mC=o.mC; - mB=o.mB; - firstAdaptionDone=o.firstAdaptionDone; - } - - public CMAParamSet() {} - - @Override - public Object clone() { - return new CMAParamSet(this); - } - - @Override - public String toString() { - return "d_sig " + d_sig + ", c_sig " + c_sig + ", sigma " + sigma + ", firstSigma " + firstSigma+ ", firstAdaptionDone " + firstAdaptionDone - + ",\n meanX " + Arrays.toString(meanX) + ", pathC " + Arrays.toString(pathC)+ ", pathS " + Arrays.toString(pathS)+ ", eigenvalues " + Arrays.toString(eigenvalues) - + ", weights " + Arrays.toString(weights)+ ",\n mC " + mC.toString() + ",\n mB " + mB.toString(); - } + private static final long serialVersionUID = -1940875082544233819L; + protected double firstSigma = -1.; + protected double sigma; + protected double d_sig, c_sig; + protected double[] meanX, pathC, pathS, eigenvalues; + protected double[] weights = null; + protected double[][] range = null; + protected Matrix mC; + protected Matrix mB; + protected boolean firstAdaptionDone = false; - /** - * Initializes a new CMAParamSet from scratch. - * - * @see #initCMAParams(CMAParamSet, int, int, Population, double) - * @param mu - * @param lambda - * @param oldGen - * @param initialSigma - * @return - */ - public static CMAParamSet initCMAParams(int mu, int lambda, Population oldGen, double initialSigma) { - return initCMAParams(new CMAParamSet(), mu, lambda, oldGen, initialSigma); - } - - /** - * Initializes the CMA parameter set for given mu, lambda and a population. - * The initialSigma parameter is used as initial sigma directly unless it is <0, in - * that case the average range is used as initial sigma. - * The parameter instance is also added as listener to the population. - * - * @param params the CMA parameter set to be used - its data are overwritten - * @param mu ES mu parameter - * @param lambda ES lambda parameter - * @param pop associated Population - * @param initialSigma initial sigma or -1 to indicate the usage of average range - * @return - */ - public static CMAParamSet initCMAParams(CMAParamSet params, int mu, int lambda, Population pop, double initialSigma) { - initCMAParams(params, mu, lambda, pop.getBestEAIndividual().getDoublePosition(), ((InterfaceDataTypeDouble)pop.getEAIndividual(0)).getDoubleRange(), initialSigma); - pop.addPopulationChangedEventListener(params); - return params; - } - - /** - * Initializes the CMA parameter set for given mu, lambda and a population. - * The initialSigma parameter is used as initial sigma directly unless it is <0, in - * that case the average range is used as initial sigma. - * - * @param params the CMA parameter set to be used - its data are overwritten - * @param mu ES mu parameter - * @param lambda ES lambda parameter - * @param pop associated Population - * @param initialSigma initial sigma or -1 to indicate the usage of average range - * @return - */ - public static CMAParamSet initCMAParams(CMAParamSet params, int mu, int lambda, double[] center, double[][] range, double initialSigma) { - // those are from init: - params.firstAdaptionDone = false; - params.range = range; + public CMAParamSet(CMAParamSet o) { + firstSigma = o.firstSigma; + sigma = o.sigma; + d_sig = o.d_sig; + c_sig = o.c_sig; + meanX = o.meanX.clone(); + pathC = o.pathC.clone(); + pathS = o.pathS.clone(); + eigenvalues = o.eigenvalues.clone(); + weights = o.weights.clone(); + range = o.range; + mC = o.mC; + mB = o.mB; + firstAdaptionDone = o.firstAdaptionDone; + } - int dim = params.range.length; + public CMAParamSet() { + } + + @Override + public Object clone() { + return new CMAParamSet(this); + } + + @Override + public String toString() { + return "d_sig " + d_sig + ", c_sig " + c_sig + ", sigma " + sigma + ", firstSigma " + firstSigma + ", firstAdaptionDone " + firstAdaptionDone + + ",\n meanX " + Arrays.toString(meanX) + ", pathC " + Arrays.toString(pathC) + ", pathS " + Arrays.toString(pathS) + ", eigenvalues " + Arrays.toString(eigenvalues) + + ", weights " + Arrays.toString(weights) + ",\n mC " + mC.toString() + ",\n mB " + mB.toString(); + } + + /** + * Initializes a new CMAParamSet from scratch. + * + * @param mu + * @param lambda + * @param oldGen + * @param initialSigma + * @return + * @see #initCMAParams(CMAParamSet, int, int, Population, double) + */ + public static CMAParamSet initCMAParams(int mu, int lambda, Population oldGen, double initialSigma) { + return initCMAParams(new CMAParamSet(), mu, lambda, oldGen, initialSigma); + } + + /** + * Initializes the CMA parameter set for given mu, lambda and a population. + * The initialSigma parameter is used as initial sigma directly unless it is <0, in + * that case the average range is used as initial sigma. + * The parameter instance is also added as listener to the population. + * + * @param params the CMA parameter set to be used - its data are overwritten + * @param mu ES mu parameter + * @param lambda ES lambda parameter + * @param pop associated Population + * @param initialSigma initial sigma or -1 to indicate the usage of average range + * @return + */ + public static CMAParamSet initCMAParams(CMAParamSet params, int mu, int lambda, Population pop, double initialSigma) { + initCMAParams(params, mu, lambda, pop.getBestEAIndividual().getDoublePosition(), ((InterfaceDataTypeDouble) pop.getEAIndividual(0)).getDoubleRange(), initialSigma); + pop.addPopulationChangedEventListener(params); + return params; + } + + /** + * Initializes the CMA parameter set for given mu, lambda and a population. + * The initialSigma parameter is used as initial sigma directly unless it is <0, in + * that case the average range is used as initial sigma. + * + * @param params the CMA parameter set to be used - its data are overwritten + * @param mu ES mu parameter + * @param lambda ES lambda parameter + * @param pop associated Population + * @param initialSigma initial sigma or -1 to indicate the usage of average range + * @return + */ + public static CMAParamSet initCMAParams(CMAParamSet params, int mu, int lambda, double[] center, double[][] range, double initialSigma) { + // those are from init: + params.firstAdaptionDone = false; + params.range = range; + + int dim = params.range.length; // if (TRACE_1) System.out.println("WCMA init " + dim); // if (TRACE_1) System.out.println("WCMA static init " + dim); - params.eigenvalues = new double[dim]; - Arrays.fill(params.eigenvalues, 1.); - params.meanX = new double[dim]; - params.pathC = new double[dim]; - params.pathS = new double[dim]; + params.eigenvalues = new double[dim]; + Arrays.fill(params.eigenvalues, 1.); + params.meanX = new double[dim]; + params.pathC = new double[dim]; + params.pathS = new double[dim]; - params.mC = Matrix.identity(dim, dim); - params.mB = Matrix.identity(dim, dim); + params.mC = Matrix.identity(dim, dim); + params.mB = Matrix.identity(dim, dim); - // from adaptAfterSel - params.weights = initWeights(mu, lambda); - double muEff = getMuEff(params.weights, mu); - params.c_sig = (muEff+2)/(muEff+dim+3); + // from adaptAfterSel + params.weights = initWeights(mu, lambda); + double muEff = getMuEff(params.weights, mu); + params.c_sig = (muEff + 2) / (muEff + dim + 3); // c_u_sig = Math.sqrt(c_sig * (2.-c_sig)); - params.d_sig = params.c_sig+1+2*Math.max(0, Math.sqrt((muEff-1)/(dim+1)) - 1); - - if (initialSigma<0) { // this means we scale the average range - if (initialSigma!=-0.25 && (initialSigma!=-0.5)) { - EVAERROR.errorMsgOnce("Warning, unexpected initial sigma in CMAParamSet!"); - } - initialSigma = -initialSigma*Mathematics.getAvgRange(params.range); - } - if (initialSigma <= 0) { - EVAERROR.errorMsgOnce("warning: initial sigma <= zero! Working with converged population?"); - initialSigma = 10e-10; - } - params.sigma = initialSigma; + params.d_sig = params.c_sig + 1 + 2 * Math.max(0, Math.sqrt((muEff - 1) / (dim + 1)) - 1); + + if (initialSigma < 0) { // this means we scale the average range + if (initialSigma != -0.25 && (initialSigma != -0.5)) { + EVAERROR.errorMsgOnce("Warning, unexpected initial sigma in CMAParamSet!"); + } + initialSigma = -initialSigma * Mathematics.getAvgRange(params.range); + } + if (initialSigma <= 0) { + EVAERROR.errorMsgOnce("warning: initial sigma <= zero! Working with converged population?"); + initialSigma = 10e-10; + } + params.sigma = initialSigma; // System.out.println("INitial sigma: "+sigma); - params.firstSigma = params.sigma; + params.firstSigma = params.sigma; // System.out.println("new center is " + BeanInspector.toString(center)); - params.meanX = center; // this might be ok? - return params; - } + params.meanX = center; // this might be ok? + return params; + } - /** - * Initialize the default weights for the mu update using a log scale. - * - * @param mu - * @param lambda - * @return - */ - public static double[] initWeights(int mu, int lambda) { - if (lambda==1) { - System.err.println("Invalid lambda value in CMAParamSet.initWeights!"); - lambda++; //kind of a cheat to save against div. by zero - } - double[] theWeights = new double[mu]; - double sum = 0; - int type = 0; // zero is default log scale - for (int i=0; i mutators = GenericObjectEditor.getClassesFromProperties(InterfaceMutation.class.getCanonicalName(), null); tmpList = new InterfaceMutation[mutators.size()]; - for (int i = 0; i < mutators.size(); i++) { - if (((String)mutators.get(i)).equals(this.getClass().getName())) { - continue; - } + for (int i = 0; i < mutators.size(); i++) { + if (((String) mutators.get(i)).equals(this.getClass().getName())) { + continue; + } try { - tmpList[i] = (InterfaceMutation)Class.forName((String)mutators.get(i)).newInstance(); + tmpList[i] = (InterfaceMutation) Class.forName((String) mutators.get(i)).newInstance(); } catch (java.lang.ClassNotFoundException e) { - System.out.println("Could not find class for " +(String)mutators.get(i) ); - } catch (java.lang.InstantiationException k) { - System.out.println("Instantiation exception for " +(String)mutators.get(i) ); + System.out.println("Could not find class for " + (String) mutators.get(i)); + } catch (java.lang.InstantiationException k) { + System.out.println("Instantiation exception for " + (String) mutators.get(i)); } catch (java.lang.IllegalAccessException a) { - System.out.println("Illegal access exception for " +(String)mutators.get(i) ); + System.out.println("Illegal access exception for " + (String) mutators.get(i)); } } this.m_Mutators = new PropertyMutationMixer(tmpList, false); @@ -50,31 +51,34 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { this.m_Mutators.setWeightsLabel("Weigths"); } - + /** * Create a mutation mixer with equal weights of the given mutation operators. + * * @param mutators */ - public MutateEAMixer(InterfaceMutation ... mutators) { - this.m_Mutators = new PropertyMutationMixer(mutators, true); + public MutateEAMixer(InterfaceMutation... mutators) { + this.m_Mutators = new PropertyMutationMixer(mutators, true); } - + public MutateEAMixer(InterfaceMutation m1, InterfaceMutation m2) { - this(new InterfaceMutation[] {m1, m2}); + this(new InterfaceMutation[]{m1, m2}); } - + public MutateEAMixer(InterfaceMutation m1, InterfaceMutation m2, InterfaceMutation m3) { - this(new InterfaceMutation[] {m1, m2, m3}); + this(new InterfaceMutation[]{m1, m2, m3}); } - + public MutateEAMixer(MutateEAMixer mutator) { - this.m_Mutators = (PropertyMutationMixer)mutator.m_Mutators.clone(); - this.m_UseSelfAdaption = mutator.m_UseSelfAdaption; - this.m_Tau1 = mutator.m_Tau1; + this.m_Mutators = (PropertyMutationMixer) mutator.m_Mutators.clone(); + this.m_UseSelfAdaption = mutator.m_UseSelfAdaption; + this.m_Tau1 = mutator.m_Tau1; this.m_LowerLimitChance = mutator.m_LowerLimitChance; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -82,14 +86,16 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { return new MutateEAMixer(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateEAMixer) { - MutateEAMixer mut = (MutateEAMixer)mutator; + MutateEAMixer mut = (MutateEAMixer) mutator; return true; } else { @@ -97,26 +103,30 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ - InterfaceMutation[] mutators = this.m_Mutators.getSelectedMutators(); + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { + InterfaceMutation[] mutators = this.m_Mutators.getSelectedMutators(); for (int i = 0; i < mutators.length; i++) { mutators[i].init(individual, opt); } } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { this.m_Mutators.normalizeWeights(); - double[] probs = this.m_Mutators.getWeights(); + double[] probs = this.m_Mutators.getWeights(); if (this.m_UseSelfAdaption) { for (int i = 0; i < probs.length; i++) { probs[i] *= Math.exp(this.m_Tau1 * RNG.gaussianDouble(1)); @@ -130,16 +140,16 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { this.m_Mutators.normalizeWeights(); } - InterfaceMutation[] mutators = this.m_Mutators.getSelectedMutators(); - double pointer = RNG.randomFloat(0, 1); - double dum = probs[0]; - int index = 0; - while ((pointer > dum) && (index < probs.length-1)) { + InterfaceMutation[] mutators = this.m_Mutators.getSelectedMutators(); + double pointer = RNG.randomFloat(0, 1); + double dum = probs[0]; + int index = 0; + while ((pointer > dum) && (index < probs.length - 1)) { index++; dum += probs[index]; } if (index == probs.length) { - index = RNG.randomInt(0, probs.length-1); + index = RNG.randomInt(0, probs.length - 1); } //System.out.println("Using : " + mutators[index].getStringRepresentation()); // for (int i = 0; i < probs.length; i++) { @@ -149,10 +159,12 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { mutators[index].mutate(individual); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -161,8 +173,10 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -173,48 +187,63 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "EA mutation mixer"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This meta-mutation operator allows you to combine multiple alternative mutation operators."; } - /** Choose the set of mutators. - * @param d The mutation operators. + /** + * Choose the set of mutators. + * + * @param d The mutation operators. */ public void setMutators(PropertyMutationMixer d) { this.m_Mutators = d; } + public PropertyMutationMixer getMutators() { return this.m_Mutators; } + public String mutatorsTipText() { return "Choose the set of mutators."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setUseSelfAdaption(boolean d) { this.m_UseSelfAdaption = d; } + public boolean getUseSelfAdaption() { return this.m_UseSelfAdaption; } + public String useSelfAdaptionTipText() { return "Use my implementation of self-adaption for the mutation mixer."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitChance(double d) { if (d < 0) { @@ -222,15 +251,19 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { } this.m_LowerLimitChance = d; } + public double getLowerLimitChance() { return this.m_LowerLimitChance; } + public String lowerLimitChanceTipText() { return "Set the lower limit for the mutation chance."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setTau1(double d) { if (d < 0) { @@ -238,9 +271,11 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { } this.m_Tau1 = d; } + public double getTau1() { return this.m_Tau1; } + public String tau1TipText() { return "Set the value for tau1."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESCorrVector.java b/src/eva2/optimization/operator/mutation/MutateESCorrVector.java index cf977d63..98332a54 100644 --- a/src/eva2/optimization/operator/mutation/MutateESCorrVector.java +++ b/src/eva2/optimization/operator/mutation/MutateESCorrVector.java @@ -7,6 +7,7 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.util.ArrayList; @@ -15,19 +16,19 @@ import java.util.ArrayList; * updates the velocity by rotation and scaling, and then mutates the individual * by adding the velocity. This was used for a particle filter localization problem * and is less useful in general. - * + *

* Rotation vectors are normal distributed with mean zero, scaling factors are * log-normally distributed around mean 1. This means that the averaged expected change * of the mutation vector is zero. The smaller the deviations, the higher the correlations * between successive mutation steps. */ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializable { - protected double m_scalingDev = 0.05; - protected double m_initialVelocity = 0.02; - protected double m_LowerLimitStepSize = 0.0000001; - protected double m_UpperLimitStepSize = 0.5; - protected double m_rotationDev = 15.; - protected boolean m_checkConstraints = true; + protected double m_scalingDev = 0.05; + protected double m_initialVelocity = 0.02; + protected double m_LowerLimitStepSize = 0.0000001; + protected double m_UpperLimitStepSize = 0.5; + protected double m_rotationDev = 15.; + protected boolean m_checkConstraints = true; public static final String vectorKey = "MutateESCorrVectorVector"; public static final boolean TRACE = false; @@ -37,26 +38,28 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab public MutateESCorrVector(double scalingDev) { setScalingDev(scalingDev); } - + public MutateESCorrVector(double scalingDev, double initialVelocity) { setScalingDev(scalingDev); setInitialVelocity(initialVelocity); } - + public MutateESCorrVector(double scalingDev, double initialVelocity, double rotDev) { setScalingDev(scalingDev); setInitialVelocity(initialVelocity); setRotationDev(rotDev); } - + public MutateESCorrVector(MutateESCorrVector mutator) { - this.m_scalingDev = mutator.m_scalingDev; - this.m_initialVelocity = mutator.m_initialVelocity; - this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; + this.m_scalingDev = mutator.m_scalingDev; + this.m_initialVelocity = mutator.m_initialVelocity; + this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; this.m_rotationDev = mutator.m_rotationDev; } - - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -64,14 +67,16 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab return new MutateESCorrVector(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESCorrVector) { - MutateESCorrVector mut = (MutateESCorrVector)mutator; + MutateESCorrVector mut = (MutateESCorrVector) mutator; if (this.m_scalingDev != mut.m_scalingDev) { return false; } @@ -87,123 +92,131 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - double[] initVelocity = calcInitialVel(m_initialVelocity, ((InterfaceESIndividual)individual).getDoubleRange()); - individual.putData(vectorKey, initVelocity); + double[] initVelocity = calcInitialVel(m_initialVelocity, ((InterfaceESIndividual) individual).getDoubleRange()); + individual.putData(vectorKey, initVelocity); } /** - * Create a random vector of length relative to the given range given by the velocity parameter. - * + * Create a random vector of length relative to the given range given by the velocity parameter. + * * @param velocity * @param doubleRange * @return */ private double[] calcInitialVel(double velocity, double[][] doubleRange) { - double[] initVelocity = Mathematics.randomVector(doubleRange.length, 1.0); - double nrm=Mathematics.norm(initVelocity); - double[] shiftedRange=Mathematics.getAbsRange(doubleRange); - // normalize to speed - Mathematics.svMult(velocity/nrm, initVelocity, initVelocity); - // and scale by ranges - Mathematics.vvMultCw(shiftedRange, initVelocity, initVelocity); - // System.out.println(Mathematics.getRelativeLength(initVelocity, doubleRange)); - return initVelocity; - } + double[] initVelocity = Mathematics.randomVector(doubleRange.length, 1.0); + double nrm = Mathematics.norm(initVelocity); + double[] shiftedRange = Mathematics.getAbsRange(doubleRange); + // normalize to speed + Mathematics.svMult(velocity / nrm, initVelocity, initVelocity); + // and scale by ranges + Mathematics.vvMultCw(shiftedRange, initVelocity, initVelocity); + // System.out.println(Mathematics.getRelativeLength(initVelocity, doubleRange)); + return initVelocity; + } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceESIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { // if (TRACE) System.out.println("Before Mutate: " + AbstractEAIndividual.getDefaultDataString(individual)); if (individual instanceof InterfaceESIndividual) { - double[] genes = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); - - double[] vel = (double[])individual.getData(vectorKey); - + double[] genes = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); + + double[] vel = (double[]) individual.getData(vectorKey); + // mutate the velocity vector and write it back if ((m_scalingDev > 0) || (m_rotationDev > 0)) { // for (int i = 0; i < vel.length; i++) { // vel[i] += ((range[i][1] -range[i][0])/2)*RNG.gaussianDouble(this.mutationStepSize); // } - double rotateRad = m_rotationDev*(Math.PI/360.)*RNG.gaussianDouble(1.); - // rotate with a gaussian distribution of deviation rotationDeg - Mathematics.rotateAllAxes(vel, rotateRad, false); // rotate - double rScale=Math.exp(RNG.gaussianDouble(m_scalingDev)); - - if ((m_LowerLimitStepSize > 0) || (m_UpperLimitStepSize > 0) ) { - double stepLen=Mathematics.norm(vel); - if (m_LowerLimitStepSize > 0) { - rScale=Math.max(rScale, m_LowerLimitStepSize/stepLen); - } - if (m_UpperLimitStepSize > 0) { - rScale=Math.min(rScale, m_UpperLimitStepSize/stepLen); - } - } - - Mathematics.svMult(rScale, vel, vel); // mutate speed + double rotateRad = m_rotationDev * (Math.PI / 360.) * RNG.gaussianDouble(1.); + // rotate with a gaussian distribution of deviation rotationDeg + Mathematics.rotateAllAxes(vel, rotateRad, false); // rotate + double rScale = Math.exp(RNG.gaussianDouble(m_scalingDev)); - individual.putData(vectorKey, vel); - if (TRACE) { + if ((m_LowerLimitStepSize > 0) || (m_UpperLimitStepSize > 0)) { + double stepLen = Mathematics.norm(vel); + if (m_LowerLimitStepSize > 0) { + rScale = Math.max(rScale, m_LowerLimitStepSize / stepLen); + } + if (m_UpperLimitStepSize > 0) { + rScale = Math.min(rScale, m_UpperLimitStepSize / stepLen); + } + } + + Mathematics.svMult(rScale, vel, vel); // mutate speed + + individual.putData(vectorKey, vel); + if (TRACE) { System.out.println("rotated by " + rotateRad + ", scaled by " + rScale); } - if (TRACE) { + if (TRACE) { System.out.println("-- dir is " + BeanInspector.toString(vel)); } } - + // add velocity to the individual Mathematics.vvAdd(genes, vel, genes); - + // check the range if (m_checkConstraints) { Mathematics.projectToRange(genes, range); } - + // write genotype back - ((InterfaceESIndividual)individual).SetDGenotype(genes); + ((InterfaceESIndividual) individual).SetDGenotype(genes); } // if (TRACE) System.out.println("After Mutate: " + AbstractEAIndividual.getDefaultDataString(individual)); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { ArrayList tmpList = new ArrayList(); if (indy1.getMutationOperator() instanceof MutateESCorrVector) { - tmpList.add(new Double(((MutateESCorrVector)indy1.getMutationOperator()).m_scalingDev)); + tmpList.add(new Double(((MutateESCorrVector) indy1.getMutationOperator()).m_scalingDev)); } for (int i = 0; i < partners.size(); i++) { - if (((AbstractEAIndividual)partners.get(i)).getMutationOperator() instanceof MutateESCorrVector) { - tmpList.add(new Double(((MutateESCorrVector)((AbstractEAIndividual)partners.get(i)).getMutationOperator()).m_scalingDev)); + if (((AbstractEAIndividual) partners.get(i)).getMutationOperator() instanceof MutateESCorrVector) { + tmpList.add(new Double(((MutateESCorrVector) ((AbstractEAIndividual) partners.get(i)).getMutationOperator()).m_scalingDev)); } } double[] list = new double[tmpList.size()]; for (int i = 0; i < tmpList.size(); i++) { - list[i] = ((Double)tmpList.get(i)).doubleValue(); + list[i] = ((Double) tmpList.get(i)).doubleValue(); } if (list.length <= 1) { return; } // discreete mutation for step size - this.m_scalingDev = list[RNG.randomInt(0, list.length-1)]; + this.m_scalingDev = list[RNG.randomInt(0, list.length - 1)]; } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -214,35 +227,46 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES correlated vector mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The correlated vector mutation stores a specific mutation vector per individual."; } - /** Set the initial mutation step size with this method. - * @param d The mutation operator. + /** + * Set the initial mutation step size with this method. + * + * @param d The mutation operator. */ public void setScalingDev(double d) { this.m_scalingDev = d; } + public double getScalingDev() { return this.m_scalingDev; } + public String scalingDevTipText() { return "Choose the devation of lognormal vector scaling."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { if (d < 0) { @@ -250,42 +274,44 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab } this.m_LowerLimitStepSize = d; } + public double getLowerLimitStepSize() { return this.m_LowerLimitStepSize; } + public String lowerLimitStepSizeTipText() { return "Set the lower limit for the mutation step."; } - public double getRotationDev() { - return m_rotationDev; - } + public double getRotationDev() { + return m_rotationDev; + } - public void setRotationDev(double rotationDeg) { - this.m_rotationDev = rotationDeg; - } - - public String rotationDevTipText() { - return "Std deviation of the rotation angle distribution"; - } + public void setRotationDev(double rotationDeg) { + this.m_rotationDev = rotationDeg; + } - public double getInitialVelocity() { - return m_initialVelocity; - } + public String rotationDevTipText() { + return "Std deviation of the rotation angle distribution"; + } - public void setInitialVelocity(double velocity) { - m_initialVelocity = velocity; - } + public double getInitialVelocity() { + return m_initialVelocity; + } - public double getUpperLimitStepSize() { - return m_UpperLimitStepSize; - } + public void setInitialVelocity(double velocity) { + m_initialVelocity = velocity; + } - public void setUpperLimitStepSize(double upperLimitStepSize) { - m_UpperLimitStepSize = upperLimitStepSize; - } - - public String upperLimitStepSizeTipText() { - return "Set the upper limit for the mutation step."; - } + public double getUpperLimitStepSize() { + return m_UpperLimitStepSize; + } + + public void setUpperLimitStepSize(double upperLimitStepSize) { + m_UpperLimitStepSize = upperLimitStepSize; + } + + public String upperLimitStepSizeTipText() { + return "Set the upper limit for the mutation step."; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateESCorrolated.java b/src/eva2/optimization/operator/mutation/MutateESCorrolated.java index fb202d42..d93df3ed 100644 --- a/src/eva2/optimization/operator/mutation/MutateESCorrolated.java +++ b/src/eva2/optimization/operator/mutation/MutateESCorrolated.java @@ -17,9 +17,9 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab protected double mutationStepSize = 0.2; protected double tau1 = 0.15; protected double lowerLimitStepSize = 0.0000005; - private static final long serialVersionUID = 1L; - private double[] sigmas = null; - private double[] alphas = null; + private static final long serialVersionUID = 1L; + private double[] sigmas = null; + private double[] alphas = null; protected double tau2 = 0.15; public MutateESCorrolated() { @@ -36,20 +36,22 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab } if (mutator.alphas != null) { - this.alphas = new double[mutator.alphas.length]; - for (int i = 0; i < this.alphas.length; i++) { - this.alphas[i] = mutator.alphas[i]; - } + this.alphas = new double[mutator.alphas.length]; + for (int i = 0; i < this.alphas.length; i++) { + this.alphas[i] = mutator.alphas[i]; + } } - + this.mutationStepSize = mutator.mutationStepSize; this.tau1 = mutator.tau1; this.tau2 = mutator.tau2; this.lowerLimitStepSize = mutator.lowerLimitStepSize; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -57,17 +59,19 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab return new MutateESCorrolated(this); } - /** This method allows you to evaluate whether two mutation operators + /** + * This method allows you to evaluate whether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { - if (mutator==this) { + if (mutator == this) { return true; } if (mutator instanceof MutateESCorrolated) { - MutateESCorrolated mut = (MutateESCorrolated)mutator; + MutateESCorrolated mut = (MutateESCorrolated) mutator; if (this.tau1 != mut.tau1) { return false; } @@ -101,34 +105,38 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); if (this.sigmas == null) { - // init the Sigmas - this.sigmas = new double[x.length]; - for (int i = 0; i < this.sigmas.length; i++) { + // init the Sigmas + this.sigmas = new double[x.length]; + for (int i = 0; i < this.sigmas.length; i++) { this.sigmas[i] = this.mutationStepSize; } } if (this.alphas == null) { - // init the Alphas - this.alphas = new double[(x.length*(x.length-1))/2]; - for (int i = 0; i < this.alphas.length; i++) { + // init the Alphas + this.alphas = new double[(x.length * (x.length - 1)) / 2]; + for (int i = 0; i < this.alphas.length; i++) { this.alphas[i] = 0.0; } } } } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ // public void mutate(AbstractEAIndividual individual) { // if (individual instanceof InterfaceESIndividual) { @@ -188,69 +196,70 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab // // } // } - @Override public void mutate(AbstractEAIndividual individual) { if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[] xCopy = new double[x.length]; - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); - double tmpR = RNG.gaussianDouble(1); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[] xCopy = new double[x.length]; + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); + double tmpR = RNG.gaussianDouble(1); - //Mutate Sigmas - for (int i = 0; i < x.length; i++) { - this.sigmas[i] *= Math.exp(this.tau1 * tmpR + this.tau2 * RNG.gaussianDouble(1)); - if (this.sigmas[i] < this.lowerLimitStepSize) { - this.sigmas[i] = this.lowerLimitStepSize; - } - } + //Mutate Sigmas + for (int i = 0; i < x.length; i++) { + this.sigmas[i] *= Math.exp(this.tau1 * tmpR + this.tau2 * RNG.gaussianDouble(1)); + if (this.sigmas[i] < this.lowerLimitStepSize) { + this.sigmas[i] = this.lowerLimitStepSize; + } + } - //Mutate Alphas - for (int i = 0; i < this.alphas.length; i++) { - this.alphas[i] += RNG.gaussianDouble(0.2); - if (this.alphas[i] < -Math.PI/2) { - this.alphas[i] = -Math.PI/2; - } - if (this.alphas[i] > Math.PI/2) { - this.alphas[i] = Math.PI/2; - } - } - - //Generate mutationvector in unitspace modified by sigmas - for (int i = 0; i < x.length; i++) { - xCopy[i] = RNG.gaussianDouble(this.sigmas[i]); - } + //Mutate Alphas + for (int i = 0; i < this.alphas.length; i++) { + this.alphas[i] += RNG.gaussianDouble(0.2); + if (this.alphas[i] < -Math.PI / 2) { + this.alphas[i] = -Math.PI / 2; + } + if (this.alphas[i] > Math.PI / 2) { + this.alphas[i] = Math.PI / 2; + } + } - //turn mutationvector with alphas - for (int i = 0; i < x.length-1; i++) { - for (int j = i+1; j < x.length; j++) { - double alpha=this.getAlpha(i,j, x.length); - double xX=java.lang.Math.cos(alpha)*xCopy[i]-java.lang.Math.sin(alpha)*xCopy[j]; - double xY=java.lang.Math.sin(alpha)*xCopy[i]+java.lang.Math.cos(alpha)*xCopy[j]; - xCopy[i]=xX; - xCopy[j]=xY; - } - } + //Generate mutationvector in unitspace modified by sigmas + for (int i = 0; i < x.length; i++) { + xCopy[i] = RNG.gaussianDouble(this.sigmas[i]); + } - //modify genotype - for (int i = 0; i < x.length; i++) { - x[i] += ((range[i][1] -range[i][0])/2)*xCopy[i]; - if (range[i][0] > x[i]) { - x[i] = range[i][0]; - } - if (range[i][1] < x[i]) { - x[i] = range[i][1]; - } - } + //turn mutationvector with alphas + for (int i = 0; i < x.length - 1; i++) { + for (int j = i + 1; j < x.length; j++) { + double alpha = this.getAlpha(i, j, x.length); + double xX = java.lang.Math.cos(alpha) * xCopy[i] - java.lang.Math.sin(alpha) * xCopy[j]; + double xY = java.lang.Math.sin(alpha) * xCopy[i] + java.lang.Math.cos(alpha) * xCopy[j]; + xCopy[i] = xX; + xCopy[j] = xY; + } + } - ((InterfaceESIndividual)individual).SetDGenotype(x); + //modify genotype + for (int i = 0; i < x.length; i++) { + x[i] += ((range[i][1] - range[i][0]) / 2) * xCopy[i]; + if (range[i][0] > x[i]) { + x[i] = range[i][0]; + } + if (range[i][1] < x[i]) { + x[i] = range[i][1]; + } + } + + ((InterfaceESIndividual) individual).SetDGenotype(x); } } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -258,25 +267,28 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab } /** - * @param i - * @param j - */ - private double getAlpha(int i, int j, int n) { - int sum=0; - if (i0) { - this.m_SigmaGlobal = this.m_InitSigmaScalar; - } - else { - double avgRange = Mathematics.getAvgRange(ranges); - this.m_SigmaGlobal = 0.25*avgRange; + this.m_Counter = this.m_frequency; + if (m_InitSigmaScalar > 0) { + this.m_SigmaGlobal = this.m_InitSigmaScalar; + } else { + double avgRange = Mathematics.getAvgRange(ranges); + this.m_SigmaGlobal = 0.25 * avgRange; } System.out.println("Init sigma: " + m_SigmaGlobal); - this.m_D = x.length; - this.m_C = Matrix.identity(this.m_D, this.m_D); + this.m_D = x.length; + this.m_C = Matrix.identity(this.m_D, this.m_D); EigenvalueDecomposition helper = new EigenvalueDecomposition(this.m_C); - this.B = helper.getV(); - this.m_c = Math.sqrt(1.0 / (double) this.m_D); - this.cu = Math.sqrt( (2.0 - this.m_c) / this.m_c); - this.Beta = this.m_c; - this.cov = 2.0 / ( (double) this.m_D * (double) this.m_D); - this.m_Z = new double[this.m_D]; - this.s_N = new double[this.m_D]; - this.Bz = new double[this.m_D]; - this.m_PathS = new double[this.m_D]; + this.B = helper.getV(); + this.m_c = Math.sqrt(1.0 / (double) this.m_D); + this.cu = Math.sqrt((2.0 - this.m_c) / this.m_c); + this.Beta = this.m_c; + this.cov = 2.0 / ((double) this.m_D * (double) this.m_D); + this.m_Z = new double[this.m_D]; + this.s_N = new double[this.m_D]; + this.Bz = new double[this.m_D]; + this.m_PathS = new double[this.m_D]; for (int i = 0; i < this.m_D; i++) { - this.s_N[i] = 0; - this.Bz[i] = 0; - this.m_PathS[i] = 0; + this.s_N[i] = 0; + this.Bz[i] = 0; + this.m_PathS[i] = 0; } this.xi_dach = Math.sqrt(this.m_D - 0.5); evaluateNewObjectX(x, ranges); } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] ranges = ((InterfaceESIndividual) individual).getDoubleRange(); this.adaptStrategy(); this.evaluateNewObjectX(x, ranges); for (int i = 0; i < x.length; i++) { - if (x[i] < ranges[i][0]) { + if (x[i] < ranges[i][0]) { x[i] = ranges[i][0]; } - if (x[i] > ranges[i][1]) { + if (x[i] > ranges[i][1]) { x[i] = ranges[i][1]; } } - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -211,15 +220,15 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java } protected void adaptStrategy() { - double Cij; - double Bz_d; - double pathLen = 0.0; + double Cij; + double Bz_d; + double pathLen = 0.0; for (int i = 0; i < this.m_D; i++) { this.s_N[i] = (1.0 - this.m_c) * this.s_N[i] + this.m_c * this.cu * this.Bz[i]; } // System.out.println("C bef:\n" + m_C.toString()); // ADAPT COVARIANCE - for (int i = 0; i = this.m_frequency) { EigenvalueDecomposition helper; - this.m_Counter = 0; - helper = new EigenvalueDecomposition(this.m_C); - this.B = helper.getV(); - this.m_Eigenvalues = helper.getRealEigenvalues(); + this.m_Counter = 0; + helper = new EigenvalueDecomposition(this.m_C); + this.B = helper.getV(); + this.m_Eigenvalues = helper.getRealEigenvalues(); } - boolean isNewPosFeasible = false; - int counter = 0; + boolean isNewPosFeasible = false; + int counter = 0; while (!isNewPosFeasible && counter < this.m_constraintMaxTries) { for (int i = 0; i < this.m_D; i++) { this.Bz[i] = 0; @@ -305,11 +314,11 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java if (this.m_CheckConstraints == true) { for (int i = 0; i < m_D; i++) { if (x[i] < range[i][0] || x[i] > range[i][1]) { - // undo the step and try new Z + // undo the step and try new Z for (int j = 0; j < this.m_D; j++) { x[j] = oldX[j] - this.m_SigmaGlobal * this.Bz[j]; } - this.m_SigmaGlobal*=0.5; + this.m_SigmaGlobal *= 0.5; isNewPosFeasible = false; counter++; break; @@ -317,19 +326,21 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java } } } - if (counter>0) { + if (counter > 0) { // System.out.print("CMA ES Req " + counter + " "); // if (counter > 15) System.out.println(BeanInspector.toString(x)); // else System.out.println(); } if (this.m_CheckConstraints && !isNewPosFeasible) { // use force - Mathematics.projectToRange(x, range); + Mathematics.projectToRange(x, range); // System.err.println("PROJECTING BY FORCE"); } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -339,42 +350,55 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "CMA mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is the most sophisticated CMA mutation."; } - /** Use only positive numbers this limits the freedom of effect. - * @param bit The new representation for the inner constants. - */ + /** + * Use only positive numbers this limits the freedom of effect. + * + * @param bit The new representation for the inner constants. + */ public void setCheckConstraints(boolean bit) { this.m_CheckConstraints = bit; } + public boolean getCheckConstraints() { return this.m_CheckConstraints; } + public String checkConstraintsTipText() { return "Toggle check constraints."; } - /** This method allows you to set the initial sigma value. - * @param d The initial sigma value. - */ + /** + * This method allows you to set the initial sigma value. + * + * @param d The initial sigma value. + */ public void setInitSigmaScalar(double d) { this.m_InitSigmaScalar = d; } + public double getInitSigmaScalar() { return this.m_InitSigmaScalar; } + public String initSigmaScalarTipText() { return "Set the initial sigma value, or -1 to use quarter average range of the problem."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaptionPlus.java b/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaptionPlus.java index 868e5dfe..c631c620 100644 --- a/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaptionPlus.java +++ b/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaptionPlus.java @@ -7,232 +7,229 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Jama.Matrix; public class MutateESCovarianceMatrixAdaptionPlus extends - MutateESCovarianceMatrixAdaption implements InterfaceMutation, - InterfaceAdaptOperatorGenerational { - protected double m_psuccess; - protected double m_cp; - protected double m_psuccesstarget = 0.44; - protected double m_stepd; - protected double m_pthresh; - protected int m_lambda = 1; + MutateESCovarianceMatrixAdaption implements InterfaceMutation, + InterfaceAdaptOperatorGenerational { + protected double m_psuccess; + protected double m_cp; + protected double m_psuccesstarget = 0.44; + protected double m_stepd; + protected double m_pthresh; + protected int m_lambda = 1; - public MutateESCovarianceMatrixAdaptionPlus() { - super(); - } + public MutateESCovarianceMatrixAdaptionPlus() { + super(); + } - public MutateESCovarianceMatrixAdaptionPlus( - MutateESCovarianceMatrixAdaptionPlus mutator) { - super(mutator); - m_psuccess = mutator.m_psuccess; - m_cp = mutator.m_cp; - m_psuccesstarget = mutator.m_psuccesstarget; - m_lambda = mutator.m_lambda; - m_pthresh = mutator.m_pthresh; - m_stepd = mutator.m_stepd; - } + public MutateESCovarianceMatrixAdaptionPlus( + MutateESCovarianceMatrixAdaptionPlus mutator) { + super(mutator); + m_psuccess = mutator.m_psuccess; + m_cp = mutator.m_cp; + m_psuccesstarget = mutator.m_psuccesstarget; + m_lambda = mutator.m_lambda; + m_pthresh = mutator.m_pthresh; + m_stepd = mutator.m_stepd; + } - /** - * This method will enable you to clone a given mutation operator - * - * @return The clone - */ + /** + * This method will enable you to clone a given mutation operator + * + * @return The clone + */ @Override - public Object clone() { - return new MutateESCovarianceMatrixAdaptionPlus(this); - } + public Object clone() { + return new MutateESCovarianceMatrixAdaptionPlus(this); + } - /** - * This method allows you to init the mutation operator - * - * @param individual - * The individual that will be mutated. - * @param opt - * The optimization problem. - */ + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. + */ @Override - public void init(AbstractEAIndividual individual, - InterfaceOptimizationProblem opt) { + public void init(AbstractEAIndividual individual, + InterfaceOptimizationProblem opt) { - if (!(individual instanceof InterfaceESIndividual)) { - return; - } - super.init(individual, opt); - m_psuccesstarget = 1.0 / (5 + Math.sqrt(m_lambda) / 2); - m_psuccess = m_psuccesstarget; - m_stepd = 1.0 + m_D / (2.0 * m_lambda); - m_cp = m_psuccesstarget * m_lambda / (2 + m_psuccesstarget * m_lambda); - m_c = 2.0 / (2.0 + m_D); - this.cov = 2.0 / (6.0 + Math.pow(m_D, 2)); // ATTN: differs from the - // standard CMA-ES - m_pthresh = 0.44; + if (!(individual instanceof InterfaceESIndividual)) { + return; + } + super.init(individual, opt); + m_psuccesstarget = 1.0 / (5 + Math.sqrt(m_lambda) / 2); + m_psuccess = m_psuccesstarget; + m_stepd = 1.0 + m_D / (2.0 * m_lambda); + m_cp = m_psuccesstarget * m_lambda / (2 + m_psuccesstarget * m_lambda); + m_c = 2.0 / (2.0 + m_D); + this.cov = 2.0 / (6.0 + Math.pow(m_D, 2)); // ATTN: differs from the + // standard CMA-ES + m_pthresh = 0.44; - } + } - protected void adaptStrategyGen(AbstractEAIndividual child, - AbstractEAIndividual parent) { - if (child.getFitness(0) <= parent.getFitness(0)) { - // updatecov - updateCovariance(child, parent); - // updateCovariance(); - } + protected void adaptStrategyGen(AbstractEAIndividual child, + AbstractEAIndividual parent) { + if (child.getFitness(0) <= parent.getFitness(0)) { + // updatecov + updateCovariance(child, parent); + // updateCovariance(); + } - } + } - /** - * @param parent - * @param child - */ - public void updateCovariance(AbstractEAIndividual child, - AbstractEAIndividual parent) { - double[] step = new double[m_D]; - for (int i = 0; i < m_D; i++) { - step[i] = ((InterfaceESIndividual) parent).getDGenotype()[i] - - ((InterfaceESIndividual) child).getDGenotype()[i]; - } - updateCovariance(step); - } + /** + * @param parent + * @param child + */ + public void updateCovariance(AbstractEAIndividual child, + AbstractEAIndividual parent) { + double[] step = new double[m_D]; + for (int i = 0; i < m_D; i++) { + step[i] = ((InterfaceESIndividual) parent).getDGenotype()[i] + - ((InterfaceESIndividual) child).getDGenotype()[i]; + } + updateCovariance(step); + } - public void updateCovariance() { - double[] step = new double[m_D]; - for (int i = 0; i < m_D; i++) { - step[i] = Bz[i]; - } - updateCovariance(step); - } + public void updateCovariance() { + double[] step = new double[m_D]; + for (int i = 0; i < m_D; i++) { + step[i] = Bz[i]; + } + updateCovariance(step); + } - /** - * @param step - * - */ - public void updateCovariance(double[] step) { - for (int i = 0; i < m_D; i++) { - if (m_psuccess < m_pthresh) { - m_PathS[i] = (1.0 - m_c) * m_PathS[i] - + Math.sqrt(m_c * (2.0 - m_c)) * (step[i]) - / m_SigmaGlobal; - } else { - m_PathS[i] = (1.0 - m_c) * m_PathS[i]; - } + /** + * @param step + */ + public void updateCovariance(double[] step) { + for (int i = 0; i < m_D; i++) { + if (m_psuccess < m_pthresh) { + m_PathS[i] = (1.0 - m_c) * m_PathS[i] + + Math.sqrt(m_c * (2.0 - m_c)) * (step[i]) + / m_SigmaGlobal; + } else { + m_PathS[i] = (1.0 - m_c) * m_PathS[i]; + } - } - if (m_psuccess < m_pthresh) { - m_C = m_C.multi((1.0 - cov)); - m_C.plusEquals(Matrix.outer(m_PathS, m_PathS).multi(cov)); - } else { - m_C = m_C.multi((1.0 - cov)).plus( - (Matrix.outer(m_PathS, m_PathS).plus( - m_C.multi(m_c * (2.0 - m_c))).multi(cov))); - } - } + } + if (m_psuccess < m_pthresh) { + m_C = m_C.multi((1.0 - cov)); + m_C.plusEquals(Matrix.outer(m_PathS, m_PathS).multi(cov)); + } else { + m_C = m_C.multi((1.0 - cov)).plus( + (Matrix.outer(m_PathS, m_PathS).plus( + m_C.multi(m_c * (2.0 - m_c))).multi(cov))); + } + } @Override - protected void adaptStrategy() { - } + protected void adaptStrategy() { + } - public int getLambda() { - return m_lambda; - } + public int getLambda() { + return m_lambda; + } - public void setLambda(int mLambda) { - m_lambda = mLambda; - } - - @Override - public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, - Population partners) { - // ATTN: Crossover is not defined for this - - } - - // @Override - @Override - public void adaptAfterSelection(Population oldPop, Population selectedPop) { - // TODO Auto-generated method stub - - } - - // @Override - @Override - public void adaptGenerational(Population selectedPop, Population parentPop, - Population newPop, boolean updateSelected) { - double rate = 0.; - for (int i = 0; i < parentPop.size(); i++) { - // calculate success rate - // System.out.println("new fit / old fit: " + - // BeanInspector.toString(newPop.getEAIndividual(i).getFitness()) + - // " , " + - // BeanInspector.toString(parentPop.getEAIndividual(i).getFitness())); - if (newPop.getEAIndividual(i).getFitness(0) < parentPop - .getEAIndividual(i).getFitness(0)) { - rate++; - } - } - rate /= parentPop.size(); - - if (updateSelected) { - for (int i = 0; i < selectedPop.size(); i++) { // applied to the old - // population as - // well in case of - // plus strategy - MutateESCovarianceMatrixAdaptionPlus mutator = (MutateESCovarianceMatrixAdaptionPlus) ((AbstractEAIndividual) selectedPop - .get(i)).getMutationOperator(); - updateMutator(rate, mutator); - if (selectedPop.getEAIndividual(i).getFitness(0) <= parentPop - .getEAIndividual(0).getFitness(0)) { - mutator.adaptStrategyGen(selectedPop.getEAIndividual(i), - parentPop.getEAIndividual(0)); - } - // System.out.println("old pop step size " + mutator.getSigma()+ - // " (" + mutator+ ")"); - } - } - for (int i = 0; i < newPop.size(); i++) { - MutateESCovarianceMatrixAdaptionPlus mutator = (MutateESCovarianceMatrixAdaptionPlus) ((AbstractEAIndividual) newPop - .get(i)).getMutationOperator(); - updateMutator(rate, mutator); - if (newPop.getEAIndividual(i).getFitness(0) <= parentPop - .getEAIndividual(0).getFitness(0)) { - mutator.adaptStrategyGen(newPop.getEAIndividual(i), parentPop - .getEAIndividual(0)); - } - // System.out.println("new pop step size " + mutator.getSigma()+ - // " (" + mutator+ ")"); - } - } - - private void updateMutator(double rate, - MutateESCovarianceMatrixAdaptionPlus mutator) { - mutator.updateStepSize(rate); - } - - public double getPSuccess() { - return m_psuccess; - } - - public void updateStepSize(double psuccess) { - this.m_psuccess = (1 - m_cp) * m_psuccess + m_cp * psuccess; - m_SigmaGlobal *= Math.exp(1 / m_stepd * (m_psuccess - m_psuccesstarget) - / (1 - m_psuccesstarget)); - } + public void setLambda(int mLambda) { + m_lambda = mLambda; + } @Override - public String getName() { - return "CMA mutation for plus Strategies"; - } + public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, + Population partners) { + // ATTN: Crossover is not defined for this - /** - * This method returns a global info string - * - * @return description - */ - public static String globalInfo() { - return "This is the CMA mutation according to Igel,Hansen,Roth 2007"; - } + } - @Override - public String getStringRepresentation() { - // TODO Auto-generated method stub - return "CMA-plus mutation"; - } + // @Override + @Override + public void adaptAfterSelection(Population oldPop, Population selectedPop) { + // TODO Auto-generated method stub + + } + + // @Override + @Override + public void adaptGenerational(Population selectedPop, Population parentPop, + Population newPop, boolean updateSelected) { + double rate = 0.; + for (int i = 0; i < parentPop.size(); i++) { + // calculate success rate + // System.out.println("new fit / old fit: " + + // BeanInspector.toString(newPop.getEAIndividual(i).getFitness()) + + // " , " + + // BeanInspector.toString(parentPop.getEAIndividual(i).getFitness())); + if (newPop.getEAIndividual(i).getFitness(0) < parentPop + .getEAIndividual(i).getFitness(0)) { + rate++; + } + } + rate /= parentPop.size(); + + if (updateSelected) { + for (int i = 0; i < selectedPop.size(); i++) { // applied to the old + // population as + // well in case of + // plus strategy + MutateESCovarianceMatrixAdaptionPlus mutator = (MutateESCovarianceMatrixAdaptionPlus) ((AbstractEAIndividual) selectedPop + .get(i)).getMutationOperator(); + updateMutator(rate, mutator); + if (selectedPop.getEAIndividual(i).getFitness(0) <= parentPop + .getEAIndividual(0).getFitness(0)) { + mutator.adaptStrategyGen(selectedPop.getEAIndividual(i), + parentPop.getEAIndividual(0)); + } + // System.out.println("old pop step size " + mutator.getSigma()+ + // " (" + mutator+ ")"); + } + } + for (int i = 0; i < newPop.size(); i++) { + MutateESCovarianceMatrixAdaptionPlus mutator = (MutateESCovarianceMatrixAdaptionPlus) ((AbstractEAIndividual) newPop + .get(i)).getMutationOperator(); + updateMutator(rate, mutator); + if (newPop.getEAIndividual(i).getFitness(0) <= parentPop + .getEAIndividual(0).getFitness(0)) { + mutator.adaptStrategyGen(newPop.getEAIndividual(i), parentPop + .getEAIndividual(0)); + } + // System.out.println("new pop step size " + mutator.getSigma()+ + // " (" + mutator+ ")"); + } + } + + private void updateMutator(double rate, + MutateESCovarianceMatrixAdaptionPlus mutator) { + mutator.updateStepSize(rate); + } + + public double getPSuccess() { + return m_psuccess; + } + + public void updateStepSize(double psuccess) { + this.m_psuccess = (1 - m_cp) * m_psuccess + m_cp * psuccess; + m_SigmaGlobal *= Math.exp(1 / m_stepd * (m_psuccess - m_psuccesstarget) + / (1 - m_psuccesstarget)); + } + + @Override + public String getName() { + return "CMA mutation for plus Strategies"; + } + + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "This is the CMA mutation according to Igel,Hansen,Roth 2007"; + } + + @Override + public String getStringRepresentation() { + // TODO Auto-generated method stub + return "CMA-plus mutation"; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateESFixedStepSize.java b/src/eva2/optimization/operator/mutation/MutateESFixedStepSize.java index b96546d7..6fa5fb6c 100644 --- a/src/eva2/optimization/operator/mutation/MutateESFixedStepSize.java +++ b/src/eva2/optimization/operator/mutation/MutateESFixedStepSize.java @@ -13,21 +13,23 @@ import eva2.tools.math.RNG; * Time: 17:05:23 * To change this template use File | Settings | File Templates. */ -public class MutateESFixedStepSize implements InterfaceMutation, java.io.Serializable { - protected double m_Sigma = 0.005; +public class MutateESFixedStepSize implements InterfaceMutation, java.io.Serializable { + protected double m_Sigma = 0.005; public MutateESFixedStepSize() { } - + public MutateESFixedStepSize(MutateESFixedStepSize mutator) { - this.m_Sigma = mutator.m_Sigma; + this.m_Sigma = mutator.m_Sigma; } - + public MutateESFixedStepSize(double sigma) { - m_Sigma = sigma; + m_Sigma = sigma; } - - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -35,14 +37,16 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali return new MutateESFixedStepSize(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESFixedStepSize) { - MutateESFixedStepSize mut = (MutateESFixedStepSize)mutator; + MutateESFixedStepSize mut = (MutateESFixedStepSize) mutator; if (this.m_Sigma != mut.m_Sigma) { return false; } @@ -52,27 +56,31 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); for (int i = 0; i < x.length; i++) { - x[i] += ((range[i][1] -range[i][0])/2)*RNG.gaussianDouble(this.m_Sigma); + x[i] += ((range[i][1] - range[i][0]) / 2) * RNG.gaussianDouble(this.m_Sigma); if (range[i][0] > x[i]) { x[i] = range[i][0]; } @@ -80,50 +88,61 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali x[i] = range[i][1]; } } - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override public String getStringRepresentation() { - return "ES fixed step size mutation "+getSigma(); + return "ES fixed step size mutation " + getSigma(); } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES fixed step size mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The fixed step size mutation alters all elements with a fixed mutation step size."; } - /** Set the value for Sigma with this method. - * @param d The mutation operator. + /** + * Set the value for Sigma with this method. + * + * @param d The mutation operator. */ public void setSigma(double d) { if (d < 0) { @@ -131,9 +150,11 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali } this.m_Sigma = d; } + public double getSigma() { return this.m_Sigma; } + public String sigmaTipText() { return "Set the value for the fixed sigma."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESGlobal.java b/src/eva2/optimization/operator/mutation/MutateESGlobal.java index 4e9673f7..dc061495 100644 --- a/src/eva2/optimization/operator/mutation/MutateESGlobal.java +++ b/src/eva2/optimization/operator/mutation/MutateESGlobal.java @@ -8,6 +8,7 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.ArrayList; @@ -19,9 +20,9 @@ import java.util.ArrayList; * To change this template use Options | File Templates. */ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, InterfaceAdditionalPopulationInformer { - protected double m_MutationStepSize = 0.2; - protected double m_Tau1 = 0.15; - protected double m_LowerLimitStepSize = 0.0000005; + protected double m_MutationStepSize = 0.2; + protected double m_Tau1 = 0.15; + protected double m_LowerLimitStepSize = 0.0000005; protected MutateESCrossoverTypeEnum m_CrossoverType = MutateESCrossoverTypeEnum.none; public MutateESGlobal() { @@ -29,31 +30,33 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, /** * Use given mutation step size and no crossover on strategy params. - * + * * @param mutationStepSize */ public MutateESGlobal(double mutationStepSize) { - this(mutationStepSize, MutateESCrossoverTypeEnum.none); + this(mutationStepSize, MutateESCrossoverTypeEnum.none); } /** * Use given mutation step size and given crossover type on strategy params. - * + * * @param mutationStepSize */ public MutateESGlobal(double mutationStepSize, MutateESCrossoverTypeEnum coType) { setMutationStepSize(mutationStepSize); setCrossoverType(coType); } - + public MutateESGlobal(MutateESGlobal mutator) { - this.m_MutationStepSize = mutator.m_MutationStepSize; - this.m_Tau1 = mutator.m_Tau1; - this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; - this.m_CrossoverType = mutator.m_CrossoverType; + this.m_MutationStepSize = mutator.m_MutationStepSize; + this.m_Tau1 = mutator.m_Tau1; + this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; + this.m_CrossoverType = mutator.m_CrossoverType; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -61,14 +64,16 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, return new MutateESGlobal(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESGlobal) { - MutateESGlobal mut = (MutateESGlobal)mutator; + MutateESGlobal mut = (MutateESGlobal) mutator; if (this.m_MutationStepSize != mut.m_MutationStepSize) { return false; } @@ -84,31 +89,35 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceESIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); this.m_MutationStepSize *= Math.exp(this.m_Tau1 * RNG.gaussianDouble(1)); if (this.m_MutationStepSize < this.m_LowerLimitStepSize) { this.m_MutationStepSize = this.m_LowerLimitStepSize; } for (int i = 0; i < x.length; i++) { - x[i] += ((range[i][1] -range[i][0])/2)*RNG.gaussianDouble(this.m_MutationStepSize); + x[i] += ((range[i][1] - range[i][0]) / 2) * RNG.gaussianDouble(this.m_MutationStepSize); if (range[i][0] > x[i]) { x[i] = range[i][0]; } @@ -116,56 +125,60 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, x[i] = range[i][1]; } } - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { - if (m_CrossoverType!=MutateESCrossoverTypeEnum.none) { - ArrayList tmpList = new ArrayList(); - if (indy1.getMutationOperator() instanceof MutateESGlobal) { - tmpList.add(new Double(((MutateESGlobal)indy1.getMutationOperator()).m_MutationStepSize)); + if (m_CrossoverType != MutateESCrossoverTypeEnum.none) { + ArrayList tmpList = new ArrayList(); + if (indy1.getMutationOperator() instanceof MutateESGlobal) { + tmpList.add(new Double(((MutateESGlobal) indy1.getMutationOperator()).m_MutationStepSize)); } - for (int i = 0; i < partners.size(); i++) { - if (((AbstractEAIndividual)partners.get(i)).getMutationOperator() instanceof MutateESGlobal) { - tmpList.add(new Double(((MutateESGlobal)((AbstractEAIndividual)partners.get(i)).getMutationOperator()).m_MutationStepSize)); - } - } - double[] list = new double[tmpList.size()]; - for (int i = 0; i < tmpList.size(); i++) { - list[i] = ((Double)tmpList.get(i)).doubleValue(); + for (int i = 0; i < partners.size(); i++) { + if (((AbstractEAIndividual) partners.get(i)).getMutationOperator() instanceof MutateESGlobal) { + tmpList.add(new Double(((MutateESGlobal) ((AbstractEAIndividual) partners.get(i)).getMutationOperator()).m_MutationStepSize)); + } } - if (list.length <= 1) { + double[] list = new double[tmpList.size()]; + for (int i = 0; i < tmpList.size(); i++) { + list[i] = ((Double) tmpList.get(i)).doubleValue(); + } + if (list.length <= 1) { return; } - switch (this.m_CrossoverType) { - case intermediate : - this.m_MutationStepSize = 0; - for (int i = 0; i < list.length; i++) { - this.m_MutationStepSize += list[i]; + switch (this.m_CrossoverType) { + case intermediate: + this.m_MutationStepSize = 0; + for (int i = 0; i < list.length; i++) { + this.m_MutationStepSize += list[i]; + } + this.m_MutationStepSize /= (double) list.length; + break; + case discrete: + this.m_MutationStepSize = list[RNG.randomInt(0, list.length - 1)]; + break; + case none: // do nothing + break; } - this.m_MutationStepSize /= (double)list.length; - break; - case discrete : - this.m_MutationStepSize = list[RNG.randomInt(0, list.length-1)]; - break; - case none : // do nothing - break; - } - } + } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -176,22 +189,29 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES global mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The global mutation stores only one sigma for all double attributes."; } - /** Set the initial mutation step size with this method. - * @param d The mutation operator. + /** + * Set the initial mutation step size with this method. + * + * @param d The mutation operator. */ public void setMutationStepSize(double d) { if (d < 0) { @@ -199,15 +219,19 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, } this.m_MutationStepSize = d; } + public double getMutationStepSize() { return this.m_MutationStepSize; } + public String mutationStepSizeTipText() { return "Choose the initial mutation step size."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { if (d < 0) { @@ -215,15 +239,19 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, } this.m_LowerLimitStepSize = d; } + public double getLowerLimitStepSize() { return this.m_LowerLimitStepSize; } + public String lowerLimitStepSizeTipText() { return "Set the lower limit for the mutation step size."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setTau1(double d) { if (d < 0) { @@ -231,50 +259,56 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, } this.m_Tau1 = d; } + public double getTau1() { return this.m_Tau1; } + public String tau1TipText() { return "Set the value for tau1."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setCrossoverType(MutateESCrossoverTypeEnum d) { this.m_CrossoverType = d; } + public MutateESCrossoverTypeEnum getCrossoverType() { return this.m_CrossoverType; } + public String crossoverTypeTipText() { return "Choose the crossover type for the strategy parameters."; } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataHeader() - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataHeader() + */ @Override - public String[] getAdditionalDataHeader() { - return new String[] {"sigma"}; - } + public String[] getAdditionalDataHeader() { + return new String[]{"sigma"}; + } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataInfo() - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataInfo() + */ @Override - public String[] getAdditionalDataInfo() { - return new String[] {"The ES global mutation step size."}; - } + public String[] getAdditionalDataInfo() { + return new String[]{"The ES global mutation step size."}; + } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataValue(eva2.optimization.PopulationInterface) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataValue(eva2.optimization.PopulationInterface) + */ @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - return new Object[]{m_MutationStepSize}; - } + public Object[] getAdditionalDataValue(PopulationInterface pop) { + return new Object[]{m_MutationStepSize}; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateESLocal.java b/src/eva2/optimization/operator/mutation/MutateESLocal.java index e433623f..ecd92c8f 100644 --- a/src/eva2/optimization/operator/mutation/MutateESLocal.java +++ b/src/eva2/optimization/operator/mutation/MutateESLocal.java @@ -10,6 +10,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.SelectedTag; import eva2.tools.Tag; import eva2.tools.math.RNG; + import java.util.ArrayList; /** @@ -21,12 +22,12 @@ import java.util.ArrayList; */ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopulationInformer, java.io.Serializable { - protected double m_MutationStepSize = 0.2; - protected double m_Tau1 = 0.15; - protected double m_LowerLimitStepSize = 0.0000005; - private double[] m_Sigmas; - protected double m_Tau2 = 0.15; - protected SelectedTag m_CrossoverType; + protected double m_MutationStepSize = 0.2; + protected double m_Tau1 = 0.15; + protected double m_LowerLimitStepSize = 0.0000005; + private double[] m_Sigmas; + protected double m_Tau2 = 0.15; + protected SelectedTag m_CrossoverType; public MutateESLocal() { this.m_Sigmas = null; @@ -44,14 +45,16 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu this.m_Sigmas[i] = mutator.m_Sigmas[i]; } } - this.m_MutationStepSize = mutator.m_MutationStepSize; - this.m_Tau1 = mutator.m_Tau1; - this.m_Tau2 = mutator.m_Tau2; - this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; - this.m_CrossoverType = (SelectedTag)mutator.m_CrossoverType.clone(); + this.m_MutationStepSize = mutator.m_MutationStepSize; + this.m_Tau1 = mutator.m_Tau1; + this.m_Tau2 = mutator.m_Tau2; + this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; + this.m_CrossoverType = (SelectedTag) mutator.m_CrossoverType.clone(); } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -59,17 +62,19 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu return new MutateESLocal(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { - if (mutator==this) { + if (mutator == this) { return true; } if (mutator instanceof MutateESLocal) { - MutateESLocal mut = (MutateESLocal)mutator; + MutateESLocal mut = (MutateESLocal) mutator; if (this.m_Tau1 != mut.m_Tau1) { return false; } @@ -94,40 +99,44 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { if (individual instanceof InterfaceESIndividual) { // init the Sigmas - this.m_Sigmas = new double[((InterfaceESIndividual)individual).getDGenotype().length]; + this.m_Sigmas = new double[((InterfaceESIndividual) individual).getDGenotype().length]; for (int i = 0; i < this.m_Sigmas.length; i++) { this.m_Sigmas[i] = this.m_MutationStepSize; } } } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceESIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); - double tmpR = RNG.gaussianDouble(1); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); + double tmpR = RNG.gaussianDouble(1); for (int i = 0; i < x.length; i++) { this.m_Sigmas[i] *= Math.exp(this.m_Tau1 * tmpR + this.m_Tau2 * RNG.gaussianDouble(1)); if (this.m_Sigmas[i] < this.m_LowerLimitStepSize) { this.m_Sigmas[i] = this.m_LowerLimitStepSize; } - x[i] += ((range[i][1] -range[i][0])/2)*RNG.gaussianDouble(this.m_Sigmas[i]); + x[i] += ((range[i][1] - range[i][0]) / 2) * RNG.gaussianDouble(this.m_Sigmas[i]); if (range[i][0] > x[i]) { x[i] = range[i][0]; } @@ -135,74 +144,78 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu x[i] = range[i][1]; } } - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { ArrayList tmpListA = new ArrayList(); ArrayList tmpListB = new ArrayList(); if (indy1.getMutationOperator() instanceof MutateESLocal) { - tmpListA.add(new Double(((MutateESLocal)indy1.getMutationOperator()).m_MutationStepSize)); - tmpListB.add(((MutateESLocal)indy1.getMutationOperator()).m_Sigmas); + tmpListA.add(new Double(((MutateESLocal) indy1.getMutationOperator()).m_MutationStepSize)); + tmpListB.add(((MutateESLocal) indy1.getMutationOperator()).m_Sigmas); } for (int i = 0; i < partners.size(); i++) { - if (((AbstractEAIndividual)partners.get(i)).getMutationOperator() instanceof MutateESLocal) { - tmpListA.add(new Double(((MutateESLocal)((AbstractEAIndividual)partners.get(i)).getMutationOperator()).m_MutationStepSize)); - tmpListB.add(((MutateESLocal)((AbstractEAIndividual)partners.get(i)).getMutationOperator()).m_Sigmas); + if (((AbstractEAIndividual) partners.get(i)).getMutationOperator() instanceof MutateESLocal) { + tmpListA.add(new Double(((MutateESLocal) ((AbstractEAIndividual) partners.get(i)).getMutationOperator()).m_MutationStepSize)); + tmpListB.add(((MutateESLocal) ((AbstractEAIndividual) partners.get(i)).getMutationOperator()).m_Sigmas); } } double[] listA = new double[tmpListA.size()]; double[][] listB = new double[tmpListA.size()][]; for (int i = 0; i < tmpListA.size(); i++) { - listA[i] = ((Double)tmpListA.get(i)).doubleValue(); - listB[i] = (double[])tmpListB.get(i); + listA[i] = ((Double) tmpListA.get(i)).doubleValue(); + listB[i] = (double[]) tmpListB.get(i); } if (listA.length <= 1) { return; } switch (this.m_CrossoverType.getSelectedTag().getID()) { - case 1 : { + case 1: { this.m_MutationStepSize = 0; for (int i = 0; i < this.m_Sigmas.length; i++) { - this.m_Sigmas[i] = 0; - } + this.m_Sigmas[i] = 0; + } for (int i = 0; i < listA.length; i++) { this.m_MutationStepSize += listA[i]; for (int j = 0; j < this.m_Sigmas.length; j++) { - this.m_Sigmas[j] += listB[i][j]; + this.m_Sigmas[j] += listB[i][j]; + } } - } - this.m_MutationStepSize /= (double)listA.length; + this.m_MutationStepSize /= (double) listA.length; for (int i = 0; i < this.m_Sigmas.length; i++) { - this.m_Sigmas[i] /= (double)listA.length; - } + this.m_Sigmas[i] /= (double) listA.length; + } break; } - case 2 : { - int rn = RNG.randomInt(0, listA.length-1); + case 2: { + int rn = RNG.randomInt(0, listA.length - 1); this.m_MutationStepSize = listA[rn]; for (int i = 0; i < this.m_Sigmas.length; i++) { - rn = RNG.randomInt(0, listA.length-1); + rn = RNG.randomInt(0, listA.length - 1); this.m_Sigmas[i] = listB[rn][i]; } break; } - default : { + default: { // do nothing } } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -213,22 +226,29 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES local mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The local mutation stores n sigmas for each double attribute."; } - /** Set the initial mutation step size with this method. - * @param d The mutation operator. + /** + * Set the initial mutation step size with this method. + * + * @param d The mutation operator. */ public void setMutationStepSize(double d) { if (d < 0) { @@ -236,15 +256,19 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu } this.m_MutationStepSize = d; } + public double getMutationStepSize() { return this.m_MutationStepSize; } + public String mutationStepSizeTipText() { return "Choose the initial mutation step size sigma."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { if (d < 0) { @@ -252,15 +276,19 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu } this.m_LowerLimitStepSize = d; } + public double getLowerLimitStepSize() { return this.m_LowerLimitStepSize; } + public String lowerLimitStepSizeTipText() { return "Set the lower limit for the mutation step size."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setTau1(double d) { if (d < 0) { @@ -268,15 +296,19 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu } this.m_Tau1 = d; } + public double getTau1() { return this.m_Tau1; } + public String tau1TipText() { return "Set the value for tau1."; } - /** Set the value for tau2 with this method. - * @param d The mutation operator. + /** + * Set the value for tau2 with this method. + * + * @param d The mutation operator. */ public void setTau2(double d) { if (d < 0) { @@ -284,50 +316,56 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu } this.m_Tau2 = d; } + public double getTau2() { return this.m_Tau2; } + public String tau2TipText() { return "Set the value for tau2."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setCrossoverType(SelectedTag d) { this.m_CrossoverType = d; } + public SelectedTag getCrossoverType() { return this.m_CrossoverType; } + public String crossoverTypeTipText() { return "Choose the crossover type for the strategy parameters."; } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataHeader() - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataHeader() + */ @Override - public String[] getAdditionalDataHeader() { - return new String[] {"sigma"}; - } + public String[] getAdditionalDataHeader() { + return new String[]{"sigma"}; + } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataInfo() - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataInfo() + */ @Override - public String[] getAdditionalDataInfo() { - return new String[] {"The ES local mutation step sizes."}; - } + public String[] getAdditionalDataInfo() { + return new String[]{"The ES local mutation step sizes."}; + } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataValue(eva2.optimization.PopulationInterface) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataValue(eva2.optimization.PopulationInterface) + */ @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - return new Object[]{m_Sigmas}; - } + public Object[] getAdditionalDataValue(PopulationInterface pop) { + return new Object[]{m_Sigmas}; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateESMainVectorAdaption.java b/src/eva2/optimization/operator/mutation/MutateESMainVectorAdaption.java index bff1aa9c..a022d195 100644 --- a/src/eva2/optimization/operator/mutation/MutateESMainVectorAdaption.java +++ b/src/eva2/optimization/operator/mutation/MutateESMainVectorAdaption.java @@ -14,52 +14,55 @@ import eva2.tools.math.RNG; * Time: 11:18:36 * To change this template use File | Settings | File Templates. */ -public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Serializable { +public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Serializable { - private boolean m_CheckConstraints = true; - static public final String Name = "MVA"; - private int N; - private double[] m_Z; - private double m_SigmaScalar = 1.0; - private double m_InitSigmaScalar = 1.0; - private double m_c; - private double m_cov; - private double m_Beta; - private double[] s_N; - private double[] s_d_N; - private double[] m_main_v; - private double xi_dach; - private double Z1; - private double w_v = 3.0; + private boolean m_CheckConstraints = true; + static public final String Name = "MVA"; + private int N; + private double[] m_Z; + private double m_SigmaScalar = 1.0; + private double m_InitSigmaScalar = 1.0; + private double m_c; + private double m_cov; + private double m_Beta; + private double[] s_N; + private double[] s_d_N; + private double[] m_main_v; + private double xi_dach; + private double Z1; + private double w_v = 3.0; public MutateESMainVectorAdaption() { } + public MutateESMainVectorAdaption(MutateESMainVectorAdaption mutator) { - this.N = mutator.N; - this.m_SigmaScalar = mutator.m_SigmaScalar; + this.N = mutator.N; + this.m_SigmaScalar = mutator.m_SigmaScalar; this.m_InitSigmaScalar = mutator.m_InitSigmaScalar; - this.m_c = mutator.m_c; - this.m_cov = mutator.m_cov; - this.m_Beta = mutator.m_Beta; - this.xi_dach = mutator.xi_dach; - this.Z1 = mutator.Z1; - this.w_v = mutator.w_v; + this.m_c = mutator.m_c; + this.m_cov = mutator.m_cov; + this.m_Beta = mutator.m_Beta; + this.xi_dach = mutator.xi_dach; + this.Z1 = mutator.Z1; + this.w_v = mutator.w_v; if (mutator.m_main_v != null) { - this.m_main_v = (double[]) mutator.m_main_v.clone(); + this.m_main_v = (double[]) mutator.m_main_v.clone(); } if (mutator.m_Z != null) { - this.m_Z = (double[]) mutator.m_Z.clone(); + this.m_Z = (double[]) mutator.m_Z.clone(); } if (mutator.s_N != null) { - this.s_N = (double[]) mutator.s_N.clone(); + this.s_N = (double[]) mutator.s_N.clone(); } if (mutator.s_d_N != null) { - this.s_d_N = (double[]) mutator.s_d_N.clone(); + this.s_d_N = (double[]) mutator.s_d_N.clone(); } } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -67,19 +70,21 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se return new MutateESMainVectorAdaption(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { - if (this==mutator) { + if (this == mutator) { return true; } if (mutator instanceof MutateESMainVectorAdaption) { - MutateESMainVectorAdaption mut = (MutateESMainVectorAdaption)mutator; + MutateESMainVectorAdaption mut = (MutateESMainVectorAdaption) mutator; // i assume if the main_V is equal then the mutation operators are equal - if (this.m_main_v==mut.m_main_v) { + if (this.m_main_v == mut.m_main_v) { return true; } if (this.m_main_v != null) { @@ -92,38 +97,40 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se return false; } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { if (!(individual instanceof InterfaceESIndividual)) { return; } - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); - this.m_SigmaScalar = this.m_InitSigmaScalar; - this.N = x.length; - this.m_c = Math.sqrt(1.0 / (double) this.N); // Sigma-Path-Constant - this.m_Beta = this. m_c; - this.m_cov = 2.0 / ( (double) this.N * (double) this.N); - this.m_Z = new double[this.N]; - this.s_N = new double[this.N]; - this.s_d_N = new double[this.N]; - this.m_main_v = new double[this.N]; + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] ranges = ((InterfaceESIndividual) individual).getDoubleRange(); + this.m_SigmaScalar = this.m_InitSigmaScalar; + this.N = x.length; + this.m_c = Math.sqrt(1.0 / (double) this.N); // Sigma-Path-Constant + this.m_Beta = this.m_c; + this.m_cov = 2.0 / ((double) this.N * (double) this.N); + this.m_Z = new double[this.N]; + this.s_N = new double[this.N]; + this.s_d_N = new double[this.N]; + this.m_main_v = new double[this.N]; for (int i = 0; i < this.N; i++) { - this.s_N[i] = 0; - this.s_d_N[i] = 0; - this.m_main_v[i] = 0; - }; - this.xi_dach = Math.sqrt(this.N - 0.5); + this.s_N[i] = 0; + this.s_d_N[i] = 0; + this.m_main_v[i] = 0; + } + ; + this.xi_dach = Math.sqrt(this.N - 0.5); for (int i = 0; i < this.N; i++) { this.m_Z[i] = RNG.gaussianDouble(1.0); } @@ -131,16 +138,18 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se evaluateNewObjectX(x, ranges); } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceESIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] ranges = ((InterfaceESIndividual) individual).getDoubleRange(); this.adaptStrategy(); for (int i = 0; i < N; i++) { m_Z[i] = RNG.gaussianDouble(1.0); @@ -148,15 +157,17 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se Z1 = RNG.gaussianDouble(1.0); evaluateNewObjectX(x, ranges); - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -166,7 +177,7 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se private void adaptStrategy() { double length = 0.0; for (int i = 0; i < this.N; i++) { - this.s_d_N[i] = (1.0 - this.m_c) * this.s_d_N[i] + Math.sqrt(this.m_c*(2.0-this.m_c)) * this.m_Z[i]; // PATH + this.s_d_N[i] = (1.0 - this.m_c) * this.s_d_N[i] + Math.sqrt(this.m_c * (2.0 - this.m_c)) * this.m_Z[i]; // PATH length += this.s_d_N[i] * this.s_d_N[i]; } this.m_SigmaScalar *= Math.exp(this.m_Beta * this.m_c * (Math.sqrt(length) - this.xi_dach)); @@ -177,19 +188,18 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se } if (Product < 0.0) { Product = -1.0; - } - else { + } else { Product = 1.0; } for (int i = 0; i < this.N; i++) { // ADAPT MAIN VECTOR - this.s_N[i] = (1.0 - this.m_c) * this.s_N[i] + Math.sqrt(this.m_c*(2.0-this.m_c)) * (this.m_Z[i] + this.Z1 * this.w_v * this.m_main_v[i]); // PATH MAIN VECTOR - this.m_main_v[i] = (1.0 - this.m_cov) * Product * this.m_main_v[i] + this.m_cov * this.s_N[i]; + this.s_N[i] = (1.0 - this.m_c) * this.s_N[i] + Math.sqrt(this.m_c * (2.0 - this.m_c)) * (this.m_Z[i] + this.Z1 * this.w_v * this.m_main_v[i]); // PATH MAIN VECTOR + this.m_main_v[i] = (1.0 - this.m_cov) * Product * this.m_main_v[i] + this.m_cov * this.s_N[i]; } } private void evaluateNewObjectX(double[] x, double[][] range) { if (Double.isNaN((x[0]))) { - System.err.println("treffer in mva "+ x[0]); + System.err.println("treffer in mva " + x[0]); } // boolean constraint = false; @@ -206,28 +216,31 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se // } // } // } - double[] v =(double[])this.m_main_v.clone(); - double[] grad = new double[x.length]; - double vl = 0; - double gradl = 0; - for (int i=0;i < x.length; i++) { - grad[i] = 2*x[i]; - vl += v[i]*v[i]; - gradl += grad[i]*grad[i]; - } - vl = Math.sqrt(vl); - gradl = Math.sqrt(gradl); + double[] v = (double[]) this.m_main_v.clone(); + double[] grad = new double[x.length]; + double vl = 0; + double gradl = 0; for (int i = 0; i < x.length; i++) { - v[i] /= vl; grad[i] /= gradl; + grad[i] = 2 * x[i]; + vl += v[i] * v[i]; + gradl += grad[i] * grad[i]; + } + vl = Math.sqrt(vl); + gradl = Math.sqrt(gradl); + for (int i = 0; i < x.length; i++) { + v[i] /= vl; + grad[i] /= gradl; x[i] += this.m_SigmaScalar * (this.m_Z[i] + this.Z1 * this.w_v * this.m_main_v[i]); } if (getCheckConstraints()) { // MK: lets actually do a constraint check - Mathematics.projectToRange(x, range); + Mathematics.projectToRange(x, range); } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -237,29 +250,38 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "MVA mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is the most sophisticated MVA mutation."; } - /** Use only positive numbers this limits the freedom of effect. - * @param bit The new representation for the inner constants. - */ + /** + * Use only positive numbers this limits the freedom of effect. + * + * @param bit The new representation for the inner constants. + */ public void setCheckConstraints(boolean bit) { this.m_CheckConstraints = bit; } + public boolean getCheckConstraints() { return this.m_CheckConstraints; } + public String checkConstraintsTipText() { return "Toggle check constraints."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESMutativeStepSizeControl.java b/src/eva2/optimization/operator/mutation/MutateESMutativeStepSizeControl.java index 9dabba20..942fe74a 100644 --- a/src/eva2/optimization/operator/mutation/MutateESMutativeStepSizeControl.java +++ b/src/eva2/optimization/operator/mutation/MutateESMutativeStepSizeControl.java @@ -14,38 +14,40 @@ import eva2.tools.math.RNG; * To change this template use File | Settings | File Templates. */ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java.io.Serializable { - protected double m_MutationStepSize = 0.2; - protected double m_Alpha = 1.2; - protected double m_LowerLimitStepSize = 0.0000005; - protected double m_UpperLimitStepSize = 0.4; + protected double m_MutationStepSize = 0.2; + protected double m_Alpha = 1.2; + protected double m_LowerLimitStepSize = 0.0000005; + protected double m_UpperLimitStepSize = 0.4; public MutateESMutativeStepSizeControl() { } - + public MutateESMutativeStepSizeControl(double initialStepSize, double lowerLimit, double upperLimit) { - m_MutationStepSize = initialStepSize; - if (m_LowerLimitStepSize > m_UpperLimitStepSize) { - System.err.println("Invalid step size bounds, switching upper and lower..."); - double tmp = upperLimit; - upperLimit = lowerLimit; - lowerLimit = tmp; - } - m_LowerLimitStepSize = lowerLimit; - m_UpperLimitStepSize = upperLimit; - if (initialStepSize < lowerLimit || initialStepSize > upperLimit) { - m_MutationStepSize = (upperLimit + lowerLimit) /2.; - System.err.println("Invalid initial stepsize, setting it to " + m_MutationStepSize); - } - } - - public MutateESMutativeStepSizeControl(MutateESMutativeStepSizeControl mutator) { - this.m_MutationStepSize = mutator.m_MutationStepSize; - this.m_Alpha = mutator.m_Alpha; - this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; - this.m_UpperLimitStepSize = mutator.m_UpperLimitStepSize; + m_MutationStepSize = initialStepSize; + if (m_LowerLimitStepSize > m_UpperLimitStepSize) { + System.err.println("Invalid step size bounds, switching upper and lower..."); + double tmp = upperLimit; + upperLimit = lowerLimit; + lowerLimit = tmp; + } + m_LowerLimitStepSize = lowerLimit; + m_UpperLimitStepSize = upperLimit; + if (initialStepSize < lowerLimit || initialStepSize > upperLimit) { + m_MutationStepSize = (upperLimit + lowerLimit) / 2.; + System.err.println("Invalid initial stepsize, setting it to " + m_MutationStepSize); + } } - /** This method will enable you to clone a given mutation operator + public MutateESMutativeStepSizeControl(MutateESMutativeStepSizeControl mutator) { + this.m_MutationStepSize = mutator.m_MutationStepSize; + this.m_Alpha = mutator.m_Alpha; + this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; + this.m_UpperLimitStepSize = mutator.m_UpperLimitStepSize; + } + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -53,14 +55,16 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. return new MutateESMutativeStepSizeControl(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESMutativeStepSizeControl) { - MutateESMutativeStepSizeControl mut = (MutateESMutativeStepSizeControl)mutator; + MutateESMutativeStepSizeControl mut = (MutateESMutativeStepSizeControl) mutator; if (this.m_MutationStepSize != mut.m_MutationStepSize) { return false; } @@ -79,29 +83,32 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); if (RNG.flipCoin(0.5)) { this.m_MutationStepSize *= this.m_Alpha; - } - else { + } else { this.m_MutationStepSize /= this.m_Alpha; } if (this.m_MutationStepSize < this.m_LowerLimitStepSize) { @@ -111,7 +118,7 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. this.m_MutationStepSize = this.m_UpperLimitStepSize; } for (int i = 0; i < x.length; i++) { - x[i] += ((range[i][1] -range[i][0])/2)*RNG.gaussianDouble(this.m_MutationStepSize); + x[i] += ((range[i][1] - range[i][0]) / 2) * RNG.gaussianDouble(this.m_MutationStepSize); if (range[i][0] > x[i]) { x[i] = range[i][0]; } @@ -119,24 +126,28 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. x[i] = range[i][1]; } } - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); // System.out.println("new step size: " + mutationStepSize); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -147,22 +158,29 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "MSR"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The mutative step size control mutation randomly increases/decreases the current step size."; } - /** Set the initial mutation step size with this method. - * @param d The mutation operator. + /** + * Set the initial mutation step size with this method. + * + * @param d The mutation operator. */ public void setMutationStepSize(double d) { if (d < 0) { @@ -170,41 +188,53 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. } this.m_MutationStepSize = d; } + public double getMutationStepSize() { return this.m_MutationStepSize; } + public String mutationStepSizeTipText() { return "Choose the initial mutation step size."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { this.m_LowerLimitStepSize = d; } + public double getLowerLimitStepSize() { return this.m_LowerLimitStepSize; } + public String lowerLimitStepSizeTipText() { return "Set the lower limit for the mutation step size."; } - - /** Set the upper limit for the mutation step size with this method. - * @param d The mutation operator. + + /** + * Set the upper limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setUpperLimitStepSize(double d) { this.m_UpperLimitStepSize = d; } + public double getUpperLimitStepSize() { return this.m_UpperLimitStepSize; } + public String upperLimitStepSizeTipText() { return "Set the upper limit for the mutation step size."; } - /** Set the value for Alpha with this method. - * @param d The mutation operator. + /** + * Set the value for Alpha with this method. + * + * @param d The mutation operator. */ public void setAlpha(double d) { if (d < 0) { @@ -212,9 +242,11 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. } this.m_Alpha = d; } + public double getAlpha() { return this.m_Alpha; } + public String alphaTipText() { return "Set the value for alpha."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESPathLengthAdaption.java b/src/eva2/optimization/operator/mutation/MutateESPathLengthAdaption.java index e7cf3769..3e4bf2e1 100644 --- a/src/eva2/optimization/operator/mutation/MutateESPathLengthAdaption.java +++ b/src/eva2/optimization/operator/mutation/MutateESPathLengthAdaption.java @@ -10,42 +10,44 @@ import eva2.tools.math.RNG; /** * ES mutation with path length control. The step size (single sigma) is * adapted using the evolution path length by adapting the real path length - * to the expected path length in for uncorrelated single steps. + * to the expected path length in for uncorrelated single steps. * See Hansen&Ostermeier 2001, Eqs. 16,17. - * */ -public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Serializable { +public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Serializable { - private int m_dim; - private double[] m_randZ; - private double[] m_Path; - private double m_SigmaGlobal = 1.0; - private double m_c; - private boolean m_UsePath = true; - private double dampening = 1; - private double expectedPathLen = -1; - private double m_cu; + private int m_dim; + private double[] m_randZ; + private double[] m_Path; + private double m_SigmaGlobal = 1.0; + private double m_c; + private boolean m_UsePath = true; + private double dampening = 1; + private double expectedPathLen = -1; + private double m_cu; public MutateESPathLengthAdaption() { } + public MutateESPathLengthAdaption(MutateESPathLengthAdaption mutator) { - this.m_UsePath = true; - this.m_dim = mutator.m_dim; - this.m_SigmaGlobal = mutator.m_SigmaGlobal; - this.m_c = mutator.m_c; - this.dampening = mutator.dampening; - this.expectedPathLen = mutator.expectedPathLen; - this.m_cu = mutator.m_cu; + this.m_UsePath = true; + this.m_dim = mutator.m_dim; + this.m_SigmaGlobal = mutator.m_SigmaGlobal; + this.m_c = mutator.m_c; + this.dampening = mutator.dampening; + this.expectedPathLen = mutator.expectedPathLen; + this.m_cu = mutator.m_cu; if (mutator.m_randZ != null) { - this.m_randZ = (double[]) mutator.m_randZ.clone(); + this.m_randZ = (double[]) mutator.m_randZ.clone(); } if (mutator.m_Path != null) { - this.m_Path = (double[]) mutator.m_Path.clone(); + this.m_Path = (double[]) mutator.m_Path.clone(); } } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -53,14 +55,16 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se return new MutateESPathLengthAdaption(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESPathLengthAdaption) { - MutateESPathLengthAdaption mut = (MutateESPathLengthAdaption)mutator; + MutateESPathLengthAdaption mut = (MutateESPathLengthAdaption) mutator; // i assume if the C Matrix is equal then the mutation operators are equal if (this.m_dim != mut.m_dim) { return false; @@ -86,27 +90,28 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se } } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { if (!(individual instanceof InterfaceESIndividual)) { return; } - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); - this.m_dim = x.length; + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] ranges = ((InterfaceESIndividual) individual).getDoubleRange(); + this.m_dim = x.length; // if (this.m_UsePath) this.m_c = Math.sqrt(1.0 / (double) this.m_dim); - - this.m_randZ = new double[this.m_dim]; + + this.m_randZ = new double[this.m_dim]; this.m_Path = new double[this.m_dim]; for (int i = 0; i < this.m_dim; i++) { this.m_randZ[i] = RNG.gaussianDouble(1.0); @@ -114,62 +119,65 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se } if (this.m_UsePath) { - this.m_c = 4./(m_dim+4); - } - else { + this.m_c = 4. / (m_dim + 4); + } else { this.m_c = 1.0; } - - expectedPathLen = Math.sqrt(m_dim)*(1-(1./(4*m_dim))+(1./(21*m_dim*m_dim))); - dampening = (1./m_c)+1; - m_cu = Math.sqrt(m_c*(2.0-m_c)); - + + expectedPathLen = Math.sqrt(m_dim) * (1 - (1. / (4 * m_dim)) + (1. / (21 * m_dim * m_dim))); + dampening = (1. / m_c) + 1; + m_cu = Math.sqrt(m_c * (2.0 - m_c)); + mutateX(x, ranges, true); } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); - + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] ranges = ((InterfaceESIndividual) individual).getDoubleRange(); + this.adaptStrategy(); // this updates the path using the old step and adapts sigma - + this.calculateNewStep(); - + this.mutateX(x, ranges, true); // this performs new mutation - - ((InterfaceESIndividual)individual).SetDGenotype(x); + + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - - private void checkRange(double[] x, double[][] ranges) { - for (int i = 0; i < x.length; i++) { - if (x[i] < ranges[i][0]) { - x[i] = ranges[i][0]; - } - if (x[i] > ranges[i][1]) { - x[i] = ranges[i][1]; - } - } - } + + private void checkRange(double[] x, double[][] ranges) { + for (int i = 0; i < x.length; i++) { + if (x[i] < ranges[i][0]) { + x[i] = ranges[i][0]; + } + if (x[i] > ranges[i][1]) { + x[i] = ranges[i][1]; + } + } + } private void calculateNewStep() { - for (int i = 0; i < m_dim; i++) { + for (int i = 0; i < m_dim; i++) { m_randZ[i] = RNG.gaussianDouble(1.0); - } - } - - /** This method allows you to perform either crossover on the strategy parameters + } + } + + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -179,18 +187,18 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se private void adaptStrategy() { // remember the path taken. m_randZ is at this time the last step before selection. for (int i = 0; i < m_dim; i++) { - m_Path [i] = (1.0 -m_c) * m_Path[i] + m_cu*m_randZ[i]; + m_Path[i] = (1.0 - m_c) * m_Path[i] + m_cu * m_randZ[i]; } double pathLen = Mathematics.norm(m_Path); - + // double expectedPathLen = Math.sqrt(((double)m_dim)+0.5); // double kappa_d = ((double)m_dim)/4.0+1.0; - - double exp = (pathLen - expectedPathLen)/(dampening*expectedPathLen); + + double exp = (pathLen - expectedPathLen) / (dampening * expectedPathLen); m_SigmaGlobal *= Math.exp(exp); } - private void mutateX(double[] x,double[][] range, boolean checkRange) { + private void mutateX(double[] x, double[][] range, boolean checkRange) { for (int i = 0; i < x.length; i++) { x[i] += m_SigmaGlobal * m_randZ[i]; } @@ -199,8 +207,10 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -210,14 +220,19 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Mutation/Path-Length-Control"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -237,15 +252,19 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se // return "Use path."; // } - /** This method allows you to set the initial sigma value. - * @param d The initial sigma value. - */ + /** + * This method allows you to set the initial sigma value. + * + * @param d The initial sigma value. + */ public void setSigmaGlobal(double d) { this.m_SigmaGlobal = d; } + public double getSigmaGlobal() { return this.m_SigmaGlobal; } + public String initSigmaGlobalTipText() { return "Set the initial global step size."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESPolynomial.java b/src/eva2/optimization/operator/mutation/MutateESPolynomial.java index bc664ff8..03325a7a 100644 --- a/src/eva2/optimization/operator/mutation/MutateESPolynomial.java +++ b/src/eva2/optimization/operator/mutation/MutateESPolynomial.java @@ -13,21 +13,23 @@ import eva2.tools.math.RNG; * Time: 17:05:23 * To change this template use File | Settings | File Templates. */ -public class MutateESPolynomial implements InterfaceMutation, java.io.Serializable { - private double m_Eta = 0.2; +public class MutateESPolynomial implements InterfaceMutation, java.io.Serializable { + private double m_Eta = 0.2; public MutateESPolynomial() { } - + public MutateESPolynomial(MutateESPolynomial mutator) { - this.m_Eta = mutator.m_Eta; + this.m_Eta = mutator.m_Eta; } - + public MutateESPolynomial(double eta) { - m_Eta = eta; + m_Eta = eta; } - - /** This method will enable you to clone a given mutation operator + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -35,14 +37,16 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab return new MutateESPolynomial(this); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESPolynomial) { - MutateESPolynomial mut = (MutateESPolynomial)mutator; + MutateESPolynomial mut = (MutateESPolynomial) mutator; if (this.m_Eta != mut.m_Eta) { return false; } @@ -52,34 +56,38 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceESIndividual) { - double[] x = ((InterfaceESIndividual)individual).getDGenotype(); - double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); + double[] x = ((InterfaceESIndividual) individual).getDGenotype(); + double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); for (int i = 0; i < x.length; i++) { - - double r = RNG.randomDouble(); - double delta=0; - if(r < 0.5){ - delta = Math.pow((2*r),(1/(m_Eta+1))) - 1; - }else{ - delta = 1 - Math.pow((2*(1 - r)),(1/(m_Eta+1))); - } + + double r = RNG.randomDouble(); + double delta = 0; + if (r < 0.5) { + delta = Math.pow((2 * r), (1 / (m_Eta + 1))) - 1; + } else { + delta = 1 - Math.pow((2 * (1 - r)), (1 / (m_Eta + 1))); + } x[i] += delta; if (range[i][0] > x[i]) { @@ -89,24 +97,28 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab x[i] = range[i][1]; } } - ((InterfaceESIndividual)individual).SetDGenotype(x); + ((InterfaceESIndividual) individual).SetDGenotype(x); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -117,23 +129,30 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "ES polynomial mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public String globalInfo() { return "The polynomial mutation alters all elements according to a polynomial distribution"; } - /** This method allows you to set the number of crossovers that occur in the + /** + * This method allows you to set the number of crossovers that occur in the * genotype. - * @param a The number of crossovers. + * + * @param a The number of crossovers. */ public void setEta(double a) { if (a < 0) { @@ -141,9 +160,11 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab } this.m_Eta = a; } + public double getEta() { return this.m_Eta; } + public String etaTipText() { return "Set the Eta_c value (the larger the value, the more restricted the search)."; } diff --git a/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java b/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java index 5c3e7273..869c6bbb 100644 --- a/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java +++ b/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java @@ -15,210 +15,213 @@ import eva2.tools.Pair; import eva2.tools.math.Jama.EigenvalueDecomposition; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.io.Serializable; /** * Implementing CMA ES with rank-mu-update and weighted recombination. More information can be found here: * - http://www.bionik.tu-berlin.de/user/niko/cmaesintro.html * - N.Hansen & S.Kern 2004: Evaluating the CMA Evolution Strategy on Multimodal Test Functions. - * Parallel Problem Solving from Nature 2004. - * - For the stopping criteria: Auger&Hansen, CEC '05, A Restart CMA ES with increasing population size. - * + * Parallel Problem Solving from Nature 2004. + * - For the stopping criteria: Auger&Hansen, CEC '05, A Restart CMA ES with increasing population size. + *

* The implementation uses a structure for keeping all adaptive parameters, CMAParamSet, which is stored * in the populations, so that in principle, multi-modal optimization with several populations becomes possible. * This of course requires proper handling of the generational cycle, i.e., new generations should be cloned from * the former ones (without individuals is ok) so that the parameters are taken over. - * - * @author mkron * + * @author mkron */ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, InterfaceMutation, Serializable { -// int dim; - private double c_c, expRandStepLen; - - // The static member lastParams is used to store the parameter set last seen in an adaption step, which - // is then later used for the individual mutations. Necessary because each individual has its own mutator - // instance. It would be cleaner to keep all parameters within the individual and have just one mutation - // instance, however this would create quite a big baustelle. - private static transient CMAParamSet lastParams=null; + // int dim; + private double c_c, expRandStepLen; - private ESMutationInitialSigma initializeSig = ESMutationInitialSigma.quarterRange; - private double userDefInitSig = 0.2; + // The static member lastParams is used to store the parameter set last seen in an adaption step, which + // is then later used for the individual mutations. Necessary because each individual has its own mutator + // instance. It would be cleaner to keep all parameters within the individual and have just one mutation + // instance, however this would create quite a big baustelle. + private static transient CMAParamSet lastParams = null; - private boolean doRankMuUpdate = true; - private boolean checkRange = true; - public static final String cmaParamsKey = "RankMuCMAParameters"; - - public static boolean TRACE_1 = false; // true for plotting CMA - public static boolean TRACE_2 = false; // true for plotting CMA - public static boolean TRACE_TEST = false; + private ESMutationInitialSigma initializeSig = ESMutationInitialSigma.quarterRange; + private double userDefInitSig = 0.2; - public MutateESRankMuCMA() { - } + private boolean doRankMuUpdate = true; + private boolean checkRange = true; + public static final String cmaParamsKey = "RankMuCMAParameters"; - public MutateESRankMuCMA(MutateESRankMuCMA mutator) { - this.c_c = mutator.c_c; - this.expRandStepLen = mutator.expRandStepLen; - this.initializeSig = mutator.initializeSig; - this.userDefInitSig = mutator.userDefInitSig; - this.checkRange = mutator.checkRange; - this.doRankMuUpdate = mutator.doRankMuUpdate; - } + public static boolean TRACE_1 = false; // true for plotting CMA + public static boolean TRACE_2 = false; // true for plotting CMA + public static boolean TRACE_TEST = false; + + public MutateESRankMuCMA() { + } + + public MutateESRankMuCMA(MutateESRankMuCMA mutator) { + this.c_c = mutator.c_c; + this.expRandStepLen = mutator.expRandStepLen; + this.initializeSig = mutator.initializeSig; + this.userDefInitSig = mutator.userDefInitSig; + this.checkRange = mutator.checkRange; + this.doRankMuUpdate = mutator.doRankMuUpdate; + } @Override - public Object clone() { + public Object clone() { // if (TRACE) System.out.println("WCMA clone"); - return new MutateESRankMuCMA(this); - } - - public static double[] getMeanXOfPop(Population pop) { - CMAParamSet params = (CMAParamSet)pop.getData(MutateESRankMuCMA.cmaParamsKey); - if (params==null) { - return null; - } - else { - return params.meanX; - } - } + return new MutateESRankMuCMA(this); + } - /** - * Retrieve the initial sigma for the given population and the user defined method. - * For the halfRange case, -1 is returned, as the range is not available here but set - * in initializing the CMAParams. - * @param initGen - * @return - */ - private double getInitSigma(Population initGen) { - switch (initializeSig) { - case avgInitialDistance: - // scaled by average range as the measures are normed - //return initGen.getPopulationMeasures(null)[0]*getAvgRange(); - // use euclidian measures without normation and scaling - return initGen.getPopulationMeasures(new EuclideanMetric())[0]; // use euclidean metric which is not normed by range instead of phenotype metric - //case halfRange: return getAvgRange(range)/2.; - case userDefined: return userDefInitSig ; - case halfRange: return -0.5; - case quarterRange: return -0.25; - } - throw new RuntimeException("Unknown initial sigma type!"); - } - - /** - * Perform the main adaption of sigma and C using evolution paths. - * The evolution path is deduced from the center of the selected population compared to the old - * mean value. - * See Hansen&Kern 04 for further information. - * @param oldGen - * @param selectedP - */ + public static double[] getMeanXOfPop(Population pop) { + CMAParamSet params = (CMAParamSet) pop.getData(MutateESRankMuCMA.cmaParamsKey); + if (params == null) { + return null; + } else { + return params.meanX; + } + } + + /** + * Retrieve the initial sigma for the given population and the user defined method. + * For the halfRange case, -1 is returned, as the range is not available here but set + * in initializing the CMAParams. + * + * @param initGen + * @return + */ + private double getInitSigma(Population initGen) { + switch (initializeSig) { + case avgInitialDistance: + // scaled by average range as the measures are normed + //return initGen.getPopulationMeasures(null)[0]*getAvgRange(); + // use euclidian measures without normation and scaling + return initGen.getPopulationMeasures(new EuclideanMetric())[0]; // use euclidean metric which is not normed by range instead of phenotype metric + //case halfRange: return getAvgRange(range)/2.; + case userDefined: + return userDefInitSig; + case halfRange: + return -0.5; + case quarterRange: + return -0.25; + } + throw new RuntimeException("Unknown initial sigma type!"); + } + + /** + * Perform the main adaption of sigma and C using evolution paths. + * The evolution path is deduced from the center of the selected population compared to the old + * mean value. + * See Hansen&Kern 04 for further information. + * + * @param oldGen + * @param selectedP + */ @Override - public void adaptAfterSelection(Population oldGen, Population selectedP) { - Population selectedSorted = selectedP.getSortedBestFirst(new AbstractEAIndividualComparator(-1)); - - int mu,lambda; - mu = selectedP.size(); - lambda = oldGen.size(); - int generation = oldGen.getGeneration(); - if (mu >= lambda) { - // try to override by oldGen additional data: - if (oldGen.hasData(EvolutionStrategies.esMuParam)) { - mu=(Integer) oldGen.getData(EvolutionStrategies.esMuParam); - } - if (oldGen.hasData(EvolutionStrategies.esLambdaParam)) { - lambda=(Integer) oldGen.getData(EvolutionStrategies.esLambdaParam); - } - } - if (mu >= lambda) { - mu = Math.max(1,lambda/2); - EVAERROR.errorMsgOnce("Warning: invalid mu/lambda ratio! Setting mu to lambda/2 = " + mu + ", lambda = " + lambda); - } - CMAParamSet params; - if (oldGen.getGeneration() <= 1) { // init new param set. At gen < 1 we shouldnt be called, but better do it once too often - if (oldGen.hasData(cmaParamsKey)) { - params = CMAParamSet.initCMAParams((CMAParamSet)oldGen.getData(cmaParamsKey), mu, lambda, oldGen, getInitSigma(oldGen)); - } - else { - params = CMAParamSet.initCMAParams(mu, lambda, oldGen, getInitSigma(oldGen)); - } - } else { - if (!oldGen.hasData(cmaParamsKey)) { - if (oldGen.getGeneration() > 1) { - EVAERROR.errorMsgOnce("Error: population lost cma parameters. Incompatible optimizer?"); - } - params = CMAParamSet.initCMAParams(mu, lambda, oldGen, getInitSigma(oldGen)); - } else { - params = (CMAParamSet)oldGen.getData(cmaParamsKey); - } - } + public void adaptAfterSelection(Population oldGen, Population selectedP) { + Population selectedSorted = selectedP.getSortedBestFirst(new AbstractEAIndividualComparator(-1)); - if (lambda==1 && (oldGen.size()==1) && (selectedP.size()==1) && (oldGen.getEAIndividual(0).equals(selectedP.getEAIndividual(0)))) { - // nothing really happened, so do not adapt and just store default params - lastParams = (CMAParamSet)params.clone(); - oldGen.putData(cmaParamsKey, params); - selectedP.putData(cmaParamsKey, params); - return; - } - - if (TRACE_1) { - System.out.println("WCMA adaptGenerational **********"); -// System.out.println("newPop measures: " + BeanInspector.toString(newPop.getPopulationMeasures())); - System.out.println("mu_eff: " + CMAParamSet.getMuEff(params.weights, mu)); - System.out.println(params.toString()); - System.out.println("*********************************"); - } - - double[] newMeanX = calcMeanX(params.weights, selectedSorted); - if (TRACE_1) { - System.out.println("newMeanX: " + BeanInspector.toString(newMeanX)); + int mu, lambda; + mu = selectedP.size(); + lambda = oldGen.size(); + int generation = oldGen.getGeneration(); + if (mu >= lambda) { + // try to override by oldGen additional data: + if (oldGen.hasData(EvolutionStrategies.esMuParam)) { + mu = (Integer) oldGen.getData(EvolutionStrategies.esMuParam); } - - int dim=params.meanX.length; + if (oldGen.hasData(EvolutionStrategies.esLambdaParam)) { + lambda = (Integer) oldGen.getData(EvolutionStrategies.esLambdaParam); + } + } + if (mu >= lambda) { + mu = Math.max(1, lambda / 2); + EVAERROR.errorMsgOnce("Warning: invalid mu/lambda ratio! Setting mu to lambda/2 = " + mu + ", lambda = " + lambda); + } + CMAParamSet params; + if (oldGen.getGeneration() <= 1) { // init new param set. At gen < 1 we shouldnt be called, but better do it once too often + if (oldGen.hasData(cmaParamsKey)) { + params = CMAParamSet.initCMAParams((CMAParamSet) oldGen.getData(cmaParamsKey), mu, lambda, oldGen, getInitSigma(oldGen)); + } else { + params = CMAParamSet.initCMAParams(mu, lambda, oldGen, getInitSigma(oldGen)); + } + } else { + if (!oldGen.hasData(cmaParamsKey)) { + if (oldGen.getGeneration() > 1) { + EVAERROR.errorMsgOnce("Error: population lost cma parameters. Incompatible optimizer?"); + } + params = CMAParamSet.initCMAParams(mu, lambda, oldGen, getInitSigma(oldGen)); + } else { + params = (CMAParamSet) oldGen.getData(cmaParamsKey); + } + } + + if (lambda == 1 && (oldGen.size() == 1) && (selectedP.size() == 1) && (oldGen.getEAIndividual(0).equals(selectedP.getEAIndividual(0)))) { + // nothing really happened, so do not adapt and just store default params + lastParams = (CMAParamSet) params.clone(); + oldGen.putData(cmaParamsKey, params); + selectedP.putData(cmaParamsKey, params); + return; + } + + if (TRACE_1) { + System.out.println("WCMA adaptGenerational **********"); +// System.out.println("newPop measures: " + BeanInspector.toString(newPop.getPopulationMeasures())); + System.out.println("mu_eff: " + CMAParamSet.getMuEff(params.weights, mu)); + System.out.println(params.toString()); + System.out.println("*********************************"); + } + + double[] newMeanX = calcMeanX(params.weights, selectedSorted); + if (TRACE_1) { + System.out.println("newMeanX: " + BeanInspector.toString(newMeanX)); + } + + int dim = params.meanX.length; double[] BDz = new double[dim]; - for (int i=0; i 1 && (selected.size()>1)) { - // selected pop is sorted - if (nearlySame(selected.getEAIndividual(0).getFitness(),selected.getEAIndividual(selected.size()-1).getFitness())) { - if (TRACE_1) { - System.err.println("flat fitness landscape, consider reformulation of fitness, step-size increased"); - } - params.sigma *= Math.exp(0.2+params.c_sig/params.d_sig); + boolean corrected = true; + /* Flat Fitness, Test if function values are identical */ + if (iterations > 1 && (selected.size() > 1)) { + // selected pop is sorted + if (nearlySame(selected.getEAIndividual(0).getFitness(), selected.getEAIndividual(selected.size() - 1).getFitness())) { + if (TRACE_1) { + System.err.println("flat fitness landscape, consider reformulation of fitness, step-size increased"); + } + params.sigma *= Math.exp(0.2 + params.c_sig / params.d_sig); // sigma=0.1; - } - } - + } + } + if (!checkValidDouble(params.sigma)) { - System.err.println("Error, unstable sigma!"); - corrected = false; + System.err.println("Error, unstable sigma!"); + corrected = false; // params.sigma=params.firstSigma; // MK TODO // System.err.println( } - + /* Align (renormalize) scale C (and consequently sigma) */ /* e.g. for infinite stationary state simulations (noise * handling needs to be introduced for that) */ - double fac = 1.; - double minEig = 1e-12; - double maxEig = 1e8; - if (Mathematics.max(params.eigenvalues) < minEig) { - fac = 1./Math.sqrt(Mathematics.max(params.eigenvalues)); - } - else if (Mathematics.min(params.eigenvalues) > maxEig) { - fac = 1./Math.sqrt(Mathematics.min(params.eigenvalues)); + double fac = 1.; + double minEig = 1e-12; + double maxEig = 1e8; + if (Mathematics.max(params.eigenvalues) < minEig) { + fac = 1. / Math.sqrt(Mathematics.max(params.eigenvalues)); + } else if (Mathematics.min(params.eigenvalues) > maxEig) { + fac = 1. / Math.sqrt(Mathematics.min(params.eigenvalues)); } - if (fac != 1.) { + if (fac != 1.) { // System.err.println("Scaling by " + fac); - params.sigma /= fac; - for(int i = 0; i < params.meanX.length; ++i) { - params.pathC[i] *= fac; - params.eigenvalues[i] *= fac*fac; - for (int j = 0; j <= i; ++j) { - params.mC.set(i, j, params.mC.get(i,j)*fac*fac); - if (i!=j) { - params.mC.set(j, i, params.mC.get(i,j)); - } - } - } - } - return corrected; - } // Test... - - private boolean nearlySame(double[] bestFitness, double[] worstFitness) { - double epsilon = 1e-14; - for (int i=0; iepsilon) { - return false; + params.sigma /= fac; + for (int i = 0; i < params.meanX.length; ++i) { + params.pathC[i] *= fac; + params.eigenvalues[i] *= fac * fac; + for (int j = 0; j <= i; ++j) { + params.mC.set(i, j, params.mC.get(i, j) * fac * fac); + if (i != j) { + params.mC.set(j, i, params.mC.get(i, j)); } + } + } } - return true; - } + return corrected; + } // Test... - /** - * Return the range scaled sigma parameter for dimension i. - * - * @param i - * @return - */ - private double getSigma(CMAParamSet params, int i) { - return params.sigma; - } + private boolean nearlySame(double[] bestFitness, double[] worstFitness) { + double epsilon = 1e-14; + for (int i = 0; i < bestFitness.length; i++) { + if (Math.abs(bestFitness[i] - worstFitness[i]) > epsilon) { + return false; + } + } + return true; + } + + /** + * Return the range scaled sigma parameter for dimension i. + * + * @param i + * @return + */ + private double getSigma(CMAParamSet params, int i) { + return params.sigma; + } // // private double getDamps() { // return d_sig; // } - private double getCc() { - return c_c; - } + private double getCc() { + return c_c; + } // private double getCs() { // return c_sig; // } - private double calcExpRandStepLen(int dim) { - // scale by avg range? - return Math.sqrt(dim)*(1.-(1./(4*dim))+(1./(21*dim*dim))); - } + private double calcExpRandStepLen(int dim) { + // scale by avg range? + return Math.sqrt(dim) * (1. - (1. / (4 * dim)) + (1. / (21 * dim * dim))); + } - /* update C */ - private void updateCov(CMAParamSet params, double[] newPathC, double[] newMeanX, double hsig, int mu, Population selected) { - double newVal = 0; - int dim = newMeanX.length; - double ccv = getCCov(params.weights, mu, dim); + /* update C */ + private void updateCov(CMAParamSet params, double[] newPathC, double[] newMeanX, double hsig, int mu, Population selected) { + double newVal = 0; + int dim = newMeanX.length; + double ccv = getCCov(params.weights, mu, dim); if (ccv > 0) { - double mcv = CMAParamSet.getMuCov(params.weights, mu); + double mcv = CMAParamSet.getMuCov(params.weights, mu); /* (only upper triangle!) */ /* update covariance matrix */ - //System.out.println("CCov " + getCCov(selected) + " Cc " + getCc() + " muCov " + getMuCov(selected)); + //System.out.println("CCov " + getCCov(selected) + " Cc " + getCc() + " muCov " + getMuCov(selected)); for (int i = 0; i < dim; ++i) { for (int j = 0; j <= i; ++j) { // oldVal = mC.get(i,j); - newVal = (1 - ccv) * params.mC.get(i,j) - + ccv - * (1. / mcv) - * (newPathC[i] * newPathC[j] + (1 - hsig) * getCc() - * (2. - getCc()) * params.mC.get(i,j)); - checkValidDouble(newVal); - params.mC.set(i,j,newVal); - if (isRankMu()) { - for (int k = 0; k < mu; ++k) { + newVal = (1 - ccv) * params.mC.get(i, j) + + ccv + * (1. / mcv) + * (newPathC[i] * newPathC[j] + (1 - hsig) * getCc() + * (2. - getCc()) * params.mC.get(i, j)); + checkValidDouble(newVal); + params.mC.set(i, j, newVal); + if (isRankMu()) { + for (int k = 0; k < mu; ++k) { /* * additional rank mu * update */ - // double[] x_k = ((InterfaceDataTypeDouble)selected.getEAIndividual(k)).getDoubleData(); - double[] x_k = AbstractEAIndividual.getDoublePositionShallow(selected.getEAIndividual(k)); - newVal = params.mC.get(i,j)+ ccv * (1 - 1. / mcv) - * params.weights[k] * (x_k[i] - params.meanX[i]) - * (x_k[j] - params.meanX[j]) / (getSigma(params, i) * getSigma(params, j)); // TODO right sigmas? - checkValidDouble(newVal); - params.mC.set(i,j, newVal); - } + // double[] x_k = ((InterfaceDataTypeDouble)selected.getEAIndividual(k)).getDoubleData(); + double[] x_k = AbstractEAIndividual.getDoublePositionShallow(selected.getEAIndividual(k)); + newVal = params.mC.get(i, j) + ccv * (1 - 1. / mcv) + * params.weights[k] * (x_k[i] - params.meanX[i]) + * (x_k[j] - params.meanX[j]) / (getSigma(params, i) * getSigma(params, j)); // TODO right sigmas? + checkValidDouble(newVal); + params.mC.set(i, j, newVal); } + } } } // fill rest of C for (int i = 0; i < dim; ++i) { - for (int j = i+1; j < dim; ++j) { + for (int j = i + 1; j < dim; ++j) { - params.mC.set(i, j, params.mC.get(j,i)); + params.mC.set(i, j, params.mC.get(j, i)); } - + + } + if (params.mC.get(0, 1) != params.mC.get(1, 0)) { + System.err.println("WARNING, C is not symmetric!"); } - if (params.mC.get(0,1) != params.mC.get(1,0)) { - System.err.println("WARNING, C is not symmetric!"); - } // maxsqrtdiagC = Math.sqrt(math.max(math.diag(C))); // minsqrtdiagC = Math.sqrt(math.min(math.diag(C))); } // update of C - - } - public boolean isRankMu() { - return doRankMuUpdate ; - } - public void setRankMu(boolean rankUpd) { - doRankMuUpdate = rankUpd; - } - public String rankMuTipText() { - return "Choose between rank one and rank mu update."; - } - - /** - * Return true if v is a valid numeric value (not NaN and not Infinity), else false. - * - * @param v - * @return - */ - private boolean checkValidDouble(double v) { - boolean valid = !(Double.isNaN(v) || Double.isInfinite(v)); - if (!valid) { - System.err.println("Invalid double in rankMuCMA!"); - } - return valid; - } + } - private double getCCov(double[] weights, int mu, int dim) { - // ( HK03, sec. 2) + public boolean isRankMu() { + return doRankMuUpdate; + } + + public void setRankMu(boolean rankUpd) { + doRankMuUpdate = rankUpd; + } + + public String rankMuTipText() { + return "Choose between rank one and rank mu update."; + } + + /** + * Return true if v is a valid numeric value (not NaN and not Infinity), else false. + * + * @param v + * @return + */ + private boolean checkValidDouble(double v) { + boolean valid = !(Double.isNaN(v) || Double.isInfinite(v)); + if (!valid) { + System.err.println("Invalid double in rankMuCMA!"); + } + return valid; + } + + private double getCCov(double[] weights, int mu, int dim) { + // ( HK03, sec. 2) // return Math.min(1., 2*CMAParamSet.getMuEff(weights, mu)/(dim*dim)); - double muC=CMAParamSet.getMuCov(weights, mu); - double muE=CMAParamSet.getMuEff(weights,mu); - double ccov = (2./(muC*Math.pow(dim+Math.sqrt(2.), 2))) - + (1.-(1./muC)) * Math.min(1., (2*muE-1.)/(dim*dim+2*dim+4+muE)); - return ccov; - } - - private void outputParams(CMAParamSet params, int mu) { - System.out.println("sigma=" + params.sigma + " chiN="+expRandStepLen + " cs="+params.c_sig - + " damps="+params.d_sig + " Cc=" + getCc() + " Ccov=" + getCCov(params.weights, mu, params.meanX.length) - + " mueff=" + CMAParamSet.getMuEff(params.weights, mu) + " mucov="+CMAParamSet.getMuCov(params.weights, mu)); - } + double muC = CMAParamSet.getMuCov(weights, mu); + double muE = CMAParamSet.getMuEff(weights, mu); + double ccov = (2. / (muC * Math.pow(dim + Math.sqrt(2.), 2))) + + (1. - (1. / muC)) * Math.min(1., (2 * muE - 1.) / (dim * dim + 2 * dim + 4 + muE)); + return ccov; + } - private void updateBD(CMAParamSet params) { + private void outputParams(CMAParamSet params, int mu) { + System.out.println("sigma=" + params.sigma + " chiN=" + expRandStepLen + " cs=" + params.c_sig + + " damps=" + params.d_sig + " Cc=" + getCc() + " Ccov=" + getCCov(params.weights, mu, params.meanX.length) + + " mueff=" + CMAParamSet.getMuEff(params.weights, mu) + " mucov=" + CMAParamSet.getMuCov(params.weights, mu)); + } + + private void updateBD(CMAParamSet params) { // C=triu(C)+transpose(triu(C,1)); % enforce symmetry // [B,D] = eig(C); // % limit condition of C to 1e14 + 1 @@ -504,21 +507,21 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In // end // D = diag(sqrt(diag(D))); % D contains standard deviations now // BD = B*D; % for speed up only - ////////////////////////////////////////////7 - params.mC = (params.mC.plus(params.mC.transpose()).times(0.5)); // MAKE C SYMMETRIC + ////////////////////////////////////////////7 + params.mC = (params.mC.plus(params.mC.transpose()).times(0.5)); // MAKE C SYMMETRIC - EigenvalueDecomposition helper; + EigenvalueDecomposition helper; // this.m_Counter = 0; - helper = new EigenvalueDecomposition(params.mC); - params.mB = helper.getV(); // Return the eigenvector matrix - params.eigenvalues = helper.getRealEigenvalues(); - + helper = new EigenvalueDecomposition(params.mC); + params.mB = helper.getV(); // Return the eigenvector matrix + params.eigenvalues = helper.getRealEigenvalues(); + // double[] sqrtEig = eigenvalues.clone(); // for (int i = 0; i < sqrtEig.length; i++) { // sqrtEig[i] = Math.sqrt(eigenvalues[i]); // } // mB.times(sqrtEig, mBD); - + // Matrix test = (Matrix)mB.clone(); // System.out.println(test); // System.out.println(test.transpose()); @@ -533,40 +536,41 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In // System.out.println("eigenv: " + eigenvalues[spalte]); // System.out.println(BeanInspector.toString(mult)); // System.exit(1); - } + } - /** - * calculate weighted mean of the selected population - * @param selectedPop - * @return - */ - private double[] calcMeanX(double[] weights, Population selectedPop) { - return selectedPop.getCenterWeighted(weights); - } - - @Override - public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, - Population partners) { - // nothing to do - - } - - public String getName() { - return "Rank-Mu-CMA-Mutator"; - } + /** + * calculate weighted mean of the selected population + * + * @param selectedPop + * @return + */ + private double[] calcMeanX(double[] weights, Population selectedPop) { + return selectedPop.getCenterWeighted(weights); + } @Override - public String getStringRepresentation() { - return "Rank-Mu-CMA-Mutator"; - } + public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, + Population partners) { + // nothing to do + + } + + public String getName() { + return "Rank-Mu-CMA-Mutator"; + } - public static String globalInfo() { - return "The CMA mutator scheme with static cov. matrix, rank-mu update and weighted recombination."; - } - @Override - public void init(AbstractEAIndividual individual, - InterfaceOptimizationProblem opt) { + public String getStringRepresentation() { + return "Rank-Mu-CMA-Mutator"; + } + + public static String globalInfo() { + return "The CMA mutator scheme with static cov. matrix, rank-mu update and weighted recombination."; + } + + @Override + public void init(AbstractEAIndividual individual, + InterfaceOptimizationProblem opt) { // firstAdaptionDone = false; // range = ((InterfaceDataTypeDouble)individual).getDoubleRange(); // dim = range.length; @@ -586,320 +590,324 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In // mC = Matrix.identity(dim, dim); // mB = Matrix.identity(dim, dim); // sigma = 0.2; - // ^^^ moved to CMAParamSet initialization - double[][] range = ((InterfaceDataTypeDouble)individual).getDoubleRange(); - int dim = range.length; - c_c = (4./(dim+4)); - expRandStepLen = calcExpRandStepLen(dim); + // ^^^ moved to CMAParamSet initialization + double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange(); + int dim = range.length; + c_c = (4. / (dim + 4)); + expRandStepLen = calcExpRandStepLen(dim); - } + } @Override - public void mutate(AbstractEAIndividual individual) { + public void mutate(AbstractEAIndividual individual) { // if (!firstAdaptionDone) { // if (TRACE) System.out.println("No mutation before first adaptions step"); // return; // } - if (individual instanceof InterfaceDataTypeDouble) { - double[] x = ((InterfaceDataTypeDouble)individual).getDoubleData(); + if (individual instanceof InterfaceDataTypeDouble) { + double[] x = ((InterfaceDataTypeDouble) individual).getDoubleData(); // if (TRACE) System.out.println("WCMA mutate, bef: " + BeanInspector.toString(x)); - double[][] range = ((InterfaceDataTypeDouble)individual).getDoubleRange(); - - // this is a critical point: where do the CMA parameters for this individual's mutation come from? - // for GA and ES we can expect that selection occured directly before the mutation cycle, - // so we take the parameter set from the last adpation step. - ((InterfaceDataTypeDouble)individual).SetDoubleGenotype(mutate(lastParams, x, range, 0)); - -// if (TRACE) System.out.println("WCMA mutate, aft: " + BeanInspector.toString(x)); - } else { - System.err.println("Error, expecting InterfaceDataTypeDouble"); - } - } + double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange(); - private double[] mutate(CMAParamSet params, double[] x, double[][] range, int count) { - int dim = range.length; - if (!Mathematics.isInRange(params.meanX, range)) { // TODO Im not sure why this can happen... - System.err.println("Error in MutateESRankMuCMA.mutate !"); - Mathematics.projectToRange(params.meanX, range); - } + // this is a critical point: where do the CMA parameters for this individual's mutation come from? + // for GA and ES we can expect that selection occured directly before the mutation cycle, + // so we take the parameter set from the last adpation step. + ((InterfaceDataTypeDouble) individual).SetDoubleGenotype(mutate(lastParams, x, range, 0)); + +// if (TRACE) System.out.println("WCMA mutate, aft: " + BeanInspector.toString(x)); + } else { + System.err.println("Error, expecting InterfaceDataTypeDouble"); + } + } + + private double[] mutate(CMAParamSet params, double[] x, double[][] range, int count) { + int dim = range.length; + if (!Mathematics.isInRange(params.meanX, range)) { // TODO Im not sure why this can happen... + System.err.println("Error in MutateESRankMuCMA.mutate !"); + Mathematics.projectToRange(params.meanX, range); + } // System.out.println("--- In mutate!"); - if (params!=null && (params.firstAdaptionDone)) { - double[] sampl = new double[dim]; // generate scaled random vector (D * z) - for (int i = 0; i < dim; ++i) { - sampl[i] = Math.sqrt(params.eigenvalues[i]) * RNG.gaussianDouble(1.); - if (Double.isNaN(sampl[i])) { - sampl[i]=0; - } - } - // System.out.println("Sampling around " + BeanInspector.toString(meanX)); + if (params != null && (params.firstAdaptionDone)) { + double[] sampl = new double[dim]; // generate scaled random vector (D * z) + for (int i = 0; i < dim; ++i) { + sampl[i] = Math.sqrt(params.eigenvalues[i]) * RNG.gaussianDouble(1.); + if (Double.isNaN(sampl[i])) { + sampl[i] = 0; + } + } + // System.out.println("Sampling around " + BeanInspector.toString(meanX)); /* add mutation (sigma * B * (D*z)) */ - addMutationStep(params, x, sampl); - int cnt=0; - while (!Mathematics.isInRange(x, range)) { + addMutationStep(params, x, sampl); + int cnt = 0; + while (!Mathematics.isInRange(x, range)) { // % You may handle constraints here. You may either resample // % arz(:,k) and/or multiply it with a factor between -1 and 1 // % (the latter will decrease the overall step size) and // % recalculate arx accordingly. Do not change arx or arz in any // % other way. - // multiply sampl by a no in [-1,1] and try again - double r; // actually we use [-1,-0.5] or [0.5, 1] - cnt++; - if (cnt > 10*x.length) { - // well... lets give it up. Probably the meanX is close to the bounds in several dimensions - // which is unlikely to be solved by random sampling. + // multiply sampl by a no in [-1,1] and try again + double r; // actually we use [-1,-0.5] or [0.5, 1] + cnt++; + if (cnt > 10 * x.length) { + // well... lets give it up. Probably the meanX is close to the bounds in several dimensions + // which is unlikely to be solved by random sampling. // if (!Mathematics.isInRange(params.meanX, range)) { // System.err.println("Error in MutateESRankMuCMA.mutate !"); break; // } - r=0; - } else { - r=RNG.randomDouble(-0.5, 0.5); - if (Math.abs(r)<0.5) { - r+=Math.signum(r)*0.5; - } // r is in [-1,-0.5] or [0.5,1] - } + r = 0; + } else { + r = RNG.randomDouble(-0.5, 0.5); + if (Math.abs(r) < 0.5) { + r += Math.signum(r) * 0.5; + } // r is in [-1,-0.5] or [0.5,1] + } // System.out.println("Reducing step by " + r + " for " + BeanInspector.toString(params.meanX)); - Mathematics.svMult(r, sampl, sampl); - addMutationStep(params, x, sampl); - } - } else { - if (params==null) { - System.err.println("Error in MutateESRankMuCMA: parameter set was null! Skipping mutation..."); - } // no valid meanX yet, so just do a gaussian jump with sigma - for (int i = 0; i < dim; ++i) { - x[i] += RNG.gaussianDouble(getSigma(params, i)); - checkValidDouble(x[i]); - } - } - if (!Mathematics.isInRange(params.meanX, range)) { - System.err.println("Error B in MutateESRankMuCMA.mutate !"); - } - if (TRACE_1) { - System.out.println("mutated indy: " + BeanInspector.toString(x)); + Mathematics.svMult(r, sampl, sampl); + addMutationStep(params, x, sampl); } - return x; - } - - private void addMutationStep(CMAParamSet params, double[] x, double[] sampl) { + } else { + if (params == null) { + System.err.println("Error in MutateESRankMuCMA: parameter set was null! Skipping mutation..."); + } // no valid meanX yet, so just do a gaussian jump with sigma + for (int i = 0; i < dim; ++i) { + x[i] += RNG.gaussianDouble(getSigma(params, i)); + checkValidDouble(x[i]); + } + } + if (!Mathematics.isInRange(params.meanX, range)) { + System.err.println("Error B in MutateESRankMuCMA.mutate !"); + } + if (TRACE_1) { + System.out.println("mutated indy: " + BeanInspector.toString(x)); + } + return x; + } + + private void addMutationStep(CMAParamSet params, double[] x, double[] sampl) { /* add mutation (sigma * B * (D*z)) */ - for (int i = 0; i < x.length; ++i) { - double sum = 0.; - for (int j = 0; j < x.length; ++j) { - sum += params.mB.get(i,j) * sampl[j]; + for (int i = 0; i < x.length; ++i) { + double sum = 0.; + for (int j = 0; j < x.length; ++j) { + sum += params.mB.get(i, j) * sampl[j]; } - x[i] = params.meanX[i]+getSigma(params, i)*sum; - checkValidDouble(x[i]); - } - } + x[i] = params.meanX[i] + getSigma(params, i) * sum; + checkValidDouble(x[i]); + } + } - private double[] mutateOrig(CMAParamSet params, double[] x, double[][] range, int count) { - int dim = range.length; - int maxRetries; + private double[] mutateOrig(CMAParamSet params, double[] x, double[][] range, int count) { + int dim = range.length; + int maxRetries; - if (checkRange) { - maxRetries = 100*dim; - } - else { - maxRetries = 0; - } // take the first sample, not matter in or out of range - do { // this is a loop in case that the range needs to be checked and the current sampling fails to keep the range - if (params!=null && (params.firstAdaptionDone)) { - double[] sampl = new double[dim]; // generate scaled random vector (D * z) - for (int i = 0; i < dim; ++i) { - sampl[i] = Math.sqrt(params.eigenvalues[i]) * RNG.gaussianDouble(1.); - if (Double.isNaN(sampl[i])) { - sampl[i]=0; - } - } - // System.out.println("Sampling around " + BeanInspector.toString(meanX)); - /* add mutation (sigma * B * (D*z)) */ - for (int i = 0; i < dim; ++i) { - double sum = 0.; - for (int j = 0; j < dim; ++j) { - sum += params.mB.get(i,j) * sampl[j]; + if (checkRange) { + maxRetries = 100 * dim; + } else { + maxRetries = 0; + } // take the first sample, not matter in or out of range + do + { // this is a loop in case that the range needs to be checked and the current sampling fails to keep the range + if (params != null && (params.firstAdaptionDone)) { + double[] sampl = new double[dim]; // generate scaled random vector (D * z) + for (int i = 0; i < dim; ++i) { + sampl[i] = Math.sqrt(params.eigenvalues[i]) * RNG.gaussianDouble(1.); + if (Double.isNaN(sampl[i])) { + sampl[i] = 0; } - x[i] = params.meanX[i]+getSigma(params, i)*sum; - checkValidDouble(x[i]); - } - } else { - if (params==null) { - System.err.println("Error in MutateESRankMuCMA: parameter set was null! Skipping mutation..."); - } // no valid meanX yet, so just do a gaussian jump with sigma - for (int i = 0; i < dim; ++i) { - x[i] += RNG.gaussianDouble(getSigma(params, i)); - checkValidDouble(x[i]); - } - } - } while ((maxRetries--)>0 && !(Mathematics.isInRange(x, range))); - if (checkRange && !(Mathematics.isInRange(x, range))) { - return repairMutation(x, range); - } // allow some nice tries before using brute force - else { - return x; - } - } - - private double[] repairMutation(double[] x, double[][] range) { - EVAERROR.errorMsgOnce("Warning, brute-forcing constraints! Too large initial sigma? (pot. multiple errors)"); - Mathematics.projectToRange(x, range); - return x; - } - - /** - * After optimization start, this returns the initial sigma value - * actually employed. - * - * @return the initial sigma value actually employed - */ - public double getFirstSigma(Population pop) { - return ((CMAParamSet)pop.getData(cmaParamsKey)).firstSigma; - } - - public void hideHideable() { - this.setInitializeSigma(getInitializeSigma()); - } - - /** - * @return the initialSig - */ - public ESMutationInitialSigma getInitializeSigma() { - return initializeSig; - } - - /** - * @param initialSig the initialSig to set - */ - public void setInitializeSigma(ESMutationInitialSigma initialSig) { - this.initializeSig = initialSig; - GenericObjectEditor.setHideProperty(this.getClass(), "userDefInitSig", initialSig!=ESMutationInitialSigma.userDefined); - } - - public String initializeSigmaTipText() { - return "Method to use for setting the initial step size."; - } - - /** - * From Auger&Hansen, CEC '05, stopping criterion TolX. - * - * @param tolX - * @return - */ - public boolean testAllDistBelow(Population pop, double tolX) { -// if all(sigma*(max(abs(pc), sqrt(diag(C)))) < stopTolX) - boolean res = true; - CMAParamSet params = (CMAParamSet)pop.getData(cmaParamsKey); - int i=0; - while (res && i 0 && !(Mathematics.isInRange(x, range))); + if (checkRange && !(Mathematics.isInRange(x, range))) { + return repairMutation(x, range); + } // allow some nice tries before using brute force + else { + return x; + } + } - /** - * From Auger&Hansen, CEC '05, stopping criterion noeffectaxis. - * @param d - * @param gen - * @return - */ - public boolean testNoChangeAddingDevAxis(Population pop, double d, int gen) { + private double[] repairMutation(double[] x, double[][] range) { + EVAERROR.errorMsgOnce("Warning, brute-forcing constraints! Too large initial sigma? (pot. multiple errors)"); + Mathematics.projectToRange(x, range); + return x; + } + + /** + * After optimization start, this returns the initial sigma value + * actually employed. + * + * @return the initial sigma value actually employed + */ + public double getFirstSigma(Population pop) { + return ((CMAParamSet) pop.getData(cmaParamsKey)).firstSigma; + } + + public void hideHideable() { + this.setInitializeSigma(getInitializeSigma()); + } + + /** + * @return the initialSig + */ + public ESMutationInitialSigma getInitializeSigma() { + return initializeSig; + } + + /** + * @param initialSig the initialSig to set + */ + public void setInitializeSigma(ESMutationInitialSigma initialSig) { + this.initializeSig = initialSig; + GenericObjectEditor.setHideProperty(this.getClass(), "userDefInitSig", initialSig != ESMutationInitialSigma.userDefined); + } + + public String initializeSigmaTipText() { + return "Method to use for setting the initial step size."; + } + + /** + * From Auger&Hansen, CEC '05, stopping criterion TolX. + * + * @param tolX + * @return + */ + public boolean testAllDistBelow(Population pop, double tolX) { +// if all(sigma*(max(abs(pc), sqrt(diag(C)))) < stopTolX) + boolean res = true; + CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); + int i = 0; + while (res && i < params.meanX.length) { + res = res && (getSigma(params, i) * Math.max(Math.abs(params.pathC[i]), Math.sqrt(params.mC.get(i, i))) < tolX); + i++; + } + if (TRACE_TEST) { + if (res) { + System.out.println("testAllDistBelow hit"); + } + } + return res; + } + + /** + * From Auger&Hansen, CEC '05, stopping criterion noeffectaxis. + * + * @param d + * @param gen + * @return + */ + public boolean testNoChangeAddingDevAxis(Population pop, double d, int gen) { // if all(xmean == xmean + 0.1*sigma*BD(:,1+floor(mod(countiter,N)))) // i = 1+floor(mod(countiter,N)); // stopflag(end+1) = {'warnnoeffectaxis'}; - CMAParamSet params = (CMAParamSet)pop.getData(cmaParamsKey); - int dim=params.meanX.length; - int k = gen%dim; - double[] ev_k = params.mB.getColumn(k); - Mathematics.svMult(Math.sqrt(params.eigenvalues[k]), ev_k, ev_k); // this is now e_k*v_k = BD(:,...) - - int i=0; - boolean res = true; - while (res && (i= d. - * - * @param d - * @return true, if a diagonal entry is <= 0 or >= d, else false - */ - public boolean testCCondition(Population pop, double d) { + /** + * Test condition of C (Auger&Hansen, CEC '05, stopping criterion conditioncov). + * Return true, if a diagonal entry is <= 0 or >= d. + * + * @param d + * @return true, if a diagonal entry is <= 0 or >= d, else false + */ + public boolean testCCondition(Population pop, double d) { // if (min(diag(D)) <= 0) || (max(diag(D)) > 1e14*min(diag(D))) // stopflag(end+1) = {'warnconditioncov'}; - CMAParamSet params = (CMAParamSet)pop.getData(cmaParamsKey); - Pair minMax = params.mC.getMinMaxDiag(); - if ((minMax.head <= 0) || (minMax.tail >= d)) { - if (TRACE_TEST) { - System.out.println("testCCondition hit"); - } - return true; - } else { - return false; + CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); + Pair minMax = params.mC.getMinMaxDiag(); + if ((minMax.head <= 0) || (minMax.tail >= d)) { + if (TRACE_TEST) { + System.out.println("testCCondition hit"); } - } + return true; + } else { + return false; + } + } - /** - * @return the userDefInitSig - */ - public double getUserDefInitSig() { - return userDefInitSig; - } + /** + * @return the userDefInitSig + */ + public double getUserDefInitSig() { + return userDefInitSig; + } - /** - * @param userDefInitSig the userDefInitSig to set - */ - public void setUserDefInitSig(double userDefInitSig) { - this.userDefInitSig = userDefInitSig; - } - - public String userDefInitSigTipText() { - return "Set a manual initial sigma which should be related to the initial individual distribution."; - } + /** + * @param userDefInitSig the userDefInitSig to set + */ + public void setUserDefInitSig(double userDefInitSig) { + this.userDefInitSig = userDefInitSig; + } - public boolean isCheckRange() { - return checkRange; - } - public void setCheckRange(boolean checkRange) { - this.checkRange = checkRange; - } - public String checkRangeTipText() { - return "Force the operator to remain within the problem range."; - } + public String userDefInitSigTipText() { + return "Set a manual initial sigma which should be related to the initial individual distribution."; + } + + public boolean isCheckRange() { + return checkRange; + } + + public void setCheckRange(boolean checkRange) { + this.checkRange = checkRange; + } + + public String checkRangeTipText() { + return "Force the operator to remain within the problem range."; + } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/mutation/MutateESSuccessRule.java b/src/eva2/optimization/operator/mutation/MutateESSuccessRule.java index c860be41..ecf7c572 100644 --- a/src/eva2/optimization/operator/mutation/MutateESSuccessRule.java +++ b/src/eva2/optimization/operator/mutation/MutateESSuccessRule.java @@ -5,7 +5,7 @@ import eva2.optimization.population.Population; /** * Success rule implementation. - * + *

* User: streiche * Date: 10.05.2005 * Time: 14:11:49 @@ -16,19 +16,21 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf // no one could runs n independent ES runs in parallel anymore *sigh* // protected static double mutationStepSize = 0.2; // protected double mutationStepSize = 0.2; // now in base class - protected double m_SuccessRate = 0.2; - protected double m_Alpha = 1.2; + protected double m_SuccessRate = 0.2; + protected double m_Alpha = 1.2; public MutateESSuccessRule() { } - + public MutateESSuccessRule(MutateESSuccessRule mutator) { - super(mutator); - this.m_SuccessRate = mutator.m_SuccessRate; - this.m_Alpha = mutator.m_Alpha; + super(mutator); + this.m_SuccessRate = mutator.m_SuccessRate; + this.m_Alpha = mutator.m_Alpha; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -36,14 +38,16 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf return new MutateESSuccessRule(this); } - /** This method allows you to evaluate whether two mutation operators + /** + * This method allows you to evaluate whether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateESSuccessRule) { - MutateESSuccessRule mut = (MutateESSuccessRule)mutator; + MutateESSuccessRule mut = (MutateESSuccessRule) mutator; if (this.m_Sigma != mut.m_Sigma) { return false; } @@ -58,9 +62,11 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf return false; } } - - /** This method allows you to get a string representation of the mutation + + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -68,29 +74,37 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf return "ES 1/5 Success Rule mutation"; } - /** This method increases the mutation step size. + /** + * This method increases the mutation step size. */ public void increaseMutationStepSize() { this.m_Sigma *= this.m_Alpha; } - /** This method decrease the mutation step size. + + /** + * This method decrease the mutation step size. */ public void decreaseMutationStepSize() { this.m_Sigma /= this.m_Alpha; - } + } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override public String getName() { return "ES 1/5 Success Rule mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -101,8 +115,10 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf return "Choose the initial mutation step size."; } - /** Set success rate (0.2 is default). - * @param d The mutation operator. + /** + * Set success rate (0.2 is default). + * + * @param d The mutation operator. */ public void setSuccessRate(double d) { if (d < 0) { @@ -113,15 +129,19 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf } this.m_SuccessRate = d; } + public double getSuccessRate() { return this.m_SuccessRate; } + public String successRateTipText() { return "Set success rate (0.2 is default)."; } - /** Choose the factor by which the mutation step size is to be increased/decrease. - * @param d The mutation operator. + /** + * Choose the factor by which the mutation step size is to be increased/decrease. + * + * @param d The mutation operator. */ public void setAlpha(double d) { if (d < 1) { @@ -129,54 +149,56 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf } this.m_Alpha = d; } + public double getAlpha() { return this.m_Alpha; } + public String alphaTipText() { return "Choose the factor > 1 by which the mutation step size is to be increased/decreased."; } - + @Override public String sigmaTipText() { - return "The initial step size."; + return "The initial step size."; } @Override - public void adaptAfterSelection(Population oldGen, Population selected) { - // nothing to do here - } + public void adaptAfterSelection(Population oldGen, Population selected) { + // nothing to do here + } @Override - public void adaptGenerational(Population selectedPop, Population parentPop, Population newPop, boolean updateSelected) { - double rate = 0.; + public void adaptGenerational(Population selectedPop, Population parentPop, Population newPop, boolean updateSelected) { + double rate = 0.; for (int i = 0; i < parentPop.size(); i++) { - // calculate success rate + // calculate success rate // System.out.println("new fit / old fit: " + BeanInspector.toString(newPop.getEAIndividual(i).getFitness()) + " , " + BeanInspector.toString(parentPop.getEAIndividual(i).getFitness())); if (newPop.getEAIndividual(i).getFitness(0) < parentPop.getEAIndividual(i).getFitness(0)) { rate++; } } - rate /= parentPop.size(); - + rate /= parentPop.size(); + if (updateSelected) { - for (int i = 0; i < selectedPop.size(); i++) { // applied to the old population as well in case of plus strategy -MutateESSuccessRule mutator = (MutateESSuccessRule)((AbstractEAIndividual)selectedPop.get(i)).getMutationOperator(); -updateMutator(rate, mutator); + for (int i = 0; i < selectedPop.size(); i++) { // applied to the old population as well in case of plus strategy + MutateESSuccessRule mutator = (MutateESSuccessRule) ((AbstractEAIndividual) selectedPop.get(i)).getMutationOperator(); + updateMutator(rate, mutator); // System.out.println("old pop step size " + mutator.getSigma()+ " (" + mutator+ ")"); -} } + } + } for (int i = 0; i < newPop.size(); i++) { - MutateESSuccessRule mutator = (MutateESSuccessRule)((AbstractEAIndividual)newPop.get(i)).getMutationOperator(); + MutateESSuccessRule mutator = (MutateESSuccessRule) ((AbstractEAIndividual) newPop.get(i)).getMutationOperator(); updateMutator(rate, mutator); // System.out.println("new pop step size " + mutator.getSigma()+ " (" + mutator+ ")"); } - } + } - private void updateMutator(double rate, MutateESSuccessRule mutator) { + private void updateMutator(double rate, MutateESSuccessRule mutator) { if (rate < mutator.getSuccessRate()) { - mutator.decreaseMutationStepSize(); - } - else { - mutator.increaseMutationStepSize(); - } - } + mutator.decreaseMutationStepSize(); + } else { + mutator.increaseMutationStepSize(); + } + } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/mutation/MutateGAAdaptive.java b/src/eva2/optimization/operator/mutation/MutateGAAdaptive.java index dfde3ea5..b341c5a1 100644 --- a/src/eva2/optimization/operator/mutation/MutateGAAdaptive.java +++ b/src/eva2/optimization/operator/mutation/MutateGAAdaptive.java @@ -6,12 +6,13 @@ import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** * The mutation probability is adapted using a parameter tau and stored in the individual. * Better mutation probabilities are selected indirectly as they produce better offspring. - * + *

* Created by IntelliJ IDEA. * User: streiche * Date: 27.05.2003 @@ -19,36 +20,41 @@ import java.util.BitSet; * To change this template use Options | File Templates. */ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable { - - protected double m_MutationStep = 1; - protected double m_Tau1 = 0.15; - protected double m_LowerLimitStepSize = 0.0000005; + + protected double m_MutationStep = 1; + protected double m_Tau1 = 0.15; + protected double m_LowerLimitStepSize = 0.0000005; public MutateGAAdaptive() { } + public MutateGAAdaptive(MutateGAAdaptive mutator) { - this.m_MutationStep = mutator.m_MutationStep; - this.m_Tau1 = mutator.m_Tau1; - this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; + this.m_MutationStep = mutator.m_MutationStep; + this.m_Tau1 = mutator.m_Tau1; + this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override public Object clone() { return new MutateGAAdaptive(this); } - - /** This method allows you to evaluate wether two mutation operators + + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGAAdaptive) { - MutateGAAdaptive mut = (MutateGAAdaptive)mutator; + MutateGAAdaptive mut = (MutateGAAdaptive) mutator; if (this.m_MutationStep != mut.m_MutationStep) { return false; } @@ -64,50 +70,58 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceGAIndividual) { - BitSet tmpBitSet = ((InterfaceGAIndividual)individual).getBGenotype(); + BitSet tmpBitSet = ((InterfaceGAIndividual) individual).getBGenotype(); this.m_MutationStep *= Math.exp(this.m_Tau1 * RNG.gaussianDouble(1)); if (this.m_MutationStep < this.m_LowerLimitStepSize) { this.m_MutationStep = this.m_LowerLimitStepSize; } - for (int i = 0; i < ((InterfaceGAIndividual)individual).getGenotypeLength(); i++) { - if (RNG.flipCoin(this.m_MutationStep/((InterfaceGAIndividual)individual).getGenotypeLength())) { + for (int i = 0; i < ((InterfaceGAIndividual) individual).getGenotypeLength(); i++) { + if (RNG.flipCoin(this.m_MutationStep / ((InterfaceGAIndividual) individual).getGenotypeLength())) { tmpBitSet.flip(i); } } - ((InterfaceGAIndividual)individual).SetBGenotype(tmpBitSet); + ((InterfaceGAIndividual) individual).SetBGenotype(tmpBitSet); } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -118,22 +132,29 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GA adaptive mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The standard mutation switches n bits of the GA genotype."; } - /** Set the initial mutation step size with this method. - * @param d The mutation operator. + /** + * Set the initial mutation step size with this method. + * + * @param d The mutation operator. */ public void setMutationStep(double d) { if (d < 0) { @@ -141,15 +162,19 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable } this.m_MutationStep = d; } + public double getMutationStepSize() { return this.m_MutationStep; } + public String mutationStepSizeTipText() { return "Choose the initial mutation step size."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { if (d < 0) { @@ -157,15 +182,19 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable } this.m_LowerLimitStepSize = d; } + public double getLowerLimitStepSize() { return this.m_LowerLimitStepSize; } + public String lowerLimitStepSizeTipText() { return "Set the lower limit for the mutation step size."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setTau1(double d) { if (d < 0) { @@ -173,9 +202,11 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable } this.m_Tau1 = d; } + public double getTau1() { return this.m_Tau1; } + public String tau1TipText() { return "Set the value for tau1."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGAGISwapBits.java b/src/eva2/optimization/operator/mutation/MutateGAGISwapBits.java index ad6505fe..f1e6ddcf 100644 --- a/src/eva2/optimization/operator/mutation/MutateGAGISwapBits.java +++ b/src/eva2/optimization/operator/mutation/MutateGAGISwapBits.java @@ -6,6 +6,7 @@ import eva2.optimization.individuals.InterfaceGIIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** @@ -14,247 +15,270 @@ import java.util.BitSet; * individual length). * A range of number of par mutations can be given from which the actual number of pairs * is drawn in a uniform way. - * + *

* User: streiche, mkron * Date: 05.08.2004 * Time: 17:45:36 * To change this template use File | Settings | File Templates. */ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializable { - private int minNumMutations = 1; - private int maxNumMutations = 3; - private boolean preferTrueChange = true; // if true, pairs of (1,0) are swapped with higher probability + private int minNumMutations = 1; + private int maxNumMutations = 3; + private boolean preferTrueChange = true; // if true, pairs of (1,0) are swapped with higher probability - public MutateGAGISwapBits() { - } - - public MutateGAGISwapBits(MutateGAGISwapBits mutator) { - minNumMutations = mutator.minNumMutations; - maxNumMutations = mutator.maxNumMutations; - this.setPreferTrueChange(mutator.isPreferTrueChange()); - } + public MutateGAGISwapBits() { + } - public MutateGAGISwapBits(int minMutations, int maxMutations, boolean preferTrueChange) { - minNumMutations = minMutations; - maxNumMutations = maxMutations; - this.preferTrueChange = preferTrueChange; - } - - /** This method will enable you to clone a given mutation operator - * @return The clone - */ + public MutateGAGISwapBits(MutateGAGISwapBits mutator) { + minNumMutations = mutator.minNumMutations; + maxNumMutations = mutator.maxNumMutations; + this.setPreferTrueChange(mutator.isPreferTrueChange()); + } + + public MutateGAGISwapBits(int minMutations, int maxMutations, boolean preferTrueChange) { + minNumMutations = minMutations; + maxNumMutations = maxMutations; + this.preferTrueChange = preferTrueChange; + } + + /** + * This method will enable you to clone a given mutation operator + * + * @return The clone + */ @Override - public Object clone() { - return new MutateGAGISwapBits(this); - } + public Object clone() { + return new MutateGAGISwapBits(this); + } - /** This method allows you to evaluate wether two mutation operators - * are actually the same. - * @param mutator The other mutation operator - */ + /** + * This method allows you to evaluate wether two mutation operators + * are actually the same. + * + * @param mutator The other mutation operator + */ @Override - public boolean equals(Object mutator) { - if (mutator instanceof MutateGAGISwapBits) { - MutateGAGISwapBits mut = (MutateGAGISwapBits)mutator; - if (this.minNumMutations != mut.minNumMutations) { - return false; - } - if (this.maxNumMutations != mut.maxNumMutations) { - return false; - } - return true; - } else { + public boolean equals(Object mutator) { + if (mutator instanceof MutateGAGISwapBits) { + MutateGAGISwapBits mut = (MutateGAGISwapBits) mutator; + if (this.minNumMutations != mut.minNumMutations) { return false; } - } + if (this.maxNumMutations != mut.maxNumMutations) { + return false; + } + return true; + } else { + return false; + } + } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. - */ + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. + */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - } + } - /** This method allows you to perform either crossover on the strategy parameters - * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners - */ + /** + * This method allows you to perform either crossover on the strategy parameters + * or to deal in some other way with the crossover event. + * + * @param indy1 The original mother + * @param partners The original partners + */ @Override - public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { - // nothing to do here - } + public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { + // nothing to do here + } - /** This method will mutate a given AbstractEAIndividual. If the individual - * doesn't implement InterfaceGAIndividual or InterfaceGIIndividual nothing happens. - * @param individual The individual that is to be mutated - */ + /** + * This method will mutate a given AbstractEAIndividual. If the individual + * doesn't implement InterfaceGAIndividual or InterfaceGIIndividual nothing happens. + * + * @param individual The individual that is to be mutated + */ @Override - public void mutate(AbstractEAIndividual individual) { + public void mutate(AbstractEAIndividual individual) { // System.err.println("Before Mutate: " +(individual.getStringRepresentation())); - if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { - Object genotype = null; - int genoLen=-1; - if (individual instanceof InterfaceGAIndividual) { - genotype = ((InterfaceGAIndividual)individual).getBGenotype(); - genoLen = ((InterfaceGAIndividual)individual).getGenotypeLength(); - } else { - genotype = ((InterfaceGIIndividual)individual).getIGenotype(); - genoLen =((InterfaceGIIndividual)individual).getGenotypeLength(); - } - int[][] mutationIndices = selectMutationIndices(genoLen, genotype); + if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { + Object genotype = null; + int genoLen = -1; + if (individual instanceof InterfaceGAIndividual) { + genotype = ((InterfaceGAIndividual) individual).getBGenotype(); + genoLen = ((InterfaceGAIndividual) individual).getGenotypeLength(); + } else { + genotype = ((InterfaceGIIndividual) individual).getIGenotype(); + genoLen = ((InterfaceGIIndividual) individual).getGenotypeLength(); + } + int[][] mutationIndices = selectMutationIndices(genoLen, genotype); // System.err.println("Indices are " + BeanInspector.toString(mutationIndices)); - // double instances of mutationIndices could be checked here... *sigh* - for (int i = 0; i < mutationIndices.length; i++) { - Object tmp = valueAt(genotype, mutationIndices[i][1]); - setValueAt(genotype, mutationIndices[i][1], valueAt(genotype, mutationIndices[i][0])); - setValueAt(genotype, mutationIndices[i][0], tmp); + // double instances of mutationIndices could be checked here... *sigh* + for (int i = 0; i < mutationIndices.length; i++) { + Object tmp = valueAt(genotype, mutationIndices[i][1]); + setValueAt(genotype, mutationIndices[i][1], valueAt(genotype, mutationIndices[i][0])); + setValueAt(genotype, mutationIndices[i][0], tmp); // tmpBit = tmpBitSet.get(mutationIndices[i][1]); // tmpBitSet.set(mutationIndices[i][1], tmpBitSet.get(mutationIndices[i][0])); // tmpBitSet.set(mutationIndices[i][0], tmpBit); - } - if (genotype instanceof BitSet) { - ((InterfaceGAIndividual)individual).SetBGenotype((BitSet)genotype); - } - else { - ((InterfaceGIIndividual)individual).SetIGenotype((int[])genotype); - } - } + } + if (genotype instanceof BitSet) { + ((InterfaceGAIndividual) individual).SetBGenotype((BitSet) genotype); + } else { + ((InterfaceGIIndividual) individual).SetIGenotype((int[]) genotype); + } + } // System.err.println("After Mutate: " +(individual.getStringRepresentation())); - } + } - /** - * Select the mutation indices for the current mutation operation. - * - * @param genoLen - * @param genotype - * @return - */ - protected int[][] selectMutationIndices(int genoLen, Object genotype) { - int numMutes = RNG.randomInt(minNumMutations, maxNumMutations); - int[][] mutationIndices = new int[numMutes][2]; - for (int i = 0; i < mutationIndices.length; i++) { - mutationIndices[i][0] = getRandomIndex(genoLen, genotype, -1); // may prefer true bits - mutationIndices[i][1] = getRandomIndex(genoLen, genotype, mutationIndices[i][0]); // may prefer false bits - } - return mutationIndices; - } - - private void setValueAt(Object genotype, int i, Object val) { - if (genotype instanceof BitSet) { - ((BitSet)genotype).set(i, (Boolean)val); + /** + * Select the mutation indices for the current mutation operation. + * + * @param genoLen + * @param genotype + * @return + */ + protected int[][] selectMutationIndices(int genoLen, Object genotype) { + int numMutes = RNG.randomInt(minNumMutations, maxNumMutations); + int[][] mutationIndices = new int[numMutes][2]; + for (int i = 0; i < mutationIndices.length; i++) { + mutationIndices[i][0] = getRandomIndex(genoLen, genotype, -1); // may prefer true bits + mutationIndices[i][1] = getRandomIndex(genoLen, genotype, mutationIndices[i][0]); // may prefer false bits + } + return mutationIndices; + } + + private void setValueAt(Object genotype, int i, Object val) { + if (genotype instanceof BitSet) { + ((BitSet) genotype).set(i, (Boolean) val); + } else { + ((int[]) genotype)[i] = (Integer) val; + } + } + + protected int getRandomIndex(int genoLen, Object genotype, int lastIndex) { + return getRandomIndex(genoLen / 2, genotype, (lastIndex >= 0) ? (valueAt(genotype, lastIndex)) : null, 0, genoLen - 1); + } + + /** + * Select a random index within the given genotype lying in [iMin,iMax]. If applicable, the given + * value is avoided with certain probility, namely by trying to find a different value for maxTries + * times. + * + * @param maxTries + * @param genotype + * @param maybePreferedValue + * @param iMin + * @param iMax + * @return + */ + protected int getRandomIndex(int maxTries, Object genotype, Object avoidValue, int iMin, int iMax) { + int k = RNG.randomInt(iMin, iMax); + if (isPreferTrueChange() && avoidValue != null) { + while ((avoidValue == valueAt(genotype, k)) && (maxTries >= 0)) { + k = RNG.randomInt(iMin, iMax); // try next random position + maxTries--; } - else { - ((int[])genotype)[i]=(Integer)val; - } - } - - protected int getRandomIndex(int genoLen, Object genotype, int lastIndex) { - return getRandomIndex(genoLen/2, genotype, (lastIndex>=0) ? (valueAt(genotype, lastIndex)) : null, 0, genoLen-1); - } - - /** - * Select a random index within the given genotype lying in [iMin,iMax]. If applicable, the given - * value is avoided with certain probility, namely by trying to find a different value for maxTries - * times. - * - * @param maxTries - * @param genotype - * @param maybePreferedValue - * @param iMin - * @param iMax - * @return - */ - protected int getRandomIndex(int maxTries, Object genotype, Object avoidValue, int iMin, int iMax) { - int k = RNG.randomInt(iMin, iMax); - if (isPreferTrueChange() && avoidValue!=null) { - while ((avoidValue==valueAt(genotype, k)) && (maxTries>=0)) { - k = RNG.randomInt(iMin, iMax); // try next random position - maxTries--; - } - } - return k; - } + } + return k; + } // private int getRandomSecondIndex(int firstIndex, AbstractEAIndividual individual) { // int genoLen = ((InterfaceGAIndividual)individual).getGenotypeLength(); // return RNG.randomInt(0, genoLen); // } - protected Object valueAt(Object genotype, int k) { - if (genotype instanceof BitSet) { - return ((BitSet)genotype).get(k); - } - else { - return ((int[])genotype)[k]; - } - } - /** This method allows you to get a string representation of the mutation - * operator - * @return A descriptive string. - */ + protected Object valueAt(Object genotype, int k) { + if (genotype instanceof BitSet) { + return ((BitSet) genotype).get(k); + } else { + return ((int[]) genotype)[k]; + } + } + + /** + * This method allows you to get a string representation of the mutation + * operator + * + * @return A descriptive string. + */ @Override - public String getStringRepresentation() { - return "GA/GI swap values mutation"; - } + public String getStringRepresentation() { + return "GA/GI swap values mutation"; + } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the - * name to the current object. - * @return The name. - */ - public String getName() { - return "GA-GI swap bits mutation"; - } - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "This mutation operator swaps n random position pairs (bits or integers). The number of mutations is" + - " chosen uniformly in a given interval."; - } + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the + * name to the current object. + * + * @return The name. + */ + public String getName() { + return "GA-GI swap bits mutation"; + } - /** This method allows you to set the number of mutations that occur in the - * genotype. - * @param mutations The number of mutations. - */ - public void setMinNumberOfMutations(int mutations) { - if (mutations < 0) { - mutations = 0; - } - this.minNumMutations = mutations; - } - public int getMinNumberOfMutations() { - return this.minNumMutations; - } - public String minNumberOfMutationsTipText() { - return "The minimum number of values to be swapped."; - } - - public void setMaxNumberOfMutations(int mutations) { - if (mutations < 0) { - mutations = 0; - } - this.maxNumMutations = mutations; - } - public int getMaxNumberOfMutations() { - return this.maxNumMutations; - } - public String maxNumberOfMutationsTipText() { - return "The maximum number of values to be swapped."; - } - - public void setPreferTrueChange(boolean preferPairs) { - this.preferTrueChange = preferPairs; - } - public boolean isPreferTrueChange() { - return preferTrueChange; - } - public String preferTrueChangeTipText() { - return "If set to true, mutation events will prefer swapping non-equal values"; - } + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "This mutation operator swaps n random position pairs (bits or integers). The number of mutations is" + + " chosen uniformly in a given interval."; + } + + /** + * This method allows you to set the number of mutations that occur in the + * genotype. + * + * @param mutations The number of mutations. + */ + public void setMinNumberOfMutations(int mutations) { + if (mutations < 0) { + mutations = 0; + } + this.minNumMutations = mutations; + } + + public int getMinNumberOfMutations() { + return this.minNumMutations; + } + + public String minNumberOfMutationsTipText() { + return "The minimum number of values to be swapped."; + } + + public void setMaxNumberOfMutations(int mutations) { + if (mutations < 0) { + mutations = 0; + } + this.maxNumMutations = mutations; + } + + public int getMaxNumberOfMutations() { + return this.maxNumMutations; + } + + public String maxNumberOfMutationsTipText() { + return "The maximum number of values to be swapped."; + } + + public void setPreferTrueChange(boolean preferPairs) { + this.preferTrueChange = preferPairs; + } + + public boolean isPreferTrueChange() { + return preferTrueChange; + } + + public String preferTrueChangeTipText() { + return "If set to true, mutation events will prefer swapping non-equal values"; + } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/mutation/MutateGAGISwapBitsSegmentwise.java b/src/eva2/optimization/operator/mutation/MutateGAGISwapBitsSegmentwise.java index 2e8e9dc5..0e47947d 100644 --- a/src/eva2/optimization/operator/mutation/MutateGAGISwapBitsSegmentwise.java +++ b/src/eva2/optimization/operator/mutation/MutateGAGISwapBitsSegmentwise.java @@ -1,76 +1,78 @@ package eva2.optimization.operator.mutation; import eva2.tools.EVAERROR; + import java.io.Serializable; /** * This implementation restricts the swap positions of the standard swapping mutation * to swaps within subsequences (segments) of the genotype. The segments have a fixed length. - * - * @author mkron * + * @author mkron */ public class MutateGAGISwapBitsSegmentwise extends MutateGAGISwapBits implements Serializable { - private int segmentLength = 8; - - public MutateGAGISwapBitsSegmentwise() { - super(); - } + private int segmentLength = 8; - public MutateGAGISwapBitsSegmentwise(MutateGAGISwapBitsSegmentwise mutator) { - super(mutator); - segmentLength = mutator.segmentLength; - } + public MutateGAGISwapBitsSegmentwise() { + super(); + } + + public MutateGAGISwapBitsSegmentwise(MutateGAGISwapBitsSegmentwise mutator) { + super(mutator); + segmentLength = mutator.segmentLength; + } + + public MutateGAGISwapBitsSegmentwise(int segmentLength) { + this(); + this.segmentLength = segmentLength; + } + + public MutateGAGISwapBitsSegmentwise(int segmentLen, int minMutations, int maxMutations, boolean preferTrueChange) { + super(minMutations, maxMutations, preferTrueChange); + this.segmentLength = segmentLen; + } - public MutateGAGISwapBitsSegmentwise(int segmentLength) { - this(); - this.segmentLength = segmentLength; - } - - public MutateGAGISwapBitsSegmentwise(int segmentLen, int minMutations, int maxMutations, boolean preferTrueChange) { - super(minMutations, maxMutations, preferTrueChange); - this.segmentLength = segmentLen; - } - @Override - public Object clone() { - return new MutateGAGISwapBitsSegmentwise(this); - } - - public static String globalInfo() { - return "Segment-wise swapping of elements - the mutation pairs are selected within the same" + - " subsequence of the genotype."; - } - - @Override - public String getName() { - return "GA-GI swap bits segment-wise mutation"; - } - - @Override - protected int getRandomIndex(int genoLen, Object genotype, int lastIndex) { - // restrict to the same segment of lastIndex if >= 0. - int iMin=0, iMax=genoLen-1; // default bounds - if (lastIndex>=0) { - // select same segment - iMin = segmentLength * ((int)(lastIndex/segmentLength)); - iMax = iMin+segmentLength-1; - if (iMax>=genoLen) { - EVAERROR.errorMsgOnce("Warning, the last segment exceeds the genotype length (so it is not a multiple of the genotype length"); - iMax=genoLen-1; - } - } - return super.getRandomIndex(segmentLength/2, genotype, (lastIndex>=0) ? (valueAt(genotype, lastIndex)) : null, - iMin, iMax); - } + public Object clone() { + return new MutateGAGISwapBitsSegmentwise(this); + } - public int getSegmentLength() { - return segmentLength; - } - public void setSegmentLength(int segmentLength) { - this.segmentLength = segmentLength; - } - public String segmentLengthTipText() { - return "The length of subsequences to which mutations are restricted"; - } + public static String globalInfo() { + return "Segment-wise swapping of elements - the mutation pairs are selected within the same" + + " subsequence of the genotype."; + } + + @Override + public String getName() { + return "GA-GI swap bits segment-wise mutation"; + } + + @Override + protected int getRandomIndex(int genoLen, Object genotype, int lastIndex) { + // restrict to the same segment of lastIndex if >= 0. + int iMin = 0, iMax = genoLen - 1; // default bounds + if (lastIndex >= 0) { + // select same segment + iMin = segmentLength * ((int) (lastIndex / segmentLength)); + iMax = iMin + segmentLength - 1; + if (iMax >= genoLen) { + EVAERROR.errorMsgOnce("Warning, the last segment exceeds the genotype length (so it is not a multiple of the genotype length"); + iMax = genoLen - 1; + } + } + return super.getRandomIndex(segmentLength / 2, genotype, (lastIndex >= 0) ? (valueAt(genotype, lastIndex)) : null, + iMin, iMax); + } + + public int getSegmentLength() { + return segmentLength; + } + + public void setSegmentLength(int segmentLength) { + this.segmentLength = segmentLength; + } + + public String segmentLengthTipText() { + return "The length of subsequences to which mutations are restricted"; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateGAInvertBits.java b/src/eva2/optimization/operator/mutation/MutateGAInvertBits.java index 07c8407d..d7df14c1 100644 --- a/src/eva2/optimization/operator/mutation/MutateGAInvertBits.java +++ b/src/eva2/optimization/operator/mutation/MutateGAInvertBits.java @@ -5,10 +5,11 @@ import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** - * + * */ public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializable { @@ -59,7 +60,7 @@ public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializab * This method allows you to init the mutation operator * * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -77,8 +78,10 @@ public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializab BitSet tmpBitSet = ((InterfaceGAIndividual) individual).getBGenotype(); int[][] mutationIndices = new int[this.m_NumberOfMutations][2]; for (int i = 0; i < mutationIndices.length; i++) { - mutationIndices[i][0] = RNG.randomInt(0, ((InterfaceGAIndividual) individual).getGenotypeLength());; - mutationIndices[i][1] = RNG.randomInt(0, this.m_MaxInveredBits);; + mutationIndices[i][0] = RNG.randomInt(0, ((InterfaceGAIndividual) individual).getGenotypeLength()); + ; + mutationIndices[i][1] = RNG.randomInt(0, this.m_MaxInveredBits); + ; } // ToDo: double instances of mutationIndices could be checked here... *sigh* for (int i = 0; i < mutationIndices.length; i++) { @@ -95,7 +98,7 @@ public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializab * This method allows you to perform either crossover on the strategy * parameters or to deal in some other way with the crossover event. * - * @param indy1 The original mother + * @param indy1 The original mother * @param partners The original partners */ @Override @@ -117,7 +120,7 @@ public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializab /** * These are for GUI */ - + /** * This method allows the CommonJavaObjectEditorPanel to read the name to * the current object. diff --git a/src/eva2/optimization/operator/mutation/MutateGANBit.java b/src/eva2/optimization/operator/mutation/MutateGANBit.java index 2e052cce..4c7b93f2 100644 --- a/src/eva2/optimization/operator/mutation/MutateGANBit.java +++ b/src/eva2/optimization/operator/mutation/MutateGANBit.java @@ -5,10 +5,11 @@ import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** - * + * */ public class MutateGANBit implements InterfaceMutation, java.io.Serializable { @@ -54,7 +55,7 @@ public class MutateGANBit implements InterfaceMutation, java.io.Serializable { * This method allows you to init the mutation operator * * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -74,7 +75,8 @@ public class MutateGANBit implements InterfaceMutation, java.io.Serializable { int[] mutationIndices = new int[this.numberOfMutations]; for (int i = 0; i < mutationIndices.length; i++) { mutationIndices[i] = RNG.randomInt(0, ((InterfaceGAIndividual) individual).getGenotypeLength()); - }; + } + ; // double instances of mutationIndices could be checked here... *sigh* for (int i = 0; i < mutationIndices.length; i++) { tmpBitSet.flip(mutationIndices[i]); @@ -87,7 +89,7 @@ public class MutateGANBit implements InterfaceMutation, java.io.Serializable { * This method allows you to perform either crossover on the strategy * parameters or to deal in some other way with the crossover event. * - * @param indy1 The original mother + * @param indy1 The original mother * @param partners The original partners */ @Override @@ -103,7 +105,7 @@ public class MutateGANBit implements InterfaceMutation, java.io.Serializable { */ @Override public String getStringRepresentation() { - return "GA n-Bit mutation (n="+this.numberOfMutations+")"; + return "GA n-Bit mutation (n=" + this.numberOfMutations + ")"; } /** diff --git a/src/eva2/optimization/operator/mutation/MutateGAShiftSubstring.java b/src/eva2/optimization/operator/mutation/MutateGAShiftSubstring.java index 425571a9..d9512f49 100644 --- a/src/eva2/optimization/operator/mutation/MutateGAShiftSubstring.java +++ b/src/eva2/optimization/operator/mutation/MutateGAShiftSubstring.java @@ -6,44 +6,49 @@ import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** * Shift a certain substring within the individual. The length and shift distance * can be predefined or will be selected at random. The shift is performed cyclic. - * - * @author mkron * + * @author mkron */ public class MutateGAShiftSubstring implements InterfaceMutation, java.io.Serializable { - private int m_subStringLength = 0; - private int m_shiftDistance = 0; + private int m_subStringLength = 0; + private int m_shiftDistance = 0; - public MutateGAShiftSubstring() { + public MutateGAShiftSubstring() { - } - public MutateGAShiftSubstring(MutateGAShiftSubstring mutator) { - this.m_subStringLength = mutator.m_subStringLength; - this.m_shiftDistance = mutator.m_shiftDistance; - } + } - /** This method will enable you to clone a given mutation operator - * @return The clone - */ + public MutateGAShiftSubstring(MutateGAShiftSubstring mutator) { + this.m_subStringLength = mutator.m_subStringLength; + this.m_shiftDistance = mutator.m_shiftDistance; + } + + /** + * This method will enable you to clone a given mutation operator + * + * @return The clone + */ @Override - public Object clone() { - return new MutateGAShiftSubstring(this); - } - - /** This method allows you to evaluate wether two mutation operators + public Object clone() { + return new MutateGAShiftSubstring(this); + } + + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGAShiftSubstring) { - MutateGAShiftSubstring mut = (MutateGAShiftSubstring)mutator; + MutateGAShiftSubstring mut = (MutateGAShiftSubstring) mutator; if (this.m_subStringLength != mut.m_subStringLength) { return false; } @@ -56,118 +61,136 @@ public class MutateGAShiftSubstring implements InterfaceMutation, java.io.Serial } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - } + } - /** - * This method will mutate a given AbstractEAIndividual. If the individual - * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated - */ + /** + * This method will mutate a given AbstractEAIndividual. If the individual + * doesn't implement InterfaceGAIndividual nothing happens. + * + * @param individual The individual that is to be mutated + */ @Override - public void mutate(AbstractEAIndividual individual) { + public void mutate(AbstractEAIndividual individual) { // System.out.println("Before Mutate: " +(individual.getStringRepresentation())); - if (individual instanceof InterfaceGAIndividual) { - BitSet tmpBitSet = (BitSet)((InterfaceGAIndividual)individual).getBGenotype().clone(); - int len = ((InterfaceGAIndividual)individual).getGenotypeLength(); + if (individual instanceof InterfaceGAIndividual) { + BitSet tmpBitSet = (BitSet) ((InterfaceGAIndividual) individual).getBGenotype().clone(); + int len = ((InterfaceGAIndividual) individual).getGenotypeLength(); // System.out.println(tmpBitSet.cardinality()); - int[] substr = selectSubstring(tmpBitSet, len); - int a=substr[0]; - int b=substr[1]; - int d = selectShiftDist(len); + int[] substr = selectSubstring(tmpBitSet, len); + int a = substr[0]; + int b = substr[1]; + int d = selectShiftDist(len); // System.out.println("a, b, d: " + a + " " + b + " " + d); - for (int i = 0; i = s/2 times, where s is the binary - * segment length). - * Multiple mutations per segment can occur if the boolean switch is activated, meaning + * segment length). + * Multiple mutations per segment can occur if the boolean switch is activated, meaning * that further mutations are performed recursively with p_mut. Thus, the probability * to perform k mutations per segment is (p_mut)^k. However, more than s mutations per segment will * never be performed. - * + *

* User: mkron * Date: 05.08.2004 * Time: 17:45:36 * To change this template use File | Settings | File Templates. */ public class MutateGASwapBitsSegmentwise implements InterfaceMutation, java.io.Serializable { - private double mutationProbPerSegment = 0.7; - private boolean multiplesPerSegment = false; - private int segmentLength = 8; - private boolean preferPairs = true; // if true, pairs of (1,0) are swapped with higher probability + private double mutationProbPerSegment = 0.7; + private boolean multiplesPerSegment = false; + private int segmentLength = 8; + private boolean preferPairs = true; // if true, pairs of (1,0) are swapped with higher probability - public MutateGASwapBitsSegmentwise() { + public MutateGASwapBitsSegmentwise() { - } - public MutateGASwapBitsSegmentwise(MutateGASwapBitsSegmentwise mutator) { - this.mutationProbPerSegment = mutator.mutationProbPerSegment; - this.setPreferTrueChange(mutator.isPreferTrueChange()); - this.multiplesPerSegment = mutator.multiplesPerSegment; - this.segmentLength = mutator.segmentLength; - } + } - /** - * A constructor setting all properties. - * - * @param p_mut - * @param multPerSeg - * @param segmentLen - * @param prefPairs - */ - public MutateGASwapBitsSegmentwise(double p_mut, boolean multPerSeg, int segmentLen, boolean prefPairs) { - mutationProbPerSegment=p_mut; - multiplesPerSegment=multPerSeg; - segmentLength=segmentLen; - preferPairs=prefPairs; - } - - /** This method will enable you to clone a given mutation operator - * @return The clone - */ + public MutateGASwapBitsSegmentwise(MutateGASwapBitsSegmentwise mutator) { + this.mutationProbPerSegment = mutator.mutationProbPerSegment; + this.setPreferTrueChange(mutator.isPreferTrueChange()); + this.multiplesPerSegment = mutator.multiplesPerSegment; + this.segmentLength = mutator.segmentLength; + } + + /** + * A constructor setting all properties. + * + * @param p_mut + * @param multPerSeg + * @param segmentLen + * @param prefPairs + */ + public MutateGASwapBitsSegmentwise(double p_mut, boolean multPerSeg, int segmentLen, boolean prefPairs) { + mutationProbPerSegment = p_mut; + multiplesPerSegment = multPerSeg; + segmentLength = segmentLen; + preferPairs = prefPairs; + } + + /** + * This method will enable you to clone a given mutation operator + * + * @return The clone + */ @Override - public Object clone() { - return new MutateGASwapBitsSegmentwise(this); - } + public Object clone() { + return new MutateGASwapBitsSegmentwise(this); + } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGASwapBitsSegmentwise) { - MutateGASwapBitsSegmentwise mut = (MutateGASwapBitsSegmentwise)mutator; + MutateGASwapBitsSegmentwise mut = (MutateGASwapBitsSegmentwise) mutator; if (this.mutationProbPerSegment != mut.mutationProbPerSegment) { return false; } @@ -89,147 +95,167 @@ public class MutateGASwapBitsSegmentwise implements InterfaceMutation, java.io.S } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - } + } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method will mutate a given AbstractEAIndividual. If the individual - * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated - */ + /** + * This method will mutate a given AbstractEAIndividual. If the individual + * doesn't implement InterfaceGAIndividual nothing happens. + * + * @param individual The individual that is to be mutated + */ @Override - public void mutate(AbstractEAIndividual individual) { + public void mutate(AbstractEAIndividual individual) { // System.out.println("Before Mutate: " +(individual).getStringRepresentation()); - if (individual instanceof InterfaceGAIndividual) { - BitSet tmpBitSet = ((InterfaceGAIndividual)individual).getBGenotype(); - int genLen=((InterfaceGAIndividual)individual).getGenotypeLength(); - for (int i=0; igenLen) { // avoid to violate genotype length in a segment mutation - EVAERROR.errorMsgOnce("Warning, genotype length is not a multiple of the segment length.. ignoring last bits in " + this.getClass()); - break; - } - if (RNG.flipCoin(mutationProbPerSegment)) { - int cntMutes=0; - // swap bits within a segment within certain probability - do { // this may happen multiple times depending on the settings - swapBitsInSegmentAt(tmpBitSet, i, segmentLength); - cntMutes++; - // multiples only if the corresponding switch is true and another flipCoin succeeds. - // more than segmentLength mutations will never be performed per segment - } while(multiplesPerSegment && cntMutes genLen) { // avoid to violate genotype length in a segment mutation + EVAERROR.errorMsgOnce("Warning, genotype length is not a multiple of the segment length.. ignoring last bits in " + this.getClass()); + break; + } + if (RNG.flipCoin(mutationProbPerSegment)) { + int cntMutes = 0; + // swap bits within a segment within certain probability + do { // this may happen multiple times depending on the settings + swapBitsInSegmentAt(tmpBitSet, i, segmentLength); + cntMutes++; + // multiples only if the corresponding switch is true and another flipCoin succeeds. + // more than segmentLength mutations will never be performed per segment + } while (multiplesPerSegment && cntMutes < segmentLength && RNG.flipCoin(mutationProbPerSegment)); + } + } + ((InterfaceGAIndividual) individual).SetBGenotype(tmpBitSet); // write back the genotype + } // System.out.println("After Mutate: " +(individual).getStringRepresentation()); - } + } + + /** + * Swap one pair of bits within an indicated segment. + * + * @param tmpBitSet + * @param i + * @param segmentLength2 + */ + private void swapBitsInSegmentAt(BitSet bs, int i, int segLen) { + int indexOne = getRandomIndex(bs, i, segLen, true); // may prefer true bits + int indexTwo = getRandomIndex(bs, i, segLen, false); // may prefer false bits - /** - * Swap one pair of bits within an indicated segment. - * - * @param tmpBitSet - * @param i - * @param segmentLength2 - */ - private void swapBitsInSegmentAt(BitSet bs, int i, int segLen) { - int indexOne = getRandomIndex(bs, i, segLen, true); // may prefer true bits - int indexTwo = getRandomIndex(bs, i, segLen, false); // may prefer false bits - boolean tmpBit = bs.get(indexTwo); bs.set(indexTwo, bs.get(indexOne)); bs.set(indexOne, tmpBit); - } - - private int getRandomIndex(BitSet bs, int offset, int len, boolean maybePrefered) { - int k = RNG.randomInt(offset, offset+len-1); - if (isPreferTrueChange()) { - int maxTries=(1+len)/2; - while (!(maybePrefered==bs.get(k)) && (maxTries>=0)) { - k=RNG.randomInt(offset, offset+len-1); ; // try next random position - maxTries--; - } - } - return k; - } - + } + + private int getRandomIndex(BitSet bs, int offset, int len, boolean maybePrefered) { + int k = RNG.randomInt(offset, offset + len - 1); + if (isPreferTrueChange()) { + int maxTries = (1 + len) / 2; + while (!(maybePrefered == bs.get(k)) && (maxTries >= 0)) { + k = RNG.randomInt(offset, offset + len - 1); + ; // try next random position + maxTries--; + } + } + return k; + } + // private int getRandomSecondIndex(int firstIndex, AbstractEAIndividual individual) { // int genoLen = ((InterfaceGAIndividual)individual).getGenotypeLength(); // return RNG.randomInt(0, genoLen); // } - - /** This method allows you to get a string representation of the mutation - * operator - * @return A descriptive string. - */ + + /** + * This method allows you to get a string representation of the mutation + * operator + * + * @return A descriptive string. + */ @Override - public String getStringRepresentation() { - return "GA swap bits segment-wise mutation"; - } + public String getStringRepresentation() { + return "GA swap bits segment-wise mutation"; + } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the - * name to the current object. - * @return The name. - */ - public String getName() { - return "GA swap bits segment-wise mutation"; - } - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "This mutation operator swaps bits in subsegments of the genotype. Each segment is mutated" + - " with a certain probability. Depending on the setting, multiple mutations per segment may occur."; - } + /** + * This method allows the CommonJavaObjectEditorPanel to read the + * name to the current object. + * + * @return The name. + */ + public String getName() { + return "GA swap bits segment-wise mutation"; + } - public void setPreferTrueChange(boolean preferPairs) { - this.preferPairs = preferPairs; - } - public boolean isPreferTrueChange() { - return preferPairs; - } - public String preferTrueChangeTipText() { - return "If set to true, mutation events will prefer swapping 1 and 0"; - } - - public double getMutationProbPerSegment() { - return mutationProbPerSegment; - } - public void setMutationProbPerSegment(double mutationProbPerSegment) { - this.mutationProbPerSegment = mutationProbPerSegment; - } - - public boolean isMultiplesPerSegment() { - return multiplesPerSegment; - } - public void setMultiplesPerSegment(boolean multiplesPerSegment) { - this.multiplesPerSegment = multiplesPerSegment; - } - - public int getSegmentLength() { - return segmentLength; - } - public void setSegmentLength(int segmentLength) { - this.segmentLength = segmentLength; - } - public String segmentLengthTipText() { - return "The length of sub-segments to regard (substrings of the GA genotype)"; - } + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "This mutation operator swaps bits in subsegments of the genotype. Each segment is mutated" + + " with a certain probability. Depending on the setting, multiple mutations per segment may occur."; + } + + public void setPreferTrueChange(boolean preferPairs) { + this.preferPairs = preferPairs; + } + + public boolean isPreferTrueChange() { + return preferPairs; + } + + public String preferTrueChangeTipText() { + return "If set to true, mutation events will prefer swapping 1 and 0"; + } + + public double getMutationProbPerSegment() { + return mutationProbPerSegment; + } + + public void setMutationProbPerSegment(double mutationProbPerSegment) { + this.mutationProbPerSegment = mutationProbPerSegment; + } + + public boolean isMultiplesPerSegment() { + return multiplesPerSegment; + } + + public void setMultiplesPerSegment(boolean multiplesPerSegment) { + this.multiplesPerSegment = multiplesPerSegment; + } + + public int getSegmentLength() { + return segmentLength; + } + + public void setSegmentLength(int segmentLength) { + this.segmentLength = segmentLength; + } + + public String segmentLengthTipText() { + return "The length of sub-segments to regard (substrings of the GA genotype)"; + } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/mutation/MutateGAUniform.java b/src/eva2/optimization/operator/mutation/MutateGAUniform.java index eb424484..3c82efca 100644 --- a/src/eva2/optimization/operator/mutation/MutateGAUniform.java +++ b/src/eva2/optimization/operator/mutation/MutateGAUniform.java @@ -7,104 +7,109 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.RNG; + import java.io.Serializable; /** * Uniform mutation mutates every GA bit with a fixed probability. - * - * @author mkron * + * @author mkron */ public class MutateGAUniform implements InterfaceMutation, Serializable { - double bitwiseProb = 0.1; - private boolean useInvertedLength = true; - - public MutateGAUniform() {} - - public MutateGAUniform(MutateGAUniform o) { - setBitwiseProb(o.getBitwiseProb()); - } + double bitwiseProb = 0.1; + private boolean useInvertedLength = true; + + public MutateGAUniform() { + } + + public MutateGAUniform(MutateGAUniform o) { + setBitwiseProb(o.getBitwiseProb()); + } @Override - public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, - Population partners) { - if (indy1.getMutationOperator() instanceof MutateGAUniform) { - MutateGAUniform mute = (MutateGAUniform)indy1.getMutationOperator(); - double smallerProb, largerProb; - smallerProb = Math.min(getBitwiseProb(), mute.getBitwiseProb()); - largerProb = Math.max(getBitwiseProb(), mute.getBitwiseProb()); - setBitwiseProb(RNG.randomDouble(smallerProb, largerProb)); - } - } + public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, + Population partners) { + if (indy1.getMutationOperator() instanceof MutateGAUniform) { + MutateGAUniform mute = (MutateGAUniform) indy1.getMutationOperator(); + double smallerProb, largerProb; + smallerProb = Math.min(getBitwiseProb(), mute.getBitwiseProb()); + largerProb = Math.max(getBitwiseProb(), mute.getBitwiseProb()); + setBitwiseProb(RNG.randomDouble(smallerProb, largerProb)); + } + } @Override - public Object clone() { - return new MutateGAUniform(this); - } - - public void hideHideable() { - setUseInvertedLength(isUseInvertedLength()); - } - - @Override - public String getStringRepresentation() { - return "Uniform GA mutation (" + getBitwiseProb() + ")"; - } + public Object clone() { + return new MutateGAUniform(this); + } + + public void hideHideable() { + setUseInvertedLength(isUseInvertedLength()); + } @Override - public void init(AbstractEAIndividual individual, - InterfaceOptimizationProblem opt) { - if (useInvertedLength && (individual instanceof InterfaceGAIndividual)) { - setBitwiseProb(1./((double)((InterfaceGAIndividual)individual).getGenotypeLength())); - } - } + public String getStringRepresentation() { + return "Uniform GA mutation (" + getBitwiseProb() + ")"; + } - /** - * Flip every bit with a certain probability. - */ @Override - public void mutate(AbstractEAIndividual individual) { - if (individual instanceof InterfaceGAIndividual) { - InterfaceGAIndividual indy = (InterfaceGAIndividual)individual; - for (int i=0; i 1.)) { - System.err.println("Warning, probability should be within [0,1], given: " + bitwiseProb); - } - this.bitwiseProb = bitwiseProb; - } - public String bitwiseProbTipText() { - return "The probability of every bit to be flipped."; - } + public double getBitwiseProb() { + return bitwiseProb; + } - public void setUseInvertedLength(boolean useInvertedLength) { - this.useInvertedLength = useInvertedLength; - GenericObjectEditor.setHideProperty(this.getClass(), "bitwiseProb", useInvertedLength); - } - public boolean isUseInvertedLength() { - return useInvertedLength; - } - public String useInvertedLengthTipText() { - return "Switch for using 1/l as mutation rate."; - } - - public String getName() { - return "Uniform-GA-Mutation"; - } - - public static String globalInfo() { - return "Uniform mutation mutates every GA bit with a fixed probability."; - } + public void setBitwiseProb(double bitwiseProb) { + if (bitwiseProb < 0. && (bitwiseProb > 1.)) { + System.err.println("Warning, probability should be within [0,1], given: " + bitwiseProb); + } + this.bitwiseProb = bitwiseProb; + } + + public String bitwiseProbTipText() { + return "The probability of every bit to be flipped."; + } + + public void setUseInvertedLength(boolean useInvertedLength) { + this.useInvertedLength = useInvertedLength; + GenericObjectEditor.setHideProperty(this.getClass(), "bitwiseProb", useInvertedLength); + } + + public boolean isUseInvertedLength() { + return useInvertedLength; + } + + public String useInvertedLengthTipText() { + return "Switch for using 1/l as mutation rate."; + } + + public String getName() { + return "Uniform-GA-Mutation"; + } + + public static String globalInfo() { + return "Uniform mutation mutates every GA bit with a fixed probability."; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateGIInsertDelete.java b/src/eva2/optimization/operator/mutation/MutateGIInsertDelete.java index 8b59a53f..7516d70b 100644 --- a/src/eva2/optimization/operator/mutation/MutateGIInsertDelete.java +++ b/src/eva2/optimization/operator/mutation/MutateGIInsertDelete.java @@ -13,18 +13,21 @@ import eva2.tools.math.RNG; * Time: 17:33:46 * To change this template use File | Settings | File Templates. */ -public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializable { +public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializable { - int m_MaxLengthOfInsDel = 2; + int m_MaxLengthOfInsDel = 2; public MutateGIInsertDelete() { } + public MutateGIInsertDelete(MutateGIInsertDelete mutator) { - this.m_MaxLengthOfInsDel = mutator.m_MaxLengthOfInsDel; + this.m_MaxLengthOfInsDel = mutator.m_MaxLengthOfInsDel; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -32,111 +35,120 @@ public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializ return new MutateGIInsertDelete(); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGIInsertDelete) { - MutateGIInsertDelete mut = (MutateGIInsertDelete)mutator; + MutateGIInsertDelete mut = (MutateGIInsertDelete) mutator; if (this.m_MaxLengthOfInsDel != mut.m_MaxLengthOfInsDel) { return false; } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { if (individual instanceof InterfaceGIIndividual) { - int[] x = ((InterfaceGIIndividual)individual).getIGenotype(); - int[][] range = ((InterfaceGIIndividual)individual).getIntRange(); - int[] newX; - int[][] newRange; - int length, position; + int[] x = ((InterfaceGIIndividual) individual).getIGenotype(); + int[][] range = ((InterfaceGIIndividual) individual).getIntRange(); + int[] newX; + int[][] newRange; + int length, position; //this.pintInt("Before ", x); length = RNG.randomInt(1, this.m_MaxLengthOfInsDel); boolean insert = RNG.flipCoin(0.5); - if ((!insert) && (length >= x.length-1)) { + if ((!insert) && (length >= x.length - 1)) { insert = true; } if (insert) { // insert - position = RNG.randomInt(0, x.length-1); - newX = new int[x.length + length]; - newRange = new int[range.length + length][2]; + position = RNG.randomInt(0, x.length - 1); + newX = new int[x.length + length]; + newRange = new int[range.length + length][2]; for (int i = 0; i < position; i++) { - newX[i] = x[i]; - newRange[i] = range[i]; + newX[i] = x[i]; + newRange[i] = range[i]; } - for (int i = position; i < position+length; i++) { - newX[i] = RNG.randomInt(range[position][0], range[position][1]); - newRange[i][0] = range[position][0]; - newRange[i][1] = range[position][1]; + for (int i = position; i < position + length; i++) { + newX[i] = RNG.randomInt(range[position][0], range[position][1]); + newRange[i][0] = range[position][0]; + newRange[i][1] = range[position][1]; } for (int i = position; i < x.length; i++) { - newX[i+length] = x[i]; - newRange[i+length] = range[i]; + newX[i + length] = x[i]; + newRange[i + length] = range[i]; } } else { // delete - position = RNG.randomInt(0, x.length-1-length); - newX = new int[x.length - length]; - newRange = new int[range.length - length][2]; - if (newX.length <=1) { + position = RNG.randomInt(0, x.length - 1 - length); + newX = new int[x.length - length]; + newRange = new int[range.length - length][2]; + if (newX.length <= 1) { return; } for (int i = 0; i < position; i++) { - newX[i] = x[i]; - newRange[i] = range[i]; + newX[i] = x[i]; + newRange[i] = range[i]; } for (int i = position + length; i < x.length; i++) { - newX[i-length] = x[i]; - newRange[i-length] = range[i]; + newX[i - length] = x[i]; + newRange[i - length] = range[i]; } } if (newX.length <= 1) { System.out.println("newX " + newX.length); } - ((InterfaceGIIndividual)individual).setIntegerDataLength(newX.length); - ((InterfaceGIIndividual)individual).SetIGenotype(newX); - ((InterfaceGIIndividual)individual).SetIntRange(newRange); - newX = ((InterfaceGIIndividual)individual).getIGenotype(); + ((InterfaceGIIndividual) individual).setIntegerDataLength(newX.length); + ((InterfaceGIIndividual) individual).SetIGenotype(newX); + ((InterfaceGIIndividual) individual).SetIntRange(newRange); + newX = ((InterfaceGIIndividual) individual).getIGenotype(); if (newX.length <= 1) { System.out.println("newX " + newX.length); - } + } } } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -147,29 +159,38 @@ public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI insert/delete mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This mutation operator inserts or adds elements to the array."; } - /** This method allows you to set the max length of the insert or deletion. - * @param n The max length of invert + /** + * This method allows you to set the max length of the insert or deletion. + * + * @param n The max length of invert */ public void setMaxLengthOfInsDel(int n) { this.m_MaxLengthOfInsDel = n; } + public int getMaxLengthOfInsDel() { return this.m_MaxLengthOfInsDel; } + public String maxLengthOfInsDelTipText() { return "Gives the maximum length of an inserted or deleted segment."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGIInvert.java b/src/eva2/optimization/operator/mutation/MutateGIInvert.java index 71ccd5f5..05eb26bd 100644 --- a/src/eva2/optimization/operator/mutation/MutateGIInvert.java +++ b/src/eva2/optimization/operator/mutation/MutateGIInvert.java @@ -15,16 +15,19 @@ import eva2.tools.math.RNG; */ public class MutateGIInvert implements InterfaceMutation, java.io.Serializable { - int m_MaxLengthOfInvert = 2; + int m_MaxLengthOfInvert = 2; public MutateGIInvert() { } + public MutateGIInvert(MutateGIInvert mutator) { - this.m_MaxLengthOfInvert = mutator.m_MaxLengthOfInvert; + this.m_MaxLengthOfInvert = mutator.m_MaxLengthOfInvert; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -32,65 +35,72 @@ public class MutateGIInvert implements InterfaceMutation, java.io.Serializable { return new MutateGIInvert(); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGIInvert) { - MutateGIInvert mut = (MutateGIInvert)mutator; + MutateGIInvert mut = (MutateGIInvert) mutator; if (this.m_MaxLengthOfInvert != mut.m_MaxLengthOfInvert) { return false; } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { if (individual instanceof InterfaceGIIndividual) { - int[] x = ((InterfaceGIIndividual)individual).getIGenotype(); - int range, center, index = 0; + int[] x = ((InterfaceGIIndividual) individual).getIGenotype(); + int range, center, index = 0; //this.pintInt("Before ", x); range = RNG.randomInt(1, this.m_MaxLengthOfInvert); - if (2*range >= x.length) { + if (2 * range >= x.length) { return; } - center = RNG.randomInt(0+range, x.length-1-range); + center = RNG.randomInt(0 + range, x.length - 1 - range); //System.out.println("Range: " + range + " Center: " + center); int[] tmp = new int[x.length]; System.arraycopy(x, 0, tmp, 0, x.length); - for (int i = center-range; i < center+range; i++) { - x[center -1 + range - index] = tmp[i]; + for (int i = center - range; i < center + range; i++) { + x[center - 1 + range - index] = tmp[i]; index++; } //this.pintInt("After ", tmp); //this.pintInt("After ", x); - ((InterfaceGIIndividual)individual).SetIGenotype(x); + ((InterfaceGIIndividual) individual).SetIGenotype(x); } } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -98,15 +108,17 @@ public class MutateGIInvert implements InterfaceMutation, java.io.Serializable { } private void pintInt(String s, int[] x) { - String tmp = "{"+x[0]; + String tmp = "{" + x[0]; for (int i = 1; i < x.length; i++) { - tmp += ", "+x[i]; + tmp += ", " + x[i]; } - System.out.println(s+tmp+"}"); + System.out.println(s + tmp + "}"); } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -117,29 +129,38 @@ public class MutateGIInvert implements InterfaceMutation, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI invert mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The invert mutation inverts a segment of the int[]."; } - /** This method allows you to set the max length of invert. - * @param n The max length of invert + /** + * This method allows you to set the max length of invert. + * + * @param n The max length of invert */ public void setMaxLengthOfInvert(int n) { this.m_MaxLengthOfInvert = n; } + public int getMaxLengthOfInvert() { return this.m_MaxLengthOfInvert; } + public String maxLengthOfInvertTipText() { return "Gives half the maximum length of an inverted segment."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGINominal.java b/src/eva2/optimization/operator/mutation/MutateGINominal.java index b0c9913b..3a0d26fc 100644 --- a/src/eva2/optimization/operator/mutation/MutateGINominal.java +++ b/src/eva2/optimization/operator/mutation/MutateGINominal.java @@ -15,16 +15,19 @@ import eva2.tools.math.RNG; */ public class MutateGINominal implements InterfaceMutation, java.io.Serializable { - int m_NumberOfMutations = 2; + int m_NumberOfMutations = 2; public MutateGINominal() { } + public MutateGINominal(MutateGINominal mutator) { - this.m_NumberOfMutations = mutator.m_NumberOfMutations; + this.m_NumberOfMutations = mutator.m_NumberOfMutations; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -32,67 +35,76 @@ public class MutateGINominal implements InterfaceMutation, java.io.Serializable return new MutateGINominal(); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGINominal) { - MutateGINominal mut = (MutateGINominal)mutator; + MutateGINominal mut = (MutateGINominal) mutator; if (this.m_NumberOfMutations != mut.m_NumberOfMutations) { return false; } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { if (individual instanceof InterfaceGIIndividual) { - int[] x = ((InterfaceGIIndividual)individual).getIGenotype(); - int[][] range = ((InterfaceGIIndividual)individual).getIntRange(); - int mutInd = 0; + int[] x = ((InterfaceGIIndividual) individual).getIGenotype(); + int[][] range = ((InterfaceGIIndividual) individual).getIntRange(); + int mutInd = 0; for (int k = 0; k < this.m_NumberOfMutations; k++) { try { - mutInd = RNG.randomInt(0, x.length-1); + mutInd = RNG.randomInt(0, x.length - 1); } catch (java.lang.ArithmeticException e) { System.out.println("x.length " + x.length); } x[mutInd] = RNG.randomInt(range[mutInd][0], range[mutInd][1]); } - ((InterfaceGIIndividual)individual).SetIGenotype(x); + ((InterfaceGIIndividual) individual).SetIGenotype(x); } } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -103,29 +115,38 @@ public class MutateGINominal implements InterfaceMutation, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI nominal mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The nominal mutation alters n element of the int attributes completely at random."; } - /** This method allows you to set the number of mutations to occur. - * @param n The number of mutations + /** + * This method allows you to set the number of mutations to occur. + * + * @param n The number of mutations */ public void setNumberOfMutations(int n) { this.m_NumberOfMutations = n; } + public int getNumberOfMutations() { return this.m_NumberOfMutations; } + public String numberOfMutationsTipText() { return "Gives the number of mutations."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGIOrdinal.java b/src/eva2/optimization/operator/mutation/MutateGIOrdinal.java index b01a4482..c45be3e4 100644 --- a/src/eva2/optimization/operator/mutation/MutateGIOrdinal.java +++ b/src/eva2/optimization/operator/mutation/MutateGIOrdinal.java @@ -15,18 +15,21 @@ import eva2.tools.math.RNG; */ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable { - double m_StepSize = 0.1; - int m_NumberOfMutations = 2; + double m_StepSize = 0.1; + int m_NumberOfMutations = 2; public MutateGIOrdinal() { } + public MutateGIOrdinal(MutateGIOrdinal mutator) { - this.m_StepSize = mutator.m_StepSize; - this.m_NumberOfMutations = mutator.m_NumberOfMutations; + this.m_StepSize = mutator.m_StepSize; + this.m_NumberOfMutations = mutator.m_NumberOfMutations; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -34,14 +37,16 @@ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable return new MutateGIOrdinal(); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGIOrdinal) { - MutateGIOrdinal mut = (MutateGIOrdinal)mutator; + MutateGIOrdinal mut = (MutateGIOrdinal) mutator; if (this.m_StepSize != mut.m_StepSize) { return false; } @@ -49,42 +54,44 @@ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable return false; } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { if (individual instanceof InterfaceGIIndividual) { - int[] x = ((InterfaceGIIndividual)individual).getIGenotype(); - int[][] range = ((InterfaceGIIndividual)individual).getIntRange(); - int mutInd, mut; - double mutate; + int[] x = ((InterfaceGIIndividual) individual).getIGenotype(); + int[][] range = ((InterfaceGIIndividual) individual).getIntRange(); + int mutInd, mut; + double mutate; for (int k = 0; k < this.m_NumberOfMutations; k++) { - mutInd = RNG.randomInt(0, x.length-1); + mutInd = RNG.randomInt(0, x.length - 1); mutate = RNG.gaussianDouble(this.m_StepSize); mutate *= (range[mutInd][1] - range[mutInd][1]); - mut = (int)Math.round(mutate); + mut = (int) Math.round(mutate); if (mut == 0) { if (RNG.flipCoin(0.5)) { mut = -1; - } - else { + } else { mut = 1; } } @@ -96,22 +103,26 @@ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable x[mutInd] = range[mutInd][1]; } } - ((InterfaceGIIndividual)individual).SetIGenotype(x); + ((InterfaceGIIndividual) individual).SetIGenotype(x); } } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -122,42 +133,55 @@ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI ordinal mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The ordinal mutation alters n element of the int attributes based on an ordinal ordering."; } - /** This method allows you to set the mean step size. - * @param n The step size + /** + * This method allows you to set the mean step size. + * + * @param n The step size */ public void setStepSize(double n) { this.m_StepSize = n; } + public double getStepSize() { return this.m_StepSize; } + public String stepSizeTipText() { return "Gives the mean step size on a normalized search space."; } - /** This method allows you to set the number of mutations to occur. - * @param n The number of mutations + /** + * This method allows you to set the number of mutations to occur. + * + * @param n The number of mutations */ public void setNumberOfMutations(int n) { this.m_NumberOfMutations = n; } + public int getNumberOfMutations() { return this.m_NumberOfMutations; } + public String numberOfMutationsTipText() { return "Gives the number of mutations."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGISubset.java b/src/eva2/optimization/operator/mutation/MutateGISubset.java index 43a6c9ed..380ae596 100644 --- a/src/eva2/optimization/operator/mutation/MutateGISubset.java +++ b/src/eva2/optimization/operator/mutation/MutateGISubset.java @@ -7,166 +7,176 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.RNG; + import java.io.Serializable; /** * An integer mutation operator which switches elements within a given subset only. - * - * @author mkron * + * @author mkron */ public class MutateGISubset implements InterfaceMutation, Serializable { - private int[] mutableSet = new int[]{0,1}; - private int minNumMutations = 1; - private int maxNumMutations = 3; - private boolean enforceMutablePositions = true; - - public MutateGISubset() {} - - public MutateGISubset(MutateGISubset o) { - this.minNumMutations = o.minNumMutations; - this.maxNumMutations = o.maxNumMutations; - this.enforceMutablePositions = o.enforceMutablePositions; - if (o.mutableSet!=null) { - this.mutableSet=new int[o.mutableSet.length]; - System.arraycopy(o.mutableSet, 0, this.mutableSet, 0, o.mutableSet.length); - } - } - - public MutateGISubset(int[] muteSet, int minMutes, int maxMutes) { - setMutableSet(muteSet); - setMinNumMutations(minMutes); - setMaxNumMutations(maxMutes); - } - - @Override - public Object clone() { - return new MutateGISubset(this); - } - - @Override - public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, - Population partners) { - // nothing to do - } + private int[] mutableSet = new int[]{0, 1}; + private int minNumMutations = 1; + private int maxNumMutations = 3; + private boolean enforceMutablePositions = true; + + public MutateGISubset() { + } + + public MutateGISubset(MutateGISubset o) { + this.minNumMutations = o.minNumMutations; + this.maxNumMutations = o.maxNumMutations; + this.enforceMutablePositions = o.enforceMutablePositions; + if (o.mutableSet != null) { + this.mutableSet = new int[o.mutableSet.length]; + System.arraycopy(o.mutableSet, 0, this.mutableSet, 0, o.mutableSet.length); + } + } + + public MutateGISubset(int[] muteSet, int minMutes, int maxMutes) { + setMutableSet(muteSet); + setMinNumMutations(minMutes); + setMaxNumMutations(maxMutes); + } @Override - public String getStringRepresentation() { - return "GI subset mutation in " + BeanInspector.toString(mutableSet); - } + public Object clone() { + return new MutateGISubset(this); + } @Override - public void init(AbstractEAIndividual individual, - InterfaceOptimizationProblem opt) { - // nothing to do - - } + public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, + Population partners) { + // nothing to do + } @Override - public void mutate(AbstractEAIndividual individual) { - if (individual instanceof InterfaceGIIndividual) { - InterfaceGIIndividual giIndy = (InterfaceGIIndividual)individual; - int[] genotype = giIndy.getIGenotype(); - int[][] range = giIndy.getIntRange(); - int numMutes=RNG.randomInt(minNumMutations, maxNumMutations); - for (int i=0; i0 && (!isMutable(genotype[index]))); - } - if (isMutable(genotype[index])) { // if it is in the mutable subset - genotype[index]=randomValidElement(range, index, genotype[index]); - } - } + @Override + public void init(AbstractEAIndividual individual, + InterfaceOptimizationProblem opt) { + // nothing to do - /** - * Return a randomly chosen element of the mutable subset lying in the range - * or the old value if the randomly chosen value - * @param range - * @param index - * @param oldVal - * @return - */ - private int randomValidElement(int[][] range, int index, int oldVal) { - int v = mutableSet[RNG.randomInt(mutableSet.length)]; - if (v>=range[index][0] && (v<=range[index][1])) { - return v; + } + + @Override + public void mutate(AbstractEAIndividual individual) { + if (individual instanceof InterfaceGIIndividual) { + InterfaceGIIndividual giIndy = (InterfaceGIIndividual) individual; + int[] genotype = giIndy.getIGenotype(); + int[][] range = giIndy.getIntRange(); + int numMutes = RNG.randomInt(minNumMutations, maxNumMutations); + for (int i = 0; i < numMutes; i++) { + maybePerformSingleMutation(genotype, range, genotype.length / numMutes); } - else { - EVAERROR.errorMsgOnce("Warning, mutation subset violates range definition!"); - return oldVal; - } - } + } + } - /** - * Return true if the given value is member of the mutable subset, otherwise false. - * @param v - * @return - */ - private boolean isMutable(int v) { - for (int i=0; i 0 && (!isMutable(genotype[index]))); + } + if (isMutable(genotype[index])) { // if it is in the mutable subset + genotype[index] = randomValidElement(range, index, genotype[index]); + } + } - public static String globalInfo() { - return "A mutation operator which switches positions within a given subset only. A random " + - "position is chosen but mutated only if its allele is contained" + - " in the mutable set. The new allele is chosen from this set as well." + - " In case the random positions do not contain a mutable allele, the switching is skipped. " + - "This means that fewer switches may occur than expected from the minimal bound."; - } - - public int[] getMutableSet() { - return mutableSet; - } - public void setMutableSet(int[] mutationSubset) { - this.mutableSet = mutationSubset; - } - public String mutableSetTipText() { - return "A subset of integers among which mutations may occur."; - } + /** + * Return a randomly chosen element of the mutable subset lying in the range + * or the old value if the randomly chosen value + * + * @param range + * @param index + * @param oldVal + * @return + */ + private int randomValidElement(int[][] range, int index, int oldVal) { + int v = mutableSet[RNG.randomInt(mutableSet.length)]; + if (v >= range[index][0] && (v <= range[index][1])) { + return v; + } else { + EVAERROR.errorMsgOnce("Warning, mutation subset violates range definition!"); + return oldVal; + } + } - public int getMinNumMutations() { - return minNumMutations; - } - public void setMinNumMutations(int minNumMutations) { - this.minNumMutations = minNumMutations; - } - public String minNumMutationsTipText() { - return "A lower bound for the number of positions changed per mutation event"; - } - - public int getMaxNumMutations() { - return maxNumMutations; - } - public void setMaxNumMutations(int maxNumMutations) { - this.maxNumMutations = maxNumMutations; - } - public String maxNumMutationsTipText() { - return "An upper bound for the number of positions changed per mutation event"; - } + /** + * Return true if the given value is member of the mutable subset, otherwise false. + * + * @param v + * @return + */ + private boolean isMutable(int v) { + for (int i = 0; i < mutableSet.length; i++) { + if (mutableSet[i] == v) { + return true; + } + } + return false; + } - public boolean isEnforceMutablePositions() { - return enforceMutablePositions; - } - public void setEnforceMutablePositions(boolean enforceMutablePositions) { - this.enforceMutablePositions = enforceMutablePositions; - } - public String enforceMutablePositionsTipText() { - return "If true, the probability to hit a mutable position in a mutation event is increased by trying multiple times."; - } + public static String globalInfo() { + return "A mutation operator which switches positions within a given subset only. A random " + + "position is chosen but mutated only if its allele is contained" + + " in the mutable set. The new allele is chosen from this set as well." + + " In case the random positions do not contain a mutable allele, the switching is skipped. " + + "This means that fewer switches may occur than expected from the minimal bound."; + } + + public int[] getMutableSet() { + return mutableSet; + } + + public void setMutableSet(int[] mutationSubset) { + this.mutableSet = mutationSubset; + } + + public String mutableSetTipText() { + return "A subset of integers among which mutations may occur."; + } + + public int getMinNumMutations() { + return minNumMutations; + } + + public void setMinNumMutations(int minNumMutations) { + this.minNumMutations = minNumMutations; + } + + public String minNumMutationsTipText() { + return "A lower bound for the number of positions changed per mutation event"; + } + + public int getMaxNumMutations() { + return maxNumMutations; + } + + public void setMaxNumMutations(int maxNumMutations) { + this.maxNumMutations = maxNumMutations; + } + + public String maxNumMutationsTipText() { + return "An upper bound for the number of positions changed per mutation event"; + } + + public boolean isEnforceMutablePositions() { + return enforceMutablePositions; + } + + public void setEnforceMutablePositions(boolean enforceMutablePositions) { + this.enforceMutablePositions = enforceMutablePositions; + } + + public String enforceMutablePositionsTipText() { + return "If true, the probability to hit a mutable position in a mutation event is increased by trying multiple times."; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateGITranslocate.java b/src/eva2/optimization/operator/mutation/MutateGITranslocate.java index 1fff78cf..5f5c0fba 100644 --- a/src/eva2/optimization/operator/mutation/MutateGITranslocate.java +++ b/src/eva2/optimization/operator/mutation/MutateGITranslocate.java @@ -11,32 +11,35 @@ import eva2.tools.math.RNG; * Mutate an integer individual by shifting a connected subsequence within the genotype. The sequence * length is chosen uniformly randomly up to an upper limit. The destination position may either be * fully randomly or also limited to a maximal distance. - * + *

* User: mkron, streiche */ public class MutateGITranslocate implements InterfaceMutation, java.io.Serializable { - int m_MaxLengthOfTranslocate = 4; - int m_maxTransLocDistance = -1; + int m_MaxLengthOfTranslocate = 4; + int m_maxTransLocDistance = -1; + + public MutateGITranslocate() { + } - public MutateGITranslocate() {} - public MutateGITranslocate(int maxTranslLen) { - this(); - setMaxLengthOfTranslocate(maxTranslLen); - } - - public MutateGITranslocate(int maxTranslLen, int maxTransDist) { - this(); - setMaxLengthOfTranslocate(maxTranslLen); - setMaxTranslocationDist(maxTransDist); - } - - public MutateGITranslocate(MutateGITranslocate mutator) { - this.m_MaxLengthOfTranslocate = mutator.m_MaxLengthOfTranslocate; + this(); + setMaxLengthOfTranslocate(maxTranslLen); } - /** This method will enable you to clone a given mutation operator + public MutateGITranslocate(int maxTranslLen, int maxTransDist) { + this(); + setMaxLengthOfTranslocate(maxTranslLen); + setMaxTranslocationDist(maxTransDist); + } + + public MutateGITranslocate(MutateGITranslocate mutator) { + this.m_MaxLengthOfTranslocate = mutator.m_MaxLengthOfTranslocate; + } + + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -44,90 +47,96 @@ public class MutateGITranslocate implements InterfaceMutation, java.io.Serializa return new MutateGITranslocate(); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGITranslocate) { - MutateGITranslocate mut = (MutateGITranslocate)mutator; + MutateGITranslocate mut = (MutateGITranslocate) mutator; if (this.m_MaxLengthOfTranslocate != mut.m_MaxLengthOfTranslocate) { return false; } return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override - public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt){ + public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGIIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { - if (individual instanceof InterfaceGIIndividual) { - int[] x = ((InterfaceGIIndividual)individual).getIGenotype(); - int from, to, length; - length = RNG.randomInt(1, this.m_MaxLengthOfTranslocate); - if (x.length < length+2) { + if (individual instanceof InterfaceGIIndividual) { + int[] x = ((InterfaceGIIndividual) individual).getIGenotype(); + int from, to, length; + length = RNG.randomInt(1, this.m_MaxLengthOfTranslocate); + if (x.length < length + 2) { return; } - from = RNG.randomInt(0, x.length - 1 - length); - if (m_maxTransLocDistance<=0) { - to = RNG.randomInt(0, x.length - 1 - length); - } else { - int minTo = Math.max(0, from-m_maxTransLocDistance); - int maxTo = Math.min(x.length - 1 - length, from + m_maxTransLocDistance); + from = RNG.randomInt(0, x.length - 1 - length); + if (m_maxTransLocDistance <= 0) { + to = RNG.randomInt(0, x.length - 1 - length); + } else { + int minTo = Math.max(0, from - m_maxTransLocDistance); + int maxTo = Math.min(x.length - 1 - length, from + m_maxTransLocDistance); // System.out.println("min/max-to: " + minTo + ", " + maxTo); - to = RNG.randomInt(minTo, maxTo); + to = RNG.randomInt(minTo, maxTo); // System.out.println("to is " + to); - } -// this.printInt("####\nBefore ", x); - int[] tmp = new int[x.length]; - int[] without = new int[x.length - length]; - int[] insert = new int[length]; - for (int i = 0; i < length; i++) { - insert[i] = x[i+from]; } - for (int i = 0; i < without.length; i++) { - if (i < from) { - without[i] = x[i]; - } - else { - without[i] = x[i+length]; - } - } - for (int i = 0; i < to; i++) { - tmp[i] = without[i]; - } - for (int i = to; i < to+length; i++) { - tmp[i] = insert[i-to]; - } - for (int i = to+length; i < x.length; i++) { - tmp[i] = without[i-length]; - } +// this.printInt("####\nBefore ", x); + int[] tmp = new int[x.length]; + int[] without = new int[x.length - length]; + int[] insert = new int[length]; + for (int i = 0; i < length; i++) { + insert[i] = x[i + from]; + } + for (int i = 0; i < without.length; i++) { + if (i < from) { + without[i] = x[i]; + } else { + without[i] = x[i + length]; + } + } + for (int i = 0; i < to; i++) { + tmp[i] = without[i]; + } + for (int i = to; i < to + length; i++) { + tmp[i] = insert[i - to]; + } + for (int i = to + length; i < x.length; i++) { + tmp[i] = without[i - length]; + } // System.out.println(""+from+"/"+to+"/"+length); // this.printInt("After ", tmp); - ((InterfaceGIIndividual)individual).SetIGenotype(tmp); - } + ((InterfaceGIIndividual) individual).SetIGenotype(tmp); + } } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { @@ -149,9 +158,11 @@ public class MutateGITranslocate implements InterfaceMutation, java.io.Serializa // for (int i=1; i<100; i++) indy.mutate(); // System.out.println(indy.getStringRepresentation()); // } - - /** This method allows you to get a string representation of the mutation + + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -162,42 +173,55 @@ public class MutateGITranslocate implements InterfaceMutation, java.io.Serializa /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GI translocation mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This mutation translocates a segment of the int[]."; } - /** This method allows you to set the max length of invert. - * @param n The max length of invert + /** + * This method allows you to set the max length of invert. + * + * @param n The max length of invert */ public void setMaxLengthOfTranslocate(int n) { this.m_MaxLengthOfTranslocate = n; } + public int getMaxLengthOfTranslocate() { return this.m_MaxLengthOfTranslocate; } + public String maxLengthOfTranslocateTipText() { return "Gives the maximum length of the translocated segment."; } - - /** This method allows you to set the max length of invert. - * @param n The max length of invert + + /** + * This method allows you to set the max length of invert. + * + * @param n The max length of invert */ public void setMaxTranslocationDist(int n) { this.m_maxTransLocDistance = n; } + public int getMaxTranslocationDist() { return this.m_maxTransLocDistance; } + public String maxTranslocationDistTipText() { return "Gives the maximum distance by which a segment may be translocated."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGPAdaptive.java b/src/eva2/optimization/operator/mutation/MutateGPAdaptive.java index dcd6ed98..c1faa32d 100644 --- a/src/eva2/optimization/operator/mutation/MutateGPAdaptive.java +++ b/src/eva2/optimization/operator/mutation/MutateGPAdaptive.java @@ -16,37 +16,42 @@ import eva2.tools.math.RNG; * To change this template use Options | File Templates. */ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable { - protected double m_MutationStep = 1; - protected double m_Tau1 = 0.15; - protected double m_Tau2 = 0.15; - protected double m_LowerLimitStepSize = 0.0000005; + protected double m_MutationStep = 1; + protected double m_Tau1 = 0.15; + protected double m_Tau2 = 0.15; + protected double m_LowerLimitStepSize = 0.0000005; public MutateGPAdaptive() { } + public MutateGPAdaptive(MutateGPAdaptive mutator) { - this.m_MutationStep = mutator.m_MutationStep; - this.m_Tau1 = mutator.m_Tau1; - this.m_Tau2 = mutator.m_Tau2; - this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; + this.m_MutationStep = mutator.m_MutationStep; + this.m_Tau1 = mutator.m_Tau1; + this.m_Tau2 = mutator.m_Tau2; + this.m_LowerLimitStepSize = mutator.m_LowerLimitStepSize; } - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override public Object clone() { return new MutateGPAdaptive(this); - } + } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGPAdaptive) { - MutateGPAdaptive mut = (MutateGPAdaptive)mutator; + MutateGPAdaptive mut = (MutateGPAdaptive) mutator; if (this.m_MutationStep != mut.m_MutationStep) { return false; } @@ -65,18 +70,22 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { @@ -90,24 +99,28 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable this.m_MutationStep = 1; } if (RNG.flipCoin(this.m_MutationStep)) { - ((IndividualInterface)individual).defaultMutate(); + ((IndividualInterface) individual).defaultMutate(); } } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -118,22 +131,29 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GP adaptive mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This mutation replaces a random node with a new random subtree."; } - /** Set the initial mutation step size with this method. - * @param d The mutation operator. + /** + * Set the initial mutation step size with this method. + * + * @param d The mutation operator. */ public void setMutationStep(double d) { if (d < 0) { @@ -141,15 +161,19 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable } this.m_MutationStep = d; } + public double getMutationStepSize() { return this.m_MutationStep; } + public String mutationStepSizeTipText() { return "Choose the initial mutation step size."; } - /** Set the lower limit for the mutation step size with this method. - * @param d The mutation operator. + /** + * Set the lower limit for the mutation step size with this method. + * + * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { if (d < 0) { @@ -157,15 +181,19 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable } this.m_LowerLimitStepSize = d; } + public double getLowerLimitStepSize() { return this.m_LowerLimitStepSize; } + public String lowerLimitStepSizeTipText() { return "Set the lower limit for the mutation step size."; } - /** Set the value for tau1 with this method. - * @param d The mutation operator. + /** + * Set the value for tau1 with this method. + * + * @param d The mutation operator. */ public void setTau1(double d) { if (d < 0) { @@ -173,15 +201,19 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable } this.m_Tau1 = d; } + public double getTau1() { return this.m_Tau1; } + public String tau1TipText() { return "Set the value for tau1."; } - /** Set the value for tau2 with this method. - * @param d The mutation operator. + /** + * Set the value for tau2 with this method. + * + * @param d The mutation operator. */ public void setTau2(double d) { if (d < 0) { @@ -189,9 +221,11 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable } this.m_Tau2 = d; } + public double getTau2() { return this.m_Tau2; } + public String tau2TipText() { return "Set the value for tau2."; } diff --git a/src/eva2/optimization/operator/mutation/MutateGPSingleNode.java b/src/eva2/optimization/operator/mutation/MutateGPSingleNode.java index dd46e8ac..84f374fc 100644 --- a/src/eva2/optimization/operator/mutation/MutateGPSingleNode.java +++ b/src/eva2/optimization/operator/mutation/MutateGPSingleNode.java @@ -8,6 +8,7 @@ import eva2.optimization.individuals.codings.gp.GPArea; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.ArrayList; /** @@ -19,7 +20,9 @@ import java.util.ArrayList; */ public class MutateGPSingleNode implements InterfaceMutation, java.io.Serializable { - /** This method will enable you to clone a given mutation operator + /** + * This method will enable you to clone a given mutation operator + * * @return The clone */ @Override @@ -27,32 +30,37 @@ public class MutateGPSingleNode implements InterfaceMutation, java.io.Serializab return new MutateGPSingleNode(); } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateGPSingleNode) { return true; - } - else { + } else { return false; } } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + /** + * This method allows you to init the mutation operator + * + * @param individual The individual that will be mutated. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { } - /** This method will mutate a given AbstractEAIndividual. If the individual + /** + * This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ @Override public void mutate(AbstractEAIndividual individual) { @@ -60,25 +68,25 @@ public class MutateGPSingleNode implements InterfaceMutation, java.io.Serializab // System.out.println("Length: " +((InterfaceGPIndividual)individual).getPGenotype()[0].getNumberOfNodes()); if (individual instanceof InterfaceGPIndividual) { ArrayList allNodes = new ArrayList(); - AbstractGPNode[] programs = ((InterfaceGPIndividual)individual).getPGenotype(); - GPArea[] areas = (GPArea[])((InterfaceGPIndividual)individual).getFunctionArea(); + AbstractGPNode[] programs = ((InterfaceGPIndividual) individual).getPGenotype(); + GPArea[] areas = (GPArea[]) ((InterfaceGPIndividual) individual).getFunctionArea(); for (int i = 0; i < programs.length; i++) { programs[i].addNodesTo(allNodes); - AbstractGPNode nodeToMutate = (AbstractGPNode) allNodes.get(RNG.randomInt(0, allNodes.size()-1)); + AbstractGPNode nodeToMutate = (AbstractGPNode) allNodes.get(RNG.randomInt(0, allNodes.size() - 1)); int orgArity = nodeToMutate.getArity(); - AbstractGPNode newNode = (AbstractGPNode)areas[i].getRandomNodeWithArity(orgArity).clone(); + AbstractGPNode newNode = (AbstractGPNode) areas[i].getRandomNodeWithArity(orgArity).clone(); // System.out.println("OldNode "+ nodeToMutate.getName() + ":"+nodeToMutate.getArity() + " / NewNode "+newNode.getName() + ":"+newNode.getArity()); AbstractGPNode parent = nodeToMutate.getParent(); if (parent != null) { newNode.setParent(parent); } else { - ((InterfaceGPIndividual)individual).SetPGenotype(newNode, i); + ((InterfaceGPIndividual) individual).SetPGenotype(newNode, i); } // now reconnect the children newNode.initNodeArray(); for (int j = 0; j < nodeToMutate.getArity(); j++) { if (nodeToMutate.getNode(j) == null) { - System.out.println("j"+j); + System.out.println("j" + j); } newNode.setNode(nodeToMutate.getNode(j), j); } @@ -88,18 +96,22 @@ public class MutateGPSingleNode implements InterfaceMutation, java.io.Serializab // System.out.println("Length: " +((InterfaceGPIndividual)individual).getPGenotype()[0].getNumberOfNodes()); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -110,14 +122,19 @@ public class MutateGPSingleNode implements InterfaceMutation, java.io.Serializab /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "GP node mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/mutation/MutateOBGAFlip.java b/src/eva2/optimization/operator/mutation/MutateOBGAFlip.java index 998462be..c3b682ed 100644 --- a/src/eva2/optimization/operator/mutation/MutateOBGAFlip.java +++ b/src/eva2/optimization/operator/mutation/MutateOBGAFlip.java @@ -9,11 +9,11 @@ import eva2.tools.math.RNG; /** *

Title: EvA2

- * + *

*

Description:

- * + *

*

Copyright: Copyright (c) 2003

- * + *

*

Company:

* Mutates a permutation by flipping edges a given nubmer of times. * @@ -22,29 +22,30 @@ import eva2.tools.math.RNG; */ public class MutateOBGAFlip implements InterfaceMutation, java.io.Serializable { - /** - * times How many edges getting flipped by the mutation. - */ - int times = 2; + /** + * times How many edges getting flipped by the mutation. + */ + int times = 2; - public MutateOBGAFlip() { - } + public MutateOBGAFlip() { + } @Override - public Object clone() { - return this; - } + public Object clone() { + return this; + } - /** This method allows you to evaluate wether two mutation operators + /** + * This method allows you to evaluate wether two mutation operators * are actually the same. - * @param mutator The other mutation operator + * + * @param mutator The other mutation operator */ @Override public boolean equals(Object mutator) { if (mutator instanceof MutateOBGAFlip) { return true; - } - else { + } else { return false; } } @@ -57,32 +58,36 @@ public class MutateOBGAFlip implements InterfaceMutation, java.io.Serializable { @Override public void mutate(AbstractEAIndividual individual) { - int[][] perm = ( (InterfaceOBGAIndividual) individual). - getOBGenotype(); - for (int p = 0; p < perm.length; p++) { - for (int i = 0; i < times; i++) { - int p1 = RNG.randomInt(0, perm[p].length - 1); - int p2 = RNG.randomInt(0, perm[p].length - 1); - int temp = perm[p][p1]; - perm[p][p1] = perm[p][p2]; - perm[p][p2] = temp; - } - } - ( (InterfaceOBGAIndividual) individual).SetOBGenotype(perm); + int[][] perm = ((InterfaceOBGAIndividual) individual). + getOBGenotype(); + for (int p = 0; p < perm.length; p++) { + for (int i = 0; i < times; i++) { + int p1 = RNG.randomInt(0, perm[p].length - 1); + int p2 = RNG.randomInt(0, perm[p].length - 1); + int temp = perm[p][p1]; + perm[p][p1] = perm[p][p2]; + perm[p][p2] = temp; + } + } + ((InterfaceOBGAIndividual) individual).SetOBGenotype(perm); } - /** This method allows you to perform either crossover on the strategy parameters + /** + * This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. - * @param indy1 The original mother - * @param partners The original partners + * + * @param indy1 The original mother + * @param partners The original partners */ @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation + /** + * This method allows you to get a string representation of the mutation * operator + * * @return A descriptive string. */ @Override @@ -93,24 +98,31 @@ public class MutateOBGAFlip implements InterfaceMutation, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "OBGA flip mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This mutation operators flips edges of the OBGA."; } - public int getTimes() { - return times; - } - public void setTimes(int times) { - this.times = times; - } + + public int getTimes() { + return times; + } + + public void setTimes(int times) { + this.times = times; + } } diff --git a/src/eva2/optimization/operator/mutation/MutateOBGAInversion.java b/src/eva2/optimization/operator/mutation/MutateOBGAInversion.java index 44a9cd20..be8b3da5 100644 --- a/src/eva2/optimization/operator/mutation/MutateOBGAInversion.java +++ b/src/eva2/optimization/operator/mutation/MutateOBGAInversion.java @@ -13,28 +13,29 @@ import eva2.tools.math.RNG; *

Description:

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author planatsc * @version 1.0 -* -* Mutates a permutation by inversion a part of the permutation. -*

-* Example: -*
-*          1 2 | 3 4 5 | 6 7 8 9 ->
-*          1 2 | 5 4 3 | 6 7 8 9
-* 
+ *

+ * Mutates a permutation by inversion a part of the permutation. + *

+ * Example: + *

+ *                                              1 2 | 3 4 5 | 6 7 8 9 ->
+ *                                              1 2 | 5 4 3 | 6 7 8 9
+ *                                     
*/ public class MutateOBGAInversion implements java.io.Serializable, InterfaceMutation { - public MutateOBGAInversion() { - } + public MutateOBGAInversion() { + } @Override - public Object clone() { - return this; - } + public Object clone() { + return this; + } /** This method allows you to evaluate wether two mutation operators * are actually the same. @@ -44,30 +45,29 @@ public class MutateOBGAInversion implements java.io.Serializable, InterfaceMutat public boolean equals(Object mutator) { if (mutator instanceof MutateOBGAInversion) { return true; - } - else { + } else { return false; } } @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - //nothing to init - } + //nothing to init + } @Override - public void mutate(AbstractEAIndividual individual) { - int[][] permnew = (int[][]) ((InterfaceOBGAIndividual) individual). getOBGenotype().clone(); - int[][] perm = ((InterfaceDataTypePermutation) individual).getPermutationData(); - for (int p = 0; p < perm.length; p++) { - int p1 = RNG.randomInt(0, perm[p].length - 1); - int p2 = RNG.randomInt(p1, perm[p].length - 1); - for (int i = 0; i <= (p2-p1); i++) { - permnew[p][p1+i] = perm[p][p2-i]; - } + public void mutate(AbstractEAIndividual individual) { + int[][] permnew = (int[][]) ((InterfaceOBGAIndividual) individual).getOBGenotype().clone(); + int[][] perm = ((InterfaceDataTypePermutation) individual).getPermutationData(); + for (int p = 0; p < perm.length; p++) { + int p1 = RNG.randomInt(0, perm[p].length - 1); + int p2 = RNG.randomInt(p1, perm[p].length - 1); + for (int i = 0; i <= (p2 - p1); i++) { + permnew[p][p1 + i] = perm[p][p2 - i]; + } + } + ((InterfaceOBGAIndividual) individual).SetOBGenotype(permnew); } - ( (InterfaceOBGAIndividual) individual).SetOBGenotype(permnew); - } /** This method allows you to perform either crossover on the strategy parameters * or to deal in some other way with the crossover event. @@ -98,6 +98,7 @@ public class MutateOBGAInversion implements java.io.Serializable, InterfaceMutat public String getName() { return "OBGA inversion mutation"; } + /** This method returns a global info string * @return description */ diff --git a/src/eva2/optimization/operator/mutation/NoMutation.java b/src/eva2/optimization/operator/mutation/NoMutation.java index ec06ef1b..def3add1 100644 --- a/src/eva2/optimization/operator/mutation/NoMutation.java +++ b/src/eva2/optimization/operator/mutation/NoMutation.java @@ -43,7 +43,7 @@ public class NoMutation implements InterfaceMutation, java.io.Serializable { * This method allows you to init the mutation operator * * @param individual The individual that will be mutated. - * @param opt The optimization problem. + * @param opt The optimization problem. */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { @@ -63,7 +63,7 @@ public class NoMutation implements InterfaceMutation, java.io.Serializable { * This method allows you to perform either crossover on the strategy * parameters or to deal in some other way with the crossover event. * - * @param indy1 The original mother + * @param indy1 The original mother * @param partners The original partners */ @Override diff --git a/src/eva2/optimization/operator/mutation/PropertyMutationMixer.java b/src/eva2/optimization/operator/mutation/PropertyMutationMixer.java index a6ad8ce5..9ed3ad58 100644 --- a/src/eva2/optimization/operator/mutation/PropertyMutationMixer.java +++ b/src/eva2/optimization/operator/mutation/PropertyMutationMixer.java @@ -9,38 +9,38 @@ package eva2.optimization.operator.mutation; */ public class PropertyMutationMixer implements java.io.Serializable { - public InterfaceMutation[] m_AvailableTargets; - public InterfaceMutation[] m_SelectedTargets; - public double[] m_Weights; - public String m_DescriptiveString = "No Description given."; - public String m_WeightsLabel = "-"; - public boolean m_NormalizationEnabled = true; + public InterfaceMutation[] m_AvailableTargets; + public InterfaceMutation[] m_SelectedTargets; + public double[] m_Weights; + public String m_DescriptiveString = "No Description given."; + public String m_WeightsLabel = "-"; + public boolean m_NormalizationEnabled = true; public PropertyMutationMixer(InterfaceMutation[] d, boolean selectAllOrNone) { this.m_Weights = new double[d.length]; for (int i = 0; i < d.length; i++) { - this.m_Weights[i] = 1/((double)d.length); + this.m_Weights[i] = 1 / ((double) d.length); } this.m_AvailableTargets = d; if (selectAllOrNone) { - this.m_SelectedTargets = d.clone(); - } - else { + this.m_SelectedTargets = d.clone(); + } else { this.m_SelectedTargets = null; } } + public PropertyMutationMixer(PropertyMutationMixer d) { - this.m_DescriptiveString = d.m_DescriptiveString; - this.m_WeightsLabel = d.m_WeightsLabel; - this.m_NormalizationEnabled = d.m_NormalizationEnabled; - this.m_AvailableTargets = new InterfaceMutation[d.m_AvailableTargets.length]; + this.m_DescriptiveString = d.m_DescriptiveString; + this.m_WeightsLabel = d.m_WeightsLabel; + this.m_NormalizationEnabled = d.m_NormalizationEnabled; + this.m_AvailableTargets = new InterfaceMutation[d.m_AvailableTargets.length]; for (int i = 0; i < this.m_AvailableTargets.length; i++) { //this.m_AvailableTargets[i] = (InterfaceMutation)d.m_AvailableTargets[i].clone(); - this.m_AvailableTargets[i] = d.m_AvailableTargets[i]; + this.m_AvailableTargets[i] = d.m_AvailableTargets[i]; } - this.m_SelectedTargets = new InterfaceMutation[d.m_SelectedTargets.length]; + this.m_SelectedTargets = new InterfaceMutation[d.m_SelectedTargets.length]; for (int i = 0; i < this.m_SelectedTargets.length; i++) { - this.m_SelectedTargets[i] = (InterfaceMutation)d.m_SelectedTargets[i].clone(); + this.m_SelectedTargets[i] = (InterfaceMutation) d.m_SelectedTargets[i].clone(); } if (d.m_Weights != null) { this.m_Weights = new double[d.m_Weights.length]; @@ -53,8 +53,10 @@ public class PropertyMutationMixer implements java.io.Serializable { return (Object) new PropertyMutationMixer(this); } - /** This method will allow you to set the value of the InterfaceOptimizationTarget array - * @param d The InterfaceOptimizationTarget[] + /** + * This method will allow you to set the value of the InterfaceOptimizationTarget array + * + * @param d The InterfaceOptimizationTarget[] */ public void setSelectedMutators(InterfaceMutation[] d) { this.m_SelectedTargets = d; @@ -62,7 +64,7 @@ public class PropertyMutationMixer implements java.io.Serializable { if (this.m_Weights == null) { this.m_Weights = new double[d.length]; for (int i = 0; i < this.m_Weights.length; i++) { - this.m_Weights[i] = 1/((double)d.length); + this.m_Weights[i] = 1 / ((double) d.length); } return; } @@ -86,26 +88,33 @@ public class PropertyMutationMixer implements java.io.Serializable { } } - /** This method will return the InterfaceOptimizationTarget array + /** + * This method will return the InterfaceOptimizationTarget array + * * @return The InterfaceOptimizationTarget[]. */ public InterfaceMutation[] getSelectedMutators() { return this.m_SelectedTargets; } - /** This method will return the InterfaceOptimizationTarget array + /** + * This method will return the InterfaceOptimizationTarget array + * * @return The InterfaceOptimizationTarget[]. */ public InterfaceMutation[] getAvailableMutators() { return this.m_AvailableTargets; } - /** This method allows you to read the weights + /** + * This method allows you to read the weights + * * @return the weights */ public double[] getWeights() { return this.m_Weights; } + public void setWeights(double[] d) { this.m_Weights = d; for (int i = 0; i < this.m_Weights.length; i++) { @@ -113,22 +122,28 @@ public class PropertyMutationMixer implements java.io.Serializable { } } - /** This method allows you to set/get the descriptive string + /** + * This method allows you to set/get the descriptive string + * * @return the string */ public String getDescriptiveString() { return this.m_DescriptiveString; } + public void setDescriptiveString(String d) { this.m_DescriptiveString = d; } - /** This method allows you to set/get the weights label + /** + * This method allows you to set/get the weights label + * * @return the string */ public String getWeigthsLabel() { return this.m_WeightsLabel; } + public void setWeightsLabel(String d) { this.m_WeightsLabel = d; } @@ -145,16 +160,18 @@ public class PropertyMutationMixer implements java.io.Serializable { } } - /** This method allows you to remove a Target from the list - * @param index The index of the target to be removed. + /** + * This method allows you to remove a Target from the list + * + * @param index The index of the target to be removed. */ public void removeMutator(int index) { if ((index < 0) || (index >= this.m_SelectedTargets.length)) { return; } - InterfaceMutation[] newList = new InterfaceMutation[this.m_SelectedTargets.length-1]; - double[] newWeights = new double[this.m_Weights.length - 1]; + InterfaceMutation[] newList = new InterfaceMutation[this.m_SelectedTargets.length - 1]; + double[] newWeights = new double[this.m_Weights.length - 1]; int j = 0; for (int i = 0; i < this.m_SelectedTargets.length; i++) { if (index != i) { @@ -163,23 +180,25 @@ public class PropertyMutationMixer implements java.io.Serializable { j++; } } - this.m_SelectedTargets = newList; - this.m_Weights = newWeights; + this.m_SelectedTargets = newList; + this.m_Weights = newWeights; } - /** This method allows you to add a new target to the list + /** + * This method allows you to add a new target to the list + * * @param optTarget */ public void addMutator(InterfaceMutation optTarget) { - InterfaceMutation[] newList = new InterfaceMutation[this.m_SelectedTargets.length+1]; - double[] newWeights = new double[this.m_Weights.length + 1]; + InterfaceMutation[] newList = new InterfaceMutation[this.m_SelectedTargets.length + 1]; + double[] newWeights = new double[this.m_Weights.length + 1]; for (int i = 0; i < this.m_SelectedTargets.length; i++) { newList[i] = this.m_SelectedTargets[i]; newWeights[i] = this.m_Weights[i]; } newList[this.m_SelectedTargets.length] = optTarget; newWeights[this.m_SelectedTargets.length] = 1.0; - this.m_SelectedTargets = newList; - this.m_Weights = newWeights; + this.m_SelectedTargets = newList; + this.m_Weights = newWeights; } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/mutation/PropertyMutationMixerEditor.java b/src/eva2/optimization/operator/mutation/PropertyMutationMixerEditor.java index 9bf3c87c..f1874f22 100644 --- a/src/eva2/optimization/operator/mutation/PropertyMutationMixerEditor.java +++ b/src/eva2/optimization/operator/mutation/PropertyMutationMixerEditor.java @@ -6,6 +6,7 @@ import eva2.optimization.tools.AbstractObjectEditor; import eva2.optimization.tools.GeneralGEOFaker; import eva2.optimization.tools.GeneralGOEProperty; import eva2.tools.BasicResourceLoader; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -23,29 +24,38 @@ import javax.swing.*; */ public class PropertyMutationMixerEditor extends JPanel implements PropertyEditor, java.beans.PropertyChangeListener { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The FilePath that is to be edited*/ - private PropertyMutationMixer m_MutatorsWithWeights; + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The FilePath that is to be edited + */ + private PropertyMutationMixer m_MutatorsWithWeights; - /** The gaphix stuff */ - private JComponent m_Editor; - private JPanel m_TargetList; - private JTextField[] m_Weights; - private JComponent[] m_Targets; - private JButton[] m_Delete; - private JScrollPane m_ScrollTargets; - private GeneralGOEProperty[] m_Editors; - private GeneralGEOFaker m_Component; - private PropertyChangeListener m_self; + /** + * The gaphix stuff + */ + private JComponent m_Editor; + private JPanel m_TargetList; + private JTextField[] m_Weights; + private JComponent[] m_Targets; + private JButton[] m_Delete; + private JScrollPane m_ScrollTargets; + private GeneralGOEProperty[] m_Editors; + private GeneralGEOFaker m_Component; + private PropertyChangeListener m_self; public PropertyMutationMixerEditor() { m_self = this; } - /** This method will init the CustomEditor Panel + /** + * This method will init the CustomEditor Panel */ private void initCustomEditor() { m_self = this; @@ -54,14 +64,14 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito this.m_Editor.setMinimumSize(new Dimension(450, 200)); // init the editors - InterfaceMutation[] list = this.m_MutatorsWithWeights.getSelectedMutators(); + InterfaceMutation[] list = this.m_MutatorsWithWeights.getSelectedMutators(); this.m_Editors = new GeneralGOEProperty[list.length]; for (int i = 0; i < list.length; i++) { this.m_Editors[i] = new GeneralGOEProperty(); - this.m_Editors[i].m_Name = list[i].getStringRepresentation(); + this.m_Editors[i].m_Name = list[i].getStringRepresentation(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceMutation.class); } @@ -79,17 +89,17 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } } this.m_TargetList = new JPanel(); - this.updateTargetList(); + this.updateTargetList(); this.m_ScrollTargets = new JScrollPane(this.m_TargetList); this.m_Editor.setLayout(new BorderLayout()); this.m_Editor.add(this.m_ScrollTargets, BorderLayout.CENTER); // The Button Panel - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new GridLayout(1,2)); - JButton addButton = new JButton("Add Mutator"); - JButton normButton = new JButton("Normalize Propabilities"); + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new GridLayout(1, 2)); + JButton addButton = new JButton("Add Mutator"); + JButton normButton = new JButton("Normalize Propabilities"); normButton.setEnabled(true); normButton.addActionListener(normalizeWeights); addButton.addActionListener(addTarget); @@ -99,89 +109,89 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito this.m_Editor.add(buttonPanel, BorderLayout.SOUTH); // Some description would be nice - JTextArea jt = new JTextArea(); - jt.setFont(new Font("SansSerif", Font.PLAIN,12)); - jt.setEditable(false); - jt.setLineWrap(true); - jt.setWrapStyleWord(true); - jt.setText(this.m_MutatorsWithWeights.getDescriptiveString()); + JTextArea jt = new JTextArea(); + jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); + jt.setEditable(false); + jt.setLineWrap(true); + jt.setWrapStyleWord(true); + jt.setText(this.m_MutatorsWithWeights.getDescriptiveString()); jt.setBackground(getBackground()); - JPanel jp = new JPanel(); - jp.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Info"), - BorderFactory.createEmptyBorder(0, 5, 5, 5) - )); - jp.setLayout(new BorderLayout()); - jp.add(jt, BorderLayout.CENTER); - JPanel p2 = new JPanel(); + JPanel jp = new JPanel(); + jp.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createTitledBorder("Info"), + BorderFactory.createEmptyBorder(0, 5, 5, 5) + )); + jp.setLayout(new BorderLayout()); + jp.add(jt, BorderLayout.CENTER); + JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); JButton help = new JButton("Help"); help.setEnabled(false); p2.add(help, BorderLayout.NORTH); jp.add(p2, BorderLayout.EAST); - GridBagConstraints gbConstraints = new GridBagConstraints(); + GridBagConstraints gbConstraints = new GridBagConstraints(); this.m_Editor.add(jp, BorderLayout.NORTH); this.updateEditor(); } - /** This method updates the server list - * + /** + * This method updates the server list */ private void updateTargetList() { - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes; - InterfaceMutation[] list = this.m_MutatorsWithWeights.getSelectedMutators(); - double[] weights = this.m_MutatorsWithWeights.getWeights(); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes; + InterfaceMutation[] list = this.m_MutatorsWithWeights.getSelectedMutators(); + double[] weights = this.m_MutatorsWithWeights.getWeights(); this.m_TargetList.removeAll(); this.m_TargetList.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); - this.m_Weights = new JTextField[list.length]; - this.m_Targets = new JComponent[list.length]; - this.m_Delete = new JButton[list.length]; - String[] cups = new String[8]; + this.m_Weights = new JTextField[list.length]; + this.m_Targets = new JComponent[list.length]; + this.m_Delete = new JButton[list.length]; + String[] cups = new String[8]; for (int i = 0; i < cups.length; i++) { - cups[i] = ""+(i+1); + cups[i] = "" + (i + 1); } // The head title - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 2; this.m_TargetList.add(new JLabel(this.m_MutatorsWithWeights.getWeigthsLabel()), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.weightx = 10; this.m_TargetList.add(new JLabel("Target"), gbc); - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 2; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 2; + gbc.weightx = 1; this.m_TargetList.add(new JLabel("Remove"), gbc); for (int i = 0; i < list.length; i++) { // the weight - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 0; - gbc.weightx = 2; - this.m_Weights[i] = new JTextField(""+weights[i]); + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.weightx = 2; + this.m_Weights[i] = new JTextField("" + weights[i]); this.m_Weights[i].addKeyListener(this.readDoubleArrayAction); this.m_TargetList.add(this.m_Weights[i], gbc); // the status indicator - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.BOTH; - gbc.gridx = 1; - gbc.weightx = 10; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 1; + gbc.weightx = 10; this.m_Targets[i] = this.m_Editors[i].m_View; this.m_TargetList.add(this.m_Targets[i], gbc); // The delete button - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.REMAINDER; - gbc.gridx = 2; - gbc.weightx = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.REMAINDER; + gbc.gridx = 2; + gbc.weightx = 1; bytes = loader.getBytesFromResourceLocation("images/Sub24.gif", true); this.m_Delete[i] = new JButton("", new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); this.m_Delete[i].addActionListener(deleteTarget); @@ -199,7 +209,8 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } } - /** This action listener,... + /** + * This action listener,... */ ActionListener updateTargets = new ActionListener() { @Override @@ -208,12 +219,13 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener addTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - m_MutatorsWithWeights.addMutator((InterfaceMutation)m_MutatorsWithWeights.getAvailableMutators()[0].clone()); + m_MutatorsWithWeights.addMutator((InterfaceMutation) m_MutatorsWithWeights.getAvailableMutators()[0].clone()); int l = m_MutatorsWithWeights.getSelectedMutators().length; GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l]; for (int i = 0; i < m_Editors.length; i++) { @@ -221,11 +233,11 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } InterfaceMutation[] list = m_MutatorsWithWeights.getSelectedMutators(); l--; - newEdit[l] = new GeneralGOEProperty(); - newEdit[l].m_Name = list[l].getStringRepresentation(); + newEdit[l] = new GeneralGOEProperty(); + newEdit[l].m_Name = list[l].getStringRepresentation(); try { - newEdit[l].m_Value = list[l]; - newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); + newEdit[l].m_Value = list[l]; + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(newEdit[l].m_Value.getClass()); if (newEdit[l].m_Editor == null) { newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceMutation.class); } @@ -246,18 +258,18 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener deleteTarget = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int l = m_MutatorsWithWeights.getSelectedMutators().length, j = 0; - GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l-1]; + GeneralGOEProperty[] newEdit = new GeneralGOEProperty[l - 1]; for (int i = 0; i < m_Delete.length; i++) { if (event.getSource().equals(m_Delete[i])) { m_MutatorsWithWeights.removeMutator(i); - } - else { + } else { newEdit[j] = m_Editors[i]; j++; } @@ -267,7 +279,8 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } }; - /** This action listener,... + /** + * This action listener,... */ ActionListener normalizeWeights = new ActionListener() { @Override @@ -277,19 +290,21 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } }; - /** This action listener reads all values + /** + * This action listener reads all values */ KeyListener readDoubleArrayAction = new KeyListener() { @Override public void keyPressed(KeyEvent event) { } + @Override public void keyTyped(KeyEvent event) { } @Override public void keyReleased(KeyEvent event) { - double[] newW = m_MutatorsWithWeights.getWeights(); + double[] newW = m_MutatorsWithWeights.getWeights(); for (int i = 0; i < newW.length; i++) { try { @@ -301,10 +316,11 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } m_MutatorsWithWeights.setWeights(newW); - } + } }; - /** The object may have changed update the editor. + /** + * The object may have changed update the editor. */ private void updateEditor() { if (this.m_Editor != null) { @@ -317,18 +333,22 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito } } - /** This method will set the value of object that is to be edited. + /** + * This method will set the value of object that is to be edited. + * * @param o an object that must be an array. */ @Override public void setValue(Object o) { if (o instanceof PropertyMutationMixer) { - this.m_MutatorsWithWeights= (PropertyMutationMixer) o; + this.m_MutatorsWithWeights = (PropertyMutationMixer) o; this.updateEditor(); } } - /** Returns the current object. + /** + * Returns the current object. + * * @return the current object */ @Override @@ -365,21 +385,27 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito return null; } - /** This is used to hook an action listener to the ok button + /** + * This is used to hook an action listener to the ok button + * * @param a The action listener. */ public void addOkListener(ActionListener a) { //m_OKButton.addActionListener(a); } - /** This is used to remove an action listener from the ok button + /** + * This is used to remove an action listener from the ok button + * * @param a The action listener */ public void removeOkListener(ActionListener a) { //m_OKButton.removeActionListener(a); } - /** Returns true since the Object can be shown + /** + * Returns true since the Object can be shown + * * @return true */ @Override @@ -387,7 +413,8 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito return true; } - /** Paints a representation of the current classifier. + /** + * Paints a representation of the current classifier. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into @@ -397,30 +424,35 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getAscent()) / 2; String rep = "Mixed Mutators"; - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); } - /** Returns true because we do support a custom editor. - * @return true - */ + /** + * Returns true because we do support a custom editor. + * + * @return true + */ @Override public boolean supportsCustomEditor() { return true; } - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override public Component getCustomEditor() { if (this.m_Component == null) { this.initCustomEditor(); - this.m_Component = new GeneralGEOFaker((PropertyEditor)this, (JPanel)this.m_Editor); + this.m_Component = new GeneralGEOFaker((PropertyEditor) this, (JPanel) this.m_Editor); } return this.m_Component; } - /** This method will udate the status of the object taking the values from all + /** + * This method will udate the status of the object taking the values from all * supsequent editors and setting them to my object. */ public void updateCenterComponent(PropertyChangeEvent evt) { @@ -428,7 +460,9 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito this.updateEditor(); } - /********************************* java.beans.PropertyChangeListener *************************/ + /** + * ****************************** java.beans.PropertyChangeListener ************************ + */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { @@ -439,22 +473,25 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito public void removePropertyChangeListener(PropertyChangeListener l) { m_Support.removePropertyChangeListener(l); } - /** This will wait for the GenericObjectEditor to finish + + /** + * This will wait for the GenericObjectEditor to finish * editing an object. + * * @param evt */ @Override - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(PropertyChangeEvent evt) { Object newVal = evt.getNewValue(); Object oldVal = evt.getOldValue(); InterfaceMutation[] list = this.m_MutatorsWithWeights.getSelectedMutators(); for (int i = 0; i < list.length; i++) { if (oldVal.equals(list[i])) { - list[i] = (InterfaceMutation)newVal; - this.m_Editors[i].m_Name = list[i].getStringRepresentation(); + list[i] = (InterfaceMutation) newVal; + this.m_Editors[i].m_Name = list[i].getStringRepresentation(); try { - this.m_Editors[i].m_Value = list[i]; - this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); + this.m_Editors[i].m_Value = list[i]; + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(this.m_Editors[i].m_Value.getClass()); if (this.m_Editors[i].m_Editor == null) { this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceMutation.class); } diff --git a/src/eva2/optimization/operator/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java b/src/eva2/optimization/operator/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java index e97300d1..67d0bcf8 100644 --- a/src/eva2/optimization/operator/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java +++ b/src/eva2/optimization/operator/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java @@ -4,42 +4,43 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.strategies.ParticleSubSwarmOptimization; /** - * Particles are absorbed into a subswarm if they move into an area covered by that subswarm. - * To prevent the destabilisation of a subswarm only particles are absorbed which do not know - * a position that is better than the best position known by the subswarm. + * Particles are absorbed into a subswarm if they move into an area covered by that subswarm. + * To prevent the destabilisation of a subswarm only particles are absorbed which do not know + * a position that is better than the best position known by the subswarm. */ -public class ConsiderPBestAbsorptionStrategy extends StandardAbsorptionStrategy{ +public class ConsiderPBestAbsorptionStrategy extends StandardAbsorptionStrategy { - /** @tested - * true if - * the subswarm is active and - * the particle lies in the radius of the subswarm and - * the particles pbest is not better than the subswarms gbest (this would "pull the subswarm away") - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.StandardAbsorptionStrategy#shouldAbsorbParticleIntoSubswarm(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ + /** + * @tested true if + * the subswarm is active and + * the particle lies in the radius of the subswarm and + * the particles pbest is not better than the subswarms gbest (this would "pull the subswarm away") + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.StandardAbsorptionStrategy#shouldAbsorbParticleIntoSubswarm(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ @Override - public boolean shouldAbsorbParticleIntoSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { - if (!super.shouldAbsorbParticleIntoSubswarm(indy, subswarm, mainswarm)){ - return false; - } - if (absorbtionConstraintViolation(indy, subswarm)){ - return false; - } - return true; - } - - /** @tested - * @param indy - * @param subswarm - * @return - */ - private boolean absorbtionConstraintViolation(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm) { - AbstractEAIndividual indysPBest = (AbstractEAIndividual)indy.getData("PersonalBestKey"); - AbstractEAIndividual subswarmsGBest = subswarm.getGBestIndividual(); - if (indysPBest.isDominating(subswarmsGBest)) { - return true; - } - return false; - } + public boolean shouldAbsorbParticleIntoSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { + if (!super.shouldAbsorbParticleIntoSubswarm(indy, subswarm, mainswarm)) { + return false; + } + if (absorbtionConstraintViolation(indy, subswarm)) { + return false; + } + return true; + } + + /** + * @param indy + * @param subswarm + * @return + * @tested + */ + private boolean absorbtionConstraintViolation(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm) { + AbstractEAIndividual indysPBest = (AbstractEAIndividual) indy.getData("PersonalBestKey"); + AbstractEAIndividual subswarmsGBest = subswarm.getGBestIndividual(); + if (indysPBest.isDominating(subswarmsGBest)) { + return true; + } + return false; + } } diff --git a/src/eva2/optimization/operator/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java b/src/eva2/optimization/operator/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java index 0ce55d9a..18417b09 100644 --- a/src/eva2/optimization/operator/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java +++ b/src/eva2/optimization/operator/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java @@ -4,77 +4,80 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.strategies.ParticleSubSwarmOptimization; /** - * A threshold epsilon is proposed in [1] in order to prevent premature absorptions - * of particles into subswarms which cover large parts of the search space. - * A particle is absorbed into a subswarm if it lies within the radius of that subswarm - * and the diversity of this subswarm is below the given threshold epsilon. - * The diversity of a subswarm is defined as the average euclidean distance between - * the particles of that subswarm and the global best position of that subswarm. - * In [1], a threshold value of epsilon = 0.1 produced good results. - * [1] A.P. Engelbrecht and L.N.H. van Loggerenberg. - * Enhancing the nichepso. - * In IEEE Congress on Evolutionary Computation, - * 2007. + * A threshold epsilon is proposed in [1] in order to prevent premature absorptions + * of particles into subswarms which cover large parts of the search space. + * A particle is absorbed into a subswarm if it lies within the radius of that subswarm + * and the diversity of this subswarm is below the given threshold epsilon. + * The diversity of a subswarm is defined as the average euclidean distance between + * the particles of that subswarm and the global best position of that subswarm. + * In [1], a threshold value of epsilon = 0.1 produced good results. + * [1] A.P. Engelbrecht and L.N.H. van Loggerenberg. + * Enhancing the nichepso. + * In IEEE Congress on Evolutionary Computation, + * 2007. */ -public class EuclideanDiversityAbsorptionStrategy extends StandardAbsorptionStrategy{ +public class EuclideanDiversityAbsorptionStrategy extends StandardAbsorptionStrategy { - private double epsilon = 0.1; // 0.1 used in "Enhancing the NichePSO" by Engelbrecht et al. -/********************************************************************************************************************** - * ctors - */ - public EuclideanDiversityAbsorptionStrategy() { - } - - public EuclideanDiversityAbsorptionStrategy(EuclideanDiversityAbsorptionStrategy other){ - this.epsilon = other.epsilon; - } - - public EuclideanDiversityAbsorptionStrategy(double eps) { - epsilon = eps; - } + private double epsilon = 0.1; // 0.1 used in "Enhancing the NichePSO" by Engelbrecht et al. + + /** + * ******************************************************************************************************************* + * ctors + */ + public EuclideanDiversityAbsorptionStrategy() { + } + + public EuclideanDiversityAbsorptionStrategy(EuclideanDiversityAbsorptionStrategy other) { + this.epsilon = other.epsilon; + } + + public EuclideanDiversityAbsorptionStrategy(double eps) { + epsilon = eps; + } /********************************************************************************************************************** * shouldAbsorbParticleIntoSubswarm */ - /** @tested - * true if - * the subswarm is active and - * the particle lies in the radius of the subswarm and - * the diversity (mean distance from the gbest) of the subswarm < epsilon - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.StandardAbsorptionStrategy#shouldAbsorbParticleIntoSubswarm(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ + /** + * @tested true if + * the subswarm is active and + * the particle lies in the radius of the subswarm and + * the diversity (mean distance from the gbest) of the subswarm < epsilon + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.StandardAbsorptionStrategy#shouldAbsorbParticleIntoSubswarm(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ @Override - public boolean shouldAbsorbParticleIntoSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { - if (!super.shouldAbsorbParticleIntoSubswarm(indy, subswarm, mainswarm)){ - return false; // - } - if (!diversityIsBelowThreshold(subswarm)){ - return false; - } - return true; - } + public boolean shouldAbsorbParticleIntoSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { + if (!super.shouldAbsorbParticleIntoSubswarm(indy, subswarm, mainswarm)) { + return false; // + } + if (!diversityIsBelowThreshold(subswarm)) { + return false; + } + return true; + } - private boolean diversityIsBelowThreshold(ParticleSubSwarmOptimization subswarm) { - double meanDistanceFromGBestPos = subswarm.getEuclideanDiversity(); - if (meanDistanceFromGBestPos < getEpsilon()){ - return true; - } else { - return false; - } - } + private boolean diversityIsBelowThreshold(ParticleSubSwarmOptimization subswarm) { + double meanDistanceFromGBestPos = subswarm.getEuclideanDiversity(); + if (meanDistanceFromGBestPos < getEpsilon()) { + return true; + } else { + return false; + } + } -/********************************************************************************************************************** - * setter, getter - */ - public void setEpsilon(double epsilon) { - this.epsilon = epsilon; - } + /** + * ******************************************************************************************************************* + * setter, getter + */ + public void setEpsilon(double epsilon) { + this.epsilon = epsilon; + } - public double getEpsilon() { - return epsilon; - } - - public String epsilonTipText(){ - return "threshold for the diversity of the subswarm that confines the absorption of main swarm particles"; - } + public double getEpsilon() { + return epsilon; + } + + public String epsilonTipText() { + return "threshold for the diversity of the subswarm that confines the absorption of main swarm particles"; + } } diff --git a/src/eva2/optimization/operator/nichepso/absorption/InterfaceAbsorptionStrategy.java b/src/eva2/optimization/operator/nichepso/absorption/InterfaceAbsorptionStrategy.java index ab1b87b3..6a967591 100644 --- a/src/eva2/optimization/operator/nichepso/absorption/InterfaceAbsorptionStrategy.java +++ b/src/eva2/optimization/operator/nichepso/absorption/InterfaceAbsorptionStrategy.java @@ -8,29 +8,29 @@ import eva2.optimization.strategies.ParticleSubSwarmOptimization; */ public interface InterfaceAbsorptionStrategy { - /** @tested - * decides whether indy should be absorbed into the subswarm according to the absorption strategie - * @param indy - * @param subswarm the swarm indy will be absorbed from - * @param mainswarm the swarm indy currently belongs to - * (population statistics from that swarm may be used to decide whether indy should be absorbed) - * @return - */ - public abstract boolean shouldAbsorbParticleIntoSubswarm( - AbstractEAIndividual indy, - ParticleSubSwarmOptimization subswarm, - ParticleSubSwarmOptimization mainswarm); + /** + * @param indy + * @param subswarm the swarm indy will be absorbed from + * @param mainswarm the swarm indy currently belongs to + * (population statistics from that swarm may be used to decide whether indy should be absorbed) + * @return + * @tested decides whether indy should be absorbed into the subswarm according to the absorption strategie + */ + public abstract boolean shouldAbsorbParticleIntoSubswarm( + AbstractEAIndividual indy, + ParticleSubSwarmOptimization subswarm, + ParticleSubSwarmOptimization mainswarm); - /** @tested - * absorbs indy according to the absorbtion strategy - * @param indy - * @param subswarm the swarm indy will be absorbed from - * @param mainswarm the swarm indy currently belongs to - */ - public abstract void absorbParticle( - AbstractEAIndividual indy, - ParticleSubSwarmOptimization subswarm, - ParticleSubSwarmOptimization mainswarm); + /** + * @param indy + * @param subswarm the swarm indy will be absorbed from + * @param mainswarm the swarm indy currently belongs to + * @tested absorbs indy according to the absorbtion strategy + */ + public abstract void absorbParticle( + AbstractEAIndividual indy, + ParticleSubSwarmOptimization subswarm, + ParticleSubSwarmOptimization mainswarm); - public abstract Object clone(); + public abstract Object clone(); } diff --git a/src/eva2/optimization/operator/nichepso/absorption/StandardAbsorptionStrategy.java b/src/eva2/optimization/operator/nichepso/absorption/StandardAbsorptionStrategy.java index d9dd3ece..832816a9 100644 --- a/src/eva2/optimization/operator/nichepso/absorption/StandardAbsorptionStrategy.java +++ b/src/eva2/optimization/operator/nichepso/absorption/StandardAbsorptionStrategy.java @@ -4,80 +4,82 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.strategies.ParticleSubSwarmOptimization; /** - * Particles are absorbed into a subswarm when they move into an area - * within the radius of that subswarm. + * Particles are absorbed into a subswarm when they move into an area + * within the radius of that subswarm. * This strategy is proposed in - * R. Brits, A. P. Engelbrecht and B. Bergh. - * A Niching Particle Swarm Optimizer - * In Proceedings of the 4th Asia-Pacific Conference on Simulated Evolution and Learning (SEAL'02), - * 2002, 2, 692-696 + * R. Brits, A. P. Engelbrecht and B. Bergh. + * A Niching Particle Swarm Optimizer + * In Proceedings of the 4th Asia-Pacific Conference on Simulated Evolution and Learning (SEAL'02), + * 2002, 2, 692-696 */ -public class StandardAbsorptionStrategy implements InterfaceAbsorptionStrategy, java.io.Serializable { +public class StandardAbsorptionStrategy implements InterfaceAbsorptionStrategy, java.io.Serializable { -/********************************************************************************************************************** - * ctors, init, clone - */ + /** + * ******************************************************************************************************************* + * ctors, init, clone + */ @Override - public Object clone(){ - return (Object) new StandardAbsorptionStrategy(); - } - - public String globalInfo(){ - return "Strategy to absorb main swarm particles into a subswarm"; - } - + public Object clone() { + return (Object) new StandardAbsorptionStrategy(); + } + + public String globalInfo() { + return "Strategy to absorb main swarm particles into a subswarm"; + } + /********************************************************************************************************************** * shouldAbsorbParticleIntoSubswarm */ - - /** @tested - * true if - * the subswarm is active and - * the particle lies in the radius of the subswarm - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceAbsorptionStrategy#shouldAbsorbParticleIntoSubswarm(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ - @Override - public boolean shouldAbsorbParticleIntoSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { - if (!subswarm.isActive()){ - return false; // no interaction between active mainswarmparticle and inactive subswarm - } - if (!particleLiesInSubswarmRadius(indy, subswarm)) { - return false; - } - return true; - } - private boolean particleLiesInSubswarmRadius(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm) { - - double R = subswarm.getBoundSwarmRadius(); // uses euclidean distance - AbstractEAIndividual gbest = subswarm.getGBestIndividual(); - double dist = subswarm.distance(indy,gbest); // euclidean distance - if (dist <= R){ - return true; - }else { - return false; - } - } + /** + * @tested true if + * the subswarm is active and + * the particle lies in the radius of the subswarm + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceAbsorptionStrategy#shouldAbsorbParticleIntoSubswarm(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ + @Override + public boolean shouldAbsorbParticleIntoSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { + if (!subswarm.isActive()) { + return false; // no interaction between active mainswarmparticle and inactive subswarm + } + if (!particleLiesInSubswarmRadius(indy, subswarm)) { + return false; + } + return true; + } + + private boolean particleLiesInSubswarmRadius(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm) { + + double R = subswarm.getBoundSwarmRadius(); // uses euclidean distance + AbstractEAIndividual gbest = subswarm.getGBestIndividual(); + double dist = subswarm.distance(indy, gbest); // euclidean distance + if (dist <= R) { + return true; + } else { + return false; + } + } /********************************************************************************************************************** * absorbParticle */ - - /** @tested junit - * adds indy to an active subswarm, then removes indy from the mainswarm. - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceAbsorptionStrategy#absorbParticle(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ + + /** + * @tested junit + * adds indy to an active subswarm, then removes indy from the mainswarm. + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceAbsorptionStrategy#absorbParticle(javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ @Override - public void absorbParticle(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { - if (!subswarm.isActive()){ - System.out.println("absorbParticle: trying to absorb a particle into an inactive subswarm."); - return; - } - subswarm.add(indy); - subswarm.populationSizeHasChanged(); - mainswarm.removeSubIndividual(indy); - mainswarm.populationSizeHasChanged(); - } - + public void absorbParticle(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { + if (!subswarm.isActive()) { + System.out.println("absorbParticle: trying to absorb a particle into an inactive subswarm."); + return; + } + subswarm.add(indy); + subswarm.populationSizeHasChanged(); + mainswarm.removeSubIndividual(indy); + mainswarm.populationSizeHasChanged(); + } + } diff --git a/src/eva2/optimization/operator/nichepso/deactivation/DummyDeactivationStrategy.java b/src/eva2/optimization/operator/nichepso/deactivation/DummyDeactivationStrategy.java index e94cc75b..27a5afb9 100644 --- a/src/eva2/optimization/operator/nichepso/deactivation/DummyDeactivationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/deactivation/DummyDeactivationStrategy.java @@ -4,25 +4,24 @@ import eva2.optimization.strategies.ParticleSubSwarmOptimization; /** * dummy strategy does not deactivate anything - * */ public class DummyDeactivationStrategy implements InterfaceDeactivationStrategy, java.io.Serializable { @Override - public Object clone(){ - return (Object) new DummyDeactivationStrategy(); - } + public Object clone() { + return (Object) new DummyDeactivationStrategy(); + } @Override - public int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, - ParticleSubSwarmOptimization mainswarm) { - return null; - } + public int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, + ParticleSubSwarmOptimization mainswarm) { + return null; + } @Override - public boolean shouldDeactivateSubswarm( - ParticleSubSwarmOptimization subswarm) { - return false; - } + public boolean shouldDeactivateSubswarm( + ParticleSubSwarmOptimization subswarm) { + return false; + } } diff --git a/src/eva2/optimization/operator/nichepso/deactivation/ImprovementDeactivationStrategy.java b/src/eva2/optimization/operator/nichepso/deactivation/ImprovementDeactivationStrategy.java index 3f01e4d1..80da31d3 100644 --- a/src/eva2/optimization/operator/nichepso/deactivation/ImprovementDeactivationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/deactivation/ImprovementDeactivationStrategy.java @@ -5,155 +5,162 @@ import eva2.optimization.population.Population; import eva2.optimization.strategies.NichePSO; import eva2.optimization.strategies.ParticleSubSwarmOptimization; import eva2.tools.EVAERROR; + import java.util.List; import java.util.Vector; /** - * A subswarm is deactivated if all its particles are converged. - * A particle is considered converged if the standard deviation of its fitness values + * A subswarm is deactivated if all its particles are converged. + * A particle is considered converged if the standard deviation of its fitness values * over the last 3 iterations is less or equal a given threshold epsilon * Experiments showed good results using epsilon = 0.0001. - * */ public class ImprovementDeactivationStrategy implements InterfaceDeactivationStrategy, java.io.Serializable { - private double epsilon = 0.0001; - private int haltingWindow = 15; + private double epsilon = 0.0001; + private int haltingWindow = 15; + + /** + * ******************************************************************************************************************* + * ctors + */ + public ImprovementDeactivationStrategy() { + } + + public ImprovementDeactivationStrategy(double thresh, int hwLen) { + epsilon = thresh; + haltingWindow = hwLen; + } + + public ImprovementDeactivationStrategy(ImprovementDeactivationStrategy other) { + this.epsilon = other.epsilon; + this.haltingWindow = other.haltingWindow; + } + + public ImprovementDeactivationStrategy(double eps) { + this.epsilon = eps; + } -/********************************************************************************************************************** - * ctors - */ - public ImprovementDeactivationStrategy(){ - } - - public ImprovementDeactivationStrategy(double thresh, int hwLen) { - epsilon=thresh; - haltingWindow=hwLen; - } - - public ImprovementDeactivationStrategy(ImprovementDeactivationStrategy other){ - this.epsilon = other.epsilon; - this.haltingWindow=other.haltingWindow; - } - - public ImprovementDeactivationStrategy(double eps) { - this.epsilon = eps; - } - @Override - public Object clone(){ - return (Object) new ImprovementDeactivationStrategy(this); - } - - public String globalInfo(){ - return "Strategy to deactivate subswarms"; - } - -/********************************************************************************************************************** - * shouldDeactivateSubswarm - */ - - public boolean isConverged(Population pop){ + public Object clone() { + return (Object) new ImprovementDeactivationStrategy(this); + } + + public String globalInfo() { + return "Strategy to deactivate subswarms"; + } + + /** + * ******************************************************************************************************************* + * shouldDeactivateSubswarm + */ + + public boolean isConverged(Population pop) { // Vector bests = new Vector(pop.size()); - - Vector bests = (Vector)pop.getEAIndividual(0).getData(NichePSO.fitArchiveKey); - if (bests.size() lst = bests.subList(bests.size()-haltingWindow, bests.size()); - bests = new Vector(haltingWindow); - bests.addAll(lst); - for (int i=1; i fitArch = (Vector)pop.getEAIndividual(i).getData(NichePSO.fitArchiveKey); - int archIndex=fitArch.size()-haltingWindow+k; // index within the fitness archive of the current particle, which may be larger than the bests list - the tail is important - if (archIndex>=0 && (fitArch.get(archIndex) bests = (Vector) pop.getEAIndividual(0).getData(NichePSO.fitArchiveKey); + if (bests.size() < haltingWindow) { + return false; + } else { + List lst = bests.subList(bests.size() - haltingWindow, bests.size()); + bests = new Vector(haltingWindow); + bests.addAll(lst); + for (int i = 1; i < pop.size(); i++) { + for (int k = 0; k < haltingWindow; k++) { + Vector fitArch = (Vector) pop.getEAIndividual(i).getData(NichePSO.fitArchiveKey); + int archIndex = fitArch.size() - haltingWindow + k; // index within the fitness archive of the current particle, which may be larger than the bests list - the tail is important + if (archIndex >= 0 && (fitArch.get(archIndex) < bests.get(k))) { + bests.set(k, fitArch.get(archIndex)); + } + } } - return (isConverged(subswarm.getPopulation())); - } - + } + // bests contains now the sequence of best fitness values across the last generations + Double historicHWAgo = bests.get(0); + boolean res = true; + for (int i = 1; i < haltingWindow; i++) { + // if historic[-hW] is worse than historic[-hW+i] return false + Double historicIter = bests.get(i); + // if the iterated value (the later one in history) has improved, there is no convergence. + boolean improvementHappened = (historicIter < historicHWAgo);// testSecondForImprovement(historicHWAgo, historicIter)); + if (improvementHappened) { + res = false; + break; + } + } + return res; + } + + /** + * @tested true if the subswarm is active and all particles are completely converged + * (i.e. the stddev over the past 3 iterations is < epsilson) + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#shouldDeactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ + @Override + public boolean shouldDeactivateSubswarm(ParticleSubSwarmOptimization subswarm) { + if (!subswarm.isActive()) { + return false; + } + if (subswarm.getFitnessArchiveSize() < haltingWindow) { + EVAERROR.errorMsgOnce("Warning: halting window length " + haltingWindow + " too long for sub swarm template, which stores only " + subswarm.getFitnessArchiveSize() + " fitness values!"); + } + return (isConverged(subswarm.getPopulation())); + } + /********************************************************************************************************************** * deactivateSubswarm - */ - - /** @tested - * the subswarm is deactivated and the particles indices are returned. They are - * to be reinitialized into the mainswarm. - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#deactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ - @Override - public int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { - if (!subswarm.isActive()){ - System.out.println("deactivateSubSwarm: try to deactivate inactive subswarm"); - return null; - } - - // use the indizes of the deactivated particles for the reinitialized particles (important for ANPSO) - Population pop = subswarm.getPopulation(); - int[] particleIndices = new int[pop.size()]; - for (int i = 0; i < pop.size(); ++i){ - AbstractEAIndividual indy = pop.getEAIndividual(i); - //Integer index = (Integer)indy.getData("particleIndex"); - particleIndices[i] = indy.getIndividualIndex();//index.intValue(); - } - subswarm.SetActive(false); - return particleIndices; - } - -/********************************************************************************************************************** - * getter, setter */ - public void setEpsilon(double epsilon) { - this.epsilon = epsilon; - } - public double getEpsilon() { - return epsilon; - } - public String epsilonTipText(){ - return "If the fitness improves by less than this threshold within the halting window, convergence is assumed."; - } + /** + * @tested the subswarm is deactivated and the particles indices are returned. They are + * to be reinitialized into the mainswarm. + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#deactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ + @Override + public int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { + if (!subswarm.isActive()) { + System.out.println("deactivateSubSwarm: try to deactivate inactive subswarm"); + return null; + } - public int getHaltingWindowLen() { - return haltingWindow; - } - public void setHaltingWindowLen(int hwLen) { - this.haltingWindow = hwLen; - } - public String haltingWindowLenTipText() { - return "The number of generations to be tested for improvement"; - } + // use the indizes of the deactivated particles for the reinitialized particles (important for ANPSO) + Population pop = subswarm.getPopulation(); + int[] particleIndices = new int[pop.size()]; + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual indy = pop.getEAIndividual(i); + //Integer index = (Integer)indy.getData("particleIndex"); + particleIndices[i] = indy.getIndividualIndex();//index.intValue(); + } + subswarm.SetActive(false); + return particleIndices; + } + + /** + * ******************************************************************************************************************* + * getter, setter + */ + + public void setEpsilon(double epsilon) { + this.epsilon = epsilon; + } + + public double getEpsilon() { + return epsilon; + } + + public String epsilonTipText() { + return "If the fitness improves by less than this threshold within the halting window, convergence is assumed."; + } + + public int getHaltingWindowLen() { + return haltingWindow; + } + + public void setHaltingWindowLen(int hwLen) { + this.haltingWindow = hwLen; + } + + public String haltingWindowLenTipText() { + return "The number of generations to be tested for improvement"; + } } diff --git a/src/eva2/optimization/operator/nichepso/deactivation/InterfaceDeactivationStrategy.java b/src/eva2/optimization/operator/nichepso/deactivation/InterfaceDeactivationStrategy.java index 6eeebef7..25480ebe 100644 --- a/src/eva2/optimization/operator/nichepso/deactivation/InterfaceDeactivationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/deactivation/InterfaceDeactivationStrategy.java @@ -7,22 +7,22 @@ import eva2.optimization.strategies.ParticleSubSwarmOptimization; */ public interface InterfaceDeactivationStrategy { - /** @tested - * decides whether a subswarm should be deacitvated according to the deactivation strategy - * @param subswarm - * @return - */ - public abstract boolean shouldDeactivateSubswarm(ParticleSubSwarmOptimization subswarm); - - /** @tested - * deactivates a given subswarm. - * What happens to the particles in this subswarm depends on the concrete strategy. - * Return the list of indices to be reinitialized or null. - * @param subswarm - * @param mainswarm - */ - public abstract int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm); + /** + * @param subswarm + * @return + * @tested decides whether a subswarm should be deacitvated according to the deactivation strategy + */ + public abstract boolean shouldDeactivateSubswarm(ParticleSubSwarmOptimization subswarm); + + /** + * @param subswarm + * @param mainswarm + * @tested deactivates a given subswarm. + * What happens to the particles in this subswarm depends on the concrete strategy. + * Return the list of indices to be reinitialized or null. + */ + public abstract int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm); + + public abstract Object clone(); - public abstract Object clone(); - } diff --git a/src/eva2/optimization/operator/nichepso/deactivation/StandardDeactivationStrategy.java b/src/eva2/optimization/operator/nichepso/deactivation/StandardDeactivationStrategy.java index a45a8a86..ac3403be 100644 --- a/src/eva2/optimization/operator/nichepso/deactivation/StandardDeactivationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/deactivation/StandardDeactivationStrategy.java @@ -5,57 +5,59 @@ import eva2.optimization.population.Population; import eva2.optimization.strategies.NichePSO; import eva2.optimization.strategies.ParticleSubSwarmOptimization; import eva2.tools.EVAERROR; + import java.util.Vector; /** - * A subswarm is deactivated if all its particles are converged. - * A particle is considered converged if the standard deviation of its fitness values + * A subswarm is deactivated if all its particles are converged. + * A particle is considered converged if the standard deviation of its fitness values * over the last 3 iterations is less or equal a given threshold epsilon * Experiments showed good results using epsilon = 0.0001. - * */ public class StandardDeactivationStrategy implements InterfaceDeactivationStrategy, java.io.Serializable { - private double epsilon = 0.0001; - private int stdDevHorizon = 3; + private double epsilon = 0.0001; + private int stdDevHorizon = 3; + + /** + * ******************************************************************************************************************* + * ctors + */ + public StandardDeactivationStrategy() { + + } + + public StandardDeactivationStrategy(StandardDeactivationStrategy other) { + this.epsilon = other.epsilon; + this.stdDevHorizon = other.stdDevHorizon; + } + + public StandardDeactivationStrategy(double eps, int horizon) { + this.epsilon = eps; + this.stdDevHorizon = horizon; + } + + public StandardDeactivationStrategy(double eps) { + this.epsilon = eps; + } + + @Override + public Object clone() { + return (Object) new StandardDeactivationStrategy(this); + } + + public String globalInfo() { + return "Strategy to deactivate subswarms"; + } -/********************************************************************************************************************** - * ctors - */ - public StandardDeactivationStrategy(){ - - } - - public StandardDeactivationStrategy(StandardDeactivationStrategy other){ - this.epsilon = other.epsilon; - this.stdDevHorizon = other.stdDevHorizon; - } - - public StandardDeactivationStrategy(double eps, int horizon) { - this.epsilon = eps; - this.stdDevHorizon = horizon; - } - - public StandardDeactivationStrategy(double eps) { - this.epsilon = eps; - } - - @Override - public Object clone(){ - return (Object) new StandardDeactivationStrategy(this); - } - - public String globalInfo(){ - return "Strategy to deactivate subswarms"; - } - /********************************************************************************************************************** * shouldDeactivateSubswarm - */ - /** @tested - * @param pop - * @return - */ + */ + /** + * @param pop + * @return + * @tested + */ // public boolean areAllConverged(Population pop){ // for (int i = 0; i < pop.size(); ++i){ // AbstractEAIndividual currentindy = pop.getEAIndividual(i); @@ -66,92 +68,94 @@ public class StandardDeactivationStrategy implements InterfaceDeactivationStrate // } // return true; // } - public boolean areAllConverged(Population pop){ - for (int i = 0; i < pop.size(); ++i){ - AbstractEAIndividual currentindy = pop.getEAIndividual(i); - double value; - if (stdDevHorizon == NichePSO.defaultFitStdDevHorizon) { - value = ((Double)currentindy.getData(NichePSO.stdDevKey)).doubleValue(); - } else { - Vector fitArch = (Vector)currentindy.getData(NichePSO.fitArchiveKey); - value = ParticleSubSwarmOptimization.stdDev(fitArch,stdDevHorizon); - } - if (value > getEpsilon()){ - return false; // particle not converged... - } - - } - return true; - } - /** @tested - * true if the subswarm is active and all particles are completely converged - * (i.e. the stddev over the past 3 iterations is < epsilson) - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#shouldDeactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ - @Override - public boolean shouldDeactivateSubswarm(ParticleSubSwarmOptimization subswarm) { - if (!subswarm.isActive()){ - return false; - } - if (subswarm.getFitnessArchiveSize() fitArch = (Vector) currentindy.getData(NichePSO.fitArchiveKey); + value = ParticleSubSwarmOptimization.stdDev(fitArch, stdDevHorizon); } - return (areAllConverged(subswarm.getPopulation())); - } - + if (value > getEpsilon()) { + return false; // particle not converged... + } + + } + return true; + } + + /** + * @tested true if the subswarm is active and all particles are completely converged + * (i.e. the stddev over the past 3 iterations is < epsilson) + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#shouldDeactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ + @Override + public boolean shouldDeactivateSubswarm(ParticleSubSwarmOptimization subswarm) { + if (!subswarm.isActive()) { + return false; + } + if (subswarm.getFitnessArchiveSize() < stdDevHorizon) { + EVAERROR.errorMsgOnce("Warning: halting window length " + stdDevHorizon + " too long for sub swarm template, which stores only " + subswarm.getFitnessArchiveSize() + " fitness values!"); + } + return (areAllConverged(subswarm.getPopulation())); + } + /********************************************************************************************************************** * deactivateSubswarm - */ - - /** @tested - * the subswarm is deactivated and the particles indices are returned. They are - * to be reinitialized into the mainswarm. - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#deactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ - @Override - public int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { - if (!subswarm.isActive()){ - System.out.println("deactivateSubSwarm: try to deactivate inactive subswarm"); - return null; - } - - // use the indizes of the deactivated particles for the reinitialized particles (important for ANPSO) - Population pop = subswarm.getPopulation(); - int[] particleIndices = new int[pop.size()]; - for (int i = 0; i < pop.size(); ++i){ - AbstractEAIndividual indy = pop.getEAIndividual(i); - //Integer index = (Integer)indy.getData("particleIndex"); - particleIndices[i] = indy.getIndividualIndex();//index.intValue(); - } - subswarm.SetActive(false); - return particleIndices; - } - -/********************************************************************************************************************** - * getter, setter */ - public void setEpsilon(double epsilon) { - this.epsilon = epsilon; - } + /** + * @tested the subswarm is deactivated and the particles indices are returned. They are + * to be reinitialized into the mainswarm. + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceDeactivationStrategy#deactivateSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ + @Override + public int[] deactivateSubswarm(ParticleSubSwarmOptimization subswarm, ParticleSubSwarmOptimization mainswarm) { + if (!subswarm.isActive()) { + System.out.println("deactivateSubSwarm: try to deactivate inactive subswarm"); + return null; + } - public double getEpsilon() { - return epsilon; - } - - public String epsilonTipText(){ - return "threshold used to identify converged particles"; - } + // use the indizes of the deactivated particles for the reinitialized particles (important for ANPSO) + Population pop = subswarm.getPopulation(); + int[] particleIndices = new int[pop.size()]; + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual indy = pop.getEAIndividual(i); + //Integer index = (Integer)indy.getData("particleIndex"); + particleIndices[i] = indy.getIndividualIndex();//index.intValue(); + } + subswarm.SetActive(false); + return particleIndices; + } - public int getStdDevHorizon() { - return stdDevHorizon; - } + /** + * ******************************************************************************************************************* + * getter, setter + */ - public void setStdDevHorizon(int stdDevHorizon) { - this.stdDevHorizon = stdDevHorizon; - } - - public String stdDevHorizonTipText() { - return "The number of past fitness values to use for deactivation indication, note theres a maximum defined by the NichePSO fitness archiving."; - } + public void setEpsilon(double epsilon) { + this.epsilon = epsilon; + } + + public double getEpsilon() { + return epsilon; + } + + public String epsilonTipText() { + return "threshold used to identify converged particles"; + } + + public int getStdDevHorizon() { + return stdDevHorizon; + } + + public void setStdDevHorizon(int stdDevHorizon) { + this.stdDevHorizon = stdDevHorizon; + } + + public String stdDevHorizonTipText() { + return "The number of past fitness values to use for deactivation indication, note theres a maximum defined by the NichePSO fitness archiving."; + } } diff --git a/src/eva2/optimization/operator/nichepso/merging/InterfaceMergingStrategy.java b/src/eva2/optimization/operator/nichepso/merging/InterfaceMergingStrategy.java index 588f369b..6c3f78d7 100644 --- a/src/eva2/optimization/operator/nichepso/merging/InterfaceMergingStrategy.java +++ b/src/eva2/optimization/operator/nichepso/merging/InterfaceMergingStrategy.java @@ -1,6 +1,7 @@ package eva2.optimization.operator.nichepso.merging; import eva2.optimization.strategies.ParticleSubSwarmOptimization; + import java.util.Vector; @@ -9,31 +10,33 @@ import java.util.Vector; */ public interface InterfaceMergingStrategy { - /** - * decides whether the two subswarms should be merged according to the merging strategie - * @param subswarm1 - * @param subswarm2 - * @return - */ - public abstract boolean shouldMergeSubswarms( - ParticleSubSwarmOptimization subswarm1, - ParticleSubSwarmOptimization subswarm2); - - /** - * Merges the i. and j. subswarm from subSwarms. - * The meaning of this depends on the concrete strategy but two aspects schould be taken care of: - * 1. the overall population size (in all subSwarms and the mainSwarm) should remain constant - * 2. call populationSizeHasChanged() for changed swarms - * @param i - * @param j - * @param subSwarms - * @param mainSwarm - */ - public abstract void mergeSubswarms( - int i, - int j, - Vector subSwarms, - ParticleSubSwarmOptimization mainSwarm); + /** + * decides whether the two subswarms should be merged according to the merging strategie + * + * @param subswarm1 + * @param subswarm2 + * @return + */ + public abstract boolean shouldMergeSubswarms( + ParticleSubSwarmOptimization subswarm1, + ParticleSubSwarmOptimization subswarm2); - public abstract Object clone(); + /** + * Merges the i. and j. subswarm from subSwarms. + * The meaning of this depends on the concrete strategy but two aspects schould be taken care of: + * 1. the overall population size (in all subSwarms and the mainSwarm) should remain constant + * 2. call populationSizeHasChanged() for changed swarms + * + * @param i + * @param j + * @param subSwarms + * @param mainSwarm + */ + public abstract void mergeSubswarms( + int i, + int j, + Vector subSwarms, + ParticleSubSwarmOptimization mainSwarm); + + public abstract Object clone(); } diff --git a/src/eva2/optimization/operator/nichepso/merging/ScatterMergingStrategy.java b/src/eva2/optimization/operator/nichepso/merging/ScatterMergingStrategy.java index b5c4fab6..4dc15f2f 100644 --- a/src/eva2/optimization/operator/nichepso/merging/ScatterMergingStrategy.java +++ b/src/eva2/optimization/operator/nichepso/merging/ScatterMergingStrategy.java @@ -1,97 +1,97 @@ package eva2.optimization.operator.nichepso.merging; import eva2.optimization.strategies.ParticleSubSwarmOptimization; + import java.util.Vector; /** - * Two subswarms are merged if their radii overlap. - * In case both radii equal zero the subswarms are merged if their distance is below a given threshold mu. - * During merging, the particles of one of these subswarms are reinitialized into the main swarm. - * This improves exploration compared to the StandardMergingStrategy. - * This strategy is proposed in [1] and a small value, such as mu = 0.001, is suggested. - * [1] A.P. Engelbrecht and L.N.H. van Loggerenberg. - * Enhancing the nichepso. - * In IEEE Congress on Evolutionary Computation, + * Two subswarms are merged if their radii overlap. + * In case both radii equal zero the subswarms are merged if their distance is below a given threshold mu. + * During merging, the particles of one of these subswarms are reinitialized into the main swarm. + * This improves exploration compared to the StandardMergingStrategy. + * This strategy is proposed in [1] and a small value, such as mu = 0.001, is suggested. + * [1] A.P. Engelbrecht and L.N.H. van Loggerenberg. + * Enhancing the nichepso. + * In IEEE Congress on Evolutionary Computation, * 2007. */ -public class ScatterMergingStrategy extends StandardMergingStrategy{ +public class ScatterMergingStrategy extends StandardMergingStrategy { + + public ScatterMergingStrategy() { + super(); + } + + public ScatterMergingStrategy(double theMu) { + super(theMu); + } - public ScatterMergingStrategy() { - super(); - } - - public ScatterMergingStrategy(double theMu) { - super(theMu); - } - @Override - public String globalInfo(){ - return "Strategy to merge subswarms"; - } - + public String globalInfo() { + return "Strategy to merge subswarms"; + } + /********************************************************************************************************************** * mergeSubswarms */ - /** @tested - * if both active: reinitializes subswarm j back into the main swarm and deletes it from the subswarms. - * if both inactive: adds population of subswarm j to population of subswarm i, then deletes subswarm j. - * @param i - * @param j - */ + /** + * @param i + * @param j + * @tested if both active: reinitializes subswarm j back into the main swarm and deletes it from the subswarms. + * if both inactive: adds population of subswarm j to population of subswarm i, then deletes subswarm j. + */ @Override - public void mergeSubswarms( - int i, - int j, - Vector subSwarms, - ParticleSubSwarmOptimization mainSwarm) - { - ParticleSubSwarmOptimization borg= subSwarms.get(i); - ParticleSubSwarmOptimization others= subSwarms.get(j); + public void mergeSubswarms( + int i, + int j, + Vector subSwarms, + ParticleSubSwarmOptimization mainSwarm) { + ParticleSubSwarmOptimization borg = subSwarms.get(i); + ParticleSubSwarmOptimization others = subSwarms.get(j); - if (borg.isActive() && others.isActive()){ - mergeActiveSubswarms(i,j,subSwarms,mainSwarm); - return; - } - if (!borg.isActive() && !others.isActive()){ - mergeInactiveSubswarms(i,j,subSwarms,mainSwarm); - return; - } - System.out.print("ScatterMergingStrategy.mergeSubswarms problem: subswarms not of equal state."); - } + if (borg.isActive() && others.isActive()) { + mergeActiveSubswarms(i, j, subSwarms, mainSwarm); + return; + } + if (!borg.isActive() && !others.isActive()) { + mergeInactiveSubswarms(i, j, subSwarms, mainSwarm); + return; + } + System.out.print("ScatterMergingStrategy.mergeSubswarms problem: subswarms not of equal state."); + } - private void mergeInactiveSubswarms( - int i, - int j, - Vector subSwarms, - ParticleSubSwarmOptimization mainSwarm) { - ParticleSubSwarmOptimization borg = subSwarms.get(i); - ParticleSubSwarmOptimization others= subSwarms.get(j); - - borg.addPopulation(others); - borg.populationSizeHasChanged(); - - subSwarms.remove(j); - } + private void mergeInactiveSubswarms( + int i, + int j, + Vector subSwarms, + ParticleSubSwarmOptimization mainSwarm) { + ParticleSubSwarmOptimization borg = subSwarms.get(i); + ParticleSubSwarmOptimization others = subSwarms.get(j); - /** @tested - * subswarm j is reinited into the mainswarm and deleted, the function calls are added to the main swarm - * @param i - * @param j - * @param subSwarms - * @param mainSwarm - */ - private void mergeActiveSubswarms( - int i, - int j, - Vector subSwarms, - ParticleSubSwarmOptimization mainSwarm) { - mainSwarm.reinitIndividuals(subSwarms.get(j).getPopulation().size()); // add to the mainswarm - //mainSwarm.populationSizeHasChanged(); // already called in addNewParticlesToPopulation - // transfer functioncalls from the subswarm to the mainswarm before deleting it: - int calls = subSwarms.get(j).getPopulation().getFunctionCalls(); - mainSwarm.getPopulation().incrFunctionCallsBy(calls); - subSwarms.remove(j); - } + borg.addPopulation(others); + borg.populationSizeHasChanged(); + + subSwarms.remove(j); + } + + /** + * @param i + * @param j + * @param subSwarms + * @param mainSwarm + * @tested subswarm j is reinited into the mainswarm and deleted, the function calls are added to the main swarm + */ + private void mergeActiveSubswarms( + int i, + int j, + Vector subSwarms, + ParticleSubSwarmOptimization mainSwarm) { + mainSwarm.reinitIndividuals(subSwarms.get(j).getPopulation().size()); // add to the mainswarm + //mainSwarm.populationSizeHasChanged(); // already called in addNewParticlesToPopulation + // transfer functioncalls from the subswarm to the mainswarm before deleting it: + int calls = subSwarms.get(j).getPopulation().getFunctionCalls(); + mainSwarm.getPopulation().incrFunctionCallsBy(calls); + subSwarms.remove(j); + } } diff --git a/src/eva2/optimization/operator/nichepso/merging/StandardMergingStrategy.java b/src/eva2/optimization/operator/nichepso/merging/StandardMergingStrategy.java index b74061bb..cb6315c6 100644 --- a/src/eva2/optimization/operator/nichepso/merging/StandardMergingStrategy.java +++ b/src/eva2/optimization/operator/nichepso/merging/StandardMergingStrategy.java @@ -5,154 +5,156 @@ import eva2.optimization.individuals.InterfaceESIndividual; import eva2.optimization.operator.distancemetric.EuclideanMetric; import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.strategies.ParticleSubSwarmOptimization; + import java.util.Vector; /** - * Two subswarms are merged if their radii overlap. - * In case both radii equal zero the subswarms are merged if their distance is below a given threshold mu. - * This strategy is proposed in [1] and a small value, such as mu = 0.001, is suggested. - * [1] R. Brits, A. P. Engelbrecht and B. Bergh. - * A Niching Particle Swarm Optimizer - * In Proceedings of the 4th Asia-Pacific Conference on Simulated Evolution and Learning (SEAL'02), - * 2002, 2, 692-696 + * Two subswarms are merged if their radii overlap. + * In case both radii equal zero the subswarms are merged if their distance is below a given threshold mu. + * This strategy is proposed in [1] and a small value, such as mu = 0.001, is suggested. + * [1] R. Brits, A. P. Engelbrecht and B. Bergh. + * A Niching Particle Swarm Optimizer + * In Proceedings of the 4th Asia-Pacific Conference on Simulated Evolution and Learning (SEAL'02), + * 2002, 2, 692-696 */ public class StandardMergingStrategy implements InterfaceMergingStrategy, java.io.Serializable { - private double mu = 0.001; // "experimentally found to be effective" according to "a niching particle swarm optimizer" by Brits et al. + private double mu = 0.001; // "experimentally found to be effective" according to "a niching particle swarm optimizer" by Brits et al. + + public String globalInfo() { + return "Strategy to merge subswarms"; + } + + /** + * ******************************************************************************************************************* + * ctors + */ + public StandardMergingStrategy() { + + } + + public StandardMergingStrategy(double theMu) { + mu = theMu; + } + + public StandardMergingStrategy(StandardMergingStrategy other) { + this.mu = other.mu; + } - public String globalInfo(){ - return "Strategy to merge subswarms"; - } - -/********************************************************************************************************************** - * ctors - */ - public StandardMergingStrategy(){ - - } - - public StandardMergingStrategy(double theMu){ - mu = theMu; - } - - public StandardMergingStrategy(StandardMergingStrategy other){ - this.mu = other.mu; - } - @Override - public Object clone(){ - return (Object) new StandardMergingStrategy(this); - } - + public Object clone() { + return (Object) new StandardMergingStrategy(this); + } + /********************************************************************************************************************** * shouldMergeSubswarms */ - /** @tested - * the subswarms are merged, if they overlap (or are very close) and if they are of equal state - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceMergingStrategie#shouldMergeSubswarms(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ + /** + * @tested the subswarms are merged, if they overlap (or are very close) and if they are of equal state + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceMergingStrategie#shouldMergeSubswarms(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ @Override - public boolean shouldMergeSubswarms(ParticleSubSwarmOptimization subswarm1, ParticleSubSwarmOptimization subswarm2) { - // check for equal state - if (subswarm1.isActive() && !subswarm2.isActive()) { - return false; - } - if (!subswarm1.isActive() && subswarm2.isActive()) { - return false; - } - - if (!subswarmsOverlapOrAreVeryClose(subswarm1,subswarm2)){ - return false; - } + public boolean shouldMergeSubswarms(ParticleSubSwarmOptimization subswarm1, ParticleSubSwarmOptimization subswarm2) { + // check for equal state + if (subswarm1.isActive() && !subswarm2.isActive()) { + return false; + } + if (!subswarm1.isActive() && subswarm2.isActive()) { + return false; + } - - return true; - } + if (!subswarmsOverlapOrAreVeryClose(subswarm1, subswarm2)) { + return false; + } - private boolean subswarmsOverlapOrAreVeryClose(ParticleSubSwarmOptimization subswarm1,ParticleSubSwarmOptimization subswarm2) { - // check if they overlap - AbstractEAIndividual gbesti = subswarm1.getGBestIndividual(); - AbstractEAIndividual gbestj = subswarm2.getGBestIndividual(); - InterfaceESIndividual i1=null, i2=null; - - double dist; - if (gbesti instanceof InterfaceESIndividual) { - i1=(InterfaceESIndividual)gbesti; - i2=(InterfaceESIndividual)gbestj; - } - - if (i1 != null) { - dist = EuclideanMetric.euclideanDistance(i1.getDGenotype(), i2.getDGenotype()); - } - else { - dist = subswarm1.distance(gbesti, gbestj); - } // euclidean distance + + return true; + } + + private boolean subswarmsOverlapOrAreVeryClose(ParticleSubSwarmOptimization subswarm1, ParticleSubSwarmOptimization subswarm2) { + // check if they overlap + AbstractEAIndividual gbesti = subswarm1.getGBestIndividual(); + AbstractEAIndividual gbestj = subswarm2.getGBestIndividual(); + InterfaceESIndividual i1 = null, i2 = null; + + double dist; + if (gbesti instanceof InterfaceESIndividual) { + i1 = (InterfaceESIndividual) gbesti; + i2 = (InterfaceESIndividual) gbestj; + } + + if (i1 != null) { + dist = EuclideanMetric.euclideanDistance(i1.getDGenotype(), i2.getDGenotype()); + } else { + dist = subswarm1.distance(gbesti, gbestj); + } // euclidean distance // System.out.println("dist is " + dist); - - if (dist < (subswarm1.getMaxAllowedSwarmRadiusAbs() + subswarm2.getMaxAllowedSwarmRadiusAbs())) { - // only then is the next (expensive) test feasible - double Ri = subswarm1.getBoundSwarmRadius(); // uses euclidean distance - double Rj = subswarm2.getBoundSwarmRadius(); // uses euclidean distance - - if (dist < Ri+Rj ){ // all in euclidean metric - return true; - } - } - - // check if they are "very close" - double dist_norm; - if (i1 != null) { - dist_norm = EuclideanMetric.normedEuclideanDistance(i1.getDGenotype(), i1.getDoubleRange(), - i2.getDGenotype(), i2.getDoubleRange()); - } else { - dist_norm = PhenotypeMetric.dist(gbesti, gbestj); - } // normalised distance - - //if (Ri == 0 && Rj == 0 && dist_norm < getEpsilon()){ // see "Enhancing the NichePSO" paper - if (dist_norm < getMu()){ // Ri und Rj auf null testen sinvoll ? - return true; - } - return false; - } + + if (dist < (subswarm1.getMaxAllowedSwarmRadiusAbs() + subswarm2.getMaxAllowedSwarmRadiusAbs())) { + // only then is the next (expensive) test feasible + double Ri = subswarm1.getBoundSwarmRadius(); // uses euclidean distance + double Rj = subswarm2.getBoundSwarmRadius(); // uses euclidean distance + + if (dist < Ri + Rj) { // all in euclidean metric + return true; + } + } + + // check if they are "very close" + double dist_norm; + if (i1 != null) { + dist_norm = EuclideanMetric.normedEuclideanDistance(i1.getDGenotype(), i1.getDoubleRange(), + i2.getDGenotype(), i2.getDoubleRange()); + } else { + dist_norm = PhenotypeMetric.dist(gbesti, gbestj); + } // normalised distance + + //if (Ri == 0 && Rj == 0 && dist_norm < getEpsilon()){ // see "Enhancing the NichePSO" paper + if (dist_norm < getMu()) { // Ri und Rj auf null testen sinvoll ? + return true; + } + return false; + } /********************************************************************************************************************** * mergeSubswarms */ - - /** @tested junit - * adds population of subswarm j to population of subswarm i, then deletes subswarm j. - * @param i - * @param j - */ + + /** + * @param i + * @param j + * @tested junit + * adds population of subswarm j to population of subswarm i, then deletes subswarm j. + */ @Override - public void mergeSubswarms( - int i, - int j, - Vector subSwarms, - ParticleSubSwarmOptimization mainSwarm) - { - ParticleSubSwarmOptimization borg = subSwarms.get(i); - ParticleSubSwarmOptimization others= subSwarms.get(j); + public void mergeSubswarms( + int i, + int j, + Vector subSwarms, + ParticleSubSwarmOptimization mainSwarm) { + ParticleSubSwarmOptimization borg = subSwarms.get(i); + ParticleSubSwarmOptimization others = subSwarms.get(j); // System.out.println("merging " + (borg.isActive() ? " active " : " inactive ") + " with " + (others.isActive() ? "active" : "inactive")); - borg.addPopulation(others); - borg.populationSizeHasChanged(); - - subSwarms.remove(j); // ok: function calls added to borg swarm... - } - -/********************************************************************************************************************** - * getter, setter - */ + borg.addPopulation(others); + borg.populationSizeHasChanged(); - public void setMu(double mu) { - this.mu = mu; - } + subSwarms.remove(j); // ok: function calls added to borg swarm... + } - public double getMu() { - return mu; - } - - public String muTipText(){ - return "threshold used to merge subswarms that lie very close but have no spatial extent"; - } + /** + * ******************************************************************************************************************* + * getter, setter + */ + + public void setMu(double mu) { + this.mu = mu; + } + + public double getMu() { + return mu; + } + + public String muTipText() { + return "threshold used to merge subswarms that lie very close but have no spatial extent"; + } } diff --git a/src/eva2/optimization/operator/nichepso/subswarmcreation/DummySubswarmCreationStrategy.java b/src/eva2/optimization/operator/nichepso/subswarmcreation/DummySubswarmCreationStrategy.java index 78bd266d..e5eca994 100644 --- a/src/eva2/optimization/operator/nichepso/subswarmcreation/DummySubswarmCreationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/subswarmcreation/DummySubswarmCreationStrategy.java @@ -6,22 +6,22 @@ import eva2.optimization.strategies.ParticleSubSwarmOptimization; public class DummySubswarmCreationStrategy implements InterfaceSubswarmCreationStrategy { @Override - public Object clone(){ - return (Object) new DummySubswarmCreationStrategy(); - } - - @Override - public void createSubswarm(ParticleSubSwarmOptimization preparedSubswarm, - AbstractEAIndividual indy, ParticleSubSwarmOptimization mainSwarm) { - // TODO Auto-generated method stub - - } + public Object clone() { + return (Object) new DummySubswarmCreationStrategy(); + } @Override - public boolean shouldCreateSubswarm(AbstractEAIndividual indy, - ParticleSubSwarmOptimization mainswarm) { - // TODO Auto-generated method stub - return false; - } + public void createSubswarm(ParticleSubSwarmOptimization preparedSubswarm, + AbstractEAIndividual indy, ParticleSubSwarmOptimization mainSwarm) { + // TODO Auto-generated method stub + + } + + @Override + public boolean shouldCreateSubswarm(AbstractEAIndividual indy, + ParticleSubSwarmOptimization mainswarm) { + // TODO Auto-generated method stub + return false; + } } diff --git a/src/eva2/optimization/operator/nichepso/subswarmcreation/GenerateNeighborSubswarmCreationStrategy.java b/src/eva2/optimization/operator/nichepso/subswarmcreation/GenerateNeighborSubswarmCreationStrategy.java index 3cee75b7..a32a0d4f 100644 --- a/src/eva2/optimization/operator/nichepso/subswarmcreation/GenerateNeighborSubswarmCreationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/subswarmcreation/GenerateNeighborSubswarmCreationStrategy.java @@ -7,92 +7,93 @@ import eva2.optimization.population.Population; import eva2.optimization.strategies.ParticleSubSwarmOptimization; /** - * The standard deviation in the fitness of each main swarm particle over the last 3 iterations is calculated. - * If this standard deviation falls below a given threshold delta it is assumed that the particle is converging - * on an optimum and a subswarm is created with that particle and a generated neighbor. + * The standard deviation in the fitness of each main swarm particle over the last 3 iterations is calculated. + * If this standard deviation falls below a given threshold delta it is assumed that the particle is converging + * on an optimum and a subswarm is created with that particle and a generated neighbor. * This neighbor is generated by mutating the converged particle using the mutation step size mu. - * delta = 0.0001 and mu = 0.1 could experimentally produce acceptable results - * but further effort to obtain appropriate values for mu may significantly improve the performance of this strategy. + * delta = 0.0001 and mu = 0.1 could experimentally produce acceptable results + * but further effort to obtain appropriate values for mu may significantly improve the performance of this strategy. */ public class GenerateNeighborSubswarmCreationStrategy extends - StandardSubswarmCreationStrategy { - - private double mu = 0.1; - + StandardSubswarmCreationStrategy { + + private double mu = 0.1; + /********************************************************************************************************************** * shouldCreateSubswarm - */ - - // same as in StandardSubswarmCreationStrategy - + */ + + // same as in StandardSubswarmCreationStrategy + /********************************************************************************************************************** * createSubswarm - */ - - /** @tested - * creates a subswarm from the given particle and its neighbor in the mainswarm. - * If the neighbors pbest is better than the particles pbest, a new neighbor is generated. - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.StandardSubswarmCreationStrategy#createSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ + */ + + /** + * @tested creates a subswarm from the given particle and its neighbor in the mainswarm. + * If the neighbors pbest is better than the particles pbest, a new neighbor is generated. + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.StandardSubswarmCreationStrategy#createSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ @Override - public void createSubswarm(ParticleSubSwarmOptimization preparedSubswarm, AbstractEAIndividual indy, ParticleSubSwarmOptimization mainSwarm) { - // get the neighbor in the mainswarm - AbstractEAIndividual neighbor = mainSwarm.getMemberNeighbor(indy); - AbstractEAIndividual worst; - // check if neighbor would "pull the indy away from its niche" because it has a better pbest - AbstractEAIndividual indypbest = (AbstractEAIndividual)indy.getData("PersonalBestKey"); - AbstractEAIndividual neighpbest = (AbstractEAIndividual)neighbor.getData("PersonalBestKey"); + public void createSubswarm(ParticleSubSwarmOptimization preparedSubswarm, AbstractEAIndividual indy, ParticleSubSwarmOptimization mainSwarm) { + // get the neighbor in the mainswarm + AbstractEAIndividual neighbor = mainSwarm.getMemberNeighbor(indy); + AbstractEAIndividual worst; + // check if neighbor would "pull the indy away from its niche" because it has a better pbest + AbstractEAIndividual indypbest = (AbstractEAIndividual) indy.getData("PersonalBestKey"); + AbstractEAIndividual neighpbest = (AbstractEAIndividual) neighbor.getData("PersonalBestKey"); - if (true){//neighpbest.isDominating(indypbest)) { - neighbor = generateNeighborFrom(indy,mainSwarm); // neighbor wouldnt help with indies niche - worst = mainSwarm.getParticleWithWorstPBestButNot(indy); // delete another particle for the gnerated neighbor - }else{ - worst = neighbor; // use the neighbor particle and delete it from the mainswarm - } - - Population pop = new Population(2); - pop.add(indy); - pop.add(neighbor); - preparedSubswarm.setPopulation(pop); - preparedSubswarm.populationSizeHasChanged(); - - // remove particles from the main swarm: - mainSwarm.removeSubIndividual(indy); - mainSwarm.removeSubIndividual(worst); - mainSwarm.populationSizeHasChanged(); - } - - private AbstractEAIndividual generateNeighborFrom(AbstractEAIndividual indy, ParticleSubSwarmOptimization mainswarm) { - // generate a neighbor - ESIndividualDoubleData neighbor = (ESIndividualDoubleData)indy.clone(); - MutateESFixedStepSize mutator = new MutateESFixedStepSize(); - mutator.setSigma(getMu()); - neighbor.setMutationOperator(mutator); - neighbor.setMutationProbability(1); - neighbor.mutate(); - //TODO more stuff: stddev ... from indy - //TODO mutate velocity? evaluate? - neighbor.putData("BestFitness", neighbor.getFitness()); - neighbor.putData("BestPosition", neighbor.getDGenotype()); - return neighbor; - } + if (true) {//neighpbest.isDominating(indypbest)) { + neighbor = generateNeighborFrom(indy, mainSwarm); // neighbor wouldnt help with indies niche + worst = mainSwarm.getParticleWithWorstPBestButNot(indy); // delete another particle for the gnerated neighbor + } else { + worst = neighbor; // use the neighbor particle and delete it from the mainswarm + } -/********************************************************************************************************************** - * getter, setter - */ - - public void setMu( - double generateNeighborWithMutationStep) { - this.mu = generateNeighborWithMutationStep; - } + Population pop = new Population(2); + pop.add(indy); + pop.add(neighbor); + preparedSubswarm.setPopulation(pop); + preparedSubswarm.populationSizeHasChanged(); + + // remove particles from the main swarm: + mainSwarm.removeSubIndividual(indy); + mainSwarm.removeSubIndividual(worst); + mainSwarm.populationSizeHasChanged(); + } + + private AbstractEAIndividual generateNeighborFrom(AbstractEAIndividual indy, ParticleSubSwarmOptimization mainswarm) { + // generate a neighbor + ESIndividualDoubleData neighbor = (ESIndividualDoubleData) indy.clone(); + MutateESFixedStepSize mutator = new MutateESFixedStepSize(); + mutator.setSigma(getMu()); + neighbor.setMutationOperator(mutator); + neighbor.setMutationProbability(1); + neighbor.mutate(); + //TODO more stuff: stddev ... from indy + //TODO mutate velocity? evaluate? + neighbor.putData("BestFitness", neighbor.getFitness()); + neighbor.putData("BestPosition", neighbor.getDGenotype()); + return neighbor; + } + + /** + * ******************************************************************************************************************* + * getter, setter + */ + + public void setMu( + double generateNeighborWithMutationStep) { + this.mu = generateNeighborWithMutationStep; + } + + public double getMu() { + return mu; + } + + public String muTipText() { + return "mutation step size used to generate a neighbor"; + } - public double getMu() { - return mu; - } - - public String muTipText(){ - return "mutation step size used to generate a neighbor"; - } - } diff --git a/src/eva2/optimization/operator/nichepso/subswarmcreation/InterfaceSubswarmCreationStrategy.java b/src/eva2/optimization/operator/nichepso/subswarmcreation/InterfaceSubswarmCreationStrategy.java index f7660fd6..f82ad131 100644 --- a/src/eva2/optimization/operator/nichepso/subswarmcreation/InterfaceSubswarmCreationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/subswarmcreation/InterfaceSubswarmCreationStrategy.java @@ -8,28 +8,28 @@ import eva2.optimization.strategies.ParticleSubSwarmOptimization; */ public interface InterfaceSubswarmCreationStrategy { - /** @tested - * decides whether a subswarm should be created for the given indy and mainswarm according to the creation strategie - * @param indy - * @param mainswarm - * @return - */ - public abstract boolean shouldCreateSubswarm( - AbstractEAIndividual indy, - ParticleSubSwarmOptimization mainswarm); - - /** @tested - * creates a subswarm from indy, the details depend on the concrete strategy. - * @param preparedSubswarm a subswarm which is appropriatly prepared - * (ie its problem, optimization strategy etc. are set correctly from the "meta-optimizer") - * Afterwards the subswarm containes the generated particles - * @param indy a particle from which a subswarm should be created - * @param mainSwarm the main swarm which contains indy - */ - public abstract void createSubswarm( - ParticleSubSwarmOptimization preparedSubswarm, - AbstractEAIndividual indy, - ParticleSubSwarmOptimization mainSwarm); + /** + * @param indy + * @param mainswarm + * @return + * @tested decides whether a subswarm should be created for the given indy and mainswarm according to the creation strategie + */ + public abstract boolean shouldCreateSubswarm( + AbstractEAIndividual indy, + ParticleSubSwarmOptimization mainswarm); - public abstract Object clone(); + /** + * @param preparedSubswarm a subswarm which is appropriatly prepared + * (ie its problem, optimization strategy etc. are set correctly from the "meta-optimizer") + * Afterwards the subswarm containes the generated particles + * @param indy a particle from which a subswarm should be created + * @param mainSwarm the main swarm which contains indy + * @tested creates a subswarm from indy, the details depend on the concrete strategy. + */ + public abstract void createSubswarm( + ParticleSubSwarmOptimization preparedSubswarm, + AbstractEAIndividual indy, + ParticleSubSwarmOptimization mainSwarm); + + public abstract Object clone(); } diff --git a/src/eva2/optimization/operator/nichepso/subswarmcreation/StandardSubswarmCreationStrategy.java b/src/eva2/optimization/operator/nichepso/subswarmcreation/StandardSubswarmCreationStrategy.java index 7141fcab..a74bba43 100644 --- a/src/eva2/optimization/operator/nichepso/subswarmcreation/StandardSubswarmCreationStrategy.java +++ b/src/eva2/optimization/operator/nichepso/subswarmcreation/StandardSubswarmCreationStrategy.java @@ -6,117 +6,119 @@ import eva2.optimization.strategies.NichePSO; import eva2.optimization.strategies.ParticleSubSwarmOptimization; /** - * The standard deviation in the fitness of each main swarm particle over the last 3 iterations is calculated. - * If this standard deviation falls below a given threshold delta it is assumed - * that the particle is converging on an optimum and a subswarm is created with that particle and its topological neighbor. - * The strategy is proposed in [1] suggesting a value of delta = 0.0001. - * [1] R. Brits, A. P. Engelbrecht and B. Bergh. - * A Niching Particle Swarm Optimizer - * In Proceedings of the 4th Asia-Pacific Conference on Simulated Evolution and Learning (SEAL'02), - * 2002, 2, 692-696 + * The standard deviation in the fitness of each main swarm particle over the last 3 iterations is calculated. + * If this standard deviation falls below a given threshold delta it is assumed + * that the particle is converging on an optimum and a subswarm is created with that particle and its topological neighbor. + * The strategy is proposed in [1] suggesting a value of delta = 0.0001. + * [1] R. Brits, A. P. Engelbrecht and B. Bergh. + * A Niching Particle Swarm Optimizer + * In Proceedings of the 4th Asia-Pacific Conference on Simulated Evolution and Learning (SEAL'02), + * 2002, 2, 692-696 */ public class StandardSubswarmCreationStrategy implements InterfaceSubswarmCreationStrategy, java.io.Serializable { - protected double delta = 0.0001; // "experimentally found to be effective" according to "a niching particle swarm optimizer" by Brits et al. - - public StandardSubswarmCreationStrategy(double theDelta) { - delta = theDelta; - } - - public StandardSubswarmCreationStrategy() { - delta = 0.0001; - } - + protected double delta = 0.0001; // "experimentally found to be effective" according to "a niching particle swarm optimizer" by Brits et al. + + public StandardSubswarmCreationStrategy(double theDelta) { + delta = theDelta; + } + + public StandardSubswarmCreationStrategy() { + delta = 0.0001; + } + @Override - public Object clone(){ - return (Object) new StandardSubswarmCreationStrategy(delta); - } - - public String globalInfo(){ - return "Strategy to create subswarms from the main swarm"; - } - + public Object clone() { + return (Object) new StandardSubswarmCreationStrategy(delta); + } + + public String globalInfo() { + return "Strategy to create subswarms from the main swarm"; + } + /********************************************************************************************************************** * shouldCreateSubswarm - */ - /** @tested junit - * true if the stddev of the particles fitness < delta and no constraints are violated - * @param indy main swarm particle - * @return - */ + */ + /** + * @param indy main swarm particle + * @return + * @tested junit + * true if the stddev of the particles fitness < delta and no constraints are violated + */ @Override - public boolean shouldCreateSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization mainswarm) { - if (createSubswarmConstraintViolation(indy, mainswarm)){ - return false; - } - - // check for stddev < delta condition - double stddev = (((Double)indy.getData(NichePSO.stdDevKey))).doubleValue(); - if (stddev >= getDelta()){ - return false; - } + public boolean shouldCreateSubswarm(AbstractEAIndividual indy, ParticleSubSwarmOptimization mainswarm) { + if (createSubswarmConstraintViolation(indy, mainswarm)) { + return false; + } - return true; - } - - /** @tested junit - * true, if reasons exist why no subswarm should be created from indy. - * Reasons like: - * poor fitness (not implemented), - * convergence on plateau (not implemented), - * indy is the only particle in the mainswarm and therefor has no neighbor - * @param indy main swarm particle - * @return - */ - public boolean createSubswarmConstraintViolation(AbstractEAIndividual indy, ParticleSubSwarmOptimization mainswarm){ - boolean result = false; - - // check for MainSwarm-Size - if (mainswarm.getPopulation().size() < 2){ - //if (verbose) System.out.print("createSubswarmConstraintViolation: MainSwarm too small, no subswarm can be created\n"); - result = true; - } - - return result; - } + // check for stddev < delta condition + double stddev = (((Double) indy.getData(NichePSO.stdDevKey))).doubleValue(); + if (stddev >= getDelta()) { + return false; + } + + return true; + } + + /** + * @param indy main swarm particle + * @return + * @tested junit + * true, if reasons exist why no subswarm should be created from indy. + * Reasons like: + * poor fitness (not implemented), + * convergence on plateau (not implemented), + * indy is the only particle in the mainswarm and therefor has no neighbor + */ + public boolean createSubswarmConstraintViolation(AbstractEAIndividual indy, ParticleSubSwarmOptimization mainswarm) { + boolean result = false; + + // check for MainSwarm-Size + if (mainswarm.getPopulation().size() < 2) { + //if (verbose) System.out.print("createSubswarmConstraintViolation: MainSwarm too small, no subswarm can be created\n"); + result = true; + } + + return result; + } /********************************************************************************************************************** * createSubswarm - */ + */ - /** @tested - * creates a subswarm from the given particle and its neighbor in the mainswarm, - * then deletes the two particles from the mainswarm. - * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceSubswarmCreationStrategy#createSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) - */ + /** + * @tested creates a subswarm from the given particle and its neighbor in the mainswarm, + * then deletes the two particles from the mainswarm. + * (non-Javadoc) @see javaeva.server.oa.go.Operators.NichePSO.InterfaceSubswarmCreationStrategy#createSubswarm(javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization, javaeva.server.oa.go.EAIndividuals.AbstractEAIndividual, javaeva.server.oa.go.Strategies.ParticleSubSwarmOptimization) + */ @Override - public void createSubswarm(ParticleSubSwarmOptimization preparedSubswarm, AbstractEAIndividual indy, ParticleSubSwarmOptimization mainSwarm) { - - // get the neighbor to create the subswarm - AbstractEAIndividual neighbor = mainSwarm.getMemberNeighbor(indy); - - Population pop = new Population(2); - pop.add(indy); - pop.add(neighbor); - preparedSubswarm.setPopulation(pop); - preparedSubswarm.populationSizeHasChanged(); - - // remove particles from the main swarm: - mainSwarm.removeSubIndividual(indy); - mainSwarm.removeSubIndividual(neighbor); - mainSwarm.populationSizeHasChanged(); - } + public void createSubswarm(ParticleSubSwarmOptimization preparedSubswarm, AbstractEAIndividual indy, ParticleSubSwarmOptimization mainSwarm) { - public double getDelta() { - return delta; - } + // get the neighbor to create the subswarm + AbstractEAIndividual neighbor = mainSwarm.getMemberNeighbor(indy); + + Population pop = new Population(2); + pop.add(indy); + pop.add(neighbor); + preparedSubswarm.setPopulation(pop); + preparedSubswarm.populationSizeHasChanged(); + + // remove particles from the main swarm: + mainSwarm.removeSubIndividual(indy); + mainSwarm.removeSubIndividual(neighbor); + mainSwarm.populationSizeHasChanged(); + } + + public double getDelta() { + return delta; + } + + public void setDelta(double delta) { + this.delta = delta; + } + + public String deltaTipText() { + return "threshold used to identify converging particles which lead to the creation of subswarms"; + } - public void setDelta(double delta) { - this.delta = delta; - } - - public String deltaTipText(){ - return "threshold used to identify converging particles which lead to the creation of subswarms"; - } - } diff --git a/src/eva2/optimization/operator/paramcontrol/AbstractLinearParamAdaption.java b/src/eva2/optimization/operator/paramcontrol/AbstractLinearParamAdaption.java index 3a8a929e..83b2c4be 100644 --- a/src/eva2/optimization/operator/paramcontrol/AbstractLinearParamAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/AbstractLinearParamAdaption.java @@ -3,70 +3,77 @@ package eva2.optimization.operator.paramcontrol; import eva2.gui.BeanInspector; import eva2.optimization.population.Population; import eva2.tools.math.Mathematics; + import java.io.Serializable; /** * Simple linear adaption of a String property. - * - * @author mkron * + * @author mkron */ public abstract class AbstractLinearParamAdaption implements ParamAdaption, Serializable { - private double startV=0.7, endV=0.2; + private double startV = 0.7, endV = 0.2; - public AbstractLinearParamAdaption(AbstractLinearParamAdaption o) { - startV=o.startV; - endV=o.endV; - } - - public AbstractLinearParamAdaption(double startValue, double endValue) { - this.startV = startValue; - this.endV = endValue; - } - - @Override - public abstract Object clone(); - - @Override - public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { - return Mathematics.linearInterpolation(iteration, 0, maxIteration, startV, endV); - } + public AbstractLinearParamAdaption(AbstractLinearParamAdaption o) { + startV = o.startV; + endV = o.endV; + } + + public AbstractLinearParamAdaption(double startValue, double endValue) { + this.startV = startValue; + this.endV = endValue; + } @Override - public abstract String getControlledParam(); - public String controlledParamTipText() { - return "The name of the parameter to be controlled by this adaption scheme."; - } + public abstract Object clone(); @Override - public void init(Object obj, Population pop, Object[] initialValues) { - BeanInspector.setMem(obj, getControlledParam(), startV); - } - @Override - public void finish(Object obj, Population pop) {} - - public double getStartV() { - return startV; - } - public void setStartV(double startV) { - this.startV = startV; - } - public String startVTipText() { - return "The initial value."; - } + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { + return Mathematics.linearInterpolation(iteration, 0, maxIteration, startV, endV); + } - public double getEndV() { - return endV; - } - public void setEndV(double endV) { - this.endV = endV; - } - public String endVTipText() { - return "The final value."; - } - - public String getName() { - return "Lin.adpt." + getControlledParam() + "(" + startV + "-" + endV + ")"; - } + @Override + public abstract String getControlledParam(); + + public String controlledParamTipText() { + return "The name of the parameter to be controlled by this adaption scheme."; + } + + @Override + public void init(Object obj, Population pop, Object[] initialValues) { + BeanInspector.setMem(obj, getControlledParam(), startV); + } + + @Override + public void finish(Object obj, Population pop) { + } + + public double getStartV() { + return startV; + } + + public void setStartV(double startV) { + this.startV = startV; + } + + public String startVTipText() { + return "The initial value."; + } + + public double getEndV() { + return endV; + } + + public void setEndV(double endV) { + this.endV = endV; + } + + public String endVTipText() { + return "The final value."; + } + + public String getName() { + return "Lin.adpt." + getControlledParam() + "(" + startV + "-" + endV + ")"; + } } diff --git a/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java b/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java index 2aea7459..a12d41c5 100644 --- a/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java +++ b/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java @@ -4,87 +4,88 @@ import eva2.gui.BeanInspector; import eva2.optimization.population.Population; /** - * Convenience class. Besides the init() method, two more remain to be implemented: + * Convenience class. Besides the init() method, two more remain to be implemented: * the first one to retrieve an array of strings with the canonical names of the controlled parameters, * and the second one to produce an object array of the same length with the values to be assigned * at the iteration. If there is no iteration known, iteration counts will be set to -1. - * + *

* This class can be used to implement strategies to adapt multiple parameters within one strategy. * For single parameter adaption, better use the ParamAdaption inheritance tree and the ParameterControlManager class. - * - * @author mkron * + * @author mkron */ public abstract class AbstractParameterControl implements InterfaceParameterControl { - public Object[] initialValues = null; - protected static boolean TRACE=false; - - public AbstractParameterControl() { } - - public AbstractParameterControl(AbstractParameterControl o) { - initialValues = o.initialValues.clone(); - } - - @Override - public abstract Object clone(); - - @Override - public void init(Object obj, Population initialPop) { - String[] params = getControlledParameters(); - if (params != null) { - initialValues=new Object[params.length]; - for (int i=0; i= 0 && (interestingRatio < minInterestingRatio)) { // performance too bad - // reduce period --> increase frequency - adaptValue(decFact, pop); - } else if (interestingRatio > maxInterestingRatio) { // performance is too good - // increase period --> decrease frequency - adaptValue(incFact, pop); - } - if (oldVal!=currentVal) { + private void checkForAdaption(CBNPSO cbpso, Population pop, + int iteration, int maxIteration) { + // How to find out if we are in need of improvement? + double oldVal = currentVal; + + if (isPossibleAdaptionTime(pop)) { + double interestingRatio = cbpso.getInterestingSolutionRatio(); + if (interestingRatio >= 0 && (interestingRatio < minInterestingRatio)) { // performance too bad + // reduce period --> increase frequency + adaptValue(decFact, pop); + } else if (interestingRatio > maxInterestingRatio) { // performance is too good + // increase period --> decrease frequency + adaptValue(incFact, pop); + } + if (oldVal != currentVal) { // System.out.println("++ Changed period at it." + iteration // + ", ratio " + interestingRatio + " from " + oldVal + " to " + currentVal); - setShift(cbpso, pop, oldVal, currentVal); - } - } - } - - private void setShift(CBNPSO cbpso, Population pop, double oldVal, double currentVal2) { - double k = pop.getFunctionCalls()/currentVal; - int diff = (int) (pop.getFunctionCalls()-(((int)k)*currentVal)); - - cbpso.setSigmaAdaptionShift(diff); - - } - - private void adaptValue(double fact, Population pop) { - currentVal *= fact; - currentVal = Math.max(lowerBnd, Math.min(upperBnd, currentVal)); - lastAdaption = pop.getGeneration(); - adptIntervalGenerations = (int)(currentVal/pop.getTargetSize()); - } - - private boolean isPossibleAdaptionTime(Population pop) { - if (lastAdaption+adptIntervalGenerations>pop.getGeneration()) { - return false; + setShift(cbpso, pop, oldVal, currentVal); } - else { - return true; - } - } + } + } - /* - * (non-Javadoc) - * @see eva2.optimization.operators.paramcontrol.ParamAdaption#finish(java.lang.Object, eva2.optimization.populations.Population) - */ + private void setShift(CBNPSO cbpso, Population pop, double oldVal, double currentVal2) { + double k = pop.getFunctionCalls() / currentVal; + int diff = (int) (pop.getFunctionCalls() - (((int) k) * currentVal)); + + cbpso.setSigmaAdaptionShift(diff); + + } + + private void adaptValue(double fact, Population pop) { + currentVal *= fact; + currentVal = Math.max(lowerBnd, Math.min(upperBnd, currentVal)); + lastAdaption = pop.getGeneration(); + adptIntervalGenerations = (int) (currentVal / pop.getTargetSize()); + } + + private boolean isPossibleAdaptionTime(Population pop) { + if (lastAdaption + adptIntervalGenerations > pop.getGeneration()) { + return false; + } else { + return true; + } + } + + /* + * (non-Javadoc) + * @see eva2.optimization.operators.paramcontrol.ParamAdaption#finish(java.lang.Object, eva2.optimization.populations.Population) + */ @Override - public void finish(Object obj, Population pop) { - - } + public void finish(Object obj, Population pop) { - /* - * (non-Javadoc) - * @see eva2.optimization.operators.paramcontrol.ParamAdaption#getControlledParam() - */ + } + + /* + * (non-Javadoc) + * @see eva2.optimization.operators.paramcontrol.ParamAdaption#getControlledParam() + */ @Override - public String getControlledParam() { - return paramName; - } + public String getControlledParam() { + return paramName; + } - /* - * (non-Javadoc) - * @see eva2.optimization.operators.paramcontrol.ParamAdaption#init(java.lang.Object, eva2.optimization.populations.Population, java.lang.Object[]) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.operators.paramcontrol.ParamAdaption#init(java.lang.Object, eva2.optimization.populations.Population, java.lang.Object[]) + */ @Override - public void init(Object obj, Population pop, Object[] initialValues) { - currentVal=initialVal; - lastAdaption=0; - adptIntervalGenerations = (int)(currentVal/pop.getTargetSize()); - } + public void init(Object obj, Population pop, Object[] initialValues) { + currentVal = initialVal; + lastAdaption = 0; + adptIntervalGenerations = (int) (currentVal / pop.getTargetSize()); + } - /* - * (non-Javadoc) - * @see eva2.optimization.operators.paramcontrol.GenericParamAdaption#setControlledParam(java.lang.String) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.operators.paramcontrol.GenericParamAdaption#setControlledParam(java.lang.String) + */ @Override - public void setControlledParam(String prm) { - paramName = prm; - } + public void setControlledParam(String prm) { + paramName = prm; + } - /** - * - * @param initialVal - */ - public void setInitialVal(double initialVal) { - this.initialVal = initialVal; - } + /** + * @param initialVal + */ + public void setInitialVal(double initialVal) { + this.initialVal = initialVal; + } + + /** + * @return + */ + public double getInitialVal() { + return initialVal; + } - /** - * - * @return - */ - public double getInitialVal() { - return initialVal; - } - } diff --git a/src/eva2/optimization/operator/paramcontrol/ConstantParameters.java b/src/eva2/optimization/operator/paramcontrol/ConstantParameters.java index 08227782..a2fdd657 100644 --- a/src/eva2/optimization/operator/paramcontrol/ConstantParameters.java +++ b/src/eva2/optimization/operator/paramcontrol/ConstantParameters.java @@ -1,41 +1,42 @@ package eva2.optimization.operator.paramcontrol; import eva2.optimization.population.Population; + import java.io.Serializable; /** * Dummy implementation. This class is ignored by the Processor. Parameters will not be changed. - * - * @author mkron * + * @author mkron */ public class ConstantParameters extends AbstractParameterControl implements Serializable { - public ConstantParameters() {} - - public ConstantParameters(ConstantParameters o) { - super(o); - } + public ConstantParameters() { + } - @Override - public Object clone() { - return new ConstantParameters(this); - } - - @Override - public String[] getControlledParameters() { - return null; - } - - @Override - public Object[] getValues(Object obj, Population pop, int iteration, int maxIteration) { - return null; - } + public ConstantParameters(ConstantParameters o) { + super(o); + } @Override - public void updateParameters(Object obj) { - } - - public static String globalInfo() { - return "Parameters will not be changed."; - } + public Object clone() { + return new ConstantParameters(this); + } + + @Override + public String[] getControlledParameters() { + return null; + } + + @Override + public Object[] getValues(Object obj, Population pop, int iteration, int maxIteration) { + return null; + } + + @Override + public void updateParameters(Object obj) { + } + + public static String globalInfo() { + return "Parameters will not be changed."; + } } diff --git a/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java b/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java index 45432178..964e9a6a 100644 --- a/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java @@ -4,6 +4,7 @@ import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.operator.constraint.AbstractConstraint; import eva2.optimization.population.Population; import eva2.tools.math.Mathematics; + import java.io.Serializable; import java.util.LinkedList; @@ -12,193 +13,200 @@ import java.util.LinkedList; * If the best individual was always feasible for k generations, the penalty factor is decreased, * if it was always infeasible, the penalty factor is increased. For other cases, the penalty remains the same. * This is plausible for the typical case that the optimum lies near the constraint boundary, however it makes - * the fitness function change dynamically based only on the positions of last best indidivuals. - * - * The authors advise to select betaInc != 1./betaDec to avoid cycling. - * @author mkron + * the fitness function change dynamically based only on the positions of last best indidivuals. + *

+ * The authors advise to select betaInc != 1./betaDec to avoid cycling. * + * @author mkron */ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { - private double betaInc=1.5; - private double betaDec=0.7; - private double initialPenalty = 1.; - private double minPenalty=0.01; - private double maxPenalty=100.; - private double currentFactor = 1.; - private int genGap=5; - - LinkedList lastBestSatisfactionState = new LinkedList(); - -// private double endAct=0; + private double betaInc = 1.5; + private double betaDec = 0.7; + private double initialPenalty = 1.; + private double minPenalty = 0.01; + private double maxPenalty = 100.; + private double currentFactor = 1.; + private int genGap = 5; + + LinkedList lastBestSatisfactionState = new LinkedList(); + + // private double endAct=0; // private double deltaInertness = 0.1; - private static boolean TRACE=false; - - private static String target = "penaltyFactor"; - - public ConstraintBasedAdaption() {}; - - public ConstraintBasedAdaption( - ConstraintBasedAdaption o) { - betaInc = o.betaInc; - betaDec = o.betaDec; - genGap = o.genGap; + private static boolean TRACE = false; + + private static String target = "penaltyFactor"; + + public ConstraintBasedAdaption() { + } + + ; + + public ConstraintBasedAdaption( + ConstraintBasedAdaption o) { + betaInc = o.betaInc; + betaDec = o.betaDec; + genGap = o.genGap; // endAct = o.endAct; // deltaInertness = o.deltaInertness; - } + } @Override - public Object clone() { - return new ConstraintBasedAdaption(this); - } + public Object clone() { + return new ConstraintBasedAdaption(this); + } @Override - public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { - boolean changed = false; - if (!(obj instanceof AbstractConstraint)) { - System.err.println(this.getClass().getSimpleName() + " cant control " + obj.getClass().getSimpleName() + " ! "); + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { + boolean changed = false; + if (!(obj instanceof AbstractConstraint)) { + System.err.println(this.getClass().getSimpleName() + " cant control " + obj.getClass().getSimpleName() + " ! "); + } else { + if (TRACE) { + System.out.println("calc value at it " + iteration + " of " + maxIteration); } - else { - if (TRACE) { - System.out.println("calc value at it " + iteration + " of " + maxIteration); - } - if (lastBestSatisfactionState.size()==genGap) { - lastBestSatisfactionState.poll(); - } - boolean bestIsFeasible = ((AbstractConstraint)obj).isSatisfied(((InterfaceDataTypeDouble)pop.getBestEAIndividual()).getDoubleDataWithoutUpdate()); - if (!lastBestSatisfactionState.offer(bestIsFeasible)) { - System.err.println("Error, could not push best indy state!"); - } - - changed=maybeAdaptFactor((AbstractConstraint)obj); - } - double curPen = initialPenalty * currentFactor; - if (curPen maxPenalty) { - currentFactor = maxPenalty/initialPenalty; - curPen=maxPenalty; - } - if (TRACE && changed) { - System.out.println("NEW penalty: " + curPen); + if (lastBestSatisfactionState.size() == genGap) { + lastBestSatisfactionState.poll(); } - return curPen; - } - - private boolean maybeAdaptFactor(AbstractConstraint constr) { - boolean changed = false; - if (lastBestSatisfactionState.size() >= genGap) { - boolean allValid=true; - boolean allInvalid=true; - for (Boolean isFeasible : lastBestSatisfactionState) { - if (isFeasible) { - allInvalid=false; - } - else { - allValid=false; - } - } - if (allValid) { - currentFactor*=betaDec; - changed=true; - if (TRACE) { - System.out.println("all valid, new fact is " + currentFactor + " times " + initialPenalty); - } - } else if (allInvalid) { - changed=true; - currentFactor*=betaInc; - if (TRACE) { - System.out.println("all invalid, new fact is " + currentFactor + " times " + initialPenalty); - } - } - } else if (TRACE) { - System.out.println("not yet looking at " + genGap + " individuals..."); + boolean bestIsFeasible = ((AbstractConstraint) obj).isSatisfied(((InterfaceDataTypeDouble) pop.getBestEAIndividual()).getDoubleDataWithoutUpdate()); + if (!lastBestSatisfactionState.offer(bestIsFeasible)) { + System.err.println("Error, could not push best indy state!"); } - return changed; - } + + changed = maybeAdaptFactor((AbstractConstraint) obj); + } + double curPen = initialPenalty * currentFactor; + if (curPen < minPenalty) { + currentFactor = minPenalty / initialPenalty; + curPen = minPenalty; + } else if (curPen > maxPenalty) { + currentFactor = maxPenalty / initialPenalty; + curPen = maxPenalty; + } + if (TRACE && changed) { + System.out.println("NEW penalty: " + curPen); + } + return curPen; + } + + private boolean maybeAdaptFactor(AbstractConstraint constr) { + boolean changed = false; + if (lastBestSatisfactionState.size() >= genGap) { + boolean allValid = true; + boolean allInvalid = true; + for (Boolean isFeasible : lastBestSatisfactionState) { + if (isFeasible) { + allInvalid = false; + } else { + allValid = false; + } + } + if (allValid) { + currentFactor *= betaDec; + changed = true; + if (TRACE) { + System.out.println("all valid, new fact is " + currentFactor + " times " + initialPenalty); + } + } else if (allInvalid) { + changed = true; + currentFactor *= betaInc; + if (TRACE) { + System.out.println("all invalid, new fact is " + currentFactor + " times " + initialPenalty); + } + } + } else if (TRACE) { + System.out.println("not yet looking at " + genGap + " individuals..."); + } + return changed; + } @Override - public String getControlledParam() { - return target; - } + public String getControlledParam() { + return target; + } - public double getBetaInc() { - return betaInc; - } - public void setBetaInc(double d) { - this.betaInc = d; - } - public String betaIncTipText() { - return "The increase factor for the penalty."; - } - - public double getBetaDec() { - return betaDec; - } - public void setBetaDec(double d) { - this.betaDec = d; - } - public String betaDecTipText() { - return "The decrease factor for the penalty."; - } - - public int getGenGap() { - return genGap; - } - public void setGenGap(int v) { - this.genGap = v; - } - public String genGapTipText() { - return "The number of generations regarded."; - } + public double getBetaInc() { + return betaInc; + } - public static String globalInfo() { - return "Adapt a constraint's penalty factor (esp. fitness based) if the population contained only valid or only invalid individuals for some generations."; - } - - @Override - public void finish(Object obj, Population pop) { - lastBestSatisfactionState.clear(); - ((AbstractConstraint) obj).setPenaltyFactor(initialPenalty); - } + public void setBetaInc(double d) { + this.betaInc = d; + } + + public String betaIncTipText() { + return "The increase factor for the penalty."; + } + + public double getBetaDec() { + return betaDec; + } + + public void setBetaDec(double d) { + this.betaDec = d; + } + + public String betaDecTipText() { + return "The decrease factor for the penalty."; + } + + public int getGenGap() { + return genGap; + } + + public void setGenGap(int v) { + this.genGap = v; + } + + public String genGapTipText() { + return "The number of generations regarded."; + } + + public static String globalInfo() { + return "Adapt a constraint's penalty factor (esp. fitness based) if the population contained only valid or only invalid individuals for some generations."; + } @Override - public void init(Object obj, Population pop, Object[] initialValues) { - initialPenalty = ((AbstractConstraint) obj).getPenaltyFactor(); - if (minPenalty > maxPenalty) { - System.err.println("Error in " + this.getClass().getSimpleName() + ", inconsistent penalty factor restrictions!"); - } - initialPenalty = Mathematics.projectValue(initialPenalty, minPenalty, maxPenalty); - lastBestSatisfactionState.clear(); - currentFactor=1.; - } + public void finish(Object obj, Population pop) { + lastBestSatisfactionState.clear(); + ((AbstractConstraint) obj).setPenaltyFactor(initialPenalty); + } - public double getMinPenalty() { - return minPenalty; - } + @Override + public void init(Object obj, Population pop, Object[] initialValues) { + initialPenalty = ((AbstractConstraint) obj).getPenaltyFactor(); + if (minPenalty > maxPenalty) { + System.err.println("Error in " + this.getClass().getSimpleName() + ", inconsistent penalty factor restrictions!"); + } + initialPenalty = Mathematics.projectValue(initialPenalty, minPenalty, maxPenalty); + lastBestSatisfactionState.clear(); + currentFactor = 1.; + } - public void setMinPenalty(double minPenalty) { - this.minPenalty = minPenalty; - } - - public String minPenaltyTipText() { - return "The minimum penalty factor."; - } + public double getMinPenalty() { + return minPenalty; + } - public double getMaxPenalty() { - return maxPenalty; - } + public void setMinPenalty(double minPenalty) { + this.minPenalty = minPenalty; + } - public void setMaxPenalty(double maxPenalty) { - this.maxPenalty = maxPenalty; - } - - public String maxPenaltyTipText() { - return "The maximum penalty factor."; - } - - public String getName() { - return "Adaptive penalty factor"; - } + public String minPenaltyTipText() { + return "The minimum penalty factor."; + } + + public double getMaxPenalty() { + return maxPenalty; + } + + public void setMaxPenalty(double maxPenalty) { + this.maxPenalty = maxPenalty; + } + + public String maxPenaltyTipText() { + return "The maximum penalty factor."; + } + + public String getName() { + return "Adaptive penalty factor"; + } } diff --git a/src/eva2/optimization/operator/paramcontrol/ExponentialDecayAdaption.java b/src/eva2/optimization/operator/paramcontrol/ExponentialDecayAdaption.java index 2ec6e87c..55c7b01f 100644 --- a/src/eva2/optimization/operator/paramcontrol/ExponentialDecayAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/ExponentialDecayAdaption.java @@ -1,110 +1,120 @@ package eva2.optimization.operator.paramcontrol; import eva2.optimization.population.Population; + import java.io.Serializable; /** * Adapt a generic parameter using exponential decay. - * - * @author mkron * + * @author mkron */ public class ExponentialDecayAdaption implements ParamAdaption, GenericParamAdaption, Serializable { - private double startValue=0.2, halvingTimePerCent=50; - private double saturation=0.; - private String target = "undefinedParameter"; - - public ExponentialDecayAdaption() { - } - - public ExponentialDecayAdaption(double startV, double halvingTimePC, String param) { - this(startV, halvingTimePC, 0., param); - } - public ExponentialDecayAdaption(double startV, double halvingTimePC, double offset, String param) { - this.setSaturation(offset); - startValue = startV; - halvingTimePerCent = halvingTimePC; - target = param; - } - - public ExponentialDecayAdaption( - ExponentialDecayAdaption o) { - startValue = o.startValue; - halvingTimePerCent = o.halvingTimePerCent; - target = o.target; - setSaturation(o.getSaturation()); - } + private double startValue = 0.2, halvingTimePerCent = 50; + private double saturation = 0.; + private String target = "undefinedParameter"; + + public ExponentialDecayAdaption() { + } + + public ExponentialDecayAdaption(double startV, double halvingTimePC, String param) { + this(startV, halvingTimePC, 0., param); + } + + public ExponentialDecayAdaption(double startV, double halvingTimePC, double offset, String param) { + this.setSaturation(offset); + startValue = startV; + halvingTimePerCent = halvingTimePC; + target = param; + } + + public ExponentialDecayAdaption( + ExponentialDecayAdaption o) { + startValue = o.startValue; + halvingTimePerCent = o.halvingTimePerCent; + target = o.target; + setSaturation(o.getSaturation()); + } @Override - public Object clone() { - return new ExponentialDecayAdaption(this); - } - + public Object clone() { + return new ExponentialDecayAdaption(this); + } + @Override - public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { - return getSaturation()+(startValue-getSaturation())*Math.pow(0.5, (iteration/(double)maxIteration)*100/halvingTimePerCent); + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { + return getSaturation() + (startValue - getSaturation()) * Math.pow(0.5, (iteration / (double) maxIteration) * 100 / halvingTimePerCent); // return startValue*Math.pow(0.5, (iteration/(double)maxIteration)*100/halvingTimePerCent); - } - @Override - public String getControlledParam() { - return target; - } - - public double getStartValue() { - return startValue; - } - public void setStartValue(double startValue) { - this.startValue = startValue; - } - public String startValueTipText() { - return "The initial starting value at generation zero."; - } - - public double getHalvingTimePerCent() { - return halvingTimePerCent; - } - public void setHalvingTimePerCent(double halvingTimePerCent) { - this.halvingTimePerCent = halvingTimePerCent; - } - public String halvingTimePerCentTipText() { - return "The number of iterations (usually generations) within which the respecitve value will be halved."; - } + } @Override - public void setControlledParam(String target) { - this.target = target; - } - - public String getName() { - return "Exp. adapt. "+target+" ("+startValue + "/" + halvingTimePerCent + ")"; - } - - public static String globalInfo() { - return "Exponential decay with a percentual halving time."; - } + public String getControlledParam() { + return target; + } + + public double getStartValue() { + return startValue; + } + + public void setStartValue(double startValue) { + this.startValue = startValue; + } + + public String startValueTipText() { + return "The initial starting value at generation zero."; + } + + public double getHalvingTimePerCent() { + return halvingTimePerCent; + } + + public void setHalvingTimePerCent(double halvingTimePerCent) { + this.halvingTimePerCent = halvingTimePerCent; + } + + public String halvingTimePerCentTipText() { + return "The number of iterations (usually generations) within which the respecitve value will be halved."; + } @Override - public void finish(Object obj, Population pop) {} + public void setControlledParam(String target) { + this.target = target; + } + + public String getName() { + return "Exp. adapt. " + target + " (" + startValue + "/" + halvingTimePerCent + ")"; + } + + public static String globalInfo() { + return "Exponential decay with a percentual halving time."; + } @Override - public void init(Object obj, Population pop, Object[] initialValues) {} - - public static void main(String[] args) { - ExponentialDecayAdaption eda = new ExponentialDecayAdaption(1, 20, 0.05, ""); - int maxIt = 1000; - for (int i=0; i * Notice how Processor handles parameter control. For now, a controlled object must implement * the method getParamControl() which is to return either an InterfaceParameterControl or an array - * of Objects which should either be instances of InterfaceParameterControl or + * of Objects which should either be instances of InterfaceParameterControl or * themselves should implement getParamControl(). This allows recursive * parameter adaption hierarchies. - * - * @author mkron * + * @author mkron */ public interface InterfaceParameterControl { - - /** - * Make a deep copy of the object. - * @return - */ - public Object clone(); - - /** - * Initialize the parameter control instance before a run. - * - * @param obj The controlled object. - */ - public void init(Object obj, Population initialPop); - - /** - * After an optimization run, finalizing stuff may be done. - * - * @param obj The controlled object. - */ - public void finish(Object obj, Population finalPop); - - /** - * For a given runtime (maxIteration) and current iteration, update the parameters of the object. - * - * @param obj - * @param iteration - * @param maxIteration - */ - public void updateParameters(Object obj, Population pop, int iteration, int maxIteration); - - /** - * If no runtime in terms of iterations can be specified, the parameter control may try to infer - * the state from the object itself. - * - * @param obj - */ - public void updateParameters(Object obj); + + /** + * Make a deep copy of the object. + * + * @return + */ + public Object clone(); + + /** + * Initialize the parameter control instance before a run. + * + * @param obj The controlled object. + */ + public void init(Object obj, Population initialPop); + + /** + * After an optimization run, finalizing stuff may be done. + * + * @param obj The controlled object. + */ + public void finish(Object obj, Population finalPop); + + /** + * For a given runtime (maxIteration) and current iteration, update the parameters of the object. + * + * @param obj + * @param iteration + * @param maxIteration + */ + public void updateParameters(Object obj, Population pop, int iteration, int maxIteration); + + /** + * If no runtime in terms of iterations can be specified, the parameter control may try to infer + * the state from the object itself. + * + * @param obj + */ + public void updateParameters(Object obj); } diff --git a/src/eva2/optimization/operator/paramcontrol/LinearParamAdaption.java b/src/eva2/optimization/operator/paramcontrol/LinearParamAdaption.java index c681e4c5..8f11ddd1 100644 --- a/src/eva2/optimization/operator/paramcontrol/LinearParamAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/LinearParamAdaption.java @@ -5,82 +5,82 @@ import java.io.Serializable; /** * Linearly adapt a specific target String parameter. - * - * @author mkron * + * @author mkron */ -public class LinearParamAdaption extends AbstractLinearParamAdaption -implements InterfaceHasUpperDoubleBound, GenericParamAdaption, Serializable { - String target = "undefinedParameter"; - - public LinearParamAdaption() { - super(0.7,0.2); - target = "undefinedParameter"; - } - - public LinearParamAdaption(LinearParamAdaption o) { - super(o); - target=o.target; - } - - public LinearParamAdaption(String target, double startValue, double endValue) { - super(startValue, endValue); - this.target = target; - } - - @Override - public Object clone() { - return new LinearParamAdaption(this); - } +public class LinearParamAdaption extends AbstractLinearParamAdaption + implements InterfaceHasUpperDoubleBound, GenericParamAdaption, Serializable { + String target = "undefinedParameter"; + + public LinearParamAdaption() { + super(0.7, 0.2); + target = "undefinedParameter"; + } + + public LinearParamAdaption(LinearParamAdaption o) { + super(o); + target = o.target; + } + + public LinearParamAdaption(String target, double startValue, double endValue) { + super(startValue, endValue); + this.target = target; + } @Override - public String getControlledParam() { - return target; - } + public Object clone() { + return new LinearParamAdaption(this); + } + @Override - public void setControlledParam(String target) { - this.target = target; - } - - public static String globalInfo() { - return "Simple linear parameter adaption."; - } - - public String[] customPropertyOrder() { - return new String[] {"startV", "endV"}; - } - - /** - * Return the larger value of the start and end value. - * - * @return - */ + public String getControlledParam() { + return target; + } + @Override - public double getUpperBnd() { - return Math.max(getEndV(), getStartV()); - } - - /** - * Set the larger one of start- or end-value to the given value. If they are - * equal, both are set. - * - * @param u - */ + public void setControlledParam(String target) { + this.target = target; + } + + public static String globalInfo() { + return "Simple linear parameter adaption."; + } + + public String[] customPropertyOrder() { + return new String[]{"startV", "endV"}; + } + + /** + * Return the larger value of the start and end value. + * + * @return + */ @Override - public void SetUpperBnd(double u) { - if (getEndV()==getStartV()) { - setEndV(u); - setStartV(u); - } else if (getEndV()>getStartV()) { // end value is larger - if (u getStartV()) { // end value is larger + if (u < getStartV()) { + System.err.println("Warning, changing direction of linear adaption!"); + } + setEndV(u); + } else { // start value is larger + if (u < getEndV()) { + System.err.println("Warning, changing direction of linear adaption!"); + } + setStartV(u); + } + } } diff --git a/src/eva2/optimization/operator/paramcontrol/NoParamAdaption.java b/src/eva2/optimization/operator/paramcontrol/NoParamAdaption.java index eeaa0589..815e6ffe 100644 --- a/src/eva2/optimization/operator/paramcontrol/NoParamAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/NoParamAdaption.java @@ -1,38 +1,40 @@ package eva2.optimization.operator.paramcontrol; import eva2.optimization.population.Population; + import java.io.Serializable; /** * A dummy implementation which does not do any adaption. - * - * @author mkron * + * @author mkron */ public class NoParamAdaption implements ParamAdaption, Serializable { @Override - public Object clone() { - return new NoParamAdaption(); - } - - @Override - public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { - return null; - } + public Object clone() { + return new NoParamAdaption(); + } @Override - public String getControlledParam() { - return null; - } - - public static String globalInfo() { - return "A dummy implementation which will not change parameters."; - } + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { + return null; + } @Override - public void finish(Object obj, Population pop) {} + public String getControlledParam() { + return null; + } + + public static String globalInfo() { + return "A dummy implementation which will not change parameters."; + } @Override - public void init(Object obj, Population pop, Object[] initialValues) {} + public void finish(Object obj, Population pop) { + } + + @Override + public void init(Object obj, Population pop, Object[] initialValues) { + } } diff --git a/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java b/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java index 4e590467..ef04a1eb 100644 --- a/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java +++ b/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java @@ -3,173 +3,187 @@ package eva2.optimization.operator.paramcontrol; import eva2.optimization.population.Population; import eva2.optimization.strategies.ParticleSwarmOptimization; import eva2.tools.math.Mathematics; + import java.io.Serializable; /** * After the ANTS 08 paper by Yasuda et al., this implements an activity feedback control mechanism. * The inertia of the PSO is made dependent on time and the target activity of the swarm, where activity * here is simply the average relative velocity of the particles. - * The target activity decreases with time, and if the current activity is too low (high), the + * The target activity decreases with time, and if the current activity is too low (high), the * inertia is increased (decreased) so that the activity approximates the target activity. - * + *

* The original authors used an absolute velocity measure and FIPS which is not implemented in EvA2 so far. - * However, after some initial tests, this version seems + * However, after some initial tests, this version seems * to work ok, although it depends on the defined target activity. I am not convinced that in general it is * easier to define than a constant constriction factor for the standard constricted PSO. * Still, the possibility to control the convergence behaviour based on time is nice, and it works quite good on F6, for example. - * - * @author mkron * + * @author mkron */ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable { - private double minInert=0.5; - private double maxInert=1; - private double startAct=0.17; - private double endAct=0.01; - private double deltaInertness = 0.1; - private static boolean TRACE=false; - private boolean exponentialSchedule = true; + private double minInert = 0.5; + private double maxInert = 1; + private double startAct = 0.17; + private double endAct = 0.01; + private double deltaInertness = 0.1; + private static boolean TRACE = false; + private boolean exponentialSchedule = true; - private static String target = "inertnessOrChi"; - - public PSOActivityFeedbackControl() {}; - - public PSOActivityFeedbackControl( - PSOActivityFeedbackControl o) { - minInert = o.minInert; - maxInert = o.maxInert; - startAct = o.startAct; - endAct = o.endAct; - deltaInertness = o.deltaInertness; - } + private static String target = "inertnessOrChi"; + + public PSOActivityFeedbackControl() { + } + + ; + + public PSOActivityFeedbackControl( + PSOActivityFeedbackControl o) { + minInert = o.minInert; + maxInert = o.maxInert; + startAct = o.startAct; + endAct = o.endAct; + deltaInertness = o.deltaInertness; + } @Override - public Object clone() { - return new PSOActivityFeedbackControl(this); - } + public Object clone() { + return new PSOActivityFeedbackControl(this); + } @Override - public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { - if (obj instanceof ParticleSwarmOptimization) { - ParticleSwarmOptimization pso = (ParticleSwarmOptimization)obj; - - double currentAct = calculateActivity(pso); - double currentInertness = pso.getInertnessOrChi(); - Double val = calcNewInertness(currentInertness, currentAct, desiredActivity(iteration, maxIteration)); - return val; - } else { - System.err.println("Cant control this object type!!"); - return null; - } - } + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { + if (obj instanceof ParticleSwarmOptimization) { + ParticleSwarmOptimization pso = (ParticleSwarmOptimization) obj; + + double currentAct = calculateActivity(pso); + double currentInertness = pso.getInertnessOrChi(); + Double val = calcNewInertness(currentInertness, currentAct, desiredActivity(iteration, maxIteration)); + return val; + } else { + System.err.println("Cant control this object type!!"); + return null; + } + } @Override - public String getControlledParam() { - return target; - } + public String getControlledParam() { + return target; + } - private double calcNewInertness(double currentInertness, double currentAct, - double desiredActivity) { - if (TRACE) { - System.out.println("Activity was " + currentAct + ", desired: " + desiredActivity); - } - if (currentAct < desiredActivity) { // increase inertness - return Math.min(maxInert, currentInertness + deltaInertness); - } else if (currentAct > desiredActivity) { // too high act, so decrease inertness - return Math.max(minInert, currentInertness - deltaInertness); - } else { - return currentInertness; - } - } + private double calcNewInertness(double currentInertness, double currentAct, + double desiredActivity) { + if (TRACE) { + System.out.println("Activity was " + currentAct + ", desired: " + desiredActivity); + } + if (currentAct < desiredActivity) { // increase inertness + return Math.min(maxInert, currentInertness + deltaInertness); + } else if (currentAct > desiredActivity) { // too high act, so decrease inertness + return Math.max(minInert, currentInertness - deltaInertness); + } else { + return currentInertness; + } + } - private double desiredActivity(int iteration, int maxIteration) { - if (exponentialSchedule) { - return startAct*Math.pow(endAct/startAct, iteration/(double)maxIteration); - } - else { - return Mathematics.linearInterpolation(iteration, 0, maxIteration, startAct, endAct); - } - } + private double desiredActivity(int iteration, int maxIteration) { + if (exponentialSchedule) { + return startAct * Math.pow(endAct / startAct, iteration / (double) maxIteration); + } else { + return Mathematics.linearInterpolation(iteration, 0, maxIteration, startAct, endAct); + } + } - private double calculateActivity(ParticleSwarmOptimization pso) { - return pso.getPopulationAvgNormedVelocity(pso.getPopulation()); - } + private double calculateActivity(ParticleSwarmOptimization pso) { + return pso.getPopulationAvgNormedVelocity(pso.getPopulation()); + } - public double getMinInertness() { - return minInert; - } - public void setMinInertness(double minInert) { - this.minInert = minInert; - } - public String minInertnessTipText() { - return "The minimum inertness value to be used."; - } - - public double getMaxInertness() { - return maxInert; - } - public void setMaxInertness(double maxInert) { - this.maxInert = maxInert; - } - public String maxInertnessTipText() { - return "The maximum inertness value to be used."; - } - - public double getInitActivity() { - return startAct; - } - public void setInitActivity(double startAct) { - this.startAct = startAct; - } - public String initActivityTipText() { - return "The initial target activity (relative to the range)."; - } + public double getMinInertness() { + return minInert; + } - public double getFinalActivity() { - return endAct; - } - public void setFinalActivity(double endAct) { - this.endAct = endAct; - if (endAct==0 && isExponentialSchedule()) { - System.err.println("Warning: zero final activity will not work with exponential schedule, set it to small epsilon!"); - } - } - public String finalActivityTipText() { - return "The final target activity (relative to the range), should be close to zero."; - } - - public double getDeltaInertness() { - return deltaInertness; - } - public void setDeltaInertness(double deltaInertness) { - this.deltaInertness = deltaInertness; - } - public String deltaInertnessTipText() { - return "The additive change of the inertness in each adaption step."; - } - - public static String globalInfo() { - return "Controls the inertness factor based on the average velocity."; - } + public void setMinInertness(double minInert) { + this.minInert = minInert; + } + + public String minInertnessTipText() { + return "The minimum inertness value to be used."; + } + + public double getMaxInertness() { + return maxInert; + } + + public void setMaxInertness(double maxInert) { + this.maxInert = maxInert; + } + + public String maxInertnessTipText() { + return "The maximum inertness value to be used."; + } + + public double getInitActivity() { + return startAct; + } + + public void setInitActivity(double startAct) { + this.startAct = startAct; + } + + public String initActivityTipText() { + return "The initial target activity (relative to the range)."; + } + + public double getFinalActivity() { + return endAct; + } + + public void setFinalActivity(double endAct) { + this.endAct = endAct; + if (endAct == 0 && isExponentialSchedule()) { + System.err.println("Warning: zero final activity will not work with exponential schedule, set it to small epsilon!"); + } + } + + public String finalActivityTipText() { + return "The final target activity (relative to the range), should be close to zero."; + } + + public double getDeltaInertness() { + return deltaInertness; + } + + public void setDeltaInertness(double deltaInertness) { + this.deltaInertness = deltaInertness; + } + + public String deltaInertnessTipText() { + return "The additive change of the inertness in each adaption step."; + } + + public static String globalInfo() { + return "Controls the inertness factor based on the average velocity."; + } @Override - public void finish(Object obj, Population pop) {} + public void finish(Object obj, Population pop) { + } @Override - public void init(Object obj, Population pop, Object[] initialValues) {} - - public boolean isExponentialSchedule() { - return exponentialSchedule; - } + public void init(Object obj, Population pop, Object[] initialValues) { + } - public void setExponentialSchedule(boolean exponentialSchedule) { - this.exponentialSchedule = exponentialSchedule; - if (getFinalActivity()==0) { - System.err.println("Warning: zero final activity will not work with exponential schedule, set it to small epsilon!"); - } - } + public boolean isExponentialSchedule() { + return exponentialSchedule; + } - public String exponentialScheduleTipText() { - return "Use linear or exponential activity decrease schedule."; - } + public void setExponentialSchedule(boolean exponentialSchedule) { + this.exponentialSchedule = exponentialSchedule; + if (getFinalActivity() == 0) { + System.err.println("Warning: zero final activity will not work with exponential schedule, set it to small epsilon!"); + } + } + + public String exponentialScheduleTipText() { + return "Use linear or exponential activity decrease schedule."; + } } diff --git a/src/eva2/optimization/operator/paramcontrol/PSOInertnessAdaption.java b/src/eva2/optimization/operator/paramcontrol/PSOInertnessAdaption.java index d7926726..8e9f6927 100644 --- a/src/eva2/optimization/operator/paramcontrol/PSOInertnessAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/PSOInertnessAdaption.java @@ -1,6 +1,7 @@ package eva2.optimization.operator.paramcontrol; import eva2.gui.editor.GenericObjectEditor; + import java.io.Serializable; /** @@ -8,31 +9,30 @@ import java.io.Serializable; * This only works if iterations are known. The new variant allows exponential adaption, * where the second parameter (endV) is interpreted as halfing time in percent of the * full run. - * - * @author mkron * + * @author mkron */ public class PSOInertnessAdaption extends LinearParamAdaption implements Serializable { - - public PSOInertnessAdaption() { - super("inertnessOrChi", 0.7, 0.2); - } - public void hideHideable() { - GenericObjectEditor.setHideProperty(this.getClass(), "controlledParam", true); - } - - @Override - public String startVTipText() { - return "Start value for the inertness"; - } + public PSOInertnessAdaption() { + super("inertnessOrChi", 0.7, 0.2); + } + + public void hideHideable() { + GenericObjectEditor.setHideProperty(this.getClass(), "controlledParam", true); + } @Override - public String endVTipText() { - return "End value for the inertness"; - } + public String startVTipText() { + return "Start value for the inertness"; + } - public static String globalInfo() { - return "Adapt the inertnessOrChi value of PSO."; - } + @Override + public String endVTipText() { + return "End value for the inertness"; + } + + public static String globalInfo() { + return "Adapt the inertnessOrChi value of PSO."; + } } diff --git a/src/eva2/optimization/operator/paramcontrol/ParamAdaption.java b/src/eva2/optimization/operator/paramcontrol/ParamAdaption.java index df6680ab..f34d9646 100644 --- a/src/eva2/optimization/operator/paramcontrol/ParamAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/ParamAdaption.java @@ -4,26 +4,26 @@ import eva2.optimization.population.Population; /** * Adapt exactly one parameter with a generic method. - * @author mkron * + * @author mkron */ public interface ParamAdaption { - public Object clone(); - - public String getControlledParam(); - - /** - * Perform the adaption. - * - * @param iteration iteration count at the time of the call, evaluations or generations, depending on the terminator - * @param maxIteration - * @return - */ - public Object calcValue(Object obj, Population pop, int iteration, int maxIteration); - - public void init(Object obj, Population pop, Object[] initialValues); - - public void finish(Object obj, Population pop); - + public Object clone(); + + public String getControlledParam(); + + /** + * Perform the adaption. + * + * @param iteration iteration count at the time of the call, evaluations or generations, depending on the terminator + * @param maxIteration + * @return + */ + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration); + + public void init(Object obj, Population pop, Object[] initialValues); + + public void finish(Object obj, Population pop); + } diff --git a/src/eva2/optimization/operator/paramcontrol/ParamChangeListener.java b/src/eva2/optimization/operator/paramcontrol/ParamChangeListener.java index 6c6e82ee..357e5b49 100644 --- a/src/eva2/optimization/operator/paramcontrol/ParamChangeListener.java +++ b/src/eva2/optimization/operator/paramcontrol/ParamChangeListener.java @@ -1,5 +1,5 @@ package eva2.optimization.operator.paramcontrol; public interface ParamChangeListener { - public void notifyChange(InterfaceParamControllable controllable, Object oldVal, Object newVal, String msg); + public void notifyChange(InterfaceParamControllable controllable, Object oldVal, Object newVal, String msg); } diff --git a/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java b/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java index 05412d24..194188e1 100644 --- a/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java +++ b/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java @@ -4,6 +4,7 @@ import eva2.gui.BeanInspector; import eva2.optimization.population.Population; import eva2.optimization.modules.Processor; import eva2.tools.Pair; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -17,221 +18,219 @@ import java.util.Vector; * or the array of singleAdapters directly. In the latter case, the GUI is simpler (because theres * one fewer window layer) but there must be an additional method getParamControl implemented * which returns the ParameterControlManager to make it available to the Processor. - * + * + * @author mkron * @see ParamAdaption * @see Processor * @see AbstractParameterControl - * - * @author mkron - * */ public class ParameterControlManager implements InterfaceParameterControl, Serializable { - public Object[] initialValues = null; - private ParamAdaption[] singleAdapters = new ParamAdaption[]{}; - protected static boolean TRACE=false; - - public ParameterControlManager() { } - - public ParameterControlManager(ParamAdaption adaptor) { - singleAdapters = new ParamAdaption[]{adaptor}; - } - - public ParameterControlManager(ParamAdaption[] adaptors) { - singleAdapters = adaptors; - } - - public ParameterControlManager(ParameterControlManager o) { - if (o.initialValues!=null) { - initialValues = o.initialValues.clone(); + public Object[] initialValues = null; + private ParamAdaption[] singleAdapters = new ParamAdaption[]{}; + protected static boolean TRACE = false; + + public ParameterControlManager() { + } + + public ParameterControlManager(ParamAdaption adaptor) { + singleAdapters = new ParamAdaption[]{adaptor}; + } + + public ParameterControlManager(ParamAdaption[] adaptors) { + singleAdapters = adaptors; + } + + public ParameterControlManager(ParameterControlManager o) { + if (o.initialValues != null) { + initialValues = o.initialValues.clone(); + } else { + initialValues = null; + } + if (o.singleAdapters != null) { + singleAdapters = new ParamAdaption[o.singleAdapters.length]; + for (int i = 0; i < singleAdapters.length; i++) { + singleAdapters[i] = (ParamAdaption) o.singleAdapters[i].clone(); } - else { - initialValues=null; - } - if (o.singleAdapters != null) { - singleAdapters = new ParamAdaption[o.singleAdapters.length]; - for (int i=0; i names = new Vector(singleAdapters.length); - for (int i = 0; i < singleAdapters.length; i++) { - String prm=singleAdapters[i].getControlledParam(); - if (prm!=null) { - names.add(prm); - } - } - return names.toArray(new String[names.size()]); - } else { - return null; + public void updateParameters(Object obj) { + updateParameters(obj, null, -1, -1); + } + + /** + * Return a String array of canonical names of the parameters to be adapted. + * + * @return a String array of canonical names of the parameters to be adapted + */ + public String[] getControlledParameters() { + if (singleAdapters != null) { + Vector names = new Vector(singleAdapters.length); + for (int i = 0; i < singleAdapters.length; i++) { + String prm = singleAdapters[i].getControlledParam(); + if (prm != null) { + names.add(prm); + } } - } + return names.toArray(new String[names.size()]); + } else { + return null; + } + } - /** - * Retrieve the values of the adaptable parameters at a given iteration. - * If the maximum iteration is not known, both iteration and maxIteration will be set to -1. - * - * @param obj The instance which is controlled - * @param iteration current iteration (or -1 if unknown) - * @param maxIteration maximum iteration count (or -1 if unknown) - * @return - */ - public Object[] getValues(Object obj, Population pop, int iteration, int maxIteration) { - if (singleAdapters != null) { - Object[] vals = new Object[singleAdapters.length]; - for (int i = 0; i < vals.length; i++) { - vals[i]=singleAdapters[i].calcValue(obj, pop, iteration, maxIteration); - } - return vals; - } else { - return null; + /** + * Retrieve the values of the adaptable parameters at a given iteration. + * If the maximum iteration is not known, both iteration and maxIteration will be set to -1. + * + * @param obj The instance which is controlled + * @param iteration current iteration (or -1 if unknown) + * @param maxIteration maximum iteration count (or -1 if unknown) + * @return + */ + public Object[] getValues(Object obj, Population pop, int iteration, int maxIteration) { + if (singleAdapters != null) { + Object[] vals = new Object[singleAdapters.length]; + for (int i = 0; i < vals.length; i++) { + vals[i] = singleAdapters[i].calcValue(obj, pop, iteration, maxIteration); } - } + return vals; + } else { + return null; + } + } - public ParamAdaption[] getSingleAdapters() { - return singleAdapters; - } + public ParamAdaption[] getSingleAdapters() { + return singleAdapters; + } - public void setSingleAdapters(ParamAdaption[] singleAdapters) { - this.singleAdapters = singleAdapters; - } + public void setSingleAdapters(ParamAdaption[] singleAdapters) { + this.singleAdapters = singleAdapters; + } - /** - * Add a single ParamAdaption instance to the manager. - * - * @param pa - */ - public void addSingleAdapter(ParamAdaption pa) { - if (singleAdapters==null) { - setSingleAdapters(new ParamAdaption[]{pa}); + /** + * Add a single ParamAdaption instance to the manager. + * + * @param pa + */ + public void addSingleAdapter(ParamAdaption pa) { + if (singleAdapters == null) { + setSingleAdapters(new ParamAdaption[]{pa}); + } else { + ParamAdaption[] newP = new ParamAdaption[singleAdapters.length + 1]; + for (int i = 0; i < singleAdapters.length; i++) { + newP[i] = singleAdapters[i]; } - else { - ParamAdaption[] newP = new ParamAdaption[singleAdapters.length+1]; - for (int i=0; i listOfControllables( - Object target) { - Pair propsNamesVals = BeanInspector.getPublicPropertiesOf(target, true, true); - ArrayList controllables = new ArrayList(); + public static String globalInfo() { + return "Define a list of dynamically adapted parameters."; + } + + public String getName() { + return "ParameterControlManager"; + } + + /** + * Retrieve a list of objects which are properties of the given target object (retrievable by a + * getter method) and which implement the getParamControl method. + * This can be used to avoid a GUI layer as stated in the class comment. + * + * @param target + * @return + */ + public static List listOfControllables( + Object target) { + Pair propsNamesVals = BeanInspector.getPublicPropertiesOf(target, true, true); + ArrayList controllables = new ArrayList(); // Object ownParamCtrl = BeanInspector.callIfAvailable(target, "getParameterControl", null); // if the target itself has a ParameterControlManager, add it to the list of controllables. // if (ownParamCtrl!=null) controllables.add(ownParamCtrl); - Object[] objs = propsNamesVals.tail; - for (int i=0; i sin(-1+(t+1)^d)"; - } - /** - * Calculate sub-linear t as -1+(t+1)^dampeningExp - * @param t - * @param dampeningExp - * @return - */ - private static double dampen(double t, double dampeningExp) { - return Math.pow(t+1, dampeningExp)-1; - } + return res; + } + + public String getName() { + return "SinAdapt(" + getControlledParam() + "_" + lowerBnd + "_" + upperBnd + "_" + iterationPeriod + ((dampening != 1) ? ("_dmp-" + dampening) : "") + ")"; + } + + public String globalInfo() { + return "Sinusoidally oscillating value, the frequency may be varyied with time. E.g. use dampening 0.9 " + + "for a slightly decreasing frequency, dampening 1.1 for a slight increase. The frequency is modified " + + "in the form sin(t) -> sin(-1+(t+1)^d)"; + } + + /** + * Calculate sub-linear t as -1+(t+1)^dampeningExp + * + * @param t + * @param dampeningExp + * @return + */ + private static double dampen(double t, double dampeningExp) { + return Math.pow(t + 1, dampeningExp) - 1; + } @Override - public Object clone() { - return new SinusoidalParamAdaption(this); - } - - @Override - public void finish(Object obj, Population pop) { - } + public Object clone() { + return new SinusoidalParamAdaption(this); + } @Override - public String getControlledParam() { - return paramName ; - } + public void finish(Object obj, Population pop) { + } @Override - public void init(Object obj, Population pop, Object[] initialValues) { - } + public String getControlledParam() { + return paramName; + } + @Override - public void setControlledParam(String prm) { - paramName = prm; - } - public String controlledParamTipText() { - return "The name of the generic parameter to be adapted."; - } - + public void init(Object obj, Population pop, Object[] initialValues) { + } + + @Override + public void setControlledParam(String prm) { + paramName = prm; + } + + public String controlledParamTipText() { + return "The name of the generic parameter to be adapted."; + } + // public ParameterControlManager getParamControl() { // return paramControl; // } @@ -128,65 +131,76 @@ public class SinusoidalParamAdaption implements InterfaceHasUpperDoubleBound, Pa // } @Override - public double getUpperBnd() { - return upperBnd; - } - public void setUpperBnd(double upperBnd) { - this.upperBnd = upperBnd; - updateMed(); - } + public double getUpperBnd() { + return upperBnd; + } + + public void setUpperBnd(double upperBnd) { + this.upperBnd = upperBnd; + updateMed(); + } + @Override - public void SetUpperBnd(double u) { - this.setUpperBnd(u); - } - public String upperBndTipText() { - return "The upper deviation of the oscillation."; - } + public void SetUpperBnd(double u) { + this.setUpperBnd(u); + } - public double getLowerBnd() { - return lowerBnd; - } - public void setLowerBnd(double lowerBnd) { - this.lowerBnd = lowerBnd; - updateMed(); - } - private void updateMed() { - medVal = 0.5*(upperBnd + lowerBnd); - } + public String upperBndTipText() { + return "The upper deviation of the oscillation."; + } - public String lowerBndTipText() { - return "The lower deviation of the oscillation."; - } + public double getLowerBnd() { + return lowerBnd; + } - public int getIterationPeriod() { - return iterationPeriod; - } - public void setIterationPeriod(int iterationPeriod) { - this.iterationPeriod = iterationPeriod; - } - public String iterationPeriodTipText() { - return "The period length of the oscillation, in iterations."; - } + public void setLowerBnd(double lowerBnd) { + this.lowerBnd = lowerBnd; + updateMed(); + } - public int getInitialShift() { - return initialShift; - } - public void setInitialShift(int initialShift) { - this.initialShift = initialShift; - } - public String initialShiftTipText() { - return "The initial phase shift of the sinusoidal, in iterations."; - } + private void updateMed() { + medVal = 0.5 * (upperBnd + lowerBnd); + } - public double getDampening() { - return dampening; - } - public void setDampening(double dampening) { - this.dampening = dampening; - } - public String dampeningTipText() { - return "Dampening exponent for frequency variation: values above 1 increase frequency with time, values below dampen it."; - } + public String lowerBndTipText() { + return "The lower deviation of the oscillation."; + } + + public int getIterationPeriod() { + return iterationPeriod; + } + + public void setIterationPeriod(int iterationPeriod) { + this.iterationPeriod = iterationPeriod; + } + + public String iterationPeriodTipText() { + return "The period length of the oscillation, in iterations."; + } + + public int getInitialShift() { + return initialShift; + } + + public void setInitialShift(int initialShift) { + this.initialShift = initialShift; + } + + public String initialShiftTipText() { + return "The initial phase shift of the sinusoidal, in iterations."; + } + + public double getDampening() { + return dampening; + } + + public void setDampening(double dampening) { + this.dampening = dampening; + } + + public String dampeningTipText() { + return "Dampening exponent for frequency variation: values above 1 increase frequency with time, values below dampen it."; + } // // public void setBeatFreq(boolean beatFreq) { // this.beatFreq = beatFreq; @@ -200,5 +214,5 @@ public class SinusoidalParamAdaption implements InterfaceHasUpperDoubleBound, Pa // public boolean isBeatFreq() { // return beatFreq; // } - + } diff --git a/src/eva2/optimization/operator/paramcontrol/SuccessBasedAdaption.java b/src/eva2/optimization/operator/paramcontrol/SuccessBasedAdaption.java index 65aec0f6..2c7e1d52 100644 --- a/src/eva2/optimization/operator/paramcontrol/SuccessBasedAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/SuccessBasedAdaption.java @@ -3,111 +3,114 @@ package eva2.optimization.operator.paramcontrol; import eva2.optimization.population.Population; import eva2.optimization.population.SolutionSet; import eva2.optimization.strategies.InterfaceOptimizer; + import java.io.Serializable; -public class SuccessBasedAdaption implements ParamAdaption, InterfaceHasUpperDoubleBound, -GenericParamAdaption, Serializable { - private double fitThreshold; -// private double lastSuccRate=-1; - private int fitCrit=0; - private double targetRate = 0.75; - private String paramStr = "unnamedParameter"; - private double lowerBnd=0.1; - private double upperBnd=2; - private double curValue; - private double incFact = 1.05; - - public SuccessBasedAdaption() {} - - public SuccessBasedAdaption(double thresh, int crit, double rate) { - setFitThreshold(thresh); - fitCrit = crit; - targetRate = rate; - } - - public SuccessBasedAdaption(SuccessBasedAdaption successBasedAdaption) { - // TODO Auto-generated constructor stub - } +public class SuccessBasedAdaption implements ParamAdaption, InterfaceHasUpperDoubleBound, + GenericParamAdaption, Serializable { + private double fitThreshold; + // private double lastSuccRate=-1; + private int fitCrit = 0; + private double targetRate = 0.75; + private String paramStr = "unnamedParameter"; + private double lowerBnd = 0.1; + private double upperBnd = 2; + private double curValue; + private double incFact = 1.05; + + public SuccessBasedAdaption() { + } + + public SuccessBasedAdaption(double thresh, int crit, double rate) { + setFitThreshold(thresh); + fitCrit = crit; + targetRate = rate; + } + + public SuccessBasedAdaption(SuccessBasedAdaption successBasedAdaption) { + // TODO Auto-generated constructor stub + } @Override - public Object clone() { - return new SuccessBasedAdaption(this); - } + public Object clone() { + return new SuccessBasedAdaption(this); + } @Override - public Object calcValue(Object obj, Population pop, int iteration, - int maxIteration) { - if (obj instanceof InterfaceOptimizer) { - SolutionSet sols = (SolutionSet) ((InterfaceOptimizer)obj).getAllSolutions(); - double curSuccRate = getSuccessRate(sols.getSolutions()); - if (curSuccRate 2) { smPop = new Population(); } - double[][] f = new double[archive.size()][dim]; - double[] tmpF, redF; + double[][] f = new double[archive.size()][dim]; + double[] tmpF, redF; for (int i = 0; i < f.length; i++) { - tmpF = ((AbstractEAIndividual)archive.get(i)).getFitness(); + tmpF = ((AbstractEAIndividual) archive.get(i)).getFitness(); for (int j = 0; j < dim; j++) { f[i][j] = tmpF[j]; } if (smPop != null) { - redF = new double[tmpF.length -1]; + redF = new double[tmpF.length - 1]; for (int j = 0; j < redF.length; j++) { redF[j] = tmpF[j]; } @@ -145,57 +151,57 @@ public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable } double[] lastValue = null; - lastValue = new double[dim]; + lastValue = new double[dim]; for (int i = 0; i < dim; i++) { lastValue[i] = border[i][1]; } - lastValue[dim-1] = border[dim-1][0]-1; + lastValue[dim - 1] = border[dim - 1][0] - 1; for (int i = 0; i < f.length; i++) { // first search for the smallest in the last dimension - tmpIndex = 0; + tmpIndex = 0; tmpSmallest = Double.MAX_VALUE; for (int j = 0; j < f.length; j++) { - if ((f[j][dim-1] > lastValue[dim-1]) && (f[j][dim-1] < tmpSmallest)) { - tmpIndex = j; - tmpSmallest = f[j][dim-1]; + if ((f[j][dim - 1] > lastValue[dim - 1]) && (f[j][dim - 1] < tmpSmallest)) { + tmpIndex = j; + tmpSmallest = f[j][dim - 1]; } } - if (f[tmpIndex][dim-1] > lastValue[dim-1]) { + if (f[tmpIndex][dim - 1] > lastValue[dim - 1]) { // now i should have identified the current smallest // here i found the very first individual, therefore // no lastValue has been set... set it to border - if (lastValue[dim-1] < border[dim-1][0]) { - lastValue[dim-1] = border[dim-1][0]; + if (lastValue[dim - 1] < border[dim - 1][0]) { + lastValue[dim - 1] = border[dim - 1][0]; } if (dim == 2) { - result += lastValue[0] * (f[tmpIndex][1]-lastValue[1]); + result += lastValue[0] * (f[tmpIndex][1] - lastValue[1]); } else { // reduce dimension and call calculateCMetric recursively - Population tmpPop = new Population(); - double[][] tmpBorder; - double tmpS; + Population tmpPop = new Population(); + double[][] tmpBorder; + double tmpS; for (int j = 0; j < archive.size(); j++) { - if (((AbstractEAIndividual)archive.get(j)).getFitness(dim-1) < f[tmpIndex][dim-1]) { + if (((AbstractEAIndividual) archive.get(j)).getFitness(dim - 1) < f[tmpIndex][dim - 1]) { // this one is small enough to join the next level tmpPop.add(smPop.get(j)); } } - tmpBorder = new double[border.length-1][2]; + tmpBorder = new double[border.length - 1][2]; for (int j = 0; j < tmpBorder.length; j++) { tmpBorder[j][0] = border[j][0]; tmpBorder[j][1] = border[j][1]; } - tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim-1); - result += (f[tmpIndex][dim-1] - lastValue[dim-1]) * tmpS; + tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim - 1); + result += (f[tmpIndex][dim - 1] - lastValue[dim - 1]) * tmpS; } for (int j = 0; j < f[tmpIndex].length; j++) { lastValue[j] = f[tmpIndex][j]; } } else { // no smallest found break - i = f.length+1; + i = f.length + 1; break; } } @@ -205,22 +211,22 @@ public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable result += lastValue[0] * (border[1][1] - lastValue[1]); } else { // reduce dimension and call calculateCMetric recursively - Population tmpPop = new Population(); - double[][] tmpBorder; - double tmpS; + Population tmpPop = new Population(); + double[][] tmpBorder; + double tmpS; for (int j = 0; j < archive.size(); j++) { - if (((AbstractEAIndividual)archive.get(j)).getFitness(dim-1) <= lastValue[dim-1]) { + if (((AbstractEAIndividual) archive.get(j)).getFitness(dim - 1) <= lastValue[dim - 1]) { // this one is small enough to join the next level tmpPop.add(smPop.get(j)); } } - tmpBorder = new double[border.length-1][2]; + tmpBorder = new double[border.length - 1][2]; for (int j = 0; j < tmpBorder.length; j++) { tmpBorder[j][0] = border[j][0]; tmpBorder[j][1] = border[j][1]; } - tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim-1); - result += (border[dim-1][1] - lastValue[dim-1]) * tmpS; + tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim - 1); + result += (border[dim - 1][1] - lastValue[dim - 1]) * tmpS; } return result; } @@ -228,15 +234,19 @@ public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "S-Metric"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/operator/paretofrontmetrics/MetricSWithReference.java b/src/eva2/optimization/operator/paretofrontmetrics/MetricSWithReference.java index 14da7390..e6a00fbf 100644 --- a/src/eva2/optimization/operator/paretofrontmetrics/MetricSWithReference.java +++ b/src/eva2/optimization/operator/paretofrontmetrics/MetricSWithReference.java @@ -8,9 +8,11 @@ import eva2.optimization.operator.archiving.ArchivingAllDominating; import eva2.optimization.population.Population; import eva2.optimization.problems.AbstractMultiObjectiveOptimizationProblem; import eva2.optimization.tools.FileTools; + import java.util.ArrayList; -/** S-Metric calculates the hyper-volume covered between the current solutions and a reference point. +/** + * S-Metric calculates the hyper-volume covered between the current solutions and a reference point. * But here the difference to a given hybervolume is to be minimized. * Created by IntelliJ IDEA. * User: streiche @@ -19,11 +21,11 @@ import java.util.ArrayList; * To change this template use File | Settings | File Templates. */ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io.Serializable { - private double[][] m_ObjectiveSpaceRange; - private PropertyFilePath m_InputFilePath = PropertyFilePath.getFilePathFromResource("MOPReference/T1_250.txt"); - private String[] m_Titles; - private double[][] m_Reference; - private double m_ReferenceSMetric = -1; + private double[][] m_ObjectiveSpaceRange; + private PropertyFilePath m_InputFilePath = PropertyFilePath.getFilePathFromResource("MOPReference/T1_250.txt"); + private String[] m_Titles; + private double[][] m_Reference; + private double m_ReferenceSMetric = -1; public MetricSWithReference() { this.loadReferenceData(); @@ -37,7 +39,7 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io this.m_ObjectiveSpaceRange[i][1] = b.m_ObjectiveSpaceRange[i][1]; } } - this.m_InputFilePath = b.m_InputFilePath; + this.m_InputFilePath = b.m_InputFilePath; if (b.m_Titles != null) { this.m_Titles = new String[b.m_Titles.length]; System.arraycopy(b.m_Titles, 0, this.m_Titles, 0, this.m_Titles.length); @@ -51,16 +53,18 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io } } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new MetricSWithReference(this); } - /** This method allows you to init the metric loading data etc - * + /** + * This method allows you to init the metric loading data etc */ public void init() { this.loadReferenceData(); @@ -70,18 +74,18 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io this.m_ObjectiveSpaceRange = range; } - /** This method loads the reference data - * + /** + * This method loads the reference data */ private void loadReferenceData() { - String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); + String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); if (lines == null) { - System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); + System.out.println("Failed to read " + this.m_InputFilePath.getCompleteFilePath()); } lines[0].trim(); this.m_Titles = lines[0].split("\t"); - ArrayList tmpA = new ArrayList(); - double[] tmpD; + ArrayList tmpA = new ArrayList(); + double[] tmpD; for (int i = 1; i < lines.length; i++) { tmpD = new double[this.m_Titles.length]; lines[i].trim(); @@ -93,12 +97,13 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io } this.m_Reference = new double[tmpA.size()][]; for (int i = 0; i < tmpA.size(); i++) { - this.m_Reference[i] = (double[])tmpA.get(i); + this.m_Reference[i] = (double[]) tmpA.get(i); } this.m_ReferenceSMetric = -1; } - /** This method gives a metric how to evaluate + /** + * This method gives a metric how to evaluate * an achieved Pareto-Front */ @Override @@ -106,8 +111,8 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io this.m_ObjectiveSpaceRange = problem.getObjectiveSpaceRange(); double smetric = this.calculateSMetric(pop, this.m_ObjectiveSpaceRange, this.m_ObjectiveSpaceRange.length); if (this.m_ReferenceSMetric < 0) { - Population tmpPop = new Population(); - AbstractEAIndividual tmpIndy; + Population tmpPop = new Population(); + AbstractEAIndividual tmpIndy; tmpPop.setTargetSize(this.m_Reference.length); tmpPop.clear(); for (int i = 0; i < this.m_Reference.length; i++) { @@ -120,16 +125,18 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io return (smetric - this.m_ReferenceSMetric); } - /** This method will calucuate the s-metric from a double array of + /** + * This method will calucuate the s-metric from a double array of * fitness cases - * @param pop Array of fitness cases - * @param border The border to use wehn calculating the s-metric. + * + * @param pop Array of fitness cases + * @param border The border to use wehn calculating the s-metric. * @return s-metric */ public double calculateSMetric(Population pop, double[][] border, int dim) { - double result = 0; - int tmpIndex; - double tmpSmallest; + double result = 0; + int tmpIndex; + double tmpSmallest; Population smPop = null; AbstractEAIndividual tmpIndy; @@ -145,15 +152,15 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io if (dim > 2) { smPop = new Population(); } - double[][] f = new double[archive.size()][dim]; - double[] tmpF, redF; + double[][] f = new double[archive.size()][dim]; + double[] tmpF, redF; for (int i = 0; i < f.length; i++) { - tmpF = ((AbstractEAIndividual)archive.get(i)).getFitness(); + tmpF = ((AbstractEAIndividual) archive.get(i)).getFitness(); for (int j = 0; j < dim; j++) { f[i][j] = tmpF[j]; } if (smPop != null) { - redF = new double[tmpF.length -1]; + redF = new double[tmpF.length - 1]; for (int j = 0; j < redF.length; j++) { redF[j] = tmpF[j]; } @@ -173,57 +180,57 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io } double[] lastValue = null; - lastValue = new double[dim]; + lastValue = new double[dim]; for (int i = 0; i < dim; i++) { lastValue[i] = border[i][1]; } - lastValue[dim-1] = border[dim-1][0]-1; + lastValue[dim - 1] = border[dim - 1][0] - 1; for (int i = 0; i < f.length; i++) { // first search for the smallest in the last dimension - tmpIndex = 0; + tmpIndex = 0; tmpSmallest = Double.MAX_VALUE; for (int j = 0; j < f.length; j++) { - if ((f[j][dim-1] > lastValue[dim-1]) && (f[j][dim-1] < tmpSmallest)) { - tmpIndex = j; - tmpSmallest = f[j][dim-1]; + if ((f[j][dim - 1] > lastValue[dim - 1]) && (f[j][dim - 1] < tmpSmallest)) { + tmpIndex = j; + tmpSmallest = f[j][dim - 1]; } } - if (f[tmpIndex][dim-1] > lastValue[dim-1]) { + if (f[tmpIndex][dim - 1] > lastValue[dim - 1]) { // now i should have identified the current smallest // here i found the very first individual, therefore // no lastValue has been set... set it to border - if (lastValue[dim-1] < border[dim-1][0]) { - lastValue[dim-1] = border[dim-1][0]; + if (lastValue[dim - 1] < border[dim - 1][0]) { + lastValue[dim - 1] = border[dim - 1][0]; } if (dim == 2) { - result += lastValue[0] * (f[tmpIndex][1]-lastValue[1]); + result += lastValue[0] * (f[tmpIndex][1] - lastValue[1]); } else { // reduce dimension and call calculateCMetric recursively - Population tmpPop = new Population(); - double[][] tmpBorder; - double tmpS; + Population tmpPop = new Population(); + double[][] tmpBorder; + double tmpS; for (int j = 0; j < archive.size(); j++) { - if (((AbstractEAIndividual)archive.get(j)).getFitness(dim-1) < f[tmpIndex][dim-1]) { + if (((AbstractEAIndividual) archive.get(j)).getFitness(dim - 1) < f[tmpIndex][dim - 1]) { // this one is small enough to join the next level tmpPop.add(smPop.get(j)); } } - tmpBorder = new double[border.length-1][2]; + tmpBorder = new double[border.length - 1][2]; for (int j = 0; j < tmpBorder.length; j++) { tmpBorder[j][0] = border[j][0]; tmpBorder[j][1] = border[j][1]; } - tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim-1); - result += (f[tmpIndex][dim-1] - lastValue[dim-1]) * tmpS; + tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim - 1); + result += (f[tmpIndex][dim - 1] - lastValue[dim - 1]) * tmpS; } for (int j = 0; j < f[tmpIndex].length; j++) { lastValue[j] = f[tmpIndex][j]; } } else { // no smallest found break - i = f.length+1; + i = f.length + 1; break; } } @@ -233,22 +240,22 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io result += lastValue[0] * (border[1][1] - lastValue[1]); } else { // reduce dimension and call calculateCMetric recursively - Population tmpPop = new Population(); - double[][] tmpBorder; - double tmpS; + Population tmpPop = new Population(); + double[][] tmpBorder; + double tmpS; for (int j = 0; j < archive.size(); j++) { - if (((AbstractEAIndividual)archive.get(j)).getFitness(dim-1) <= lastValue[dim-1]) { + if (((AbstractEAIndividual) archive.get(j)).getFitness(dim - 1) <= lastValue[dim - 1]) { // this one is small enough to join the next level tmpPop.add(smPop.get(j)); } } - tmpBorder = new double[border.length-1][2]; + tmpBorder = new double[border.length - 1][2]; for (int j = 0; j < tmpBorder.length; j++) { tmpBorder[j][0] = border[j][0]; tmpBorder[j][1] = border[j][1]; } - tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim-1); - result += (border[dim-1][1] - lastValue[dim-1]) * tmpS; + tmpS = this.calculateSMetric(tmpPop, tmpBorder, dim - 1); + result += (border[dim - 1][1] - lastValue[dim - 1]) * tmpS; } return result; } @@ -256,31 +263,39 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "S-Metric"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Difference between the current SMetric and the reference SMetric (curSM - refSM)."; } - /** This method allows you to set the path to the data file. - * @param b File path. + /** + * This method allows you to set the path to the data file. + * + * @param b File path. */ public void setInputFilePath(PropertyFilePath b) { this.m_InputFilePath = b; this.loadReferenceData(); } + public PropertyFilePath getInputFilePath() { return this.m_InputFilePath; } + public String inputFilePathTipText() { return "Select the reference soltuion by choosing the input file."; } diff --git a/src/eva2/optimization/operator/postprocess/InterfacePostProcessParams.java b/src/eva2/optimization/operator/postprocess/InterfacePostProcessParams.java index d8a92324..7abe05f5 100644 --- a/src/eva2/optimization/operator/postprocess/InterfacePostProcessParams.java +++ b/src/eva2/optimization/operator/postprocess/InterfacePostProcessParams.java @@ -7,31 +7,41 @@ import eva2.optimization.enums.PostProcessMethod; * parameters for a hill climbing step, namely the number of evaluations and * the sigma condition for clustering. The idea is to optimize the best * individual within each cluster. - * - * @author mkron * + * @author mkron */ public interface InterfacePostProcessParams { public int getPostProcessSteps(); + public void setPostProcessSteps(int ppSteps); + public String postProcessStepsTipText(); - + public boolean isDoPostProcessing(); - public void setDoPostProcessing(boolean postProcess); - public String doPostProcessingTipText(); - - public double getPostProcessClusterSigma(); - public void setPostProcessClusterSigma(double postProcessClusterSigma); - public String postProcessClusterSigmaTipText(); - - public int getPrintNBest(); - public void setPrintNBest(int nBest); - public String printNBestTipText(); - - public void setPPMethod(PostProcessMethod meth); - public PostProcessMethod getPPMethod(); - public String PPMethodTipText(); - - public boolean isWithPlot(); - public void setWithPlot(boolean withPlot); + + public void setDoPostProcessing(boolean postProcess); + + public String doPostProcessingTipText(); + + public double getPostProcessClusterSigma(); + + public void setPostProcessClusterSigma(double postProcessClusterSigma); + + public String postProcessClusterSigmaTipText(); + + public int getPrintNBest(); + + public void setPrintNBest(int nBest); + + public String printNBestTipText(); + + public void setPPMethod(PostProcessMethod meth); + + public PostProcessMethod getPPMethod(); + + public String PPMethodTipText(); + + public boolean isWithPlot(); + + public void setWithPlot(boolean withPlot); } diff --git a/src/eva2/optimization/operator/postprocess/PostProcess.java b/src/eva2/optimization/operator/postprocess/PostProcess.java index c938134d..7c74387d 100644 --- a/src/eva2/optimization/operator/postprocess/PostProcess.java +++ b/src/eva2/optimization/operator/postprocess/PostProcess.java @@ -42,6 +42,7 @@ import eva2.optimization.stat.InterfaceTextListener; import eva2.optimization.stat.StatisticsParameter; import eva2.tools.Pair; import eva2.tools.math.Mathematics; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -50,32 +51,31 @@ import java.util.Vector; /** * Postprocess a population / list of individuals to find out a set of distinct optima. - * - * @author mkron * + * @author mkron */ public class PostProcess { - protected static InterfaceDistanceMetric metric = new PhenotypeMetric(); - private static final boolean TRACE = false; - - // the default mutation step size for HC post processing - private static double defaultMutationStepSize = 0.01; - // lower limit mutation step size for HC post processing - private static double minMutationStepSize = 0.0000000000000001; - // used for hill climbing post processing and only alive during that period - private static Vector ppRunnables = new Vector(); - public static final String movedDistanceKey = "PostProcessingMovedBy"; - public static final String movedToPositionKey = "PostProcessingMovedTo"; - - public static final int BEST_ONLY = 1; - public static final int BEST_RAND = 2; - public static final int RAND_ONLY = 3; - - public static final int KEEP_LONERS = 11; - public static final int DISCARD_LONERS = 12; - public static final int LONERS_AS_CLUSTERS = 13; - - /** + protected static InterfaceDistanceMetric metric = new PhenotypeMetric(); + private static final boolean TRACE = false; + + // the default mutation step size for HC post processing + private static double defaultMutationStepSize = 0.01; + // lower limit mutation step size for HC post processing + private static double minMutationStepSize = 0.0000000000000001; + // used for hill climbing post processing and only alive during that period + private static Vector ppRunnables = new Vector(); + public static final String movedDistanceKey = "PostProcessingMovedBy"; + public static final String movedToPositionKey = "PostProcessingMovedTo"; + + public static final int BEST_ONLY = 1; + public static final int BEST_RAND = 2; + public static final int RAND_ONLY = 3; + + public static final int KEEP_LONERS = 11; + public static final int DISCARD_LONERS = 12; + public static final int LONERS_AS_CLUSTERS = 13; + + /** * This method returns a set of individuals corresponding to an optimum in a given list. * The individuals returned are to be nearer than epsilon to a given optimum. For each optimum, there is * returned zero or one individual at max. @@ -83,17 +83,17 @@ public class PostProcess { * may be selected, indicated by the boolean flag bTakeFitter. This means, that an individual may be * returned in more than one copy if the optima are close together and the individual lies in between. * The returned array may contain null values if an optimum is not considered found at all. - * - * @param pop A population of possible solutions. - * @param optima a set of predefined optima - * @param epsilon the threshold up to which an optimum is considered found. - * @param bTakeFitter if true, the fitter of two close individuals is selected, otherwise the closer one + * + * @param pop A population of possible solutions. + * @param optima a set of predefined optima + * @param epsilon the threshold up to which an optimum is considered found. + * @param bTakeFitter if true, the fitter of two close individuals is selected, otherwise the closer one * @return an array of individuals corresponding to the optimum with the same index */ public static AbstractEAIndividual[] getFoundOptimaArray(Population pop, Population optima, double epsilon, boolean bTakeFitter) { - AbstractEAIndividual candidate, opt; + AbstractEAIndividual candidate, opt; // Population result = new Population(5); - AbstractEAIndividual[] found = new AbstractEAIndividual[optima.size()]; + AbstractEAIndividual[] found = new AbstractEAIndividual[optima.size()]; double indDist; for (int i = 0; i < found.length; i++) { found[i] = null; @@ -106,213 +106,213 @@ public class PostProcess { indDist = metric.distance(candidate, opt); if (found[j] == null) { // current optimum has not been found yet if (indDist < epsilon) { - found[j] = (AbstractEAIndividual)candidate.clone(); + found[j] = (AbstractEAIndividual) candidate.clone(); // result.add(found[j]); } } else {// there was another one found. set the fitter one or the closer one - if (indDist < epsilon) { - if ((bTakeFitter && (candidate.isDominatingDebConstraints(found[j]))) // flag "fitter" and new one is fitter - || (!bTakeFitter && (indDist < metric.distance(found[j], opt)))) { // flag "closer" and new one is closer + if (indDist < epsilon) { + if ((bTakeFitter && (candidate.isDominatingDebConstraints(found[j]))) // flag "fitter" and new one is fitter + || (!bTakeFitter && (indDist < metric.distance(found[j], opt)))) { // flag "closer" and new one is closer // int index = result.indexOf(found[j]); // do replacement - found[j] = (AbstractEAIndividual)candidate.clone(); + found[j] = (AbstractEAIndividual) candidate.clone(); // result.set(index, found[j]); - } - } + } + } } } } return found; } - /** + /** * Convenience method for getFoundOptimaArray(), returning the same set of optima in a Population. - * - * @see getFoundOptimaArray(Population pop, Population optima, double epsilon, boolean bTakeFitter) - * @param pop A population of possible solutions. - * @param optima a set of known optima - * @param epsilon the threshold up to which an optimum is considered found. - * @param bTakeFitter if true, the fitter of two close individuals is selected, otherwise the closer one + * + * @param pop A population of possible solutions. + * @param optima a set of known optima + * @param epsilon the threshold up to which an optimum is considered found. + * @param bTakeFitter if true, the fitter of two close individuals is selected, otherwise the closer one * @return a Population of individuals corresponding to the given optima + * @see getFoundOptimaArray(Population pop, Population optima, double epsilon, boolean bTakeFitter) */ public static Population getFoundOptima(Population pop, Population optima, double epsilon, boolean bTakeFitter) { - Population result = new Population(5); - AbstractEAIndividual[] optsFound = getFoundOptimaArray(pop, optima, epsilon, bTakeFitter); - - for (int i=0; i 0. * takeOverMode defines whether, of a cluster with size > 1, which n individuals are kept. Either the n best only, - * or the single best and random n-1, or all n random. - * + * or the single best and random n-1, or all n random. + * * @param pop * @param clustering * @param returnQuota * @param lonerMode - * @param takeOverMode + * @param takeOverMode * @return for every cluster a population of representatives which are the best individuals or a random subset of the cluster */ public static Population clusterBest(Population pop, InterfaceClustering clustering, double returnQuota, int lonerMode, int takeOverMode) { //cluster the undifferentiated population - Population result = new Population(10); - result.setSameParams(pop); - clustering.initClustering(pop); - Population[] clusters = clustering.cluster(pop, null); - if (TRACE) { - System.out.println("found " + clusters.length + " clusters!"); - int sum=0; - for (int j=0; j= 1) { - result.addAll((Collection)clusters[j]); + if (j == 0) { // cluster 0 contains non-assigned individuals + if (lonerMode == DISCARD_LONERS) { + continue; + } // loners are discarded + else if (lonerMode == KEEP_LONERS) { + result.addAll(clusters[j]); // loners are all kept + continue; + } // default case: treat loners just as the rest + if (lonerMode != LONERS_AS_CLUSTERS) { + System.err.println("invalid loner mode in (), default is treating them like clusters"); + } + } + if (returnQuota >= 1) { + result.addAll((Collection) clusters[j]); } // easy case - else { - int n = Math.max(1, (int)(returnQuota*clusters[j].size())); // return at least one per cluster! - switch (takeOverMode) { - case BEST_ONLY: // another easy case - result.addAll((Collection)(clusters[j].getBestNIndividuals(n, -1))); - break; - case BEST_RAND: - Population exclude = new Population(); - exclude.add(clusters[j].getBestEAIndividual()); - result.add(exclude.getEAIndividual(0)); - result.addAll(clusters[j].moveRandNIndividualsExcept(n-1, exclude)); - break; - case RAND_ONLY: - result.addAll(clusters[j].moveRandNIndividuals(n)); - break; - default: System.err.println("Unknown mode in PostProcess:clusterBest!"); break; - } - } + else { + int n = Math.max(1, (int) (returnQuota * clusters[j].size())); // return at least one per cluster! + switch (takeOverMode) { + case BEST_ONLY: // another easy case + result.addAll((Collection) (clusters[j].getBestNIndividuals(n, -1))); + break; + case BEST_RAND: + Population exclude = new Population(); + exclude.add(clusters[j].getBestEAIndividual()); + result.add(exclude.getEAIndividual(0)); + result.addAll(clusters[j].moveRandNIndividualsExcept(n - 1, exclude)); + break; + case RAND_ONLY: + result.addAll(clusters[j].moveRandNIndividuals(n)); + break; + default: + System.err.println("Unknown mode in PostProcess:clusterBest!"); + break; + } + } } result.synchSize(); return result; } - - public static double[] populationMeasures(Population pop) { - double[] measures = pop.getPopulationMeasures(); - return measures; - } - + + public static double[] populationMeasures(Population pop) { + double[] measures = pop.getPopulationMeasures(); + return measures; + } + /** * Filter the individuals of a population which have a fitness norm within given bounds. * Returns shallow copies! - * + * * @param pop * @param lower * @param upper * @return */ public static Population filterFitnessIn(Population pop, double lower, double upper, int crit) { - Population result = filterFitness(pop, upper, true, crit); - return filterFitness(result, lower, false, crit); + Population result = filterFitness(pop, upper, true, crit); + return filterFitness(result, lower, false, crit); } - + /** * Filter the individuals of a population which have a fitness norm below a given value. * Returns shallow copies! - * + * * @param pop * @param fitNorm * @param bSmaller if true, return individuals with lower or equal, else with higher fitness norm only * @return */ public static Population filterFitnessNormed(Population pop, double fitNorm, boolean bSmallerEq) { - AbstractEAIndividual indy; - Population result = new Population(); - for (int i=0; i fitNorm)) { result.add(indy); } - else if (!bSmallerEq && (PhenotypeMetric.norm(indy.getFitness())>fitNorm)) { - result.add(indy); - } - } - return result; + } + return result; } - + /** * Filter the individuals of a population which have a fitness below a given value. * If the single fitness criterion is valid (within the range of the fitness array), * the absolute value of that criterion is compared, otherwise (e.g. crit=-1) the * phenotypic norm of the full vector is used. * Returns shallow copies! - * + * * @param pop * @param fitNorm * @param bSmaller if true, return individuals with lower or equal, else with higher fitness only - * @param crit index of the fitness criterion or -1 to use the norm + * @param crit index of the fitness criterion or -1 to use the norm * @return */ public static Population filterFitness(Population pop, double fitThresh, boolean bSmallerEq, int crit) { - double curFit; - AbstractEAIndividual indy; - Population result = new Population(); - for (int i=0; i=0) && (crit= 0) && (crit < indy.getFitness().length)) { curFit = indy.getFitness(crit); - } - else { + } else { curFit = PhenotypeMetric.norm(indy.getFitness()); } - - if (bSmallerEq && (curFit<=fitThresh)) { + + if (bSmallerEq && (curFit <= fitThresh)) { + result.add(indy); + } else if (!bSmallerEq && (curFit > fitThresh)) { result.add(indy); } - else if (!bSmallerEq && (curFit>fitThresh)) { - result.add(indy); - } - } - return result; + } + return result; } - + // /** // * This method returns a set of individuals corresponding to an optimum in a given list. // * The individuals returned are to be nearer than epsilon to a given optimum. It is not @@ -351,694 +351,694 @@ public class PostProcess { /** * Search a population and find the closest individual to a given individual. Return the * best distance and corresponding index in a pair structure. - * + * * @param indy * @param pop - * @return index and distance to the closest individual in the population + * @return index and distance to the closest individual in the population */ - public static Pair getClosestIndy(AbstractEAIndividual indy, Population pop) { - double bestDist = -1, tmpDist = -1; - int bestIndex = -1; - AbstractEAIndividual opt; + public static Pair getClosestIndy(AbstractEAIndividual indy, Population pop) { + double bestDist = -1, tmpDist = -1; + int bestIndex = -1; + AbstractEAIndividual opt; for (int j = 0; j < pop.size(); j++) { - opt = (AbstractEAIndividual) pop.get(j); - tmpDist = metric.distance(indy, opt); // distance current indy to current optimum - if (bestDist < 0 || (tmpDist < bestDist)) { // we have a better hit - bestIndex = j; - bestDist = tmpDist; - } + opt = (AbstractEAIndividual) pop.get(j); + tmpDist = metric.distance(indy, opt); // distance current indy to current optimum + if (bestDist < 0 || (tmpDist < bestDist)) { // we have a better hit + bestIndex = j; + bestDist = tmpDist; + } } return new Pair(bestDist, bestIndex); - } - - /** - * Optimize a population with a default hill-climbing heuristic for a number of fitness evaluations. - * As mutation operator, a mutative step size ES mutation is used, the step size of which is not allowed - * to increase above the initial stepSize. Returns the number of evaluations actually performed, which - * may be slightly above the maxSteps given. - * - * @param pop the set of individuals to work on - * @param problem the optimization problem - * @param maxSteps the number of evaluations to perform during HC - * @param stepSize the initial mutation step size - * @param minStepSize the minimal step size allowed for a mutation - * @return the number of evaluations actually performed - */ - public static int processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps, double stepSize, double minStepSize) { + } + + /** + * Optimize a population with a default hill-climbing heuristic for a number of fitness evaluations. + * As mutation operator, a mutative step size ES mutation is used, the step size of which is not allowed + * to increase above the initial stepSize. Returns the number of evaluations actually performed, which + * may be slightly above the maxSteps given. + * + * @param pop the set of individuals to work on + * @param problem the optimization problem + * @param maxSteps the number of evaluations to perform during HC + * @param stepSize the initial mutation step size + * @param minStepSize the minimal step size allowed for a mutation + * @return the number of evaluations actually performed + */ + public static int processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps, double stepSize, double minStepSize) { // pop.SetFunctionCalls(0); // or else optimization wont restart on an "old" population // pop.setGenerationTo(0); - int stepsBef = pop.getFunctionCalls(); - processWithHC(pop, problem, new EvaluationTerminator(pop.getFunctionCalls()+maxSteps), new MutateESMutativeStepSizeControl(stepSize, minStepSize, stepSize)); - return pop.getFunctionCalls()-stepsBef; - } - - /** - * Perform hill climbing with default mutation parameters. - * - * @see processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps, double stepSize, double minStepSize) - * @param pop - * @param problem - * @param maxSteps - * @return the number of evaluations actually performed - */ - public static int processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps) { - return processWithHC(pop, problem, maxSteps, defaultMutationStepSize, minMutationStepSize); - } - - /** - * Optimize a population with a default hill-climbing heuristic with a given termination criterion and mutation operator. - * - * @param pop - * @param problem - * @param term - * @param mute - */ - public static void processWithHC(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, InterfaceMutation mute) { - HillClimbing hc = new HillClimbing(); - // HC depends heavily on the selected mutation operator! - hc.setProblem(problem); - mute.init(problem.getIndividualTemplate(), problem); - hc.SetMutationOperator(mute); - if (pop.size() != pop.getTargetSize()) { - System.err.println(pop.size() + " vs. "+ pop.getTargetSize()); - System.err.println("warning: population size and vector size dont match! (PostProcess::processWithHC)"); - } - hc.setPopulation(pop); + int stepsBef = pop.getFunctionCalls(); + processWithHC(pop, problem, new EvaluationTerminator(pop.getFunctionCalls() + maxSteps), new MutateESMutativeStepSizeControl(stepSize, minStepSize, stepSize)); + return pop.getFunctionCalls() - stepsBef; + } + + /** + * Perform hill climbing with default mutation parameters. + * + * @param pop + * @param problem + * @param maxSteps + * @return the number of evaluations actually performed + * @see processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps, double stepSize, double minStepSize) + */ + public static int processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps) { + return processWithHC(pop, problem, maxSteps, defaultMutationStepSize, minMutationStepSize); + } + + /** + * Optimize a population with a default hill-climbing heuristic with a given termination criterion and mutation operator. + * + * @param pop + * @param problem + * @param term + * @param mute + */ + public static void processWithHC(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, InterfaceMutation mute) { + HillClimbing hc = new HillClimbing(); + // HC depends heavily on the selected mutation operator! + hc.setProblem(problem); + mute.init(problem.getIndividualTemplate(), problem); + hc.SetMutationOperator(mute); + if (pop.size() != pop.getTargetSize()) { + System.err.println(pop.size() + " vs. " + pop.getTargetSize()); + System.err.println("warning: population size and vector size dont match! (PostProcess::processWithHC)"); + } + hc.setPopulation(pop); // hc.initByPopulation(pop, false); - OptimizerRunnable ppRunnable = new OptimizerRunnable(OptimizerFactory.makeParams(hc, pop, problem, 0, term), true); - - runPP(ppRunnable); - - } - - // TODO ! test this - public static int processWithGDA(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, int baseEvals, double minStepSize, double maxStepSize) { - GradientDescentAlgorithm gda = new GradientDescentAlgorithm(); - gda.setAdaptStepSizeLocally(true); - gda.setProblem(problem); - gda.setLocalMinStepSize(minStepSize); - gda.setLocalMaxStepSize(maxStepSize); - gda.setRecovery(false); - gda.initByPopulation(pop, false); + OptimizerRunnable ppRunnable = new OptimizerRunnable(OptimizerFactory.makeParams(hc, pop, problem, 0, term), true); - int funCallsBefore = pop.getFunctionCalls(); - pop.SetFunctionCalls(baseEvals); + runPP(ppRunnable); - OptimizerRunnable ppRunnable = new OptimizerRunnable(OptimizerFactory.makeParams(gda, pop, problem, 0, term), true); - runPP(ppRunnable); + } + + // TODO ! test this + public static int processWithGDA(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, int baseEvals, double minStepSize, double maxStepSize) { + GradientDescentAlgorithm gda = new GradientDescentAlgorithm(); + gda.setAdaptStepSizeLocally(true); + gda.setProblem(problem); + gda.setLocalMinStepSize(minStepSize); + gda.setLocalMaxStepSize(maxStepSize); + gda.setRecovery(false); + gda.initByPopulation(pop, false); + + int funCallsBefore = pop.getFunctionCalls(); + pop.SetFunctionCalls(baseEvals); + + OptimizerRunnable ppRunnable = new OptimizerRunnable(OptimizerFactory.makeParams(gda, pop, problem, 0, term), true); + runPP(ppRunnable); // ppRunnable.getStats().createNextGenerationPerformed(gda.getPopulation(), gda, null); - int funCallsDone = pop.getFunctionCalls()-baseEvals; - pop.SetFunctionCalls(funCallsBefore); + int funCallsDone = pop.getFunctionCalls() - baseEvals; + pop.SetFunctionCalls(funCallsBefore); - return funCallsDone; - } + return funCallsDone; + } + + /** + * Search for a local minimum using nelder mead and return the solution found and the number of steps + * (evaluations) actually performed. This uses the whole population as starting population for nelder mead + * meaning that typically only one best is returned. + * Returns the number of function calls really performed by the method and a flag indicating whether the + * processing was aborted by the user. Sets the number of function calls + * in the population back to the original count. + * If the baseEvals parameter (which should be >= 0) is > 0, then the number of evaluations is set as + * number of evaluations before the optimization using the given terminator. + * + * @param pop + * @param problem + * @param term + * @param baseEvals + * @return pair of the number of performed function calls and a flag indicating whether the processing was aborted by the user + */ + public static Pair processWithNMS(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, int baseEvals) { + NelderMeadSimplex nms = new NelderMeadSimplex(); + nms.setProblemAndPopSize(problem); + nms.setGenerationCycle(5); + nms.initByPopulation(pop, false); + int funCallsBefore = pop.getFunctionCalls(); + pop.SetFunctionCalls(baseEvals); + + OptimizerRunnable ppRunnable = new OptimizerRunnable(OptimizerFactory.makeParams(nms, pop, problem, 0, term), true); + // as nms creates a new population and has already evaluated them, send a signal to stats + ppRunnable.getStats().createNextGenerationPerformed(nms.getPopulation(), nms, null); - /** - * Search for a local minimum using nelder mead and return the solution found and the number of steps - * (evaluations) actually performed. This uses the whole population as starting population for nelder mead - * meaning that typically only one best is returned. - * Returns the number of function calls really performed by the method and a flag indicating whether the - * processing was aborted by the user. Sets the number of function calls - * in the population back to the original count. - * If the baseEvals parameter (which should be >= 0) is > 0, then the number of evaluations is set as - * number of evaluations before the optimization using the given terminator. - * - * @param pop - * @param problem - * @param term - * @param baseEvals - * @return pair of the number of performed function calls and a flag indicating whether the processing was aborted by the user - */ - public static Pair processWithNMS(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, int baseEvals) { - NelderMeadSimplex nms = new NelderMeadSimplex(); - nms.setProblemAndPopSize(problem); - nms.setGenerationCycle(5); - nms.initByPopulation(pop, false); - int funCallsBefore = pop.getFunctionCalls(); - pop.SetFunctionCalls(baseEvals); - - OptimizerRunnable ppRunnable = new OptimizerRunnable(OptimizerFactory.makeParams(nms, pop, problem, 0, term), true); - // as nms creates a new population and has already evaluated them, send a signal to stats - ppRunnable.getStats().createNextGenerationPerformed(nms.getPopulation(), nms, null); - -// if (problem instanceof InterfaceFirstOrderDerivableProblem) { -// double[] x = pop.getBestEAIndividual().getDoublePosition(); -// System.out.println("grads: " + BeanInspector.toString(((InterfaceFirstOrderDerivableProblem)problem).getFirstOrderGradients(x))); -// } - - runPP(ppRunnable); - // if (problem instanceof InterfaceFirstOrderDerivableProblem) { // double[] x = pop.getBestEAIndividual().getDoublePosition(); // System.out.println("grads: " + BeanInspector.toString(((InterfaceFirstOrderDerivableProblem)problem).getFirstOrderGradients(x))); // } - int funCallsDone = pop.getFunctionCalls()-baseEvals; - pop.SetFunctionCalls(funCallsBefore); - - return new Pair(funCallsDone, ppRunnable.wasAborted()); - } - - /** - * Search for a local minimum using CMA and return the solution found and the number of steps - * (evaluations) actually performed. This uses the whole population as starting population for nelder mead - * meaning that typically only one best is returned. - * Returns the number of function calls really performed by the method and a flag indicating whether the - * processing was aborted by the user. Sets the number of function calls - * in the population back to the original count. If the baseEvals parameter (which should be >= 0) is > 0, - * then the number of evaluations is set as - * number of evaluations before the optimization using the given terminator. - * - * @param pop - * @param problem - * @param term - * @param baseEvals - * @return - */ - public static Pair processWithCMA(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, int baseEvals) { - MutateESRankMuCMA mutator = new MutateESRankMuCMA(); - mutator.setInitializeSigma(ESMutationInitialSigma.avgInitialDistance); - EvolutionStrategies es = OptimizerFactory.createEvolutionStrategy(pop.size()/2, pop.size(), false, mutator, 1., new CrossoverESDefault(), 0., - new SelectBestIndividuals(), problem, null); - for (int i=0; i(funCallsDone, ppRunnable.wasAborted()); - } - - private static boolean checkRange(AbstractEAIndividual indy) { - InterfaceDataTypeDouble idd = (InterfaceDataTypeDouble)indy; - return Mathematics.isInRange(idd.getDoubleData(), idd.getDoubleRange()); - } +// if (problem instanceof InterfaceFirstOrderDerivableProblem) { +// double[] x = pop.getBestEAIndividual().getDoublePosition(); +// System.out.println("grads: " + BeanInspector.toString(((InterfaceFirstOrderDerivableProblem)problem).getFirstOrderGradients(x))); +// } - /** - * For a given candidate solution, perform a nelder-mead-simplex refining search by producing a sample - * population around the candidate (with given perturbation ratio relative to the problem range). - * Then, the nelder mead algorithm is started and the best individual returned together with - * the evaluations actually performed. - * - * @see NelderMeadSimplex.createNMSPopulation(candidate, perturbRatio, range, includeCand) - * - * @param cand - * @param hcSteps - * @param initPerturbation - * @param prob - * @return - */ - public static Pair localSolverNMS(AbstractEAIndividual cand, int hcSteps, - double initPerturbation, AbstractOptimizationProblem prob) { - - Population pop = new Population(1); - pop.add(cand); - int evalsDone = processSingleCandidates(PostProcessMethod.nelderMead, pop, hcSteps, initPerturbation, prob, null); - - return new Pair(pop.getBestEAIndividual(), evalsDone); - } + int funCallsDone = pop.getFunctionCalls() - baseEvals; + pop.SetFunctionCalls(funCallsBefore); - /** - * Create a sub-population around an indicated individual from the candidate set. - * Depending on the post processing method, this is done slightly differently. For hill-climbing, - * an error message is produced. - * - * @see #createPopInSubRange(double, AbstractOptimizationProblem, AbstractEAIndividual) - * @see #NelderMeadSimplex.createNMSPopulation(AbstractEAIndividual, double, double[][], boolean) - * @param method - * @param problem - * @param candidates - * @param index index of the individual for which to produce the sub population - * @param maxPerturbation - * @param includeCand - */ - public static Population createLSSupPopulation(PostProcessMethod method, AbstractOptimizationProblem problem, Population candidates, int index, double maxRelativePerturbation, boolean includeCand) { - Population subPop = null; - switch (method) { - case cmaES: - // target size minus one because indy is added later - subPop = new Population(); - createPopInSubRange(subPop, maxRelativePerturbation, getDefCMAPopSize(candidates.getEAIndividual(index))-1, candidates.getEAIndividual(index)); - break; - case hillClimber: - System.err.println("INVALID in createLSSupPopulation"); - break; - case nelderMead: - double[][] range = ((InterfaceDataTypeDouble)candidates.getEAIndividual(index)).getDoubleRange(); - double perturb = findNMSPerturb(candidates, index, relToAbsPerturb(maxRelativePerturbation, range)); - if (TRACE) { - System.out.println("perturb " + index + " is " + perturb); - } - subPop = NelderMeadSimplex.createNMSPopulation(candidates.getEAIndividual(index), absToRelPerturb(perturb, range), range, false); - } + return new Pair(funCallsDone, ppRunnable.wasAborted()); + } + + /** + * Search for a local minimum using CMA and return the solution found and the number of steps + * (evaluations) actually performed. This uses the whole population as starting population for nelder mead + * meaning that typically only one best is returned. + * Returns the number of function calls really performed by the method and a flag indicating whether the + * processing was aborted by the user. Sets the number of function calls + * in the population back to the original count. If the baseEvals parameter (which should be >= 0) is > 0, + * then the number of evaluations is set as + * number of evaluations before the optimization using the given terminator. + * + * @param pop + * @param problem + * @param term + * @param baseEvals + * @return + */ + public static Pair processWithCMA(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, int baseEvals) { + MutateESRankMuCMA mutator = new MutateESRankMuCMA(); + mutator.setInitializeSigma(ESMutationInitialSigma.avgInitialDistance); + EvolutionStrategies es = OptimizerFactory.createEvolutionStrategy(pop.size() / 2, pop.size(), false, mutator, 1., new CrossoverESDefault(), 0., + new SelectBestIndividuals(), problem, null); + for (int i = 0; i < pop.size(); i++) { + pop.getEAIndividual(i).initCloneOperators(mutator, 1., new CrossoverESDefault(), 0., problem); + } + es.initByPopulation(pop, false); + + OptimizationParameters cmaParams = OptimizerFactory.makeParams(es, pop, problem, 0, term); + + int funCallsBefore = pop.getFunctionCalls(); + pop.SetFunctionCalls(baseEvals); + + OptimizerRunnable ppRunnable = new OptimizerRunnable(cmaParams, true); + ppRunnable.getStats().createNextGenerationPerformed(cmaParams.getOptimizer().getPopulation(), cmaParams.getOptimizer(), null); + + runPP(ppRunnable); + pop.clear(); + pop.addPopulation(es.getPopulation()); + + int funCallsDone = es.getPopulation().getFunctionCalls() - baseEvals; + pop.SetFunctionCalls(funCallsBefore); + + return new Pair(funCallsDone, ppRunnable.wasAborted()); + } + + private static boolean checkRange(AbstractEAIndividual indy) { + InterfaceDataTypeDouble idd = (InterfaceDataTypeDouble) indy; + return Mathematics.isInRange(idd.getDoubleData(), idd.getDoubleRange()); + } + + /** + * For a given candidate solution, perform a nelder-mead-simplex refining search by producing a sample + * population around the candidate (with given perturbation ratio relative to the problem range). + * Then, the nelder mead algorithm is started and the best individual returned together with + * the evaluations actually performed. + * + * @param cand + * @param hcSteps + * @param initPerturbation + * @param prob + * @return + * @see NelderMeadSimplex.createNMSPopulation(candidate, perturbRatio, range, includeCand) + */ + public static Pair localSolverNMS(AbstractEAIndividual cand, int hcSteps, + double initPerturbation, AbstractOptimizationProblem prob) { + + Population pop = new Population(1); + pop.add(cand); + int evalsDone = processSingleCandidates(PostProcessMethod.nelderMead, pop, hcSteps, initPerturbation, prob, null); + + return new Pair(pop.getBestEAIndividual(), evalsDone); + } + + /** + * Create a sub-population around an indicated individual from the candidate set. + * Depending on the post processing method, this is done slightly differently. For hill-climbing, + * an error message is produced. + * + * @param method + * @param problem + * @param candidates + * @param index index of the individual for which to produce the sub population + * @param maxPerturbation + * @param includeCand + * @see #createPopInSubRange(double, AbstractOptimizationProblem, AbstractEAIndividual) + * @see #NelderMeadSimplex.createNMSPopulation(AbstractEAIndividual, double, double[][], boolean) + */ + public static Population createLSSupPopulation(PostProcessMethod method, AbstractOptimizationProblem problem, Population candidates, int index, double maxRelativePerturbation, boolean includeCand) { + Population subPop = null; + switch (method) { + case cmaES: + // target size minus one because indy is added later + subPop = new Population(); + createPopInSubRange(subPop, maxRelativePerturbation, getDefCMAPopSize(candidates.getEAIndividual(index)) - 1, candidates.getEAIndividual(index)); + break; + case hillClimber: + System.err.println("INVALID in createLSSupPopulation"); + break; + case nelderMead: + double[][] range = ((InterfaceDataTypeDouble) candidates.getEAIndividual(index)).getDoubleRange(); + double perturb = findNMSPerturb(candidates, index, relToAbsPerturb(maxRelativePerturbation, range)); + if (TRACE) { + System.out.println("perturb " + index + " is " + perturb); + } + subPop = NelderMeadSimplex.createNMSPopulation(candidates.getEAIndividual(index), absToRelPerturb(perturb, range), range, false); + } // subPop.setSameParams(candidates); - return subPop; - } - - public static double relToAbsPerturb(double maxRelativePerturbation, double[][] range) { - return maxRelativePerturbation*(Mathematics.getAvgRange(range)); - } - - public static double absToRelPerturb(double maxAbsPerturbation, double[][] range) { - return maxAbsPerturbation/(Mathematics.getAvgRange(range)); - } - - private static int getDefCMAPopSize(AbstractEAIndividual template) { - if (isDoubleCompliant(template)) { - double[][] range = getDoubleRange(template); - int targetSize = (int) (4.0 + 3.0 * Math.log(range.length)); // minus one because indy is added later - return targetSize; - } else { - System.err.println("Warning, invalid individual for PostProcess.getDefCMAPopSize"); - return 10; - } - } + return subPop; + } - /** - * Employ hill-climbing directly or NM/CMA on the candidates. The candidate population - * must not be empty and candidates must implement InterfaceDataTypeDouble. - * The given number of steps gives the number of evaluations which may not be hit exactly. - * The population will not be altered for Nelder-Mead or CMA-ES, and the evaluation calls will not be added to - * the candidate population! - * - * @see #processWithHC(Population, AbstractOptimizationProblem, InterfaceTerminator, InterfaceMutation) - * @see #processSingleCandidatesNMCMA(PostProcessMethod, Population, InterfaceTerminator, double, AbstractOptimizationProblem) - * @param method - * @param candidates - * @param steps number of evaluations to be performed (summed up) - * @param maxPerturbation - * @param prob - * @param mute the mutator to use (in case of HC) - * @return the evaluations performed - */ - public static int processSingleCandidates(PostProcessMethod method, Population candidates, int steps, double maxPerturbation, AbstractOptimizationProblem prob, InterfaceMutation mute) { - int dim=((InterfaceDataTypeDouble)candidates.getEAIndividual(0)).getDoubleRange().length; - int candCnt = candidates.size(); - - if (method == PostProcessMethod.hillClimber) { - int evalsOld = candidates.getFunctionCalls(); - processWithHC(candidates, prob, new EvaluationTerminator(evalsOld+steps), mute); - int evalsDone = candidates.getFunctionCalls()-evalsOld; - candidates.SetFunctionCalls(evalsOld); - return evalsDone; - } else { - int stepsPerCand = (steps-(candCnt*(dim-1)))/candCnt; - if (TRACE) { - System.out.println("employing " + stepsPerCand + " steps per cand."); - } - if (stepsPerCand < dim) { - System.err.println("Too few steps allowed in processSingleCandidates!"); - System.err.println("Method: " + method + ", cands: " + candidates.size() + ", steps: " + steps); - return 0; - } else { - EvaluationTerminator term = new EvaluationTerminator(stepsPerCand); - return processSingleCandidatesNMCMA(method, candidates, term, maxPerturbation, prob); - } - } - } - - /** - * For each candidate individual, create an own sub-population and optimize it separately. Candidates must have - * been evaluated earlier. The candidates population is not altered. - * The performed evaluation calls for problem dimension n will be (n+k)*candPopSize for a positive integer k. - * At the moment, the function calls are distributed evenly between all candidate solutions. This could be - * improved by checking the convergence state in the future. The given terminator will be applied to each - * candidate sub-population anew. If the terminator is null, 10*n steps will be performed on each candidate. - * - * A double value is added to each solution individual that replaces its ancestor candidate, using the key - * PostProcess.movedDistanceKey. - * It indicates the phenotype distance the found solution has moved relatively to the original candidate. - * - * @see #findNMSPerturb(Population, int, double) - * @see #createLSSupPopulation(PostProcessMethod, AbstractOptimizationProblem, Population, int, double, boolean) - * @see #processWithCMA(Population, AbstractOptimizationProblem, InterfaceTerminator, int) - * @see #processWithNMS(Population, AbstractOptimizationProblem, InterfaceTerminator, int) - * @param method NM or CMA is allowed here - * @param candidates - * @param term - * @param maxRelativePerturbation perturbation for the sub population relative to problem range - * @param prob - * @return the number of evaluations performed - */ - public static int processSingleCandidatesNMCMA(PostProcessMethod method, Population candidates, InterfaceTerminator term, double maxRelativePerturbation, AbstractOptimizationProblem prob) { - ArrayList nmPops = new ArrayList(); - int stepsPerf = 0; - Population subPop; - - for (int i=0; i stepsAbortedFlag = null; - for (int i=0; i + * A double value is added to each solution individual that replaces its ancestor candidate, using the key + * PostProcess.movedDistanceKey. + * It indicates the phenotype distance the found solution has moved relatively to the original candidate. + * + * @param method NM or CMA is allowed here + * @param candidates + * @param term + * @param maxRelativePerturbation perturbation for the sub population relative to problem range + * @param prob + * @return the number of evaluations performed + * @see #findNMSPerturb(Population, int, double) + * @see #createLSSupPopulation(PostProcessMethod, AbstractOptimizationProblem, Population, int, double, boolean) + * @see #processWithCMA(Population, AbstractOptimizationProblem, InterfaceTerminator, int) + * @see #processWithNMS(Population, AbstractOptimizationProblem, InterfaceTerminator, int) + */ + public static int processSingleCandidatesNMCMA(PostProcessMethod method, Population candidates, InterfaceTerminator term, double maxRelativePerturbation, AbstractOptimizationProblem prob) { + ArrayList nmPops = new ArrayList(); + int stepsPerf = 0; + Population subPop; + + for (int i = 0; i < candidates.size(); i++) { // create all subPopulations + subPop = createLSSupPopulation(method, prob, candidates, i, maxRelativePerturbation, false); + + prob.evaluate(subPop); + stepsPerf += subPop.size(); + subPop.add(candidates.getEAIndividual(i).clone()); + nmPops.add(subPop); + } + + if (term == null) { + int stepsPerCand = 10 * (nmPops.get(0).size() - 1); // == 10*dim for NM + if (TRACE) { + System.out.println("employing " + stepsPerCand + " per candidate."); + } + if (stepsPerCand < 1) { + System.err.println("Too few steps allowed!"); + return 0; + } + term = new EvaluationTerminator(stepsPerCand); + } + Pair stepsAbortedFlag = null; + for (int i = 0; i < candidates.size(); i++) { // improve each single sub pop + subPop = nmPops.get(i); + term.init(prob); // if (TRACE) System.out.println("*** before " + subPop.getBestEAIndividual().getStringRepresentation()); - switch (method) { - case nelderMead: stepsAbortedFlag = PostProcess.processWithNMS(subPop, prob, term, subPop.size()-1); - break; - case cmaES: stepsAbortedFlag = PostProcess.processWithCMA(subPop, prob, term, subPop.size()-1); - break; - default: System.err.println("Invalid pp method in processSingleCandidatesNMCMA!"); - } - if (stepsAbortedFlag==null) { - System.err.println("Error in processSingleCandidatesNMCMA!"); - } - stepsPerf += stepsAbortedFlag.head; - if (stepsAbortedFlag.tail) { // user aborted post processing - System.err.println("Warning: Post processing interrupted after " + i + " of " + candidates.size() + " candidates were processed."); - break; - } + switch (method) { + case nelderMead: + stepsAbortedFlag = PostProcess.processWithNMS(subPop, prob, term, subPop.size() - 1); + break; + case cmaES: + stepsAbortedFlag = PostProcess.processWithCMA(subPop, prob, term, subPop.size() - 1); + break; + default: + System.err.println("Invalid pp method in processSingleCandidatesNMCMA!"); + } + if (stepsAbortedFlag == null) { + System.err.println("Error in processSingleCandidatesNMCMA!"); + } + stepsPerf += stepsAbortedFlag.head; + if (stepsAbortedFlag.tail) { // user aborted post processing + System.err.println("Warning: Post processing interrupted after " + i + " of " + candidates.size() + " candidates were processed."); + break; + } - // if (TRACE) System.out.println("*** after: " + subPop.getBestEAIndividual().getStringRepresentation()); - if (checkRange(subPop.getBestEAIndividual())) { - // and replace corresponding individual (should usually be better) + // if (TRACE) System.out.println("*** after: " + subPop.getBestEAIndividual().getStringRepresentation()); + if (checkRange(subPop.getBestEAIndividual())) { + // and replace corresponding individual (should usually be better) // if (subPop.getBestEAIndividual().isDominant(candidates.getEAIndividual(i))) { // TODO Multiobjective??? - if (subPop.getBestEAIndividual().getFitness(0) popD = new Pair(pop, 1.); - int i=0; - int evalCnt = 0; - while (popD.tail() > 0.001) { - i++; + public static void main(String[] args) { + AbstractOptimizationProblem problem = new FM0Problem(); + InterfaceMultimodalProblemKnown mmp = (InterfaceMultimodalProblemKnown) problem; + OptimizerRunnable runnable = OptimizerFactory.getOptRunnable(OptimizerFactory.STD_GA, problem, 100, null); + runnable.run(); + Population pop = runnable.getGOParams().getOptimizer().getPopulation(); +// System.out.println("no optima found: " + mmp.getNumberOfFoundOptima(pop)); + Population found = getFoundOptima(pop, mmp.getRealOptima(), 0.05, true); + System.out.println("all found (" + found.size() + "): " + BeanInspector.toString(found)); + + Pair popD = new Pair(pop, 1.); + int i = 0; + int evalCnt = 0; + while (popD.tail() > 0.001) { + i++; // public static PopDoublePair clusterHC(pop, problem, sigmaCluster, funCalls, keepClusterRatio, mute) { - popD = clusterLocalSearch(PostProcessMethod.hillClimber, popD.head(), problem, 0.01, 1500, 0.1, new MutateESFixedStepSize(0.02)); - evalCnt += popD.head().getFunctionCalls(); - System.out.println("popsize is " + popD.head().size()); - } - found = getFoundOptima(popD.head(), mmp.getRealOptima(), 0.05, true); - System.out.println("found at " + i + " (" + found.size() + "): " + BeanInspector.toString(found)); - System.out.println("funcalls: " + evalCnt); + popD = clusterLocalSearch(PostProcessMethod.hillClimber, popD.head(), problem, 0.01, 1500, 0.1, new MutateESFixedStepSize(0.02)); + evalCnt += popD.head().getFunctionCalls(); + System.out.println("popsize is " + popD.head().size()); + } + found = getFoundOptima(popD.head(), mmp.getRealOptima(), 0.05, true); + System.out.println("found at " + i + " (" + found.size() + "): " + BeanInspector.toString(found)); + System.out.println("funcalls: " + evalCnt); // System.out.println(BeanInspector.toString(pop.getMeanFitness())); - + // System.out.println("no optima found: " + mmp.getNumberOfFoundOptima(pop)); // System.out.println("best after: " + AbstractEAIndividual.getDefaultStringRepresentation(pop.getBestEAIndividual())); - - } - - /** - * Cluster a population and reduce it by a certain ratio, then optimize the remaining individuals for a given number of function calls with a LS. - * Return a pair of the optimized population and the improvement in the mean fitness (not normed) that was achieved by the LS run. The returned - * individuals are deep clones, so the given population is not altered. Of a cluster of individuals, the given - * ratio of individuals is kept, more precisely, the best one is kept while the remaining are selected randomly. All loners are kept. - * - * @param method the local search method to be used - * @param pop the population to work on - * @param problem the target problem instance - * @param sigmaCluster minimum clustering distance - * @param funCalls number of function calls for the optimization step - * @param keepClusterRatio of a cluster of individuals, this ratio of individuals is kept for optimization - * @param mute the mutation operator to be used by the hill climber - * @return a pair of the optimized population and the improvement in the mean fitness (not normed) achieved by the HC run - */ - public static Pair clusterLocalSearch(PostProcessMethod method, Population pop, AbstractOptimizationProblem problem, double sigmaCluster, int funCalls, double keepClusterRatio, InterfaceMutation mute) { - int evalsBefore = pop.getFunctionCalls(); - Population clust = (Population)clusterBest(pop, new ClusteringDensityBased(sigmaCluster, 2), keepClusterRatio, KEEP_LONERS, BEST_RAND).clone(); + } - //clust.addPopulationChangedEventListener() - double[] meanFit = clust.getMeanFitness(); - - if (TRACE) { - System.out.println("BEF: funcalls done: " + pop.getFunctionCalls() + ", now allowed: " + funCalls); - } - - int evalsDone = processSingleCandidates(method, clust, funCalls, sigmaCluster/2., problem, mute); - - clust.SetFunctionCalls(evalsBefore + evalsDone); - - double improvement = EuclideanMetric.euclideanDistance(meanFit, clust.getMeanFitness()); - if (TRACE) { - System.out.println("improvement by " + improvement + " funcalls done: " + evalsDone); - } - return new Pair(clust, improvement); - } - - /** - * Do some data output for multimodal problems to the listener. - * This may be expensive computationally. - */ - public static void evaluateMultiModal(Population solutions, AbstractOptimizationProblem prob, InterfaceTextListener listener) { - if (listener == null) { - return; - } - if (prob instanceof InterfaceMultimodalProblemKnown) { - InterfaceMultimodalProblemKnown mmkProb = (InterfaceMultimodalProblemKnown)prob; - listener.println("number of known optima is " + mmkProb.getRealOptima().size()); - listener.println("default epsilon is " + mmkProb.getDefaultAccuracy()); - listener.println("optima found with default epsilon: " + getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true).size()); - listener.println("max peak ratio is " + mmkProb.getMaximumPeakRatio(getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true))); - if (mmkProb.fullListAvailable()) { - for (double epsilon=0.1; epsilon > 0.00000001; epsilon/=10.) { + /** + * Cluster a population and reduce it by a certain ratio, then optimize the remaining individuals for a given number of function calls with a LS. + * Return a pair of the optimized population and the improvement in the mean fitness (not normed) that was achieved by the LS run. The returned + * individuals are deep clones, so the given population is not altered. Of a cluster of individuals, the given + * ratio of individuals is kept, more precisely, the best one is kept while the remaining are selected randomly. All loners are kept. + * + * @param method the local search method to be used + * @param pop the population to work on + * @param problem the target problem instance + * @param sigmaCluster minimum clustering distance + * @param funCalls number of function calls for the optimization step + * @param keepClusterRatio of a cluster of individuals, this ratio of individuals is kept for optimization + * @param mute the mutation operator to be used by the hill climber + * @return a pair of the optimized population and the improvement in the mean fitness (not normed) achieved by the HC run + */ + public static Pair clusterLocalSearch(PostProcessMethod method, Population pop, AbstractOptimizationProblem problem, double sigmaCluster, int funCalls, double keepClusterRatio, InterfaceMutation mute) { + int evalsBefore = pop.getFunctionCalls(); + + Population clust = (Population) clusterBest(pop, new ClusteringDensityBased(sigmaCluster, 2), keepClusterRatio, KEEP_LONERS, BEST_RAND).clone(); + + //clust.addPopulationChangedEventListener() + double[] meanFit = clust.getMeanFitness(); + + if (TRACE) { + System.out.println("BEF: funcalls done: " + pop.getFunctionCalls() + ", now allowed: " + funCalls); + } + + int evalsDone = processSingleCandidates(method, clust, funCalls, sigmaCluster / 2., problem, mute); + + clust.SetFunctionCalls(evalsBefore + evalsDone); + + double improvement = EuclideanMetric.euclideanDistance(meanFit, clust.getMeanFitness()); + if (TRACE) { + System.out.println("improvement by " + improvement + " funcalls done: " + evalsDone); + } + return new Pair(clust, improvement); + } + + /** + * Do some data output for multimodal problems to the listener. + * This may be expensive computationally. + */ + public static void evaluateMultiModal(Population solutions, AbstractOptimizationProblem prob, InterfaceTextListener listener) { + if (listener == null) { + return; + } + if (prob instanceof InterfaceMultimodalProblemKnown) { + InterfaceMultimodalProblemKnown mmkProb = (InterfaceMultimodalProblemKnown) prob; + listener.println("number of known optima is " + mmkProb.getRealOptima().size()); + listener.println("default epsilon is " + mmkProb.getDefaultAccuracy()); + listener.println("optima found with default epsilon: " + getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true).size()); + listener.println("max peak ratio is " + mmkProb.getMaximumPeakRatio(getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true))); + if (mmkProb.fullListAvailable()) { + for (double epsilon = 0.1; epsilon > 0.00000001; epsilon /= 10.) { // out.println("no optima found: " + ((InterfaceMultimodalProblemKnown)mmProb).getNumberOfFoundOptima(pop)); -listener.println("found " + getFoundOptima(solutions, mmkProb.getRealOptima(), epsilon, true).size() + " for epsilon = " + epsilon + ", maxPeakRatio: " + mmkProb.getMaximumPeakRatio(solutions)); -} } - } else { - // TODO in this form it may cost a lot of time and cant be stopped, which is bad + listener.println("found " + getFoundOptima(solutions, mmkProb.getRealOptima(), epsilon, true).size() + " for epsilon = " + epsilon + ", maxPeakRatio: " + mmkProb.getMaximumPeakRatio(solutions)); + } + } + } else { + // TODO in this form it may cost a lot of time and cant be stopped, which is bad // double epsilonPhenoSpace = 0.01, epsilonFitConv = 1e-10, clusterSigma = 0.; // Population extrOpts; // for (int k=0; k<3; k++) { @@ -1052,456 +1052,451 @@ listener.println("found " + getFoundOptima(solutions, mmkProb.getRealOptima(), e // } // epsilonPhenoSpace /= 10.; // } - } - } - - /** - * Cluster the potential optima from a population using {@link #getFoundOptima(Population, Population, double, boolean)} or - * extractPotentialOptima {@link AbstractOptimizationProblem}. Overwrites the given histogram and returns the found solutions - * within a new population. - * - * @param pop - * @param prob - * @param hist - * @param accuracy - * @param maxPPEvalsPerIndy - * @return - */ - public static Population clusterBestUpdateHistogram(Population pop, AbstractOptimizationProblem prob, SolutionHistogram hist, int crit, double accuracy) { - Population opts = clusterBest(pop, accuracy, 0, KEEP_LONERS, BEST_ONLY); - hist.updateFrom(opts, crit); - return opts; - } - - /** - * General post processing method, receiving parameter instance for specification. - * Optional clustering and HC step, output contains population measures, fitness histogram and - * a list of solutions after post processing. - * - * @param params - * @param inputPop - * @param problem - * @param listener - * @return the clustered, post-processed population - */ - public static Population postProcess(InterfacePostProcessParams params, Population inputPop, AbstractOptimizationProblem problem, InterfaceTextListener listener) { - if (params.isDoPostProcessing() && (inputPop!=null)) { - Plot plot; - - Population clusteredPop, outputPop, stateBeforeLS; - if (params.getPostProcessClusterSigma() > 0) { - // ##### pre clustering - clusteredPop = (Population)PostProcess.clusterBest(inputPop, params.getPostProcessClusterSigma(), 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); - if (clusteredPop.size() < inputPop.size()) { - if (listener != null) { - listener.println("Initial clustering reduced population size from " + inputPop.size() + " to " + clusteredPop.size()); - } - } else if (listener != null) { - listener.println("Initial clustering yielded no size reduction."); - } - } else { - clusteredPop = inputPop; + } + } + + /** + * Cluster the potential optima from a population using {@link #getFoundOptima(Population, Population, double, boolean)} or + * extractPotentialOptima {@link AbstractOptimizationProblem}. Overwrites the given histogram and returns the found solutions + * within a new population. + * + * @param pop + * @param prob + * @param hist + * @param accuracy + * @param maxPPEvalsPerIndy + * @return + */ + public static Population clusterBestUpdateHistogram(Population pop, AbstractOptimizationProblem prob, SolutionHistogram hist, int crit, double accuracy) { + Population opts = clusterBest(pop, accuracy, 0, KEEP_LONERS, BEST_ONLY); + hist.updateFrom(opts, crit); + return opts; + } + + /** + * General post processing method, receiving parameter instance for specification. + * Optional clustering and HC step, output contains population measures, fitness histogram and + * a list of solutions after post processing. + * + * @param params + * @param inputPop + * @param problem + * @param listener + * @return the clustered, post-processed population + */ + public static Population postProcess(InterfacePostProcessParams params, Population inputPop, AbstractOptimizationProblem problem, InterfaceTextListener listener) { + if (params.isDoPostProcessing() && (inputPop != null)) { + Plot plot; + + Population clusteredPop, outputPop, stateBeforeLS; + if (params.getPostProcessClusterSigma() > 0) { + // ##### pre clustering + clusteredPop = (Population) PostProcess.clusterBest(inputPop, params.getPostProcessClusterSigma(), 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); + if (clusteredPop.size() < inputPop.size()) { + if (listener != null) { + listener.println("Initial clustering reduced population size from " + inputPop.size() + " to " + clusteredPop.size()); } - - int stepsDone = 0; - if (params.getPostProcessSteps() > 0) { - double stepSize = selectMaxSearchRange(params.getPPMethod(), params.getPostProcessClusterSigma()); - stateBeforeLS = (Population)clusteredPop.clone(); - // Actual local search comes here - InterfaceMutation mutator; - if (params.getPPMethod() == PostProcessMethod.hillClimber){ - mutator = new MutateESMutativeStepSizeControl(stepSize, minMutationStepSize, stepSize); + } else if (listener != null) { + listener.println("Initial clustering yielded no size reduction."); + } + } else { + clusteredPop = inputPop; + } + + int stepsDone = 0; + if (params.getPostProcessSteps() > 0) { + double stepSize = selectMaxSearchRange(params.getPPMethod(), params.getPostProcessClusterSigma()); + stateBeforeLS = (Population) clusteredPop.clone(); + // Actual local search comes here + InterfaceMutation mutator; + if (params.getPPMethod() == PostProcessMethod.hillClimber) { + mutator = new MutateESMutativeStepSizeControl(stepSize, minMutationStepSize, stepSize); // stepsDone = processWithHC(clusteredPop, problem, params.getPostProcessSteps(), stepSize, minMutationStepSize); - } else { - mutator = null; - } - // #### Actuall call to post processing - stepsDone = processSingleCandidates(params.getPPMethod(), clusteredPop, params.getPostProcessSteps(), stepSize, problem, mutator); + } else { + mutator = null; + } + // #### Actuall call to post processing + stepsDone = processSingleCandidates(params.getPPMethod(), clusteredPop, params.getPostProcessSteps(), stepSize, problem, mutator); - if (listener != null) { - listener.println("Post processing: " + stepsDone + " steps done."); - } - if (params.isWithPlot()) { - plot = draw("After " + stepsDone + " steps ("+ params.getPPMethod() + ")", null, stateBeforeLS, clusteredPop, problem); - } - // ##### post clustering - // some individuals may have now converged again - if (params.getPostProcessClusterSigma() > 0) { - // so if wished, cluster again. - outputPop = (Population)PostProcess.clusterBest(clusteredPop, params.getPostProcessClusterSigma(), 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); - if (outputPop.size() < clusteredPop.size()) { - if (listener != null) { - listener.println("Second clustering reduced population size from " + clusteredPop.size() + " to " + outputPop.size()); - } - } else if (listener != null) { - listener.println("Second clustering yielded no size reduction."); - } - } else { - outputPop = clusteredPop; - } - } else { - outputPop = clusteredPop; + if (listener != null) { + listener.println("Post processing: " + stepsDone + " steps done."); + } + if (params.isWithPlot()) { + plot = draw("After " + stepsDone + " steps (" + params.getPPMethod() + ")", null, stateBeforeLS, clusteredPop, problem); + } + // ##### post clustering + // some individuals may have now converged again + if (params.getPostProcessClusterSigma() > 0) { + // so if wished, cluster again. + outputPop = (Population) PostProcess.clusterBest(clusteredPop, params.getPostProcessClusterSigma(), 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); + if (outputPop.size() < clusteredPop.size()) { + if (listener != null) { + listener.println("Second clustering reduced population size from " + clusteredPop.size() + " to " + outputPop.size()); + } + } else if (listener != null) { + listener.println("Second clustering yielded no size reduction."); } + } else { + outputPop = clusteredPop; + } + } else { + outputPop = clusteredPop; + } - if (params.isWithPlot()) { - plot = draw("After " + stepsDone + " steps (" + params.getPPMethod() + ")" + ((params.getPostProcessClusterSigma()>0) ? " and second clustering" : ""), null, outputPop, null, problem); - } - // ##### some statistics - double upBnd = PhenotypeMetric.norm(outputPop.getWorstEAIndividual().getFitness())*1.1; - upBnd = Math.pow(10,Math.floor(Math.log10(upBnd)+1)); - double lowBnd = 0; - int fitCrit = 0; // use first fitness criterion - SolutionHistogram solHist = SolutionHistogram.createFitNormHistogram(outputPop, lowBnd, upBnd, 20, fitCrit); + if (params.isWithPlot()) { + plot = draw("After " + stepsDone + " steps (" + params.getPPMethod() + ")" + ((params.getPostProcessClusterSigma() > 0) ? " and second clustering" : ""), null, outputPop, null, problem); + } + // ##### some statistics + double upBnd = PhenotypeMetric.norm(outputPop.getWorstEAIndividual().getFitness()) * 1.1; + upBnd = Math.pow(10, Math.floor(Math.log10(upBnd) + 1)); + double lowBnd = 0; + int fitCrit = 0; // use first fitness criterion + SolutionHistogram solHist = SolutionHistogram.createFitNormHistogram(outputPop, lowBnd, upBnd, 20, fitCrit); // PostProcessInterim.outputResult((AbstractOptimizationProblem)goParams.getProblem(), outputPop, 0.01, System.out, 0, 2000, 20, goParams.getPostProcessSteps()); - if (outputPop.size()>1) { - if (listener != null) { - listener.println("measures: " + BeanInspector.toString(outputPop.getPopulationMeasures())); - } - if (listener != null) { - listener.println("pop.metric: " + BeanInspector.toString(outputPop.getPopMetric())); - } - if (listener != null) { - listener.println("solution histogram: " + solHist + ", score " + solHist.getScore()); - } - if ((listener != null) && (problem instanceof InterfaceInterestingHistogram)) { - SolutionHistogram pSolHist = ((InterfaceInterestingHistogram)problem).getHistogram(); - pSolHist.updateFrom(outputPop, fitCrit); - listener.println("problem-defined histogram: " + pSolHist + ", score " + pSolHist.getScore()); - } - } - - //////////// multimodal data output - evaluateMultiModal(outputPop, problem, listener); + if (outputPop.size() > 1) { + if (listener != null) { + listener.println("measures: " + BeanInspector.toString(outputPop.getPopulationMeasures())); + } + if (listener != null) { + listener.println("pop.metric: " + BeanInspector.toString(outputPop.getPopMetric())); + } + if (listener != null) { + listener.println("solution histogram: " + solHist + ", score " + solHist.getScore()); + } + if ((listener != null) && (problem instanceof InterfaceInterestingHistogram)) { + SolutionHistogram pSolHist = ((InterfaceInterestingHistogram) problem).getHistogram(); + pSolHist.updateFrom(outputPop, fitCrit); + listener.println("problem-defined histogram: " + pSolHist + ", score " + pSolHist.getScore()); + } + } - Population nBestPop = outputPop.getBestNIndividuals(0, -1); // the individuals are returned and sorted, all of them if n<=0 - if (params.getPrintNBest()!=0) { - int printK = ((params.getPrintNBest()>0) ? params.getPrintNBest() : nBestPop.size()); - printK = Math.min(printK, nBestPop.size()); - if (listener != null) { - listener.println("Best after post process:" + " (first " + printK + " of " + outputPop.size() + ")"); - } + //////////// multimodal data output + evaluateMultiModal(outputPop, problem, listener); + + Population nBestPop = outputPop.getBestNIndividuals(0, -1); // the individuals are returned and sorted, all of them if n<=0 + if (params.getPrintNBest() != 0) { + int printK = ((params.getPrintNBest() > 0) ? params.getPrintNBest() : nBestPop.size()); + printK = Math.min(printK, nBestPop.size()); + if (listener != null) { + listener.println("Best after post process:" + " (first " + printK + " of " + outputPop.size() + ")"); + } // ((outputPop.size()>nBestPop.size()) // ? ( " (first " + nBestPop.size() + " of " + outputPop.size() + ")") : // (" (" + nBestPop.size() + ")") )); - //////////// output some individual data - if (listener != null) { - for (int i=0; i + * For refining, either known optima are used or {@link AbstractOptimizationProblem}.extractPotentialOptima() + * is called. + * + * @param prob + * @param sols + * @param epsilonPhenoSpace + * @param extrOptEpsFitConf + * @param extrOptClustSig clustering distance; if set negative, 0.1 times the respective epsilonPhenoSpace parameter is used for clustering + * @param maxEvals + * @param solHists + * @param treatAsUnknown + * @param listener + * @return + * @see {@link AbstractOptimizationProblem.extractPotentialOptima} + * @see AbstractOptimizationProblem.isPotentialOptimumNMS(AbstractEAIndividual, double, double, int) + */ + public static int[] checkAccuracy(AbstractOptimizationProblem prob, Population sols, double[] epsilonPhenoSpace, + double extrOptEpsFitConf, double extrOptClustSig, int maxEvals, SolutionHistogram[] solHists, boolean treatAsUnknown, + InterfaceTextListener listener) { + int[] foundOpts = new int[epsilonPhenoSpace.length]; + Population extrOpts = null; + if (listener != null) { + listener.println("Accuracy regarding epsilon thresholds " + BeanInspector.toString(epsilonPhenoSpace)); + } // System.out.println("unref: " + sols.getStringRepresentation()); - // extract optima (known or estimated) for different epsilon criteria - for (int k=0; k 0) { - if (listener!=null) { - listener.print(" measures fit: "); - } - int critCnt = extrOpts.getEAIndividual(0).getFitness().length; - for (int i=0; i1) { - if (listener!=null) { - listener.print("; phen: " + BeanInspector.toString(extrOpts.getPopulationMeasures(new PhenotypeMetric()))); - } - if (listener!=null) { - listener.print("; eucl: " + BeanInspector.toString(extrOpts.getPopulationMeasures(new EuclideanMetric()))); - } - if (listener!=null) { - listener.print("; popMetric: " + BeanInspector.toString(extrOpts.getPopulationMeasures())); - } - } - if (listener!=null) { - listener.println(""); - } + } + } + if (extrOpts.size() > 0) { + if (listener != null) { + listener.print(" measures fit: "); + } + int critCnt = extrOpts.getEAIndividual(0).getFitness().length; + for (int i = 0; i < critCnt; i++) { + if (listener != null) { + listener.print(BeanInspector.toString(extrOpts.getFitnessMeasures(i)) + " "); + } + } + if (extrOpts.size() > 1) { + if (listener != null) { + listener.print("; phen: " + BeanInspector.toString(extrOpts.getPopulationMeasures(new PhenotypeMetric()))); + } + if (listener != null) { + listener.print("; eucl: " + BeanInspector.toString(extrOpts.getPopulationMeasures(new EuclideanMetric()))); + } + if (listener != null) { + listener.print("; popMetric: " + BeanInspector.toString(extrOpts.getPopulationMeasures())); + } + } + if (listener != null) { + listener.println(""); + } // listener.println(" correlations of all (min,max,avg,med,var): "+ BeanInspector.toString(extrOpts.getCorrelations())); - for (int i=16; i>2; i/=2) { - Population bestN = extrOpts.getBestNIndividuals(i, -1); - listener.println(" phen. measures of top " + bestN.size() + ": " + BeanInspector.toString(bestN.getPopulationMeasures(new PhenotypeMetric()))); + for (int i = 16; i > 2; i /= 2) { + Population bestN = extrOpts.getBestNIndividuals(i, -1); + listener.println(" phen. measures of top " + bestN.size() + ": " + BeanInspector.toString(bestN.getPopulationMeasures(new PhenotypeMetric()))); // ClusteringKMeans km = new ClusteringKMeans(); km.setK(2); // km.initClustering(bestN); // Population[] clusts = km.cluster(bestN, bestN); // System.out.println("cluster sizes: " + clusts[0].size() + " " + clusts[1].size() + " " + clusts[2].size()); // listener.println(" correlations of top " + bestN.size() + ": " + BeanInspector.toString(bestN.getCorrelations())); - } - } - } + } + } + } - return foundOpts; - } - - /** - * Select a local search range for a given method based on the clustering parameter. - * If clustering was deactivated (sigma <= 0), then the default mutation step size is used. - * The specific search method may interpret the search range differently. - * - * @param method - * @param postProcessClusterSigma - * @return - */ - private static double selectMaxSearchRange(PostProcessMethod method, - double postProcessClusterSigma) { - double resolution = defaultMutationStepSize*2; // somewhat keep the ratio between mutation and resolution - if (postProcessClusterSigma > 0.) { - resolution = postProcessClusterSigma; - } - switch (method) { - case hillClimber: - return resolution/2.; - case nelderMead: - return resolution/3.; - default: - System.err.println("Invalid method!"); - case cmaES: - return resolution; - } - } - - - /** - * Select a perturbation for individual i fitting to the population - avoiding overlap. - * In this case, return the third of the minimum distance to the next neighbor in the population. - * The maxPerturb can be given as upper bound of the perturbation if it is > 0. - * - * @param candidates population of solutions to look at - * @param i index of the individual in the population to look at - * @param maxPerturb optional upper bound of the returned perturbation - * @return - */ - public static double findNMSPerturb(Population candidates, int i, double maxAbsPerturb) { - double minDistNeighbour = Double.MAX_VALUE; - AbstractEAIndividual indy = candidates.getEAIndividual(i); - boolean found=false; - for (int k=0; k 0.) { + resolution = postProcessClusterSigma; + } + switch (method) { + case hillClimber: + return resolution / 2.; + case nelderMead: + return resolution / 3.; + default: + System.err.println("Invalid method!"); + case cmaES: + return resolution; + } + } + + + /** + * Select a perturbation for individual i fitting to the population - avoiding overlap. + * In this case, return the third of the minimum distance to the next neighbor in the population. + * The maxPerturb can be given as upper bound of the perturbation if it is > 0. + * + * @param candidates population of solutions to look at + * @param i index of the individual in the population to look at + * @param maxPerturb optional upper bound of the returned perturbation + * @return + */ + public static double findNMSPerturb(Population candidates, int i, double maxAbsPerturb) { + double minDistNeighbour = Double.MAX_VALUE; + AbstractEAIndividual indy = candidates.getEAIndividual(i); + boolean found = false; + for (int k = 0; k < candidates.size(); k++) { + if (k != i) { + double dist = EuclideanMetric.euclideanDistance(AbstractEAIndividual.getDoublePositionShallow(indy), AbstractEAIndividual.getDoublePositionShallow(candidates.getEAIndividual(k))); + if (dist == 0.) { // System.err.println("error, equal candidates in findNMSPerturb!"); - } else if (dist < minDistNeighbour) { - minDistNeighbour = dist; - found=true; - } - } - } - if (!found) { + } else if (dist < minDistNeighbour) { + minDistNeighbour = dist; + found = true; + } + } + } + if (!found) { // System.err.println("warning, equal candidates in PostProcess.findNMSPerturb - converged population?!"); - if (maxAbsPerturb>0) { - return maxAbsPerturb; - } - else { - System.err.println("error, unable to select perturbance value in PostProcess.findNMSPerturb since all candidates are equal. Converged population?!"); - return 0.01; - } - } - if (maxAbsPerturb>0) { - return Math.min(maxAbsPerturb, minDistNeighbour/3.); + if (maxAbsPerturb > 0) { + return maxAbsPerturb; + } else { + System.err.println("error, unable to select perturbance value in PostProcess.findNMSPerturb since all candidates are equal. Converged population?!"); + return 0.01; } - else { - return minDistNeighbour/3.; - } - } - - /** - * Sample a given problem randomly for the number of times specified and calculate the average - * fitness returned after evaluation. This may give a general measure of how good an optimum is - * on an unknown function. Of course its expensive for problems with considerable computational - * cost. - * - * @param steps - * @param prob - * @return an averaged fitness vector - */ - public static double[] calcAvgRandomFunctionValue(int steps, AbstractOptimizationProblem prob) { - int cnt = 0; - int portion = 100; - int curPopSize = Math.min(portion, steps); - double[] portionFitSum = null; - double[] avgFit = null; - Population pop = new Population(portion); - IndividualInterface indy; - prob.initializeProblem(); - while (cnt < steps) { - pop.clear(); - for (int i=0; i 0) { + return Math.min(maxAbsPerturb, minDistNeighbour / 3.); + } else { + return minDistNeighbour / 3.; + } + } - /** - * Try to abort all post processing threads currently running. - * - */ - public static void stopAllPP() { - synchronized (ppRunnables) { - for (OptimizerRunnable rnbl : ppRunnables) { - rnbl.stopOpt(); - } - } - } + /** + * Sample a given problem randomly for the number of times specified and calculate the average + * fitness returned after evaluation. This may give a general measure of how good an optimum is + * on an unknown function. Of course its expensive for problems with considerable computational + * cost. + * + * @param steps + * @param prob + * @return an averaged fitness vector + */ + public static double[] calcAvgRandomFunctionValue(int steps, AbstractOptimizationProblem prob) { + int cnt = 0; + int portion = 100; + int curPopSize = Math.min(portion, steps); + double[] portionFitSum = null; + double[] avgFit = null; + Population pop = new Population(portion); + IndividualInterface indy; + prob.initializeProblem(); + while (cnt < steps) { + pop.clear(); + for (int i = 0; i < curPopSize; i++) { + // fill pop randomly + indy = prob.getIndividualTemplate().getClone(); + indy.defaultInit(prob); + pop.add(indy); + } + pop.synchSize(); + // evaluate pop + prob.evaluate(pop); + if (portionFitSum == null) { + portionFitSum = new double[pop.getEAIndividual(0).getFitness().length]; + avgFit = new double[portionFitSum.length]; + Arrays.fill(avgFit, 0.); + } + Arrays.fill(portionFitSum, 0.); + for (int i = 0; i < curPopSize; i++) { + // calc fit-sum + Mathematics.vvAdd(portionFitSum, pop.getEAIndividual(i).getFitness(), portionFitSum); + } + // add to average + Mathematics.svvAddScaled(1. / (steps), portionFitSum, avgFit, avgFit); + // select next population size + cnt += curPopSize; + curPopSize = Math.min(portion, steps - cnt); // the new population size. + } + return avgFit; + } + + /** + * Calculate the average Euclidian distance between the individual with given index + * within the population to the other members of the population. + * If the population has only one member, zero is returned. + * + * @param index + * @param pop + * @return + */ + public static double getAvgDistToNeighbor(int index, Population pop) { + double distSum = 0; + int cnt = pop.size() - 1; + if (cnt == 0) { + return 0.; + } else { + double[] indyPos = AbstractEAIndividual.getDoublePositionShallow(pop.getEAIndividual(index)); + for (int i = 0; i < pop.size(); i++) { + if (i != index) { + distSum += EuclideanMetric.euclideanDistance(AbstractEAIndividual.getDoublePositionShallow(pop.getEAIndividual(i)), indyPos); + } + } + return distSum / ((double) cnt); + } + } + + /** + * Calculate a score for a given population of solutions to a problem. The score depends on the + * quality and the diversity of the solutions, growing with both. It is expected that the + * population is clustered beforehand. This method is rather experimental. + * + * @param avgFitSteps + * @param solutions + * @param criterion + * @param problem + * @return + */ + public static double calcQualityMeasure(int avgFitSteps, Population solutions, int criterion, AbstractOptimizationProblem problem) { + int solCnt = solutions.size(); + double indyQual, indyAvgDist, indyScore = 0.; + double scoreSum = 0.; + double[] avgFit = calcAvgRandomFunctionValue(avgFitSteps, problem); + for (int i = 0; i < solCnt; i++) { + indyQual = avgFit[criterion] - solutions.getEAIndividual(i).getFitness(criterion); + indyAvgDist = getAvgDistToNeighbor(i, solutions); + indyScore = Math.pow(indyQual, 2) + Math.pow(1 + indyAvgDist, 2); + scoreSum += indyScore; + } + return Math.sqrt(scoreSum); + } + + /** + * Try to abort all post processing threads currently running. + */ + public static void stopAllPP() { + synchronized (ppRunnables) { + for (OptimizerRunnable rnbl : ppRunnables) { + rnbl.stopOpt(); + } + } + } } diff --git a/src/eva2/optimization/operator/postprocess/PostProcessParams.java b/src/eva2/optimization/operator/postprocess/PostProcessParams.java index 12a45354..02a1dce7 100644 --- a/src/eva2/optimization/operator/postprocess/PostProcessParams.java +++ b/src/eva2/optimization/operator/postprocess/PostProcessParams.java @@ -2,200 +2,219 @@ package eva2.optimization.operator.postprocess; import eva2.gui.editor.GenericObjectEditor; import eva2.optimization.enums.PostProcessMethod; + import java.io.Serializable; public class PostProcessParams implements InterfacePostProcessParams, Serializable { - - protected int postProcessSteps = 5000; - private boolean postProcess = false; - protected double postProcessClusterSigma = 0.05; - protected int printNBest = 10; - protected PostProcessMethod method = PostProcessMethod.nelderMead; - protected double[] accuracies = new double[]{0.01};//{0.01, 0.001, 0.0001}; - protected double accAssumeConv = 1e-8; - protected int accMaxEval = -1; - private boolean withPlot = false; - - public PostProcessParams() { - postProcessSteps = 5000; - postProcess = false; - postProcessClusterSigma = 0.05; - printNBest = 10; - } - - public PostProcessParams(boolean doPP) { - postProcessSteps = 5000; - postProcess = doPP; - postProcessClusterSigma = 0.05; - } - - public PostProcessParams(int steps, double clusterSigma) { - this(steps, clusterSigma, 10); - } - - public PostProcessParams(int steps, double clusterSigma, int nBest) { - postProcessSteps = steps; - postProcess = true; - postProcessClusterSigma = clusterSigma; - printNBest = nBest; - } - - public PostProcessParams(PostProcessMethod meth, int steps, double clusterSigma, int nBest) { - reset(meth, steps, clusterSigma, nBest, false); - } - - public PostProcessParams(PostProcessMethod meth, int steps, double clusterSigma, int nBest, boolean doPlot) { - reset(meth, steps, clusterSigma, nBest, doPlot); - } - - public PostProcessParams reset(PostProcessMethod meth, int steps, double clusterSigma, int nBest, boolean doPlot) { - method = meth; - postProcessSteps = steps; - postProcess = true; - postProcessClusterSigma = clusterSigma; - printNBest = nBest; - withPlot = doPlot; - return this; - } - - public void hideHideable() { - setDoPostProcessing(isDoPostProcessing()); - } - - /** - * @return the postProcess - */ + protected int postProcessSteps = 5000; + private boolean postProcess = false; + protected double postProcessClusterSigma = 0.05; + protected int printNBest = 10; + protected PostProcessMethod method = PostProcessMethod.nelderMead; + protected double[] accuracies = new double[]{0.01};//{0.01, 0.001, 0.0001}; + protected double accAssumeConv = 1e-8; + protected int accMaxEval = -1; + + private boolean withPlot = false; + + public PostProcessParams() { + postProcessSteps = 5000; + postProcess = false; + postProcessClusterSigma = 0.05; + printNBest = 10; + } + + public PostProcessParams(boolean doPP) { + postProcessSteps = 5000; + postProcess = doPP; + postProcessClusterSigma = 0.05; + } + + public PostProcessParams(int steps, double clusterSigma) { + this(steps, clusterSigma, 10); + } + + public PostProcessParams(int steps, double clusterSigma, int nBest) { + postProcessSteps = steps; + postProcess = true; + postProcessClusterSigma = clusterSigma; + printNBest = nBest; + } + + public PostProcessParams(PostProcessMethod meth, int steps, double clusterSigma, int nBest) { + reset(meth, steps, clusterSigma, nBest, false); + } + + public PostProcessParams(PostProcessMethod meth, int steps, double clusterSigma, int nBest, boolean doPlot) { + reset(meth, steps, clusterSigma, nBest, doPlot); + } + + public PostProcessParams reset(PostProcessMethod meth, int steps, double clusterSigma, int nBest, boolean doPlot) { + method = meth; + postProcessSteps = steps; + postProcess = true; + postProcessClusterSigma = clusterSigma; + printNBest = nBest; + withPlot = doPlot; + return this; + } + + public void hideHideable() { + setDoPostProcessing(isDoPostProcessing()); + } + + /** + * @return the postProcess + */ @Override - public boolean isDoPostProcessing() { - return postProcess; - } - /** - * @param postProcess the postProcess to set - */ + public boolean isDoPostProcessing() { + return postProcess; + } + + /** + * @param postProcess the postProcess to set + */ @Override - public void setDoPostProcessing(boolean postProcess) { - this.postProcess = postProcess; - GenericObjectEditor.setShowProperty(this.getClass(), "postProcessSteps", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "postProcessClusterSigma", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "printNBest", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "PPMethod", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "withPlot", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "accuracies", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "accAssumeConv", postProcess); - GenericObjectEditor.setShowProperty(this.getClass(), "accMaxEval", postProcess); - } - @Override - public String doPostProcessingTipText() { - return "Toggle post processing of the solutions."; - } - /** - * @return the postProcessClusterSigma - */ - @Override - public double getPostProcessClusterSigma() { - return postProcessClusterSigma; - } - /** - * @param postProcessClusterSigma the postProcessClusterSigma to set - */ - @Override - public void setPostProcessClusterSigma(double postProcessClusterSigma) { - this.postProcessClusterSigma = postProcessClusterSigma; - } - @Override - public String postProcessClusterSigmaTipText() { - return "Set the sigma parameter for clustering during post processing; set to 0 for no clustering."; - } - - @Override - public String postProcessStepsTipText() { - return "The number of HC post processing steps in fitness evaluations."; - } - @Override - public int getPostProcessSteps() { - return postProcessSteps; - } - @Override - public void setPostProcessSteps(int ppSteps) { - postProcessSteps = ppSteps; - } - - @Override - public int getPrintNBest() { - return printNBest; - } - @Override - public void setPrintNBest(int nBest) { - printNBest = nBest; - } - @Override - public String printNBestTipText() { - return "Print as many solutions at max; set to -1 to print all"; - } - //////////////////////// GUI - - public String getName() { - return "PostProcessing " + (postProcess ? (postProcessSteps + "/" + postProcessClusterSigma) : "off"); - } - - public static String globalInfo() { - return "Combined clustering and local search post-processing of solutions. Additionally, accuracy checks can be performed on the " + - "returned solutions with different thresholds."; - } + public void setDoPostProcessing(boolean postProcess) { + this.postProcess = postProcess; + GenericObjectEditor.setShowProperty(this.getClass(), "postProcessSteps", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "postProcessClusterSigma", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "printNBest", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "PPMethod", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "withPlot", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "accuracies", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "accAssumeConv", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "accMaxEval", postProcess); + } @Override - public PostProcessMethod getPPMethod() { - return method; - } + public String doPostProcessingTipText() { + return "Toggle post processing of the solutions."; + } + + /** + * @return the postProcessClusterSigma + */ @Override - public String PPMethodTipText() { - return "The method to use for post-processing."; - } + public double getPostProcessClusterSigma() { + return postProcessClusterSigma; + } + + /** + * @param postProcessClusterSigma the postProcessClusterSigma to set + */ @Override - public void setPPMethod(PostProcessMethod meth) { - method=meth; - } + public void setPostProcessClusterSigma(double postProcessClusterSigma) { + this.postProcessClusterSigma = postProcessClusterSigma; + } @Override - public boolean isWithPlot() { - return withPlot; - } + public String postProcessClusterSigmaTipText() { + return "Set the sigma parameter for clustering during post processing; set to 0 for no clustering."; + } + @Override - public void setWithPlot(boolean withPlot) { - this.withPlot = withPlot; - } + public String postProcessStepsTipText() { + return "The number of HC post processing steps in fitness evaluations."; + } - public double[] getAccuracies() { - return accuracies; - } - public void setAccuracies(double[] accuracies) { - this.accuracies = accuracies; - } - public String accuraciesTipText() { - return "The accuracy thresholds to be tested"; - } - - public double getAccAssumeConv() { - return accAssumeConv; - } - public void setAccAssumeConv(double accAssumeConv) { - this.accAssumeConv = accAssumeConv; - } - public String accAssumeConvTipText() { - return "The local search refinement is stopped earlier if the fitness changes less than this value"; - } + @Override + public int getPostProcessSteps() { + return postProcessSteps; + } + + @Override + public void setPostProcessSteps(int ppSteps) { + postProcessSteps = ppSteps; + } + + @Override + public int getPrintNBest() { + return printNBest; + } + + @Override + public void setPrintNBest(int nBest) { + printNBest = nBest; + } + + @Override + public String printNBestTipText() { + return "Print as many solutions at max; set to -1 to print all"; + } + //////////////////////// GUI + + public String getName() { + return "PostProcessing " + (postProcess ? (postProcessSteps + "/" + postProcessClusterSigma) : "off"); + } + + public static String globalInfo() { + return "Combined clustering and local search post-processing of solutions. Additionally, accuracy checks can be performed on the " + + "returned solutions with different thresholds."; + } + + @Override + public PostProcessMethod getPPMethod() { + return method; + } + + @Override + public String PPMethodTipText() { + return "The method to use for post-processing."; + } + + @Override + public void setPPMethod(PostProcessMethod meth) { + method = meth; + } + + @Override + public boolean isWithPlot() { + return withPlot; + } + + @Override + public void setWithPlot(boolean withPlot) { + this.withPlot = withPlot; + } + + public double[] getAccuracies() { + return accuracies; + } + + public void setAccuracies(double[] accuracies) { + this.accuracies = accuracies; + } + + public String accuraciesTipText() { + return "The accuracy thresholds to be tested"; + } + + public double getAccAssumeConv() { + return accAssumeConv; + } + + public void setAccAssumeConv(double accAssumeConv) { + this.accAssumeConv = accAssumeConv; + } + + public String accAssumeConvTipText() { + return "The local search refinement is stopped earlier if the fitness changes less than this value"; + } + + public int getAccMaxEval() { + return accMaxEval; + } + + public void setAccMaxEval(int accMaxEval) { + this.accMaxEval = accMaxEval; + } + + public String accMaxEvalTipText() { + return "The maximal number of evaluations (times dimension) for accuracy check or -1 to use the default."; + } - public int getAccMaxEval() { - return accMaxEval; - } - public void setAccMaxEval(int accMaxEval) { - this.accMaxEval = accMaxEval; - } - public String accMaxEvalTipText() { - return "The maximal number of evaluations (times dimension) for accuracy check or -1 to use the default."; - } - } diff --git a/src/eva2/optimization/operator/postprocess/SolutionHistogram.java b/src/eva2/optimization/operator/postprocess/SolutionHistogram.java index d0cc9f08..22c861c8 100644 --- a/src/eva2/optimization/operator/postprocess/SolutionHistogram.java +++ b/src/eva2/optimization/operator/postprocess/SolutionHistogram.java @@ -5,192 +5,198 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.AbstractOptimizationProblem; import eva2.optimization.problems.InterfaceInterestingHistogram; import eva2.tools.math.Mathematics; + import java.util.Arrays; public class SolutionHistogram { - private double lBound, uBound; - private int numBins; - private int[] histogram; - private int arity; // number of summed-up histograms - - public SolutionHistogram(double lower, double upper, int nBins) { - lBound=lower; - uBound=upper; - numBins=nBins; - histogram = new int[numBins]; - arity = 0; - } - - public SolutionHistogram cloneEmpty() { - return new SolutionHistogram(getLowerBound(), getUpperBound(), getNumBins()); - } - - public boolean isEmtpy() { - return arity==0; - } - - private void setEntry(int i, int v) { - histogram[i]=v; - } - - public int getEntry(int i) { - return histogram[i]; - } - - public double lowerBoundOfEntry(int i) { - return lBound+(i*getStepSize()); - } - public double upperBoundOfEntry(int i) { - return lBound+((i+1)*getStepSize()); - } - public double getLowerBound() { - return lBound; - } + private double lBound, uBound; + private int numBins; + private int[] histogram; + private int arity; // number of summed-up histograms - public double getUpperBound() { - return uBound; - } - - public int getNumBins() { - return numBins; - } - - public double getStepSize() { - return (uBound-lBound)/numBins; - } - - public boolean isCompatible(SolutionHistogram o) { - if (lBound==o.getLowerBound() && (uBound==o.getUpperBound()) && (numBins==o.getNumBins())) { - return true; - } - else { - return false; - } - } - - /** - * Add another histogram to this one. - * @param o - */ - public void addHistogram(SolutionHistogram o) { - if (o.isEmtpy()) { - System.err.println("Warning, adding empty histogram... (SolutionHistogram)"); - } - if (isCompatible(o)) { - arity+=o.arity; - for (int i=0; i1 ? (",Avg.Sc:"+(getScore()/arity)) : ("")); - } - - /** - * Fill a given histogram from a population. Old entries are overwritten. - * @param pop - * @param hist - */ - public static void createFitNormHistogram(Population pop, SolutionHistogram hist, int crit) { - hist.reset(); - if (pop.size()>0) { - if (pop.getBestFitness()[crit] 1 ? (",Avg.Sc:" + (getScore() / arity)) : ("")); + } + + /** + * Fill a given histogram from a population. Old entries are overwritten. + * + * @param pop + * @param hist + */ + public static void createFitNormHistogram(Population pop, SolutionHistogram hist, int crit) { + hist.reset(); + if (pop.size() > 0) { + if (pop.getBestFitness()[crit] < hist.getLowerBound()) { + System.err.println("Warning, population contains solution with lower fitness than lower bound of the histogram!"); +// System.err.println("Pop was " + pop.getStringRepresentation()); + System.err.println("Histogramm was " + hist.toString()); + } + for (int i = 0; i < hist.getNumBins(); i++) { + hist.setEntry(i, PostProcess.filterFitnessIn(pop, hist.lowerBoundOfEntry(i), hist.upperBoundOfEntry(i), crit).size()); + } + } + hist.setSingularHist(); + } + + public static SolutionHistogram defaultEmptyHistogram(AbstractOptimizationProblem prob) { + if (prob instanceof InterfaceInterestingHistogram) { + return ((InterfaceInterestingHistogram) prob).getHistogram(); + } else { // System.err.println("Unknown problem to make histogram for, returning default..."); - return new SolutionHistogram(0, 100, 10); - } - } - + return new SolutionHistogram(0, 100, 10); + } + } + /** * Notify that a single histogram has been created. */ private void setSingularHist() { - arity=1; - } - - private void reset() { - arity=0; - Arrays.fill(histogram, 0); - } - - /** - * Fill a given histogram from a population. Old entries are overwritten. - * This resets the arity. - * @param pop - * @param hist - */ - public void updateFrom(Population pop, int crit) { - SolutionHistogram.createFitNormHistogram(pop, this, crit); + arity = 1; } - + + private void reset() { + arity = 0; + Arrays.fill(histogram, 0); + } + + /** + * Fill a given histogram from a population. Old entries are overwritten. + * This resets the arity. + * + * @param pop + * @param hist + */ + public void updateFrom(Population pop, int crit) { + SolutionHistogram.createFitNormHistogram(pop, this, crit); + } + /** * Create a fitness histogram of an evaluated population within the given interval and nBins number of bins. * Therefore a bin is of size (upperBound-lowerBound)/nBins, and bin 0 starts at lowerBound. - * Returns an integer array with the number of individuals in each bin. - * - * @param pop the population to scan. - * @param lowerBound lower bound of the fitness interval - * @param upperBound upper bound of the fitness interval - * @param nBins number of bins - * @return an integer array with the number of individuals in each bin + * Returns an integer array with the number of individuals in each bin. + * + * @param pop the population to scan. + * @param lowerBound lower bound of the fitness interval + * @param upperBound upper bound of the fitness interval + * @param nBins number of bins + * @return an integer array with the number of individuals in each bin * @see filterFitnessIn() - */ + */ public static SolutionHistogram createFitNormHistogram(Population pop, double lowerBound, double upperBound, int nBins, int crit) { - SolutionHistogram res = new SolutionHistogram(lowerBound, upperBound, nBins); - createFitNormHistogram(pop, res, crit); - return res; - } - + SolutionHistogram res = new SolutionHistogram(lowerBound, upperBound, nBins); + createFitNormHistogram(pop, res, crit); + return res; + } + // public void updateFrom(Population pop, double accuracy) { // // } - public double getScore() { - double sc = 0; - if (sum()>0) { - for (int i=numBins-1; i>=0; i--) { - sc += getScalingFactor(i)*((double)getEntry(i)); - } - return sc; - } else { - return 0; + public double getScore() { + double sc = 0; + if (sum() > 0) { + for (int i = numBins - 1; i >= 0; i--) { + sc += getScalingFactor(i) * ((double) getEntry(i)); } - } + return sc; + } else { + return 0; + } + } - private double getScalingFactor(int i) { - return (numBins-i)/((double)numBins); - } + private double getScalingFactor(int i) { + return (numBins - i) / ((double) numBins); + } } diff --git a/src/eva2/optimization/operator/selection/InterfaceSelection.java b/src/eva2/optimization/operator/selection/InterfaceSelection.java index 92003ab5..ca463dcb 100644 --- a/src/eva2/optimization/operator/selection/InterfaceSelection.java +++ b/src/eva2/optimization/operator/selection/InterfaceSelection.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** Selection methods have to implement on the one hand the +/** + * Selection methods have to implement on the one hand the * selection of the mother and on the other hand the selection * for the fathers (eventually more than one). This allows * niching method based on mating restrion, which is currently @@ -19,39 +20,49 @@ import eva2.optimization.population.Population; */ public interface InterfaceSelection { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ public void prepareSelection(Population population); - /** This method will select >size< individuals from the given + /** + * This method will select >size< individuals from the given * Population. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ public Population selectFrom(Population population, int size); - /** This method allows you to select >size< partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select >size< partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ public Population findPartnerFor(AbstractEAIndividual dad, Population avaiablePartners, int size); - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ - public void setObeyDebsConstViolationPrinciple(boolean b); + public void setObeyDebsConstViolationPrinciple(boolean b); } diff --git a/src/eva2/optimization/operator/selection/MOMultipleSolutions.java b/src/eva2/optimization/operator/selection/MOMultipleSolutions.java index 5efbc5bc..ef1265eb 100644 --- a/src/eva2/optimization/operator/selection/MOMultipleSolutions.java +++ b/src/eva2/optimization/operator/selection/MOMultipleSolutions.java @@ -10,11 +10,11 @@ import java.util.ArrayList; * To change this template use File | Settings | File Templates. */ public class MOMultipleSolutions { - - public int m_ParetoOptimalSolutions; - private ArrayList m_Solutions = new ArrayList(); - public int m_Iterations; - public int m_SizeDominantSolutions = 0; + + public int m_ParetoOptimalSolutions; + private ArrayList m_Solutions = new ArrayList(); + public int m_Iterations; + public int m_SizeDominantSolutions = 0; public void add(double[] fit, double[] w) { this.m_Solutions.add(new MOSolution(fit, w)); @@ -25,7 +25,7 @@ public class MOMultipleSolutions { } public MOSolution get(int i) { - return (MOSolution)this.m_Solutions.get(i); + return (MOSolution) this.m_Solutions.get(i); } public Object remove(int i) { diff --git a/src/eva2/optimization/operator/selection/MOSolution.java b/src/eva2/optimization/operator/selection/MOSolution.java index 83161a85..b8a34a56 100644 --- a/src/eva2/optimization/operator/selection/MOSolution.java +++ b/src/eva2/optimization/operator/selection/MOSolution.java @@ -9,9 +9,9 @@ package eva2.optimization.operator.selection; */ public class MOSolution { - public double[] fitness; - public double[] weights; - public boolean isDominant = true; + public double[] fitness; + public double[] weights; + public boolean isDominant = true; public MOSolution(double[] fit, double[] w) { this.fitness = fit; diff --git a/src/eva2/optimization/operator/selection/SelectAll.java b/src/eva2/optimization/operator/selection/SelectAll.java index 8d91f9a3..5a9e8e16 100644 --- a/src/eva2/optimization/operator/selection/SelectAll.java +++ b/src/eva2/optimization/operator/selection/SelectAll.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** Simple method to selecet all. +/** + * Simple method to selecet all. * In case of multiple fitness values the selection * critria is selected randomly for each selection event. pff * Created by IntelliJ IDEA. @@ -14,7 +15,7 @@ import eva2.optimization.population.Population; */ public class SelectAll implements InterfaceSelection, java.io.Serializable { - private boolean m_ObeyDebsConstViolationPrinciple = true; + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectAll() { } @@ -28,22 +29,26 @@ public class SelectAll implements InterfaceSelection, java.io.Serializable { return (Object) new SelectAll(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -53,30 +58,32 @@ public class SelectAll implements InterfaceSelection, java.io.Serializable { if (this.m_ObeyDebsConstViolationPrinciple) { int index = 0; while (result.size() < size) { - if (!((AbstractEAIndividual)population.get(index%population.size())).violatesConstraint()) { - result.add(population.get(index%population.size())); + if (!((AbstractEAIndividual) population.get(index % population.size())).violatesConstraint()) { + result.add(population.get(index % population.size())); } index++; if ((index >= size) && (result.size() == 0)) { // darn no one is feasible for (int i = 0; i < size; i++) { - result.add(population.get(i%population.size())); + result.add(population.get(i % population.size())); } } } } else { for (int i = 0; i < size; i++) { - result.add(population.get(i%population.size())); + result.add(population.get(i % population.size())); } } return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -87,32 +94,40 @@ public class SelectAll implements InterfaceSelection, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "All Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method selects all individuals."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectBestIndividuals.java b/src/eva2/optimization/operator/selection/SelectBestIndividuals.java index 0cefc204..55ba3c13 100644 --- a/src/eva2/optimization/operator/selection/SelectBestIndividuals.java +++ b/src/eva2/optimization/operator/selection/SelectBestIndividuals.java @@ -4,9 +4,11 @@ package eva2.optimization.operator.selection; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; + import java.util.ArrayList; -/** Select the best individuals. +/** + * Select the best individuals. * In case of multiple fitness values the selection * critria is selected randomly for each selection event. * Created by IntelliJ IDEA. @@ -17,13 +19,13 @@ import java.util.ArrayList; */ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serializable { - private boolean m_ObeyDebsConstViolationPrinciple = true; + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectBestIndividuals() { } public SelectBestIndividuals(SelectBestIndividuals a) { - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @Override @@ -31,30 +33,33 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial return (Object) new SelectBestIndividuals(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** + /** * This method will select n best individuals from the given * Population. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { - Population result = new Population(); - int currentCriteria = 0, critSize; + Population result = new Population(); + int currentCriteria = 0, critSize; - critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length; + critSize = ((AbstractEAIndividual) population.get(0)).getFitness().length; ArrayList[] bestIndividuals = new ArrayList[critSize]; for (int i = 0; i < critSize; i++) { @@ -67,7 +72,7 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial // now get the actual result from the tmp list for (int i = 0; i < size; i++) { - currentCriteria = RNG.randomInt(0, critSize-1); + currentCriteria = RNG.randomInt(0, critSize - 1); result.add(bestIndividuals[currentCriteria].get(0)); bestIndividuals[currentCriteria].remove(0); } @@ -75,22 +80,24 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial return result; } - /** This method will return the best individual that is not in tabu regarding + /** + * This method will return the best individual that is not in tabu regarding * crit - * @param pop The population to select from - * @param tabu The individuals that are to be ignored - * @param crit The criterion + * + * @param pop The population to select from + * @param tabu The individuals that are to be ignored + * @param crit The criterion * @return Object the individual */ private Object getBestIndividualExcept(Population pop, ArrayList tabu, int crit) { - int index = -1; - double bestProb = Double.POSITIVE_INFINITY; + int index = -1; + double bestProb = Double.POSITIVE_INFINITY; boolean member; AbstractEAIndividual indy; if (this.m_ObeyDebsConstViolationPrinciple) { for (int i = 0; i < pop.size(); i++) { - indy = (AbstractEAIndividual)pop.get(i); + indy = (AbstractEAIndividual) pop.get(i); // check if indy is tabu member = false; for (int j = 0; j < tabu.size(); j++) { @@ -100,18 +107,17 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial } } if ((!indy.violatesConstraint()) && (!member) && (indy.getFitness(crit) < bestProb)) { - index = i; - bestProb = indy.getFitness(crit); + index = i; + bestProb = indy.getFitness(crit); } } if (index >= 0) { return pop.get(index); - } - else { + } else { // darn all individuals seem to violate the constraints // so lets select the guy with the least worst constraint violation for (int i = 0; i < pop.size(); i++) { - indy = (AbstractEAIndividual)pop.get(i); + indy = (AbstractEAIndividual) pop.get(i); // check if indy is tabu member = false; for (int j = 0; j < tabu.size(); j++) { @@ -121,20 +127,19 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial } } if ((!member) && (indy.getConstraintViolation() < bestProb)) { - index = i; - bestProb = indy.getConstraintViolation(); + index = i; + bestProb = indy.getConstraintViolation(); } } if (index >= 0) { return pop.get(index); - } - else { - return pop.get(RNG.randomInt(0, pop.size()-1)); + } else { + return pop.get(RNG.randomInt(0, pop.size() - 1)); } } } else { for (int i = 0; i < pop.size(); i++) { - indy = (AbstractEAIndividual)pop.get(i); + indy = (AbstractEAIndividual) pop.get(i); // check if indy is tabu member = false; for (int j = 0; j < tabu.size(); j++) { @@ -144,23 +149,24 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial } } if ((!member) && (indy.getFitness(crit) < bestProb)) { - index = i; - bestProb = indy.getFitness(crit); + index = i; + bestProb = indy.getFitness(crit); } } if (index >= 0) { return pop.get(index); - } - else { - return pop.get(RNG.randomInt(0, pop.size()-1)); + } else { + return pop.get(RNG.randomInt(0, pop.size() - 1)); } } } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -170,32 +176,40 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This selection method will select the n-Best individuals." + "This is a single objective selecting method, it will select in respect to a random criterion."; } - - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Elitist Selection"; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectBestSingle.java b/src/eva2/optimization/operator/selection/SelectBestSingle.java index 519a79a8..7a61505a 100644 --- a/src/eva2/optimization/operator/selection/SelectBestSingle.java +++ b/src/eva2/optimization/operator/selection/SelectBestSingle.java @@ -5,7 +5,8 @@ import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** Select best individual multiple times if necessary. +/** + * Select best individual multiple times if necessary. * In case of multiple fitness values the selection * critria is selected randomly for each selection event. * Created by IntelliJ IDEA. @@ -16,16 +17,16 @@ import eva2.tools.math.RNG; */ public class SelectBestSingle implements InterfaceSelection, java.io.Serializable { - private boolean m_ObeyDebsConstViolationPrinciple = true; - private boolean excludeSelfAsPartner = true; // try to avoid selecting as a mating partner the individual itself + private boolean m_ObeyDebsConstViolationPrinciple = true; + private boolean excludeSelfAsPartner = true; // try to avoid selecting as a mating partner the individual itself - public SelectBestSingle() { + public SelectBestSingle() { } - - public SelectBestSingle(boolean excludeSelfInPartners) { - this.excludeSelfAsPartner=excludeSelfInPartners; + + public SelectBestSingle(boolean excludeSelfInPartners) { + this.excludeSelfAsPartner = excludeSelfInPartners; } - + public SelectBestSingle(SelectBestSingle a) { this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -35,53 +36,57 @@ public class SelectBestSingle implements InterfaceSelection, java.io.Serializabl return (Object) new SelectBestSingle(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method will select >size< individuals from the given + /** + * This method will select >size< individuals from the given * Population. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { - Population result = new Population(); - AbstractEAIndividual tmpIndy = null; - int currentCriteria = 0, critSize; - double currentBestValue; + Population result = new Population(); + AbstractEAIndividual tmpIndy = null; + int currentCriteria = 0, critSize; + double currentBestValue; - if (population.size()==0) { + if (population.size() == 0) { return population; } // trivial - critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length; + critSize = ((AbstractEAIndividual) population.get(0)).getFitness().length; result.setTargetSize(size); if (this.m_ObeyDebsConstViolationPrinciple) { for (int i = 0; i < size; i++) { - currentCriteria = RNG.randomInt(0, critSize-1); - currentBestValue = Double.POSITIVE_INFINITY; + currentCriteria = RNG.randomInt(0, critSize - 1); + currentBestValue = Double.POSITIVE_INFINITY; tmpIndy = null; for (int j = 0; j < population.size(); j++) { - if ((!((AbstractEAIndividual)population.get(j)).violatesConstraint()) && (((AbstractEAIndividual)population.get(j)).getFitness(currentCriteria) < currentBestValue)) { - currentBestValue = ((AbstractEAIndividual)population.get(j)).getFitness(currentCriteria); - tmpIndy = (AbstractEAIndividual)population.get(j); + if ((!((AbstractEAIndividual) population.get(j)).violatesConstraint()) && (((AbstractEAIndividual) population.get(j)).getFitness(currentCriteria) < currentBestValue)) { + currentBestValue = ((AbstractEAIndividual) population.get(j)).getFitness(currentCriteria); + tmpIndy = (AbstractEAIndividual) population.get(j); } } if (tmpIndy == null) { // darn all individuals violate the constraints // so select the guy with the least worst constraint violation for (int j = 0; j < population.size(); j++) { - if (((AbstractEAIndividual)population.get(j)).getConstraintViolation() < currentBestValue) { - currentBestValue = ((AbstractEAIndividual)population.get(j)).getConstraintViolation(); - tmpIndy = (AbstractEAIndividual)population.get(j); + if (((AbstractEAIndividual) population.get(j)).getConstraintViolation() < currentBestValue) { + currentBestValue = ((AbstractEAIndividual) population.get(j)).getConstraintViolation(); + tmpIndy = (AbstractEAIndividual) population.get(j); } } } @@ -89,12 +94,12 @@ public class SelectBestSingle implements InterfaceSelection, java.io.Serializabl } } else { for (int i = 0; i < size; i++) { - currentCriteria = RNG.randomInt(0, critSize-1); - currentBestValue = Double.POSITIVE_INFINITY; + currentCriteria = RNG.randomInt(0, critSize - 1); + currentBestValue = Double.POSITIVE_INFINITY; for (int j = 0; j < population.size(); j++) { - if (((AbstractEAIndividual)population.get(j)).getFitness(currentCriteria) < currentBestValue) { - currentBestValue = ((AbstractEAIndividual)population.get(j)).getFitness(currentCriteria); - tmpIndy = (AbstractEAIndividual)population.get(j); + if (((AbstractEAIndividual) population.get(j)).getFitness(currentCriteria) < currentBestValue) { + currentBestValue = ((AbstractEAIndividual) population.get(j)).getFitness(currentCriteria); + tmpIndy = (AbstractEAIndividual) population.get(j); } } result.add(tmpIndy); @@ -103,67 +108,80 @@ public class SelectBestSingle implements InterfaceSelection, java.io.Serializabl return result; } - /** This method allows you to select >size< partners for a given Individual + /** + * This method allows you to select >size< partners for a given Individual + * * @param dad The already selected parent - * @param availablePartners The mating pool. + * @param availablePartners The mating pool. * @param size The number of partners needed. * @return The selected partners. */ @Override public Population findPartnerFor(AbstractEAIndividual dad, Population availablePartners, int size) { - if (excludeSelfAsPartner) { - Population newPartners = availablePartners.filter(new Population().addToPop(dad)); - if (newPartners.size()==0) { - // no problem if crossover is deactivated + if (excludeSelfAsPartner) { + Population newPartners = availablePartners.filter(new Population().addToPop(dad)); + if (newPartners.size() == 0) { + // no problem if crossover is deactivated // EVAERROR.errorMsgOnce("Warning, no partners available when excluding self (SelectBestSingle.findPartnerFor)"); // EVAERROR.errorMsgOnce("Partners where: " + availablePartners.getStringRepresentation()); - return newPartners; - } - return this.selectFrom(newPartners, size); - } else { + return newPartners; + } + return this.selectFrom(newPartners, size); + } else { return this.selectFrom(availablePartners, size); } } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This selection method will select the single Best individual (n-times if necessary)." + "This is a single objective selecting method, it will select in respect to a random criterion."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Totalitarian Selection"; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } - + public boolean isExcludeSelfAsPartner() { - return excludeSelfAsPartner; - } - public void setExcludeSelfAsPartner(boolean excludeSelfAsPartner) { - this.excludeSelfAsPartner = excludeSelfAsPartner; - } - public String excludeSelfAsPartnerTipText() { - return "When employed for partner selection, the partners may be allowed to contain the parents itself or not."; - } + return excludeSelfAsPartner; + } + + public void setExcludeSelfAsPartner(boolean excludeSelfAsPartner) { + this.excludeSelfAsPartner = excludeSelfAsPartner; + } + + public String excludeSelfAsPartnerTipText() { + return "When employed for partner selection, the partners may be allowed to contain the parents itself or not."; + } } diff --git a/src/eva2/optimization/operator/selection/SelectEPTournaments.java b/src/eva2/optimization/operator/selection/SelectEPTournaments.java index a425ad12..b5f54d3d 100644 --- a/src/eva2/optimization/operator/selection/SelectEPTournaments.java +++ b/src/eva2/optimization/operator/selection/SelectEPTournaments.java @@ -4,9 +4,11 @@ package eva2.optimization.operator.selection; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; + import java.util.ArrayList; -/** This method implements the multiple tournament scheme +/** + * This method implements the multiple tournament scheme * for EP. * In case of multiple fitness values the selection * critria is selected randomly for each selection event. @@ -18,16 +20,16 @@ import java.util.ArrayList; */ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializable { - private int m_TournamentSize = 4; - private int m_Tournaments = 10; - private boolean m_ObeyDebsConstViolationPrinciple = true; - private int[][] m_Victories; + private int m_TournamentSize = 4; + private int m_Tournaments = 10; + private boolean m_ObeyDebsConstViolationPrinciple = true; + private int[][] m_Victories; public SelectEPTournaments() { } public SelectEPTournaments(SelectEPTournaments a) { - this.m_TournamentSize = a.m_TournamentSize; + this.m_TournamentSize = a.m_TournamentSize; this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -36,17 +38,19 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ return (Object) new SelectEPTournaments(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { - int[] best = new int[population.getBestEAIndividual().getFitness().length]; - int rand; - AbstractEAIndividual tmpIndy; + int[] best = new int[population.getBestEAIndividual().getFitness().length]; + int rand; + AbstractEAIndividual tmpIndy; this.m_Victories = new int[population.size()][population.getBestEAIndividual().getFitness().length]; for (int i = 0; i < this.m_Victories.length; i++) { @@ -61,15 +65,15 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ } // perform tournament for (int k = 0; k < this.m_TournamentSize; k++) { - rand = RNG.randomInt(0, population.size()-1); - tmpIndy = ((AbstractEAIndividual)population.get(rand)); + rand = RNG.randomInt(0, population.size() - 1); + tmpIndy = ((AbstractEAIndividual) population.get(rand)); for (int l = 0; l < best.length; l++) { if (this.m_ObeyDebsConstViolationPrinciple) { - if ((!tmpIndy.violatesConstraint()) && (tmpIndy.getFitness(l) < ((AbstractEAIndividual)population.get(best[l])).getFitness(l))) { + if ((!tmpIndy.violatesConstraint()) && (tmpIndy.getFitness(l) < ((AbstractEAIndividual) population.get(best[l])).getFitness(l))) { best[l] = rand; } } else { - if (tmpIndy.getFitness(l) < ((AbstractEAIndividual)population.get(best[l])).getFitness(l)) { + if (tmpIndy.getFitness(l) < ((AbstractEAIndividual) population.get(best[l])).getFitness(l)) { best[l] = rand; } } @@ -83,19 +87,21 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ } } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { - Population result = new Population(); - int currentCriteria = 0, critSize; + Population result = new Population(); + int currentCriteria = 0, critSize; - critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length; + critSize = ((AbstractEAIndividual) population.get(0)).getFitness().length; ArrayList[] bestIndividuals = new ArrayList[critSize]; for (int i = 0; i < critSize; i++) { @@ -108,7 +114,7 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ // now get the actual result from the tmp list for (int i = 0; i < size; i++) { - currentCriteria = RNG.randomInt(0, critSize-1); + currentCriteria = RNG.randomInt(0, critSize - 1); result.add(bestIndividuals[currentCriteria].get(0)); bestIndividuals[currentCriteria].remove(0); } @@ -116,21 +122,23 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ return result; } - /** This method will return the best individual that is not in tabu regarding + /** + * This method will return the best individual that is not in tabu regarding * crit - * @param pop The population to select from - * @param tabu The individuals that are to be ignored - * @param crit The criterion + * + * @param pop The population to select from + * @param tabu The individuals that are to be ignored + * @param crit The criterion * @return Object the individual */ private Object getBestIndividualExcept(Population pop, ArrayList tabu, int crit) { - int index = -1; - int mostVictories = -1; + int index = -1; + int mostVictories = -1; boolean member; AbstractEAIndividual indy; for (int i = 0; i < pop.size(); i++) { - indy = (AbstractEAIndividual)pop.get(i); + indy = (AbstractEAIndividual) pop.get(i); // check if indy is tabu member = false; for (int j = 0; j < tabu.size(); j++) { @@ -140,22 +148,23 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ } } if ((!member) && (this.m_Victories[i][crit] > mostVictories)) { - index = i; - mostVictories = this.m_Victories[i][crit]; + index = i; + mostVictories = this.m_Victories[i][crit]; } } if (index >= 0) { return pop.get(index); - } - else { - return pop.get(RNG.randomInt(0, pop.size()-1)); + } else { + return pop.get(RNG.randomInt(0, pop.size() - 1)); } } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -166,15 +175,19 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "EP Tournament Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -183,41 +196,51 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ " This is a single objective selecting method, it will select in respect to a random criterion."; } - /** You can choose the tournament size. - */ + /** + * You can choose the tournament size. + */ public String tournamentSizeTipText() { return "Choose the tournament size."; } + public int getTournamentSize() { return m_TournamentSize; } + public void setTournamentSize(int g) { m_TournamentSize = g; } - /** You can choose the number of tournaments - */ + /** + * You can choose the number of tournaments + */ public String tournamentsTipText() { return "Choose the number of tournaments."; } + public int getTournaments() { return m_Tournaments; } + public void setTournaments(int g) { m_Tournaments = g; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectHomologousMate.java b/src/eva2/optimization/operator/selection/SelectHomologousMate.java index c3329f77..43f8c4fd 100644 --- a/src/eva2/optimization/operator/selection/SelectHomologousMate.java +++ b/src/eva2/optimization/operator/selection/SelectHomologousMate.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric; import eva2.optimization.operator.distancemetric.ObjectiveSpaceMetric; import eva2.optimization.population.Population; -/** An experimental implementation for mating restriction. +/** + * An experimental implementation for mating restriction. * Possibly defunct. * Created by IntelliJ IDEA. * User: streiche @@ -15,15 +16,15 @@ import eva2.optimization.population.Population; */ public class SelectHomologousMate extends SelectTournament implements java.io.Serializable { - private double m_MatingRadius = 0.1; - private InterfaceDistanceMetric m_Metric = new ObjectiveSpaceMetric(); + private double m_MatingRadius = 0.1; + private InterfaceDistanceMetric m_Metric = new ObjectiveSpaceMetric(); public SelectHomologousMate() { } public SelectHomologousMate(SelectHomologousMate a) { - this.m_MatingRadius = a.m_MatingRadius; - this.m_Metric = (InterfaceDistanceMetric)a.m_Metric.clone(); + this.m_MatingRadius = a.m_MatingRadius; + this.m_Metric = (InterfaceDistanceMetric) a.m_Metric.clone(); } @Override @@ -31,39 +32,42 @@ public class SelectHomologousMate extends SelectTournament implements java.io.Se return (Object) new SelectHomologousMate(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method allows you to select partners for a given Individual + /** + * This method allows you to select partners for a given Individual + * * @param dad The already seleceted parent - * @param availablePartners The mating pool. + * @param availablePartners The mating pool. * @param size The number of partners needed. * @return The selected partners. */ @Override public Population findPartnerFor(AbstractEAIndividual dad, Population availablePartners, int size) { - Population possibleMates = new Population(); + Population possibleMates = new Population(); // first select all possible partners for daddy // to be honest daddy himself is not omitted.... for (int i = 0; i < availablePartners.size(); i++) { - if (this.m_Metric.distance(dad, (AbstractEAIndividual)availablePartners.get(i)) < this.m_MatingRadius) { + if (this.m_Metric.distance(dad, (AbstractEAIndividual) availablePartners.get(i)) < this.m_MatingRadius) { possibleMates.add(availablePartners.get(i)); } } //System.out.println("Partners Size: " + possibleMates.size()); - if (possibleMates.size() <=1) { + if (possibleMates.size() <= 1) { return this.selectFrom(availablePartners, size); - } - else { + } else { return this.selectFrom(possibleMates, size); } } @@ -71,8 +75,10 @@ public class SelectHomologousMate extends SelectTournament implements java.io.Se /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -80,7 +86,9 @@ public class SelectHomologousMate extends SelectTournament implements java.io.Se return "Homologous Mating Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -88,28 +96,36 @@ public class SelectHomologousMate extends SelectTournament implements java.io.Se "This is a single objective selecting method, it will select in respect to a random criterion."; } - /** This method allows you to set/get the mating radius. + /** + * This method allows you to set/get the mating radius. + * * @return The current optimizing method */ public double getMatingRadius() { return this.m_MatingRadius; } - public void setMatingRadius(double b){ + + public void setMatingRadius(double b) { this.m_MatingRadius = b; } + public String matingRadiusTipText() { return "Choose the mating radius."; } - /** These methods allows you to set/get the type of Distance Metric. + /** + * These methods allows you to set/get the type of Distance Metric. + * * @param Metric */ public void setMetric(InterfaceDistanceMetric Metric) { this.m_Metric = Metric; } + public InterfaceDistanceMetric getMetric() { return this.m_Metric; } + public String metricTipText() { return "The distance metric used. Note: This depends on the type of EAIndividual used!"; } diff --git a/src/eva2/optimization/operator/selection/SelectMOMAIIDominanceCounter.java b/src/eva2/optimization/operator/selection/SelectMOMAIIDominanceCounter.java index f21b61ed..315b5d56 100644 --- a/src/eva2/optimization/operator/selection/SelectMOMAIIDominanceCounter.java +++ b/src/eva2/optimization/operator/selection/SelectMOMAIIDominanceCounter.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** Experimental selection mechanism for MOMA II where +/** + * Experimental selection mechanism for MOMA II where * a single individual is a whole set of Pareto optimal * solution. Currently defunct. * Created by IntelliJ IDEA. @@ -14,14 +15,14 @@ import eva2.optimization.population.Population; */ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io.Serializable { - private InterfaceSelection m_Selection = new SelectBestIndividuals(); - private boolean m_ObeyDebsConstViolationPrinciple = true; + private InterfaceSelection m_Selection = new SelectBestIndividuals(); + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMOMAIIDominanceCounter() { } public SelectMOMAIIDominanceCounter(SelectMOMAIIDominanceCounter a) { - this.m_Selection = (InterfaceSelection)a.m_Selection.clone(); + this.m_Selection = (InterfaceSelection) a.m_Selection.clone(); this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -30,48 +31,50 @@ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io return (Object) new SelectMOMAIIDominanceCounter(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // here i need to calculate the number of donimating solutions for all // individuals that have a MatlabMultipleSolution element - AbstractEAIndividual tmpIndy1, tmpIndy2; - Object tmpObj; + AbstractEAIndividual tmpIndy1, tmpIndy2; + Object tmpObj; MOMultipleSolutions malta, tmpMalta; // reset the stuff for (int i = 0; i < population.size(); i++) { - tmpIndy1 = (AbstractEAIndividual)population.get(i); + tmpIndy1 = (AbstractEAIndividual) population.get(i); tmpObj = tmpIndy1.getData("MOMAII"); if ((tmpObj != null) && (tmpObj instanceof MOMultipleSolutions)) { - ((MOMultipleSolutions)tmpObj).reset(); + ((MOMultipleSolutions) tmpObj).reset(); } } // now check the stuff for (int i = 0; i < population.size(); i++) { - tmpIndy1 = (AbstractEAIndividual)population.get(i); + tmpIndy1 = (AbstractEAIndividual) population.get(i); tmpObj = tmpIndy1.getData("MOMAII"); if ((tmpObj != null) && (tmpObj instanceof MOMultipleSolutions)) { - malta = (MOMultipleSolutions)tmpObj; + malta = (MOMultipleSolutions) tmpObj; //for (int j = i+1; j < population.size(); i++) { // MK: Im rather sure the i++ was intended to become a j++ - for (int j = i+1; j < population.size(); j++) { - tmpIndy2 = (AbstractEAIndividual)population.get(j); + for (int j = i + 1; j < population.size(); j++) { + tmpIndy2 = (AbstractEAIndividual) population.get(j); tmpObj = tmpIndy2.getData("MOMAII"); if ((tmpObj != null) && (tmpObj instanceof MOMultipleSolutions)) { - tmpMalta = (MOMultipleSolutions)tmpObj; + tmpMalta = (MOMultipleSolutions) tmpObj; malta.testDominance(tmpMalta); } } // now i have compared malta to all remaining individuals // lets count the number of dominant solutions - int domCount = 0; + int domCount = 0; for (int j = 0; j < malta.size(); j++) { if (malta.get(i).isDominant) { domCount++; @@ -79,7 +82,7 @@ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io } malta.m_SizeDominantSolutions = domCount; double[] fitness = new double[1]; - fitness[0] = 1/((double)(domCount+1)); + fitness[0] = 1 / ((double) (domCount + 1)); tmpIndy1.setFitness(fitness); } else { double[] fitness = new double[1]; @@ -89,11 +92,13 @@ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io } } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -101,10 +106,12 @@ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io return this.m_Selection.selectFrom(population, size); } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -115,44 +122,57 @@ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This selection method only works for MOMA-II, it selects an individual depending on the number of non-dominated solutions."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MOMAII-DonCount"; } - /** Since SelectMOMaxiMin relies on a MOSO conversion + /** + * Since SelectMOMaxiMin relies on a MOSO conversion * a single criterion selection method can be used. - * @param pop The selection method used. + * + * @param pop The selection method used. */ public void setSelectionMethod(InterfaceSelection pop) { this.m_Selection = pop; } + public InterfaceSelection getSelectionMethod() { return this.m_Selection; } + public String selectionMethodTipText() { return "Choose the selection method (single-criteria ones please)."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectMOMaxiMin.java b/src/eva2/optimization/operator/selection/SelectMOMaxiMin.java index 86316c41..62ce8a91 100644 --- a/src/eva2/optimization/operator/selection/SelectMOMaxiMin.java +++ b/src/eva2/optimization/operator/selection/SelectMOMaxiMin.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.operator.moso.MOSOMaxiMin; import eva2.optimization.population.Population; -/** A multi-objective selection criterion based on the maximin +/** + * A multi-objective selection criterion based on the maximin * method. * Created by IntelliJ IDEA. * User: streiche @@ -14,17 +15,17 @@ import eva2.optimization.population.Population; */ public class SelectMOMaxiMin implements InterfaceSelection, java.io.Serializable { - private MOSOMaxiMin m_MaxiMin = new MOSOMaxiMin(); - private InterfaceSelection m_Selection = new SelectBestIndividuals(); - private boolean m_ObeyDebsConstViolationPrinciple = true; + private MOSOMaxiMin m_MaxiMin = new MOSOMaxiMin(); + private InterfaceSelection m_Selection = new SelectBestIndividuals(); + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMOMaxiMin() { } public SelectMOMaxiMin(SelectMOMaxiMin a) { - this.m_MaxiMin = new MOSOMaxiMin(); - this.m_Selection = (InterfaceSelection)a.m_Selection.clone(); - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_MaxiMin = new MOSOMaxiMin(); + this.m_Selection = (InterfaceSelection) a.m_Selection.clone(); + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @Override @@ -32,28 +33,32 @@ public class SelectMOMaxiMin implements InterfaceSelection, java.io.Serializable return (Object) new SelectMOMaxiMin(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { - Population result = new Population(), tmpPop = (Population)population.clone(); - double[] tmpD; + Population result = new Population(), tmpPop = (Population) population.clone(); + double[] tmpD; // Now calculate the MaxiMin Criterium this.m_MaxiMin.convertMultiObjective2SingleObjective(tmpPop); @@ -63,16 +68,18 @@ public class SelectMOMaxiMin implements InterfaceSelection, java.io.Serializable // now unconvert from SO to MO for (int i = 0; i < result.size(); i++) { - tmpD = (double[])((AbstractEAIndividual)result.get(i)).getData("MOFitness"); - ((AbstractEAIndividual)result.get(i)).setFitness(tmpD); + tmpD = (double[]) ((AbstractEAIndividual) result.get(i)).getData("MOFitness"); + ((AbstractEAIndividual) result.get(i)).setFitness(tmpD); } return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -83,44 +90,57 @@ public class SelectMOMaxiMin implements InterfaceSelection, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This selection method will use the MaxiMin criteria to select individuals (use SelectBestIndividuals)."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "MaxiMin Selection"; } - /** Since SelectMOMaxiMin relies on a MOSO conversion + /** + * Since SelectMOMaxiMin relies on a MOSO conversion * a single criterion selection method can be used. - * @param pop The selection method used. + * + * @param pop The selection method used. */ public void setSelectionMethod(InterfaceSelection pop) { this.m_Selection = pop; } + public InterfaceSelection getSelectionMethod() { return this.m_Selection; } + public String selectionMethodTipText() { return "Choose the selection method (single-criteria ones please)."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectMONSGAIICrowedTournament.java b/src/eva2/optimization/operator/selection/SelectMONSGAIICrowedTournament.java index 51cb470d..1c04f425 100644 --- a/src/eva2/optimization/operator/selection/SelectMONSGAIICrowedTournament.java +++ b/src/eva2/optimization/operator/selection/SelectMONSGAIICrowedTournament.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.archiving.ArchivingNSGAII; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** The infamous NSGA-II selection scheme for multi-objective +/** + * The infamous NSGA-II selection scheme for multi-objective * optimization based on Pareto ranks and hybergrids. * Created by IntelliJ IDEA. * User: streiche @@ -15,19 +16,19 @@ import eva2.tools.math.RNG; */ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java.io.Serializable { - private int m_TournamentSize = 4; - private ArchivingNSGAII m_NSGAII = new ArchivingNSGAII(); - private Population[] m_Fronts; - private boolean m_ObeyDebsConstViolationPrinciple = true; + private int m_TournamentSize = 4; + private ArchivingNSGAII m_NSGAII = new ArchivingNSGAII(); + private Population[] m_Fronts; + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMONSGAIICrowedTournament() { } public SelectMONSGAIICrowedTournament(SelectMONSGAIICrowedTournament a) { - this.m_TournamentSize = a.m_TournamentSize; - this.m_NSGAII = new ArchivingNSGAII(); - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_TournamentSize = a.m_TournamentSize; + this.m_NSGAII = new ArchivingNSGAII(); + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @Override @@ -35,11 +36,13 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. return (Object) new SelectMONSGAIICrowedTournament(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { @@ -47,11 +50,13 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. this.m_NSGAII.calculateCrowdingDistance(this.m_Fronts); } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -64,27 +69,28 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. return result; } - /** This method selects a single individual from the current population + /** + * This method selects a single individual from the current population + * * @param population The population to select from */ private AbstractEAIndividual select(Population population) { - AbstractEAIndividual result = null, tmpIndy; - Population feasiblePop = new Population(); - Population infeasiblePop = new Population(); - int smallestLevel = Integer.MAX_VALUE, tmpL; - double curCrowdingDistance, tmpCrowdingDistance; + AbstractEAIndividual result = null, tmpIndy; + Population feasiblePop = new Population(); + Population infeasiblePop = new Population(); + int smallestLevel = Integer.MAX_VALUE, tmpL; + double curCrowdingDistance, tmpCrowdingDistance; try { for (int i = 0; i < this.m_TournamentSize; i++) { - tmpIndy = (AbstractEAIndividual) population.get(RNG.randomInt(0, population.size()-1)); - tmpL = ((Integer)tmpIndy.getData("ParetoLevel")).intValue(); + tmpIndy = (AbstractEAIndividual) population.get(RNG.randomInt(0, population.size() - 1)); + tmpL = ((Integer) tmpIndy.getData("ParetoLevel")).intValue(); if (tmpL < smallestLevel) { smallestLevel = tmpL; } if (tmpIndy.getConstraintViolation() > 0) { infeasiblePop.add(tmpIndy); - } - else { + } else { feasiblePop.add(tmpIndy); } } @@ -92,7 +98,7 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. // choose the least infeasible one int best = 0; for (int i = 1; i < infeasiblePop.size(); i++) { - if (((AbstractEAIndividual)infeasiblePop.get(i)).getConstraintViolation() < ((AbstractEAIndividual)infeasiblePop.get(best)).getConstraintViolation()) { + if (((AbstractEAIndividual) infeasiblePop.get(i)).getConstraintViolation() < ((AbstractEAIndividual) infeasiblePop.get(best)).getConstraintViolation()) { best = i; } } @@ -102,30 +108,29 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. smallestLevel = Integer.MAX_VALUE; for (int i = 0; i < feasiblePop.size(); i++) { tmpIndy = (AbstractEAIndividual) feasiblePop.get(i); - tmpL = ((Integer)tmpIndy.getData("ParetoLevel")).intValue(); + tmpL = ((Integer) tmpIndy.getData("ParetoLevel")).intValue(); if (tmpL < smallestLevel) { smallestLevel = tmpL; } } // first remove all individual from tmpPop which are not of smallestLevel for (int i = 0; i < feasiblePop.size(); i++) { - if (((Integer)((AbstractEAIndividual)feasiblePop.get(i)).getData("ParetoLevel")).intValue() > smallestLevel) { + if (((Integer) ((AbstractEAIndividual) feasiblePop.get(i)).getData("ParetoLevel")).intValue() > smallestLevel) { feasiblePop.remove(i); i--; } } if (feasiblePop.size() == 1) { - return (AbstractEAIndividual)feasiblePop.get(0); - } - else { + return (AbstractEAIndividual) feasiblePop.get(0); + } else { // now find the one with the biggest crowding distance - result = (AbstractEAIndividual)feasiblePop.get(0); - curCrowdingDistance = ((Double)(result.getData("HyperCube"))).doubleValue(); + result = (AbstractEAIndividual) feasiblePop.get(0); + curCrowdingDistance = ((Double) (result.getData("HyperCube"))).doubleValue(); for (int i = 1; i < feasiblePop.size(); i++) { - tmpCrowdingDistance = ((Double)((AbstractEAIndividual)feasiblePop.get(i)).getData("HyperCube")).doubleValue(); + tmpCrowdingDistance = ((Double) ((AbstractEAIndividual) feasiblePop.get(i)).getData("HyperCube")).doubleValue(); if (tmpCrowdingDistance > curCrowdingDistance) { curCrowdingDistance = tmpCrowdingDistance; - result = (AbstractEAIndividual)feasiblePop.get(i); + result = (AbstractEAIndividual) feasiblePop.get(i); } } } @@ -139,10 +144,12 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -153,15 +160,19 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "MO Crowded Tournament Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -169,29 +180,35 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. } /** - * You can choose the tournament size. - */ + * You can choose the tournament size. + */ public String tournamentSizeTipText() { return "Choose the tournament size."; } + public int getTournamentSize() { return m_TournamentSize; } + public void setTournamentSize(int g) { m_TournamentSize = g; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectMONonDominated.java b/src/eva2/optimization/operator/selection/SelectMONonDominated.java index 3672b0bd..675aa1e7 100644 --- a/src/eva2/optimization/operator/selection/SelectMONonDominated.java +++ b/src/eva2/optimization/operator/selection/SelectMONonDominated.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** This multi-objective selection method preferrs non-dominated +/** + * This multi-objective selection method preferrs non-dominated * individuals over dominated ones. Actually, this fails in case * all individuals are Pareto optimal. * Created by IntelliJ IDEA. @@ -15,13 +16,13 @@ import eva2.tools.math.RNG; */ public class SelectMONonDominated implements InterfaceSelection, java.io.Serializable { - private boolean m_ObeyDebsConstViolationPrinciple = true; + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMONonDominated() { } public SelectMONonDominated(SelectMONonDominated a) { - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @Override @@ -29,46 +30,50 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali return (Object) new SelectMONonDominated(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { - Population result = new Population(); - int index = RNG.randomInt(0, population.size()-1); + Population result = new Population(); + int index = RNG.randomInt(0, population.size() - 1); if (this.m_ObeyDebsConstViolationPrinciple) { boolean feasible = false; for (int i = 0; i < population.size(); i++) { - if (((AbstractEAIndividual)population.get(i)).getConstraintViolation() == 0) { + if (((AbstractEAIndividual) population.get(i)).getConstraintViolation() == 0) { feasible = true; } } if (feasible) { while (result.size() < size) { - int tmpI = index%population.size(); + int tmpI = index % population.size(); if (tmpI < 0) { System.out.println("Index: " + index); System.out.println("Pop.Size(): " + population.size()); tmpI = 0; } - if ((((AbstractEAIndividual)population.get(tmpI)).getConstraintViolation() == 0) && (this.isDominant((AbstractEAIndividual)population.get(tmpI), population))) { - result.addIndividual((AbstractEAIndividual)population.get(index%population.size())); + if ((((AbstractEAIndividual) population.get(tmpI)).getConstraintViolation() == 0) && (this.isDominant((AbstractEAIndividual) population.get(tmpI), population))) { + result.addIndividual((AbstractEAIndividual) population.get(index % population.size())); } index++; } @@ -78,14 +83,14 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali } } else { while (result.size() < size) { - int tmpI = index%population.size(); + int tmpI = index % population.size(); if (tmpI < 0) { System.out.println("Index: " + index); System.out.println("Pop.Size(): " + population.size()); tmpI = 0; } - if (this.isDominant((AbstractEAIndividual)population.get(tmpI), population)) { - result.addIndividual((AbstractEAIndividual)population.get(index%population.size())); + if (this.isDominant((AbstractEAIndividual) population.get(tmpI), population)) { + result.addIndividual((AbstractEAIndividual) population.get(index % population.size())); } index++; } @@ -93,10 +98,12 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -104,22 +111,24 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali return this.selectFrom(avaiablePartners, size); } - /** This mehtod will test if a given individual is dominant within + /** + * This mehtod will test if a given individual is dominant within * a given population - * @param indy The individual that is to be tested. - * @param pop The population that the individual is to be tested against. + * + * @param indy The individual that is to be tested. + * @param pop The population that the individual is to be tested against. * @return True if the individual is dominating */ public boolean isDominant(AbstractEAIndividual indy, Population pop) { if (this.m_ObeyDebsConstViolationPrinciple) { for (int i = 0; i < pop.size(); i++) { - if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominatingDebConstraintsEqual(indy))) { + if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual) pop.get(i)).isDominatingDebConstraintsEqual(indy))) { return false; } } } else { for (int i = 0; i < pop.size(); i++) { - if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominatingEqual(indy))) { + if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual) pop.get(i)).isDominatingEqual(indy))) { return false; } } @@ -130,30 +139,39 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This selection method will select all non-dominated individuals. Therefore the target size of the selection may be exceeded."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Non-Dominated Selection"; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectMOPESA.java b/src/eva2/optimization/operator/selection/SelectMOPESA.java index 282ed707..6bbf1694 100644 --- a/src/eva2/optimization/operator/selection/SelectMOPESA.java +++ b/src/eva2/optimization/operator/selection/SelectMOPESA.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.archiving.ArchivingPESAII; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** The multi-objective PESA selection method. +/** + * The multi-objective PESA selection method. * Created by IntelliJ IDEA. * User: streiche * Date: 11.08.2004 @@ -14,17 +15,17 @@ import eva2.tools.math.RNG; */ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable { - ArchivingPESAII m_PESAII = new ArchivingPESAII(); - int[] m_Squeeze; - int m_TournamentSize = 2; - boolean m_ObeyDebsConstViolationPrinciple = true; + ArchivingPESAII m_PESAII = new ArchivingPESAII(); + int[] m_Squeeze; + int m_TournamentSize = 2; + boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMOPESA() { } public SelectMOPESA(SelectMOPESA a) { - this.m_PESAII = new ArchivingPESAII(); - this.m_TournamentSize = a.m_TournamentSize; + this.m_PESAII = new ArchivingPESAII(); + this.m_TournamentSize = a.m_TournamentSize; this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -33,22 +34,26 @@ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable { return (Object) new SelectMOPESA(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { this.m_Squeeze = this.m_PESAII.calculateSqueezeFactor(population); } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -61,17 +66,19 @@ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable { return result; } - /** This method selects a single individual from the current population + /** + * This method selects a single individual from the current population + * * @param population The population to select from */ private AbstractEAIndividual select(Population population) { - AbstractEAIndividual resultIndy; - int winner, tmp; + AbstractEAIndividual resultIndy; + int winner, tmp; try { - winner = RNG.randomInt(0, population.size()-1); + winner = RNG.randomInt(0, population.size() - 1); for (int i = 1; i < this.m_TournamentSize; i++) { - tmp = RNG.randomInt(0, population.size()-1); + tmp = RNG.randomInt(0, population.size() - 1); if (this.m_Squeeze[tmp] < this.m_Squeeze[winner]) { winner = tmp; } @@ -84,10 +91,12 @@ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable { return resultIndy; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -98,42 +107,54 @@ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Performs a binary tournament selection, preferring the individual with the smaller squeezing factor."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "PESA Selection"; } - /** You can choose the tournament size. - */ + /** + * You can choose the tournament size. + */ public String tournamentSizeTipText() { return "Choose the tournament size."; } + public int getTournamentSize() { return m_TournamentSize; } + public void setTournamentSize(int g) { m_TournamentSize = g; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectMOPESAII.java b/src/eva2/optimization/operator/selection/SelectMOPESAII.java index 35b90549..c503e47e 100644 --- a/src/eva2/optimization/operator/selection/SelectMOPESAII.java +++ b/src/eva2/optimization/operator/selection/SelectMOPESAII.java @@ -5,12 +5,14 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.operator.archiving.ArchivingPESAII; import eva2.optimization.population.Population; import eva2.tools.math.RNG; + import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; -/** The multi-objective PESA II selection criteria based on an n-dimensional - * grid using a squeezing factor. +/** + * The multi-objective PESA II selection criteria based on an n-dimensional + * grid using a squeezing factor. * Created by IntelliJ IDEA. * User: streiche * Date: 11.08.2004 @@ -19,19 +21,19 @@ import java.util.Hashtable; */ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable { - ArchivingPESAII m_PESAII = new ArchivingPESAII(); - int[] m_Squeeze; - int m_TournamentSize = 2; - ArrayList m_GridBoxes; - boolean m_ObeyDebsConstViolationPrinciple = true; + ArchivingPESAII m_PESAII = new ArchivingPESAII(); + int[] m_Squeeze; + int m_TournamentSize = 2; + ArrayList m_GridBoxes; + boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMOPESAII() { } public SelectMOPESAII(SelectMOPESAII a) { - this.m_PESAII = new ArchivingPESAII(); - this.m_TournamentSize = a.m_TournamentSize; - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_PESAII = new ArchivingPESAII(); + this.m_TournamentSize = a.m_TournamentSize; + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @Override @@ -39,28 +41,30 @@ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable return (Object) new SelectMOPESAII(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { - this.m_Squeeze = this.m_PESAII.calculateSqueezeFactor(population); - Hashtable tmpGridBoxes = new Hashtable(); - ArrayList tmp; + this.m_Squeeze = this.m_PESAII.calculateSqueezeFactor(population); + Hashtable tmpGridBoxes = new Hashtable(); + ArrayList tmp; AbstractEAIndividual tmpIndy; - int[] gridBox; - String tmpString; + int[] gridBox; + String tmpString; // first build the hashtable for (int i = 0; i < population.size(); i++) { - tmpIndy = (AbstractEAIndividual)population.get(i); - gridBox = (int[])tmpIndy.getData("GridBox"); - tmpString =""; + tmpIndy = (AbstractEAIndividual) population.get(i); + gridBox = (int[]) tmpIndy.getData("GridBox"); + tmpString = ""; for (int j = 0; j < gridBox.length; j++) { - tmpString += gridBox[j]+"/"; + tmpString += gridBox[j] + "/"; } if (tmpGridBoxes.get(tmpString) == null) { tmp = new ArrayList(); @@ -78,11 +82,13 @@ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable } } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -95,22 +101,24 @@ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable return result; } - /** This method selects a single individual from the current population + /** + * This method selects a single individual from the current population + * * @param population The population to select from */ private AbstractEAIndividual select(Population population) { - AbstractEAIndividual resultIndy; - ArrayList box1, box2; - int winner, tmp; + AbstractEAIndividual resultIndy; + ArrayList box1, box2; + int winner, tmp; try { - box1 = (ArrayList)this.m_GridBoxes.get(RNG.randomInt(0, this.m_GridBoxes.size()-1)); - box2 = (ArrayList)this.m_GridBoxes.get(RNG.randomInt(0, this.m_GridBoxes.size()-1)); - if (((Integer)((AbstractEAIndividual)box1.get(0)).getData("SqueezeFactor")).intValue() - < ((Integer)((AbstractEAIndividual)box2.get(0)).getData("SqueezeFactor")).intValue()) { - resultIndy = (AbstractEAIndividual) (box1.get(RNG.randomInt(0, box1.size()-1))); + box1 = (ArrayList) this.m_GridBoxes.get(RNG.randomInt(0, this.m_GridBoxes.size() - 1)); + box2 = (ArrayList) this.m_GridBoxes.get(RNG.randomInt(0, this.m_GridBoxes.size() - 1)); + if (((Integer) ((AbstractEAIndividual) box1.get(0)).getData("SqueezeFactor")).intValue() + < ((Integer) ((AbstractEAIndividual) box2.get(0)).getData("SqueezeFactor")).intValue()) { + resultIndy = (AbstractEAIndividual) (box1.get(RNG.randomInt(0, box1.size() - 1))); } else { - resultIndy = (AbstractEAIndividual) (box2.get(RNG.randomInt(0, box2.size()-1))); + resultIndy = (AbstractEAIndividual) (box2.get(RNG.randomInt(0, box2.size() - 1))); } } catch (java.lang.IndexOutOfBoundsException e) { System.out.println("Tournament Selection produced IndexOutOfBoundsException!"); @@ -119,10 +127,12 @@ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable return resultIndy; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -133,30 +143,39 @@ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Performs a binary tournament selection, preferring the gridbox of smaller squeezing factor and selecting a random individual from the winner box."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "PESAII Selection"; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectMOSPEAII.java b/src/eva2/optimization/operator/selection/SelectMOSPEAII.java index ef624cd6..c7c863fe 100644 --- a/src/eva2/optimization/operator/selection/SelectMOSPEAII.java +++ b/src/eva2/optimization/operator/selection/SelectMOSPEAII.java @@ -9,7 +9,8 @@ import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; -/** The SPEA II selection criteria using strength and raw fitness to determine +/** + * The SPEA II selection criteria using strength and raw fitness to determine * good individuals. * Created by IntelliJ IDEA. * User: streiche @@ -19,17 +20,17 @@ import eva2.tools.chart2d.DPoint; */ public class SelectMOSPEAII implements InterfaceSelection, java.io.Serializable { - private InterfaceSelection m_EnvironmentSelection = new SelectTournament(); - private ArchivingSPEAII m_SPEAII = new ArchivingSPEAII(); - private double[] m_SPEAFitness; - private boolean m_ObeyDebsConstViolationPrinciple = true; + private InterfaceSelection m_EnvironmentSelection = new SelectTournament(); + private ArchivingSPEAII m_SPEAII = new ArchivingSPEAII(); + private double[] m_SPEAFitness; + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectMOSPEAII() { } public SelectMOSPEAII(SelectMOSPEAII a) { - this.m_SPEAII = new ArchivingSPEAII(); - this.m_EnvironmentSelection = (InterfaceSelection)a.m_EnvironmentSelection.clone(); + this.m_SPEAII = new ArchivingSPEAII(); + this.m_EnvironmentSelection = (InterfaceSelection) a.m_EnvironmentSelection.clone(); this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -38,34 +39,38 @@ public class SelectMOSPEAII implements InterfaceSelection, java.io.Serializable return (Object) new SelectMOSPEAII(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { m_SPEAFitness = this.m_SPEAII.calculateSPEA(population); } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { // first replace the fitness with the SPEA strength - double[][] orgFit = new double[population.size()][]; - double[] newFit = new double[1]; + double[][] orgFit = new double[population.size()][]; + double[] newFit = new double[1]; for (int i = 0; i < population.size(); i++) { - orgFit[i] = ((AbstractEAIndividual)population.get(i)).getFitness(); - newFit = new double[1]; - newFit[0] = this.m_SPEAFitness[i]; - ((AbstractEAIndividual)population.get(i)).setFitness(newFit); + orgFit[i] = ((AbstractEAIndividual) population.get(i)).getFitness(); + newFit = new double[1]; + newFit[0] = this.m_SPEAFitness[i]; + ((AbstractEAIndividual) population.get(i)).setFitness(newFit); } // then select @@ -73,7 +78,7 @@ public class SelectMOSPEAII implements InterfaceSelection, java.io.Serializable // finally replace the fitness with the original for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).setFitness(orgFit[i]); + ((AbstractEAIndividual) population.get(i)).setFitness(orgFit[i]); } if (false) { @@ -84,16 +89,16 @@ public class SelectMOSPEAII implements InterfaceSelection, java.io.Serializable Plot plot = new Plot("Debug SPEAIISelect", "Y1", "Y2", tmpD, tmpD); plot.setUnconnectedPoint(0, 0, 11); plot.setUnconnectedPoint(1.2, 10, 11); - GraphPointSet mySet = new GraphPointSet(10, plot.getFunctionArea()); - DPoint myPoint; - double tmp1, tmp2; + GraphPointSet mySet = new GraphPointSet(10, plot.getFunctionArea()); + DPoint myPoint; + double tmp1, tmp2; Chart2DDPointIconText tmp; mySet.setConnectedMode(false); for (int i = 0; i < orgFit.length; i++) { myPoint = new DPoint(orgFit[i][0], orgFit[i][1]); - tmp1 = Math.round(m_SPEAFitness[i]*100)/(double)100; - tmp = new Chart2DDPointIconText(""+tmp1); + tmp1 = Math.round(m_SPEAFitness[i] * 100) / (double) 100; + tmp = new Chart2DDPointIconText("" + tmp1); tmp.setIcon(new Chart2DDPointIconCircle()); myPoint.setIcon(tmp); mySet.addDPoint(myPoint); @@ -109,10 +114,12 @@ public class SelectMOSPEAII implements InterfaceSelection, java.io.Serializable return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -123,45 +130,57 @@ public class SelectMOSPEAII implements InterfaceSelection, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "MO SPEAII selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This selection method calucates the strength and selects using the strength."; } - /** This method will set the selection method that is to be used + /** + * This method will set the selection method that is to be used + * * @param selection */ public void setEnvironmentSelection(InterfaceSelection selection) { this.m_EnvironmentSelection = selection; } + public InterfaceSelection getEnvironmentSelection() { return this.m_EnvironmentSelection; } + public String environmentSelectionTipText() { return "Choose a method for selecting the reduced population."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectParticleWheel.java b/src/eva2/optimization/operator/selection/SelectParticleWheel.java index 6efbc5d4..22866e51 100644 --- a/src/eva2/optimization/operator/selection/SelectParticleWheel.java +++ b/src/eva2/optimization/operator/selection/SelectParticleWheel.java @@ -8,7 +8,8 @@ import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** This method implements the roulette wheel selection for +/** + * This method implements the roulette wheel selection for * a partical filter. In case of multiple fitness values the selection * critria should be selected randomly for each selection event. * Created by IntelliJ IDEA. @@ -18,28 +19,28 @@ import eva2.tools.math.RNG; * To change this template use Options | File Templates. */ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializable { - - private boolean m_ObeyDebsConstViolationPrinciple = true; + + private boolean m_ObeyDebsConstViolationPrinciple = true; /** - * Comment for serialVersionUID - */ - private static final long serialVersionUID = 1L; - private InterfaceSelectionProbability m_SelProbCalculator = new SelProbStandard(); - private boolean selectFixedSteps = false; + * Comment for serialVersionUID + */ + private static final long serialVersionUID = 1L; + private InterfaceSelectionProbability m_SelProbCalculator = new SelProbStandard(); + private boolean selectFixedSteps = false; public SelectParticleWheel() { } - + public SelectParticleWheel(double scalingProb) { - m_SelProbCalculator = new SelProbStandardScaling(scalingProb); + m_SelProbCalculator = new SelProbStandardScaling(scalingProb); } public SelectParticleWheel(InterfaceSelectionProbability selProb) { - m_SelProbCalculator = selProb; + m_SelProbCalculator = selProb; } public SelectParticleWheel(SelectParticleWheel a) { - this.m_SelProbCalculator = (InterfaceSelectionProbability)a.m_SelProbCalculator.clone(); + this.m_SelProbCalculator = (InterfaceSelectionProbability) a.m_SelProbCalculator.clone(); this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -47,33 +48,32 @@ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializ public Object clone() { return (Object) new SelectParticleWheel(this); } - + @Override public void prepareSelection(Population population) { - m_SelProbCalculator.computeSelectionProbability(population, "Fitness", m_ObeyDebsConstViolationPrinciple); + m_SelProbCalculator.computeSelectionProbability(population, "Fitness", m_ObeyDebsConstViolationPrinciple); } /** - * This method will select individuals from the given Population with respect to their + * This method will select individuals from the given Population with respect to their * selection propability. This implements a fixed segment roulette wheel selection which ensures * that every individual which has a selection probability p >= (k/size) is selected k or k+1 times. - * - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override public Population selectFrom(Population population, int size) { Population result = new Population(); result.setTargetSize(size); - - if (selectFixedSteps ) { + + if (selectFixedSteps) { selectFixed(population, size, result); - } - else { + } else { selectDrawIndependent(population, size, result); } - + //// Unfortunately, this was really problem specific (mk) // // double overallFit=0.0; @@ -95,49 +95,51 @@ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializ // } // // } - return result; + return result; } - private void selectDrawIndependent(Population population, int size, - Population result) { - double sum=0, selPoint=0; - int selIndex; - for (int i=0; i < size; i++) { - selPoint = RNG.randomDouble(); - selIndex = 0; - sum = ((AbstractEAIndividual)population.getIndividual(0)).getSelectionProbability(0); - while (selPoint>=sum) { - selIndex++; - sum += ((AbstractEAIndividual)population.getIndividual(selIndex)).getSelectionProbability(0); - } - result.add(((AbstractEAIndividual)population.get(selIndex)).clone()); - ((AbstractEAIndividual)result.getIndividual(i)).SetAge(0); + private void selectDrawIndependent(Population population, int size, + Population result) { + double sum = 0, selPoint = 0; + int selIndex; + for (int i = 0; i < size; i++) { + selPoint = RNG.randomDouble(); + selIndex = 0; + sum = ((AbstractEAIndividual) population.getIndividual(0)).getSelectionProbability(0); + while (selPoint >= sum) { + selIndex++; + sum += ((AbstractEAIndividual) population.getIndividual(selIndex)).getSelectionProbability(0); + } + result.add(((AbstractEAIndividual) population.get(selIndex)).clone()); + ((AbstractEAIndividual) result.getIndividual(i)).SetAge(0); } - } + } - private void selectFixed(Population population, int size, Population result) { - // use a fixed segment roulette wheel selection - double segment = 1./(size+1); + private void selectFixed(Population population, int size, Population result) { + // use a fixed segment roulette wheel selection + double segment = 1. / (size + 1); double selPoint = RNG.randomDouble(0., segment); - - int selIndex = 0; - double selFitSum = ((AbstractEAIndividual)population.getIndividual(selIndex)).getSelectionProbability(0); - - for (int i=0; i < size; i++) { - while (selFitSum < selPoint) { - selIndex++; - selFitSum += ((AbstractEAIndividual)population.getIndividual(selIndex)).getSelectionProbability(0); - } - result.add(((AbstractEAIndividual)population.get(selIndex)).clone()); - ((AbstractEAIndividual)result.getIndividual(i)).SetAge(0); - selPoint += segment; - } - } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + int selIndex = 0; + double selFitSum = ((AbstractEAIndividual) population.getIndividual(selIndex)).getSelectionProbability(0); + + for (int i = 0; i < size; i++) { + while (selFitSum < selPoint) { + selIndex++; + selFitSum += ((AbstractEAIndividual) population.getIndividual(selIndex)).getSelectionProbability(0); + } + result.add(((AbstractEAIndividual) population.get(selIndex)).clone()); + ((AbstractEAIndividual) result.getIndividual(i)).SetAge(0); + selPoint += segment; + } + } + + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -148,15 +150,19 @@ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Particle Wheel Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -164,55 +170,59 @@ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializ "This is a single objective selecting method, it will select in respect to a random criterion."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle(todo)."; } - /** - * @return the selectFixedSteps - */ - public boolean isSelectFixedSteps() { - return selectFixedSteps; - } + /** + * @return the selectFixedSteps + */ + public boolean isSelectFixedSteps() { + return selectFixedSteps; + } - /** - * @param selectFixedSteps the selectFixedSteps to set - */ - public void setSelectFixedSteps(boolean selectFixedSteps) { - this.selectFixedSteps = selectFixedSteps; - } - - public String selectFixedStepsTipText() { - return "Use fixed segment wheel for selection if marked or independent draws if not."; - } + /** + * @param selectFixedSteps the selectFixedSteps to set + */ + public void setSelectFixedSteps(boolean selectFixedSteps) { + this.selectFixedSteps = selectFixedSteps; + } - /** - * @return the m_SelProbCalculator - */ - public InterfaceSelectionProbability getSelProbCalculator() { - return m_SelProbCalculator; - } + public String selectFixedStepsTipText() { + return "Use fixed segment wheel for selection if marked or independent draws if not."; + } - /** - * @param selProbCalculator the m_SelProbCalculator to set - */ - public void setSelProbCalculator( - InterfaceSelectionProbability selProbCalculator) { - m_SelProbCalculator = selProbCalculator; - } - - public String selProbCalculatorTipText() { - return "The method for calculating selection probability from the fitness."; - } + /** + * @return the m_SelProbCalculator + */ + public InterfaceSelectionProbability getSelProbCalculator() { + return m_SelProbCalculator; + } + + /** + * @param selProbCalculator the m_SelProbCalculator to set + */ + public void setSelProbCalculator( + InterfaceSelectionProbability selProbCalculator) { + m_SelProbCalculator = selProbCalculator; + } + + public String selProbCalculatorTipText() { + return "The method for calculating selection probability from the fitness."; + } } \ No newline at end of file diff --git a/src/eva2/optimization/operator/selection/SelectRandom.java b/src/eva2/optimization/operator/selection/SelectRandom.java index 66045223..ec4b30be 100644 --- a/src/eva2/optimization/operator/selection/SelectRandom.java +++ b/src/eva2/optimization/operator/selection/SelectRandom.java @@ -5,9 +5,9 @@ import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** +/** * Random selection typically used for ES as mating selection. - * + *

* Created by IntelliJ IDEA. * User: streiche * Date: 18.03.2003 @@ -16,8 +16,8 @@ import eva2.tools.math.RNG; */ public class SelectRandom implements InterfaceSelection, java.io.Serializable { - private boolean m_ObeyDebsConstViolationPrinciple = false; - private boolean withReplacement = true; + private boolean m_ObeyDebsConstViolationPrinciple = false; + private boolean withReplacement = true; public SelectRandom() { } @@ -28,33 +28,36 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable { } public SelectRandom(boolean withRepl) { - withReplacement=withRepl; - if (m_ObeyDebsConstViolationPrinciple) { + withReplacement = withRepl; + if (m_ObeyDebsConstViolationPrinciple) { System.err.println("Error, replacement selection not supported for constrained selection (SelectRandom)"); } } - + @Override public Object clone() { return (Object) new SelectRandom(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method will select individuals randomly from the given + /** + * This method will select individuals randomly from the given * Population. Individuals may be drawn several times or not at all. - * - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -64,41 +67,43 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable { if (this.m_ObeyDebsConstViolationPrinciple) { int index = 0, rand; while (result.size() < size) { - rand = RNG.randomInt(0, population.size()-1); - if (!((AbstractEAIndividual)population.get(rand)).violatesConstraint()) { + rand = RNG.randomInt(0, population.size() - 1); + if (!((AbstractEAIndividual) population.get(rand)).violatesConstraint()) { result.add(population.get(rand)); } index++; - if ((index > 0) && (result.size() == 0 )) { + if ((index > 0) && (result.size() == 0)) { // darn there seems to be no feasible solution // just select random one instead for (int i = 0; i < size; i++) { - result.add(population.get(RNG.randomInt(0, population.size()-1))); + result.add(population.get(RNG.randomInt(0, population.size() - 1))); } } } } else { - if (withReplacement) { - for (int i = 0; i < size; i++) { - result.add(population.get(RNG.randomInt(0, population.size()-1))); - } - } else { - if (size > population.size()) { - throw new RuntimeException("Error, invalid selection: trying to select more individuals (without replacement) than available in SelectRandom."); - } - int[] perm = RNG.randomPerm(size); - for (int i=0; i population.size()) { + throw new RuntimeException("Error, invalid selection: trying to select more individuals (without replacement) than available in SelectRandom."); + } + int[] perm = RNG.randomPerm(size); + for (int i = 0; i < size; i++) { + result.add(population.getEAIndividual(perm[i])); + } + } } return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already selected parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already selected parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -109,32 +114,40 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable { /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Random Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method selects randomly. Therefore, it even works fine on Multiobjective fitness cases."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectTournament.java b/src/eva2/optimization/operator/selection/SelectTournament.java index bd3b0c0c..d5d2fd68 100644 --- a/src/eva2/optimization/operator/selection/SelectTournament.java +++ b/src/eva2/optimization/operator/selection/SelectTournament.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** Tournament selection within a given tournament group size, +/** + * Tournament selection within a given tournament group size, * also scaling invariant. * In case of multiple fitness values the selection * critria is selected randomly for each selection event. @@ -16,19 +17,19 @@ import eva2.tools.math.RNG; */ public class SelectTournament implements InterfaceSelection, java.io.Serializable { - private int m_TournamentSize = 4; - private boolean m_ObeyDebsConstViolationPrinciple = true; + private int m_TournamentSize = 4; + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectTournament() { } public SelectTournament(int tSize) { - this(); - setTournamentSize(tSize); + this(); + setTournamentSize(tSize); } - + public SelectTournament(SelectTournament a) { - this.m_TournamentSize = a.m_TournamentSize; + this.m_TournamentSize = a.m_TournamentSize; this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; } @@ -37,22 +38,26 @@ public class SelectTournament implements InterfaceSelection, java.io.Serializabl return (Object) new SelectTournament(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { // nothing to prepare here } - /** This method will select one Individual from the given + /** + * This method will select one Individual from the given * Population in respect to the selection propability of the * individual. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -65,28 +70,30 @@ public class SelectTournament implements InterfaceSelection, java.io.Serializabl return result; } - /** This method selects a single individual from the current population + /** + * This method selects a single individual from the current population + * * @param population The population to select from */ private AbstractEAIndividual select(Population population) { - AbstractEAIndividual result, tmpIndy; - int currentCriteria = 0, critSize = 0; + AbstractEAIndividual result, tmpIndy; + int currentCriteria = 0, critSize = 0; try { - critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length; - currentCriteria = RNG.randomInt(0, critSize-1); + critSize = ((AbstractEAIndividual) population.get(0)).getFitness().length; + currentCriteria = RNG.randomInt(0, critSize - 1); if (this.m_ObeyDebsConstViolationPrinciple) { Population tournamentGroup = new Population(); for (int i = 0; i < this.m_TournamentSize; i++) { - tournamentGroup.add(population.get(RNG.randomInt(0, population.size()-1))); + tournamentGroup.add(population.get(RNG.randomInt(0, population.size() - 1))); } SelectBestIndividuals best = new SelectBestIndividuals(); best.setObeyDebsConstViolationPrinciple(true); - result = (AbstractEAIndividual)best.selectFrom(tournamentGroup, 1).get(0); + result = (AbstractEAIndividual) best.selectFrom(tournamentGroup, 1).get(0); } else { - result = (AbstractEAIndividual) population.get(RNG.randomInt(0, population.size()-1)); + result = (AbstractEAIndividual) population.get(RNG.randomInt(0, population.size() - 1)); for (int i = 1; i < this.m_TournamentSize; i++) { - tmpIndy = (AbstractEAIndividual) population.get(RNG.randomInt(0, population.size()-1)); + tmpIndy = (AbstractEAIndividual) population.get(RNG.randomInt(0, population.size() - 1)); if (tmpIndy.getFitness(currentCriteria) < result.getFitness(currentCriteria)) { result = tmpIndy; } @@ -101,10 +108,12 @@ public class SelectTournament implements InterfaceSelection, java.io.Serializabl return result; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -115,15 +124,19 @@ public class SelectTournament implements InterfaceSelection, java.io.Serializabl /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Tournament Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -131,29 +144,36 @@ public class SelectTournament implements InterfaceSelection, java.io.Serializabl "This is a single-objective method, it selects with respect to the first criterion in the multi-objective case."; } - /** You can choose the tournament size. - */ + /** + * You can choose the tournament size. + */ public String tournamentSizeTipText() { return "Choose the tournament size."; } + public int getTournamentSize() { return m_TournamentSize; } + public void setTournamentSize(int g) { m_TournamentSize = g; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/SelectXProbRouletteWheel.java b/src/eva2/optimization/operator/selection/SelectXProbRouletteWheel.java index 48059ce2..1aea2eae 100644 --- a/src/eva2/optimization/operator/selection/SelectXProbRouletteWheel.java +++ b/src/eva2/optimization/operator/selection/SelectXProbRouletteWheel.java @@ -8,9 +8,9 @@ import eva2.tools.math.RNG; class treeElement implements java.io.Serializable { - public double separator = 0; - public int m_Index = -1; - public treeElement m_Left = null, m_Right = null; + public double separator = 0; + public int m_Index = -1; + public treeElement m_Left = null, m_Right = null; public treeElement(double[][] d, int list, int low, int high) { //System.out.println("Calling Low/high: "+low+"/"+high); @@ -19,12 +19,12 @@ class treeElement implements java.io.Serializable { //System.out.println("This: "+low); this.m_Index = low; } else { - if (low == high-1) { + if (low == high - 1) { //System.out.println("This: "+high); this.m_Index = high; } else { - int midPoint = (int)((high+low)/2); - this.separator = d[midPoint-1][list]; + int midPoint = (int) ((high + low) / 2); + this.separator = d[midPoint - 1][list]; //System.out.println("Branching: "+midPoint + " : " + this.separator); this.m_Left = new treeElement(d, list, low, midPoint); this.m_Right = new treeElement(d, list, midPoint, high); @@ -34,13 +34,11 @@ class treeElement implements java.io.Serializable { public int getIndexFor(double d) { if (this.m_Index >= 0) { - return this.m_Index-1; - } - else { + return this.m_Index - 1; + } else { if (d < this.separator) { return this.m_Left.getIndexFor(d); - } - else { + } else { return this.m_Right.getIndexFor(d); } } @@ -49,15 +47,15 @@ class treeElement implements java.io.Serializable { @Override public String toString() { if (this.m_Index >= 0) { - return "Ind:"+this.m_Index; - } - else { - return "{"+this.m_Left.toString()+"} X<"+this.separator+" {"+this.m_Right.toString()+"}"; + return "Ind:" + this.m_Index; + } else { + return "{" + this.m_Left.toString() + "} X<" + this.separator + " {" + this.m_Right.toString() + "}"; } } } -/** The RoulettWheel selection requires a selection probability calculator. +/** + * The RoulettWheel selection requires a selection probability calculator. * In case of multiple fitness values the selection * critria is selected randomly for each selection event. * Created by IntelliJ IDEA. @@ -68,16 +66,16 @@ class treeElement implements java.io.Serializable { */ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Serializable { - private transient treeElement[] m_TreeRoot = null; - private InterfaceSelectionProbability m_SelProbCalculator = new SelProbStandard(); - private boolean m_ObeyDebsConstViolationPrinciple = true; + private transient treeElement[] m_TreeRoot = null; + private InterfaceSelectionProbability m_SelProbCalculator = new SelProbStandard(); + private boolean m_ObeyDebsConstViolationPrinciple = true; public SelectXProbRouletteWheel() { } public SelectXProbRouletteWheel(SelectXProbRouletteWheel a) { - this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; - this.m_SelProbCalculator = (InterfaceSelectionProbability)a.m_SelProbCalculator.clone(); + this.m_ObeyDebsConstViolationPrinciple = a.m_ObeyDebsConstViolationPrinciple; + this.m_SelProbCalculator = (InterfaceSelectionProbability) a.m_SelProbCalculator.clone(); } @Override @@ -85,11 +83,13 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser return (Object) new SelectXProbRouletteWheel(this); } - /** This method allows an selection method to do some preliminary + /** + * This method allows an selection method to do some preliminary * calculations on the population before selection is performed. * For example: Homologeuos mate could compute all the distances * before hand... - * @param population The population that is to be processed. + * + * @param population The population that is to be processed. */ @Override public void prepareSelection(Population population) { @@ -97,12 +97,13 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser this.m_TreeRoot = this.buildSelectionTree(population); } - /** + /** * This method will select a pool of individuals from the given * Population in respect to the selection probability of the * individuals. - * @param population The source population where to select from - * @param size The number of Individuals to select + * + * @param population The source population where to select from + * @param size The number of Individuals to select * @return The selected population. */ @Override @@ -111,26 +112,27 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser result.setTargetSize(size); for (int i = 0; i < size; i++) { - result.add(this.selectTree(population)); + result.add(this.selectTree(population)); } return result; } - /** + /** * This method will build a selection tree. - * @param p The population + * + * @param p The population */ private treeElement[] buildSelectionTree(Population p) { treeElement result[]; - double[][] tmpList = new double[p.size()][]; + double[][] tmpList = new double[p.size()][]; for (int i = 0; i < p.size(); i++) { - tmpList[i] = new double[((AbstractEAIndividual)(p.get(i))).getSelectionProbability().length]; - System.arraycopy(((AbstractEAIndividual)(p.get(i))).getSelectionProbability(), 0, tmpList[i], 0, tmpList[i].length); + tmpList[i] = new double[((AbstractEAIndividual) (p.get(i))).getSelectionProbability().length]; + System.arraycopy(((AbstractEAIndividual) (p.get(i))).getSelectionProbability(), 0, tmpList[i], 0, tmpList[i].length); if (i > 0) { for (int j = 0; j < tmpList[i].length; j++) { - tmpList[i][j] += tmpList[i-1][j]; + tmpList[i][j] += tmpList[i - 1][j]; } } } @@ -147,38 +149,39 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser return result; } - /** This method selects a single individual from the current population + /** + * This method selects a single individual from the current population + * * @param population The population to select from */ private AbstractEAIndividual selectTree(Population population) { - int currentCriteria = 0, critSize; + int currentCriteria = 0, critSize; - critSize = ((AbstractEAIndividual)population.get(0)).getSelectionProbability().length; - currentCriteria = RNG.randomInt(0, critSize-1); + critSize = ((AbstractEAIndividual) population.get(0)).getSelectionProbability().length; + currentCriteria = RNG.randomInt(0, critSize - 1); double d = RNG.randomDouble(); int index = this.m_TreeRoot[currentCriteria].getIndexFor(d); //System.out.println("Looking for: " + d + " found " +index); - return ((AbstractEAIndividual)(population.get(index))); + return ((AbstractEAIndividual) (population.get(index))); } private AbstractEAIndividual selectStandard(Population population) { - // old version - double sum = 1, random, tmpD; - int currentCriteria = 0, critSize; + // old version + double sum = 1, random, tmpD; + int currentCriteria = 0, critSize; - critSize = ((AbstractEAIndividual)population.get(0)).getSelectionProbability().length; - currentCriteria = RNG.randomInt(0, critSize-1); + critSize = ((AbstractEAIndividual) population.get(0)).getSelectionProbability().length; + currentCriteria = RNG.randomInt(0, critSize - 1); String logger = ""; while (sum > 0) { sum = 0; random = RNG.randomDouble(); for (int i = 0; i < population.size(); i++) { - tmpD = ((AbstractEAIndividual)(population.get(i))).getSelectionProbability(currentCriteria); + tmpD = ((AbstractEAIndividual) (population.get(i))).getSelectionProbability(currentCriteria); logger += tmpD + "; "; if (random < (sum + tmpD)) { - return ((AbstractEAIndividual)(population.get(i))); - } - else { + return ((AbstractEAIndividual) (population.get(i))); + } else { sum += tmpD; } } @@ -189,10 +192,12 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser return null; } - /** This method allows you to select partners for a given Individual - * @param dad The already seleceted parent - * @param avaiablePartners The mating pool. - * @param size The number of partners needed. + /** + * This method allows you to select partners for a given Individual + * + * @param dad The already seleceted parent + * @param avaiablePartners The mating pool. + * @param size The number of partners needed. * @return The selected partners. */ @Override @@ -203,15 +208,19 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Roulette Wheel Selection"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -219,30 +228,38 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser "This is a single objective selecting method, it select with respect to a random criterion."; } - /** This method will set the normation method that is to be used. + /** + * This method will set the normation method that is to be used. + * * @param normation */ - public void setSelProbCalculator (InterfaceSelectionProbability normation) { + public void setSelProbCalculator(InterfaceSelectionProbability normation) { this.m_SelProbCalculator = normation; } - public InterfaceSelectionProbability getSelProbCalculator () { + + public InterfaceSelectionProbability getSelProbCalculator() { return this.m_SelProbCalculator; } + public String selProbCalculatorTipText() { return "Select the normation method."; } - /** Toggle the use of obeying the constraint violation principle + /** + * Toggle the use of obeying the constraint violation principle * of Deb - * @param b The new state + * + * @param b The new state */ @Override public void setObeyDebsConstViolationPrinciple(boolean b) { this.m_ObeyDebsConstViolationPrinciple = b; } + public boolean getObeyDebsConstViolationPrinciple() { return this.m_ObeyDebsConstViolationPrinciple; } + public String obeyDebsConstViolationPrincipleToolTip() { return "Toggle the use of Deb's coonstraint violation principle."; } diff --git a/src/eva2/optimization/operator/selection/probability/AbstractSelProb.java b/src/eva2/optimization/operator/selection/probability/AbstractSelProb.java index 5bec5c80..118427c8 100644 --- a/src/eva2/optimization/operator/selection/probability/AbstractSelProb.java +++ b/src/eva2/optimization/operator/selection/probability/AbstractSelProb.java @@ -4,9 +4,11 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.EVAERROR; + import java.util.ArrayList; -/** This abstract implementation gives some general +/** + * This abstract implementation gives some general * methods for retrieving and cleaning fitness values. * Created by IntelliJ IDEA. * User: streiche @@ -16,29 +18,35 @@ import java.util.ArrayList; */ public abstract class AbstractSelProb implements InterfaceSelectionProbability, java.io.Serializable { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ @Override public abstract Object clone(); - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param input The name of the input. + * probability sums up to one. + * + * @param population The population to compute. + * @param input The name of the input. */ @Override public void computeSelectionProbability(Population population, String[] input, boolean obeyConst) { this.computeSelectionProbability(population, this.preprocess(population, input), obeyConst); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param input The name of the input. + * probability sums up to one. + * + * @param population The population to compute. + * @param input The name of the input. */ @Override public void computeSelectionProbability(Population population, String input, boolean obeyConst) { @@ -47,90 +55,94 @@ public abstract class AbstractSelProb implements InterfaceSelectionProbability, this.computeSelectionProbability(population, tmp, obeyConst); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input data as double[][]. + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input data as double[][]. */ @Override public abstract void computeSelectionProbability(Population population, double[][] data, boolean obeyConst); - /** This method converts all inputs to a list of double values - * @param population A population that is to be computed. - * @param inputs A list of inputs. + /** + * This method converts all inputs to a list of double values + * + * @param population A population that is to be computed. + * @param inputs A list of inputs. * @return double[][] A array of values, first index gives the individual, second index the value. */ protected double[][] preprocess(Population population, String[] inputs) { - double[][] result; - double[] tmpD; - ArrayList tmpList = new ArrayList(); + double[][] result; + double[] tmpD; + ArrayList tmpList = new ArrayList(); AbstractEAIndividual tmpIndy; - Object obj; + Object obj; result = new double[population.size()][]; for (int i = 0; i < population.size(); i++) { - tmpIndy = (AbstractEAIndividual)population.get(i); + tmpIndy = (AbstractEAIndividual) population.get(i); tmpList = new ArrayList(); for (int j = 0; j < inputs.length; j++) { obj = tmpIndy.getData(inputs[j]); - if (obj==null) { + if (obj == null) { EVAERROR.errorMsgOnce("Error: could not get data by key " + inputs[j] + " from individual in AbstractSelProb"); } if (obj instanceof double[]) { - for (int m = 0; m < ((double[])obj).length; m++) { - tmpList.add(new Double(((double[])obj)[m])); + for (int m = 0; m < ((double[]) obj).length; m++) { + tmpList.add(new Double(((double[]) obj)[m])); } continue; } if (obj instanceof Double) { - tmpList.add((Double)obj); + tmpList.add((Double) obj); continue; } if (obj instanceof float[]) { - for (int m = 0; m < ((float[])obj).length; m++) { - tmpList.add(new Double(((float[])obj)[m])); + for (int m = 0; m < ((float[]) obj).length; m++) { + tmpList.add(new Double(((float[]) obj)[m])); } continue; } if (obj instanceof Float) { - tmpList.add((Float)obj); + tmpList.add((Float) obj); continue; } if (obj instanceof long[]) { - for (int m = 0; m < ((long[])obj).length; m++) { - tmpList.add(new Double(((long[])obj)[m])); + for (int m = 0; m < ((long[]) obj).length; m++) { + tmpList.add(new Double(((long[]) obj)[m])); } continue; } if (obj instanceof Long) { - tmpList.add((Long)obj); + tmpList.add((Long) obj); continue; } if (obj instanceof int[]) { - for (int m = 0; m < ((int[])obj).length; m++) { - tmpList.add(new Double(((int[])obj)[m])); + for (int m = 0; m < ((int[]) obj).length; m++) { + tmpList.add(new Double(((int[]) obj)[m])); } continue; } if (obj instanceof Integer) { - tmpList.add((Integer)obj); + tmpList.add((Integer) obj); } } // now we got a complete ArrayList tmpD = new double[tmpList.size()]; for (int j = 0; j < tmpD.length; j++) { - tmpD[j] = ((Double)tmpList.get(j)).doubleValue(); + tmpD[j] = ((Double) tmpList.get(j)).doubleValue(); } result[i] = tmpD; } // Here i could check for NaN and BufferOverflows - double tmpSum, min, max; + double tmpSum, min, max; for (int i = 0; i < result.length; i++) { - tmpSum = 0; - min = Double.MAX_VALUE; - max = Double.MIN_VALUE; + tmpSum = 0; + min = Double.MAX_VALUE; + max = Double.MIN_VALUE; for (int j = 0; j < result[i].length; j++) { if (Double.isInfinite(result[i][j])) { result[i][j] = Double.NaN; diff --git a/src/eva2/optimization/operator/selection/probability/InterfaceSelectionProbability.java b/src/eva2/optimization/operator/selection/probability/InterfaceSelectionProbability.java index 4206da6e..cd629277 100644 --- a/src/eva2/optimization/operator/selection/probability/InterfaceSelectionProbability.java +++ b/src/eva2/optimization/operator/selection/probability/InterfaceSelectionProbability.java @@ -2,7 +2,8 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.population.Population; -/** The interface for methods with calculate the selection +/** + * The interface for methods with calculate the selection * probability from the fitness values. While the fitness * is typically to be minimized the selection probability * is within [0,1] sums up to one and is to be maximizes. @@ -14,33 +15,41 @@ import eva2.optimization.population.Population; */ public interface InterfaceSelectionProbability { - /** This method allows you to make a deep clone of + /** + * This method allows you to make a deep clone of * the object + * * @return the deep clone */ public Object clone(); - /** This method computes the selection probability for each individual - * in the population. Note: Summed over the complete population the selection - * probability gives one. - * @param population The population to compute. - * @param input The name of the input. + /** + * This method computes the selection probability for each individual + * in the population. Note: Summed over the complete population the selection + * probability gives one. + * + * @param population The population to compute. + * @param input The name of the input. */ public void computeSelectionProbability(Population population, String[] input, boolean obeyConst); - /** This method computes the selection probability for each individual - * in the population. Note: Summed over the complete population the selection - * probability gives one. - * @param population The population to compute. - * @param input The name of the input. + /** + * This method computes the selection probability for each individual + * in the population. Note: Summed over the complete population the selection + * probability gives one. + * + * @param population The population to compute. + * @param input The name of the input. */ public void computeSelectionProbability(Population population, String input, boolean obeyConst); - /** This method computes the selection probability for each individual - * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input data as double[][]. + /** + * This method computes the selection probability for each individual + * in the population. Note: Summed over the complete population the selection + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input data as double[][]. */ public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst); } diff --git a/src/eva2/optimization/operator/selection/probability/SelProbBoltzman.java b/src/eva2/optimization/operator/selection/probability/SelProbBoltzman.java index 00a7032f..22ba9ac4 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbBoltzman.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbBoltzman.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** Boltzman selection, actually it is no a selection method +/** + * Boltzman selection, actually it is no a selection method * but a scaling method, but it is very good, because it is * invariant to any linear transition function. * Created by IntelliJ IDEA. @@ -14,17 +15,17 @@ import eva2.optimization.population.Population; */ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializable { - private double m_Q = 1.0; + private double m_Q = 1.0; public SelProbBoltzman() { } public SelProbBoltzman(double q) { - m_Q = q; + m_Q = q; } - + public SelProbBoltzman(SelProbBoltzman a) { - this.m_Q = a.m_Q; + this.m_Q = a.m_Q; } @Override @@ -32,22 +33,24 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ return (Object) new SelProbBoltzman(this); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input data as double[][]. + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input data as double[][]. */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double sum = 0, mean = 0, dev = 0; - double[] result = new double[data.length]; + double sum = 0, mean = 0, dev = 0; + double[] result = new double[data.length]; if (obeyConst) { // first check if anyone holds the constraints boolean isFeasible = false; for (int i = 0; i < population.size(); i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { isFeasible = true; } } @@ -55,9 +58,9 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ // at least one is feasible // iterating over the fitness cases for (int x = 0; x < data[0].length; x++) { - sum = 0; - mean = 0; - dev = 0; + sum = 0; + mean = 0; + dev = 0; // first find the worst, to be able to default double worst = Double.NEGATIVE_INFINITY; for (int i = 0; i < data.length; i++) { @@ -66,42 +69,41 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ } } for (int i = 0; i < data.length; i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { - result[i] = -data[i][x]; + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { + result[i] = -data[i][x]; + } else { + result[i] = -worst; } - else { - result[i] = -worst; - } - sum += result[i]; + sum += result[i]; } - mean = sum/((double)data.length); + mean = sum / ((double) data.length); for (int i = 0; i < data.length; i++) { - dev += Math.pow((result[i]-mean), 2); + dev += Math.pow((result[i] - mean), 2); } - dev = Math.sqrt(dev/(data.length-1)); + dev = Math.sqrt(dev / (data.length - 1)); if (dev < 0.0000001) { dev = 0.0000001; } sum = 0; for (int i = 0; i < data.length; i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { - result[i] = Math.exp((this.m_Q*-data[i][x])/dev); - } - else { - result[i] = Math.exp((this.m_Q*-worst)/dev); + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { + result[i] = Math.exp((this.m_Q * -data[i][x]) / dev); + } else { + result[i] = Math.exp((this.m_Q * -worst) / dev); } sum += result[i]; } if (sum == 0) { for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; - } } - else { + result[i] = 1 / result.length; + } + } else { for (int i = 0; i < data.length; i++) { - result[i] /= sum; - }} + result[i] /= sum; + } + } boolean check = true; for (int i = 0; i < data.length; i++) { @@ -116,45 +118,46 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ System.out.println("Dev: " + dev); System.out.println("Worst:" + worst); for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; + result[i] = 1 / result.length; } } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i]); } } } else { // not one is feasible therefore select the best regarding feasibility - sum = 0; - mean = 0; - dev = 0; + sum = 0; + mean = 0; + dev = 0; for (int i = 0; i < data.length; i++) { - result[i] = -((AbstractEAIndividual)population.get(i)).getConstraintViolation(); - sum += result[i]; + result[i] = -((AbstractEAIndividual) population.get(i)).getConstraintViolation(); + sum += result[i]; } - mean = sum/((double)data.length); + mean = sum / ((double) data.length); for (int i = 0; i < data.length; i++) { - dev += Math.pow((result[i]-mean), 2); + dev += Math.pow((result[i] - mean), 2); } - dev = Math.sqrt(dev/(data.length-1)); + dev = Math.sqrt(dev / (data.length - 1)); if (dev < 0.0000001) { dev = 0.0000001; } sum = 0; for (int i = 0; i < data.length; i++) { - result[i] = Math.exp((this.m_Q*-((AbstractEAIndividual)population.get(i)).getConstraintViolation())/dev); + result[i] = Math.exp((this.m_Q * -((AbstractEAIndividual) population.get(i)).getConstraintViolation()) / dev); sum += result[i]; } if (sum == 0) { for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; - } } - else { + result[i] = 1 / result.length; + } + } else { for (int i = 0; i < data.length; i++) { - result[i] /= sum; - }} + result[i] /= sum; + } + } boolean check = true; for (int i = 0; i < data.length; i++) { @@ -165,45 +168,47 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ if (!check) { System.out.println("Boltzman Normation created major error (const, but no feasible)!"); for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; + result[i] = 1 / result.length; } } for (int i = 0; i < population.size(); i++) { double[] tmpD = new double[1]; - tmpD[0] = result[i]/sum; - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(tmpD); - } } + tmpD[0] = result[i] / sum; + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(tmpD); + } + } } else { for (int x = 0; x < data[0].length; x++) { - sum = 0; - mean = 0; - dev = 0; + sum = 0; + mean = 0; + dev = 0; for (int i = 0; i < data.length; i++) { - result[i] = -data[i][x]; - sum += result[i]; + result[i] = -data[i][x]; + sum += result[i]; } - mean = sum/((double)data.length); + mean = sum / ((double) data.length); for (int i = 0; i < data.length; i++) { - dev += Math.pow((result[i]-mean), 2); + dev += Math.pow((result[i] - mean), 2); } - dev = Math.sqrt(dev/(data.length-1)); + dev = Math.sqrt(dev / (data.length - 1)); if (dev < 0.0000001) { dev = 0.0000001; } sum = 0; for (int i = 0; i < data.length; i++) { - result[i] = Math.exp((this.m_Q*-data[i][x])/dev); + result[i] = Math.exp((this.m_Q * -data[i][x]) / dev); sum += result[i]; } if (sum == 0) { for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; - } } - else { + result[i] = 1 / result.length; + } + } else { for (int i = 0; i < data.length; i++) { - result[i] /= sum; - }} + result[i] /= sum; + } + } boolean check = true; for (int i = 0; i < data.length; i++) { @@ -214,12 +219,12 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ if (!check) { System.out.println("Boltzman Normation created major error (no const)!"); for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; + result[i] = 1 / result.length; } } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i]); } } } @@ -228,28 +233,37 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is the Boltzman Normation."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Boltzman Normation"; } - /** This method will allow you to set and get the Q Parameter + /** + * This method will allow you to set and get the Q Parameter + * * @return The new selection pressure q. */ public double getQ() { return this.m_Q; } - public void setQ(double b){ + + public void setQ(double b) { this.m_Q = Math.abs(b); } + public String qTipText() { return "The selection pressure. The bigger q, the higher the selection pressure."; } diff --git a/src/eva2/optimization/operator/selection/probability/SelProbFitnessSharing.java b/src/eva2/optimization/operator/selection/probability/SelProbFitnessSharing.java index 67a8ba5e..8703d0bf 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbFitnessSharing.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbFitnessSharing.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric; import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.population.Population; -/** Here we have the infamous fitness sharing method. +/** + * Here we have the infamous fitness sharing method. * Created by IntelliJ IDEA. * User: streiche * Date: 15.06.2005 @@ -14,19 +15,19 @@ import eva2.optimization.population.Population; */ public class SelProbFitnessSharing extends AbstractSelProb implements java.io.Serializable { - private InterfaceSelectionProbability m_BasicNormationMethod = new SelProbStandard(); - private InterfaceDistanceMetric m_DistanceMetric = new PhenotypeMetric(); - private double m_SharingDistance = 0.1; + private InterfaceSelectionProbability m_BasicNormationMethod = new SelProbStandard(); + private InterfaceDistanceMetric m_DistanceMetric = new PhenotypeMetric(); + private double m_SharingDistance = 0.1; public SelProbFitnessSharing() { } public SelProbFitnessSharing(SelProbFitnessSharing a) { if (a.m_BasicNormationMethod != null) { - this.m_BasicNormationMethod = (InterfaceSelectionProbability)a.m_BasicNormationMethod.clone(); + this.m_BasicNormationMethod = (InterfaceSelectionProbability) a.m_BasicNormationMethod.clone(); } if (a.m_DistanceMetric != null) { - this.m_DistanceMetric = (InterfaceDistanceMetric)a.m_DistanceMetric; + this.m_DistanceMetric = (InterfaceDistanceMetric) a.m_DistanceMetric; } this.m_SharingDistance = a.m_SharingDistance; } @@ -36,95 +37,114 @@ public class SelProbFitnessSharing extends AbstractSelProb implements java.io.Se return (Object) new SelProbFitnessSharing(this); } - /** This method computes the selection probability for each individual - * in the population. Note: Summed over the complete population the selection - * probability sums up to one. Keep in mind that fitness is always to be - * minimizied! Small values for data => big values for selectionprob. - * @param population The population to compute. - * @param data The input data as double[][]. + /** + * This method computes the selection probability for each individual + * in the population. Note: Summed over the complete population the selection + * probability sums up to one. Keep in mind that fitness is always to be + * minimizied! Small values for data => big values for selectionprob. + * + * @param population The population to compute. + * @param data The input data as double[][]. */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { this.m_BasicNormationMethod.computeSelectionProbability(population, data, obeyConst); // now perform fitness sharing double[] selProb = new double[population.size()]; - double distance, sharing, sum = 0; + double distance, sharing, sum = 0; AbstractEAIndividual tmpIndy1, tmpIndy2; for (int i = 0; i < population.size(); i++) { - tmpIndy1 = ((AbstractEAIndividual)population.get(i)); - selProb[i] = tmpIndy1.getSelectionProbability()[0]; - sharing = 0; + tmpIndy1 = ((AbstractEAIndividual) population.get(i)); + selProb[i] = tmpIndy1.getSelectionProbability()[0]; + sharing = 0; for (int j = 0; j < population.size(); j++) { if (i != j) { - distance = this.m_DistanceMetric.distance(tmpIndy1, ((AbstractEAIndividual)population.get(i))); + distance = this.m_DistanceMetric.distance(tmpIndy1, ((AbstractEAIndividual) population.get(i))); if (distance < this.m_SharingDistance) { - sharing += (1 - distance/this.m_SharingDistance); + sharing += (1 - distance / this.m_SharingDistance); } } } - selProb[i] /= (1+sharing); + selProb[i] /= (1 + sharing); sum += selProb[i]; } for (int i = 0; i < population.size(); i++) { - tmpIndy1 = ((AbstractEAIndividual)population.get(i)); - tmpIndy1.SetSelectionProbability(0, (selProb[i]/sum)); + tmpIndy1 = ((AbstractEAIndividual) population.get(i)); + tmpIndy1.SetSelectionProbability(0, (selProb[i] / sum)); } } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a fitness sharing based normation method."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Fitness Sharing"; } - /** This method will allow you to set and get the Q Parameter + /** + * This method will allow you to set and get the Q Parameter + * * @return The new selection pressure q. */ public InterfaceSelectionProbability getBasicNormationMethod() { return this.m_BasicNormationMethod; } - public void setBasicNormationMethod(InterfaceSelectionProbability b){ + + public void setBasicNormationMethod(InterfaceSelectionProbability b) { this.m_BasicNormationMethod = b; } + public String basicNormationMethodTipText() { return "Choose the basic normation method."; } - /** This method will allow you to set and get the Q Parameter + /** + * This method will allow you to set and get the Q Parameter + * * @return The new selection pressure q. */ public InterfaceDistanceMetric getDistanceMetric() { return this.m_DistanceMetric; } - public void setDistanceMetric(InterfaceDistanceMetric b){ + + public void setDistanceMetric(InterfaceDistanceMetric b) { this.m_DistanceMetric = b; } + public String distanceMetricTipText() { return "Select the distance metric to use."; } - /** This method will allow you to set and get the Q Parameter + /** + * This method will allow you to set and get the Q Parameter + * * @return The new selection pressure q. */ public double getSharingDistance() { return this.m_SharingDistance; } - public void setSharingDistance(double b){ + + public void setSharingDistance(double b) { if (b < 0.000001) { b = 0.000001; } this.m_SharingDistance = b; } + public String sharingDistanceTipText() { return "Choose the sharing distance to use."; } diff --git a/src/eva2/optimization/operator/selection/probability/SelProbInvertByMax.java b/src/eva2/optimization/operator/selection/probability/SelProbInvertByMax.java index e36d26f9..29df2129 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbInvertByMax.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbInvertByMax.java @@ -9,117 +9,126 @@ import eva2.optimization.population.Population; * selection probability of zero. * * @author mkron - * - * May 2, 2007 - * + *

+ * May 2, 2007 */ public class SelProbInvertByMax extends AbstractSelProb { - private double maxFit = 1.; + private double maxFit = 1.; - public SelProbInvertByMax() { - } + public SelProbInvertByMax() { + } - public SelProbInvertByMax(double mF) { - maxFit = mF; - } + public SelProbInvertByMax(double mF) { + maxFit = mF; + } - public SelProbInvertByMax(SelProbInvertByMax a) { - this.maxFit = a.maxFit; - } + public SelProbInvertByMax(SelProbInvertByMax a) { + this.maxFit = a.maxFit; + } @Override - public Object clone() { - return (Object) new SelProbInvertByMax(this); - } + public Object clone() { + return (Object) new SelProbInvertByMax(this); + } - /** This method computes the selection probability for each individual - * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input data as double[][]. - */ + /** + * This method computes the selection probability for each individual + * in the population. Note: Summed over the complete population the selection + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input data as double[][]. + */ @Override - public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double sum = 0; - double[] result = new double[data.length]; - boolean isFeasible = false; - - if (obeyConst) { - // first check if anyone holds the constraints - int k=0; - while ((k < population.size()) && !isFeasible) { - if (!(population.getEAIndividual(k)).violatesConstraint()) { - isFeasible = true; - } - k++; - } - } - if (isFeasible || !obeyConst) { - // at least one is feasible - // iterating over the fitness cases - for (int x = 0; x < data[0].length; x++) { - sum = 0; - // invert fitness - for (int i = 0; i < data.length; i++) { - if (population.getEAIndividual(i).violatesConstraint()) { - result[i]=0; - } - else { - result[i] = maxFit - data[i][x]; - } - sum += result[i]; - } + public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { + double sum = 0; + double[] result = new double[data.length]; + boolean isFeasible = false; - for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]/sum); - } - } - } else { - // not one is feasible therefore select the best regarding feasibility - System.err.println("warning, using standard probability for selection"); - sum = 0; - // iterating over the individuals - for (int i = 0; i < data.length; i++) { - result[i] = Math.exp(-((AbstractEAIndividual)population.get(i)).getConstraintViolation()); + if (obeyConst) { + // first check if anyone holds the constraints + int k = 0; + while ((k < population.size()) && !isFeasible) { + if (!(population.getEAIndividual(k)).violatesConstraint()) { + isFeasible = true; + } + k++; + } + } + if (isFeasible || !obeyConst) { + // at least one is feasible + // iterating over the fitness cases + for (int x = 0; x < data[0].length; x++) { + sum = 0; + // invert fitness + for (int i = 0; i < data.length; i++) { + if (population.getEAIndividual(i).violatesConstraint()) { + result[i] = 0; + } else { + result[i] = maxFit - data[i][x]; } - for (int i = 0; i < data.length; i++) { - sum += result[i]; - } - for (int i = 0; i < population.size(); i++) { - double[] tmpD = new double[1]; - tmpD[0] = result[i]/sum; - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(tmpD); - } - } - } + sum += result[i]; + } - /********************************************************************************************************************** - * These are for GUI - */ - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "This is a standard normation method inverted by maximum fitness."; - } - /** This method will return a naming String - * @return The name of the algorithm - */ - public String getName() { - return "Inverted Maximum Fitness Normation"; - } + for (int i = 0; i < population.size(); i++) { + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); + } + } + } else { + // not one is feasible therefore select the best regarding feasibility + System.err.println("warning, using standard probability for selection"); + sum = 0; + // iterating over the individuals + for (int i = 0; i < data.length; i++) { + result[i] = Math.exp(-((AbstractEAIndividual) population.get(i)).getConstraintViolation()); + } + for (int i = 0; i < data.length; i++) { + sum += result[i]; + } + for (int i = 0; i < population.size(); i++) { + double[] tmpD = new double[1]; + tmpD[0] = result[i] / sum; + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(tmpD); + } + } + } - /** This method will allow you to set and get the Q Parameter - * @return The new selection pressure q. - */ - public double getMaxFit() { - return this.maxFit; - } - public void setMaxFit(double b){ - this.maxFit = Math.abs(b); - } - public String maxFitTipText() { - return "The maximum fitness value by which to invert"; - } + /********************************************************************************************************************** + * These are for GUI + */ + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "This is a standard normation method inverted by maximum fitness."; + } + + /** + * This method will return a naming String + * + * @return The name of the algorithm + */ + public String getName() { + return "Inverted Maximum Fitness Normation"; + } + + /** + * This method will allow you to set and get the Q Parameter + * + * @return The new selection pressure q. + */ + public double getMaxFit() { + return this.maxFit; + } + + public void setMaxFit(double b) { + this.maxFit = Math.abs(b); + } + + public String maxFitTipText() { + return "The maximum fitness value by which to invert"; + } } diff --git a/src/eva2/optimization/operator/selection/probability/SelProbLinearRanking.java b/src/eva2/optimization/operator/selection/probability/SelProbLinearRanking.java index d80a6e89..cf50d0ba 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbLinearRanking.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbLinearRanking.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** A linear ranking method with offsets. +/** + * A linear ranking method with offsets. * Created by IntelliJ IDEA. * User: streiche * Date: 11.06.2004 @@ -12,14 +13,14 @@ import eva2.optimization.population.Population; */ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Serializable { - private double nappaPlus = 1.1; - private double nappaMinus = 0.9; + private double nappaPlus = 1.1; + private double nappaMinus = 0.9; public SelProbLinearRanking() { } public SelProbLinearRanking(SelProbLinearRanking a) { - this.nappaPlus = a.nappaPlus; + this.nappaPlus = a.nappaPlus; this.nappaMinus = a.nappaMinus; } @@ -28,23 +29,25 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser return (Object) new SelProbLinearRanking(this); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input as double[][] + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input as double[][] */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double temp; - double[] result = new double[data.length]; - int tempI, size = population.size(); + double temp; + double[] result = new double[data.length]; + int tempI, size = population.size(); if (obeyConst) { // first check if anyone holds the constraints boolean isFeasible = false; for (int i = 0; i < population.size(); i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { isFeasible = true; } } @@ -58,112 +61,112 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser worst = data[i][x]; } } - int[] rank_index = new int[data.length]; - double[] fitness = new double[data.length]; + int[] rank_index = new int[data.length]; + double[] fitness = new double[data.length]; for (int i = 0; i < result.length; i++) { result[i] = 0; } for (int i = 0; i < data.length; i++) { - if (!(((AbstractEAIndividual)population.get(i)).violatesConstraint())) { - fitness[i] = data[i][x]; + if (!(((AbstractEAIndividual) population.get(i)).violatesConstraint())) { + fitness[i] = data[i][x]; } else { - fitness[i] = worst; + fitness[i] = worst; } - rank_index[i] = i; + rank_index[i] = i; } //rank sorting for (int index = 0; index < fitness.length; index++) { int min = index; - for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) { + for (int i = index; i < fitness.length; i++) { + if (fitness[min] > fitness[i]) { min = i; } } - if(fitness[index] != fitness[min]) { - temp = fitness[index]; - fitness[index] = fitness[min]; - fitness[min] = temp; - tempI = rank_index[index]; - rank_index[index] = rank_index[min]; - rank_index[min] = tempI; + if (fitness[index] != fitness[min]) { + temp = fitness[index]; + fitness[index] = fitness[min]; + fitness[min] = temp; + tempI = rank_index[index]; + rank_index[index] = rank_index[min]; + rank_index[min] = tempI; } } // set the selection propability for (int i = 0; i < data.length; i++) { - temp = (1/(double)size) * (this.nappaPlus - ((this.nappaPlus - this.nappaMinus)*((double)(i)/(double)(size-1)))); - ((AbstractEAIndividual)population.get(rank_index[i])).SetSelectionProbability(x, temp); + temp = (1 / (double) size) * (this.nappaPlus - ((this.nappaPlus - this.nappaMinus) * ((double) (i) / (double) (size - 1)))); + ((AbstractEAIndividual) population.get(rank_index[i])).SetSelectionProbability(x, temp); } } } else { // not one is feasible therefore select the best regarding feasibility - int[] rank_index = new int[data.length]; - double[] fitness = new double[data.length]; + int[] rank_index = new int[data.length]; + double[] fitness = new double[data.length]; for (int i = 0; i < result.length; i++) { result[i] = 0; } for (int i = 0; i < data.length; i++) { - fitness[i] = -((AbstractEAIndividual)population.get(i)).getConstraintViolation(); - rank_index[i] = i; + fitness[i] = -((AbstractEAIndividual) population.get(i)).getConstraintViolation(); + rank_index[i] = i; } //rank sorting for (int index = 0; index < fitness.length; index++) { int min = index; - for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) { + for (int i = index; i < fitness.length; i++) { + if (fitness[min] > fitness[i]) { min = i; } } - if(fitness[index] != fitness[min]) { - temp = fitness[index]; - fitness[index] = fitness[min]; - fitness[min] = temp; - tempI = rank_index[index]; - rank_index[index] = rank_index[min]; - rank_index[min] = tempI; + if (fitness[index] != fitness[min]) { + temp = fitness[index]; + fitness[index] = fitness[min]; + fitness[min] = temp; + tempI = rank_index[index]; + rank_index[index] = rank_index[min]; + rank_index[min] = tempI; } } // set the selection propability for (int i = 0; i < data.length; i++) { - double[] tmpD = new double[1]; - tmpD[0] = (1/(double)size) * (this.nappaPlus - ((this.nappaPlus - this.nappaMinus)*((double)(i)/(double)(size-1)))); - ((AbstractEAIndividual)population.get(rank_index[i])).SetSelectionProbability(tmpD); + double[] tmpD = new double[1]; + tmpD[0] = (1 / (double) size) * (this.nappaPlus - ((this.nappaPlus - this.nappaMinus) * ((double) (i) / (double) (size - 1)))); + ((AbstractEAIndividual) population.get(rank_index[i])).SetSelectionProbability(tmpD); } } } else { for (int x = 0; x < data[0].length; x++) { - int[] rank_index = new int[data.length]; - double[] fitness = new double[data.length]; + int[] rank_index = new int[data.length]; + double[] fitness = new double[data.length]; for (int i = 0; i < result.length; i++) { result[i] = 0; } for (int i = 0; i < data.length; i++) { - fitness[i] = data[i][x]; - rank_index[i] = i; + fitness[i] = data[i][x]; + rank_index[i] = i; } //rank sorting for (int index = 0; index < fitness.length; index++) { int min = index; - for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) { + for (int i = index; i < fitness.length; i++) { + if (fitness[min] > fitness[i]) { min = i; } } - if(fitness[index] != fitness[min]) { - temp = fitness[index]; - fitness[index] = fitness[min]; - fitness[min] = temp; - tempI = rank_index[index]; - rank_index[index] = rank_index[min]; - rank_index[min] = tempI; + if (fitness[index] != fitness[min]) { + temp = fitness[index]; + fitness[index] = fitness[min]; + fitness[min] = temp; + tempI = rank_index[index]; + rank_index[index] = rank_index[min]; + rank_index[min] = tempI; } } // set the selection propability for (int i = 0; i < data.length; i++) { - temp = (1/(double)size) * (this.nappaPlus - ((this.nappaPlus - this.nappaMinus)*((double)(i)/(double)(size-1)))); - ((AbstractEAIndividual)population.get(rank_index[i])).SetSelectionProbability(x, temp); + temp = (1 / (double) size) * (this.nappaPlus - ((this.nappaPlus - this.nappaMinus) * ((double) (i) / (double) (size - 1)))); + ((AbstractEAIndividual) population.get(rank_index[i])).SetSelectionProbability(x, temp); } } } @@ -171,21 +174,28 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is linear ranking normation."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Linear Ranking"; } - /** This methods allow you to set and get the nappa. - * @param x Long seed. + /** + * This methods allow you to set and get the nappa. + * + * @param x Long seed. */ public void setNappa(double x) { if (x < 1) { @@ -197,9 +207,11 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser nappaPlus = x; this.nappaMinus = 2 - this.nappaPlus; } + public double getNappa() { return nappaPlus; } + public String nappaTipText() { return "The etha variable in lin. ranking (1<= etha <= 2)."; } diff --git a/src/eva2/optimization/operator/selection/probability/SelProbNonLinearRanking.java b/src/eva2/optimization/operator/selection/probability/SelProbNonLinearRanking.java index 1cf48c78..60b904fe 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbNonLinearRanking.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbNonLinearRanking.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** A non-linear ranking, which is difficult to tune to +/** + * A non-linear ranking, which is difficult to tune to * the given optimization problem i guess. * Created by IntelliJ IDEA. * User: streiche @@ -13,17 +14,17 @@ import eva2.optimization.population.Population; */ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io.Serializable { - private double m_C = 0.04; + private double m_C = 0.04; public SelProbNonLinearRanking() { } public SelProbNonLinearRanking(double theC) { - this.m_C = theC; + this.m_C = theC; } - + public SelProbNonLinearRanking(SelProbNonLinearRanking a) { - this.m_C = a.m_C; + this.m_C = a.m_C; } @Override @@ -31,23 +32,25 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. return (Object) new SelProbNonLinearRanking(this); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input as double[][] + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input as double[][] */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double temp, sum; - double[] result = new double[data.length]; - int tempI, size = population.size(); + double temp, sum; + double[] result = new double[data.length]; + int tempI, size = population.size(); if (obeyConst) { // first check if anyone holds the constraints boolean isFeasible = false; for (int i = 0; i < population.size(); i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { isFeasible = true; } } @@ -61,125 +64,125 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. worst = data[i][x]; } } - int[] rank_index = new int[data.length]; - double[] fitness = new double[data.length]; + int[] rank_index = new int[data.length]; + double[] fitness = new double[data.length]; for (int i = 0; i < result.length; i++) { result[i] = 0; } for (int i = 0; i < data.length; i++) { - if (!(((AbstractEAIndividual)population.get(i)).violatesConstraint())) { - fitness[i] = data[i][x]; + if (!(((AbstractEAIndividual) population.get(i)).violatesConstraint())) { + fitness[i] = data[i][x]; } else { - fitness[i] = worst; + fitness[i] = worst; } - rank_index[i] = i; + rank_index[i] = i; } //rank sorting for (int index = 0; index < fitness.length; index++) { int min = index; - for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) { + for (int i = index; i < fitness.length; i++) { + if (fitness[min] > fitness[i]) { min = i; } } - if(fitness[index] != fitness[min]) { - temp = fitness[index]; - fitness[index] = fitness[min]; - fitness[min] = temp; - tempI = rank_index[index]; - rank_index[index] = rank_index[min]; - rank_index[min] = tempI; + if (fitness[index] != fitness[min]) { + temp = fitness[index]; + fitness[index] = fitness[min]; + fitness[min] = temp; + tempI = rank_index[index]; + rank_index[index] = rank_index[min]; + rank_index[min] = tempI; } } // set the selection propability sum = 0; for (int i = 0; i < data.length; i++) { - result[i] = this.m_C * Math.pow(1-this.m_C, i); + result[i] = this.m_C * Math.pow(1 - this.m_C, i); sum += result[i]; } for (int i = 0; i < data.length; i++) { - ((AbstractEAIndividual)population.get(rank_index[i])).SetSelectionProbability(x, result[i]/sum); + ((AbstractEAIndividual) population.get(rank_index[i])).SetSelectionProbability(x, result[i] / sum); } } } else { // not one is feasible therefore select the best regarding feasibility - int[] rank_index = new int[data.length]; - double[] fitness = new double[data.length]; + int[] rank_index = new int[data.length]; + double[] fitness = new double[data.length]; for (int i = 0; i < result.length; i++) { result[i] = 0; } for (int i = 0; i < data.length; i++) { - fitness[i] = -((AbstractEAIndividual)population.get(i)).getConstraintViolation(); - rank_index[i] = i; + fitness[i] = -((AbstractEAIndividual) population.get(i)).getConstraintViolation(); + rank_index[i] = i; } //rank sorting for (int index = 0; index < fitness.length; index++) { int min = index; - for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) { + for (int i = index; i < fitness.length; i++) { + if (fitness[min] > fitness[i]) { min = i; } } - if(fitness[index] != fitness[min]) { - temp = fitness[index]; - fitness[index] = fitness[min]; - fitness[min] = temp; - tempI = rank_index[index]; - rank_index[index] = rank_index[min]; - rank_index[min] = tempI; + if (fitness[index] != fitness[min]) { + temp = fitness[index]; + fitness[index] = fitness[min]; + fitness[min] = temp; + tempI = rank_index[index]; + rank_index[index] = rank_index[min]; + rank_index[min] = tempI; } } // set the selection propability sum = 0; for (int i = 0; i < data.length; i++) { - result[i] = this.m_C * Math.pow(1-this.m_C, i); + result[i] = this.m_C * Math.pow(1 - this.m_C, i); sum += result[i]; } for (int i = 0; i < data.length; i++) { - double[] tmpD = new double[1]; - tmpD[0] = result[i]/sum; - ((AbstractEAIndividual)population.get(rank_index[i])).SetSelectionProbability(tmpD); + double[] tmpD = new double[1]; + tmpD[0] = result[i] / sum; + ((AbstractEAIndividual) population.get(rank_index[i])).SetSelectionProbability(tmpD); } } } else { for (int x = 0; x < data[0].length; x++) { - int[] rank_index = new int[data.length]; - double[] fitness = new double[data.length]; + int[] rank_index = new int[data.length]; + double[] fitness = new double[data.length]; for (int i = 0; i < result.length; i++) { result[i] = 0; } for (int i = 0; i < data.length; i++) { - fitness[i] = data[i][x]; - rank_index[i] = i; + fitness[i] = data[i][x]; + rank_index[i] = i; } //rank sorting for (int index = 0; index < fitness.length; index++) { int min = index; - for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) { + for (int i = index; i < fitness.length; i++) { + if (fitness[min] > fitness[i]) { min = i; } } - if(fitness[index] != fitness[min]) { - temp = fitness[index]; - fitness[index] = fitness[min]; - fitness[min] = temp; - tempI = rank_index[index]; - rank_index[index] = rank_index[min]; - rank_index[min] = tempI; + if (fitness[index] != fitness[min]) { + temp = fitness[index]; + fitness[index] = fitness[min]; + fitness[min] = temp; + tempI = rank_index[index]; + rank_index[index] = rank_index[min]; + rank_index[min] = tempI; } } // set the selection propability sum = 0; for (int i = 0; i < data.length; i++) { - result[i] = this.m_C * Math.pow(1-this.m_C, i); + result[i] = this.m_C * Math.pow(1 - this.m_C, i); sum += result[i]; } for (int i = 0; i < data.length; i++) { - ((AbstractEAIndividual)population.get(rank_index[i])).SetSelectionProbability(x, result[i]/sum); + ((AbstractEAIndividual) population.get(rank_index[i])).SetSelectionProbability(x, result[i] / sum); } } } @@ -187,21 +190,28 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is non-linear ranking normation."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Non-Linear Ranking"; } - /** This methods allow you to set and get the scaling. - * @param x Long seed. + /** + * This methods allow you to set and get the scaling. + * + * @param x Long seed. */ public void setC(double x) { if (x < 0) { @@ -212,9 +222,11 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. } this.m_C = x; } + public double getC() { return m_C; } + public String cTipText() { return "The exponential base c is taken to the power of the individual's rank and should be << 1."; } diff --git a/src/eva2/optimization/operator/selection/probability/SelProbRanking.java b/src/eva2/optimization/operator/selection/probability/SelProbRanking.java index 790fedbc..d37dbbf3 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbRanking.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbRanking.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** Ranking for calculating the selection probability. +/** + * Ranking for calculating the selection probability. * This truly scaling invariant. * Created by IntelliJ IDEA. * User: streiche @@ -24,16 +25,18 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa return (Object) new SelProbRanking(this); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input as double[][] + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input as double[][] */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double sum = 0; - double[] result = new double[data.length]; + double sum = 0; + double[] result = new double[data.length]; if (obeyConst) { for (int x = 0; x < data[0].length; x++) { @@ -46,17 +49,16 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa } for (int i = 0; i < data.length; i++) { for (int j = i + 1; j < data.length; j++) { - if (!(((AbstractEAIndividual)population.get(i)).violatesConstraint()) && (!((AbstractEAIndividual)population.get(j)).violatesConstraint())) { + if (!(((AbstractEAIndividual) population.get(i)).violatesConstraint()) && (!((AbstractEAIndividual) population.get(j)).violatesConstraint())) { // no one violates, therefore it is up to the data to decied if (data[j][x] < data[i][x]) { result[i]++; - } - else { + } else { result[j]++; } } else { // at least one violates, so the constraint violation is to decide - if (((AbstractEAIndividual)population.get(j)).getConstraintViolation() < ((AbstractEAIndividual)population.get(i)).getConstraintViolation()) { + if (((AbstractEAIndividual) population.get(j)).getConstraintViolation() < ((AbstractEAIndividual) population.get(i)).getConstraintViolation()) { result[j]++; } else { result[i]++; @@ -70,7 +72,7 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i] /sum); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); } } } else { @@ -86,8 +88,7 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa for (int j = i + 1; j < data.length; j++) { if (data[j][x] < data[i][x]) { result[i]++; - } - else { + } else { result[j]++; } } @@ -98,7 +99,7 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i] /sum); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); } } } @@ -106,13 +107,18 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is ranking normation."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/probability/SelProbStandard.java b/src/eva2/optimization/operator/selection/probability/SelProbStandard.java index aaa785e5..f4e3bc69 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbStandard.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbStandard.java @@ -3,10 +3,11 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** A simple sum to calculate the selection probability. - * +/** + * A simple sum to calculate the selection probability. + *

* p(i is selected) = exp(-fitness(i))/sum_j(exp(-fitness(j))) - * + *

* Created by IntelliJ IDEA. * User: streiche * Date: 30.03.2004 @@ -26,25 +27,27 @@ public class SelProbStandard extends AbstractSelProb implements java.io.Serializ return (Object) new SelProbStandard(this); } - /** This method computes the selection probability for each individual - * in the population. Note: Summed over the complete population the selection - * probability sums up to one. Keep in mind that fitness is always to be - * minimizied! Small values for data => big values for selectionprob. - * @param population The population to compute. - * @param data The input data as double[][]. + /** + * This method computes the selection probability for each individual + * in the population. Note: Summed over the complete population the selection + * probability sums up to one. Keep in mind that fitness is always to be + * minimizied! Small values for data => big values for selectionprob. + * + * @param population The population to compute. + * @param data The input data as double[][]. */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double sum = 0; - double[] result = new double[data.length]; + double sum = 0; + double[] result = new double[data.length]; if (obeyConst) { // first check if anyone holds the constraints boolean isFeasible = false; for (int i = 0; i < population.size(); i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { - isFeasible = true; - break; + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { + isFeasible = true; + break; } } if (isFeasible) { @@ -54,16 +57,15 @@ public class SelProbStandard extends AbstractSelProb implements java.io.Serializ sum = 0; // iterating over the individuals for (int i = 0; i < data.length; i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { result[i] = Math.exp(-data[i][x]); - } - else { + } else { result[i] = 0; } sum += result[i]; } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]/sum); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); } } } else { @@ -71,15 +73,15 @@ public class SelProbStandard extends AbstractSelProb implements java.io.Serializ sum = 0; // iterating over the individuals for (int i = 0; i < data.length; i++) { - result[i] = Math.exp(-((AbstractEAIndividual)population.get(i)).getConstraintViolation()); + result[i] = Math.exp(-((AbstractEAIndividual) population.get(i)).getConstraintViolation()); } for (int i = 0; i < data.length; i++) { sum += result[i]; } for (int i = 0; i < population.size(); i++) { double[] tmpD = new double[1]; - tmpD[0] = result[i]/sum; - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(tmpD); + tmpD[0] = result[i] / sum; + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(tmpD); } } } else { @@ -94,7 +96,7 @@ public class SelProbStandard extends AbstractSelProb implements java.io.Serializ sum += result[i]; } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]/sum); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); } } } @@ -103,13 +105,18 @@ public class SelProbStandard extends AbstractSelProb implements java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a standard normation method using the exp function."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/probability/SelProbStandardScaling.java b/src/eva2/optimization/operator/selection/probability/SelProbStandardScaling.java index 284fed26..06535496 100644 --- a/src/eva2/optimization/operator/selection/probability/SelProbStandardScaling.java +++ b/src/eva2/optimization/operator/selection/probability/SelProbStandardScaling.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.probability; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** A simple sum with a scaling factor. +/** + * A simple sum with a scaling factor. * Created by IntelliJ IDEA. * User: streiche * Date: 30.03.2004 @@ -12,17 +13,17 @@ import eva2.optimization.population.Population; */ public class SelProbStandardScaling extends AbstractSelProb implements java.io.Serializable { - private double m_Q = 0; + private double m_Q = 0; public SelProbStandardScaling() { } public SelProbStandardScaling(double q) { - m_Q = q; + m_Q = q; } - + public SelProbStandardScaling(SelProbStandardScaling a) { - this.m_Q = a.m_Q; + this.m_Q = a.m_Q; } @Override @@ -30,23 +31,25 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S return (Object) new SelProbStandardScaling(this); } - /** This method computes the selection probability for each individual + /** + * This method computes the selection probability for each individual * in the population. Note: Summed over the complete population the selection - * probability sums up to one. - * @param population The population to compute. - * @param data The input data as double[][]. + * probability sums up to one. + * + * @param population The population to compute. + * @param data The input data as double[][]. */ @Override public void computeSelectionProbability(Population population, double[][] data, boolean obeyConst) { - double sum = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY, delta; - double[] result = new double[data.length]; + double sum = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY, delta; + double[] result = new double[data.length]; if (obeyConst) { // first check if anyone holds the constraints boolean isFeasible = false; - int k=0; + int k = 0; while ((k < population.size()) && !isFeasible) { - if (!((AbstractEAIndividual)population.get(k)).violatesConstraint()) { + if (!((AbstractEAIndividual) population.get(k)).violatesConstraint()) { isFeasible = true; } k++; @@ -65,10 +68,9 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S } } for (int i = 0; i < data.length; i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + if (!((AbstractEAIndividual) population.get(i)).violatesConstraint()) { result[i] = -data[i][x]; - } - else { + } else { result[i] = -worst; } } @@ -81,19 +83,18 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S } } if (max != min) { - delta = max -min; - } - else { + delta = max - min; + } else { delta = 1; } for (int i = 0; i < data.length; i++) { - result[i] = ((result[i] - min)/delta) + this.m_Q; + result[i] = ((result[i] - min) / delta) + this.m_Q; sum += result[i]; } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]/sum); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); } } } else { @@ -101,7 +102,7 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S sum = 0; min = Double.POSITIVE_INFINITY; for (int i = 0; i < data.length; i++) { - result[i] = -((AbstractEAIndividual)population.get(i)).getConstraintViolation(); + result[i] = -((AbstractEAIndividual) population.get(i)).getConstraintViolation(); } for (int i = 0; i < data.length; i++) { if (result[i] < min) { @@ -113,19 +114,18 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S } if (max != min) { delta = max - min; - } - else { + } else { delta = 1; } for (int i = 0; i < data.length; i++) { - result[i] = ((result[i] - min)/delta) + this.m_Q; + result[i] = ((result[i] - min) / delta) + this.m_Q; sum += result[i]; } for (int i = 0; i < population.size(); i++) { double[] tmpD = new double[1]; - tmpD[0] = result[i]/sum; - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(tmpD); + tmpD[0] = result[i] / sum; + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(tmpD); } } } else { @@ -144,19 +144,18 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S } } if (max != min) { - delta = max -min; - } - else { + delta = max - min; + } else { delta = 1; } for (int i = 0; i < data.length; i++) { - result[i] = ((result[i] - min)/delta) + this.m_Q; + result[i] = ((result[i] - min) / delta) + this.m_Q; sum += result[i]; } for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetSelectionProbability(x, result[i]/sum); + ((AbstractEAIndividual) population.get(i)).SetSelectionProbability(x, result[i] / sum); } } } @@ -165,28 +164,37 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a standard normation method with scaling."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Scaled Normation"; } - /** This method will allow you to set and get the Q Parameter + /** + * This method will allow you to set and get the Q Parameter + * * @return The new selection pressure q. */ public double getQ() { return this.m_Q; } - public void setQ(double b){ + + public void setQ(double b) { this.m_Q = Math.abs(b); } + public String qTipText() { return "The selection pressure. The bigger q, the higher the selection pressure."; } diff --git a/src/eva2/optimization/operator/selection/replacement/InterfaceReplacement.java b/src/eva2/optimization/operator/selection/replacement/InterfaceReplacement.java index 79b26d97..c359a7bc 100644 --- a/src/eva2/optimization/operator/selection/replacement/InterfaceReplacement.java +++ b/src/eva2/optimization/operator/selection/replacement/InterfaceReplacement.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.replacement; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** Replacement schemes for the steady-state GA. +/** + * Replacement schemes for the steady-state GA. * Created by IntelliJ IDEA. * User: streiche * Date: 19.07.2005 @@ -12,16 +13,19 @@ import eva2.optimization.population.Population; */ public interface InterfaceReplacement { - /** The ever present clone method + /** + * The ever present clone method */ - public Object clone(); + public Object clone(); - /** This method will insert the given individual into the population + /** + * This method will insert the given individual into the population * by replacing a individual either from the population or the given * subset - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub); } diff --git a/src/eva2/optimization/operator/selection/replacement/ReplaceDeterministicCrowding.java b/src/eva2/optimization/operator/selection/replacement/ReplaceDeterministicCrowding.java index 49cd3429..490e6943 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplaceDeterministicCrowding.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplaceDeterministicCrowding.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.population.Population; -/** The deterministic crowiding method replaces the most similar parent if better +/** + * The deterministic crowiding method replaces the most similar parent if better * Created by IntelliJ IDEA. * User: streiche * Date: 19.07.2005 @@ -15,20 +16,21 @@ public class ReplaceDeterministicCrowding implements InterfaceReplacement, java. PhenotypeMetric metric = new PhenotypeMetric(); - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** + /** * Take the closest individual within the subset and remove it from pop. Add - * indy as a replacement. - * - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * indy as a replacement. + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @Override public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { @@ -37,14 +39,14 @@ public class ReplaceDeterministicCrowding implements InterfaceReplacement, java. double distance = Double.POSITIVE_INFINITY, tmpD; for (int i = 0; i < sub.size(); i++) { - tmpD = this.metric.distance(indy, (AbstractEAIndividual)sub.get(i)); + tmpD = this.metric.distance(indy, (AbstractEAIndividual) sub.get(i)); if (tmpD < distance) { - index = i; - distance = tmpD; + index = i; + distance = tmpD; } } - if (indy.isDominatingDebConstraints((AbstractEAIndividual)sub.get(index))) { - if (pop.remove((AbstractEAIndividual)sub.get(index))) { + if (indy.isDominatingDebConstraints((AbstractEAIndividual) sub.get(index))) { + if (pop.remove((AbstractEAIndividual) sub.get(index))) { pop.addIndividual(indy); } } @@ -52,13 +54,18 @@ public class ReplaceDeterministicCrowding implements InterfaceReplacement, java. /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method replaces the most similar parent if better."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/replacement/ReplacePreselection.java b/src/eva2/optimization/operator/selection/replacement/ReplacePreselection.java index 7033e610..199621f5 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplacePreselection.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplacePreselection.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.replacement; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** The preselection replacement scheme replaces the worst parent in case +/** + * The preselection replacement scheme replaces the worst parent in case * the offspring is better. * Created by IntelliJ IDEA. * User: streiche @@ -13,19 +14,22 @@ import eva2.optimization.population.Population; */ public class ReplacePreselection implements InterfaceReplacement, java.io.Serializable { - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** This method will insert the given individual into the population + /** + * This method will insert the given individual into the population * by replacing a individual either from the population or the given * subset - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @Override public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { @@ -37,13 +41,18 @@ public class ReplacePreselection implements InterfaceReplacement, java.io.Serial /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method replaces the worst parent if better."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/replacement/ReplaceRandom.java b/src/eva2/optimization/operator/selection/replacement/ReplaceRandom.java index 3956bd5e..8bab44da 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplaceRandom.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplaceRandom.java @@ -4,7 +4,8 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.tools.math.RNG; -/** Random replacement. +/** + * Random replacement. * Created by IntelliJ IDEA. * User: streiche * Date: 19.07.2005 @@ -13,36 +14,44 @@ import eva2.tools.math.RNG; */ public class ReplaceRandom implements InterfaceReplacement, java.io.Serializable { - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** This method will insert the given individual into the population + /** + * This method will insert the given individual into the population * by replacing a individual either from the population or the given * subset - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @Override public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { - int rand = RNG.randomInt(0, pop.size()-1); + int rand = RNG.randomInt(0, pop.size() - 1); pop.remove(rand); pop.addIndividual(indy); } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method replaces a random individual."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/replacement/ReplaceWorst.java b/src/eva2/optimization/operator/selection/replacement/ReplaceWorst.java index 94c23c59..67471b21 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplaceWorst.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplaceWorst.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.replacement; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** This method replaces the worst indvidual in the population. +/** + * This method replaces the worst indvidual in the population. * Created by IntelliJ IDEA. * User: streiche * Date: 19.07.2005 @@ -12,19 +13,22 @@ import eva2.optimization.population.Population; */ public class ReplaceWorst implements InterfaceReplacement, java.io.Serializable { - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** This method will insert the given individual into the population + /** + * This method will insert the given individual into the population * by replacing a individual either from the population or the given * subset - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @Override public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { @@ -36,13 +40,18 @@ public class ReplaceWorst implements InterfaceReplacement, java.io.Serializable /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method replaces the worst individual from the population."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/replacement/ReplaceWorstParent.java b/src/eva2/optimization/operator/selection/replacement/ReplaceWorstParent.java index 8a928652..77f9df31 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplaceWorstParent.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplaceWorstParent.java @@ -3,7 +3,8 @@ package eva2.optimization.operator.selection.replacement; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; -/** This method replaces the worst parent. Doesn't work, +/** + * This method replaces the worst parent. Doesn't work, * most likely it has the effect of a negative elitism. * Good selected parents are replaced by the offspring * regardless how bad it is... @@ -15,19 +16,22 @@ import eva2.optimization.population.Population; */ public class ReplaceWorstParent implements InterfaceReplacement, java.io.Serializable { - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** This method will insert the given individual into the population + /** + * This method will insert the given individual into the population * by replacing a individual either from the population or the given * subset - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @Override public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { @@ -44,13 +48,18 @@ public class ReplaceWorstParent implements InterfaceReplacement, java.io.Seriali /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method replaces the worst parent, if better."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { diff --git a/src/eva2/optimization/operator/selection/replacement/ReplacementCrowding.java b/src/eva2/optimization/operator/selection/replacement/ReplacementCrowding.java index 034df36b..f6175f8d 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplacementCrowding.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplacementCrowding.java @@ -5,7 +5,8 @@ import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.operator.selection.SelectRandom; import eva2.optimization.population.Population; -/** This crowding method replaces the most similar individual from a random group if better. +/** + * This crowding method replaces the most similar individual from a random group if better. * Created by IntelliJ IDEA. * User: streiche * Date: 19.07.2005 @@ -15,8 +16,8 @@ import eva2.optimization.population.Population; public class ReplacementCrowding implements InterfaceReplacement, java.io.Serializable { PhenotypeMetric metric = new PhenotypeMetric(); - SelectRandom random = new SelectRandom(); - int m_C = 5; + SelectRandom random = new SelectRandom(); + int m_C = 5; public ReplacementCrowding() { @@ -25,27 +26,28 @@ public class ReplacementCrowding implements InterfaceReplacement, java.io.Serial public ReplacementCrowding(ReplacementCrowding b) { this.metric = new PhenotypeMetric(); this.random = new SelectRandom(); - this.m_C = b.m_C; + this.m_C = b.m_C; } public ReplacementCrowding(int C) { - setC(C); + setC(C); } - - /** The ever present clone method + + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** - * From a random subset of size C, the closest is replaced by the given individual. + /** + * From a random subset of size C, the closest is replaced by the given individual. * The sub parameter is not regarded. - * - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @Override public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { @@ -54,14 +56,14 @@ public class ReplacementCrowding implements InterfaceReplacement, java.io.Serial double distance = Double.POSITIVE_INFINITY, tmpD; Population tmp = random.selectFrom(pop, this.m_C); for (int i = 0; i < tmp.size(); i++) { - tmpD = this.metric.distance(indy, (AbstractEAIndividual)tmp.get(i)); + tmpD = this.metric.distance(indy, (AbstractEAIndividual) tmp.get(i)); if (tmpD < distance) { - index = i; - distance = tmpD; + index = i; + distance = tmpD; } } - if (indy.isDominatingDebConstraints((AbstractEAIndividual)tmp.get(index))) { - if (pop.remove((AbstractEAIndividual)tmp.get(index))) { + if (indy.isDominatingDebConstraints((AbstractEAIndividual) tmp.get(index))) { + if (pop.remove((AbstractEAIndividual) tmp.get(index))) { pop.addIndividual(indy); } } @@ -69,27 +71,37 @@ public class ReplacementCrowding implements InterfaceReplacement, java.io.Serial /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This method replaces the most similar individual from a random group if better."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ public String getName() { return "Crowding"; } - /** This method will set c + + /** + * This method will set c + * * @param c */ public void setC(int c) { this.m_C = c; } + public int getC() { return this.m_C; } + public String cTipText() { return "Set the crwoding factor."; } diff --git a/src/eva2/optimization/operator/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java b/src/eva2/optimization/operator/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java index 03082069..029cd3ec 100644 --- a/src/eva2/optimization/operator/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java +++ b/src/eva2/optimization/operator/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java @@ -4,11 +4,13 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.operator.archiving.ArchivingNSGAII; import eva2.optimization.operator.selection.SelectRandom; import eva2.optimization.population.Population; + import java.util.Collections; import java.util.Comparator; -/** This crowding method replaces the most similar individual from a random group if better. +/** + * This crowding method replaces the most similar individual from a random group if better. * Created by IntelliJ IDEA. * User: streiche * Date: 19.07.2005 @@ -17,93 +19,98 @@ import java.util.Comparator; */ public class ReplacementNondominatedSortingDistanceCrowding implements InterfaceReplacement, java.io.Serializable { - public class HypervolumeComperator implements Comparator{ + public class HypervolumeComperator implements Comparator { @Override - public int compare(AbstractEAIndividual arg0, AbstractEAIndividual arg1) { - // TODO Auto-generated method stub - Double a0=(Double) arg0.getData("HyperCube"); - Double a1=(Double) arg1.getData("HyperCube"); - if(a0!=null&a1!=null){ - return a1.compareTo(a0); - }else { - return 0; - } - } - } - - ArchivingNSGAII dummyArchive=new ArchivingNSGAII(); - - SelectRandom random = new SelectRandom(); - + public int compare(AbstractEAIndividual arg0, AbstractEAIndividual arg1) { + // TODO Auto-generated method stub + Double a0 = (Double) arg0.getData("HyperCube"); + Double a1 = (Double) arg1.getData("HyperCube"); + if (a0 != null & a1 != null) { + return a1.compareTo(a0); + } else { + return 0; + } + } + } + + ArchivingNSGAII dummyArchive = new ArchivingNSGAII(); + + SelectRandom random = new SelectRandom(); + public ReplacementNondominatedSortingDistanceCrowding() { } public ReplacementNondominatedSortingDistanceCrowding(ReplacementNondominatedSortingDistanceCrowding b) { - this.dummyArchive=new ArchivingNSGAII(); + this.dummyArchive = new ArchivingNSGAII(); } - - /** The ever present clone method + /** + * The ever present clone method */ @Override public Object clone() { return new ReplaceRandom(); } - /** - * From a random subset of size C, the closest is replaced by the given individual. + /** + * From a random subset of size C, the closest is replaced by the given individual. * The sub parameter is not regarded. - * - * @param indy The individual to insert - * @param pop The population - * @param sub The subset + * + * @param indy The individual to insert + * @param pop The population + * @param sub The subset */ @SuppressWarnings("unchecked") @Override - public void insertIndividual(AbstractEAIndividual indy, Population pop, Population sub) { - - - pop.add(indy); - Population []store=dummyArchive.getNonDominatedSortedFronts(pop); - dummyArchive.calculateCrowdingDistance(store);//TODO die f�r das gesamte Archiv am St�ck berechnen und nicht f�r die Einzelfronten! - for(int i=0;i= haltingWindowLen) { - List subHist = ((Population)pop).getHistory().subList(histLen-haltingWindowLen, histLen); - if (stdDevInsteadOfImprovement) { // look at fitness std dev. - double[] fitMeas = Population.getFitnessMeasures(subHist, fitCrit); - res = (fitMeas[3] subHist = ((Population) pop).getHistory().subList(histLen - haltingWindowLen, histLen); + if (stdDevInsteadOfImprovement) { // look at fitness std dev. + double[] fitMeas = Population.getFitnessMeasures(subHist, fitCrit); + res = (fitMeas[3] < convergenceThreshold); + if (res) { + msg = "Historic fitness std.dev. below " + convergenceThreshold + " for " + histLen + " generations."; + } + } else { // look at improvements + AbstractEAIndividual historicHWAgo = subHist.get(0); // System.out.println("Ref indy: " + historicHWAgo); // System.out.println("Best historic: " + ((Population)pop).getBestHistoric()); - res = true; - for (int i = 1; i < haltingWindowLen; i++) { - // if historic[-hW] is worse than historic[-hW+i] return false - AbstractEAIndividual historicIter = subHist.get(i); - // if the iterated indy (the later one in history) has improved, there is no convergence. - boolean improvementHappened = (testSecondForImprovement(historicHWAgo, historicIter)); - if (improvementHappened) { - res = false; - break; - } - } - if (res) { - msg = "History did not improve" + (convergenceThreshold>0 ? (" by more than " + convergenceThreshold) : "") + " for " + haltingWindowLen + " iterations."; - } - } + res = true; + for (int i = 1; i < haltingWindowLen; i++) { + // if historic[-hW] is worse than historic[-hW+i] return false + AbstractEAIndividual historicIter = subHist.get(i); + // if the iterated indy (the later one in history) has improved, there is no convergence. + boolean improvementHappened = (testSecondForImprovement(historicHWAgo, historicIter)); + if (improvementHappened) { + res = false; + break; + } + } + if (res) { + msg = "History did not improve" + (convergenceThreshold > 0 ? (" by more than " + convergenceThreshold) : "") + " for " + haltingWindowLen + " iterations."; + } + } } else { - if (haltingWindowLen > ((Population)pop).getMaxHistLength()) { + if (haltingWindowLen > ((Population) pop).getMaxHistLength()) { System.err.println("Warning, population history length not long enough for window length " + haltingWindowLen + " (HistoryConvergenceTerminator)"); } } return res; - } + } - /** + /** * Define the criterion by which individual improvement is judged. The original version defined * improvement strictly, but for some EA this should be done more laxly. E.g. DE will hardly ever * stop improving slightly, so optionally use an epsilon-bound: improvement only counts if it is * larger than epsilon in case useEpsilonBound is true. - * + * * @param firstIndy * @param secIndy * @return true if the second individual has improved in relation to the first one */ private boolean testSecondForImprovement(AbstractEAIndividual firstIndy, AbstractEAIndividual secIndy) { - if (convergenceThreshold > 0) { - double fitDiff = (new ObjectiveSpaceMetric()).distance(firstIndy, secIndy); - boolean ret = (secIndy.isDominatingDebConstraints(firstIndy)); - ret = ret && (fitDiff > convergenceThreshold); // there is improvement if the second is dominant and the fitness difference is larger than epsilon - return ret; - } else { - return (indyImprovementComparator.compare(firstIndy, secIndy)>0); - } + if (convergenceThreshold > 0) { + double fitDiff = (new ObjectiveSpaceMetric()).distance(firstIndy, secIndy); + boolean ret = (secIndy.isDominatingDebConstraints(firstIndy)); + ret = ret && (fitDiff > convergenceThreshold); // there is improvement if the second is dominant and the fitness difference is larger than epsilon + return ret; + } else { + return (indyImprovementComparator.compare(firstIndy, secIndy) > 0); + } } - - @Override - public boolean isTerminated(InterfaceSolutionSet sols) { - return isTerminated(sols.getCurrentPopulation()); - } @Override - public String lastTerminationMessage() { - return msg; - } + public boolean isTerminated(InterfaceSolutionSet sols) { + return isTerminated(sols.getCurrentPopulation()); + } - public int getHaltingWindowLen() { - return haltingWindowLen; - } - public void setHaltingWindowLen(int haltingWindowLen) { - this.haltingWindowLen = haltingWindowLen; - } - public String haltingWindowLenTipText() { - return "Number of generations regarded back in the history"; - } + @Override + public String lastTerminationMessage() { + return msg; + } - public int getFitCrit() { - return fitCrit; - } - public void setFitCrit(int fitCrit) { - this.fitCrit = fitCrit; - } - public String fitCritTipText() { - return "The index of the fitness criterion regarded (multi-objective case)."; - } + public int getHaltingWindowLen() { + return haltingWindowLen; + } - public double getConvergenceThreshold() { - return convergenceThreshold; - } - public void setConvergenceThreshold(double convergenceThreshold) { - this.convergenceThreshold = convergenceThreshold; - } - public String convergenceThresholdTipText() { - return "Threshold below improvements (or deviations) are still seen as stagnation."; - } + public void setHaltingWindowLen(int haltingWindowLen) { + this.haltingWindowLen = haltingWindowLen; + } + + public String haltingWindowLenTipText() { + return "Number of generations regarded back in the history"; + } + + public int getFitCrit() { + return fitCrit; + } + + public void setFitCrit(int fitCrit) { + this.fitCrit = fitCrit; + } + + public String fitCritTipText() { + return "The index of the fitness criterion regarded (multi-objective case)."; + } + + public double getConvergenceThreshold() { + return convergenceThreshold; + } + + public void setConvergenceThreshold(double convergenceThreshold) { + this.convergenceThreshold = convergenceThreshold; + } + + public String convergenceThresholdTipText() { + return "Threshold below improvements (or deviations) are still seen as stagnation."; + } + + public boolean isStdDevInsteadOfImprovement() { + return stdDevInsteadOfImprovement; + } + + public void setStdDevInsteadOfImprovement(boolean stdDevInsteadOfImprovement) { + this.stdDevInsteadOfImprovement = stdDevInsteadOfImprovement; + } + + public String stdDevInsteadOfImprovementTipText() { + return "Look at the standard deviation of historic fitness values instead of absolute fitness."; + } - public boolean isStdDevInsteadOfImprovement() { - return stdDevInsteadOfImprovement; - } - public void setStdDevInsteadOfImprovement(boolean stdDevInsteadOfImprovement) { - this.stdDevInsteadOfImprovement = stdDevInsteadOfImprovement; - } - public String stdDevInsteadOfImprovementTipText() { - return "Look at the standard deviation of historic fitness values instead of absolute fitness."; - } - } diff --git a/src/eva2/optimization/operator/terminators/KnownOptimaFoundTerminator.java b/src/eva2/optimization/operator/terminators/KnownOptimaFoundTerminator.java index e6d0e1ea..169c3cd9 100644 --- a/src/eva2/optimization/operator/terminators/KnownOptimaFoundTerminator.java +++ b/src/eva2/optimization/operator/terminators/KnownOptimaFoundTerminator.java @@ -7,6 +7,7 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceMultimodalProblemKnown; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; + import java.io.Serializable; /** @@ -14,82 +15,81 @@ import java.io.Serializable; * implements InterfaceMultimodalProblemKnown. A population is regarded as terminated * if the preset number of optima is identified. * For any other problem types, this terminator will not make sense, so take care. - * - * @author mkron * + * @author mkron */ public class KnownOptimaFoundTerminator implements InterfaceTerminator, Serializable { - InterfaceMultimodalProblemKnown mProblem = null; - int reqOptima = 1; - private String msg = ""; - - public KnownOptimaFoundTerminator() { - } - + InterfaceMultimodalProblemKnown mProblem = null; + int reqOptima = 1; + private String msg = ""; + + public KnownOptimaFoundTerminator() { + } + @Override - public void init(InterfaceOptimizationProblem prob) { - if (prob != null) { - if (prob instanceof InterfaceMultimodalProblemKnown) { - mProblem = (InterfaceMultimodalProblemKnown)prob; - } else { - System.err.println("KnownOptimaFoundTerminator only works with InterfaceMultimodalProblemKnown instances!"); - } - } else { - System.err.println("KnownOptimaFoundTerminator wont work with null problem!"); + public void init(InterfaceOptimizationProblem prob) { + if (prob != null) { + if (prob instanceof InterfaceMultimodalProblemKnown) { + mProblem = (InterfaceMultimodalProblemKnown) prob; + } else { + System.err.println("KnownOptimaFoundTerminator only works with InterfaceMultimodalProblemKnown instances!"); } - msg = "Not terminated."; - } + } else { + System.err.println("KnownOptimaFoundTerminator wont work with null problem!"); + } + msg = "Not terminated."; + } @Override - public boolean isTerminated(InterfaceSolutionSet solSet) { - return isTerm(solSet.getSolutions()); - } - + public boolean isTerminated(InterfaceSolutionSet solSet) { + return isTerm(solSet.getSolutions()); + } + @Override - public boolean isTerminated(PopulationInterface pop) { - EVAERROR.errorMsgOnce("Warning, the KnownOptimaFoundTerminator is supposed to work on a final population."); - return isTerm((Population)pop); - } + public boolean isTerminated(PopulationInterface pop) { + EVAERROR.errorMsgOnce("Warning, the KnownOptimaFoundTerminator is supposed to work on a final population."); + return isTerm((Population) pop); + } + + private boolean isTerm(Population pop) { + int found = mProblem.getNumberOfFoundOptima(pop); + if (found >= reqOptima) { + msg = "There were " + reqOptima + " optima found."; + return true; + } else { + return false; + } + } - private boolean isTerm(Population pop) { - int found = mProblem.getNumberOfFoundOptima(pop); - if (found >= reqOptima) { - msg = "There were " + reqOptima + " optima found."; - return true; - } else { - return false; - } - } - @Override - public String lastTerminationMessage() { - return msg; - } + public String lastTerminationMessage() { + return msg; + } - /** - * @return the reqOptima - */ - public int getReqOptima() { - return reqOptima; - } + /** + * @return the reqOptima + */ + public int getReqOptima() { + return reqOptima; + } - /** - * @param reqOptima the reqOptima to set - */ - public void setReqOptima(int reqOptima) { - this.reqOptima = reqOptima; - } + /** + * @param reqOptima the reqOptima to set + */ + public void setReqOptima(int reqOptima) { + this.reqOptima = reqOptima; + } + + public String reqOptimaTipText() { + return "The number of optima that need to be found to terminate the optimization."; + } - public String reqOptimaTipText() { - return "The number of optima that need to be found to terminate the optimization."; - } - @Override - public String toString() { - return "KnownOptimaFoundTerminator requiring " + reqOptima + " optima."; - } - - public static String globalInfo() { - return "Terminate if a given number of optima has been found. Works for problems implementing InterfaceMultimodalProblemKnown, e.g. FM0."; - } + public String toString() { + return "KnownOptimaFoundTerminator requiring " + reqOptima + " optima."; + } + + public static String globalInfo() { + return "Terminate if a given number of optima has been found. Works for problems implementing InterfaceMultimodalProblemKnown, e.g. FM0."; + } } diff --git a/src/eva2/optimization/operator/terminators/ParetoMetricTerminator.java b/src/eva2/optimization/operator/terminators/ParetoMetricTerminator.java index b7059432..20777667 100644 --- a/src/eva2/optimization/operator/terminators/ParetoMetricTerminator.java +++ b/src/eva2/optimization/operator/terminators/ParetoMetricTerminator.java @@ -8,110 +8,112 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.AbstractMultiObjectiveOptimizationProblem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; + import java.io.Serializable; /** * Employ a pareto metric to determine convergence of a population. Requires to be run - * with a AbstractMultiObjectiveOptimizationProblem instance since the metric depend + * with a AbstractMultiObjectiveOptimizationProblem instance since the metric depend * on the fitness range. * The metric may be employed on the current population or the current pareto front * maintained by the problem instance. - * - * @author mkron * + * @author mkron */ public class ParetoMetricTerminator extends PopulationMeasureTerminator implements Serializable { - private InterfaceParetoFrontMetric pMetric = new MetricS(); - AbstractMultiObjectiveOptimizationProblem moProb=null; - private boolean useCurrentPop = false; - - public ParetoMetricTerminator() { - moProb=null; - } - - public ParetoMetricTerminator(InterfaceParetoFrontMetric metric, boolean useCurrentPop, double convergenceThreshold, int stagnationTime, StagnationTypeEnum stagType, ChangeTypeEnum changeType, DirectionTypeEnum dirType) { - super(convergenceThreshold, stagnationTime, stagType, changeType, dirType); - this.pMetric = metric; - this.useCurrentPop = useCurrentPop; - } - - public ParetoMetricTerminator(ParetoMetricTerminator o) { - super(o); - this.pMetric = (InterfaceParetoFrontMetric)o.pMetric.clone(); - this.moProb = o.moProb; - this.useCurrentPop = o.useCurrentPop; - } - - @Override - public void init(InterfaceOptimizationProblem prob) { - super.init(prob); - if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { - moProb = (AbstractMultiObjectiveOptimizationProblem)prob; + private InterfaceParetoFrontMetric pMetric = new MetricS(); + AbstractMultiObjectiveOptimizationProblem moProb = null; + private boolean useCurrentPop = false; + + public ParetoMetricTerminator() { + moProb = null; + } + + public ParetoMetricTerminator(InterfaceParetoFrontMetric metric, boolean useCurrentPop, double convergenceThreshold, int stagnationTime, StagnationTypeEnum stagType, ChangeTypeEnum changeType, DirectionTypeEnum dirType) { + super(convergenceThreshold, stagnationTime, stagType, changeType, dirType); + this.pMetric = metric; + this.useCurrentPop = useCurrentPop; + } + + public ParetoMetricTerminator(ParetoMetricTerminator o) { + super(o); + this.pMetric = (InterfaceParetoFrontMetric) o.pMetric.clone(); + this.moProb = o.moProb; + this.useCurrentPop = o.useCurrentPop; + } + + @Override + public void init(InterfaceOptimizationProblem prob) { + super.init(prob); + if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { + moProb = (AbstractMultiObjectiveOptimizationProblem) prob; + } else { + moProb = null; + EVAERROR.errorMsgOnce("Error, " + this.getClass() + " works only with problems inheriting from " + AbstractMultiObjectiveOptimizationProblem.class + "!"); + } + } + + @Override + protected double calcInitialMeasure(PopulationInterface pop) { + if (moProb == null) { + return Double.MAX_VALUE; + } else { + if (isUseCurrentPop()) { + return getParetoMetric().calculateMetricOn((Population) pop, moProb); + } else { + return getParetoMetric().calculateMetricOn(moProb.getLocalParetoFront(), moProb); } - else { - moProb = null; - EVAERROR.errorMsgOnce("Error, " + this.getClass() + " works only with problems inheriting from " + AbstractMultiObjectiveOptimizationProblem.class + "!"); - } - } + } + } - @Override - protected double calcInitialMeasure(PopulationInterface pop) { - if (moProb==null) { - return Double.MAX_VALUE; - } - else { - if (isUseCurrentPop()) { - return getParetoMetric().calculateMetricOn((Population)pop, moProb); - } - else { - return getParetoMetric().calculateMetricOn(moProb.getLocalParetoFront(), moProb); - } - } - } + @Override + protected double calcPopulationMeasure(PopulationInterface pop) { + return calcInitialMeasure(pop); + } - @Override - protected double calcPopulationMeasure(PopulationInterface pop) { - return calcInitialMeasure(pop); - } + @Override + protected String getMeasureName() { + String metricName = null; + try { + metricName = (String) BeanInspector.callIfAvailable(getParetoMetric(), "getName", null); + } catch (ClassCastException e) { + metricName = null; + } - @Override - protected String getMeasureName() { - String metricName=null; - try { - metricName = (String)BeanInspector.callIfAvailable(getParetoMetric(), "getName", null); - } catch(ClassCastException e) {metricName=null;} - - if (metricName==null) { - return "ParetoMetric"; - } - else { - return metricName; - } - } + if (metricName == null) { + return "ParetoMetric"; + } else { + return metricName; + } + } - public static String globalInfo() { - return "Terminate if the pareto front of a multi-objective optimization process converges " + - "with respect to a certain measure. Note that this only works with " + - "AbstractMultiObjectiveOptimizationProblem instances."; - } + public static String globalInfo() { + return "Terminate if the pareto front of a multi-objective optimization process converges " + + "with respect to a certain measure. Note that this only works with " + + "AbstractMultiObjectiveOptimizationProblem instances."; + } - public void setParetoMetric(InterfaceParetoFrontMetric pMetric) { - this.pMetric = pMetric; - } - public InterfaceParetoFrontMetric getParetoMetric() { - return pMetric; - } - public String paretoMetricTipText() { - return "The pareto metric to use"; - } + public void setParetoMetric(InterfaceParetoFrontMetric pMetric) { + this.pMetric = pMetric; + } - public void setUseCurrentPop(boolean useCurrentPop) { - this.useCurrentPop = useCurrentPop; - } - public boolean isUseCurrentPop() { - return useCurrentPop; - } - public String useCurrentPopTipText() { - return "If true, the current population is used, otherwise the pareto front of the multi-objective problem instance is used"; - } + public InterfaceParetoFrontMetric getParetoMetric() { + return pMetric; + } + + public String paretoMetricTipText() { + return "The pareto metric to use"; + } + + public void setUseCurrentPop(boolean useCurrentPop) { + this.useCurrentPop = useCurrentPop; + } + + public boolean isUseCurrentPop() { + return useCurrentPop; + } + + public String useCurrentPopTipText() { + return "If true, the current population is used, otherwise the pareto front of the multi-objective problem instance is used"; + } } diff --git a/src/eva2/optimization/operator/terminators/PhenotypeConvergenceTerminator.java b/src/eva2/optimization/operator/terminators/PhenotypeConvergenceTerminator.java index d6b37c2d..845715f9 100644 --- a/src/eva2/optimization/operator/terminators/PhenotypeConvergenceTerminator.java +++ b/src/eva2/optimization/operator/terminators/PhenotypeConvergenceTerminator.java @@ -7,59 +7,59 @@ import eva2.optimization.operator.distancemetric.PhenotypeMetric; import eva2.optimization.problems.InterfaceOptimizationProblem; public class PhenotypeConvergenceTerminator extends PopulationMeasureTerminator implements InterfaceTerminator { - AbstractEAIndividual oldIndy = null; - private PhenotypeMetric pMetric = null; + AbstractEAIndividual oldIndy = null; + private PhenotypeMetric pMetric = null; // double oldPhenNorm = 0; - - public PhenotypeConvergenceTerminator() { - super(); - pMetric = new PhenotypeMetric(); - } - public PhenotypeConvergenceTerminator(double thresh, int stagnTime, StagnationTypeEnum stagType, ChangeTypeEnum changeType, DirectionTypeEnum dirType) { - super(thresh, stagnTime, stagType, changeType, dirType); - pMetric = new PhenotypeMetric(); - } - - public PhenotypeConvergenceTerminator(PhenotypeConvergenceTerminator o) { - super(o); - oldIndy = (AbstractEAIndividual)o.oldIndy.clone(); - pMetric = (PhenotypeMetric)o.pMetric.clone(); + public PhenotypeConvergenceTerminator() { + super(); + pMetric = new PhenotypeMetric(); + } + + public PhenotypeConvergenceTerminator(double thresh, int stagnTime, StagnationTypeEnum stagType, ChangeTypeEnum changeType, DirectionTypeEnum dirType) { + super(thresh, stagnTime, stagType, changeType, dirType); + pMetric = new PhenotypeMetric(); + } + + public PhenotypeConvergenceTerminator(PhenotypeConvergenceTerminator o) { + super(o); + oldIndy = (AbstractEAIndividual) o.oldIndy.clone(); + pMetric = (PhenotypeMetric) o.pMetric.clone(); // oldPhenNorm = o.oldPhenNorm; - } - + } + @Override - public void init(InterfaceOptimizationProblem prob) { - super.init(prob); + public void init(InterfaceOptimizationProblem prob) { + super.init(prob); // oldPhenNorm = 0; - oldIndy = null; - } - - @Override - protected double calcInitialMeasure(PopulationInterface pop) { - oldIndy = (AbstractEAIndividual)((AbstractEAIndividual)pop.getBestIndividual()).clone(); + oldIndy = null; + } + + @Override + protected double calcInitialMeasure(PopulationInterface pop) { + oldIndy = (AbstractEAIndividual) ((AbstractEAIndividual) pop.getBestIndividual()).clone(); // oldPhenNorm = PhenotypeMetric.norm(oldIndy); - return Double.MAX_VALUE; - } + return Double.MAX_VALUE; + } - @Override - protected double calcPopulationMeasure(PopulationInterface pop) { - return pMetric.distance(oldIndy, (AbstractEAIndividual)pop.getBestIndividual()); - } + @Override + protected double calcPopulationMeasure(PopulationInterface pop) { + return pMetric.distance(oldIndy, (AbstractEAIndividual) pop.getBestIndividual()); + } - @Override - protected void saveState(PopulationInterface Pop) { - super.saveState(Pop); - oldIndy = (AbstractEAIndividual)((AbstractEAIndividual)Pop.getBestIndividual()).clone(); + @Override + protected void saveState(PopulationInterface Pop) { + super.saveState(Pop); + oldIndy = (AbstractEAIndividual) ((AbstractEAIndividual) Pop.getBestIndividual()).clone(); // oldPhenNorm = PhenotypeMetric.norm(oldIndy); - } + } - @Override - protected String getMeasureName() { - return "Phenotype"; - } - - public static String globalInfo() { - return "Terminate if the best individual of the current population moved less than a threshold within phenotypic space."; - } + @Override + protected String getMeasureName() { + return "Phenotype"; + } + + public static String globalInfo() { + return "Terminate if the best individual of the current population moved less than a threshold within phenotypic space."; + } } diff --git a/src/eva2/optimization/operator/terminators/PopulationArchiveTerminator.java b/src/eva2/optimization/operator/terminators/PopulationArchiveTerminator.java index 3dc0946d..fbf6a656 100644 --- a/src/eva2/optimization/operator/terminators/PopulationArchiveTerminator.java +++ b/src/eva2/optimization/operator/terminators/PopulationArchiveTerminator.java @@ -7,51 +7,50 @@ import eva2.optimization.population.Population; /** * Terminate if a score based on the archive of the population converges. * Note that this only works if the archive is filled with sensible data. - * - * @author mkron * + * @author mkron */ public class PopulationArchiveTerminator extends PopulationMeasureTerminator { - IndividualWeightedFitnessComparator wfComp = new IndividualWeightedFitnessComparator(new double[]{1.}); + IndividualWeightedFitnessComparator wfComp = new IndividualWeightedFitnessComparator(new double[]{1.}); - public static String globalInfo() { - return "Stop if a linear recombination of the best fitness stagnates for a certain period."; - } - - @Override - protected double calcInitialMeasure(PopulationInterface pop) { - Population archive = ((Population)pop).getArchive(); - if (archive==null || (archive.size()<1)) { - return Double.MAX_VALUE; - } - else { - return wfComp.calcScore(archive.getBestEAIndividual(wfComp)); - } - } + public static String globalInfo() { + return "Stop if a linear recombination of the best fitness stagnates for a certain period."; + } - @Override - protected double calcPopulationMeasure(PopulationInterface pop) { - Population archive = ((Population)pop).getArchive(); - if (archive==null || (archive.size()<1)) { - return Double.MAX_VALUE; - } - else { - return wfComp.calcScore(archive.getBestEAIndividual(wfComp)); - } - } + @Override + protected double calcInitialMeasure(PopulationInterface pop) { + Population archive = ((Population) pop).getArchive(); + if (archive == null || (archive.size() < 1)) { + return Double.MAX_VALUE; + } else { + return wfComp.calcScore(archive.getBestEAIndividual(wfComp)); + } + } - @Override - protected String getMeasureName() { - return "Archive Weighted Score"; - } + @Override + protected double calcPopulationMeasure(PopulationInterface pop) { + Population archive = ((Population) pop).getArchive(); + if (archive == null || (archive.size() < 1)) { + return Double.MAX_VALUE; + } else { + return wfComp.calcScore(archive.getBestEAIndividual(wfComp)); + } + } - public double[] getFitWeights() { - return wfComp.getFitWeights(); - } - public void setFitWeights(double[] fWeights) { - wfComp.setFitWeights(fWeights); - } - public String fitWeightsTipText() { - return wfComp.fitWeightsTipText(); - } + @Override + protected String getMeasureName() { + return "Archive Weighted Score"; + } + + public double[] getFitWeights() { + return wfComp.getFitWeights(); + } + + public void setFitWeights(double[] fWeights) { + wfComp.setFitWeights(fWeights); + } + + public String fitWeightsTipText() { + return wfComp.fitWeightsTipText(); + } } diff --git a/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java b/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java index fae852dd..06253cd9 100644 --- a/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java +++ b/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java @@ -5,76 +5,85 @@ import eva2.optimization.go.InterfaceTerminator; import eva2.optimization.population.PopulationInterface; import eva2.optimization.population.InterfaceSolutionSet; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.io.Serializable; /** * Abstract class giving the framework for a terminator that is based on - * a population measure converging for a given time (number of evaluations or + * a population measure converging for a given time (number of evaluations or * generations). * The class detects changes of a population measure over time and may signal convergence * if the measure m(P) behaved in a certain way for a given time. Convergence may - * be signaled + * be signaled * - if the measure reached absolute values below convThresh (absolute value), * - if the measure remained within m(P)+/-convThresh (absolute change), * - if the measure remained above m(P)-convThresh (absolute change and regard improvement only), * - if the measure remained within m(P)*[1-convThresh, 1+convThresh] (relative change), * - if the measure remained above m(P)*(1-convThresh) (relative change and regard improvement only). - * - * @author mkron * + * @author mkron */ public abstract class PopulationMeasureTerminator implements InterfaceTerminator, -Serializable { - public enum ChangeTypeEnum {relativeChange, absoluteChange, absoluteValue}; - public enum DirectionTypeEnum {decrease, bidirectional}; - public enum StagnationTypeEnum {fitnessCallBased, generationBased}; - - protected static boolean TRACE = false; - private double convThresh = 0.01; //, convThreshLower=0.02; - private double oldMeasure = -1; - private int stagTime = 1000; - private int oldPopFitCalls = 1000; - private int oldPopGens = 1000; - private boolean firstTime = true; - private StagnationTypeEnum stagnationMeasure = StagnationTypeEnum.fitnessCallBased; -// private SelectedTag convCondition = new SelectedTag("Relative change", "Absolute change", "Absolute value"); - private ChangeTypeEnum changeType = ChangeTypeEnum.relativeChange; - private DirectionTypeEnum condDirection = DirectionTypeEnum.decrease; -// private SelectedTag condImprovementOrChange = new SelectedTag("Decrease", "Improvement and Deterioration"); - protected String msg="Not terminated."; + Serializable { + public enum ChangeTypeEnum {relativeChange, absoluteChange, absoluteValue} - public PopulationMeasureTerminator() {} - - public PopulationMeasureTerminator(double convergenceThreshold, int stagnationTime, StagnationTypeEnum stagType, ChangeTypeEnum changeType, DirectionTypeEnum dirType) { - this.convThresh = convergenceThreshold; - this.stagTime = stagnationTime; - this.stagnationMeasure = stagType; + ; + + public enum DirectionTypeEnum {decrease, bidirectional} + + ; + + public enum StagnationTypeEnum {fitnessCallBased, generationBased} + + ; + + protected static boolean TRACE = false; + private double convThresh = 0.01; //, convThreshLower=0.02; + private double oldMeasure = -1; + private int stagTime = 1000; + private int oldPopFitCalls = 1000; + private int oldPopGens = 1000; + private boolean firstTime = true; + private StagnationTypeEnum stagnationMeasure = StagnationTypeEnum.fitnessCallBased; + // private SelectedTag convCondition = new SelectedTag("Relative change", "Absolute change", "Absolute value"); + private ChangeTypeEnum changeType = ChangeTypeEnum.relativeChange; + private DirectionTypeEnum condDirection = DirectionTypeEnum.decrease; + // private SelectedTag condImprovementOrChange = new SelectedTag("Decrease", "Improvement and Deterioration"); + protected String msg = "Not terminated."; + + public PopulationMeasureTerminator() { + } + + public PopulationMeasureTerminator(double convergenceThreshold, int stagnationTime, StagnationTypeEnum stagType, ChangeTypeEnum changeType, DirectionTypeEnum dirType) { + this.convThresh = convergenceThreshold; + this.stagTime = stagnationTime; + this.stagnationMeasure = stagType; // this.convergenceCondition.setSelectedTag(bAbsolute ? 1 : 0); - this.changeType = changeType; - this.condDirection = dirType; + this.changeType = changeType; + this.condDirection = dirType; // this.condImprovementOrChange.setSelectedTag(bImprovement ? 0 : 1); - } + } - public PopulationMeasureTerminator(PopulationMeasureTerminator o) { - convThresh = o.convThresh; - stagTime = o.stagTime; - oldPopFitCalls = o.oldPopFitCalls; - oldPopGens = o.oldPopGens; - firstTime = o.firstTime; + public PopulationMeasureTerminator(PopulationMeasureTerminator o) { + convThresh = o.convThresh; + stagTime = o.stagTime; + oldPopFitCalls = o.oldPopFitCalls; + oldPopGens = o.oldPopGens; + firstTime = o.firstTime; // oldFit = o.oldFit.clone(); // oldNorm = o.oldNorm; - msg = o.msg; - this.stagnationMeasure = o.stagnationMeasure; + msg = o.msg; + this.stagnationMeasure = o.stagnationMeasure; // this.convergenceCondition.setSelectedTag(o.convergenceCondition.getSelectedTagID()); - this.changeType = o.changeType; - this.condDirection = o.condDirection; + this.changeType = o.changeType; + this.condDirection = o.condDirection; // this.condImprovementOrChange.setSelectedTag(o.condImprovementOrChange.getSelectedTagID()); - } - + } + // public void hideHideable() { // setConvergenceCondition(getConvergenceCondition()); // } - + // public PopulationMeasureTerminator() { // pMetric = new PhenotypeMetric(); // } @@ -96,152 +105,160 @@ Serializable { // stagnationMeasure.setSelectedTag(other.getStagnationMeasure().getSelectedTagID()); // convergenceCondition.setSelectedTag(other.getConvergenceCondition().getSelectedTagID()); // } - - public static String globalInfo() { - return "Stop if a convergence criterion has been met."; - } + + public static String globalInfo() { + return "Stop if a convergence criterion has been met."; + } @Override - public void init(InterfaceOptimizationProblem prob) { - firstTime = true; - msg = "Not terminated."; + public void init(InterfaceOptimizationProblem prob) { + firstTime = true; + msg = "Not terminated."; // oldFit = null; // oldNorm=-1; - oldPopFitCalls=-1; - oldPopGens=-1; - } + oldPopFitCalls = -1; + oldPopGens = -1; + } @Override - public boolean isTerminated(InterfaceSolutionSet solSet) { - return isTerminated(solSet.getCurrentPopulation()); - } + public boolean isTerminated(InterfaceSolutionSet solSet) { + return isTerminated(solSet.getCurrentPopulation()); + } @Override - public boolean isTerminated(PopulationInterface pop) { - if (!firstTime && isStillConverged(pop)) { - if (TRACE) { - System.out.println("Converged at " + pop.getGeneration() + "/" + pop.getFunctionCalls() + ", measure " + calcPopulationMeasure(pop)); - } - if (stagnationTimeHasPassed(pop)) { - // population hasnt changed much for max time, criterion is met - msg = getTerminationMessage(); - return true; - } else { - // population hasnt changed much for i= allowedLower); - // Old Version: + break; + case relativeChange: + double delta = oldMeasure * convThresh; + allowedLower = oldMeasure - delta; + if (!doCheckImprovement()) { + allowedUpper = oldMeasure + delta; + } + break; + } + ret = (measure <= allowedUpper) && (measure >= allowedLower); + // Old Version: // if (isRelativeConvergence()) { // double delta = oldMeasure*convThresh; // if (doCheckImprovement()) ret = (measure >= (oldMeasure - delta)); @@ -250,47 +267,49 @@ Serializable { // if (doCheckImprovement()) ret = (measure < oldMeasure+convThresh); // absolute improvement below fixed number // else ret = ((measure < oldMeasure+convThresh) && (measure > oldMeasure-convThresh)); // absolute change within fixed range // } - if (TRACE) { - System.out.println("isStillConverged returns " + ret + ", measure " + measure + ", old measure " + BeanInspector.toString(oldMeasure) + ", bounds: [" + allowedLower + " , " + allowedUpper + "]"); - } - return ret; - } + if (TRACE) { + System.out.println("isStillConverged returns " + ret + ", measure " + measure + ", old measure " + BeanInspector.toString(oldMeasure) + ", bounds: [" + allowedLower + " , " + allowedUpper + "]"); + } + return ret; + } - public boolean doCheckImprovement() { - return (condDirection==DirectionTypeEnum.decrease); + public boolean doCheckImprovement() { + return (condDirection == DirectionTypeEnum.decrease); // return condImprovementOrChange.isSelectedString("Improvement"); - } + } - public boolean isRelativeConvergence() { - return changeType==ChangeTypeEnum.relativeChange; - } - - /** - * Return true if the defined stagnation time (function calls or generations) has passed - * since the last noteable change. - * - * @param pop - * @return - */ - private boolean stagnationTimeHasPassed(PopulationInterface pop) { - if (stagnationMeasure==StagnationTypeEnum.fitnessCallBased) { // by fitness calls + public boolean isRelativeConvergence() { + return changeType == ChangeTypeEnum.relativeChange; + } + + /** + * Return true if the defined stagnation time (function calls or generations) has passed + * since the last noteable change. + * + * @param pop + * @return + */ + private boolean stagnationTimeHasPassed(PopulationInterface pop) { + if (stagnationMeasure == StagnationTypeEnum.fitnessCallBased) { // by fitness calls // System.out.println("stagnationTimeHasPassed returns " + ((pop.getFunctionCalls() - popFitCalls) >= m_stagTime) + " after " + (pop.getFunctionCalls() - popFitCalls)); - return (pop.getFunctionCalls() - oldPopFitCalls) >= stagTime; - } else {// by generation + return (pop.getFunctionCalls() - oldPopFitCalls) >= stagTime; + } else {// by generation // System.out.println("stagnationTimeHasPassed returns " + ((pop.getFunctionCalls() - popGens) >= m_stagTime) + " after " + (pop.getFunctionCalls() - popGens)); - return (pop.getGeneration() - oldPopGens) >= stagTime; - } - } + return (pop.getGeneration() - oldPopGens) >= stagTime; + } + } - public void setConvergenceThreshold(double x) { - convThresh = x; - } - public double getConvergenceThreshold() { - return convThresh; - } - public String convergenceThresholdTipText() { - return "Ratio of improvement/change or absolute value of improvement/change to determine convergence."; - } + public void setConvergenceThreshold(double x) { + convThresh = x; + } + + public double getConvergenceThreshold() { + return convThresh; + } + + public String convergenceThresholdTipText() { + return "Ratio of improvement/change or absolute value of improvement/change to determine convergence."; + } // public void setConvergenceThresholdLower(double x) { // convThreshLower = x; @@ -301,44 +320,52 @@ Serializable { // public String convergenceThresholdUpperTipText() { // return "Lower threshold value in case of detecting absolute change, meaning the bounds [measure-convThresh,measure+convThresh] must be kept to assume convergence."; // } - - public void setStagnationTime(int k) { - stagTime = k; - } - public int getStagnationTime() { - return stagTime; - } - public String stagnationTimeTipText() { - return "Terminate if the population has not improved/changed for this time"; - } - public StagnationTypeEnum getStagnationMeasure() { - return stagnationMeasure; - } - public void setStagnationMeasure(StagnationTypeEnum stagnationTimeIn) { - this.stagnationMeasure = stagnationTimeIn; - } - public String stagnationMeasureTipText() { - return "Stagnation time is measured in fitness calls or generations"; - } + public void setStagnationTime(int k) { + stagTime = k; + } - public ChangeTypeEnum getConvergenceCondition() { - return changeType; - } - public void setConvergenceCondition(ChangeTypeEnum convergenceCondition) { - this.changeType = convergenceCondition; - } - public String convergenceConditionTipText() { - return "Select absolute or relative convergence condition"; - } - - public DirectionTypeEnum getCheckType() { - return condDirection; - } - public void setCheckType(DirectionTypeEnum dt) { - this.condDirection = dt; - } - public String checkTypeTipText() { - return "Detect improvement only (decreasing measure) or change in both directions (decrease and increase)"; - } + public int getStagnationTime() { + return stagTime; + } + + public String stagnationTimeTipText() { + return "Terminate if the population has not improved/changed for this time"; + } + + public StagnationTypeEnum getStagnationMeasure() { + return stagnationMeasure; + } + + public void setStagnationMeasure(StagnationTypeEnum stagnationTimeIn) { + this.stagnationMeasure = stagnationTimeIn; + } + + public String stagnationMeasureTipText() { + return "Stagnation time is measured in fitness calls or generations"; + } + + public ChangeTypeEnum getConvergenceCondition() { + return changeType; + } + + public void setConvergenceCondition(ChangeTypeEnum convergenceCondition) { + this.changeType = convergenceCondition; + } + + public String convergenceConditionTipText() { + return "Select absolute or relative convergence condition"; + } + + public DirectionTypeEnum getCheckType() { + return condDirection; + } + + public void setCheckType(DirectionTypeEnum dt) { + this.condDirection = dt; + } + + public String checkTypeTipText() { + return "Detect improvement only (decreasing measure) or change in both directions (decrease and increase)"; + } } \ No newline at end of file diff --git a/src/eva2/optimization/population/InterfaceSolutionSet.java b/src/eva2/optimization/population/InterfaceSolutionSet.java index f0bc60dd..90de4d0f 100644 --- a/src/eva2/optimization/population/InterfaceSolutionSet.java +++ b/src/eva2/optimization/population/InterfaceSolutionSet.java @@ -5,12 +5,13 @@ package eva2.optimization.population; * of an optimizer) and a final solution set, in which archived and deactivated * individuals may be contained as well. Both may be equal if the optimizer doesnt * make this distinction. - * - * @author mkron * + * @author mkron */ public interface InterfaceSolutionSet { - public Population getSolutions(); - public Population getCurrentPopulation(); - public SolutionSet clone(); + public Population getSolutions(); + + public Population getCurrentPopulation(); + + public SolutionSet clone(); } diff --git a/src/eva2/optimization/population/PBILPopulation.java b/src/eva2/optimization/population/PBILPopulation.java index c8de81da..aa089ded 100644 --- a/src/eva2/optimization/population/PBILPopulation.java +++ b/src/eva2/optimization/population/PBILPopulation.java @@ -3,32 +3,34 @@ package eva2.optimization.population; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.tools.math.RNG; + import java.util.BitSet; -/** +/** * This implementation of Population Based Incremental Learning is only * suited for a BitString based genotype representation. * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture - * @author Felix Streichert - * @version: $Revision: 306 $ - * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ - * $Author: mkron $ + * + * @author Felix Streichert + * @version: $Revision: 306 $ + * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ + * $Author: mkron $ */ public class PBILPopulation extends Population implements Cloneable, java.io.Serializable { - private double[] m_ProbabilityVector = new double[1]; + private double[] m_ProbabilityVector = new double[1]; public PBILPopulation() { } public PBILPopulation(int popSize) { - super(popSize); + super(popSize); } - + public PBILPopulation(PBILPopulation population) { - super(population); + super(population); this.m_ProbabilityVector = new double[population.m_ProbabilityVector.length]; for (int i = 0; i < this.m_ProbabilityVector.length; i++) { @@ -41,35 +43,36 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser return (Object) new PBILPopulation(this); } - /** + /** * This method inits the state of the population AFTER the individuals * have been inited by a problem. */ @Override public void init() { - this.generationCount = 0; - this.functionCallCount = 0; + this.generationCount = 0; + this.functionCallCount = 0; if (!(this.get(0) instanceof InterfaceGAIndividual)) { System.err.println("Members of the population are not instance of InterfaceGAIndividual!"); return; } - this.m_ProbabilityVector = new double[((InterfaceGAIndividual)this.get(0)).getGenotypeLength()]; + this.m_ProbabilityVector = new double[((InterfaceGAIndividual) this.get(0)).getGenotypeLength()]; for (int i = 0; i < this.m_ProbabilityVector.length; i++) { this.m_ProbabilityVector[i] = 0.5; } } - /** + /** * This method allows you to learn from several examples + * * @param examples A population of examples. * @param learnRate The learning rate. */ - public void learnFrom (Population examples, double learnRate) { + public void learnFrom(Population examples, double learnRate) { InterfaceGAIndividual tmpIndy; - BitSet tmpBitSet; - + BitSet tmpBitSet; + for (int i = 0; i < examples.size(); i++) { - tmpIndy = (InterfaceGAIndividual)(examples.getEAIndividual(i)).clone(); + tmpIndy = (InterfaceGAIndividual) (examples.getEAIndividual(i)).clone(); tmpBitSet = tmpIndy.getBGenotype(); for (int j = 0; j < this.m_ProbabilityVector.length; j++) { this.m_ProbabilityVector[j] *= (1.0 - learnRate); @@ -80,22 +83,21 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser } } - /** + /** * This method creates a new population based on the bit probability vector. */ public void initPBIL() { - InterfaceGAIndividual tmpIndy, template = (InterfaceGAIndividual)((AbstractEAIndividual)this.get(0)).clone(); - BitSet tmpBitSet; + InterfaceGAIndividual tmpIndy, template = (InterfaceGAIndividual) ((AbstractEAIndividual) this.get(0)).clone(); + BitSet tmpBitSet; this.clear(); for (int i = 0; i < this.getTargetSize(); i++) { - tmpIndy = (InterfaceGAIndividual)((AbstractEAIndividual)template).clone(); + tmpIndy = (InterfaceGAIndividual) ((AbstractEAIndividual) template).clone(); tmpBitSet = tmpIndy.getBGenotype(); for (int j = 0; j < this.m_ProbabilityVector.length; j++) { if (RNG.flipCoin(this.m_ProbabilityVector[j])) { tmpBitSet.set(j); - } - else { + } else { tmpBitSet.clear(j); } } @@ -104,9 +106,10 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser } } - /** + /** * This method allows you to mutate the bit probability vector - * @param mutationRate The mutation rate. + * + * @param mutationRate The mutation rate. */ public void mutateProbabilityVector(double mutationRate, double sigma) { for (int j = 0; j < this.m_ProbabilityVector.length; j++) { @@ -122,12 +125,12 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser } } - /** + /** * This method will build a probability vector from the current population. */ public void buildProbabilityVector() { - int dim = ((InterfaceGAIndividual)this.get(0)).getGenotypeLength(); - BitSet tmpSet; + int dim = ((InterfaceGAIndividual) this.get(0)).getGenotypeLength(); + BitSet tmpSet; this.m_ProbabilityVector = new double[dim]; for (int i = 0; i < this.m_ProbabilityVector.length; i++) { @@ -135,7 +138,7 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser } // first count the true bits for (int i = 0; i < this.size(); i++) { - tmpSet = ((InterfaceGAIndividual)this.get(i)).getBGenotype(); + tmpSet = ((InterfaceGAIndividual) this.get(i)).getBGenotype(); for (int j = 0; j < dim; j++) { if (tmpSet.get(j)) { this.m_ProbabilityVector[j] += 1; @@ -148,21 +151,23 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser } } - /** + /** * This method allows you to set the current probability vector. - * @param pv The new probability vector. + * + * @param pv The new probability vector. */ public void setProbabilityVector(double[] pv) { this.m_ProbabilityVector = pv; } - + public double[] getProbabilityVector() { return this.m_ProbabilityVector; } - /** + /** * This method will return a string description of the GAIndividal * notably the Genotype. + * * @return A descriptive string */ @Override @@ -171,21 +176,23 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser result += "PBIL-Population:\n"; result += "Probability vector: {"; for (int i = 0; i < this.m_ProbabilityVector.length; i++) { - result += this.m_ProbabilityVector[i] +"; "; + result += this.m_ProbabilityVector[i] + "; "; } result += "}\n"; result += "Population size: " + this.size() + "\n"; result += "Function calls : " + this.functionCallCount + "\n"; result += "Generations : " + this.generationCount; //for (int i = 0; i < this.size(); i++) { - //result += ((AbstractEAIndividual)this.get(i)).getSolutionRepresentationFor()+"\n"; + //result += ((AbstractEAIndividual)this.get(i)).getSolutionRepresentationFor()+"\n"; //} return result; } /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/population/Population.java b/src/eva2/optimization/population/Population.java index a3a465c5..8a20be5a 100644 --- a/src/eva2/optimization/population/Population.java +++ b/src/eva2/optimization/population/Population.java @@ -20,47 +20,49 @@ import eva2.tools.math.Jama.Matrix; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; import eva2.tools.math.StatisticUtils; + import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -/** +/** * A basic implementation of an EA population. Manage a set of potential solutions * in form of AbstractEAIndividuals. They can be sorted using an AbstractEAIndividualComparator. * Optionally, a history list is kept storing a clone of the best individual of any generation. * The Population also provides for appropriate counting of function calls performed. * For initialization, the default individual initialization method may be used, as well as a - * random latin hypercube implementation for InterfaceDataTypeDouble individuals. - * + * random latin hypercube implementation for InterfaceDataTypeDouble individuals. + *

* Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture - * @author Felix Streichert, Marcel Kronfeld - * @version: $Revision: 307 $ - * $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ - * $Author: mkron $ + * + * @author Felix Streichert, Marcel Kronfeld + * @version: $Revision: 307 $ + * $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ + * $Author: mkron $ */ public class Population extends ArrayList implements PopulationInterface, Cloneable, java.io.Serializable { private static final Logger LOGGER = Logger.getLogger(Population.class.getName()); - + /** * Number of generations. */ protected int generationCount = 0; - + /** * Number of function calls. */ protected int functionCallCount = 0; - + /** * Size of the target population. - */ + */ protected int targetPopSize = 50; protected Population populationArchive = null; - + /** * Method by which the Population gets initialized. */ @@ -68,40 +70,40 @@ public class Population extends ArrayList implements PopulationInterface, Clonea private double[] seedPos = new double[10]; private Pair seedCardinality = new Pair(5, 1); private double aroundDist = 0.1; - + transient private ArrayList listeners = null; - + /** * The evaluation interval at which listeners are notified. */ protected int notifyEvalInterval = 0; - + /** * Additional data connected to the population. */ protected HashMap additionalPopData = null; - + /** - * historical best individuals may be traced for a given number of generations. + * historical best individuals may be traced for a given number of generations. * Set to -1 to trace all, set to 0 to not trace at all */ int historyMaxLen = 0; - + /** * Best n Individuals in the history. */ private transient LinkedList m_History = new LinkedList(); - + /** * Remember when the last sorted queue was prepared. */ private int lastQModCount = -1; - + /** * A sorted queue (for efficiency). */ transient private ArrayList sortedArr = null; - + private Comparator lastSortingComparator = null; private InterfaceDistanceMetric popDistMetric = null; // an associated metric public static final String funCallIntervalReached = "FunCallIntervalReached"; @@ -117,7 +119,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * given integer value. * * @param initialCapacity initial capacity and population size of the - * instance + * instance */ public Population(int initialCapacity) { super(initialCapacity); @@ -142,7 +144,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea } public static Population makePopFromList(List indies) { - Population pop = new Population(indies.size()); + Population pop = new Population(indies.size()); pop.setTargetSize(indies.size()); for (AbstractEAIndividual indy : indies) { pop.add(indy); @@ -344,7 +346,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * EA and is implemented for efficiency. * * @return an empty population with equal members but not containing any - * individuals + * individuals */ public Population cloneWithoutInds() { // these two basically clone without cloning every individual @@ -530,11 +532,11 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * possibly gaussian variation defined by std.dev. which is truncated at * zero and the genotype length. * - * @param pop the population instance - * @param fillPop if true, fill the population up to the target size + * @param pop the population instance + * @param fillPop if true, fill the population up to the target size * @param cardinality an integer giving the number of (random) bits to set - * @param stdDev standard deviation of the cardinality variation (can be - * zero to fix the cardinality) + * @param stdDev standard deviation of the cardinality variation (can be + * zero to fix the cardinality) * @return */ public static void createBinCardinality(Population pop, boolean fillPop, int cardinality, int stdDev) { @@ -565,7 +567,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * Fill the population up to the target size with clones of a template * individual. * - * @param template a template individual used to fill the population + * @param template a template individual used to fill the population */ public void fill(AbstractEAIndividual template) { if (this.size() < this.getTargetSize()) { @@ -666,7 +668,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea */ protected void firePropertyChangedEvent(String name) { if (listeners != null) { - for (Iterator iterator = listeners.iterator(); iterator.hasNext();) { + for (Iterator iterator = listeners.iterator(); iterator.hasNext(); ) { InterfacePopulationChangedEventListener listener = iterator.next(); if (listener != null) { listener.registerPopulationStateChanged(this, name); @@ -693,13 +695,13 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method set the current number of function calls performed. Use with * care * - * @deprecated * @param d The new number of functioncalls. + * @deprecated */ public void SetFunctionCalls(int d) { this.functionCallCount = d; } - + /** * This method set the current number of function calls performed. Use with * care @@ -758,18 +760,18 @@ public class Population extends ArrayList implements PopulationInterface, Clonea /** * This method sets the generation. * - * @param gen the value to set as new generation index - * @deprecated + * @param gen the value to set as new generation index * @see setGeneration + * @deprecated */ public void setGenerationTo(int gen) { this.generationCount = gen; } - + /** * This method sets the generation. * - * @param gen the value to set as new generation index + * @param gen the value to set as new generation index */ public void setGeneration(int gen) { this.generationCount = gen; @@ -814,9 +816,9 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * exceeded. If indicated, this method checks for and avoids duplicate * object pointers. * - * @param pop The population that is to be added. + * @param pop The population that is to be added. * @param avoidDuplicatePointers if true, duplicate object pointers are - * forbidden + * forbidden */ public Population addPopulation(Population pop, boolean avoidDuplicatePointers) { if (pop != null) { @@ -838,9 +840,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * Fill the population up to the given size with random elements from the * given population. * - * @param upTo target size of the population + * @param upTo target size of the population * @param fromPop The population that is to be added. - * */ public boolean fillWithRandom(int upTo, Population fromPop) { if (upTo <= this.size()) { @@ -903,7 +904,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * @param startIndex the first index to start the search * @param indy * @return the index of the first individual which has an equal position or - * -1 + * -1 */ public int indexByPosition(int startIndex, AbstractEAIndividual indy) { for (int i = startIndex; i < size(); i++) { @@ -917,7 +918,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea /** * Resets the fitnes to the maximum possible value for the given individual. * - * @param indy an individual whose fitness will be reset + * @param indy an individual whose fitness will be reset */ public void resetFitness(IndividualInterface indy) { double[] tmpFit = indy.getFitness(); @@ -967,7 +968,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * Compare two fitness vectors. If bChooseBetter is true, the function * delivers the predicate "first is better than second" using the fitness * component indicated by fitIndex or a dominance criterion if fitIndex < 0. - * + * * @param bChooseBetter * @param fit1 * @param fit2 @@ -994,8 +995,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method will return the index of the current best individual from the * population. If the population is empty, -1 is returned. * - * @see getIndexOfBestOrWorstIndividual() * @return The index of the best individual. + * @see getIndexOfBestOrWorstIndividual() */ public int getIndexOfBestIndividualPrefFeasible() { if (size() < 1) { @@ -1008,8 +1009,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method will return the index of the current worst individual from * the population. * - * @see getIndexOfBestOrWorstIndividual() * @return The index of the worst individual. + * @see getIndexOfBestOrWorstIndividual() */ public int getIndexOfWorstIndividualNoConstr() { return getIndexOfBestOrWorstIndy(false, false, -1); @@ -1020,10 +1021,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * population in the given fitness component (or using dominance when * fitIndex < 0). If the population is empty, -1 is returned. * - - * - * @see getIndexOfBestOrWorstIndividual() * @return The index of the best individual. + * @see getIndexOfBestOrWorstIndividual() */ public int getIndexOfBestIndividualPrefFeasible(int fitIndex) { if (size() < 1) { @@ -1037,8 +1036,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * population in the given fitness component (or using dominance when * fitIndex < 0). * - * @see getIndexOfBestOrWorstIndividual() * @return The index of the best individual. + * @see getIndexOfBestOrWorstIndividual() */ public int getIndexOfWorstIndividualNoConstr(int fitIndex) { return getIndexOfBestOrWorstIndy(false, false, fitIndex); @@ -1067,8 +1066,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * from the population. A given comparator is employed for individual * comparisons. * - * @param bBest if true, the best (first) index is returned, else the worst - * (last) one + * @param bBest if true, the best (first) index is returned, else the worst + * (last) one * @param comparator indicate whether constraints should be regarded * @return The index of the best (worst) individual. */ @@ -1095,13 +1094,13 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * AbstractEAIndividualComparator that checks the constraints first and then * for the given fitness criterion (or a pareto criterion if it is -1). * - * @param bBest if true, the best (first) index is returned, else the worst - * (last) one + * @param bBest if true, the best (first) index is returned, else the worst + * (last) one * @param checkConstraints * @param fitIndex + * @return * @see #getIndexOfBestOrWorstIndividual(boolean, Comparator) * @see AbstractEAIndividualComparator - * @return */ public int getIndexOfBestOrWorstIndy(boolean bBest, boolean checkConstraints, int fitIndex) { return getIndexOfBestOrWorstIndividual(bBest, new AbstractEAIndividualComparator(fitIndex, checkConstraints)); @@ -1135,7 +1134,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * @param bBest * @param fitIndex * @return -1 if no feasible solution is found, else the index of the best - * feasible individual + * feasible individual */ public int getIndexOfBestOrWorstFeasibleIndividual(boolean bBest, int fitIndex) { int result = -1; @@ -1196,9 +1195,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * individuals are returned and effectively just sorted by fitness. This * does not check constraints! * - * @param n number of individuals to look out for + * @param n number of individuals to look out for * @return The m best individuals, where m <= n - * */ public Population getBestNIndividuals(int n, int fitIndex) { if (n <= 0 || (n > super.size())) { @@ -1217,9 +1215,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * individuals are returned and effectively just sorted by fitness. This * does not check constraints! * - * @param n number of individuals to look out for + * @param n number of individuals to look out for * @return The m worst individuals, where m <= n - * */ public Population getWorstNIndividuals(int n, int fitIndex) { Population pop = new Population(n); @@ -1231,10 +1228,9 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method returns a clone of the population instance with sorted * individuals, where the sorting criterion is delivered by a Comparator. * - * @see #getSortedNIndividuals(int, boolean, Population, Comparator) - * * @return a clone of the population instance with sorted individuals, best - * fitness first + * fitness first + * @see #getSortedNIndividuals(int, boolean, Population, Comparator) */ public Population getSortedBestFirst(Comparator comp) { Population result = this.cloneWithoutInds(); @@ -1249,13 +1245,12 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * are less than n individuals returned if the population is smaller than n. * This does not check constraints! * - * @param n number of individuals to look out for + * @param n number of individuals to look out for * @param bBestOrWorst if true, the best n are returned, else the worst n - * individuals - * @param res sorted result population, will be cleared - * @param comp the Comparator to use with individuals + * individuals + * @param res sorted result population, will be cleared + * @param comp the Comparator to use with individuals * @return The m sorted best or worst individuals, where m <= n - * */ public void getSortedNIndividuals(int n, boolean bBestOrWorst, Population res, Comparator comp) { if ((n < 0) || (n > super.size())) { @@ -1328,7 +1323,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * not be modified! * * @param comp A comparator by which sorting is performed - it should work - * on AbstractEAIndividual instances. + * on AbstractEAIndividual instances. * @return */ protected ArrayList sortBy(Comparator comp) { @@ -1358,7 +1353,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * altered! * * @param fitIndex the fitness criterion to be used or -1 for pareto - * dominance + * dominance * @return */ public ArrayList getSorted(Comparator comp) { @@ -1392,9 +1387,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method retrieves n random individuals from the population and * returns them within a new population. * - * @param n number of individuals to look out for + * @param n number of individuals to look out for * @return The n best individuals - * */ public Population getRandNIndividuals(int n) { if (n >= size()) { @@ -1411,9 +1405,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method removes n random individuals from the population and returns * them within a new population. * - * @param n number of individuals to look out for + * @param n number of individuals to look out for * @return The n best individuals - * */ public Population moveRandNIndividuals(int n) { return moveRandNIndividualsExcept(n, new Population()); @@ -1423,9 +1416,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This method removes n random individuals from the population (excluding * the given ones) and returns them in a new population instance. * - * @param n number of individuals to look out for + * @param n number of individuals to look out for * @return The n random individuals - * */ public Population moveRandNIndividualsExcept(int n, Population exclude) { return moveNInds(n, filter(exclude), new Population()); @@ -1494,7 +1486,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea } /** - * This method will remove + * This method will remove * N individuals from the population Note: the * current strategy will be remove N individuals at random but later a * special heuristic could be introduced. @@ -1533,7 +1525,6 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * being equal by the equals relation of the individual. * * @return the number of equal individuals - * */ public int getRedundancyCount() { int redund = 0; @@ -1777,7 +1768,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * Remove an individual from the population efficiently by switching it with * last position and removing that. * - * @param index individual index to be removed + * @param index individual index to be removed */ public AbstractEAIndividual removeIndexSwitched(int index) { AbstractEAIndividual indy = getEAIndividual(index); @@ -1802,7 +1793,6 @@ public class Population extends ArrayList implements PopulationInterface, Clonea } /** - * * @param ind * @return true if an indy was actually removed, else false */ @@ -1879,7 +1869,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * the instance. * * @return the average, minimal and maximal mean distance of individuals in - * an array of three + * an array of three */ @Override public double[] getPopulationMeasures() { @@ -1909,7 +1899,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This is of course rather expensive computationally. * * @return the average, minimal and maximal mean distance of individuals in - * an array of three + * an array of three */ public double[] getPopulationMeasures(InterfaceDistanceMetric metric) { // Integer lastMeasuresModCount = (Integer)getData(lastPopMeasuresFlagKey); @@ -1941,7 +1931,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * This is of course rather expensive computationally. * * @return the average, minimal and maximal mean distance of individuals in - * an array of three + * an array of three */ public static double[] getPopulationMeasures(List pop, InterfaceDistanceMetric metric) { double d; @@ -2040,7 +2030,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * * @param fitCrit fitness dimension to be used * @return the average, minimal, maximal and std dev. of fitness of - * individuals in an array + * individuals in an array */ public double[] getFitnessMeasures(int fitCrit) { return Population.getFitnessMeasures(this, fitCrit); @@ -2052,7 +2042,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * * @param fitCrit fitness dimension to be used * @return the average, minimal, maximal and std dev. of fitness of - * individuals in an array + * individuals in an array */ public static double[] getFitnessMeasures(List pop, int fitCrit) { double d; @@ -2099,7 +2089,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * @param pos * @param pop * @param closestOrFarthest if true, the closest individual is retrieved, - * otherwise the farthest + * otherwise the farthest * @return */ public static Pair getClosestFarthestIndy(double[] pos, Population pop, boolean closestOrFarthest) { @@ -2126,7 +2116,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * @param pos * @param pop * @param closestOrFarthest if true, the closest individual is retrieved, - * otherwise the farthest + * otherwise the farthest * @return */ public static Pair getClosestFarthestIndy(AbstractEAIndividual refIndy, Population pop, InterfaceDistanceMetric metric, boolean closestOrFarthest) { @@ -2219,9 +2209,9 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * AbstractEAIndidivual.getDoublePosition(individual) returns a valid * position. If they dont, null is returned. * - * @see AbstractEAIndidivual.getDoublePosition(individual) * @param criterion * @return + * @see AbstractEAIndidivual.getDoublePosition(individual) */ public double[] getCenterWeighted(AbstractSelProb selProb, int criterion, boolean obeyConst) { selProb.computeSelectionProbability(this, "Fitness", obeyConst); @@ -2245,7 +2235,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * * @param indy * @return closest neighbor (euclidian measure) of the given individual in - * the given population + * the given population */ public int getNeighborIndex(int neighborIndex) { // get the neighbor... @@ -2278,7 +2268,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * * @param normalizedPhenoMetric * @return a double array containing the average (or average and variance) - * of the distance of each individual to its closest neighbor + * of the distance of each individual to its closest neighbor */ public double[] getAvgDistToClosestNeighbor(boolean normalizedPhenoMetric, boolean calcVariance) { PhenotypeMetric metric = new PhenotypeMetric(); @@ -2380,7 +2370,6 @@ public class Population extends ArrayList implements PopulationInterface, Clonea /** * Set the desired population size parameter to the actual current size. - * */ public void synchSize() { setTargetSize(size()); diff --git a/src/eva2/optimization/population/PopulationInitMethod.java b/src/eva2/optimization/population/PopulationInitMethod.java index bf5ddcf6..bd0b6c1d 100644 --- a/src/eva2/optimization/population/PopulationInitMethod.java +++ b/src/eva2/optimization/population/PopulationInitMethod.java @@ -1,5 +1,5 @@ package eva2.optimization.population; public enum PopulationInitMethod { - individualDefault, randomLatinHypercube, aroundSeed, binCardinality, aroundRandomSeed; + individualDefault, randomLatinHypercube, aroundSeed, binCardinality, aroundRandomSeed; } diff --git a/src/eva2/optimization/population/PopulationInterface.java b/src/eva2/optimization/population/PopulationInterface.java index 320fa9b6..c5fc05a9 100644 --- a/src/eva2/optimization/population/PopulationInterface.java +++ b/src/eva2/optimization/population/PopulationInterface.java @@ -19,14 +19,14 @@ public interface PopulationInterface { /** * Returns the best individual of the population. - * + * * @return The best individual */ IndividualInterface getBestIndividual(); /** * Returns the worst individual of the population. - * + * * @return The worst individual */ IndividualInterface getWorstIndividual(); @@ -41,12 +41,14 @@ public interface PopulationInterface { /** * Returns the number of function calls. + * * @return The number of function calls */ int getFunctionCalls(); /** * The current generation count. + * * @return int The current generation */ int getGeneration(); @@ -67,11 +69,12 @@ public interface PopulationInterface { */ String[] getSpecificDataNames(); - + Object get(int i); /** * Return the size of the population. + * * @return int size of the population */ int size(); diff --git a/src/eva2/optimization/population/SolutionSet.java b/src/eva2/optimization/population/SolutionSet.java index 6537dbfe..2938da46 100644 --- a/src/eva2/optimization/population/SolutionSet.java +++ b/src/eva2/optimization/population/SolutionSet.java @@ -1,37 +1,37 @@ package eva2.optimization.population; public class SolutionSet implements InterfaceSolutionSet { - Population pop = null; - Population sols = null; - - public SolutionSet(Population currentPop, Population allSols) { - pop = currentPop; - sols = allSols; - } - - /** - * Create a solution set from a single population. This can be used by optimizers which - * make no distinction between current solution set and archived solution set. - * - * @param p - */ - public SolutionSet(Population p) { - pop = p; - sols = p; - } - + Population pop = null; + Population sols = null; + + public SolutionSet(Population currentPop, Population allSols) { + pop = currentPop; + sols = allSols; + } + + /** + * Create a solution set from a single population. This can be used by optimizers which + * make no distinction between current solution set and archived solution set. + * + * @param p + */ + public SolutionSet(Population p) { + pop = p; + sols = p; + } + @Override - public SolutionSet clone() { - return new SolutionSet((Population)pop.clone(), (Population)sols.clone()); - } - + public SolutionSet clone() { + return new SolutionSet((Population) pop.clone(), (Population) sols.clone()); + } + @Override - public Population getSolutions() { - return sols; - } - + public Population getSolutions() { + return sols; + } + @Override - public Population getCurrentPopulation() { - return pop; - } + public Population getCurrentPopulation() { + return pop; + } } diff --git a/src/eva2/optimization/problems/AbstractDynTransProblem.java b/src/eva2/optimization/problems/AbstractDynTransProblem.java index 15d5148e..14c949d7 100644 --- a/src/eva2/optimization/problems/AbstractDynTransProblem.java +++ b/src/eva2/optimization/problems/AbstractDynTransProblem.java @@ -5,191 +5,191 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; + import java.util.Random; public abstract class AbstractDynTransProblem extends AbstractSynchronousOptimizationProblem { - private static final long serialVersionUID = 2361612076300958044L; + private static final long serialVersionUID = 2361612076300958044L; - protected InterfaceOptimizationProblem prob; - protected AbstractEAIndividual bestIndividual = null; + protected InterfaceOptimizationProblem prob; + protected AbstractEAIndividual bestIndividual = null; - - /* for the random number generator, so that every solution is traceable */ - protected int seed = 1; - protected Random rand = new Random(seed); - protected int problemDimension; - protected double[][] range; - - public AbstractDynTransProblem() { - super(); - setProblem(new F1Problem()); - setFrequencyRelative(true); - } - /** - * Returns the instance of the object. - * - * @return the problem instance of the object. - */ - protected AbstractOptimizationProblem getInstance() { - return this; - } - - /** - * Evaluate the function at the individuals position using an arbitrary translation which may be dynamically changing. - * - * @param individual the individual to be evaluated - * @param t timestamp of the evaluation - */ + /* for the random number generator, so that every solution is traceable */ + protected int seed = 1; + protected Random rand = new Random(seed); + protected int problemDimension; + protected double[][] range; + + public AbstractDynTransProblem() { + super(); + setProblem(new F1Problem()); + setFrequencyRelative(true); + } + + /** + * Returns the instance of the object. + * + * @return the problem instance of the object. + */ + protected AbstractOptimizationProblem getInstance() { + return this; + } + + /** + * Evaluate the function at the individuals position using an arbitrary translation which may be dynamically changing. + * + * @param individual the individual to be evaluated + * @param t timestamp of the evaluation + */ @Override - public void evaluateAt(AbstractEAIndividual individual, double time) { - /* the fitness ist set by the evaluate function */ - AbstractEAIndividual tussy = (AbstractEAIndividual)individual.clone(); - transform(tussy, time); + public void evaluateAt(AbstractEAIndividual individual, double time) { + /* the fitness ist set by the evaluate function */ + AbstractEAIndividual tussy = (AbstractEAIndividual) individual.clone(); + transform(tussy, time); getProblem().evaluate(tussy); - individual.setFitness(tussy.getFitness()); - } + individual.setFitness(tussy.getFitness()); + } - /** - * Override population evaluation to do some data output. - * - */ + /** + * Override population evaluation to do some data output. + */ @Override - public void evaluatePopulationEnd(Population population) { - double delta = transLength(getCurrentProblemTime()); - if (isExtraPlot() == true) { - if (myplot != null) { - // myplot.addGraph(0, 1); - myplot.jump(); - } else { - if (TRACE) { - System.out.println("creating myplot instance"); - } - double[] tmpD = new double[2]; - tmpD[0] = 0; - tmpD[1] = 0; - // im not really certain about what tmpD is required for - this.myplot = new Plot("population measures", "x1", "x2", tmpD, tmpD); - } - myplot.setConnectedPoint(population.getFunctionCalls(), delta, 0); - //myplot.setUnconnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[2], 2); - } - else { - myplot = null; + public void evaluatePopulationEnd(Population population) { + double delta = transLength(getCurrentProblemTime()); + if (isExtraPlot() == true) { + if (myplot != null) { + // myplot.addGraph(0, 1); + myplot.jump(); + } else { + if (TRACE) { + System.out.println("creating myplot instance"); + } + double[] tmpD = new double[2]; + tmpD[0] = 0; + tmpD[1] = 0; + // im not really certain about what tmpD is required for + this.myplot = new Plot("population measures", "x1", "x2", tmpD, tmpD); } - } - - private double transLength(double time) { - double ret = 0.; - for (int i = 0; i < getProblemDimension(); i++) { + myplot.setConnectedPoint(population.getFunctionCalls(), delta, 0); + //myplot.setUnconnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[2], 2); + } else { + myplot = null; + } + } + + private double transLength(double time) { + double ret = 0.; + for (int i = 0; i < getProblemDimension(); i++) { ret += Math.pow(getTranslation(i, time), 2.); } - return Math.sqrt(ret); - } - - /** - * Returns the translation in the given dimension at the given time. - * - * @param dim the dimension - * @param time the simulation time - * @return the translation in the given dimension at the given time - */ - protected abstract double getTranslation(int dim, double time); - - protected void transform(AbstractEAIndividual individual, double time) { - double[] indyData = ((InterfaceDataTypeDouble)individual).getDoubleData(); - for (int i = 0; i < indyData.length; ++i) { - /* individuum moves towords untranslated problem */ - indyData[i] -= getTranslation(i, time); - } - ((InterfaceDataTypeDouble)individual).SetDoubleGenotype(indyData); - } + return Math.sqrt(ret); + } - /* - * Initializes the underlying problem in the problem class - */ + /** + * Returns the translation in the given dimension at the given time. + * + * @param dim the dimension + * @param time the simulation time + * @return the translation in the given dimension at the given time + */ + protected abstract double getTranslation(int dim, double time); + + protected void transform(AbstractEAIndividual individual, double time) { + double[] indyData = ((InterfaceDataTypeDouble) individual).getDoubleData(); + for (int i = 0; i < indyData.length; ++i) { + /* individuum moves towords untranslated problem */ + indyData[i] -= getTranslation(i, time); + } + ((InterfaceDataTypeDouble) individual).SetDoubleGenotype(indyData); + } + + /* + * Initializes the underlying problem in the problem class + */ @Override - public void initializeProblem() { - super.initializeProblem(); - bestIndividual = null; - getProblem().initializeProblem(); - } + public void initializeProblem() { + super.initializeProblem(); + bestIndividual = null; + getProblem().initializeProblem(); + } /** * Whenever the environment (or the time, primarily) has changed, some problem * properties (like stored individual fitness) may require updating. - * + * * @param severity the severity of the change (time measure) */ @Override - public void resetProblem(double severity) { - if ((prob != null) && (bestIndividual != null)) { - this.evaluateAt(bestIndividual, getCurrentProblemTime()); - } - } - - /* inits the population in the problem itself - * - */ - @Override - public void initPopulationAt(Population population, double time) { - if (TRACE) { - System.out.println("DynTransProblem at " + this + " initPop, problem is " + getProblem()); - } - getProblem().initializePopulation(population); - for (int i = 0; i < population.size(); i++) { - ((AbstractEAIndividual)population.get(i)).SetAge(0); + public void resetProblem(double severity) { + if ((prob != null) && (bestIndividual != null)) { + this.evaluateAt(bestIndividual, getCurrentProblemTime()); } - } - - public int getProblemDimension() { - return problemDimension; - } + } -/****************************************************************************** - * These are for the GUI - */ + /* inits the population in the problem itself + * + */ @Override - public String getStringRepresentationForProblem(InterfaceOptimizer opt) { - return "DynTransProblem"; - } + public void initPopulationAt(Population population, double time) { + if (TRACE) { + System.out.println("DynTransProblem at " + this + " initPop, problem is " + getProblem()); + } + getProblem().initializePopulation(population); + for (int i = 0; i < population.size(); i++) { + ((AbstractEAIndividual) population.get(i)).SetAge(0); + } + } - /** - * This is for the Scroll Box: - * in JParaPanel.java package eva2.gui - * in installActions() - * PropertyEditorManager.registerEditor(AbstractOptimizationProblem.class, GenericObjectEditor.class); - * don't forget the import statement - * - */ - public InterfaceOptimizationProblem getProblem() { - return prob; - } - public void setProblem(InterfaceOptimizationProblem prob) { - this.prob = prob; + public int getProblemDimension() { + return problemDimension; + } + + /** + * *************************************************************************** + * These are for the GUI + */ + @Override + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + return "DynTransProblem"; + } + + /** + * This is for the Scroll Box: + * in JParaPanel.java package eva2.gui + * in installActions() + * PropertyEditorManager.registerEditor(AbstractOptimizationProblem.class, GenericObjectEditor.class); + * don't forget the import statement + */ + public InterfaceOptimizationProblem getProblem() { + return prob; + } + + public void setProblem(InterfaceOptimizationProblem prob) { + this.prob = prob; /* to get the right values for problemDimension and Range */ - Population pop = new Population(); - pop.setTargetSize(1); - prob.initializePopulation(pop); - AbstractEAIndividual indy = (AbstractEAIndividual)pop.get(0); - if (indy instanceof InterfaceDataTypeDouble) { - problemDimension = ((InterfaceDataTypeDouble)indy).getDoubleRange().length; - range = ((InterfaceDataTypeDouble)indy).getDoubleRange(); - } else { - System.out.println("Wrong Problem"); - } - pop.clear(); - } + Population pop = new Population(); + pop.setTargetSize(1); + prob.initializePopulation(pop); + AbstractEAIndividual indy = (AbstractEAIndividual) pop.get(0); + if (indy instanceof InterfaceDataTypeDouble) { + problemDimension = ((InterfaceDataTypeDouble) indy).getDoubleRange().length; + range = ((InterfaceDataTypeDouble) indy).getDoubleRange(); + } else { + System.out.println("Wrong Problem"); + } + pop.clear(); + } - public int getSeed() { - return seed; - } + public int getSeed() { + return seed; + } - public void setSeed(int seed) { - this.seed = seed; - this.rand = new Random(seed); - } + public void setSeed(int seed) { + this.seed = seed; + this.rand = new Random(seed); + } } diff --git a/src/eva2/optimization/problems/AbstractDynamicOptimizationProblem.java b/src/eva2/optimization/problems/AbstractDynamicOptimizationProblem.java index dc5f983b..7d01bbe5 100644 --- a/src/eva2/optimization/problems/AbstractDynamicOptimizationProblem.java +++ b/src/eva2/optimization/problems/AbstractDynamicOptimizationProblem.java @@ -6,87 +6,89 @@ import eva2.optimization.population.Population; /** - * An abstract class for dynamic optimization problems. Main parameters are frequency and severity of + * An abstract class for dynamic optimization problems. Main parameters are frequency and severity of * changes in the problem environment (the target function). The latter may be measured in absolute - * function evaluations or relative to the population size. The necessary transmutations are to be + * function evaluations or relative to the population size. The necessary transmutations are to be * implemented, however. - * + *

* User: MK * Date: 19.12.2006 * Time: 11:02:12 */ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimizationProblem implements java.io.Serializable { - /** - * Default start time of the optimization process - */ - protected double startTime; - /** - * Current simulation time during optimization - */ - protected double currentProblemTime; - - /** - * A severity measure of the dynamics - */ - protected double severity; - /** - * A frequency measure of the dynamics - */ - protected double frequency; - /** - * Switch indicating relative (to population size) or absolute (in evaluations) frequency - */ - protected boolean frequencyRelative; - /** - * - */ - private AbstractEAIndividual idealInd; - - /** - * Switch controling extra problem visualization - */ - private boolean bExtraPlot; - /** - * Debug switch - */ - protected boolean TRACE; - /** - * the plot instance for problem data visualization - */ - transient protected Plot myplot = null; - - /** - * A constructor. - */ - public AbstractDynamicOptimizationProblem() { - //System.out.println("AbstractDynamicOptimizationProblem()"); - bExtraPlot = false; - TRACE = false; - myplot = null; - idealInd = null; -// initialize(0, 1., 0.1); - } + /** + * Default start time of the optimization process + */ + protected double startTime; + /** + * Current simulation time during optimization + */ + protected double currentProblemTime; - /** This method inits the Problem to log multiruns at the given timestamp. - * @param startT start time stamp - * @param sev initial severity - * @param freq initial frequency + /** + * A severity measure of the dynamics + */ + protected double severity; + /** + * A frequency measure of the dynamics + */ + protected double frequency; + /** + * Switch indicating relative (to population size) or absolute (in evaluations) frequency + */ + protected boolean frequencyRelative; + /** + * + */ + private AbstractEAIndividual idealInd; + + /** + * Switch controling extra problem visualization + */ + private boolean bExtraPlot; + /** + * Debug switch + */ + protected boolean TRACE; + /** + * the plot instance for problem data visualization + */ + transient protected Plot myplot = null; + + /** + * A constructor. + */ + public AbstractDynamicOptimizationProblem() { + //System.out.println("AbstractDynamicOptimizationProblem()"); + bExtraPlot = false; + TRACE = false; + myplot = null; + idealInd = null; +// initialize(0, 1., 0.1); + } + + /** + * This method inits the Problem to log multiruns at the given timestamp. + * + * @param startT start time stamp + * @param sev initial severity + * @param freq initial frequency */ public void initialize(double startT, double sev, double freq) { - setCurrentProblemTime(startT); - setSeverity(sev); - setFrequency(freq); - - if (bExtraPlot) { + setCurrentProblemTime(startT); + setSeverity(sev); + setFrequency(freq); + + if (bExtraPlot) { makePlot(); } } - + @Override public void initializeProblem() { - setCurrentProblemTime(getStartTime()); - if (myplot != null) { + setCurrentProblemTime(getStartTime()); + if (myplot != null) { try { myplot.jump(); } catch (NullPointerException e) { @@ -94,261 +96,268 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz } } } - + /** * Whenever the environment (or the time, primarily) has changed, some problem * properties (like stored individual fitness) may require updating. - * + * * @param severity the severity of the change (time measure) */ public abstract void resetProblem(double severity); - + /** * This method inits a given population at the current time stamp. - * - * @param population The populations that is to be inited + * + * @param population The populations that is to be inited */ @Override public void initializePopulation(Population population) { - //initializeProblem(); // this shouldnt be necessary - this.initPopulationAt(population, getCurrentProblemTime()); + //initializeProblem(); // this shouldnt be necessary + this.initPopulationAt(population, getCurrentProblemTime()); } - - /** + + /** * This method inits a given population - * - * @param population The populations that is to be inited - * @param time current time stamp to be used + * + * @param population The populations that is to be inited + * @param time current time stamp to be used */ public abstract void initPopulationAt(Population population, double time); - + /** - * @return the startTime - **/ - public double getStartTime() { - return startTime; - } + * @return the startTime + */ + public double getStartTime() { + return startTime; + } - /** - * @param startTime the startTime to set - **/ - public void setStartTime(double startTime) { - this.startTime = startTime; - } + /** + * @param startTime the startTime to set + */ + public void setStartTime(double startTime) { + this.startTime = startTime; + } - /** + /** * Sets the time stamp. - * - * @param newTime new time stamp for the evaluation + * + * @param newTime new time stamp for the evaluation */ protected void setCurrentProblemTime(double newTime) { - double sev = newTime - currentProblemTime; - currentProblemTime = newTime; - if (sev != 0.) { + double sev = newTime - currentProblemTime; + currentProblemTime = newTime; + if (sev != 0.) { resetProblem(sev); } } - + /** * Return the problems current time stamp. - * + * * @return the current time stamp */ protected double getCurrentProblemTime() { - return currentProblemTime; + return currentProblemTime; } - + public String problemTimeTipText() { - return "simulated starting time for the run"; + return "simulated starting time for the run"; } - - /** - * @param sev the desired severity of a dynamic change + + /** + * @param sev the desired severity of a dynamic change */ public void setSeverity(double sev) { - severity = sev; - if (TRACE) { + severity = sev; + if (TRACE) { System.out.println("severity to " + sev); } - } - - /** - * @return the severity of a dynamic alteration - */ - public double getSeverity() { - return severity; - } - + } + /** - * The frequency of changes of the problem environment. + * @return the severity of a dynamic alteration + */ + public double getSeverity() { + return severity; + } + + /** + * The frequency of changes of the problem environment. * May be measured in absolute evaluations or multiples of the population size. - * - * @return the frequency - **/ - public double getFrequency() { - return frequency; - } + * + * @return the frequency + */ + public double getFrequency() { + return frequency; + } - /** - * @param frequency the frequency to set - **/ - public void setFrequency(double frequency) { - this.frequency = frequency; - } + /** + * @param frequency the frequency to set + */ + public void setFrequency(double frequency) { + this.frequency = frequency; + } - /** - * @return true if the frequency value is meant to be relative to the population size - **/ - public boolean isFrequencyRelative() { - return frequencyRelative; - } + /** + * @return true if the frequency value is meant to be relative to the population size + */ + public boolean isFrequencyRelative() { + return frequencyRelative; + } - public String frequencyTipText() { - return "The frequency of changes in the target function, should be <= 1"; - } - - /** - * @param frequencyRelative set true if the frequency value is meant to be relative to the population size - **/ - public void setFrequencyRelative(boolean frequencyRelative) { - this.frequencyRelative = frequencyRelative; - } - - public String frequencyRelativeTipText() { - return "If marked, frequency is interpreted relative to population size, else it refers to absolute evaluations."; - } + public String frequencyTipText() { + return "The frequency of changes in the target function, should be <= 1"; + } - /** + /** + * @param frequencyRelative set true if the frequency value is meant to be relative to the population size + */ + public void setFrequencyRelative(boolean frequencyRelative) { + this.frequencyRelative = frequencyRelative; + } + + public String frequencyRelativeTipText() { + return "If marked, frequency is interpreted relative to population size, else it refers to absolute evaluations."; + } + + /** * Increases the internal time stamp by the given value. - * - * @param dt time interval + * + * @param dt time interval */ protected void incProblemTime(double dt) { - currentProblemTime += dt; - resetProblem(dt); - if (TRACE) { + currentProblemTime += dt; + resetProblem(dt); + if (TRACE) { System.out.println("new problem time is " + currentProblemTime); } } /** * If there is a known global optimum, return an individual representing it, otherwise return false. - * - * @return the optimum represented in an individual, or null if the optimum is currently unknown + * + * @return the optimum represented in an individual, or null if the optimum is currently unknown */ public abstract AbstractEAIndividual getCurrentOptimum(); - + /******************** The most important methods ****************************************/ - /** This method evaluates a single individual and sets the fitness value at default time stamp 0. - * @param individual The individual that is to be evalutated + /** + * This method evaluates a single individual and sets the fitness value at default time stamp 0. + * + * @param individual The individual that is to be evalutated */ @Override public void evaluate(AbstractEAIndividual individual) { - if (problemToChangeAt(getCurrentProblemTime())) { - changeProblemAt(getCurrentProblemTime()); - } - this.evaluateAt(individual, getCurrentProblemTime()); - countEvaluation(); + if (problemToChangeAt(getCurrentProblemTime())) { + changeProblemAt(getCurrentProblemTime()); + } + this.evaluateAt(individual, getCurrentProblemTime()); + countEvaluation(); } - /** + /** * Called every time an individual evaluation is performed. - * */ protected abstract void countEvaluation(); - - /** + + /** * Called to indicate a change in the problem environment. To be implemented. * * @param problemTime */ protected abstract void changeProblemAt(double problemTime); - /** - * Implement an indicator for when changes in the problem environment are necessary. If it returns - * true, the changeProblemAt(double problemTime) will be called. - * - * @param problemTime the current simulation time of the problem - * @return true, if the problem is to change at the given time, else false - */ - protected abstract boolean problemToChangeAt(double problemTime); + /** + * Implement an indicator for when changes in the problem environment are necessary. If it returns + * true, the changeProblemAt(double problemTime) will be called. + * + * @param problemTime the current simulation time of the problem + * @return true, if the problem is to change at the given time, else false + */ + protected abstract boolean problemToChangeAt(double problemTime); - /** This method evaluates a single individual and sets the fitness values without changing the environment (in "no time"). - * @param individual The individual that is to be evalutated - * @param t time stamp of the evaluation call + /** + * This method evaluates a single individual and sets the fitness values without changing the environment (in "no time"). + * + * @param individual The individual that is to be evalutated + * @param t time stamp of the evaluation call */ protected abstract void evaluateAt(AbstractEAIndividual individual, double t); - /** This method evaluate a single individual at the current problem time and sets the fitness values without changing the environment (in "no time"). - * @param individual The individual that is to be evalutated + /** + * This method evaluate a single individual at the current problem time and sets the fitness values without changing the environment (in "no time"). + * + * @param individual The individual that is to be evalutated */ public void evaluateInstantly(AbstractEAIndividual individual) { - evaluateAt(individual, getCurrentProblemTime()); + evaluateAt(individual, getCurrentProblemTime()); } - + /********************************************************************************************************************** * These are for GUI */ - /** - * Override population evaluation to do some data output. - * - * @param population the population whi - */ + /** + * Override population evaluation to do some data output. + * + * @param population the population whi + */ @Override - public void evaluatePopulationEnd(Population population) { - //System.out.println(">> mean distance at " + population.getFunctionCalls() + " / " + getProblemTime() + " is " + population.getMeanDistance()); - //System.out.println("> current best is " + population.getBestFitness()[0]); - //double[] meanMinMax = population.getPopulationMeasures(); - - //myplot.setConnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[0], 0); - - AbstractEAIndividual popBest = (AbstractEAIndividual)(population.getBestIndividual()); - if (idealInd == null) { - idealInd = (AbstractEAIndividual)popBest.clone(); - } - + public void evaluatePopulationEnd(Population population) { + //System.out.println(">> mean distance at " + population.getFunctionCalls() + " / " + getProblemTime() + " is " + population.getMeanDistance()); + //System.out.println("> current best is " + population.getBestFitness()[0]); + //double[] meanMinMax = population.getPopulationMeasures(); + + //myplot.setConnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[0], 0); + + AbstractEAIndividual popBest = (AbstractEAIndividual) (population.getBestIndividual()); + if (idealInd == null) { + idealInd = (AbstractEAIndividual) popBest.clone(); + } + // getCurrentOptimum((InterfaceDataTypeDouble)idealInd); - + // double d = new PhenotypeMetric().distance(popBest, idealInd); // double d = distanceBetween(popBest, idealInd); - - //System.out.println("tracking dist is " + d); - - //if (myplot!=null) myplot.setConnectedPoint(population.getFunctionCalls(), d, 0); - //myplot.setUnconnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[2], 2); - } - - protected void setExtraPlot(boolean doPlot) { - if (bExtraPlot && !doPlot) { - myplot = null; - } else if (!bExtraPlot && doPlot) { - if (myplot != null) { - myplot.jump(); - } else { - makePlot(); - } - } - bExtraPlot = doPlot; - } - - protected boolean isExtraPlot() { - return bExtraPlot; - } - - private void makePlot() { - if (TRACE) { - System.out.println("creating myplot instance"); + + //System.out.println("tracking dist is " + d); + + //if (myplot!=null) myplot.setConnectedPoint(population.getFunctionCalls(), d, 0); + //myplot.setUnconnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[2], 2); + } + + protected void setExtraPlot(boolean doPlot) { + if (bExtraPlot && !doPlot) { + myplot = null; + } else if (!bExtraPlot && doPlot) { + if (myplot != null) { + myplot.jump(); + } else { + makePlot(); } + } + bExtraPlot = doPlot; + } + + protected boolean isExtraPlot() { + return bExtraPlot; + } + + private void makePlot() { + if (TRACE) { + System.out.println("creating myplot instance"); + } double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; // im not really certain about what tmpD is required for this.myplot = new Plot("population measures", "x1", "x2", tmpD, tmpD); - } - - /** This method allows the CommonJavaObjectEditorPanel to read the + } + + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override diff --git a/src/eva2/optimization/problems/AbstractMultiModalProblemKnown.java b/src/eva2/optimization/problems/AbstractMultiModalProblemKnown.java index d16ffd64..7046742f 100644 --- a/src/eva2/optimization/problems/AbstractMultiModalProblemKnown.java +++ b/src/eva2/optimization/problems/AbstractMultiModalProblemKnown.java @@ -11,364 +11,378 @@ import eva2.optimization.population.Population; import eva2.tools.EVAERROR; import eva2.tools.ToolBox; import eva2.tools.math.Mathematics; + import java.util.List; -public abstract class AbstractMultiModalProblemKnown extends AbstractProblemDouble -implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { - protected static InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); - private double globalOptimum = 0; - protected Population listOfOptima; - protected double epsilon = 0.05; - protected int problemDimension = 2; - // if the global optimum is zero and we want to see logarithmic plots, the offset must be a little lower. see addOptimum() - protected boolean makeGlobalOptUnreachable = false; +public abstract class AbstractMultiModalProblemKnown extends AbstractProblemDouble + implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { + protected static InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); + private double globalOptimum = 0; + protected Population listOfOptima; + protected double epsilon = 0.05; + protected int problemDimension = 2; + // if the global optimum is zero and we want to see logarithmic plots, the offset must be a little lower. see addOptimum() + protected boolean makeGlobalOptUnreachable = false; - public AbstractMultiModalProblemKnown() { - this.problemDimension = 2; - this.template = new ESIndividualDoubleData(); - } + public AbstractMultiModalProblemKnown() { + this.problemDimension = 2; + this.template = new ESIndividualDoubleData(); + } - protected void cloneObjects(AbstractMultiModalProblemKnown b) { - super.cloneObjects(b); - if (b.listOfOptima != null) { - this.listOfOptima = (Population)((Population)b.listOfOptima).clone(); - }; - this.globalOptimum = b.globalOptimum; - this.epsilon = b.epsilon; - } - - public AbstractMultiModalProblemKnown(AbstractMultiModalProblemKnown b) { - cloneObjects(b); - } + protected void cloneObjects(AbstractMultiModalProblemKnown b) { + super.cloneObjects(b); + if (b.listOfOptima != null) { + this.listOfOptima = (Population) ((Population) b.listOfOptima).clone(); + } + ; + this.globalOptimum = b.globalOptimum; + this.epsilon = b.epsilon; + } - /** This method inits a given population - * @param population The populations that is to be inited - */ + public AbstractMultiModalProblemKnown(AbstractMultiModalProblemKnown b) { + cloneObjects(b); + } + + /** + * This method inits a given population + * + * @param population The populations that is to be inited + */ @Override - public void initializePopulation(Population population) { - AbstractEAIndividual tmpIndy; + public void initializePopulation(Population population) { + AbstractEAIndividual tmpIndy; - population.clear(); + population.clear(); + + ((InterfaceDataTypeDouble) this.template).setDoubleDataLength(this.problemDimension); + ((InterfaceDataTypeDouble) this.template).SetDoubleRange(makeRange()); + for (int i = 0; i < population.getTargetSize(); i++) { + tmpIndy = (AbstractEAIndividual) ((AbstractEAIndividual) this.template).clone(); + tmpIndy.init(this); + population.add(tmpIndy); + } + // population init must be last + // it set's fitcalls and generation to zero + population.init(); + if (listOfOptima == null) { + this.globalOptimum = Double.NEGATIVE_INFINITY; + listOfOptima = new Population(); + this.initListOfOptima(); + } + } - ((InterfaceDataTypeDouble)this.template).setDoubleDataLength(this.problemDimension); - ((InterfaceDataTypeDouble)this.template).SetDoubleRange(makeRange()); - for (int i = 0; i < population.getTargetSize(); i++) { - tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.template).clone(); - tmpIndy.init(this); - population.add(tmpIndy); - } - // population init must be last - // it set's fitcalls and generation to zero - population.init(); - if (listOfOptima == null) { - this.globalOptimum = Double.NEGATIVE_INFINITY; - listOfOptima = new Population(); - this.initListOfOptima(); - } - } - @Override - public void initializeProblem() { - super.initializeProblem(); - this.globalOptimum = Double.NEGATIVE_INFINITY; - listOfOptima = new Population(); - this.initListOfOptima(); - if (!fullListAvailable() && (Double.isInfinite(globalOptimum))) { - globalOptimum =0; + public void initializeProblem() { + super.initializeProblem(); + this.globalOptimum = Double.NEGATIVE_INFINITY; + listOfOptima = new Population(); + this.initListOfOptima(); + if (!fullListAvailable() && (Double.isInfinite(globalOptimum))) { + globalOptimum = 0; + } + } + + /** + * Ths method allows you to evaluate a simple bit string to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. + */ + @Override + public double[] eval(double[] x) { + x = rotateMaybe(x); + double[] result = new double[1]; + result[0] = this.globalOptimum - evalUnnormalized(x)[0]; + return result; + } + + /** + * This method returns the unnormalized (and unrotated!) function value for an maximization problem. + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. + */ + public abstract double[] evalUnnormalized(double[] x); + + @Override + public String[] getAdditionalDataHeader() { + return ToolBox.appendArrays(new String[]{"numOptsFound", "maxPeakRatio"}, super.getAdditionalDataHeader()); + } + + @Override + public String[] getAdditionalDataInfo() { + return ToolBox.appendArrays(new String[]{"The number of optima identified with default accuracy", "The maximum peak ratio measure in [0,1], best at 1, if multiple local optima are known."}, super.getAdditionalDataInfo()); + } + + @Override + public Object[] getAdditionalDataValue(PopulationInterface pop) { + Object[] result = new Object[2]; + result[0] = this.getNumberOfFoundOptima((Population) pop); + result[1] = this.getMaximumPeakRatio((Population) pop); + return ToolBox.appendArrays(result, super.getAdditionalDataValue(pop)); + } + + + /********************************************************************************************************************** + * Implementation of InterfaceMultimodalProblemKnown + */ + + /** + * This method allows you to add a 2d optima to the list of optima + * + * @param x + * @param y + */ + protected void add2DOptimum(double x, double y) { + double[] point = new double[2]; + point[0] = x; + point[1] = y; + addOptimum(point); + } + + /** + * This method allows you to add a 2d optima to the list of optima + * + * @param point + */ + protected void addOptimum(double[] point) { + InterfaceDataTypeDouble tmpIndy; + tmpIndy = (InterfaceDataTypeDouble) ((AbstractEAIndividual) this.template).clone(); + tmpIndy.SetDoubleGenotype(point); + ((AbstractEAIndividual) tmpIndy).setFitness(evalUnnormalized(point)); + if (((AbstractEAIndividual) tmpIndy).getFitness(0) >= globalOptimum) { + globalOptimum = ((AbstractEAIndividual) tmpIndy).getFitness(0); + if (makeGlobalOptUnreachable) { + double tmp = globalOptimum; + double dx = 1e-30; + while (tmp == globalOptimum) { + // this increases the optimum until there is a real difference. + // tries to avoid zero y-values which break the logarithmic plot + tmp += dx; + dx *= 10; + } + globalOptimum = tmp; } - } + } + if (isDoRotation()) { + point = inverseRotateMaybe(point); // theres an inverse rotation required + tmpIndy.SetDoubleGenotype(point); + } + this.listOfOptima.add(tmpIndy); + } - /** Ths method allows you to evaluate a simple bit string to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. - */ + /** + * This method will prepare the problem to return a list of all optima + * if possible and to return quality measures like NumberOfOptimaFound and + * the MaximumPeakRatio. When implementing, use the addOptimum(double[]) + * method for every optimum, as it keeps track the global optimum. + * This method will be called on initialization. + */ @Override - public double[] eval(double[] x) { - x = rotateMaybe(x); - double[] result = new double[1]; - result[0] = this.globalOptimum - evalUnnormalized(x)[0]; - return result; - } + public abstract void initListOfOptima(); - /** - * This method returns the unnormalized (and unrotated!) function value for an maximization problem. - * - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. - */ - public abstract double[] evalUnnormalized(double[] x); - - @Override - public String[] getAdditionalDataHeader() { - return ToolBox.appendArrays(new String[]{"numOptsFound", "maxPeakRatio"}, super.getAdditionalDataHeader()); - } - - @Override - public String[] getAdditionalDataInfo() { - return ToolBox.appendArrays(new String[]{"The number of optima identified with default accuracy", "The maximum peak ratio measure in [0,1], best at 1, if multiple local optima are known."}, super.getAdditionalDataInfo()); - } - - @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - Object[] result = new Object[2]; - result[0] = this.getNumberOfFoundOptima((Population)pop); - result[1] = this.getMaximumPeakRatio((Population)pop); - return ToolBox.appendArrays(result, super.getAdditionalDataValue(pop)); - } - - - /********************************************************************************************************************** - * Implementation of InterfaceMultimodalProblemKnown - */ - - /** This method allows you to add a 2d optima to the list of optima - * @param x - * @param y - */ - protected void add2DOptimum(double x, double y) { - double[] point = new double[2]; - point[0] = x; - point[1] = y; - addOptimum(point); - } - - /** This method allows you to add a 2d optima to the list of optima - * @param point - */ - protected void addOptimum(double[] point) { - InterfaceDataTypeDouble tmpIndy; - tmpIndy = (InterfaceDataTypeDouble)((AbstractEAIndividual)this.template).clone(); - tmpIndy.SetDoubleGenotype(point); - ((AbstractEAIndividual)tmpIndy).setFitness(evalUnnormalized(point)); - if (((AbstractEAIndividual)tmpIndy).getFitness(0)>= globalOptimum) { - globalOptimum = ((AbstractEAIndividual)tmpIndy).getFitness(0); - if (makeGlobalOptUnreachable) { - double tmp= globalOptimum; - double dx = 1e-30; - while (tmp== globalOptimum) { - // this increases the optimum until there is a real difference. - // tries to avoid zero y-values which break the logarithmic plot - tmp+=dx; - dx *= 10; - } - globalOptimum = tmp; - } - } - if (isDoRotation()) { - point = inverseRotateMaybe(point); // theres an inverse rotation required - tmpIndy.SetDoubleGenotype(point); - } - this.listOfOptima.add(tmpIndy); - } - - /** - * This method will prepare the problem to return a list of all optima - * if possible and to return quality measures like NumberOfOptimaFound and - * the MaximumPeakRatio. When implementing, use the addOptimum(double[]) - * method for every optimum, as it keeps track the global optimum. - * This method will be called on initialization. - */ + /** + * This method returns a list of all optima as population + * + * @return population + */ @Override - public abstract void initListOfOptima(); + public Population getRealOptima() { + return this.listOfOptima; + } - /** This method returns a list of all optima as population - * @return population - */ - @Override - public Population getRealOptima() { - return this.listOfOptima; - } - /** * Return true if the full list of optima is available, else false. + * * @return */ @Override public boolean fullListAvailable() { - return ((getRealOptima()!=null) && (getRealOptima().size()>0)); + return ((getRealOptima() != null) && (getRealOptima().size() > 0)); } - /** This method returns the Number of Identified optima - * @param pop A population of possible solutions. - * @return int - */ + /** + * This method returns the Number of Identified optima + * + * @param pop A population of possible solutions. + * @return int + */ @Override - public int getNumberOfFoundOptima(Population pop) { - return getNoFoundOptimaOf(this, pop); - } - - public static int getNoFoundOptimaOf(InterfaceMultimodalProblemKnown mmProb, Population pop) { - List sols = PostProcess.getFoundOptima(pop, mmProb.getRealOptima(), mmProb.getDefaultAccuracy(), true); - return sols.size(); - } + public int getNumberOfFoundOptima(Population pop) { + return getNoFoundOptimaOf(this, pop); + } - /** - * This method returns the maximum peak ratio, which is the ratio of found fitness values corresponding to - * known optima with the internal epsilon criterion and the sum of all fitness values seen as maximization. - * Thus, if all optima are perfectly found, 1 is returned. If no optimum is found, zero is returned. - * A return value of 0.5 may mean, e.g., that half of n similar optima have been found perfectly, or that 1 major - * optimum of equal weight than all the others has been found perfectly, or that all optima have been found - * with about 50% accuracy, etc. - * - * @param pop A population of possible solutions. - * @return double - */ + public static int getNoFoundOptimaOf(InterfaceMultimodalProblemKnown mmProb, Population pop) { + List sols = PostProcess.getFoundOptima(pop, mmProb.getRealOptima(), mmProb.getDefaultAccuracy(), true); + return sols.size(); + } + + /** + * This method returns the maximum peak ratio, which is the ratio of found fitness values corresponding to + * known optima with the internal epsilon criterion and the sum of all fitness values seen as maximization. + * Thus, if all optima are perfectly found, 1 is returned. If no optimum is found, zero is returned. + * A return value of 0.5 may mean, e.g., that half of n similar optima have been found perfectly, or that 1 major + * optimum of equal weight than all the others has been found perfectly, or that all optima have been found + * with about 50% accuracy, etc. + * + * @param pop A population of possible solutions. + * @return double + */ @Override - public double getMaximumPeakRatio(Population pop) { - if (!this.fullListAvailable()) { - return -1; + public double getMaximumPeakRatio(Population pop) { + if (!this.fullListAvailable()) { + return -1; + } else { + return getMaximumPeakRatio(this.getRealOptima(), pop, epsilon); + } + } + + /** + * Returns -1 if the full list is not available. Otherwise calculates the maximum peak ratio + * based on the full list of known optima. + * This assumes that the realOpts have fitness values assigned as for maximization and the + * population has fitness values assigned for minimization (mirrored by maximum fitness within realOpts). + *

+ * This is in analogy to the original implementation by F.Streichert. + * + * @param mmProb + * @param pop + * @param epsilon + * @return + */ + public static double getMaximumPeakRatio(Population realOpts, Population pop, double epsilon) { + double foundInvertedSum = 0, sumRealMaxima = 0; + if (realOpts == null || (realOpts.size() == 0)) { + return -1; + } + double tmp, maxOpt = realOpts.getEAIndividual(0).getFitness(0); + sumRealMaxima = maxOpt; + for (int i = 1; i < realOpts.size(); i++) { + // search for the maximum fitness (for the maximization problem) + // also sum up the fitness values + maxOpt = Math.max(maxOpt, realOpts.getEAIndividual(i).getFitness(0)); + sumRealMaxima += realOpts.getEAIndividual(i).getFitness(0); + if (realOpts.getEAIndividual(i).getFitness(0) < 0) { + EVAERROR.errorMsgOnce("Warning: avoid negative maxima in AbstractMultiModalProblemKnown!"); } - else { - return getMaximumPeakRatio(this.getRealOptima(), pop, epsilon); + } + AbstractEAIndividual[] optsFound = PostProcess.getFoundOptimaArray(pop, realOpts, epsilon, true); + for (int i = 0; i < realOpts.size(); i++) { + // sum up the found optimal fitness values + if (optsFound[i] != null) { + tmp = (maxOpt - optsFound[i].getFitness(0)); + if (tmp < 0) { + EVAERROR.errorMsgOnce("warning: for the MPR calculation, negative fitness values may disturb the allover result (AbstractMultiModalProblemKnown)"); + } + foundInvertedSum += Math.max(0., tmp); } - } - - /** - * Returns -1 if the full list is not available. Otherwise calculates the maximum peak ratio - * based on the full list of known optima. - * This assumes that the realOpts have fitness values assigned as for maximization and the - * population has fitness values assigned for minimization (mirrored by maximum fitness within realOpts). - * - * This is in analogy to the original implementation by F.Streichert. - * - * @param mmProb - * @param pop - * @param epsilon - * @return - */ - public static double getMaximumPeakRatio(Population realOpts, Population pop, double epsilon) { - double foundInvertedSum = 0, sumRealMaxima = 0; - if (realOpts==null || (realOpts.size()==0)) { - return -1; + } + return foundInvertedSum / sumRealMaxima; + } + + /** + * Returns -1 if the full list is not available. Otherwise calculates the maximum peak ratio + * based on the full list of known optima. Assumes that both realOpts and population have fitness + * values assigned as in a maximization problem. This is the standard formulation of MPR. + * + * @param mmProb + * @param pop + * @param epsilon + * @return + */ + public static double getMaximumPeakRatioMaximization(Population realOpts, Population pop, double epsilon, int fitCrit) { + AbstractEAIndividual[] optsFound = PostProcess.getFoundOptimaArray(pop, realOpts, epsilon, true); + double mpr = 0; + for (int i = 0; i < realOpts.size(); i++) { + // sum up the specific optimal fitness values relative to optimal fitness + if (optsFound[i] != null) { + double tmp = optsFound[i].getFitness(fitCrit); + if (tmp < 0) { + EVAERROR.errorMsgOnce("warning: for the MPR calculation, negative fitness values may disturb the allover result (AbstractMultiModalProblemKnown)"); + } + mpr += (Math.max(0., tmp) / realOpts.getEAIndividual(i).getFitness(fitCrit)); } - double tmp, maxOpt = realOpts.getEAIndividual(0).getFitness(0); - sumRealMaxima = maxOpt; - for (int i=1; i fitThreshold) { + EVAERROR.errorMsgOnce("Warning: The fitness threshold to turn minimization fitness values into " + + "maximization values should be larger than any optimal fitness! (AbstractMultiModalProblemKnown)"); } - } - return foundInvertedSum/sumRealMaxima; - } - - /** - * Returns -1 if the full list is not available. Otherwise calculates the maximum peak ratio - * based on the full list of known optima. Assumes that both realOpts and population have fitness - * values assigned as in a maximization problem. This is the standard formulation of MPR. - * - * @param mmProb - * @param pop - * @param epsilon - * @return - */ - public static double getMaximumPeakRatioMaximization(Population realOpts, Population pop, double epsilon, int fitCrit) { - AbstractEAIndividual[] optsFound = PostProcess.getFoundOptimaArray(pop, realOpts, epsilon, true); - double mpr = 0; - for (int i=0; ifitThreshold) { - EVAERROR.errorMsgOnce("Warning: The fitness threshold to turn minimization fitness values into " + - "maximization values should be larger than any optimal fitness! (AbstractMultiModalProblemKnown)"); - } - if (i==0 || (minOpt>realFits[i])) { - minOpt = realFits[i]; - } - // check if the opt. was found and store the corr. found fitness - if (optsFound[i]!=null) { - foundFits[i] = new Double(optsFound[i].getFitness(fitCrit)); - } else { - foundFits[i]=fitThreshold; // note that it wasnt found -- will result in zero - } - } - // now we mirror all values with the threshold - provided they are below the threshold... - for (int i=0; irealFits[i] && (foundFits[i]-realFits[i]>1e-10)) { - // this can happen if the real fitness is wrong or if the threshold allows individuals close to better optima to - // be counted for actually inferior optima - System.err.println("Warning: found fitness is better than real fitness - wrong predefined solution or suboptimal epsilon-criterion? Diff was: " + (foundFits[i]-realFits[i])); - } - if ((realFits[i] < 0) || (foundFits[i] < 0)) { - EVAERROR.errorMsgOnce("warning: for the MPR calculation, negative fitness values may disturb the allover result (AbstractMultiModalProblemKnown)"); - } - } - // now we can call the standard calculation method - return getMaximumPeakRatioMaximization(realFits, foundFits); - } + if (i == 0 || (minOpt > realFits[i])) { + minOpt = realFits[i]; + } + // check if the opt. was found and store the corr. found fitness + if (optsFound[i] != null) { + foundFits[i] = new Double(optsFound[i].getFitness(fitCrit)); + } else { + foundFits[i] = fitThreshold; // note that it wasnt found -- will result in zero + } + } + // now we mirror all values with the threshold - provided they are below the threshold... + for (int i = 0; i < realOpts.size(); i++) { + realFits[i] = fitThreshold - realFits[i]; + foundFits[i] = fitThreshold - foundFits[i]; + if (foundFits[i] > realFits[i] && (foundFits[i] - realFits[i] > 1e-10)) { + // this can happen if the real fitness is wrong or if the threshold allows individuals close to better optima to + // be counted for actually inferior optima + System.err.println("Warning: found fitness is better than real fitness - wrong predefined solution or suboptimal epsilon-criterion? Diff was: " + (foundFits[i] - realFits[i])); + } + if ((realFits[i] < 0) || (foundFits[i] < 0)) { + EVAERROR.errorMsgOnce("warning: for the MPR calculation, negative fitness values may disturb the allover result (AbstractMultiModalProblemKnown)"); + } + } + // now we can call the standard calculation method + return getMaximumPeakRatioMaximization(realFits, foundFits); + } - /** - * @param epsilon the epsilon to set - */ + /** + * @param epsilon the epsilon to set + */ @Override - public void setDefaultAccuracy(double epsilon) { - super.SetDefaultAccuracy(epsilon); - } + public void setDefaultAccuracy(double epsilon) { + super.SetDefaultAccuracy(epsilon); + } - @Override - public int getProblemDimension() { - return problemDimension; - } + @Override + public int getProblemDimension() { + return problemDimension; + } } \ No newline at end of file diff --git a/src/eva2/optimization/problems/AbstractMultiObjectiveOptimizationProblem.java b/src/eva2/optimization/problems/AbstractMultiObjectiveOptimizationProblem.java index 809925ab..f0799daf 100644 --- a/src/eva2/optimization/problems/AbstractMultiObjectiveOptimizationProblem.java +++ b/src/eva2/optimization/problems/AbstractMultiObjectiveOptimizationProblem.java @@ -17,6 +17,7 @@ import eva2.tools.ToolBox; import eva2.tools.chart2d.Chart2DDPointIconCircle; import eva2.tools.chart2d.Chart2DDPointIconText; import eva2.tools.chart2d.DPoint; + import java.awt.Color; import java.util.ArrayList; import java.util.Vector; @@ -32,120 +33,121 @@ import javax.swing.JFrame; */ public abstract class AbstractMultiObjectiveOptimizationProblem extends AbstractOptimizationProblem { - - /** - * Generated serial version identifier - */ - private static final long serialVersionUID = -6882081673229946521L; - - /** - * - * @author mkron - * - */ - class MultiObjectiveEvalThread extends Thread{ - AbstractMultiObjectiveOptimizationProblem prob; - AbstractEAIndividual ind; - Vector resultrep; - Population pop; - Semaphore m_Semaphore=null; - - public MultiObjectiveEvalThread(AbstractMultiObjectiveOptimizationProblem prob,AbstractEAIndividual ind,Vector resultrep, Population pop,Semaphore sema) { - this.ind = ind; - this.prob = prob; - this.resultrep = resultrep; - this.pop = pop; - this.m_Semaphore=sema; - } - + + /** + * Generated serial version identifier + */ + private static final long serialVersionUID = -6882081673229946521L; + + /** + * @author mkron + */ + class MultiObjectiveEvalThread extends Thread { + AbstractMultiObjectiveOptimizationProblem prob; + AbstractEAIndividual ind; + Vector resultrep; + Population pop; + Semaphore m_Semaphore = null; + + public MultiObjectiveEvalThread(AbstractMultiObjectiveOptimizationProblem prob, AbstractEAIndividual ind, Vector resultrep, Population pop, Semaphore sema) { + this.ind = ind; + this.prob = prob; + this.resultrep = resultrep; + this.pop = pop; + this.m_Semaphore = sema; + } + @Override - public void run() { - double[] fitness; - prob.evaluate(ind); - resultrep.add(ind); - - - fitness = ind.getFitness(); - // check and update border if necessary - if (m_Border == null) { - prob.m_Border = new double[fitness.length][2]; - } - else if (fitness.length != prob.m_Border.length) { - //System.out.println("AbstractMOOptimizationProblem: Warning fitness.length("+fitness.length+") doesn't fit border.length("+this.m_Border.length+")"); - //System.out.println("Resetting the border!"); - prob.m_Border = new double[fitness.length][2]; - } - for (int j = 0; j < fitness.length; j++) { + public void run() { + double[] fitness; + prob.evaluate(ind); + resultrep.add(ind); + + + fitness = ind.getFitness(); + // check and update border if necessary + if (m_Border == null) { + prob.m_Border = new double[fitness.length][2]; + } else if (fitness.length != prob.m_Border.length) { + //System.out.println("AbstractMOOptimizationProblem: Warning fitness.length("+fitness.length+") doesn't fit border.length("+this.m_Border.length+")"); + //System.out.println("Resetting the border!"); + prob.m_Border = new double[fitness.length][2]; + } + for (int j = 0; j < fitness.length; j++) { // if ((this.m_Border[j][0] > fitness[j]) || (this.m_Border[j][1] < fitness[j])) { // System.out.println("border... " + j); // System.out.println(this.m_Border[j][0]+" > "+fitness[j]); // System.out.println(this.m_Border[j][1]+" < "+fitness[j]); // } - prob.m_Border[j][0] = Math.min(prob.m_Border[j][0], fitness[j]); - prob.m_Border[j][1] = Math.max(prob.m_Border[j][1], fitness[j]); - } - pop.incrFunctionCalls(); - m_Semaphore.release(); - - } - } - - protected InterfaceMOSOConverter m_MOSOConverter = new MOSONoConvert(); - protected InterfaceParetoFrontMetric m_Metric = new MetricS(); - transient protected Population m_ParetoFront = new Population(); - public ArrayList m_AreaConst4Parallelization = new ArrayList(); - protected int m_OutputDimension = 2; - double m_defaultBorderLow = 0; - double m_defaultBorderHigh = 5; - - transient protected double[][] m_Border; - transient protected Plot m_Plot; - transient protected JFrame m_Result; - protected transient boolean m_Show = false; + prob.m_Border[j][0] = Math.min(prob.m_Border[j][0], fitness[j]); + prob.m_Border[j][1] = Math.max(prob.m_Border[j][1], fitness[j]); + } + pop.incrFunctionCalls(); + m_Semaphore.release(); + + } + } + + protected InterfaceMOSOConverter m_MOSOConverter = new MOSONoConvert(); + protected InterfaceParetoFrontMetric m_Metric = new MetricS(); + transient protected Population m_ParetoFront = new Population(); + public ArrayList m_AreaConst4Parallelization = new ArrayList(); + protected int m_OutputDimension = 2; + double m_defaultBorderLow = 0; + double m_defaultBorderHigh = 5; + + transient protected double[][] m_Border; + transient protected Plot m_Plot; + transient protected JFrame m_Result; + protected transient boolean m_Show = false; public AbstractMultiObjectiveOptimizationProblem(double borderHigh) { - super(); - m_defaultBorderHigh=borderHigh; + super(); + m_defaultBorderHigh = borderHigh; this.template = new ESIndividualDoubleData(); makeBorder(); if (this.m_Show) { this.initProblemFrame(); } } - + public AbstractMultiObjectiveOptimizationProblem() { - this(5.); + this(5.); } - /** This method allows you to toggle pareto-front visualisation on and off. - * @param b True if the pareto-front is to be shown. + /** + * This method allows you to toggle pareto-front visualisation on and off. + * + * @param b True if the pareto-front is to be shown. */ public void setShowParetoFront(boolean b) { this.m_Show = b; if (this.m_Show) { this.initProblemFrame(); - } - else if (this.m_Plot != null) { + } else if (this.m_Plot != null) { this.m_Plot.dispose(); this.m_Plot = null; } } - + public boolean isShowParetoFront() { return this.m_Show; } - + public String showParetoFrontTipText() { return "Toggles the pareto-front visualisation."; } - - /** This method returns a deep clone of the problem. - * @return the clone + + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public abstract Object clone(); - /** This method inits the Problem to log multiruns for the s-Metric it + /** + * This method inits the Problem to log multiruns for the s-Metric it * is necessary to give the border to get reliable results. * also it is necessary to init the local Pareto-Front and the * problem frame (i'll provide a default implementation here. @@ -168,17 +170,19 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract this.m_Border[i][1] = getUpperBorder(i); } } - + protected double getUpperBorder(int i) { - return m_defaultBorderHigh; - } + return m_defaultBorderHigh; + } protected double getLowerBorder(int i) { - return m_defaultBorderLow; - } + return m_defaultBorderLow; + } - /** This method checks whether the problem has truely evaluated + /** + * This method checks whether the problem has truely evaluated * to a multiobjective problem + * * @return true if all individuals are multiobjective */ public static boolean isPopulationMultiObjective(Population pop) { @@ -190,7 +194,7 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract } int bestFitLen = pop.getBestFitness().length, tmpFitLen; for (int i = 0; i < pop.size(); i++) { - tmpFitLen = ((AbstractEAIndividual)pop.get(i)).getFitness().length; + tmpFitLen = ((AbstractEAIndividual) pop.get(i)).getFitness().length; if (tmpFitLen <= 1) { //System.out.println("There is a single objective individual in the population!"); return false; @@ -203,35 +207,35 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract return true; } - /** This method will reset the local Pareto-Front + /** + * This method will reset the local Pareto-Front * This caused a lot of trouble for the DeNovo Approach of MOCCO */ public void resetParetoFront() { this.m_ParetoFront = new Population(); } - + @Override public void evaluatePopulationStart(Population population) { - super.evaluatePopulationStart(population); - if (this.m_Show && (this.m_Plot==null)) { + super.evaluatePopulationStart(population); + if (this.m_Show && (this.m_Plot == null)) { this.initProblemFrame(); } } - + @Override public void evaluatePopulationEnd(Population population) { - super.evaluatePopulationEnd(population); - double[] fitness; - - for (int i = 0; i < population.size(); i++) { - // check and update border if necessary - AbstractEAIndividual tmpIndy = (AbstractEAIndividual) population.get(i); + super.evaluatePopulationEnd(population); + double[] fitness; + + for (int i = 0; i < population.size(); i++) { + // check and update border if necessary + AbstractEAIndividual tmpIndy = (AbstractEAIndividual) population.get(i); fitness = tmpIndy.getFitness(); // check and update border if necessary if (m_Border == null) { this.m_Border = new double[fitness.length][2]; - } - else if (fitness.length != this.m_Border.length) { + } else if (fitness.length != this.m_Border.length) { //System.out.println("AbstractMOOptimizationProblem: Warning fitness.length("+fitness.length+") doesn't fit border.length("+this.m_Border.length+")"); //System.out.println("Resetting the border!"); this.m_Border = new double[fitness.length][2]; @@ -246,7 +250,7 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract this.m_Border[j][1] = Math.max(this.m_Border[j][1], fitness[j]); } } - + // So what is the problem: // on the one hand i want to log the pareto-front in the // multiobjective case @@ -256,7 +260,7 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract // could be pretty many // currently the problem should be multi-criteria - logPopToParetoFront(m_ParetoFront, population); + logPopToParetoFront(m_ParetoFront, population); // Sometimes you want to transform a multiobjective optimization problem // into a single objective one, this way single objective optimization @@ -264,28 +268,29 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract this.m_MOSOConverter.convertMultiObjective2SingleObjective(population); if (this.m_Show) { - if (m_Plot.isValid()) { + if (m_Plot.isValid()) { AbstractMultiObjectiveOptimizationProblem.drawProblem(population, m_Plot, this); - } + } } } /** * Unite the given population with the given pareto front and replace pFront with the new pareto front. - * This variant uses ArchivingNSGA + * This variant uses ArchivingNSGA + * * @param pFront * @param pop */ - public static void logPopToParetoFront(Population pFront, Population pop) { - // log the pareto-front + public static void logPopToParetoFront(Population pFront, Population pop) { + // log the pareto-front if (AbstractMultiObjectiveOptimizationProblem.isPopulationMultiObjective(pop)) { if (pFront == null) { System.err.println("Error, give at least an empty population as initial pareto front"); } if (pFront.getArchive() == null) { - pFront.SetArchive(new Population(100)); + pFront.SetArchive(new Population(100)); } - Population tmpPop=new Population(pop.size()); + Population tmpPop = new Population(pop.size()); tmpPop.addPopulation(pop); tmpPop.addPopulation(pFront); ArchivingNSGA archiving = new ArchivingNSGA(); @@ -293,9 +298,10 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract pFront.clear(); pFront.addPopulation(tmpPop.getArchive()); } - } - - /** This method will init the problem specific visualisation of the problem + } + + /** + * This method will init the problem specific visualisation of the problem */ public void initProblemFrame() { double[] tmpD = new double[2]; @@ -309,9 +315,11 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract this.initAdditionalData(this.m_Plot, 10); } - /** This method will plot a reference solutions or something like it - * @param plot The plot where you can draw your stuff. - * @param index The first index where you can draw your stuff + /** + * This method will plot a reference solutions or something like it + * + * @param plot The plot where you can draw your stuff. + * @param index The first index where you can draw your stuff */ public void initAdditionalData(Plot plot, int index) { // for example plot the current population @@ -319,55 +327,58 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract plot.setUnconnectedPoint(0, 0, index); } - /** This method will draw the current state of the optimization process - * @param pFront The current population + /** + * This method will draw the current state of the optimization process + * + * @param pFront The current population */ public static void drawProblem(Population pFront, Population archive, Plot plot) { - ArchivingAllDominating tmpArch = new ArchivingAllDominating(); + ArchivingAllDominating tmpArch = new ArchivingAllDominating(); // Population tmpPop = null; - // i want to plot the pareto front for MOEA and other strategies - // but i have to differentiate between the case where - // there is a true MOEA at work and where the - // MOOpt was converted into a SOOpt - if (pFront != null && (plot != null)) { - // i got either a multiobjective population or a multiobjective local population - plot.clearAll(); - tmpArch.plotParetoFront(pFront, plot); - if (archive != null) { - GraphPointSet mySet = new GraphPointSet(10, plot.getFunctionArea()); - DPoint myPoint; - Chart2DDPointIconCircle icon; - double[] tmpD; - mySet.setConnectedMode(false); - for (int i = 0; i < archive.size(); i++) { - icon = new Chart2DDPointIconCircle(); - tmpD = ((AbstractEAIndividual)archive.get(i)).getFitness(); - if (tmpD.length<2) { - throw new RuntimeException("Error, problem seems not to be multi-objective, pareto front plot not possible!"); - } - myPoint = new DPoint(tmpD[0], tmpD[1]); - if (((AbstractEAIndividual)archive.get(i)).getConstraintViolation() > 0) { - icon.setBorderColor(Color.RED); - icon.setFillColor(Color.RED); - } else { - icon.setBorderColor(Color.BLACK); - icon.setFillColor(Color.BLACK); - } - myPoint.setIcon(icon); - mySet.addDPoint(myPoint); - } - } - } + // i want to plot the pareto front for MOEA and other strategies + // but i have to differentiate between the case where + // there is a true MOEA at work and where the + // MOOpt was converted into a SOOpt + if (pFront != null && (plot != null)) { + // i got either a multiobjective population or a multiobjective local population + plot.clearAll(); + tmpArch.plotParetoFront(pFront, plot); + if (archive != null) { + GraphPointSet mySet = new GraphPointSet(10, plot.getFunctionArea()); + DPoint myPoint; + Chart2DDPointIconCircle icon; + double[] tmpD; + mySet.setConnectedMode(false); + for (int i = 0; i < archive.size(); i++) { + icon = new Chart2DDPointIconCircle(); + tmpD = ((AbstractEAIndividual) archive.get(i)).getFitness(); + if (tmpD.length < 2) { + throw new RuntimeException("Error, problem seems not to be multi-objective, pareto front plot not possible!"); + } + myPoint = new DPoint(tmpD[0], tmpD[1]); + if (((AbstractEAIndividual) archive.get(i)).getConstraintViolation() > 0) { + icon.setBorderColor(Color.RED); + icon.setFillColor(Color.RED); + } else { + icon.setBorderColor(Color.BLACK); + icon.setFillColor(Color.BLACK); + } + myPoint.setIcon(icon); + mySet.addDPoint(myPoint); + } + } + } } - - /** + + /** * This method will draw the current state of the optimization process - * @param p The current population + * + * @param p The current population */ public static void drawProblem(Population p, Plot plot, AbstractMultiObjectiveOptimizationProblem moProblem) { - ArchivingAllDominating tmpArch = new ArchivingAllDominating(); - Population tmpPop = null; + ArchivingAllDominating tmpArch = new ArchivingAllDominating(); + Population tmpPop = null; if (p.getGeneration() > 2) { // m_Plot = new eva2.gui.plot.Plot("Multiobjective Optimization", "Y1", "Y2"); @@ -389,7 +400,7 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract tmpArch.addElementsToArchive(tmpPop); tmpPop = tmpPop.getArchive(); } - + if (tmpPop != null) { drawProblem(tmpPop, p.getArchive(), plot); } @@ -399,19 +410,20 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract } } - /** + /** * This method will plot a reference solutions or something like it - * @param plot The plot where you can draw your stuff. - * @param index The first index where you can draw your stuff + * + * @param plot The plot where you can draw your stuff. + * @param index The first index where you can draw your stuff */ public void drawAdditionalData(Plot plot, Population pop, int index) { double[] tmpFitness; // for example plot the current population plot.clearGraph(index); for (int i = 0; i < pop.size(); i++) { - tmpFitness = ((AbstractEAIndividual)pop.get(i)).getFitness(); + tmpFitness = ((AbstractEAIndividual) pop.get(i)).getFitness(); if (tmpFitness.length <= 1) { - tmpFitness = (double[])((AbstractEAIndividual)pop.get(i)).getData("MOFitness"); + tmpFitness = (double[]) ((AbstractEAIndividual) pop.get(i)).getData("MOFitness"); } plot.setUnconnectedPoint(tmpFitness[0], tmpFitness[1], index); } @@ -422,88 +434,89 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract /** * Plot the given population to a MO-plot with red dots for constraint violations and blue otherwise. * The given border is used to set plot limits but may be null. - * + * * @param plot * @param pop * @param border * @param index */ - public static void drawWithConstraints(Plot plot, Population pop, double[][] border, int index) { + public static void drawWithConstraints(Plot plot, Population pop, double[][] border, int index) { // for example plot the current population - double[][] trueFitness, moFitness; - double[] constraint; + double[][] trueFitness, moFitness; + double[] constraint; - GraphPointSet mySet = new GraphPointSet(index, plot.getFunctionArea()); - DPoint myPoint; - double tmp1; - - trueFitness = new double[pop.size()][]; - constraint = new double[pop.size()]; - if (((AbstractEAIndividual)pop.get(0)).hasData("MOFitness")) { - moFitness = new double[pop.size()][]; - } else { - moFitness = null; + GraphPointSet mySet = new GraphPointSet(index, plot.getFunctionArea()); + DPoint myPoint; + double tmp1; + + trueFitness = new double[pop.size()][]; + constraint = new double[pop.size()]; + if (((AbstractEAIndividual) pop.get(0)).hasData("MOFitness")) { + moFitness = new double[pop.size()][]; + } else { + moFitness = null; + } + for (int i = 0; i < pop.size(); i++) { + constraint[i] = ((AbstractEAIndividual) pop.get(i)).getConstraintViolation(); + trueFitness[i] = ((AbstractEAIndividual) pop.get(i)).getFitness(); + if (moFitness != null) { + moFitness[i] = (double[]) ((AbstractEAIndividual) pop.get(i)).getData("MOFitness"); } - for (int i = 0; i < pop.size(); i++) { - constraint[i] = ((AbstractEAIndividual)pop.get(i)).getConstraintViolation(); - trueFitness[i] = ((AbstractEAIndividual)pop.get(i)).getFitness(); - if (moFitness != null) { - moFitness[i] = (double[])((AbstractEAIndividual)pop.get(i)).getData("MOFitness"); + } + mySet.setConnectedMode(false); + for (int i = 0; i < trueFitness.length; i++) { + if (moFitness != null) { + // moso is active + if (checkValidAt(moFitness, i)) { + myPoint = new DPoint(moFitness[i][0], moFitness[i][1]); + tmp1 = Math.round(trueFitness[i][0] * 100) / 100.0; + addPoint(constraint, mySet, myPoint, i, "" + tmp1); + } + } else { + // no moso is active + if (checkValidAt(trueFitness, i)) { + myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); + addPoint(constraint, mySet, myPoint, i, ""); + } } - } - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - if (moFitness != null) { - // moso is active - if (checkValidAt(moFitness, i)) { - myPoint = new DPoint(moFitness[i][0], moFitness[i][1]); - tmp1 = Math.round(trueFitness[i][0] *100)/100.0; - addPoint(constraint, mySet, myPoint, i, ""+tmp1); - } - } else { - // no moso is active - if (checkValidAt(trueFitness, i)) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - addPoint(constraint, mySet, myPoint, i, ""); - } - } - } - if (border!= null) { - plot.setUnconnectedPoint(border[0][1], border[1][1], index+1); - plot.setUnconnectedPoint(border[0][0], border[1][0], index+1); - } + } + if (border != null) { + plot.setUnconnectedPoint(border[0][1], border[1][1], index + 1); + plot.setUnconnectedPoint(border[0][0], border[1][0], index + 1); + } } - /** - * Check whether the given fitness array contains valid double values at position i. - * - * @param fitArray - * @param i - * @return - */ - private static boolean checkValidAt(double[][] fitArray, int i) { - return !(new Double(fitArray[i][0]).isNaN()) && !(new Double(fitArray[i][1]).isNaN()) && - !(new Double(fitArray[i][0]).isInfinite()) && !(new Double(fitArray[i][1]).isInfinite()); - } + /** + * Check whether the given fitness array contains valid double values at position i. + * + * @param fitArray + * @param i + * @return + */ + private static boolean checkValidAt(double[][] fitArray, int i) { + return !(new Double(fitArray[i][0]).isNaN()) && !(new Double(fitArray[i][1]).isNaN()) && + !(new Double(fitArray[i][0]).isInfinite()) && !(new Double(fitArray[i][1]).isInfinite()); + } - private static void addPoint(double[] constraint, GraphPointSet mySet, - DPoint myPoint, int i, String text) { - Chart2DDPointIconCircle icon; - Chart2DDPointIconText tmp = new Chart2DDPointIconText(text); - icon = new Chart2DDPointIconCircle(); - if (constraint[i] > 0) { - icon.setBorderColor(Color.RED); - icon.setFillColor(Color.RED); - } else { - icon.setBorderColor(Color.BLUE); - icon.setFillColor(Color.BLUE); - } - tmp.setIcon(icon); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - - /** This method returns a double value that will be displayed in a fitness + private static void addPoint(double[] constraint, GraphPointSet mySet, + DPoint myPoint, int i, String text) { + Chart2DDPointIconCircle icon; + Chart2DDPointIconText tmp = new Chart2DDPointIconText(text); + icon = new Chart2DDPointIconCircle(); + if (constraint[i] > 0) { + icon.setBorderColor(Color.RED); + icon.setFillColor(Color.RED); + } else { + icon.setBorderColor(Color.BLUE); + icon.setFillColor(Color.BLUE); + } + tmp.setIcon(icon); + myPoint.setIcon(tmp); + mySet.addDPoint(myPoint); + } + + /** + * This method returns a double value that will be displayed in a fitness * plot. A fitness that is to be minimized with a global min of zero * would be best, since log y can be used. But the value can depend on the problem. */ @@ -521,7 +534,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract } } - /** This method return the local Pareto front + /** + * This method return the local Pareto front + * * @return the local Pareto-front log */ public Population getLocalParetoFront() { @@ -530,31 +545,32 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract @Override public String[] getAdditionalDataHeader() { - String[] superHd = super.getAdditionalDataHeader(); - return ToolBox.appendArrays(new String[]{"paretoMetricCurrent","paretoMetricFront"}, superHd); + String[] superHd = super.getAdditionalDataHeader(); + return ToolBox.appendArrays(new String[]{"paretoMetricCurrent", "paretoMetricFront"}, superHd); } @Override public Object[] getAdditionalDataValue(PopulationInterface pop) { - Object[] result = new Object[2]; - if (m_MOSOConverter!=null && !(m_MOSOConverter instanceof MOSONoConvert)) { - result[0]=Double.NaN; result[1]=Double.NaN; - } else { - result[0] = this.calculateMetric((Population)pop); - result[1] = this.calculateMetric(getLocalParetoFront()); - } - return ToolBox.appendArrays(result, super.getAdditionalDataValue(pop)); + Object[] result = new Object[2]; + if (m_MOSOConverter != null && !(m_MOSOConverter instanceof MOSONoConvert)) { + result[0] = Double.NaN; + result[1] = Double.NaN; + } else { + result[0] = this.calculateMetric((Population) pop); + result[1] = this.calculateMetric(getLocalParetoFront()); + } + return ToolBox.appendArrays(result, super.getAdditionalDataValue(pop)); } - + /* * (non-Javadoc) * @see eva2.optimization.problems.AbstractOptimizationProblem#getAdditionalDataInfo(eva2.optimization.PopulationInterface) */ @Override public String[] getAdditionalDataInfo() { - String[] superInfo = super.getAdditionalDataInfo(); - return ToolBox.appendArrays(new String[]{"Pareto metric on the current population (per generation)", - "Pareto metric on the collected pareto front"}, superInfo); + String[] superInfo = super.getAdditionalDataInfo(); + return ToolBox.appendArrays(new String[]{"Pareto metric on the current population (per generation)", + "Pareto metric on the collected pareto front"}, superInfo); } /* @@ -562,31 +578,34 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract * @see eva2.optimization.problems.InterfaceOptimizationProblem#getStringRepresentationForProblem(eva2.optimization.strategies.InterfaceOptimizer) */ @Override - public String getStringRepresentationForProblem(InterfaceOptimizer opt) { - // TODO Auto-generated method stub - return null; - } + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + // TODO Auto-generated method stub + return null; + } - /** - * - * @param pop - * @return - */ - public double calculateMetric(Population pop) { - if (pop==null || (pop.size()==0)) { - return Double.NaN; - } + /** + * @param pop + * @return + */ + public double calculateMetric(Population pop) { + if (pop == null || (pop.size() == 0)) { + return Double.NaN; + } return this.m_Metric.calculateMetricOn(pop, this); } - /** This method should return the objective space range + /** + * This method should return the objective space range + * * @return The objective space range */ public double[][] getObjectiveSpaceRange() { return this.m_Border; } - /** This method should return the output dimension + /** + * This method should return the output dimension + * * @return The output dimension */ public int getOutputDimension() { @@ -619,30 +638,38 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract // return result; // } - /** This method allows you to set a Multiobjective to + /** + * This method allows you to set a Multiobjective to * Singleobjective converter if you choose to. - * @param b The new MO2SO converter. + * + * @param b The new MO2SO converter. */ public void setMOSOConverter(InterfaceMOSOConverter b) { this.m_MOSOConverter = b; this.m_MOSOConverter.setOutputDimension(this.m_OutputDimension); } + public InterfaceMOSOConverter getMOSOConverter() { return this.m_MOSOConverter; } + public String mOSOConverterTipText() { return "Choose a Multiobjective to Singleobjective converter."; } - /** This method allows you to choose the metric. - * @param b The new metric. + /** + * This method allows you to choose the metric. + * + * @param b The new metric. */ public void setMetric(InterfaceParetoFrontMetric b) { this.m_Metric = b; } + public InterfaceParetoFrontMetric getMetric() { return this.m_Metric; } + public String metricTipText() { return "Choose the metric to use."; } diff --git a/src/eva2/optimization/problems/AbstractOptimizationProblem.java b/src/eva2/optimization/problems/AbstractOptimizationProblem.java index cd202688..9177115c 100644 --- a/src/eva2/optimization/problems/AbstractOptimizationProblem.java +++ b/src/eva2/optimization/problems/AbstractOptimizationProblem.java @@ -24,6 +24,7 @@ import eva2.optimization.operator.terminators.PopulationMeasureTerminator.Stagna import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.ToolBox; + import java.awt.BorderLayout; import java.io.Serializable; import java.util.Vector; @@ -43,181 +44,194 @@ import javax.swing.JTextArea; * To change this template use Options | File Templates. */ public abstract class AbstractOptimizationProblem implements InterfaceOptimizationProblem, Serializable { - class EvalThread extends Thread { - AbstractOptimizationProblem prob; - AbstractEAIndividual ind; - Population population; - Semaphore semaphore; - - public EvalThread(AbstractOptimizationProblem prob, AbstractEAIndividual ind, Population pop,Semaphore sema) { - this.ind = ind; - this.prob = prob; - this.population = pop; - this.semaphore =sema; - } - + class EvalThread extends Thread { + AbstractOptimizationProblem prob; + AbstractEAIndividual ind; + Population population; + Semaphore semaphore; + + public EvalThread(AbstractOptimizationProblem prob, AbstractEAIndividual ind, Population pop, Semaphore sema) { + this.ind = ind; + this.prob = prob; + this.population = pop; + this.semaphore = sema; + } + @Override - public void run() { - prob.evaluate(ind); - population.incrFunctionCalls(); - semaphore.release(); - } - - } - - /** - * Tag for data fields concerning a solution to an abstract optimization problem. - */ - public static final String STAT_SOLUTION_HEADER = "solution"; - /** - * Store the old fitness array before evaluation. - */ - public static final String OLD_FITNESS_KEY = "oldFitness"; - - private int parallelthreads = 1; - + public void run() { + prob.evaluate(ind); + population.incrFunctionCalls(); + semaphore.release(); + } + + } + + /** + * Tag for data fields concerning a solution to an abstract optimization problem. + */ + public static final String STAT_SOLUTION_HEADER = "solution"; + /** + * Store the old fitness array before evaluation. + */ + public static final String OLD_FITNESS_KEY = "oldFitness"; + + private int parallelthreads = 1; + protected AbstractEAIndividual template = null; // private transient ArrayList changeListeners = null; - private double defaultAccuracy = 0.001; // default accuracy for identifying optima. + private double defaultAccuracy = 0.001; // default accuracy for identifying optima. - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public abstract Object clone(); public int getParallelThreads() { - return parallelthreads; - } + return parallelthreads; + } - public void setParallelThreads(int parallelthreads) { - this.parallelthreads = parallelthreads; - } - - public String parallelThreadsTipText() { - return "Set the number of threaded parallel function evaluations - interesting for slow functions and generational optimizers."; - } + public void setParallelThreads(int parallelthreads) { + this.parallelthreads = parallelthreads; + } - /** - * This method initializes the problem instance. - * If you override it, make sure to call the super method! + public String parallelThreadsTipText() { + return "Set the number of threaded parallel function evaluations - interesting for slow functions and generational optimizers."; + } + + /** + * This method initializes the problem instance. + * If you override it, make sure to call the super method! */ @Override public abstract void initializeProblem(); /******************** The most important methods ****************************************/ - /** This method inits a given population - * @param population The populations that is to be inited + /** + * This method inits a given population + * + * @param population The populations that is to be inited */ @Override public abstract void initializePopulation(Population population); - /** This method evaluates a given population and set the fitness values + /** + * This method evaluates a given population and set the fitness values * accordingly - * @param population The population that is to be evaluated. + * + * @param population The population that is to be evaluated. */ @Override public void evaluate(Population population) { - AbstractEAIndividual tmpIndy; + AbstractEAIndividual tmpIndy; evaluatePopulationStart(population); - + if (this.parallelthreads > 1) { - Vector queue = new Vector(population.size()); - Semaphore sema=new Semaphore(0); - ExecutorService pool = Executors.newFixedThreadPool(parallelthreads); - int cntIndies=0; - for (; cntIndies < population.size(); cntIndies++){ - AbstractEAIndividual tmpindy = (AbstractEAIndividual)population.get(cntIndies); - tmpindy.resetConstraintViolation(); - EvalThread evalthread = new EvalThread(this,tmpindy,population,sema); - pool.execute(evalthread); - } - try { - sema.acquire(cntIndies); - } catch (InterruptedException e) { - e.printStackTrace(); - throw new RuntimeException("Threading error in AbstractOptimizationProblem: " + e.getMessage()); - } - pool.shutdownNow(); + Vector queue = new Vector(population.size()); + Semaphore sema = new Semaphore(0); + ExecutorService pool = Executors.newFixedThreadPool(parallelthreads); + int cntIndies = 0; + for (; cntIndies < population.size(); cntIndies++) { + AbstractEAIndividual tmpindy = (AbstractEAIndividual) population.get(cntIndies); + tmpindy.resetConstraintViolation(); + EvalThread evalthread = new EvalThread(this, tmpindy, population, sema); + pool.execute(evalthread); + } + try { + sema.acquire(cntIndies); + } catch (InterruptedException e) { + e.printStackTrace(); + throw new RuntimeException("Threading error in AbstractOptimizationProblem: " + e.getMessage()); + } + pool.shutdownNow(); } else { - for (int i = 0; i < population.size(); i++) { - tmpIndy = (AbstractEAIndividual) population.get(i); - tmpIndy.putData(OLD_FITNESS_KEY, tmpIndy.getFitness()); - synchronized (tmpIndy) { - tmpIndy.resetConstraintViolation(); - this.evaluate(tmpIndy); - } - population.incrFunctionCalls(); - } + for (int i = 0; i < population.size(); i++) { + tmpIndy = (AbstractEAIndividual) population.get(i); + tmpIndy.putData(OLD_FITNESS_KEY, tmpIndy.getFitness()); + synchronized (tmpIndy) { + tmpIndy.resetConstraintViolation(); + this.evaluate(tmpIndy); + } + population.incrFunctionCalls(); + } } - + evaluatePopulationEnd(population); } - + /** * Empty thunk for implementation in subclasses. This is called right before a population is evaluated. * Made public because some steady-state optimizers do not call evaluate(Population). * * @param population - */ - - public void evaluatePopulationStart(Population population) { - } + */ - /** + public void evaluatePopulationStart(Population population) { + } + + /** * Empty thunk for implementation in subclasses. This is called after a population was evaluated. * * @param population */ public void evaluatePopulationEnd(Population population) { } - - /** This method evaluate a single individual and sets the fitness values - * @param individual The individual that is to be evaluated + + /** + * This method evaluate a single individual and sets the fitness values + * + * @param individual The individual that is to be evaluated */ @Override public abstract void evaluate(AbstractEAIndividual individual); /** - * The default initialization method. Clone the given template individual, calls its init method - * and add it to the population until the target size is reached. Earlier individuals are removed. + * The default initialization method. Clone the given template individual, calls its init method + * and add it to the population until the target size is reached. Earlier individuals are removed. + * * @param population * @param template * @param prob */ - public static void defaultInitPopulation(Population population, AbstractEAIndividual template, InterfaceOptimizationProblem prob) { + public static void defaultInitPopulation(Population population, AbstractEAIndividual template, InterfaceOptimizationProblem prob) { AbstractEAIndividual tmpIndy; population.clear(); - + for (int i = 0; i < population.getTargetSize(); i++) { - tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)template).clone(); + tmpIndy = (AbstractEAIndividual) ((AbstractEAIndividual) template).clone(); tmpIndy.init(prob); population.add(tmpIndy); } // population init must be last // it set's fitcalls and generation to zero population.init(); - } - + } + /******************** Some output methods *******************************************/ - /** This method allows you to output a string that describes a found solution + /** + * This method allows you to output a string that describes a found solution * in a way that is most suitable for a given problem. - * @param individual The individual that is to be shown. + * + * @param individual The individual that is to be shown. * @return The description. */ @Override public String getSolutionRepresentationFor(AbstractEAIndividual individual) { - return AbstractEAIndividual.getDefaultStringRepresentation(individual); + return AbstractEAIndividual.getDefaultStringRepresentation(individual); } - /** This method returns a double value that will be displayed in a fitness + /** + * This method returns a double value that will be displayed in a fitness * plot. A fitness that is to be minimized with a global min of zero * would be best, since log y can be used. But the value can depend on the problem. - * @param pop The population that is to be refined. + * + * @param pop The population that is to be refined. * @return Double value */ @Override @@ -225,136 +239,141 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati return new Double(pop.getBestEAIndividual().getFitness(0)); } - /** This method returns the header for the additional data that is to be written into a file - * @param pop The population that is to be refined. + /** + * This method returns the header for the additional data that is to be written into a file + * + * @param pop The population that is to be refined. * @return String */ @Override public String[] getAdditionalDataHeader() { - String[] header = null; - if (this instanceof InterfaceInterestingHistogram) { - header = new String[]{STAT_SOLUTION_HEADER,"histogram","score"}; - } - else { + String[] header = null; + if (this instanceof InterfaceInterestingHistogram) { + header = new String[]{STAT_SOLUTION_HEADER, "histogram", "score"}; + } else { header = new String[]{STAT_SOLUTION_HEADER}; } - - header = (String[])checkAndAppendAdd(0, getIndividualTemplate(), header, null); - header = (String[])checkAndAppendAdd(0, getIndividualTemplate().getCrossoverOperator(), header, null); - header = (String[])checkAndAppendAdd(0, getIndividualTemplate().getMutationOperator(), header, null); - return header; + + header = (String[]) checkAndAppendAdd(0, getIndividualTemplate(), header, null); + header = (String[]) checkAndAppendAdd(0, getIndividualTemplate().getCrossoverOperator(), header, null); + header = (String[]) checkAndAppendAdd(0, getIndividualTemplate().getMutationOperator(), header, null); + return header; } - + /** * Generic method to append additional information of another object. - * + * * @param type indicate header (0), info (1), or value (2) - * @param o the object to retrieve data from - * @param dat the data array to which to append to - * @param pop the current population + * @param o the object to retrieve data from + * @param dat the data array to which to append to + * @param pop the current population * @return */ private static Object[] checkAndAppendAdd(int type, Object o, Object[] dat, PopulationInterface pop) { - if (o instanceof InterfaceAdditionalPopulationInformer) { - switch(type) { - case 0: // header - return ToolBox.appendArrays((String[])dat, (String[])((InterfaceAdditionalPopulationInformer)o).getAdditionalDataHeader()); - case 1: // info - return ToolBox.appendArrays((String[])dat, (String[])((InterfaceAdditionalPopulationInformer)o).getAdditionalDataInfo()); - case 2: // value - return ToolBox.appendArrays(dat, ((InterfaceAdditionalPopulationInformer)o).getAdditionalDataValue(pop)); - default: - System.err.println("Error, invalid type in AbstractOptimizationProblem.appendAdd"); - return dat; - } - } else { + if (o instanceof InterfaceAdditionalPopulationInformer) { + switch (type) { + case 0: // header + return ToolBox.appendArrays((String[]) dat, (String[]) ((InterfaceAdditionalPopulationInformer) o).getAdditionalDataHeader()); + case 1: // info + return ToolBox.appendArrays((String[]) dat, (String[]) ((InterfaceAdditionalPopulationInformer) o).getAdditionalDataInfo()); + case 2: // value + return ToolBox.appendArrays(dat, ((InterfaceAdditionalPopulationInformer) o).getAdditionalDataValue(pop)); + default: + System.err.println("Error, invalid type in AbstractOptimizationProblem.appendAdd"); + return dat; + } + } else { return dat; } } - - /** This method returns the header for the additional data that is to be written into a file - * @param pop The population that is to be refined. + + /** + * This method returns the header for the additional data that is to be written into a file + * + * @param pop The population that is to be refined. * @return String */ @Override public String[] getAdditionalDataInfo() { - String[] info=null; - if (this instanceof InterfaceInterestingHistogram) { + String[] info = null; + if (this instanceof InterfaceInterestingHistogram) { info = new String[]{"Representation of the current best individual", "Fitness histogram of the current population", "Fitness threshold based score of the current population"}; - } - else { + } else { info = new String[]{"Representation of the current best individual"}; } - - info = (String[])checkAndAppendAdd(1, getIndividualTemplate(), info, null); - info = (String[])checkAndAppendAdd(1, getIndividualTemplate().getCrossoverOperator(), info, null); - info = (String[])checkAndAppendAdd(1, getIndividualTemplate().getMutationOperator(), info, null); - return info; + + info = (String[]) checkAndAppendAdd(1, getIndividualTemplate(), info, null); + info = (String[]) checkAndAppendAdd(1, getIndividualTemplate().getCrossoverOperator(), info, null); + info = (String[]) checkAndAppendAdd(1, getIndividualTemplate().getMutationOperator(), info, null); + return info; } - - /** This method returns the additional data that is to be written into a file - * @param pop The population that is to be refined. + + /** + * This method returns the additional data that is to be written into a file + * + * @param pop The population that is to be refined. * @return String */ @Override public Object[] getAdditionalDataValue(PopulationInterface pop) { - String solStr = AbstractEAIndividual.getDefaultDataString(pop.getBestIndividual()); - Object[] vals = null; - if (this instanceof InterfaceInterestingHistogram) { - int fitCrit=0; - SolutionHistogram hist = ((InterfaceInterestingHistogram)this).getHistogram(); - if (pop.getBestFitness()[fitCrit] < hist.getUpperBound()) { - Population maybeFiltered = (Population)pop; - if (pop.size()>100) { // for efficiency reasons... - maybeFiltered = maybeFiltered.filterByFitness(hist.getUpperBound(), fitCrit); - } - Population sols = PostProcess.clusterBestUpdateHistogram((Population)maybeFiltered, this, hist, fitCrit, getDefaultAccuracy()); - } - vals = new Object[]{solStr, hist, hist.getScore()}; - } else { + String solStr = AbstractEAIndividual.getDefaultDataString(pop.getBestIndividual()); + Object[] vals = null; + if (this instanceof InterfaceInterestingHistogram) { + int fitCrit = 0; + SolutionHistogram hist = ((InterfaceInterestingHistogram) this).getHistogram(); + if (pop.getBestFitness()[fitCrit] < hist.getUpperBound()) { + Population maybeFiltered = (Population) pop; + if (pop.size() > 100) { // for efficiency reasons... + maybeFiltered = maybeFiltered.filterByFitness(hist.getUpperBound(), fitCrit); + } + Population sols = PostProcess.clusterBestUpdateHistogram((Population) maybeFiltered, this, hist, fitCrit, getDefaultAccuracy()); + } + vals = new Object[]{solStr, hist, hist.getScore()}; + } else { vals = new Object[]{solStr}; - } - - vals = checkAndAppendAdd(2, pop.getBestIndividual(), vals, pop); - vals = checkAndAppendAdd(2, ((AbstractEAIndividual)pop.getBestIndividual()).getCrossoverOperator(), vals, pop); - vals = checkAndAppendAdd(2, ((AbstractEAIndividual)pop.getBestIndividual()).getMutationOperator(), vals, pop); - return vals; + } + + vals = checkAndAppendAdd(2, pop.getBestIndividual(), vals, pop); + vals = checkAndAppendAdd(2, ((AbstractEAIndividual) pop.getBestIndividual()).getCrossoverOperator(), vals, pop); + vals = checkAndAppendAdd(2, ((AbstractEAIndividual) pop.getBestIndividual()).getMutationOperator(), vals, pop); + return vals; } /** * Convenience method, draws with undefined generation and function evaluation count. - * - * @see #drawIndividual(int, int, AbstractEAIndividual) + * * @param indy * @return + * @see #drawIndividual(int, int, AbstractEAIndividual) */ public JComponent drawIndividual(AbstractEAIndividual indy) { - return drawIndividual(-1, -1, indy); + return drawIndividual(-1, -1, indy); } - /** - * This method allows you to request a graphical representation for a given individual. - * The additional informations generation and funCalls are shown if they are >= 0. + /** + * This method allows you to request a graphical representation for a given individual. + * The additional informations generation and funCalls are shown if they are >= 0. * individual. - * @param generation generation of the individual or -1 - * @param funCalls function calls performed or -1 - * @param indy the individual to display + * + * @param generation generation of the individual or -1 + * @param funCalls function calls performed or -1 + * @param indy the individual to display * @return JComponent */ @Override public JComponent drawIndividual(int generation, int funCalls, AbstractEAIndividual indy) { - JPanel result = new JPanel(); + JPanel result = new JPanel(); result.setLayout(new BorderLayout()); - JTextArea area = new JTextArea(); - JScrollPane scroll = new JScrollPane(area); + JTextArea area = new JTextArea(); + JScrollPane scroll = new JScrollPane(area); String text = "Best Solution:\n"; if (generation >= 0) { - text+=" Generation: " + generation + "\n"; + text += " Generation: " + generation + "\n"; } if (funCalls >= 0) { - text+=" Evaluations: " + funCalls + "\n"; + text += " Evaluations: " + funCalls + "\n"; } text += this.getSolutionRepresentationFor(indy); area.setLineWrap(true); @@ -364,14 +383,16 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati return result; } - /** This method will report whether or not this optimization problem is truly + /** + * This method will report whether or not this optimization problem is truly * multi-objective + * * @return True if multi-objective, else false. */ @Override public boolean isMultiObjective() { if (this instanceof AbstractMultiObjectiveOptimizationProblem) { - if (((AbstractMultiObjectiveOptimizationProblem)this).getMOSOConverter() instanceof MOSONoConvert) { + if (((AbstractMultiObjectiveOptimizationProblem) this).getMOSOConverter() instanceof MOSONoConvert) { return true; } else { return false; @@ -380,183 +401,182 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati return false; } } - + /** * For some evaluation cases it may be necessary to inform the problem class about the optimizer in use. - * + * * @param opt */ public void informAboutOptimizer(InterfaceOptimizer opt) { - + } /** * This allows "anyone" to access the problem's individual template and set operators etc. * Subclasses may have a method getEAIndividual additionally with a more * specific interface signature, which makes sense for the GUI which decides - * on what classes to present to the user based on the interface signature. - * + * on what classes to present to the user based on the interface signature. + * * @return the problem's individual template */ public AbstractEAIndividual getIndividualTemplate() { - return template; + return template; } - + public String individualTemplateTipText() { - return "Choose the individual representation to use."; + return "Choose the individual representation to use."; } - + /** * This method extracts the individuals from a given population that are assumed to correspond to local or global optima. * Similar individuals are clustered together with a density based clustering method + * * @param pop * @param epsilonPhenoSpace maximal allowed improvement of an individual before considered premature (given as distance in the search space) - * @param epsilonFitConv if positive: additional absolute convergence criterion (fitness space) as termination criterion of the local search - * @param clusterSigma minimum cluster distance - * @param maxEvalsPerIndy maximum number of evaluations or -1 to take the maximum + * @param epsilonFitConv if positive: additional absolute convergence criterion (fitness space) as termination criterion of the local search + * @param clusterSigma minimum cluster distance + * @param maxEvalsPerIndy maximum number of evaluations or -1 to take the maximum + * @return * @see #isPotentialOptimumNMS(AbstractEAIndividual, double, double, int) - * @return */ - public static Population extractPotentialOptima(AbstractOptimizationProblem prob, Population pop, - double epsilonPhenoSpace, double epsilonFitConv, double clusterSigma, int maxEvalsPerIndy) { - Population potOptima = new Population(); - for (int i = 0; i < pop.size(); ++i){ - //System.out.println("Refining " + i + " of " + population.size()); - AbstractEAIndividual indy = pop.getEAIndividual(i); + public static Population extractPotentialOptima(AbstractOptimizationProblem prob, Population pop, + double epsilonPhenoSpace, double epsilonFitConv, double clusterSigma, int maxEvalsPerIndy) { + Population potOptima = new Population(); + for (int i = 0; i < pop.size(); ++i) { + //System.out.println("Refining " + i + " of " + population.size()); + AbstractEAIndividual indy = pop.getEAIndividual(i); // System.out.println("bef: " + indy.toString()); - boolean isConverged = AbstractOptimizationProblem.isPotentialOptimumNMS(prob, indy, epsilonPhenoSpace, epsilonFitConv, maxEvalsPerIndy); - if (isConverged) { - potOptima.addIndividual(indy); - if (!indy.hasData(PostProcess.movedDistanceKey)) { - System.err.println("Error, missing distance information in individual (AbstractOptimizationProblem.extractPotentialOptimum)"); - } - } - } - // cluster by the converged-to positions instead of the original ones - InterfaceClustering clustering = new ClusteringDensityBased(clusterSigma, 2, new IndividualDataMetric(PostProcess.movedToPositionKey)); - clustering = new ClusteringDensityBased(clusterSigma, 2); - if (clusterSigma > 0) { - return (Population)PostProcess.clusterBest(potOptima, clustering, 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); - } - else { - return potOptima; - } + boolean isConverged = AbstractOptimizationProblem.isPotentialOptimumNMS(prob, indy, epsilonPhenoSpace, epsilonFitConv, maxEvalsPerIndy); + if (isConverged) { + potOptima.addIndividual(indy); + if (!indy.hasData(PostProcess.movedDistanceKey)) { + System.err.println("Error, missing distance information in individual (AbstractOptimizationProblem.extractPotentialOptimum)"); + } + } + } + // cluster by the converged-to positions instead of the original ones + InterfaceClustering clustering = new ClusteringDensityBased(clusterSigma, 2, new IndividualDataMetric(PostProcess.movedToPositionKey)); + clustering = new ClusteringDensityBased(clusterSigma, 2); + if (clusterSigma > 0) { + return (Population) PostProcess.clusterBest(potOptima, clustering, 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); + } else { + return potOptima; + } } - - /** + + /** * This method estimates if the given individual is within epsilon of an optimum (local or global). - * The algorithm tries to improve the given individual locally. + * The algorithm tries to improve the given individual locally. * If it is possible to improve the individual such that its changed position is further than epsilon, - * the individual is considered premature. + * the individual is considered premature. * If not, the particle is assumed to correspond to a local or global optimum. - * - * @param orig individual that is to be tested - * @param epsilon maximal allowed improvement before considered premature (given as distance in the search space) - * @param mutationStepSize step size used to mutate the individual in one step - * (if < 0 a default value of 0.0001 is used) - * @param numOfFailures number of unsuccessful improvement steps in a row before an individual is considered to be locally unimproveable - * (if < 0 a default value of 100*problem dimensions is used ) + * + * @param orig individual that is to be tested + * @param epsilon maximal allowed improvement before considered premature (given as distance in the search space) + * @param mutationStepSize step size used to mutate the individual in one step + * (if < 0 a default value of 0.0001 is used) + * @param numOfFailures number of unsuccessful improvement steps in a row before an individual is considered to be locally unimproveable + * (if < 0 a default value of 100*problem dimensions is used ) * @return estimation if the given individual is within epsilon of an optimum (local or global) */ - public boolean isPotentialOptimum(AbstractEAIndividual orig, double epsilon, double mutationStepSize, int numOfFailures){ - int stepsCounter = 0; // could be used to limit the maximal number of steps overall - - // if not provided reasonable values use defaults: - if (mutationStepSize<0) { + public boolean isPotentialOptimum(AbstractEAIndividual orig, double epsilon, double mutationStepSize, int numOfFailures) { + int stepsCounter = 0; // could be used to limit the maximal number of steps overall + + // if not provided reasonable values use defaults: + if (mutationStepSize < 0) { mutationStepSize = 0.0001; - } - if (numOfFailures<0) { - numOfFailures = 100*AbstractEAIndividual.getDoublePositionShallow(this.template).length; - } // scales the effort with the number of problem dimensions - - AbstractEAIndividual indy = (AbstractEAIndividual)orig.clone(); - this.evaluate(indy); // indy may be evaluated in a normalised way... - - InterfaceDistanceMetric metric = new PhenotypeMetric(); - double overallDist = 0; - - InterfaceMutation mutator = new MutateESFixedStepSize(mutationStepSize); - - for (int i = 0; i < numOfFailures; ++i){ - // backup - AbstractEAIndividual old = (AbstractEAIndividual)indy.clone(); - // mutate - double tmpD = indy.getMutationProbability(); - indy.setMutationProbability(1.0); - mutator.mutate(indy); - ++stepsCounter; - indy.setMutationProbability(tmpD); - // evaluate - this.evaluate(indy); - - if (old.isDominatingDebConstraints(indy)) {// indy could not be improved - indy = (AbstractEAIndividual)old.clone(); - } else { // indy could be improved - i = 0; // the given number of unsuccessful improvement steps should occur in a row - overallDist = metric.distance(orig, indy); - //System.out.println(overallDist); - } - if (overallDist > epsilon) { - return false; // dont waste any more evaluations on this candidate - } - } - if (overallDist < epsilon) { - return true; } - else { + if (numOfFailures < 0) { + numOfFailures = 100 * AbstractEAIndividual.getDoublePositionShallow(this.template).length; + } // scales the effort with the number of problem dimensions + + AbstractEAIndividual indy = (AbstractEAIndividual) orig.clone(); + this.evaluate(indy); // indy may be evaluated in a normalised way... + + InterfaceDistanceMetric metric = new PhenotypeMetric(); + double overallDist = 0; + + InterfaceMutation mutator = new MutateESFixedStepSize(mutationStepSize); + + for (int i = 0; i < numOfFailures; ++i) { + // backup + AbstractEAIndividual old = (AbstractEAIndividual) indy.clone(); + // mutate + double tmpD = indy.getMutationProbability(); + indy.setMutationProbability(1.0); + mutator.mutate(indy); + ++stepsCounter; + indy.setMutationProbability(tmpD); + // evaluate + this.evaluate(indy); + + if (old.isDominatingDebConstraints(indy)) {// indy could not be improved + indy = (AbstractEAIndividual) old.clone(); + } else { // indy could be improved + i = 0; // the given number of unsuccessful improvement steps should occur in a row + overallDist = metric.distance(orig, indy); + //System.out.println(overallDist); + } + if (overallDist > epsilon) { + return false; // dont waste any more evaluations on this candidate + } + } + if (overallDist < epsilon) { + return true; + } else { return false; - } + } } - + /** * Refine a given individual using Nelder-Mead-Simplex local search. Return true, if the refined result is within a given * distance from the original individual in phenotype space. The maxEvaluations parameter gives the maximum evaluations - * for the local search. Using the epsilonFitConv parameter one may define a convergence criterion as PhenotypeConvergenceTerminator + * for the local search. Using the epsilonFitConv parameter one may define a convergence criterion as PhenotypeConvergenceTerminator * based on the given threshold and 100*dim evaluations, which is combined (using OR) with the evaluation counter. - * If maxEvaluations is smaller than zero, a maximum of 500*dim evaluations is employed. + * If maxEvaluations is smaller than zero, a maximum of 500*dim evaluations is employed. * Be aware that this may cost quite some runtime depending on the target * function. * A double value for the distance by which it was moved is added to the individual using the key PostProcess.movedDistanceKey. - * + * * @param orig - * @param epsilonPhenoSpace allowed distance for a solution moved by local search - * @param epsilonFitConv if the fitness changes below the threshold, the search is stopped earlier. Set to -1 to deactivate. - * @param maxEvaluations maximal number of evaluations or -1 + * @param epsilonPhenoSpace allowed distance for a solution moved by local search + * @param epsilonFitConv if the fitness changes below the threshold, the search is stopped earlier. Set to -1 to deactivate. + * @param maxEvaluations maximal number of evaluations or -1 * @return */ - public static boolean isPotentialOptimumNMS(AbstractOptimizationProblem prob, AbstractEAIndividual orig, double epsilonPhenoSpace, double epsilonFitConv, int maxEvaluations){ - - AbstractEAIndividual indy = (AbstractEAIndividual)orig.clone(); - prob.evaluate(indy); // indy may be evaluated in a normalised way... - - InterfaceDistanceMetric metric = new PhenotypeMetric(); - double overallDist = 0; - double initRelPerturb = -1; - int dim = -1; - if (orig instanceof InterfaceDataTypeDouble) { - initRelPerturb = epsilonPhenoSpace*0.5; - dim=((InterfaceDataTypeDouble)orig).getDoubleRange().length; - if (maxEvaluations<0) { - maxEvaluations = 500*AbstractEAIndividual.getDoublePositionShallow(prob.template).length; + public static boolean isPotentialOptimumNMS(AbstractOptimizationProblem prob, AbstractEAIndividual orig, double epsilonPhenoSpace, double epsilonFitConv, int maxEvaluations) { + + AbstractEAIndividual indy = (AbstractEAIndividual) orig.clone(); + prob.evaluate(indy); // indy may be evaluated in a normalised way... + + InterfaceDistanceMetric metric = new PhenotypeMetric(); + double overallDist = 0; + double initRelPerturb = -1; + int dim = -1; + if (orig instanceof InterfaceDataTypeDouble) { + initRelPerturb = epsilonPhenoSpace * 0.5; + dim = ((InterfaceDataTypeDouble) orig).getDoubleRange().length; + if (maxEvaluations < 0) { + maxEvaluations = 500 * AbstractEAIndividual.getDoublePositionShallow(prob.template).length; } // scales the effort with the number of problem dimensions - } else { - System.err.println("Cannot initialize NMS on non-double valued individuals!"); - return false; - } - - Population pop = new Population(1); - pop.add(orig); - InterfaceTerminator term = new EvaluationTerminator(maxEvaluations); - if (epsilonFitConv > 0) { - term = new CombinedTerminator(new PhenotypeConvergenceTerminator(epsilonFitConv, 100*dim, StagnationTypeEnum.fitnessCallBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease), term, false); + } else { + System.err.println("Cannot initialize NMS on non-double valued individuals!"); + return false; } - int evalsPerf = PostProcess.processSingleCandidatesNMCMA(PostProcessMethod.nelderMead, pop, term, initRelPerturb, prob); - overallDist = metric.distance(indy, pop.getBestEAIndividual()); - //System.out.println(System.currentTimeMillis() + " in " + evalsPerf + " evals moved by "+ overallDist); + + Population pop = new Population(1); + pop.add(orig); + InterfaceTerminator term = new EvaluationTerminator(maxEvaluations); + if (epsilonFitConv > 0) { + term = new CombinedTerminator(new PhenotypeConvergenceTerminator(epsilonFitConv, 100 * dim, StagnationTypeEnum.fitnessCallBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease), term, false); + } + int evalsPerf = PostProcess.processSingleCandidatesNMCMA(PostProcessMethod.nelderMead, pop, term, initRelPerturb, prob); + overallDist = metric.distance(indy, pop.getBestEAIndividual()); + //System.out.println(System.currentTimeMillis() + " in " + evalsPerf + " evals moved by "+ overallDist); // System.out.println("aft: " + population.getBestEAIndividual().toString() + ", evals performed: " + evalsPerf + ", opt moved by " + overallDist); // System.out.println("terminated because: " + term.lastTerminationMessage()); - orig.putData(PostProcess.movedDistanceKey, overallDist); - orig.putData(PostProcess.movedToPositionKey, pop.getBestEAIndividual().getDoublePosition()); + orig.putData(PostProcess.movedDistanceKey, overallDist); + orig.putData(PostProcess.movedToPositionKey, pop.getBestEAIndividual().getDoublePosition()); // if (overallDist==0) { // PostProcess.processSingleCandidatesNMCMA(PostProcessMethod.nelderMead, population, term, initPerturb, this); // } @@ -568,22 +588,25 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati // System.out.println("which moved to " + BeanInspector.toString(population.getBestEAIndividual().getDoublePosition())); // System.out.println(" by " + overallDist + " > " + epsilonPhenoSpace); - return (overallDist < epsilonPhenoSpace); + return (overallDist < epsilonPhenoSpace); } - + public double getDefaultAccuracy() { - return defaultAccuracy ; + return defaultAccuracy; } + public void SetDefaultAccuracy(double defAcc) { - defaultAccuracy = defAcc; - } + defaultAccuracy = defAcc; + } + public void setDefaultAccuracy(double defAcc) { - defaultAccuracy = defAcc; + defaultAccuracy = defAcc; } + public String defaultAccuracyTipText() { - return "A default threshold to identify optima - e.g. the assumed minimal distance between any two optima."; + return "A default threshold to identify optima - e.g. the assumed minimal distance between any two optima."; } - + // /********************************************************************************************************************** // * These are for InterfaceParamControllable // */ @@ -605,12 +628,14 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati // public void removeChangeListener(ParamChangeListener l) { // if (changeListeners!=null) changeListeners.remove(l); // } - + /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -618,7 +643,9 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati return "AbstractOptimizationProblem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/AbstractParallelOptimizationProblem.java b/src/eva2/optimization/problems/AbstractParallelOptimizationProblem.java index ea5b7c5a..1e39d3b0 100644 --- a/src/eva2/optimization/problems/AbstractParallelOptimizationProblem.java +++ b/src/eva2/optimization/problems/AbstractParallelOptimizationProblem.java @@ -1,8 +1,8 @@ package eva2.optimization.problems; /** - * This class is under construction. - * + * This class is under construction. + *

* Created by IntelliJ IDEA. * User: streiche * Date: 17.12.2004 @@ -11,10 +11,10 @@ package eva2.optimization.problems; */ public abstract class AbstractParallelOptimizationProblem extends AbstractOptimizationProblem { -// private PropertyRemoteServers m_Servers = new PropertyRemoteServers(); - private int m_LocalCPUs = 4; - private boolean m_Parallelize = false; - private AbstractOptimizationProblem[] m_Slaves; + // private PropertyRemoteServers m_Servers = new PropertyRemoteServers(); + private int m_LocalCPUs = 4; + private boolean m_Parallelize = false; + private AbstractOptimizationProblem[] m_Slaves; @Override public void initializeProblem() { @@ -40,13 +40,18 @@ public abstract class AbstractParallelOptimizationProblem extends AbstractOptimi /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "This is a framework for parallelizing expensive optimization problems."; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ @Override @@ -54,16 +59,20 @@ public abstract class AbstractParallelOptimizationProblem extends AbstractOptimi return "Parallel Optimization Problem"; } - /** This method allows you to toggle between a truly parallel + /** + * This method allows you to toggle between a truly parallel * and a serial implementation. + * * @return The current optimzation mode */ public boolean getParallelize() { return this.m_Parallelize; } - public void setParallelize(boolean b){ + + public void setParallelize(boolean b) { this.m_Parallelize = b; } + public String parallelizeTipText() { return "Toggle between parallel and serial implementation."; } @@ -81,15 +90,20 @@ public abstract class AbstractParallelOptimizationProblem extends AbstractOptimi return "Choose and manage the servers (only active in parallelized mode)."; } */ - /** This method allows you to set the number of processors in local mode - * @param n Number of processors. + + /** + * This method allows you to set the number of processors in local mode + * + * @param n Number of processors. */ public void setNumberLocalCPUs(int n) { this.m_LocalCPUs = n; } + public int getNumberLocalCPUs() { return this.m_LocalCPUs; } + public String numberLocalCPUsTipText() { return "Set the number of local CPUS (only active in non-parallelized mode)."; } diff --git a/src/eva2/optimization/problems/AbstractProblemBinary.java b/src/eva2/optimization/problems/AbstractProblemBinary.java index f2db5d26..8765d518 100644 --- a/src/eva2/optimization/problems/AbstractProblemBinary.java +++ b/src/eva2/optimization/problems/AbstractProblemBinary.java @@ -6,62 +6,62 @@ import eva2.optimization.individuals.InterfaceDataTypeBinary; import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; + import java.util.BitSet; /** * An abstract problem based on binary data. - * - * @author mkron * + * @author mkron */ public abstract class AbstractProblemBinary extends AbstractOptimizationProblem { - - public AbstractProblemBinary() { - initTemplate(); - } - - protected void initTemplate() { - if (template == null) { - this.template = new GAIndividualBinaryData(); - } - if (((InterfaceGAIndividual)this.template).getGenotypeLength()!=this.getProblemDimension()) { - ((InterfaceDataTypeBinary)this.template).setBinaryDataLength(this.getProblemDimension()); - } - } - - public void cloneObjects(AbstractProblemBinary o) { - if (o.template != null) { - template = (AbstractEAIndividual)o.template.clone(); - } - } - - @Override - public void evaluate(AbstractEAIndividual individual) { - BitSet tmpBitSet; - double[] result; - - tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); + + public AbstractProblemBinary() { + initTemplate(); + } + + protected void initTemplate() { + if (template == null) { + this.template = new GAIndividualBinaryData(); + } + if (((InterfaceGAIndividual) this.template).getGenotypeLength() != this.getProblemDimension()) { + ((InterfaceDataTypeBinary) this.template).setBinaryDataLength(this.getProblemDimension()); + } + } + + public void cloneObjects(AbstractProblemBinary o) { + if (o.template != null) { + template = (AbstractEAIndividual) o.template.clone(); + } + } + + @Override + public void evaluate(AbstractEAIndividual individual) { + BitSet tmpBitSet; + double[] result; + + tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); // evaluate the fitness result = eval(tmpBitSet); // set the fitness individual.setFitness(result); - } - - /** - * Evaluate a BitSet representing a possible solution. This is the target - * function implementation. - * - * @param x a BitSet representing a possible - * @return - */ - public abstract double[] eval(BitSet bs); - - /** - * Get the problem dimension. - * - * @return the problem dimension - */ - public abstract int getProblemDimension(); + } + + /** + * Evaluate a BitSet representing a possible solution. This is the target + * function implementation. + * + * @param x a BitSet representing a possible + * @return + */ + public abstract double[] eval(BitSet bs); + + /** + * Get the problem dimension. + * + * @return the problem dimension + */ + public abstract int getProblemDimension(); // /** // * Initialize a single individual with index k in the @@ -73,38 +73,44 @@ public abstract class AbstractProblemBinary extends AbstractOptimizationProblem // indy.init(this); // } - @Override - public void initializePopulation(Population population) { - ((InterfaceDataTypeBinary)this.template).setBinaryDataLength(this.getProblemDimension()); + @Override + public void initializePopulation(Population population) { + ((InterfaceDataTypeBinary) this.template).setBinaryDataLength(this.getProblemDimension()); AbstractOptimizationProblem.defaultInitPopulation(population, template, this); - } - - @Override - public void initializeProblem() { - initTemplate(); - } - + } + + @Override + public void initializeProblem() { + initTemplate(); + } + /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override public String getName() { - return "AbstractProblemBinary"; + return "AbstractProblemBinary"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { - return "The programmer did not give further details."; + return "The programmer did not give further details."; } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -112,7 +118,7 @@ public abstract class AbstractProblemBinary extends AbstractOptimizationProblem StringBuffer sb = new StringBuffer(200); sb.append("A binary valued problem:\n"); sb.append(globalInfo()); - sb.append("Dimension : "); + sb.append("Dimension : "); sb.append(this.getProblemDimension()); return sb.toString(); } diff --git a/src/eva2/optimization/problems/AbstractProblemDouble.java b/src/eva2/optimization/problems/AbstractProblemDouble.java index 656d949b..9b6eb99e 100644 --- a/src/eva2/optimization/problems/AbstractProblemDouble.java +++ b/src/eva2/optimization/problems/AbstractProblemDouble.java @@ -28,116 +28,115 @@ import eva2.tools.math.RNG; * {@link #getProblemDimension()} must return the problem dimension, while * {@link #eval(double[])} is to evaluate a single double vector into the result * fitness vector. - * + *

* To define the problem range, you may use the default range parameter * resulting in a symmetric double range [-defaultRange,defaulRange] in all * dimensions. Or you may implement {@link #getRangeLowerBound(int)} and * {@link #getRangeUpperBound(int)} to define an arbitrary problem range. In * that case, the default range parameter is not used. - * + *

* Anything you want to do before any optimization is started on the problem * should go into {@link #initializeProblem()}, but remember to call the super-method * in your implementation. The individual template will be initialized to an * ESIndividualDoubleData by then. - * + *

* For the GUI, it is also convenient to implement the {@link #globalInfo()} and * {@link #getName()} methods to provide some distinctive information for the * user. - * */ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem implements InterfaceProblemDouble, Interface2DBorderProblem { - /** - * Generated serial version identifier. - */ - private static final long serialVersionUID = -3904130243174390134L; - private double defaultRange = 10; - private double noise = 0; - private boolean doRotation = false; // should really be false by default - private Matrix rotation; + /** + * Generated serial version identifier. + */ + private static final long serialVersionUID = -3904130243174390134L; + private double defaultRange = 10; + private double noise = 0; + private boolean doRotation = false; // should really be false by default + private Matrix rotation; - // PropertySelectableList constraintList = new - // PropertySelectableList(new AbstractConstraint[]{new - // GenericConstraint()}); - private AbstractConstraint[] constraintArray = new AbstractConstraint[] { new GenericConstraint() }; - private boolean withConstraints = false; - private transient boolean isShowing = false; - private double rotAngle = 22.5; // for default rotation along every axis - public static String rawFitKey = "UnconstrainedFitnessValue"; + // PropertySelectableList constraintList = new + // PropertySelectableList(new AbstractConstraint[]{new + // GenericConstraint()}); + private AbstractConstraint[] constraintArray = new AbstractConstraint[]{new GenericConstraint()}; + private boolean withConstraints = false; + private transient boolean isShowing = false; + private double rotAngle = 22.5; // for default rotation along every axis + public static String rawFitKey = "UnconstrainedFitnessValue"; - public AbstractProblemDouble() { - initTemplate(); - } + public AbstractProblemDouble() { + initTemplate(); + } - public AbstractProblemDouble(AbstractProblemDouble o) { - cloneObjects(o); - } + public AbstractProblemDouble(AbstractProblemDouble o) { + cloneObjects(o); + } - protected void initTemplate() { - if (template == null) { - template = new ESIndividualDoubleData(); - } - if (getProblemDimension() > 0) { // avoid evil case setting dim to 0 - // during object init - ((InterfaceDataTypeDouble) this.template) - .setDoubleDataLength(getProblemDimension()); - ((InterfaceDataTypeDouble) this.template) - .SetDoubleRange(makeRange()); - } - } + protected void initTemplate() { + if (template == null) { + template = new ESIndividualDoubleData(); + } + if (getProblemDimension() > 0) { // avoid evil case setting dim to 0 + // during object init + ((InterfaceDataTypeDouble) this.template) + .setDoubleDataLength(getProblemDimension()); + ((InterfaceDataTypeDouble) this.template) + .SetDoubleRange(makeRange()); + } + } - public void hideHideable() { - setWithConstraints(isWithConstraints()); - } + public void hideHideable() { + setWithConstraints(isWithConstraints()); + } - protected void cloneObjects(AbstractProblemDouble o) { - this.defaultRange = o.defaultRange; - this.noise = o.noise; - this.SetDefaultAccuracy(o.getDefaultAccuracy()); - if (o.template != null) { - this.template = (AbstractEAIndividual) o.template.clone(); - } - if (o.constraintArray != null) { - this.constraintArray = o.constraintArray.clone(); - for (int i = 0; i < constraintArray.length; i++) { + protected void cloneObjects(AbstractProblemDouble o) { + this.defaultRange = o.defaultRange; + this.noise = o.noise; + this.SetDefaultAccuracy(o.getDefaultAccuracy()); + if (o.template != null) { + this.template = (AbstractEAIndividual) o.template.clone(); + } + if (o.constraintArray != null) { + this.constraintArray = o.constraintArray.clone(); + for (int i = 0; i < constraintArray.length; i++) { constraintArray[i] = (AbstractConstraint) o.constraintArray[i] - .clone(); + .clone(); } - } - this.withConstraints = o.withConstraints; - this.doRotation = o.doRotation; - this.rotation = (o.rotation == null) ? null : (Matrix) o.rotation - .clone(); - this.rotAngle = o.rotAngle; - } + } + this.withConstraints = o.withConstraints; + this.doRotation = o.doRotation; + this.rotation = (o.rotation == null) ? null : (Matrix) o.rotation + .clone(); + this.rotAngle = o.rotAngle; + } - /** - * Retrieve and copy the double solution representation from an individual. - * This may also perform a coding adaption. The result is stored as - * phenotype within the evaluate method. - * - * @param individual - * @return the double solution representation - */ - protected double[] getEvalArray(AbstractEAIndividual individual) { - double[] x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; - System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); - return x; - } + /** + * Retrieve and copy the double solution representation from an individual. + * This may also perform a coding adaption. The result is stored as + * phenotype within the evaluate method. + * + * @param individual + * @return the double solution representation + */ + protected double[] getEvalArray(AbstractEAIndividual individual) { + double[] x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; + System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); + return x; + } - /** - * When implementing a double problem, inheriting classes should not - * override this method (or only extend it) and do the fitness calculations - * in the method eval(double[]). - * - * @see eval(double[] x) - */ + /** + * When implementing a double problem, inheriting classes should not + * override this method (or only extend it) and do the fitness calculations + * in the method eval(double[]). + * + * @see eval(double[] x) + */ @Override - public void evaluate(AbstractEAIndividual individual) { - double[] x; - double[] fitness; + public void evaluate(AbstractEAIndividual individual) { + double[] x; + double[] fitness; x = getEvalArray(individual); - ((InterfaceDataTypeDouble)individual).SetDoublePhenotype(x); + ((InterfaceDataTypeDouble) individual).SetDoublePhenotype(x); // evaluate the vector fitness = this.eval(x); // if indicated, add Gaussian noise @@ -147,511 +146,506 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem // set the fitness setEvalFitness(individual, x, fitness); if (isWithConstraints()) { - individual.putData(rawFitKey, individual.getFitness().clone()); - addConstraints(individual, x); + individual.putData(rawFitKey, individual.getFitness().clone()); + addConstraints(individual, x); } - } + } - protected double[] rotateMaybe(double[] x) { - if (isDoRotation()) { - if (rotation == null) { + protected double[] rotateMaybe(double[] x) { + if (isDoRotation()) { + if (rotation == null) { initializeProblem(); } - x = Mathematics.rotate(x, rotation); - } - return x; - } + x = Mathematics.rotate(x, rotation); + } + return x; + } - protected double[] inverseRotateMaybe(double[] x) { - if (isDoRotation()) { - if (rotation == null) { + protected double[] inverseRotateMaybe(double[] x) { + if (isDoRotation()) { + if (rotation == null) { initializeProblem(); } - x = Mathematics.rotate(x, rotation.inverse()); - } - return x; - } + x = Mathematics.rotate(x, rotation.inverse()); + } + return x; + } - /** - * Add all constraint violations to the individual. Expect that the fitness - * has already been set. - * - * @param individual - * @param indyPos - * may contain the decoded individual position - */ - protected void addConstraints(AbstractEAIndividual individual, double[] indyPos) { - AbstractConstraint[] contraints = getConstraints(); + /** + * Add all constraint violations to the individual. Expect that the fitness + * has already been set. + * + * @param individual + * @param indyPos may contain the decoded individual position + */ + protected void addConstraints(AbstractEAIndividual individual, double[] indyPos) { + AbstractConstraint[] contraints = getConstraints(); for (AbstractConstraint contraint : contraints) { contraint.addViolation(individual, indyPos); } - } + } - /** - * Write a fitness value back to an individual. May be overridden to add - * constraints. - * - * @param individual - * @param x - * @param fit - */ - protected void setEvalFitness(AbstractEAIndividual individual, double[] x, double[] fit) { - individual.setFitness(fit); - } + /** + * Write a fitness value back to an individual. May be overridden to add + * constraints. + * + * @param individual + * @param x + * @param fit + */ + protected void setEvalFitness(AbstractEAIndividual individual, double[] x, double[] fit) { + individual.setFitness(fit); + } - /** - * Evaluate a double vector, representing the target function. If you - * implement this, you should take care of the offsets and rotation, e.g. by - * using x=rotateMaybe(x) before further evaluation. - * - * @param x - * the vector to evaluate - * @return the target function value - */ + /** + * Evaluate a double vector, representing the target function. If you + * implement this, you should take care of the offsets and rotation, e.g. by + * using x=rotateMaybe(x) before further evaluation. + * + * @param x the vector to evaluate + * @return the target function value + */ @Override - public abstract double[] eval(double[] x); + public abstract double[] eval(double[] x); - /** - * Get the problem dimension. - * - * @return the problem dimension - */ + /** + * Get the problem dimension. + * + * @return the problem dimension + */ @Override - public abstract int getProblemDimension(); + public abstract int getProblemDimension(); - @Override - public void initializePopulation(Population population) { - initTemplate(); - AbstractOptimizationProblem.defaultInitPopulation(population, template, this); - } - - /** - * Create a new range array by using the getRangeLowerBound and - * getRangeUpperBound methods. - * - * @return a range array - */ @Override - public double[][] makeRange() { - double[][] range = new double[this.getProblemDimension()][2]; - for (int i = 0; i < range.length; i++) { - range[i][0] = getRangeLowerBound(i); - range[i][1] = getRangeUpperBound(i); - } - return range; - } + public void initializePopulation(Population population) { + initTemplate(); + AbstractOptimizationProblem.defaultInitPopulation(population, template, this); + } - /** - * Get the lower bound of the double range in the given dimension. Override - * this to implement non-symmetric ranges. Use setDefaultRange for symmetric - * ranges. - * - * @see makeRange() - * @see getRangeUpperBound(int dim) - * @param dim - * @return the lower bound of the double range in the given dimension - */ + /** + * Create a new range array by using the getRangeLowerBound and + * getRangeUpperBound methods. + * + * @return a range array + */ @Override - public double getRangeLowerBound(int dim) { - return -getDefaultRange(); - } + public double[][] makeRange() { + double[][] range = new double[this.getProblemDimension()][2]; + for (int i = 0; i < range.length; i++) { + range[i][0] = getRangeLowerBound(i); + range[i][1] = getRangeUpperBound(i); + } + return range; + } - /** - * Get the upper bound of the double range in the given dimension. Override - * this to implement non-symmetric ranges. User setDefaultRange for - * symmetric ranges. - * - * @see makeRange() - * @see getRangeLowerBound(int dim) - * @param dim - * @return the upper bound of the double range in the given dimension - */ + /** + * Get the lower bound of the double range in the given dimension. Override + * this to implement non-symmetric ranges. Use setDefaultRange for symmetric + * ranges. + * + * @param dim + * @return the lower bound of the double range in the given dimension + * @see makeRange() + * @see getRangeUpperBound(int dim) + */ @Override - public double getRangeUpperBound(int dim) { - return getDefaultRange(); - } + public double getRangeLowerBound(int dim) { + return -getDefaultRange(); + } - @Override - public void initializeProblem() { - initTemplate(); - if (isDoRotation()) { - rotation = initializeDefaultRotationMatrix(rotAngle, getProblemDimension()); - } else { + /** + * Get the upper bound of the double range in the given dimension. Override + * this to implement non-symmetric ranges. User setDefaultRange for + * symmetric ranges. + * + * @param dim + * @return the upper bound of the double range in the given dimension + * @see makeRange() + * @see getRangeLowerBound(int dim) + */ + @Override + public double getRangeUpperBound(int dim) { + return getDefaultRange(); + } + + @Override + public void initializeProblem() { + initTemplate(); + if (isDoRotation()) { + rotation = initializeDefaultRotationMatrix(rotAngle, getProblemDimension()); + } else { rotation = null; } - } + } - /** - * Initialize rotation matrix which rotates around the given angle in every - * axis. - * - * @param rotAngle - * @param dim - * @return - */ - public static Matrix initializeDefaultRotationMatrix(double rotAngle, int dim) { - Matrix rotation = null; - rotation = Mathematics.getRotationMatrix((rotAngle * Math.PI / 180.), dim).transpose(); - return rotation; - } + /** + * Initialize rotation matrix which rotates around the given angle in every + * axis. + * + * @param rotAngle + * @param dim + * @return + */ + public static Matrix initializeDefaultRotationMatrix(double rotAngle, int dim) { + Matrix rotation = null; + rotation = Mathematics.getRotationMatrix((rotAngle * Math.PI / 180.), dim).transpose(); + return rotation; + } - /** - * This method allows you to choose how much noise is to be added to the - * fitness. This can be used to make the optimization problem more - * difficult. - * - * @param noise - * The sigma for a gaussian random number. - */ - public void setNoise(double noise) { - if (noise < 0) { + /** + * This method allows you to choose how much noise is to be added to the + * fitness. This can be used to make the optimization problem more + * difficult. + * + * @param noise The sigma for a gaussian random number. + */ + public void setNoise(double noise) { + if (noise < 0) { noise = 0; } - this.noise = noise; - } + this.noise = noise; + } - /** - * Get the current noise level. - * - * @return the current noise level - */ - public double getNoise() { - return this.noise; - } + /** + * Get the current noise level. + * + * @return the current noise level + */ + public double getNoise() { + return this.noise; + } - public String noiseTipText() { - return "Gaussian noise level on the fitness value."; - } + public String noiseTipText() { + return "Gaussian noise level on the fitness value."; + } - /** - * This method allows you to choose the EA individual used by the problem. - * - * @param indy - * The EAIndividual type - */ - public void setEAIndividual(InterfaceDataTypeDouble indy) { - this.template = (AbstractEAIndividual) indy; - } + /** + * This method allows you to choose the EA individual used by the problem. + * + * @param indy The EAIndividual type + */ + public void setEAIndividual(InterfaceDataTypeDouble indy) { + this.template = (AbstractEAIndividual) indy; + } - /** - * Get the EA individual template currently used by the problem. - * - * @return the EA individual template currently used - */ + /** + * Get the EA individual template currently used by the problem. + * + * @return the EA individual template currently used + */ @Override - public InterfaceDataTypeDouble getEAIndividual() { - return (InterfaceDataTypeDouble) this.template; - } + public InterfaceDataTypeDouble getEAIndividual() { + return (InterfaceDataTypeDouble) this.template; + } - public String EAIndividualTipText() { - return "Set the base individual type defining the data representation and mutation/crossover operators"; - } + public String EAIndividualTipText() { + return "Set the base individual type defining the data representation and mutation/crossover operators"; + } - /** - * A (symmetric) absolute range limit. - * - * @return value of the absolute range limit - */ - public double getDefaultRange() { - return defaultRange; - } + /** + * A (symmetric) absolute range limit. + * + * @return value of the absolute range limit + */ + public double getDefaultRange() { + return defaultRange; + } - /** - * Set a (symmetric) absolute range limit. - * - * @param defaultRange - */ - public void setDefaultRange(double defaultRange) { - this.defaultRange = defaultRange; - initTemplate(); - } + /** + * Set a (symmetric) absolute range limit. + * + * @param defaultRange + */ + public void setDefaultRange(double defaultRange) { + this.defaultRange = defaultRange; + initTemplate(); + } - public String defaultRangeTipText() { - return "Absolute limit for the symmetric range in any dimension"; - } + public String defaultRangeTipText() { + return "Absolute limit for the symmetric range in any dimension"; + } - public void setDoRotation(boolean doRotation) { - this.doRotation = doRotation; - if (!doRotation) { - rotation = null; - } - } + public void setDoRotation(boolean doRotation) { + this.doRotation = doRotation; + if (!doRotation) { + rotation = null; + } + } - public boolean isDoRotation() { - return doRotation; - } + public boolean isDoRotation() { + return doRotation; + } - public String doRotationTipText() { - return "If marked, the function is rotated by 22.5 degrees along every axis."; - } + public String doRotationTipText() { + return "If marked, the function is rotated by 22.5 degrees along every axis."; + } - /********************************************************************************************************************** - * These are for InterfaceParamControllable - */ - public Object[] getParamControl() { - if (isWithConstraints()) { - return constraintArray; - // return constraintList.getObjects(); - } else { - return null; - } - } + /** + * ******************************************************************************************************************* + * These are for InterfaceParamControllable + */ + public Object[] getParamControl() { + if (isWithConstraints()) { + return constraintArray; + // return constraintList.getObjects(); + } else { + return null; + } + } - /********************************************************************************************************************** - * These are for Interface2DBorderProblem - */ + /** + * ******************************************************************************************************************* + * These are for Interface2DBorderProblem + */ @Override - public double[][] get2DBorder() { - return makeRange(); - } + public double[][] get2DBorder() { + return makeRange(); + } @Override - public double[] project2DPoint(double[] point) { - return Mathematics.expandVector(point, getProblemDimension(), 0.); - } + public double[] project2DPoint(double[] point) { + return Mathematics.expandVector(point, getProblemDimension(), 0.); + } @Override - public double functionValue(double[] point) { - double[] x = project2DPoint(point); - double v = eval(x)[0]; - return v; - } + public double functionValue(double[] point) { + double[] x = project2DPoint(point); + double v = eval(x)[0]; + return v; + } - /** - * Add a position as a known optimum to a list of optima. This method - * evaluates the fitness and applies inverse rotation if necessary. - * - * @param optimas - * @param prob - * @param pos - */ - public static void addUnrotatedOptimum(Population optimas, - AbstractProblemDouble prob, double[] pos) { - InterfaceDataTypeDouble tmpIndy; - tmpIndy = (InterfaceDataTypeDouble) prob.getIndividualTemplate() - .clone(); - tmpIndy.SetDoubleGenotype(pos); - if (prob.isDoRotation()) { - pos = prob.inverseRotateMaybe(pos); // theres an inverse rotation - // required - tmpIndy.SetDoubleGenotype(pos); - } - ((AbstractEAIndividual) tmpIndy).setFitness(prob.eval(pos)); - if (!Mathematics.isInRange(pos, prob.makeRange())) { - System.err.println("Warning, add optimum which is out of range!"); - } - optimas.add(tmpIndy); - } + /** + * Add a position as a known optimum to a list of optima. This method + * evaluates the fitness and applies inverse rotation if necessary. + * + * @param optimas + * @param prob + * @param pos + */ + public static void addUnrotatedOptimum(Population optimas, + AbstractProblemDouble prob, double[] pos) { + InterfaceDataTypeDouble tmpIndy; + tmpIndy = (InterfaceDataTypeDouble) prob.getIndividualTemplate() + .clone(); + tmpIndy.SetDoubleGenotype(pos); + if (prob.isDoRotation()) { + pos = prob.inverseRotateMaybe(pos); // theres an inverse rotation + // required + tmpIndy.SetDoubleGenotype(pos); + } + ((AbstractEAIndividual) tmpIndy).setFitness(prob.eval(pos)); + if (!Mathematics.isInRange(pos, prob.makeRange())) { + System.err.println("Warning, add optimum which is out of range!"); + } + optimas.add(tmpIndy); + } - /** - * Refine a potential solution using Nelder-Mead-Simplex. - * - * @param prob - * @param pos - * @return - */ - public static double[] refineSolutionNMS(AbstractProblemDouble prob, - double[] pos) { - Population pop = new Population(); - InterfaceDataTypeDouble tmpIndy; - tmpIndy = (InterfaceDataTypeDouble) prob.getIndividualTemplate() - .clone(); - tmpIndy.SetDoubleGenotype(pos); - ((AbstractEAIndividual) tmpIndy).setFitness(prob.eval(pos)); - pop.add(tmpIndy); - FitnessConvergenceTerminator convTerm = new FitnessConvergenceTerminator( - 1e-25, 10, StagnationTypeEnum.generationBased, - ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease); - int calls = PostProcess.processSingleCandidatesNMCMA( - PostProcessMethod.nelderMead, pop, convTerm, 0.001, prob); - return ((InterfaceDataTypeDouble) pop.getBestEAIndividual()) - .getDoubleData(); - } + /** + * Refine a potential solution using Nelder-Mead-Simplex. + * + * @param prob + * @param pos + * @return + */ + public static double[] refineSolutionNMS(AbstractProblemDouble prob, + double[] pos) { + Population pop = new Population(); + InterfaceDataTypeDouble tmpIndy; + tmpIndy = (InterfaceDataTypeDouble) prob.getIndividualTemplate() + .clone(); + tmpIndy.SetDoubleGenotype(pos); + ((AbstractEAIndividual) tmpIndy).setFitness(prob.eval(pos)); + pop.add(tmpIndy); + FitnessConvergenceTerminator convTerm = new FitnessConvergenceTerminator( + 1e-25, 10, StagnationTypeEnum.generationBased, + ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease); + int calls = PostProcess.processSingleCandidatesNMCMA( + PostProcessMethod.nelderMead, pop, convTerm, 0.001, prob); + return ((InterfaceDataTypeDouble) pop.getBestEAIndividual()) + .getDoubleData(); + } - /** - * Refine a candidate solution vector regarding rotations. Saves the new - * solution vector in pos and returns the number of dimensions that had to - * be modified after rotation due to range restrictions. - * - * The given position is expected to be unrotated! The returned solution is - * unrotated as well. - * - * @param pos - * @param prob - * @return - */ - public static int refineWithRotation(double[] pos, - AbstractProblemDouble prob) { - double[] res = prob.inverseRotateMaybe(pos); - int modifiedInPrjct = Mathematics.projectToRange(res, prob.makeRange()); - res = AbstractProblemDouble.refineSolutionNMS(prob, res); - res = prob.rotateMaybe(res); - System.arraycopy(res, 0, pos, 0, res.length); - return modifiedInPrjct; - } + /** + * Refine a candidate solution vector regarding rotations. Saves the new + * solution vector in pos and returns the number of dimensions that had to + * be modified after rotation due to range restrictions. + *

+ * The given position is expected to be unrotated! The returned solution is + * unrotated as well. + * + * @param pos + * @param prob + * @return + */ + public static int refineWithRotation(double[] pos, + AbstractProblemDouble prob) { + double[] res = prob.inverseRotateMaybe(pos); + int modifiedInPrjct = Mathematics.projectToRange(res, prob.makeRange()); + res = AbstractProblemDouble.refineSolutionNMS(prob, res); + res = prob.rotateMaybe(res); + System.arraycopy(res, 0, pos, 0, res.length); + return modifiedInPrjct; + } - /********************************************************************************************************************** - * These are for GUI - */ + /********************************************************************************************************************** + * These are for GUI + */ - /** - * This method allows the GUI to read the name to the current object. - * - * @return the name of the object - */ + /** + * This method allows the GUI to read the name to the current object. + * + * @return the name of the object + */ @Override - public String getName() { - return "AbstractProblemDouble"; - } + public String getName() { + return "AbstractProblemDouble"; + } - /** - * This method returns a global info string. - * - * @return description - */ - public static String globalInfo() { - return "The programmer did not give further details."; - } + /** + * This method returns a global info string. + * + * @return description + */ + public static String globalInfo() { + return "The programmer did not give further details."; + } - /** - * This method returns a string describing the optimization problem. - * - * @param opt - * The Optimizer that is used or had been used. - * @return The description. - */ + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. + * @return The description. + */ @Override - public String getStringRepresentationForProblem(InterfaceOptimizer opt) { - StringBuffer sb = new StringBuffer(200); - sb.append("A double valued problem: "); - sb.append(this.getName()); - sb.append("\n"); - sb.append(globalInfo()); - sb.append("Dimension : "); - sb.append(this.getProblemDimension()); - sb.append("\nNoise level : "); - sb.append(this.noise); - return sb.toString(); - } + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + StringBuffer sb = new StringBuffer(200); + sb.append("A double valued problem: "); + sb.append(this.getName()); + sb.append("\n"); + sb.append(globalInfo()); + sb.append("Dimension : "); + sb.append(this.getProblemDimension()); + sb.append("\nNoise level : "); + sb.append(this.noise); + return sb.toString(); + } - // public PropertySelectableList getConstraints() { - // return constraintList; - // } - // - // public void setConstraints(PropertySelectableList - // constraintArray) { - // this.constraintList = constraintArray; - // } + // public PropertySelectableList getConstraints() { + // return constraintList; + // } + // + // public void setConstraints(PropertySelectableList + // constraintArray) { + // this.constraintList = constraintArray; + // } - public AbstractConstraint[] getConstraints() { - return constraintArray; - } + public AbstractConstraint[] getConstraints() { + return constraintArray; + } - public void setConstraints(AbstractConstraint[] constrArray) { - this.constraintArray = constrArray; - } + public void setConstraints(AbstractConstraint[] constrArray) { + this.constraintArray = constrArray; + } - public String constraintsTipText() { - return "Add constraints to the problem."; - } + public String constraintsTipText() { + return "Add constraints to the problem."; + } - public boolean isWithConstraints() { - return withConstraints; - } + public boolean isWithConstraints() { + return withConstraints; + } - public void setWithConstraints(boolean withConstraints) { - this.withConstraints = withConstraints; - GenericObjectEditor.setShowProperty(this.getClass(), "constraints", - withConstraints); - } + public void setWithConstraints(boolean withConstraints) { + this.withConstraints = withConstraints; + GenericObjectEditor.setShowProperty(this.getClass(), "constraints", + withConstraints); + } - public String withConstraintsTipText() { - return "(De-)Activate constraints for the problem."; - } + public String withConstraintsTipText() { + return "(De-)Activate constraints for the problem."; + } - @Override - public String[] getAdditionalDataHeader() { - String[] superHeader = super.getAdditionalDataHeader(); - if (isWithConstraints()) { - return ToolBox.appendArrays(superHeader, new String[] { "rawFit", - "numViol", "sumViol" }); + @Override + public String[] getAdditionalDataHeader() { + String[] superHeader = super.getAdditionalDataHeader(); + if (isWithConstraints()) { + return ToolBox.appendArrays(superHeader, new String[]{"rawFit", + "numViol", "sumViol"}); + } else { + return superHeader; + } + } + + @Override + public String[] getAdditionalDataInfo() { + String[] superInfo = super.getAdditionalDataInfo(); + if (isWithConstraints()) { + return ToolBox + .appendArrays( + superInfo, + new String[]{ + "Raw fitness (unpenalized) of the current best individual", + "The number of constraints violated by the current best individual", + "The sum of constraint violations of the current best individual"}); + } else { + return superInfo; + } + } + + @Override + public Object[] getAdditionalDataValue(PopulationInterface pop) { + Object[] superVal = super.getAdditionalDataValue(pop); + if (isWithConstraints()) { + AbstractEAIndividual indy = (AbstractEAIndividual) pop + .getBestIndividual(); + Pair violation = getConstraintViolation(indy); + return ToolBox.appendArrays(superVal, + new Object[]{indy.getData(rawFitKey), violation.head(), + violation.tail()}); + // return superVal + " \t" + + // BeanInspector.toString(indy.getData(rawFitKey)) + " \t" + + // violation.head() + " \t" + violation.tail(); + } else { + return superVal; + } + } + + protected Pair getConstraintViolation( + AbstractEAIndividual indy) { + double sum = 0; + int numViol = 0; + for (AbstractConstraint constr : constraintArray) { + double v = constr.getViolation(getEvalArray(indy)); + if (v > 0) { + numViol++; } - else { - return superHeader; + sum += v; + } + return new Pair(numViol, sum); + } + + public boolean isShowPlot() { + return isShowing; + } + + public void setShowPlot(boolean showP) { + if (!isShowing && showP) { + TopoPlot plot = new TopoPlot(getName(), "x1", "x2"); + plot.setParams(60, 60, ColorBarCalculator.BLUE_TO_RED); + this.initializeProblem(); + plot.setTopology(this, makeRange(), true); + if (this instanceof InterfaceMultimodalProblemKnown + && ((InterfaceMultimodalProblemKnown) this) + .fullListAvailable()) { + plot.drawPopulation("Opt", + ((InterfaceMultimodalProblemKnown) this) + .getRealOptima()); } - } + } + isShowing = showP; + } - @Override - public String[] getAdditionalDataInfo() { - String[] superInfo = super.getAdditionalDataInfo(); - if (isWithConstraints()) { - return ToolBox - .appendArrays( - superInfo, - new String[] { - "Raw fitness (unpenalized) of the current best individual", - "The number of constraints violated by the current best individual", - "The sum of constraint violations of the current best individual" }); - } - else { - return superInfo; - } - } - - @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - Object[] superVal = super.getAdditionalDataValue(pop); - if (isWithConstraints()) { - AbstractEAIndividual indy = (AbstractEAIndividual) pop - .getBestIndividual(); - Pair violation = getConstraintViolation(indy); - return ToolBox.appendArrays(superVal, - new Object[] { indy.getData(rawFitKey), violation.head(), - violation.tail() }); - // return superVal + " \t" + - // BeanInspector.toString(indy.getData(rawFitKey)) + " \t" + - // violation.head() + " \t" + violation.tail(); - } else { - return superVal; - } - } - - protected Pair getConstraintViolation( - AbstractEAIndividual indy) { - double sum = 0; - int numViol = 0; - for (AbstractConstraint constr : constraintArray) { - double v = constr.getViolation(getEvalArray(indy)); - if (v > 0) { - numViol++; - } - sum += v; - } - return new Pair(numViol, sum); - } - - public boolean isShowPlot() { - return isShowing; - } - - public void setShowPlot(boolean showP) { - if (!isShowing && showP) { - TopoPlot plot = new TopoPlot(getName(), "x1", "x2"); - plot.setParams(60, 60, ColorBarCalculator.BLUE_TO_RED); - this.initializeProblem(); - plot.setTopology(this, makeRange(), true); - if (this instanceof InterfaceMultimodalProblemKnown - && ((InterfaceMultimodalProblemKnown) this) - .fullListAvailable()) { - plot.drawPopulation("Opt", - ((InterfaceMultimodalProblemKnown) this) - .getRealOptima()); - } - } - isShowing = showP; - } - - public String showPlotTipText() { - return "Produce an exemplary 2D plot of the function (dimensional cut at x_i=0 for n>1)."; - } + public String showPlotTipText() { + return "Produce an exemplary 2D plot of the function (dimensional cut at x_i=0 for n>1)."; + } } diff --git a/src/eva2/optimization/problems/AbstractProblemDoubleOffset.java b/src/eva2/optimization/problems/AbstractProblemDoubleOffset.java index 1632bd75..6a3389bf 100644 --- a/src/eva2/optimization/problems/AbstractProblemDoubleOffset.java +++ b/src/eva2/optimization/problems/AbstractProblemDoubleOffset.java @@ -14,33 +14,35 @@ public abstract class AbstractProblemDoubleOffset extends AbstractProblemDouble protected double yOffset = 0.0; public AbstractProblemDoubleOffset() { - super(); - setDefaultRange(10); + super(); + setDefaultRange(10); } - + public AbstractProblemDoubleOffset(AbstractProblemDoubleOffset b) { - super(); - super.cloneObjects(b); - this.problemDimension = b.problemDimension; - this.xOffset = b.xOffset; - this.yOffset = b.yOffset; + super(); + super.cloneObjects(b); + this.problemDimension = b.problemDimension; + this.xOffset = b.xOffset; + this.yOffset = b.yOffset; } - + public AbstractProblemDoubleOffset(int dim) { - this(); - setProblemDimension(dim); + this(); + setProblemDimension(dim); } - + public AbstractProblemDoubleOffset(int dim, double defRange) { - this(dim); - setDefaultRange(defRange); + this(dim); + setDefaultRange(defRange); } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -48,42 +50,55 @@ public abstract class AbstractProblemDoubleOffset extends AbstractProblemDouble return "Double-valued-Problem+Offsets"; } - /** This method allows you to set/get an offset for decision variables. - * @param XOffset The offset for the decision variables. + /** + * This method allows you to set/get an offset for decision variables. + * + * @param XOffset The offset for the decision variables. */ public void setXOffset(double XOffset) { this.xOffset = XOffset; } + public double getXOffset() { return this.xOffset; } + public String XOffsetTipText() { return "Choose an offset for the decision variables."; } - /** This method allows you to set/get the offset for the + /** + * This method allows you to set/get the offset for the * objective value. - * @param YOffset The offset for the objective value. + * + * @param YOffset The offset for the objective value. */ public void setYOffset(double YOffset) { this.yOffset = YOffset; } + public double getYOffset() { return this.yOffset; } + public String YOffsetTipText() { return "Choose an offset for the objective value."; } - /** Length of the x vector at is to be optimized + + /** + * Length of the x vector at is to be optimized + * * @param t Length of the x vector at is to be optimized */ public void setProblemDimension(int t) { this.problemDimension = t; } + @Override public int getProblemDimension() { return this.problemDimension; } + public String problemDimensionTipText() { return "Length of the x vector to be optimized."; } diff --git a/src/eva2/optimization/problems/AbstractProblemInteger.java b/src/eva2/optimization/problems/AbstractProblemInteger.java index b84772ae..709d8986 100644 --- a/src/eva2/optimization/problems/AbstractProblemInteger.java +++ b/src/eva2/optimization/problems/AbstractProblemInteger.java @@ -8,53 +8,52 @@ import eva2.optimization.strategies.InterfaceOptimizer; /** * An abstract problem with integer data type. - * */ public abstract class AbstractProblemInteger extends AbstractOptimizationProblem implements java.io.Serializable { - protected AbstractEAIndividual m_OverallBest = null; - protected int m_ProblemDimension = 10; + protected AbstractEAIndividual m_OverallBest = null; + protected int m_ProblemDimension = 10; public AbstractProblemInteger() { - initTemplate(); + initTemplate(); } protected void initTemplate() { - if (template ==null) { + if (template == null) { template = new GIIndividualIntegerData(); } - if (((InterfaceDataTypeInteger)this.template).size()!=this.getProblemDimension()) { - ((InterfaceDataTypeInteger)this.template).setIntegerDataLength(this.getProblemDimension()); - } + if (((InterfaceDataTypeInteger) this.template).size() != this.getProblemDimension()) { + ((InterfaceDataTypeInteger) this.template).setIntegerDataLength(this.getProblemDimension()); + } } - public void cloneObjects(AbstractProblemInteger o) { - if (o.template != null) { - template = (AbstractEAIndividual)o.template.clone(); - } + public void cloneObjects(AbstractProblemInteger o) { + if (o.template != null) { + template = (AbstractEAIndividual) o.template.clone(); + } if (o.m_OverallBest != null) { - m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)o.m_OverallBest).clone(); - } + m_OverallBest = (AbstractEAIndividual) ((AbstractEAIndividual) o.m_OverallBest).clone(); + } this.m_ProblemDimension = o.m_ProblemDimension; - } + } - @Override + @Override public void initializeProblem() { - initTemplate(); + initTemplate(); this.m_OverallBest = null; } - @Override + @Override public void initializePopulation(Population population) { this.m_OverallBest = null; - ((InterfaceDataTypeInteger)this.template).setIntegerDataLength(this.m_ProblemDimension); + ((InterfaceDataTypeInteger) this.template).setIntegerDataLength(this.m_ProblemDimension); AbstractOptimizationProblem.defaultInitPopulation(population, template, this); } @Override public void evaluate(AbstractEAIndividual individual) { - int[] x; - double[] fitness; + int[] x; + double[] fitness; x = new int[((InterfaceDataTypeInteger) individual).getIntegerData().length]; @@ -66,35 +65,41 @@ public abstract class AbstractProblemInteger extends AbstractOptimizationProblem individual.SetFitness(i, fitness[i]); } if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { - this.m_OverallBest = (AbstractEAIndividual)individual.clone(); + this.m_OverallBest = (AbstractEAIndividual) individual.clone(); } } - /** + /** * Evaluate a simple integer array to determine the fitness. - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ public abstract double[] eval(int[] x); -/********************************************************************************************************************** - * These are for GUI - */ + /** + * ******************************************************************************************************************* + * These are for GUI + */ @Override public String getName() { - return "AbstractProblemInteger"; + return "AbstractProblemInteger"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { - return "The programmer did not give further details."; + return "The programmer did not give further details."; } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -102,29 +107,35 @@ public abstract class AbstractProblemInteger extends AbstractOptimizationProblem StringBuffer sb = new StringBuffer(200); sb.append("An integer valued problem:\n"); sb.append(globalInfo()); - sb.append("Dimension : "); + sb.append("Dimension : "); sb.append(this.getProblemDimension()); return sb.toString(); } - /** This method allows you to set the problem dimension. - * @param n The problem dimension + /** + * This method allows you to set the problem dimension. + * + * @param n The problem dimension */ public void setProblemDimension(int n) { this.m_ProblemDimension = n; } + public int getProblemDimension() { return this.m_ProblemDimension; } + public String problemDimensionTipText() { return "Length of the integer vector to be optimized"; } - /** This method allows you to choose the EA individual + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setIndividualTemplate(AbstractEAIndividual indy) { - this.template = (AbstractEAIndividual)indy; + this.template = (AbstractEAIndividual) indy; } } \ No newline at end of file diff --git a/src/eva2/optimization/problems/AbstractSynchronousOptimizationProblem.java b/src/eva2/optimization/problems/AbstractSynchronousOptimizationProblem.java index 3631831c..49fa3909 100644 --- a/src/eva2/optimization/problems/AbstractSynchronousOptimizationProblem.java +++ b/src/eva2/optimization/problems/AbstractSynchronousOptimizationProblem.java @@ -1,11 +1,11 @@ /** - * + * */ package eva2.optimization.problems; import eva2.optimization.population.Population; -/** +/** * A synchronous problem changes in equal intervals. As the EA takes notice of the * problem only in evaluations, the smallest reasonable interval is once per evaluation * so that the problem changes after every evaluation. This of course under the simplification @@ -13,124 +13,124 @@ import eva2.optimization.population.Population; * can not be taken into account (or just discretely approximated). * * @author M.Kronfeld - * - * Jan 4, 2007 - **/ + *

+ * Jan 4, 2007 + */ public abstract class AbstractSynchronousOptimizationProblem extends - AbstractDynamicOptimizationProblem { - - /** - * counts the evaluations since the last change in problem dynamics - */ - protected double evalsSinceChange; - /** - * holds the number of evaluations for which the environment regularly remains the same - */ - protected double constantProblemEvals; - /** - * measures the "distance" which the problem shifts when it changes - */ - protected double shiftPerChange; - //protected double timeIntPerEval = 1.; // better assume this to be constant + AbstractDynamicOptimizationProblem { + + /** + * counts the evaluations since the last change in problem dynamics + */ + protected double evalsSinceChange; + /** + * holds the number of evaluations for which the environment regularly remains the same + */ + protected double constantProblemEvals; + /** + * measures the "distance" which the problem shifts when it changes + */ + protected double shiftPerChange; + //protected double timeIntPerEval = 1.; // better assume this to be constant + + /** + * + */ + public AbstractSynchronousOptimizationProblem() { + evalsSinceChange = 0.; + constantProblemEvals = 99999; + shiftPerChange = 1.; + + } + - /** - * - */ - public AbstractSynchronousOptimizationProblem() { - evalsSinceChange = 0.; - constantProblemEvals = 99999; - shiftPerChange = 1.; - - } - - @Override public void initializeProblem() { - super.initializeProblem(); - evalsSinceChange = 0.; - + super.initializeProblem(); + evalsSinceChange = 0.; + } - - /* (non-Javadoc) - * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#changeProblemAt(double) - */ - @Override - protected void changeProblemAt(double problemTime) { - incProblemTime(shiftPerChange); - if (TRACE) { - System.out.println("problem shiftet at " + problemTime + " per " + shiftPerChange); - } - evalsSinceChange = 0.; - } - /* (non-Javadoc) - * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#problemToChangeAt(double) - */ - @Override - protected boolean problemToChangeAt(double problemTime) { - return (evalsSinceChange >= constantProblemEvals); - } - - /** - * Set the number of evaluations for which the problem is static. - * This is declared protected as it usually depends on further parameters of implementations. - * - * @param constEvals new value to set - */ - protected void setConstantProblemEvals(double constEvals) { - constantProblemEvals = constEvals; - if (TRACE) { - System.out.println("setConstantProblemEvals: " + constEvals); - } - } - - /* (non-Javadoc) - * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#countEvaluation() - */ - @Override - protected void countEvaluation() { - evalsSinceChange += 1.; - } - - /** - * Return the number of evaluations for which the problem is static. - * This is declared protected as it usually depends on further parameters of implementations. - * - * @return the number of evaluations for which the problem is static - */ - protected double getConstantProblemEvals() { - return constantProblemEvals; - } - + /* (non-Javadoc) + * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#changeProblemAt(double) + */ @Override - public void setFrequency(double frequency) { - super.setFrequency(frequency); - //if (frequency > 1.) System.out.println("warning, frequency should be <= 1 (setFrequency)"); - if (isFrequencyRelative()) { - // bogus. this must be reset right before population evaluation - setConstantProblemEvals(9999999); - } else { - // in absolute evals, so 1 means once per individual eval, .5 every second - setConstantProblemEvals(1/frequency); - } - } - - - /* (non-Javadoc) - * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#setFrequencyRelative(boolean) - */ - @Override - public void setFrequencyRelative(boolean frequencyRelative) { - super.setFrequencyRelative(frequencyRelative); - setFrequency(getFrequency()); // this looks stupid, but actually recalculates stuff for a changed relative switch - } - - + protected void changeProblemAt(double problemTime) { + incProblemTime(shiftPerChange); + if (TRACE) { + System.out.println("problem shiftet at " + problemTime + " per " + shiftPerChange); + } + evalsSinceChange = 0.; + } + + /* (non-Javadoc) + * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#problemToChangeAt(double) + */ @Override - public void evaluatePopulationStart(Population population) { - if (isFrequencyRelative()) { - // sets the number of evaluations without change when depending on the population size - setConstantProblemEvals(population.size()/getFrequency()); - } - } + protected boolean problemToChangeAt(double problemTime) { + return (evalsSinceChange >= constantProblemEvals); + } + + /** + * Set the number of evaluations for which the problem is static. + * This is declared protected as it usually depends on further parameters of implementations. + * + * @param constEvals new value to set + */ + protected void setConstantProblemEvals(double constEvals) { + constantProblemEvals = constEvals; + if (TRACE) { + System.out.println("setConstantProblemEvals: " + constEvals); + } + } + + /* (non-Javadoc) + * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#countEvaluation() + */ + @Override + protected void countEvaluation() { + evalsSinceChange += 1.; + } + + /** + * Return the number of evaluations for which the problem is static. + * This is declared protected as it usually depends on further parameters of implementations. + * + * @return the number of evaluations for which the problem is static + */ + protected double getConstantProblemEvals() { + return constantProblemEvals; + } + + @Override + public void setFrequency(double frequency) { + super.setFrequency(frequency); + //if (frequency > 1.) System.out.println("warning, frequency should be <= 1 (setFrequency)"); + if (isFrequencyRelative()) { + // bogus. this must be reset right before population evaluation + setConstantProblemEvals(9999999); + } else { + // in absolute evals, so 1 means once per individual eval, .5 every second + setConstantProblemEvals(1 / frequency); + } + } + + + /* (non-Javadoc) + * @see eva2.server.oa.go.OptimizationProblems.AbstractDynamicOptimizationProblem#setFrequencyRelative(boolean) + */ + @Override + public void setFrequencyRelative(boolean frequencyRelative) { + super.setFrequencyRelative(frequencyRelative); + setFrequency(getFrequency()); // this looks stupid, but actually recalculates stuff for a changed relative switch + } + + + @Override + public void evaluatePopulationStart(Population population) { + if (isFrequencyRelative()) { + // sets the number of evaluations without change when depending on the population size + setConstantProblemEvals(population.size() / getFrequency()); + } + } } diff --git a/src/eva2/optimization/problems/B1Problem.java b/src/eva2/optimization/problems/B1Problem.java index 8811a9f2..033849a7 100644 --- a/src/eva2/optimization/problems/B1Problem.java +++ b/src/eva2/optimization/problems/B1Problem.java @@ -7,48 +7,53 @@ import eva2.optimization.operator.mutation.MutateEAMixer; import eva2.optimization.operator.mutation.MutateGAGISwapBits; import eva2.optimization.operator.mutation.MutateGAUniform; import eva2.optimization.strategies.InterfaceOptimizer; + import java.util.BitSet; /** * The minimize bits problem for binary optimization. - * + *

* User: streiche * Date: 21.03.2003 * Time: 13:05:33 * To change this template use Options | File Templates. */ public class B1Problem extends AbstractProblemBinary implements java.io.Serializable { - public int m_ProblemDimension = 30; + public int m_ProblemDimension = 30; public B1Problem() { - super(); - this.getIndividualTemplate().setMutationOperator(new MutateEAMixer(new MutateGAGISwapBits(), new MutateGAUniform())); + super(); + this.getIndividualTemplate().setMutationOperator(new MutateEAMixer(new MutateGAGISwapBits(), new MutateGAUniform())); } - + public B1Problem(B1Problem b) { super.cloneObjects(b); - + this.m_ProblemDimension = b.m_ProblemDimension; } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new B1Problem(this); } - /** This is a simple method that evaluates a given Individual. The fitness + /** + * This is a simple method that evaluates a given Individual. The fitness * values of the individual will be set inside this method. - * @param b The BitSet that is to be evaluated. - * @param l The length of the BitSet. - * @return Double[] + * + * @param b The BitSet that is to be evaluated. + * @param l The length of the BitSet. + * @return Double[] */ @Override public double[] eval(BitSet b) { - double[] result = new double[1]; - int fitness = 0; + double[] result = new double[1]; + int fitness = 0; for (int i = 0; i < getProblemDimension(); i++) { if (b.get(i)) { @@ -59,9 +64,11 @@ public class B1Problem extends AbstractProblemBinary implements java.io.Serializ return result; } - /** This method allows you to output a string that describes a found solution + /** + * This method allows you to output a string that describes a found solution * in a way that is most suiteable for a given problem. - * @param individual The individual that is to be shown. + * + * @param individual The individual that is to be shown. * @return The description. */ @Override @@ -73,8 +80,10 @@ public class B1Problem extends AbstractProblemBinary implements java.io.Serializ return result; } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -84,7 +93,7 @@ public class B1Problem extends AbstractProblemBinary implements java.io.Serializ result += "Minimize Bits Problem:\n"; result += "The task is to reduce the number of TRUE Bits in the given bit string.\n"; result += "Parameters:\n"; - result += "Number of Bits: " + this.m_ProblemDimension +"\n"; + result += "Number of Bits: " + this.m_ProblemDimension + "\n"; result += "Solution representation:\n"; //result += this.template.getSolutionRepresentationFor(); return result; @@ -93,8 +102,10 @@ public class B1Problem extends AbstractProblemBinary implements java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -102,38 +113,46 @@ public class B1Problem extends AbstractProblemBinary implements java.io.Serializ return "Maximize number of bits"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The task in this problem is to maximize the number of false bits in a BitSet."; } - /** + /** * Set the problem dimension. - * + * * @param dim The problem dimension. */ public void setProblemDimension(int dim) { this.m_ProblemDimension = dim; } + @Override public int getProblemDimension() { return this.m_ProblemDimension; } + public String multiRunsTipText() { return "Length of the BitSet that is to be optimized."; } - /** This method allows you to choose the EA individual + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setEAIndividual(InterfaceDataTypeBinary indy) { this.template = (AbstractEAIndividual) indy; } + public InterfaceDataTypeBinary getEAIndividual() { return (InterfaceDataTypeBinary) this.template; } + public String EAIndividualTipText() { return "Choose the EAIndividual to use."; } diff --git a/src/eva2/optimization/problems/BKnapsackProblem.java b/src/eva2/optimization/problems/BKnapsackProblem.java index 5e642d7b..1dad9048 100644 --- a/src/eva2/optimization/problems/BKnapsackProblem.java +++ b/src/eva2/optimization/problems/BKnapsackProblem.java @@ -1,11 +1,11 @@ package eva2.optimization.problems; - import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeBinary; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.math.RNG; + import java.util.BitSet; /** @@ -17,141 +17,144 @@ import java.util.BitSet; */ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.Serializable { - private int m_Limit = 5000; - private double m_Punish = 2.0; - private double m_LocalSearch = 0.0; - private boolean m_Lamarckism = false; - private double m_ProblemSpecificInit = 0.0; + private int m_Limit = 5000; + private double m_Punish = 2.0; + private double m_LocalSearch = 0.0; + private boolean m_Lamarckism = false; + private double m_ProblemSpecificInit = 0.0; static final int[][] items = { - {334,-328}, - {303,-291}, - {228,-232}, - {229,-226}, - {346,-347}, - {256,-257}, - {243,-243}, - {334,-328}, - {382,-377}, - {236,-234}, - {301,-295}, - {215,-209}, - {298,-305}, - {313,-313}, - {219,-212}, - {215,-214}, - {250,-244}, - {380,-373}, - {319,-317}, - {392,-396}, - {304,-304}, - {249,-252}, - {337,-331}, - {368,-365}, - {356,-354}, - {267,-260}, - {258,-251}, - {248,-252}, - {391,-391}, - {277,-273}, - {293,-297}, - {213,-214}, - {223,-218}, - {353,-359}, - {337,-338}, - {389,-396}, - {251,-256}, - {344,-340}, - {243,-236}, - {368,-367}, - {380,-378}, - {274,-269}, - {289,-291}, - {346,-353}, - {271,-268}, - {286,-281}, - {294,-292}, - {279,-282}, - {226,-221}, - {344,-337}, - {353,-352}, - {266,-265}, - {391,-393}, - {202,-199}, - {224,-223}, - {333,-330}, - {369,-368}, - {301,-308}, - {241,-237}, - {240,-233}, - {236,-238}, - {217,-212}, - {308,-308}, - {324,-320}, - {218,-220}, - {356,-358}, - {236,-234}, - {310,-299}, - {382,-382}, - {350,-357}, - {377,-382}, - {359,-351}, - {322,-321}, - {351,-347}, - {315,-309}, - {389,-382}, - {212,-213}, - {212,-209}, - {352,-352}, - {217,-215}, - {369,-366}, - {398,-399}, - {320,-323}, - {343,-353}, - {329,-322}, - {338,-332}, - {289,-294}, - {341,-339}, - {201,-194}, - {234,-235}, - {392,-399}, - {344,-347}, - {371,-380}, - {286,-288}, - {210,-219}, - {220,-218}, - {253,-247}, - {392,-390}, - {319,-324}, - {392,-386}}; + {334, -328}, + {303, -291}, + {228, -232}, + {229, -226}, + {346, -347}, + {256, -257}, + {243, -243}, + {334, -328}, + {382, -377}, + {236, -234}, + {301, -295}, + {215, -209}, + {298, -305}, + {313, -313}, + {219, -212}, + {215, -214}, + {250, -244}, + {380, -373}, + {319, -317}, + {392, -396}, + {304, -304}, + {249, -252}, + {337, -331}, + {368, -365}, + {356, -354}, + {267, -260}, + {258, -251}, + {248, -252}, + {391, -391}, + {277, -273}, + {293, -297}, + {213, -214}, + {223, -218}, + {353, -359}, + {337, -338}, + {389, -396}, + {251, -256}, + {344, -340}, + {243, -236}, + {368, -367}, + {380, -378}, + {274, -269}, + {289, -291}, + {346, -353}, + {271, -268}, + {286, -281}, + {294, -292}, + {279, -282}, + {226, -221}, + {344, -337}, + {353, -352}, + {266, -265}, + {391, -393}, + {202, -199}, + {224, -223}, + {333, -330}, + {369, -368}, + {301, -308}, + {241, -237}, + {240, -233}, + {236, -238}, + {217, -212}, + {308, -308}, + {324, -320}, + {218, -220}, + {356, -358}, + {236, -234}, + {310, -299}, + {382, -382}, + {350, -357}, + {377, -382}, + {359, -351}, + {322, -321}, + {351, -347}, + {315, -309}, + {389, -382}, + {212, -213}, + {212, -209}, + {352, -352}, + {217, -215}, + {369, -366}, + {398, -399}, + {320, -323}, + {343, -353}, + {329, -322}, + {338, -332}, + {289, -294}, + {341, -339}, + {201, -194}, + {234, -235}, + {392, -399}, + {344, -347}, + {371, -380}, + {286, -288}, + {210, -219}, + {220, -218}, + {253, -247}, + {392, -390}, + {319, -324}, + {392, -386}}; public BKnapsackProblem() { super(); } - + public BKnapsackProblem(BKnapsackProblem b) { //AbstractOptimizationProblem - cloneObjects(b); + cloneObjects(b); // BKnapsackProblem - this.m_Limit = b.m_Limit; - this.m_Punish = b.m_Punish; - this.m_LocalSearch = b.m_LocalSearch; - this.m_Lamarckism = b.m_Lamarckism; + this.m_Limit = b.m_Limit; + this.m_Punish = b.m_Punish; + this.m_LocalSearch = b.m_LocalSearch; + this.m_Lamarckism = b.m_Lamarckism; } @Override public int getProblemDimension() { - return items.length; + return items.length; } - - /** This method returns a deep clone of the problem. - * @return the clone + + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new BKnapsackProblem(this); } - /** This method inits the Problem to log multiruns + /** + * This method inits the Problem to log multiruns */ @Override public void initializeProblem() { @@ -160,26 +163,28 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S protected void initIndy(int k, AbstractEAIndividual indy) { indy.init(this); - if (RNG.flipCoin(this.m_ProblemSpecificInit)) { - BitSet tmpSet = new BitSet(); - tmpSet.clear(); + if (RNG.flipCoin(this.m_ProblemSpecificInit)) { + BitSet tmpSet = new BitSet(); + tmpSet.clear(); - while (eval(tmpSet)[1] > 0) { - tmpSet.set(RNG.randomInt(0,items.length-1)); - } - ((InterfaceDataTypeBinary)indy).SetBinaryGenotype(tmpSet); - } + while (eval(tmpSet)[1] > 0) { + tmpSet.set(RNG.randomInt(0, items.length - 1)); + } + ((InterfaceDataTypeBinary) indy).SetBinaryGenotype(tmpSet); + } } - - /** This method evaluates a single individual and sets the fitness values - * @param individual The individual that is to be evalutated + + /** + * This method evaluates a single individual and sets the fitness values + * + * @param individual The individual that is to be evalutated */ @Override public void evaluate(AbstractEAIndividual individual) { - BitSet tmpBitSet; - double[] result; + BitSet tmpBitSet; + double[] result; - tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); + tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); result = this.eval(tmpBitSet); if (RNG.flipCoin(this.m_LocalSearch)) { // first remove surplus assets @@ -188,10 +193,10 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S int weakest = tmpBitSet.nextSetBit(0); for (int i = 0; i < items.length; i++) { if (tmpBitSet.get(i)) { - if ( ((-items[i][1])/((double)items[i][0])) < ((-items[weakest][1])/((double)items[weakest][0])) ) { + if (((-items[i][1]) / ((double) items[i][0])) < ((-items[weakest][1]) / ((double) items[weakest][0]))) { weakest = i; } - if ( ((-items[i][1])/((double)items[i][0])) == ((-items[weakest][1])/((double)items[weakest][0])) ) { + if (((-items[i][1]) / ((double) items[i][0])) == ((-items[weakest][1]) / ((double) items[weakest][0]))) { if (RNG.flipCoin(0.5)) { weakest = i; } @@ -208,10 +213,10 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S int stronger = -1; for (int i = 0; i < items.length; i++) { if (tmpBitSet.get(i)) { - if ( ((-items[i][1])/((double)items[i][0])) < ((-items[weakest][1])/((double)items[weakest][0])) ) { + if (((-items[i][1]) / ((double) items[i][0])) < ((-items[weakest][1]) / ((double) items[weakest][0]))) { weakest = i; } - if ( ((-items[i][1])/((double)items[i][0])) == ((-items[weakest][1])/((double)items[weakest][0])) ) { + if (((-items[i][1]) / ((double) items[i][0])) == ((-items[weakest][1]) / ((double) items[weakest][0]))) { if (RNG.flipCoin(0.5)) { weakest = i; } @@ -224,7 +229,7 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S int weight = 0; for (int i = 0; i < items.length; i++) { if (tmpBitSet.get(i)) { - weight += items[i][0]; + weight += items[i][0]; } } @@ -233,8 +238,7 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S // possible candidate if (stronger < 0) { stronger = i; - } - else { + } else { if (items[i][1] < items[stronger][1]) { stronger = i; } @@ -248,24 +252,26 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S } if (this.m_Lamarckism) { - ((InterfaceDataTypeBinary) individual).SetBinaryGenotype(tmpBitSet); + ((InterfaceDataTypeBinary) individual).SetBinaryGenotype(tmpBitSet); } } result[0] += 5100; individual.SetFitness(0, result[0]); } - /** This is a simple method that evaluates a given Individual. The fitness + /** + * This is a simple method that evaluates a given Individual. The fitness * values of the individual will be set inside this method. - * @param b The BitSet that is to be evaluated. - * @param l The length of the BitSet. - * @return Double[] + * + * @param b The BitSet that is to be evaluated. + * @param l The length of the BitSet. + * @return Double[] */ @Override public double[] eval(BitSet b) { - double[] result = new double[3]; + double[] result = new double[3]; - int l = items.length; + int l = items.length; if (getProblemDimension() != l) { System.err.println("Error in BKnapsack!"); } @@ -274,47 +280,50 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S result[2] = 0; // net worth for (int i = 0; i < l; i++) { if (b.get(i)) { - result[1] += items[i][0]; - result[2] += items[i][1]; + result[1] += items[i][0]; + result[2] += items[i][1]; } else { b.clear(i); } } // write the solution - result[1] = Math.max(0, result[1]- this.m_Limit); + result[1] = Math.max(0, result[1] - this.m_Limit); result[0] = (this.m_Punish * result[1]) + result[2]; return result; } - /** This method allows you to output a string that describes a found solution + /** + * This method allows you to output a string that describes a found solution * in a way that is most suiteable for a given problem. - * @param individual The individual that is to be shown. + * + * @param individual The individual that is to be shown. * @return The description. */ @Override public String getSolutionRepresentationFor(AbstractEAIndividual individual) { - BitSet tmpBitSet; - double[] report; - InterfaceDataTypeBinary tmpIndy; + BitSet tmpBitSet; + double[] report; + InterfaceDataTypeBinary tmpIndy; String result = "Single Knapsack problem:\n"; - tmpIndy = (InterfaceDataTypeBinary) individual; - tmpBitSet = tmpIndy.getBinaryData(); + tmpIndy = (InterfaceDataTypeBinary) individual; + tmpBitSet = tmpIndy.getBinaryData(); report = this.eval(tmpBitSet); result += individual.getStringRepresentation() + "\n"; result += "Is worth: " + Math.abs(report[2]) + " and "; if (report[1] == 0) { result += "does not exceed the weight limit!"; - } - else { + } else { result += "exceeds the weight limit by " + report[1]; } result += "\n"; return result; } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -347,8 +356,10 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -356,86 +367,114 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S return "Single Knapsack Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Maximize the value of the knapsack without exceeding the weight limit."; } - /** This method allows you to set the number of mulitruns that are to be performed, + /** + * This method allows you to set the number of mulitruns that are to be performed, * necessary for stochastic optimizers to ensure reliable results. + * * @param punish The number of multiruns that are to be performed */ public void setPunishment(double punish) { this.m_Punish = punish; } + public double getPunishment() { return this.m_Punish; } + public String punishmentTipText() { return "Rate of punishment if the Knapsack exceeds the weight limit."; } - /** This method allows you to choose the EA individual + + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setEAIndividual(InterfaceDataTypeBinary indy) { this.template = (AbstractEAIndividual) indy; } + public InterfaceDataTypeBinary getEAIndividual() { return (InterfaceDataTypeBinary) this.template; } + public String EAIndividualTipText() { return "Choose the EA-individual to use."; } - /** This method allows you to toggle the problemspecific + + /** + * This method allows you to toggle the problemspecific * initialization method, gives the chance of problem * specific initialization + * * @param b gives the chance of problemspecific initialization. */ public void setProblemSpecificInit(double b) { this.m_ProblemSpecificInit = b; } + public double getProblemSpecificInit() { return this.m_ProblemSpecificInit; } + public String problemSpecificInitTipText() { return "Gives the chance of problemspecific initialization."; } - /** This method allows you to toggle the problemspecific + + /** + * This method allows you to toggle the problemspecific * local search method, gives the chance of problem * specific local search + * * @param b gives the chance of problemspecific local search. */ public void setLocalSearch(double b) { this.m_LocalSearch = b; } + public double getLocalSearch() { return this.m_LocalSearch; } + public String localSearchTipText() { return "Gives the chance of local search"; } - /** This method allows you to toggle the use of Lamarckism. + + /** + * This method allows you to toggle the use of Lamarckism. + * * @param b toggles lamarckism. */ public void setLamarckism(boolean b) { this.m_Lamarckism = b; } + public boolean getLamarckism() { return this.m_Lamarckism; } + public String lamarckismTipText() { return "Lamarckism alters the genotype after the local search"; } - public int getWeightLimit() { - return m_Limit; - } - public void setWeightLimit(int mLimit) { - m_Limit = mLimit; - } - public String weightLimitTipText() { - return "Weight limit for the knapsack problem"; - } + public int getWeightLimit() { + return m_Limit; + } + + public void setWeightLimit(int mLimit) { + m_Limit = mLimit; + } + + public String weightLimitTipText() { + return "Weight limit for the knapsack problem"; + } } diff --git a/src/eva2/optimization/problems/ConstrHimmelblauProblem.java b/src/eva2/optimization/problems/ConstrHimmelblauProblem.java index 786d8754..e49fde81 100644 --- a/src/eva2/optimization/problems/ConstrHimmelblauProblem.java +++ b/src/eva2/optimization/problems/ConstrHimmelblauProblem.java @@ -3,84 +3,85 @@ package eva2.optimization.problems; import eva2.optimization.operator.constraint.AbstractConstraint; import eva2.optimization.operator.constraint.ConstraintCollection; import eva2.optimization.operator.constraint.IntervalConstraint; + import java.io.Serializable; import java.util.Vector; public class ConstrHimmelblauProblem extends AbstractProblemDouble implements Serializable { - private static double yOffset = 31025.5602425; // moving the optimum close to zero - private boolean useYOffset = true; - - public ConstrHimmelblauProblem() { - setWithConstraints(true); - setDefaultRange(100); - setConstraints(new AbstractConstraint[]{new ConstraintCollection(makeDefaultConstraints())}); - } + private static double yOffset = 31025.5602425; // moving the optimum close to zero + private boolean useYOffset = true; - public ConstrHimmelblauProblem( - ConstrHimmelblauProblem o) { - super(); - super.cloneObjects(o); - useYOffset=o.useYOffset; - } + public ConstrHimmelblauProblem() { + setWithConstraints(true); + setDefaultRange(100); + setConstraints(new AbstractConstraint[]{new ConstraintCollection(makeDefaultConstraints())}); + } + + public ConstrHimmelblauProblem( + ConstrHimmelblauProblem o) { + super(); + super.cloneObjects(o); + useYOffset = o.useYOffset; + } + + @Override + public Object clone() { + return new ConstrHimmelblauProblem(this); + } - @Override - public Object clone() { - return new ConstrHimmelblauProblem(this); - } - // @Override // public void initializeProblem() { // super.initializeProblem(); // setConstraints(new AbstractConstraint[]{new ConstraintCollection(makeDefaultConstraints())}); // } - public static AbstractConstraint[] makeDefaultConstraints() { - Vector constraints = new Vector(); - constraints.add(new IntervalConstraint("+(+(85.334407,*(0.0056858,*(x1,x4))), +(*(0.00026,*(x0,x3)),*(-0.0022053,*(x2,x4))))", 0, 92)); - constraints.add(new IntervalConstraint("+(+(80.51249,*(0.0071317,*(x1,x4))), +(*(0.0029955,*(x0,x1)),*(0.0021813,*(x2,x2))))", 90, 110)); - constraints.add(new IntervalConstraint("+(+(9.300961,*(0.0047026,*(x2,x4))), +(*(0.0012547,*(x0,x2)),*(0.0019085,*(x2,x3))))", 20, 25)); - - constraints.add(new IntervalConstraint(0, 78, 102)); - constraints.add(new IntervalConstraint(1, 33, 45)); - constraints.add(new IntervalConstraint(2, 27, 45)); - constraints.add(new IntervalConstraint(3, 27, 45)); - constraints.add(new IntervalConstraint(4, 27, 45)); - return constraints.toArray(new AbstractConstraint[constraints.size()]); - } + public static AbstractConstraint[] makeDefaultConstraints() { + Vector constraints = new Vector(); + constraints.add(new IntervalConstraint("+(+(85.334407,*(0.0056858,*(x1,x4))), +(*(0.00026,*(x0,x3)),*(-0.0022053,*(x2,x4))))", 0, 92)); + constraints.add(new IntervalConstraint("+(+(80.51249,*(0.0071317,*(x1,x4))), +(*(0.0029955,*(x0,x1)),*(0.0021813,*(x2,x2))))", 90, 110)); + constraints.add(new IntervalConstraint("+(+(9.300961,*(0.0047026,*(x2,x4))), +(*(0.0012547,*(x0,x2)),*(0.0019085,*(x2,x3))))", 20, 25)); - @Override - public double[] eval(double[] x) { - x = rotateMaybe(x); - double v=5.3578547*x[2]*x[2]+0.8356891*x[0]*x[4]+37.293239*x[0]-40792.141; - if (useYOffset) { - v+=yOffset; - } - return new double[]{v}; - } + constraints.add(new IntervalConstraint(0, 78, 102)); + constraints.add(new IntervalConstraint(1, 33, 45)); + constraints.add(new IntervalConstraint(2, 27, 45)); + constraints.add(new IntervalConstraint(3, 27, 45)); + constraints.add(new IntervalConstraint(4, 27, 45)); + return constraints.toArray(new AbstractConstraint[constraints.size()]); + } - @Override - public int getProblemDimension() { - return 5; - } - @Override - public String getName() { - return "Constrained Himmelblau Problem"; - } - - public static String globalInfo() { - return "Himmelblau's nonlinear optimization problem with 5 simple boundary constraints and 3 nonlinear boundary constraints."; - } + public double[] eval(double[] x) { + x = rotateMaybe(x); + double v = 5.3578547 * x[2] * x[2] + 0.8356891 * x[0] * x[4] + 37.293239 * x[0] - 40792.141; + if (useYOffset) { + v += yOffset; + } + return new double[]{v}; + } - public boolean isUseYOffset() { - return useYOffset; - } + @Override + public int getProblemDimension() { + return 5; + } - public void setUseYOffset(boolean useYOffset) { - this.useYOffset = useYOffset; - } - - public String useYOffsetTipText() { - return "Activate offset moving the optimum (close) to zero."; - } + @Override + public String getName() { + return "Constrained Himmelblau Problem"; + } + + public static String globalInfo() { + return "Himmelblau's nonlinear optimization problem with 5 simple boundary constraints and 3 nonlinear boundary constraints."; + } + + public boolean isUseYOffset() { + return useYOffset; + } + + public void setUseYOffset(boolean useYOffset) { + this.useYOffset = useYOffset; + } + + public String useYOffsetTipText() { + return "Activate offset moving the optimum (close) to zero."; + } } diff --git a/src/eva2/optimization/problems/ConstrPressureVessel.java b/src/eva2/optimization/problems/ConstrPressureVessel.java index 03416698..e2954ec2 100644 --- a/src/eva2/optimization/problems/ConstrPressureVessel.java +++ b/src/eva2/optimization/problems/ConstrPressureVessel.java @@ -7,133 +7,140 @@ import eva2.optimization.operator.constraint.ConstraintCollection; import eva2.optimization.operator.constraint.ConstraintHandlingEnum; import eva2.optimization.operator.constraint.ConstraintRelationEnum; import eva2.optimization.operator.constraint.GenericConstraint; + import java.util.Vector; public class ConstrPressureVessel extends AbstractProblemDouble { - private boolean discreteThickness = true; - private double minThickness=0.0625; - private double maxThickness=2; - private double minRad=10, maxRad=300; - private double minLen=10, maxLen=300; + private boolean discreteThickness = true; + private double minThickness = 0.0625; + private double maxThickness = 2; + private double minRad = 10, maxRad = 300; + private double minLen = 10, maxLen = 300; // L=200; // R=40.3239; // thickS=0.8125; // thickH=0.4375; - - public ConstrPressureVessel() { - setWithConstraints(true); - setConstraints(new AbstractConstraint[]{new ConstraintCollection(makeDefaultConstraints(), ConstraintHandlingEnum.penaltyAdditive, 1000)}); -// setConstraints(makeDefaultConstraints()); - } - - public ConstrPressureVessel(ConstrPressureVessel o) { - super(); - super.cloneObjects(o); - } - public static AbstractConstraint[] makeDefaultConstraints() { - Vector constraints = new Vector(); + public ConstrPressureVessel() { + setWithConstraints(true); + setConstraints(new AbstractConstraint[]{new ConstraintCollection(makeDefaultConstraints(), ConstraintHandlingEnum.penaltyAdditive, 1000)}); +// setConstraints(makeDefaultConstraints()); + } + + public ConstrPressureVessel(ConstrPressureVessel o) { + super(); + super.cloneObjects(o); + } + + public static AbstractConstraint[] makeDefaultConstraints() { + Vector constraints = new Vector(); // constraints.add(new IntervalConstraint("+(+(85.334407,*(0.0056858,*(x1,x4))), +(*(0.00026,*(x0,x3)),*(-0.0022053,*(x2,x4))))", 0, 92)); - constraints.add(new GenericConstraint("-(*(0.0193,x2),x0)", ConstraintRelationEnum.lessEqZero)); - constraints.add(new GenericConstraint("-(*(0.00954,x2),x1)", ConstraintRelationEnum.lessEqZero)); - constraints.add(new GenericConstraint("-(1296000, +(*(pi, *(pow2(x2),x3)),*(/(4,3),*(pi,pow3(x2))))))", ConstraintRelationEnum.lessEqZero)); - constraints.add(new GenericConstraint("-(x3,240)", ConstraintRelationEnum.lessEqZero)); + constraints.add(new GenericConstraint("-(*(0.0193,x2),x0)", ConstraintRelationEnum.lessEqZero)); + constraints.add(new GenericConstraint("-(*(0.00954,x2),x1)", ConstraintRelationEnum.lessEqZero)); + constraints.add(new GenericConstraint("-(1296000, +(*(pi, *(pow2(x2),x3)),*(/(4,3),*(pi,pow3(x2))))))", ConstraintRelationEnum.lessEqZero)); + constraints.add(new GenericConstraint("-(x3,240)", ConstraintRelationEnum.lessEqZero)); // for (Iterator iterator = constraints.iterator(); iterator.hasNext();) { // AbstractConstraint constr = iterator.next(); // constr.setHandlingMethod(ConstraintHandlingEnum.penaltyAdditive); // constr.setPenaltyFactor(10000); // } - return constraints.toArray(new AbstractConstraint[constraints.size()]); - } - - @Override - protected double[] getEvalArray(AbstractEAIndividual individual) { - double[] x = super.getEvalArray(individual); - if (discreteThickness) {// integer multiple of minimal thickness - int n=(int)(x[0]/minThickness); - x[0]=n*minThickness; - n=(int)(x[1]/minThickness); - x[1]=n*minThickness; - } - //double thickS=x[0], thickH=x[1], R=x[2], L=x[3]; + return constraints.toArray(new AbstractConstraint[constraints.size()]); + } + + @Override + protected double[] getEvalArray(AbstractEAIndividual individual) { + double[] x = super.getEvalArray(individual); + if (discreteThickness) {// integer multiple of minimal thickness + int n = (int) (x[0] / minThickness); + x[0] = n * minThickness; + n = (int) (x[1] / minThickness); + x[1] = n * minThickness; + } + //double thickS=x[0], thickH=x[1], R=x[2], L=x[3]; // x[0]=0.8125; //thickS=0.8125; // x[1]=0.4375; //thickH=0.4375; // x[2]=40.3239; //R=40.3239; // x[3]=200; //L=200; - return x; - } + return x; + } - @Override - public double[] eval(double[] x) { - double v, thickS=x[0], thickH=x[1], R=x[2], L=x[3]; + @Override + public double[] eval(double[] x) { + double v, thickS = x[0], thickH = x[1], R = x[2], L = x[3]; - v = 0.6224*thickS*R*L+1.7781*thickH*R*R+3.1661*thickS*thickS*L+19.84*thickS*thickS*R; + v = 0.6224 * thickS * R * L + 1.7781 * thickH * R * R + 3.1661 * thickS * thickS * L + 19.84 * thickS * thickS * R; // v = 0.6224*x(0)*x(2)*x(3)+1.7781*x(1)*x(2)*x(2)+3.1661*x(0)*x(0)*x(3)+19.84*x(0)*x(0)*x(2); - return new double[]{v}; - } + return new double[]{v}; + } - @Override - public int getProblemDimension() { - return 4; - } + @Override + public int getProblemDimension() { + return 4; + } - @Override - public Object clone() { - return new ConstrPressureVessel(this); - } - - @Override - public double getRangeLowerBound(int dim) { - switch (dim) { - case 0: - case 1: return minThickness/2; - case 2: return minRad; - case 3: return minLen; - } - System.err.println("Invalid dimension for lower bound (ConstrPressureVessel)"); - return 0.; + @Override + public Object clone() { + return new ConstrPressureVessel(this); + } + + @Override + public double getRangeLowerBound(int dim) { + switch (dim) { + case 0: + case 1: + return minThickness / 2; + case 2: + return minRad; + case 3: + return minLen; + } + System.err.println("Invalid dimension for lower bound (ConstrPressureVessel)"); + return 0.; // if (dim<=1) return minThickness/2; // else return minLen; } - @Override - public double getRangeUpperBound(int dim) { - switch (dim) { - case 0: - case 1: return maxThickness; - case 2: return maxRad; - case 3: return maxLen; - } - System.err.println("Invalid dimension for upper bound (ConstrPressureVessel)"); - return 100.; + @Override + public double getRangeUpperBound(int dim) { + switch (dim) { + case 0: + case 1: + return maxThickness; + case 2: + return maxRad; + case 3: + return maxLen; + } + System.err.println("Invalid dimension for upper bound (ConstrPressureVessel)"); + return 100.; // if (dim<=1) { // return maxThickness; // } else if (dim==2) return maxRad; // else return maxLen; } - @Override - public String getName() { - return "Constrained-Pressure-Vessel"; - } + @Override + public String getName() { + return "Constrained-Pressure-Vessel"; + } - public static String globalInfo() { - return "Minimize the material cost of a pressure vessel"; - } + public static String globalInfo() { + return "Minimize the material cost of a pressure vessel"; + } - @Override - public void hideHideable() { - super.hideHideable(); - GenericObjectEditor.setHideProperty(this.getClass(), "defaultRange", true); - } + @Override + public void hideHideable() { + super.hideHideable(); + GenericObjectEditor.setHideProperty(this.getClass(), "defaultRange", true); + } - public boolean isDiscreteThickness() { - return discreteThickness; - } + public boolean isDiscreteThickness() { + return discreteThickness; + } + + public void setDiscreteThickness(boolean discreteThickness) { + this.discreteThickness = discreteThickness; + } - public void setDiscreteThickness(boolean discreteThickness) { - this.discreteThickness = discreteThickness; - } - } diff --git a/src/eva2/optimization/problems/DynJumpProblem.java b/src/eva2/optimization/problems/DynJumpProblem.java index 368bd4da..5f3412cf 100644 --- a/src/eva2/optimization/problems/DynJumpProblem.java +++ b/src/eva2/optimization/problems/DynJumpProblem.java @@ -2,265 +2,271 @@ package eva2.optimization.problems; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.strategies.InterfaceOptimizer; + import java.io.FileWriter; import java.io.IOException; import java.io.Writer; -/** +/** * A dynamically "jumping" problem. The severity gives the length of one jump in problem space, occurring - * with the given frequency. - * + * with the given frequency. + * * @author Geraldine Hopf * @date 25.06.2007 */ public class DynJumpProblem extends AbstractDynTransProblem { - private static final long serialVersionUID = 2693154860448970283L; - - /* correlation value: 0.0 moving is at random, 1.0 moving is totally correlated to the previous moving */ - private double lambda = 0.0; - - protected double[] translation; - private double[] previousMovement; - protected double[] randomNumber; + private static final long serialVersionUID = 2693154860448970283L; - private double evaluations = 0.0; - - /* for the output file */ - private int changeCounter; - private Writer fw = null; - private String s = ""; - - public DynJumpProblem() { - super(); - translation = new double[getProblemDimension()]; - randomNumber = new double[getProblemDimension()]; - initialize(0.0, 0.1, 0.1); - changeCounter = 0; - } - public DynJumpProblem(DynJumpProblem other) { - other.clone(); - } + /* correlation value: 0.0 moving is at random, 1.0 moving is totally correlated to the previous moving */ + private double lambda = 0.0; + + protected double[] translation; + private double[] previousMovement; + protected double[] randomNumber; + + private double evaluations = 0.0; + + /* for the output file */ + private int changeCounter; + private Writer fw = null; + private String s = ""; + + public DynJumpProblem() { + super(); + translation = new double[getProblemDimension()]; + randomNumber = new double[getProblemDimension()]; + initialize(0.0, 0.1, 0.1); + changeCounter = 0; + } + + public DynJumpProblem(DynJumpProblem other) { + other.clone(); + } @Override - protected double getTranslation(int dim, double time) { - return translation[dim]; - } - - + protected double getTranslation(int dim, double time) { + return translation[dim]; + } + + @Override - protected void changeProblemAt(double problemTime) { - super.changeProblemAt(problemTime); - makeTranslation(); - /* prooving results */ - if (TRACE) { - writeFile(); - } - ++changeCounter; - } - + protected void changeProblemAt(double problemTime) { + super.changeProblemAt(problemTime); + makeTranslation(); + /* prooving results */ + if (TRACE) { + writeFile(); + } + ++changeCounter; + } + @Override - protected void countEvaluation() { - super.countEvaluation(); - evaluations += 1.; - } - - protected void makeTranslation() { - /* will be shifted with shift, creation is the same like previousMovement*/ - double shift[] = new double[getProblemDimension()]; - double norm = 0.0; - for (int i = 0; i < getProblemDimension(); ++i) { - shift[i] = rand.nextGaussian(); - norm += Math.pow(shift[i], 2); - } + protected void countEvaluation() { + super.countEvaluation(); + evaluations += 1.; + } + + protected void makeTranslation() { + /* will be shifted with shift, creation is the same like previousMovement*/ + double shift[] = new double[getProblemDimension()]; + double norm = 0.0; + for (int i = 0; i < getProblemDimension(); ++i) { + shift[i] = rand.nextGaussian(); + norm += Math.pow(shift[i], 2); + } /* normalize */ - if (norm > 0.0){ - norm = getSeverity() / Math.sqrt(norm); - } else { - norm = 0.0; // rounding errors - } - double norm2 = 0.0; - for (int i = 0; i < getProblemDimension(); ++i) { + if (norm > 0.0) { + norm = getSeverity() / Math.sqrt(norm); + } else { + norm = 0.0; // rounding errors + } + double norm2 = 0.0; + for (int i = 0; i < getProblemDimension(); ++i) { /* crux: if lambda = 1, only previousMovement is calculated * if lambda = 0, only random is calculated * other rand and previousMovement are weighted */ - shift[i] = (1 - getLambda()) * (norm * shift[i])+ getLambda() * previousMovement[i]; - norm2 += Math.pow(shift[i], 2); - } - if (norm2 > 0.0) { - norm2 = getSeverity() / Math.sqrt(norm2); - } else { - norm2 = 0.0; - } - - for (int i = 0; i < getProblemDimension(); ++i) { - shift[i] = norm2 * shift[i]; + shift[i] = (1 - getLambda()) * (norm * shift[i]) + getLambda() * previousMovement[i]; + norm2 += Math.pow(shift[i], 2); + } + if (norm2 > 0.0) { + norm2 = getSeverity() / Math.sqrt(norm2); + } else { + norm2 = 0.0; + } + + for (int i = 0; i < getProblemDimension(); ++i) { + shift[i] = norm2 * shift[i]; /* test if still between boundaries, if not bounce it off like a pool ball */ - if (translation[i] + shift[i] < range[0][0]) { - translation[i] = 2.0 * range[0][0] - translation[i] - shift[i]; - shift[i] *= -1.0; - } else if (translation[i] + shift[i] > range[0][1]) { - translation[i] = 2.0 * range[0][1] - translation[i] - shift[i]; - shift[i] *= -1.0; - } else { - translation[i] += shift[i]; - } + if (translation[i] + shift[i] < range[0][0]) { + translation[i] = 2.0 * range[0][0] - translation[i] - shift[i]; + shift[i] *= -1.0; + } else if (translation[i] + shift[i] > range[0][1]) { + translation[i] = 2.0 * range[0][1] - translation[i] - shift[i]; + shift[i] *= -1.0; + } else { + translation[i] += shift[i]; + } /* Update previousMovement */ - previousMovement[i] = shift[i]; - } - if (TRACE) { - System.out.print("Jumped to "); - for (int i = 0; i < getProblemDimension(); i++) { + previousMovement[i] = shift[i]; + } + if (TRACE) { + System.out.print("Jumped to "); + for (int i = 0; i < getProblemDimension(); i++) { System.out.print(" " + translation[i]); } - System.out.println(); - } - } + System.out.println(); + } + } @Override - public void initializeProblem() { - super.initializeProblem(); - translation = new double[getProblemDimension()]; - evalsSinceChange = 0.0; - evaluations = 0.0; - changeCounter = 0; + public void initializeProblem() { + super.initializeProblem(); + translation = new double[getProblemDimension()]; + evalsSinceChange = 0.0; + evaluations = 0.0; + changeCounter = 0; /* if lambda > 0.0 initialize the first random direction */ - previousMovement = new double[getProblemDimension()]; - double norm = 0.0; - for (int i = 0; i < getProblemDimension(); ++i) { + previousMovement = new double[getProblemDimension()]; + double norm = 0.0; + for (int i = 0; i < getProblemDimension(); ++i) { /* previousMovement has values between -0.5 and 0.5 -> direction of movement */ - previousMovement[i] = rand.nextGaussian(); + previousMovement[i] = rand.nextGaussian(); /* needed to standardize to moveLength */ - norm += Math.pow(previousMovement[i], 2); - } + norm += Math.pow(previousMovement[i], 2); + } /* (a[]/ |a[]|) = length(1) * (a[]/ |a[]|) * moveLength = length(moveLength) * |a[]| = sqare_root( (sum (a_i)^2) ) * norm = moveLength / |a[]| * moveLenght = getSeverity() */ - if (norm > 0.0) { - norm = getSeverity() / Math.sqrt(norm); - } else { - norm = 0.0; // rounding errors - } + if (norm > 0.0) { + norm = getSeverity() / Math.sqrt(norm); + } else { + norm = 0.0; // rounding errors + } /* now previousMovement is standardized */ - for (int i = 0; i < getProblemDimension(); ++i) { - previousMovement[i] = norm * previousMovement[i]; - } - } - - - - - @Override - public Object clone() { - return new DynJumpProblem(this); - } - - @Override - public AbstractEAIndividual getCurrentOptimum() { - return null; - } - -/************************************************************************** - * These are for the GUI - * - */ - - @Override - public String getStringRepresentationForProblem(InterfaceOptimizer opt) { - return "DynJumpProblem"; - } - @Override - public String getName() { - return "DynJumpProblem"; - } - public static String globalInfo() { - return "A real valued problem jumping dynamically."; + for (int i = 0; i < getProblemDimension(); ++i) { + previousMovement[i] = norm * previousMovement[i]; + } } - - public String severityTipText() { - return "length of the jump"; - } - public double getLambda() { - return lambda; - } - public void setLambda(double lambda) { - this.lambda = lambda; - } - public String lambdaTipText() { - return "direction of movement: [0,1] 0 = random, 1 = dependent"; - } - /************************************************************************** - * These are for debugging and determining the output file - * - */ - - public void myPrint(double[] toPrint) { - for (int i = 0; i < toPrint.length; ++i){ - System.out.print(toPrint[i] + " "); - } - System.out.println(""); - } - - public void myPrint(double[][] toPrint) { - for (int i = 0; i < toPrint.length; i ++){ - for (int j = 0; j < toPrint[i].length; ++j){ - System.out.print(toPrint[i][j] + " "); - } - System.out.println(""); - } - System.out.println(""); - } - public void writeFile() { - if (fw == null) { - try { - fw = new FileWriter( "DynJumpProblem.txt" ); - } - catch ( IOException e ) { - System.err.println( "Konnte Datei nicht erstellen" ); - } - } else { - try - { - fw.write("Problem wurde " + changeCounter + " mal geaendert!\n"); - fw.write(evaluations + " Evaluierungen wurden gemacht\n"); - fw.write(myPrints(translation)); - - } - catch ( IOException e ) { } - finally { - if ( fw != null ) { - try { fw.flush(); } catch ( IOException e ) { } - } - } - } - } - public String myPrints(double[][] toPrint) { - for (int i = 0; i < toPrint.length; i ++){ - for (int j = 0; j < toPrint[i].length; ++j){ - if (j != getProblemDimension()) { - s += toPrint[i][j] + "\t"; - } - } - s += "\n"; - } - s += "\n"; - return s; - } - - public String myPrints(double[] toPrint) { - for (int i = 0; i < toPrint.length; i ++){ - s += toPrint[i] + "\t"; - s += "\n"; - } - s += "\n"; - return s; - } + @Override + public Object clone() { + return new DynJumpProblem(this); + } + + @Override + public AbstractEAIndividual getCurrentOptimum() { + return null; + } + + /** + * *********************************************************************** + * These are for the GUI + */ + + @Override + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + return "DynJumpProblem"; + } + + @Override + public String getName() { + return "DynJumpProblem"; + } + + public static String globalInfo() { + return "A real valued problem jumping dynamically."; + } + + public String severityTipText() { + return "length of the jump"; + } + + public double getLambda() { + return lambda; + } + + public void setLambda(double lambda) { + this.lambda = lambda; + } + + public String lambdaTipText() { + return "direction of movement: [0,1] 0 = random, 1 = dependent"; + } + + /** + * *********************************************************************** + * These are for debugging and determining the output file + */ + + public void myPrint(double[] toPrint) { + for (int i = 0; i < toPrint.length; ++i) { + System.out.print(toPrint[i] + " "); + } + System.out.println(""); + } + + public void myPrint(double[][] toPrint) { + for (int i = 0; i < toPrint.length; i++) { + for (int j = 0; j < toPrint[i].length; ++j) { + System.out.print(toPrint[i][j] + " "); + } + System.out.println(""); + } + System.out.println(""); + } + + public void writeFile() { + if (fw == null) { + try { + fw = new FileWriter("DynJumpProblem.txt"); + } catch (IOException e) { + System.err.println("Konnte Datei nicht erstellen"); + } + } else { + try { + fw.write("Problem wurde " + changeCounter + " mal geaendert!\n"); + fw.write(evaluations + " Evaluierungen wurden gemacht\n"); + fw.write(myPrints(translation)); + + } catch (IOException e) { + } finally { + if (fw != null) { + try { + fw.flush(); + } catch (IOException e) { + } + } + } + } + } + + public String myPrints(double[][] toPrint) { + for (int i = 0; i < toPrint.length; i++) { + for (int j = 0; j < toPrint[i].length; ++j) { + if (j != getProblemDimension()) { + s += toPrint[i][j] + "\t"; + } + } + s += "\n"; + } + s += "\n"; + return s; + } + + public String myPrints(double[] toPrint) { + for (int i = 0; i < toPrint.length; i++) { + s += toPrint[i] + "\t"; + s += "\n"; + } + s += "\n"; + return s; + } } diff --git a/src/eva2/optimization/problems/ERPStarter.java b/src/eva2/optimization/problems/ERPStarter.java index e982bc94..64038c35 100644 --- a/src/eva2/optimization/problems/ERPStarter.java +++ b/src/eva2/optimization/problems/ERPStarter.java @@ -23,157 +23,159 @@ import eva2.tools.ToolBox; import eva2.tools.math.Mathematics; public class ERPStarter { - - /** - * Start an external runtime problem with some basic configs. The - * default variant uses equally weighs all objectives through an equally weighted sum. - * Arguments: --csv --cmd --maxEvals [--multiObjective] [--gui] - * @param args - */ - public static void main(String[] args) { - ExternalRuntimeProblem erp; - boolean useMultiObjective=false, startGUI=false; - // define the number of evaluations - int maxEvals = 5000; - // prefix for data output file - set null to deactivate - String outputFilePrefix = "erpTest"; - - /** Argument handling ****************/ - String[] keys= new String[]{"--gui", "--multiObjective", "--csv", "--cmd", "--maxEvals"}; - int[] arities = new int[]{0, 0, 1, 1, 1}; - Object[] values = new Object[6]; - - Integer[] unknownArgs = StringTools.parseArguments(args, keys, arities, values, true); - - if (unknownArgs.length>0 || (values[2]==null) || (values[3]==null) || (values[4]==null)) { - System.err.println("Missing or unrecognized command line options: "); - for (int i=0; i --cmd --maxEvals [--multiObjective] [--gui] + * + * @param args + */ + public static void main(String[] args) { + ExternalRuntimeProblem erp; + boolean useMultiObjective = false, startGUI = false; + // define the number of evaluations + int maxEvals = 5000; + // prefix for data output file - set null to deactivate + String outputFilePrefix = "erpTest"; + + /** Argument handling ****************/ + String[] keys = new String[]{"--gui", "--multiObjective", "--csv", "--cmd", "--maxEvals"}; + int[] arities = new int[]{0, 0, 1, 1, 1}; + Object[] values = new Object[6]; + + Integer[] unknownArgs = StringTools.parseArguments(args, keys, arities, values, true); + + if (unknownArgs.length > 0 || (values[2] == null) || (values[3] == null) || (values[4] == null)) { + System.err.println("Missing or unrecognized command line options: "); + for (int i = 0; i < unknownArgs.length; i++) { System.err.println(" " + args[unknownArgs[i]]); } - System.err.println("Use with: --csv --cmd --maxEvals [--multiObjective] [--gui]"); - return; - } - System.out.println("Parsing file: " + values[2]); - erp = parseCSV((String)values[2]); - String cmd = (String)values[3]; - - maxEvals = Integer.parseInt((String)values[4]); - System.out.println("Setting maxEvals: " + maxEvals); - useMultiObjective=(values[1]!=null); - startGUI=(values[0]!=null); - // set target function and working directory - System.out.println("Setting target function command: " + cmd); - erp.setCommand(cmd); - int indexOfLastSlash = cmd.lastIndexOf(System.getProperty("file.separator")); - erp.setWorkingDirectory(cmd.substring(0, indexOfLastSlash)); - - /******************/ - // create optimization instance - InterfaceOptimizer opt = null; - if (useMultiObjective) { - // this uses a multi-objective strategy - erp.setMosoConverter(new MOSONoConvert()); - opt = OptimizerFactory.createMultiObjectiveEA(new GeneticAlgorithm(), 50, erp, null); - } else { - // this uses a single objective (5,20)-CMA-ES with equally weighted criteria + System.err.println("Use with: --csv --cmd --maxEvals [--multiObjective] [--gui]"); + return; + } + System.out.println("Parsing file: " + values[2]); + erp = parseCSV((String) values[2]); + String cmd = (String) values[3]; + + maxEvals = Integer.parseInt((String) values[4]); + System.out.println("Setting maxEvals: " + maxEvals); + useMultiObjective = (values[1] != null); + startGUI = (values[0] != null); + // set target function and working directory + System.out.println("Setting target function command: " + cmd); + erp.setCommand(cmd); + int indexOfLastSlash = cmd.lastIndexOf(System.getProperty("file.separator")); + erp.setWorkingDirectory(cmd.substring(0, indexOfLastSlash)); + + /******************/ + // create optimization instance + InterfaceOptimizer opt = null; + if (useMultiObjective) { + // this uses a multi-objective strategy + erp.setMosoConverter(new MOSONoConvert()); + opt = OptimizerFactory.createMultiObjectiveEA(new GeneticAlgorithm(), 50, erp, null); + } else { + // this uses a single objective (5,20)-CMA-ES with equally weighted criteria // erp.setMosoConverter(new MOSOWeightedFitness()); - opt = OptimizerFactory.createEvolutionStrategy(5, 20, false, new MutateESRankMuCMA(), 1., new CrossoverESDefault(), 0., new SelectBestIndividuals(), erp, null); - } + opt = OptimizerFactory.createEvolutionStrategy(5, 20, false, new MutateESRankMuCMA(), 1., new CrossoverESDefault(), 0., new SelectBestIndividuals(), erp, null); + } - System.out.println("Optimizer instance: " + BeanInspector.toString(opt)); - System.out.println("Problem instance: " + BeanInspector.toString(erp)); - // Instantiate optimization - OptimizationParameters params = new OptimizationParameters(opt, erp, new EvaluationTerminator(maxEvals)); - if (startGUI) { - Main.initClientGUI(params, null, null, null); - } else { - OptimizerRunnable rnbl = new OptimizerRunnable(params, new StatisticsStandalone(outputFilePrefix, 1, 3, true), false); - // actually start the optimization - OptimizerFactory.optimize(rnbl); + System.out.println("Optimizer instance: " + BeanInspector.toString(opt)); + System.out.println("Problem instance: " + BeanInspector.toString(erp)); + // Instantiate optimization + OptimizationParameters params = new OptimizationParameters(opt, erp, new EvaluationTerminator(maxEvals)); + if (startGUI) { + Main.initClientGUI(params, null, null, null); + } else { + OptimizerRunnable rnbl = new OptimizerRunnable(params, new StatisticsStandalone(outputFilePrefix, 1, 3, true), false); + // actually start the optimization + OptimizerFactory.optimize(rnbl); - // some data output - InterfaceSolutionSet solSet = opt.getAllSolutions(); - Population sols = solSet.getSolutions(); - System.out.println("*** Solutions found: " + sols.size()); - System.out.println("Best allover solution: " + AbstractEAIndividual.getDefaultStringRepresentation((AbstractEAIndividual)rnbl.getResult())); - System.out.println("Best last solution: " + AbstractEAIndividual.getDefaultStringRepresentation(solSet.getCurrentPopulation().getBestEAIndividual())); - System.out.println("Last solution set:"); - for (int i=0; i1)) { - double[][] weights = ToolBox.getCols(filteredObjectives, 6); - if (Mathematics.areFinite(weights)<0) { - erp.setMosoConverter(new MOSOWeightedFitness(weights)); - } - } - erp.setProblemDimension(filteredVars.length); - erp.setRange(range); + /** + * Parse a csv file as in the example. Reads columns 2,3,4,5 where counting starts at zero. + * Checks for the column entries at index 5 to contain a value of 1. These columns are interpreted as + * target function variables with boundaries and seed. Note that all boundary values must contain + * valid numbers. If a single seed value is empty, no initialization range is used. + * + * @param fname name of the csv data file + * @return an instance of ExternalRuntimeProblem + */ + public static ExternalRuntimeProblem parseCSV(String fname, int isVariableColIndex, int lowerBoundIndex, + int upperBoundIndex, int initialPosColIndex, int initialPosBoxLenColIndex, + int isObjectiveColIndex, int fitWeightsColIndex) { + double defaultInitialBoxLenRatio = 0.05; // by default, the init range is 5% of the domain range in a component + // this assumes that data colums are as in the example csv + // parse only columns with index 2-9. Note that these will be reindexed to 0,1,2,3 + int[] filterCols = new int[7]; + filterCols[0] = isVariableColIndex; + filterCols[1] = lowerBoundIndex; + filterCols[2] = upperBoundIndex; + filterCols[3] = initialPosColIndex; + filterCols[4] = initialPosBoxLenColIndex; + filterCols[5] = isObjectiveColIndex; + filterCols[6] = fitWeightsColIndex; +// double[][] dat = BasicResourceLoader.loadDoubleData(fname, null, ";", 1, -1, new int[]{2,3,4,5,6,7,8,9}); + double[][] dat = BasicResourceLoader.loadDoubleData(fname, null, ";", 1, -1, filterCols); +// System.out.println(BeanInspector.toString(dat)); + double[][] filteredVars = ToolBox.filterBy(dat, 0, 1., 1.); // filter only those with a value of one in column isVariable + double[][] range = ToolBox.getCols(filteredVars, 1, 2); // get columns with lower and upper bound + double[][] initPos = ToolBox.getCols(filteredVars, 3); // get column with initial position center + double[][] initBoxLen = ToolBox.getCols(filteredVars, 4); // get column with initialization range box length + double[][] filteredObjectives = ToolBox.filterBy(dat, 5, 1., 1.); // filter those with a value of one in isObjective + + ExternalRuntimeProblem erp = new ExternalRuntimeProblem(); + if (filteredObjectives != null && (filteredObjectives.length > 1)) { + double[][] weights = ToolBox.getCols(filteredObjectives, 6); + if (Mathematics.areFinite(weights) < 0) { + erp.setMosoConverter(new MOSOWeightedFitness(weights)); + } + } + erp.setProblemDimension(filteredVars.length); + erp.setRange(range); // erp.setInitialRange(range); - // produce an initial range around the seed position if available, otherwise use domain range - double[][] initialRange = new double[filteredVars.length][2]; - for (int i=0; i individual.getFitness(0))) { - this.m_OverallBest = (AbstractEAIndividual)individual.clone(); + this.m_OverallBest = (AbstractEAIndividual) individual.clone(); } } - + @Override public void evaluatePopulationEnd(Population population) { - super.evaluatePopulationEnd(population); - if (m_MosoConverter!=null) { + super.evaluatePopulationEnd(population); + if (m_MosoConverter != null) { m_MosoConverter.convertMultiObjective2SingleObjective(population); } } - - protected double[] getXVector(AbstractEAIndividual individual) { - double[] x; - x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; + + protected double[] getXVector(AbstractEAIndividual individual) { + double[] x; + x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); - return x; - } - - public static List runProcess(String[] parameters, String workingDir) { - List params = new ArrayList(parameters.length); - for (String str : parameters) { - params.add(str); - } - return runProcess(params, workingDir); - } - - /** - * Parse the output values of a process by line and by whitespace characters and some others - * returning a string list. - * - * @param parameters - * @param workingDir - * @return - */ - public static List runProcess(List parameters, String workingDir) { - String colSepRegExp= "[\\s;:|]"; // \s for whitespaces, double quoting necessary! - Process process; - ProcessBuilder pb; - List results = new ArrayList(); - try { - pb = new ProcessBuilder(parameters); - pb.directory(new File(workingDir)); - process=pb.start(); - BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); - Thread thread = new MonitorInputStreamThread(process.getErrorStream());//grab the Error Stream - thread.start(); - String line; - while ((line = br.readLine()) != null) { - line = line.trim(); - String[] parts = line.split(colSepRegExp); - for (String str : parts) { - results.add(str); - } -// results.add(line); - } - br.close(); - } catch (IOException e) { - String msg="IO Error when calling external command! Invalid command for ExternalRuntimeProblem?"; - System.err.println(msg); - e.printStackTrace(); - throw new RuntimeException(msg); - } - return results; - } + return x; + } - @Override - public double[] eval(double[] x) { - if (x==null) { - throw new RuntimeException("Error, x=null value received in ExternalRuntimeProblem.eval"); + public static List runProcess(String[] parameters, String workingDir) { + List params = new ArrayList(parameters.length); + for (String str : parameters) { + params.add(str); } - ArrayList fitList = new ArrayList(); - - List parameters=new ArrayList(); - parameters.add(this.m_Command); - if (additionalArg!=null && (additionalArg.length()>0)) { - parameters.add(additionalArg); - } - for(int i=0;i res = runProcess(parameters, m_WorkingDir); - try { - for (String str : res) { - fitList.add(new Double(str)); - } - } catch (NumberFormatException e) { - System.err.println("Error: " + m_Command + " delivered malformatted output for " + BeanInspector.toString(x)); - e.printStackTrace(); - } - double[] fit = new double[fitList.size()]; - for (int i=0; i runProcess(List parameters, String workingDir) { + String colSepRegExp = "[\\s;:|]"; // \s for whitespaces, double quoting necessary! + Process process; + ProcessBuilder pb; + List results = new ArrayList(); + try { + pb = new ProcessBuilder(parameters); + pb.directory(new File(workingDir)); + process = pb.start(); + BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); + Thread thread = new MonitorInputStreamThread(process.getErrorStream());//grab the Error Stream + thread.start(); + String line; + while ((line = br.readLine()) != null) { + line = line.trim(); + String[] parts = line.split(colSepRegExp); + for (String str : parts) { + results.add(str); + } +// results.add(line); + } + br.close(); + } catch (IOException e) { + String msg = "IO Error when calling external command! Invalid command for ExternalRuntimeProblem?"; + System.err.println(msg); + e.printStackTrace(); + throw new RuntimeException(msg); + } + return results; + } + + @Override + public double[] eval(double[] x) { + if (x == null) { + throw new RuntimeException("Error, x=null value received in ExternalRuntimeProblem.eval"); + } + ArrayList fitList = new ArrayList(); + + List parameters = new ArrayList(); + parameters.add(this.m_Command); + if (additionalArg != null && (additionalArg.length() > 0)) { + parameters.add(additionalArg); + } + for (int i = 0; i < this.m_ProblemDimension; i++) { + String p = prepareParameter(x, i); + parameters.add(p); + } + + List res = runProcess(parameters, m_WorkingDir); + try { + for (String str : res) { + fitList.add(new Double(str)); + } + } catch (NumberFormatException e) { + System.err.println("Error: " + m_Command + " delivered malformatted output for " + BeanInspector.toString(x)); + e.printStackTrace(); + } + double[] fit = new double[fitList.size()]; + for (int i = 0; i < fit.length; i++) { + fit[i] = fitList.get(i); + } + return fit; + } + + /** + * How to prepare a given parameter within a double array to present it * to the external program. - * + * * @param x * @param i * @return */ protected String prepareParameter(double[] x, int i) { - return new String(""+x[i]); - } + return new String("" + x[i]); + } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -339,7 +346,7 @@ implements Interface2DBorderProblem, InterfaceProblemDouble, InterfaceHasInitRan StringBuffer sb = new StringBuffer(200); sb.append("External Runtime Problem:\n"); sb.append("Here the individual codes a vector of real number x is to be minimized on a user given external problem.\nParameters:\n"); - sb.append("Dimension : "); + sb.append("Dimension : "); sb.append(this.m_ProblemDimension); return sb.toString(); @@ -348,8 +355,10 @@ implements Interface2DBorderProblem, InterfaceProblemDouble, InterfaceHasInitRan /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -357,21 +366,23 @@ implements Interface2DBorderProblem, InterfaceProblemDouble, InterfaceHasInitRan return "External Runtime Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Use an external command as target function."; } - + public String[] getGOEPropertyUpdateLinks() { - return new String[] {"problemDimension", "initialRange", "problemDimension", "range"}; + return new String[]{"problemDimension", "initialRange", "problemDimension", "range"}; } - /** + /** * Length of the x vector that is to be optimized. Be sure to keep * the ranges fit in length. - * + * * @param t Length of the x vector that is to be optimized */ public void setProblemDimension(int t) { @@ -379,40 +390,50 @@ implements Interface2DBorderProblem, InterfaceProblemDouble, InterfaceHasInitRan this.m_Range.adaptRowCount(t); this.m_initRange.adaptRowCount(t); } + @Override public int getProblemDimension() { return this.m_ProblemDimension; } + public String problemDimensionTipText() { return "Domain dimension of the problem"; } - - /** Length of the x vector at is to be optimized + + /** + * Length of the x vector at is to be optimized + * * @param t Length of the x vector at is to be optimized */ public void setCommand(String t) { this.m_Command = t; } + public String getCommand() { return this.m_Command; } + public String commandTipText() { return "External command to be called for evaluation"; } - - /** Working dir of the external runtime + + /** + * Working dir of the external runtime + * * @param t working directory */ public void setWorkingDirectory(String t) { this.m_WorkingDir = t; } + public String getWorkingDirectory() { return this.m_WorkingDir; } + public String workingDirectoryTipText() { return "The working directory"; } - + // /** This method allows you to toggle the application of a simple test constraint. // * @param b The mode for the test constraint // */ @@ -427,38 +448,46 @@ implements Interface2DBorderProblem, InterfaceProblemDouble, InterfaceHasInitRan // } public InterfaceMOSOConverter getMosoConverter() { - return m_MosoConverter; - } - public void setMosoConverter(InterfaceMOSOConverter mMosoConverter) { - m_MosoConverter = mMosoConverter; - } - public String mosoConverterTipText() { - return "Possible conversion of multi-objective fitness to single objective fitness."; - } + return m_MosoConverter; + } - /** This method allows you to choose the EA individual + public void setMosoConverter(InterfaceMOSOConverter mMosoConverter) { + m_MosoConverter = mMosoConverter; + } + + public String mosoConverterTipText() { + return "Possible conversion of multi-objective fitness to single objective fitness."; + } + + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setEAIndividual(InterfaceDataTypeDouble indy) { - this.template = (AbstractEAIndividual)indy; + this.template = (AbstractEAIndividual) indy; } + @Override public InterfaceDataTypeDouble getEAIndividual() { - return (InterfaceDataTypeDouble)this.template; + return (InterfaceDataTypeDouble) this.template; } + @Override - public double functionValue(double[] point) { - return eval(project2DPoint(point))[0]; - } + public double functionValue(double[] point) { + return eval(project2DPoint(point))[0]; + } + @Override public double[] project2DPoint(double[] point) { - return Mathematics.expandVector(point, getProblemDimension(), 0.); + return Mathematics.expandVector(point, getProblemDimension(), 0.); } + @Override - public double[][] get2DBorder() { - return getRange().getDoubleArrayShallow(); - } - + public double[][] get2DBorder() { + return getRange().getDoubleArrayShallow(); + } + // /** // * @return the m_upperBound // */ @@ -492,49 +521,53 @@ implements Interface2DBorderProblem, InterfaceProblemDouble, InterfaceHasInitRan // return "Lower bound of the search space in any dimension."; // } - public String additionalArgumentTipText() { - return "Optionally define an additional (first) argument for the command line command."; - } - - public String getAdditionalArgument() { - return additionalArg; - } - public void setAdditionalArgument(String additionalArg) { - this.additionalArg = additionalArg; - } + public String additionalArgumentTipText() { + return "Optionally define an additional (first) argument for the command line command."; + } -// @Override + public String getAdditionalArgument() { + return additionalArg; + } + + public void setAdditionalArgument(String additionalArg) { + this.additionalArg = additionalArg; + } + + // @Override @Override - public Object getInitRange() { - if (m_initRange==null) { - if (m_Range==null) { - System.err.println("Warning, neither range nor initRange has been set in ExternalRuntimeProblem!"); - } - return m_Range.getDoubleArrayShallow(); - } else { - return m_initRange.getDoubleArrayShallow(); - } - } - public void setInitialRange(double[][] range) { - PropertyDoubleArray pRange = new PropertyDoubleArray(range); - this.setInitialRange(pRange); - } - + public Object getInitRange() { + if (m_initRange == null) { + if (m_Range == null) { + System.err.println("Warning, neither range nor initRange has been set in ExternalRuntimeProblem!"); + } + return m_Range.getDoubleArrayShallow(); + } else { + return m_initRange.getDoubleArrayShallow(); + } + } + + public void setInitialRange(double[][] range) { + PropertyDoubleArray pRange = new PropertyDoubleArray(range); + this.setInitialRange(pRange); + } + public void setInitialRange(PropertyDoubleArray range) { - if (range.getNumRows() 1."; } - /** This method allows you to set/get Iterations - * @param iters The Iterations. + /** + * This method allows you to set/get Iterations + * + * @param iters The Iterations. */ public void setIterations(int iters) { if (iters < 2) { @@ -138,9 +159,11 @@ public class F10Problem extends AbstractProblemDoubleOffset implements Interface } this.m_Iterations = iters; } + public int getIterations() { return this.m_Iterations; } + public String iterationsTipText() { return "Choose the number of iterations per evaluation."; } diff --git a/src/eva2/optimization/problems/F11Problem.java b/src/eva2/optimization/problems/F11Problem.java index 55acdbaf..a7bd132c 100644 --- a/src/eva2/optimization/problems/F11Problem.java +++ b/src/eva2/optimization/problems/F11Problem.java @@ -11,46 +11,52 @@ import eva2.optimization.individuals.ESIndividualDoubleData; */ public class F11Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable { - private double m_D = 4000; + private double m_D = 4000; public F11Problem() { this.problemDimension = 10; this.template = new ESIndividualDoubleData(); setDefaultRange(600); } - + public F11Problem(F11Problem b) { super(b); - this.m_D = b.m_D; + this.m_D = b.m_D; } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new F11Problem(this); } - /** Ths method allows you to evaluate a double[] to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + /** + * Ths method allows you to evaluate a double[] to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] eval(double[] x) { - x = rotateMaybe(x); + x = rotateMaybe(x); double[] result = new double[1]; double tmpProd = 1; for (int i = 0; i < x.length; i++) { - double xi = x[i]- xOffset; - result[0] += Math.pow(xi, 2); - tmpProd *= Math.cos((xi)/Math.sqrt(i+1)); + double xi = x[i] - xOffset; + result[0] += Math.pow(xi, 2); + tmpProd *= Math.cos((xi) / Math.sqrt(i + 1)); } - result[0] = ((result[0]/this.m_D) - tmpProd + 1)+ yOffset; + result[0] = ((result[0] / this.m_D) - tmpProd + 1) + yOffset; return result; } - /** This method returns a string describing the optimization problem. + /** + * This method returns a string describing the optimization problem. + * * @return The description. */ public String getStringRepresentationForProblem() { @@ -58,7 +64,7 @@ public class F11Problem extends AbstractProblemDoubleOffset implements Interface result += "F11 Griewank Function:\n"; result += "Parameters:\n"; - result += "Dimension : " + this.problemDimension +"\n"; + result += "Dimension : " + this.problemDimension + "\n"; result += "Noise level : " + this.getNoise() + "\n"; // result += "Solution representation:\n"; //result += this.template.getSolutionRepresentationFor(); @@ -68,8 +74,10 @@ public class F11Problem extends AbstractProblemDoubleOffset implements Interface /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -77,24 +85,30 @@ public class F11Problem extends AbstractProblemDoubleOffset implements Interface return "F11-Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Griewank Function"; } - /** This method allows you to set/get d. - * @param d The d. + /** + * This method allows you to set/get d. + * + * @param d The d. */ public void setD(double d) { // if (d < 1) d = 1;// how can this be limited to [1,2] if 4000 is default? // if (d > 2) d = 2;// MK FIXED: this obviously was a copy-paste error from F10 this.m_D = d; } + public double getD() { return this.m_D; } + public String dTipText() { return "Set D (=4000)."; } diff --git a/src/eva2/optimization/problems/F12Problem.java b/src/eva2/optimization/problems/F12Problem.java index 64b4504d..495d2421 100644 --- a/src/eva2/optimization/problems/F12Problem.java +++ b/src/eva2/optimization/problems/F12Problem.java @@ -10,41 +10,48 @@ import java.io.Serializable; * To change this template use File | Settings | File Templates. */ public class F12Problem extends AbstractProblemDoubleOffset implements Serializable { - private final static double f12range = 5.; + private final static double f12range = 5.; public F12Problem() { setDefaultRange(f12range); } + public F12Problem(F12Problem b) { super(b); } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new F12Problem(this); } - /** Ths method allows you to evaluate a double[] to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + /** + * Ths method allows you to evaluate a double[] to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] eval(double[] x) { - x = rotateMaybe(x); + x = rotateMaybe(x); double[] result = new double[1]; double tmp = 0;//-5; - for (int i = 1; i < x.length-1; i++) { - tmp += Math.pow(x[i]- xOffset, 2); + for (int i = 1; i < x.length - 1; i++) { + tmp += Math.pow(x[i] - xOffset, 2); } - double x0 = x[0]- xOffset; - result[0] = yOffset +((Math.exp(-5*x0*x0)+2*Math.exp(-5*Math.pow(1-x0, 2)))*Math.exp(-5*tmp)); + double x0 = x[0] - xOffset; + result[0] = yOffset + ((Math.exp(-5 * x0 * x0) + 2 * Math.exp(-5 * Math.pow(1 - x0, 2))) * Math.exp(-5 * tmp)); return result; } - /** This method returns a string describing the optimization problem. + /** + * This method returns a string describing the optimization problem. + * * @return The description. */ public String getStringRepresentationForProblem() { @@ -52,7 +59,7 @@ public class F12Problem extends AbstractProblemDoubleOffset implements Serializa result += "F12 Galar:\n"; result += "Parameters:\n"; - result += "Dimension : " + this.problemDimension +"\n"; + result += "Dimension : " + this.problemDimension + "\n"; result += "Noise level : " + this.getNoise() + "\n"; result += "Solution representation:\n"; //result += this.template.getSolutionRepresentationFor(); @@ -62,8 +69,10 @@ public class F12Problem extends AbstractProblemDoubleOffset implements Serializa /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -71,7 +80,9 @@ public class F12Problem extends AbstractProblemDoubleOffset implements Serializa return "F12 Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/F13Problem.java b/src/eva2/optimization/problems/F13Problem.java index 9cb4e030..a010457f 100644 --- a/src/eva2/optimization/problems/F13Problem.java +++ b/src/eva2/optimization/problems/F13Problem.java @@ -14,58 +14,66 @@ public class F13Problem extends AbstractProblemDoubleOffset implements Interface this.template = new ESIndividualDoubleData(); setDefaultRange(500); } + public F13Problem(F13Problem b) { - super(b); - } - public F13Problem(int dim) { - super(); - setProblemDimension(dim); + super(b); } - /** This method returns a deep clone of the problem. - * @return the clone + public F13Problem(int dim) { + super(); + setProblemDimension(dim); + } + + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new F13Problem(this); } - + @Override public double getRangeLowerBound(int dim) { - return -500; //-512.03; - } - - @Override - public double getRangeUpperBound(int dim) { - return 500;// 511.97; - } - - @Override - public void hideHideable() { - super.hideHideable(); - GenericObjectEditor.setHideProperty(this.getClass(), "defaultRange", true); - } - - /** Ths method allows you to evaluate a double[] to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + return -500; //-512.03; + } + + @Override + public double getRangeUpperBound(int dim) { + return 500;// 511.97; + } + + @Override + public void hideHideable() { + super.hideHideable(); + GenericObjectEditor.setHideProperty(this.getClass(), "defaultRange", true); + } + + /** + * Ths method allows you to evaluate a double[] to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] eval(double[] x) { - x = rotateMaybe(x); + x = rotateMaybe(x); double[] result = new double[1]; result[0] = yOffset; - - for (int i=0; ialphas.length)) { // only recreate if really necessary - alphas=null; - A=null; - B=null; - } - } - - @Override - public Object clone() { - return new F19Problem(this); - } - - @Override - public String getName() { - return "F19-Problem"; - } - - public static String globalInfo() { - return "Fletcher-Powell function with up to 2^n optima from Shir&Baeck, PPSN 2006, after Bäck 1996. Alphas and Matrices A and B are randomly created with a fixed seed."; - } - - @Override - public SolutionHistogram getHistogram() { - if (getProblemDimension()<15) { - return new SolutionHistogram(0, 8, 16); + private double[] transform(double[] x) { + double[] v = new double[dim]; + Arrays.fill(v, 0.); + for (int i = 0; i < dim; i++) { + for (int j = 0; j < dim; j++) { + v[i] += get(A, i, j) * Math.sin(x[j]) + get(B, i, j) * Math.cos(x[j]); } - else { - return new SolutionHistogram(0, 40000, 16); - } - } + } + return v; + } + + /** + * Calculate partial derivation of the B_i function by the j-th coordinate + * + * @param x + * @param i + * @return + */ + private double derivedTransform(double[] x, int i, int j) { + double v = get(A, i, j) * Math.cos(x[j]) - get(B, i, j) * Math.sin(x[j]); + return v; + } + + /** + * Get a value in row i, col j, from matrix M (represented as vector). + * + * @param M + * @param i + * @param j + * @return + */ + private int get(int[] M, int i, int j) { + return M[i * dim + j]; + } @Override - public double[] getFirstOrderGradients(double[] x) { - x = rotateMaybe(x); - double[] res = new double[x.length]; - double[] Bs = transform(x); - - for (int k=0; k alphas.length)) { // only recreate if really necessary + alphas = null; + A = null; + B = null; + } + } + + @Override + public Object clone() { + return new F19Problem(this); + } + + @Override + public String getName() { + return "F19-Problem"; + } + + public static String globalInfo() { + return "Fletcher-Powell function with up to 2^n optima from Shir&Baeck, PPSN 2006, after Bäck 1996. Alphas and Matrices A and B are randomly created with a fixed seed."; + } + + @Override + public SolutionHistogram getHistogram() { + if (getProblemDimension() < 15) { + return new SolutionHistogram(0, 8, 16); + } else { + return new SolutionHistogram(0, 40000, 16); + } + } + + @Override + public double[] getFirstOrderGradients(double[] x) { + x = rotateMaybe(x); + double[] res = new double[x.length]; + double[] Bs = transform(x); + + for (int k = 0; k < getProblemDimension(); k++) { + double sum = 0; + for (int i = 0; i < getProblemDimension(); i++) { + sum += (-2 * As[i] * derivedTransform(x, i, k) + 2 * Bs[i] * derivedTransform(x, i, k)); + } + res[k] = sum; + } + return res; + } } diff --git a/src/eva2/optimization/problems/F1Problem.java b/src/eva2/optimization/problems/F1Problem.java index 07dbc56a..9bfe6046 100644 --- a/src/eva2/optimization/problems/F1Problem.java +++ b/src/eva2/optimization/problems/F1Problem.java @@ -7,30 +7,31 @@ import eva2.tools.math.Mathematics; * F1 Sphere Problem */ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2DBorderProblem, InterfaceHasInitRange, java.io.Serializable, InterfaceFirstOrderDerivableProblem { - private double initialRangeRatio=1.; // reduce to initialize in a smaller subrange of the original range (in the corner box) - + private double initialRangeRatio = 1.; // reduce to initialize in a smaller subrange of the original range (in the corner box) + public F1Problem() { - super(); - setDefaultRange(10); + super(); + setDefaultRange(10); } - + public F1Problem(F1Problem b) { - super(); - super.cloneObjects(b); + super(); + super.cloneObjects(b); } - + public F1Problem(int dim) { - super(dim); + super(dim); } - + public F1Problem(int dim, double defRange) { - this(dim); - setDefaultRange(defRange); + this(dim); + setDefaultRange(defRange); } - + /** * This method returns a deep clone of the problem. - * @return the clone + * + * @return the clone */ @Override public Object clone() { @@ -39,24 +40,26 @@ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2 /** * This method allows you to evaluate a simple bit string to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] eval(double[] x) { - x = rotateMaybe(x); + x = rotateMaybe(x); double[] result = new double[1]; result[0] = yOffset; // add an offset in solution space for (int i = 0; i < x.length; i++) { - result[0] += Math.pow(x[i] - this.xOffset, 2); + result[0] += Math.pow(x[i] - this.xOffset, 2); } return result; } /** * This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -64,7 +67,7 @@ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2 StringBuffer sb = new StringBuffer(200); sb.append("F1 Sphere model:\n"); sb.append("Here the individual codes a vector of real number x and F1(x)= x^2 is to be minimized.\nParameters:\n"); - sb.append("Dimension : "); + sb.append("Dimension : "); sb.append(this.problemDimension); sb.append("\nNoise level : "); sb.append(this.getNoise()); @@ -72,11 +75,13 @@ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2 } /** - * These are for GUI - */ + * These are for GUI + */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -84,7 +89,9 @@ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2 return "F1-Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { @@ -92,33 +99,33 @@ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2 } @Override - public double[] getFirstOrderGradients(double[] x) { - x = rotateMaybe(x); - // first order partial derivation in direction x_i is 2*x_i - double[] grads=new double[x.length]; - for (int i=0; i * For gnuplot: x *sin(sqrt(abs(-x+y+1)))*cos(sqrt(abs(x+y+1)))+(y+1)*cos(sqrt(abs(-x+y+1)))*sin(sqrt(abs(x+y+1))) - * */ -public class F20Problem extends AbstractProblemDouble implements Serializable, InterfaceInterestingHistogram{ - private int dim=10; - private boolean shiftFit = false; - - public F20Problem() { - setDefaultRange(512.); - } - - public F20Problem(int dim, boolean rotate) { - this(); - setProblemDimension(dim); - setDoRotation(rotate); - } - - public F20Problem(F20Problem o) { - super(o); - setDefaultRange(512); - this.dim = o.dim; - this.setShiftFit(o.isShiftFit()); - } +public class F20Problem extends AbstractProblemDouble implements Serializable, InterfaceInterestingHistogram { + private int dim = 10; + private boolean shiftFit = false; - @Override - public double[] eval(double[] x) { - x = rotateMaybe(x); - double sum=getYOffset(); - - for (int i=0; ithresh) { - // add a step to tmpP - Mathematics.svvAddScaled(dx*dir, normedVect, pos, tmpP); - // evaluate tmpP - tmpFit = prob.eval(tmpP)[fitCrit]; - if (tmpFit < oldFit) { - // if tmpP is better than pos continue at new pos - double[] tmp=pos; - pos = tmpP; - tmpP=tmp; - oldFit = tmpFit; - } else { - // otherwise invert direction, reduce step, continue - dx*=0.73; - dir*=-1; - } - } - return pos; - } - - private boolean listOfOptimaNeedsUpdate() { - if (state_initializing_optima) { + // a line search along a vector + double[] tmpP = pos.clone(); + double[] normedVect = Mathematics.normVect(vect); + double dx = initStep; + double tmpFit, oldFit = prob.eval(pos)[fitCrit]; + + int dir = 1; + while (dx > thresh) { + // add a step to tmpP + Mathematics.svvAddScaled(dx * dir, normedVect, pos, tmpP); + // evaluate tmpP + tmpFit = prob.eval(tmpP)[fitCrit]; + if (tmpFit < oldFit) { + // if tmpP is better than pos continue at new pos + double[] tmp = pos; + pos = tmpP; + tmpP = tmp; + oldFit = tmpFit; + } else { + // otherwise invert direction, reduce step, continue + dx *= 0.73; + dir *= -1; + } + } + return pos; + } + + private boolean listOfOptimaNeedsUpdate() { + if (state_initializing_optima) { + return false; + } // avoid recursive call during refining with GDA + if (m_ListOfOptima == null || (m_ListOfOptima.size() != (1 + 2 * getProblemDimension()))) { + return true; + } else { // the number of optima is corret - now check different offset or rotation by comparing one fitness value + AbstractEAIndividual indy = m_ListOfOptima.getEAIndividual(1); + double[] curFit = eval(indy.getDoublePosition()); + if (Math.abs(Mathematics.dist(curFit, indy.getFitness(), 2)) > 1e-10) { + return true; + } else { return false; - } // avoid recursive call during refining with GDA - if (m_ListOfOptima==null || (m_ListOfOptima.size() != (1+2*getProblemDimension()))) { - return true; - } else { // the number of optima is corret - now check different offset or rotation by comparing one fitness value - AbstractEAIndividual indy = m_ListOfOptima.getEAIndividual(1); - double[] curFit = eval(indy.getDoublePosition()); - if (Math.abs(Mathematics.dist(curFit, indy.getFitness(), 2))>1e-10) { - return true; - } else { - return false; - } - } + } + } // else { // if (listOfOptima.isEmpty()) return true; // else { @@ -293,12 +305,12 @@ public class F8Problem extends AbstractProblemDoubleOffset // return false; // } // } - } - - private void addOptimum(double[] pos) { - AbstractProblemDouble.addUnrotatedOptimum(m_ListOfOptima, this, pos); - } - + } + + private void addOptimum(double[] pos) { + AbstractProblemDouble.addUnrotatedOptimum(m_ListOfOptima, this, pos); + } + // private double[] refineSolution(double[] pos) { // Population population = new Population(); // InterfaceDataTypeDouble tmpIndy; diff --git a/src/eva2/optimization/problems/F9Problem.java b/src/eva2/optimization/problems/F9Problem.java index f37ce760..0df6bfc7 100644 --- a/src/eva2/optimization/problems/F9Problem.java +++ b/src/eva2/optimization/problems/F9Problem.java @@ -7,34 +7,41 @@ public class F9Problem extends AbstractProblemDoubleOffset implements java.io.Se public F9Problem() { this.template = new ESIndividualDoubleData(); } + public F9Problem(F9Problem b) { super(b); } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new F9Problem(this); } - /** Ths method allows you to evaluate a double[] to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + /** + * Ths method allows you to evaluate a double[] to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] eval(double[] x) { - x = rotateMaybe(x); + x = rotateMaybe(x); double[] result = new double[1]; - result[0] = yOffset; + result[0] = yOffset; for (int i = 0; i < x.length; i++) { - result[0] += (i+1)*Math.pow(x[i]- xOffset, 2); + result[0] += (i + 1) * Math.pow(x[i] - xOffset, 2); } return result; } - /** This method returns a string describing the optimization problem. + /** + * This method returns a string describing the optimization problem. + * * @return The description. */ public String getStringRepresentationForProblem() { @@ -42,7 +49,7 @@ public class F9Problem extends AbstractProblemDoubleOffset implements java.io.Se result += "F9 Weighted Sphere Model:\n"; result += "Parameters:\n"; - result += "Dimension : " + this.problemDimension +"\n"; + result += "Dimension : " + this.problemDimension + "\n"; result += "Noise level : " + this.getNoise() + "\n"; result += "Solution representation:\n"; //result += this.template.getSolutionRepresentationFor(); @@ -52,8 +59,10 @@ public class F9Problem extends AbstractProblemDoubleOffset implements java.io.Se /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -61,7 +70,9 @@ public class F9Problem extends AbstractProblemDoubleOffset implements java.io.Se return "F9 Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/FLensProblem.java b/src/eva2/optimization/problems/FLensProblem.java index 834b1366..831751fa 100644 --- a/src/eva2/optimization/problems/FLensProblem.java +++ b/src/eva2/optimization/problems/FLensProblem.java @@ -9,6 +9,7 @@ import eva2.optimization.modules.OptimizationParameters; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.math.RNG; + import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; @@ -28,18 +29,18 @@ import javax.swing.JTextArea; class MyLensViewer extends JPanel implements InterfaceSolutionViewer { /** - * - */ - private static final long serialVersionUID = 7945150208043416139L; - Population indiesToPaint=new Population(); -// private double[] m_BestVariables; + * + */ + private static final long serialVersionUID = 7945150208043416139L; + Population indiesToPaint = new Population(); + // private double[] m_BestVariables; // private double m_BestFitness; - private int m_Height, m_Width; - FLensProblem m_LensProblem; + private int m_Height, m_Width; + FLensProblem m_LensProblem; - public MyLensViewer (FLensProblem f) { + public MyLensViewer(FLensProblem f) { initView(f); - Dimension d = new Dimension (280, 220); + Dimension d = new Dimension(280, 220); this.setPreferredSize(d); this.setMinimumSize(d); resetView(); @@ -47,30 +48,30 @@ class MyLensViewer extends JPanel implements InterfaceSolutionViewer { @Override public void initView(AbstractOptimizationProblem prob) { - this.m_LensProblem = (FLensProblem)prob; + this.m_LensProblem = (FLensProblem) prob; } - + @Override public void resetView() { // this.m_BestFitness = Double.POSITIVE_INFINITY; // this.m_BestVariables = new double[10]; - ESIndividualDoubleData dummy = new ESIndividualDoubleData(); - dummy.setFitness(new double[]{Double.POSITIVE_INFINITY}); - indiesToPaint = new Population(); + ESIndividualDoubleData dummy = new ESIndividualDoubleData(); + dummy.setFitness(new double[]{Double.POSITIVE_INFINITY}); + indiesToPaint = new Population(); } - + @Override public void paint(Graphics g) { - Shape tmpShape; - BufferedImage bufferedImage; - BasicStroke ds = new BasicStroke(); - Stroke dashStroke; - int mag = 10; - int centerLens, centerScreen, segment; + Shape tmpShape; + BufferedImage bufferedImage; + BasicStroke ds = new BasicStroke(); + Stroke dashStroke; + int mag = 10; + int centerLens, centerScreen, segment; // lineStroke = ds; // pointStroke = new BasicStroke(ds.getLineWidth(), ds.getEndCap(), ds.getLineJoin(), ds.getMiterLimit() , new float[] {1, 4}, 0); - dashStroke = new BasicStroke(ds.getLineWidth(), ds.getEndCap(), ds.getLineJoin(), ds.getMiterLimit() , new float[] {8, 8}, 0); + dashStroke = new BasicStroke(ds.getLineWidth(), ds.getEndCap(), ds.getLineJoin(), ds.getMiterLimit(), new float[]{8, 8}, 0); super.paint(g); if (g == null) { @@ -92,7 +93,7 @@ class MyLensViewer extends JPanel implements InterfaceSolutionViewer { m_Width = winDim.width; // m_CenterX = m_Width/2; // m_CenterY = m_Height/2; - + // if (this.m_Height == 0) this.m_Height = 250; // if (this.m_Width == 0) this.m_Width = 350; // System.out.println(" h w cx cy " + m_Height + " " + m_Width + " " + m_CenterX + " " + m_CenterY ); @@ -106,13 +107,13 @@ class MyLensViewer extends JPanel implements InterfaceSolutionViewer { // now start to plot some interesting stuff //draw the mid line g2D.setPaint(Color.black); - g2D.drawLine(0, this.m_Height/2, this.m_Width, this.m_Height/2); - centerLens = 5 + 50; - centerScreen = centerLens + (int)this.m_LensProblem.m_FocalLength*10; - segment = 10*(int)this.m_LensProblem.m_Radius*2/(this.m_LensProblem.m_ProblemDimension-1); + g2D.drawLine(0, this.m_Height / 2, this.m_Width, this.m_Height / 2); + centerLens = 5 + 50; + centerScreen = centerLens + (int) this.m_LensProblem.m_FocalLength * 10; + segment = 10 * (int) this.m_LensProblem.m_Radius * 2 / (this.m_LensProblem.m_ProblemDimension - 1); g2D.setStroke(dashStroke); - g2D.drawLine(centerLens, this.m_Height/2+(int)this.m_LensProblem.m_Radius*10, centerLens, this.m_Height/2 -(int)this.m_LensProblem.m_Radius*10); - g2D.drawLine(centerScreen, this.m_Height/2+(int)this.m_LensProblem.m_Radius*10+10, centerScreen, this.m_Height/2 -(int)this.m_LensProblem.m_Radius*10-10); + g2D.drawLine(centerLens, this.m_Height / 2 + (int) this.m_LensProblem.m_Radius * 10, centerLens, this.m_Height / 2 - (int) this.m_LensProblem.m_Radius * 10); + g2D.drawLine(centerScreen, this.m_Height / 2 + (int) this.m_LensProblem.m_Radius * 10 + 10, centerScreen, this.m_Height / 2 - (int) this.m_LensProblem.m_Radius * 10 - 10); g2D.setStroke(ds); // System.out.println("indies to paint: " + indiesToPaint.size()); paintLens(m_LensProblem.m_ProblemDimension, m_Height, m_LensProblem.m_Radius, mag, centerLens, centerScreen, segment, g2D); @@ -121,39 +122,39 @@ class MyLensViewer extends JPanel implements InterfaceSolutionViewer { } private void paintLens(int dim, int height, double radius, int mag, int centerLens, int centerScreen, int segment, Graphics2D g2D) { - for (int i=0; i individual.getFitness(0))) { - this.m_OverallBest = (AbstractEAIndividual)individual.clone(); - } - } + fitness = this.doEvaluation(x); + for (int i = 0; i < fitness.length; i++) { + // add noise to the fitness + fitness[i] += RNG.gaussianDouble(this.m_Noise); + fitness[i] += this.m_YOffSet; + // set the fitness of the individual + individual.SetFitness(i, fitness[i]); + } + if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { + this.m_OverallBest = (AbstractEAIndividual) individual.clone(); + } + } - /** Ths method allows you to evaluate a simple bit string to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. - */ - public double[] doEvaluation(double[] x) { - double fitness = 0; - double[] ret = new double[1]; + /** + * Ths method allows you to evaluate a simple bit string to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. + */ + public double[] doEvaluation(double[] x) { + double fitness = 0; + double[] ret = new double[1]; // set a minimum value for the thickness of the lens for (int i = 0; i < x.length; i++) { @@ -389,232 +403,275 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser // Here the thickness of the middle segment of the lens is added to the fitness // to permit the optimization to reduce the overall thickness of the lens if (this.m_UseMaterialConst) { - fitness += x[(int)(x.length/2)]; - } + fitness += x[(int) (x.length / 2)]; + } ret[0] = fitness; return ret; - } + } - /** this method will return the deviations - * @param x The lens + /** + * this method will return the deviations + * + * @param x The lens * @return double[] */ public double[] testLens(double[] x) { - double m_SegmentHight = 2 * m_Radius / (x.length - 1); - double[] result = new double[x.length-1]; + double m_SegmentHight = 2 * m_Radius / (x.length - 1); + double[] result = new double[x.length - 1]; // Computation of fitness. Uses an approximation for very thin lenses. // The fitness is the sum over all segments of the deviation from the center // of focus of a beam running through a segment. for (int i = 1; i < x.length; i++) { - result[i-1] = m_Radius - m_SegmentHight / 2 - m_SegmentHight * (i - 1) - m_FocalLength / m_SegmentHight * (m_Epsilon - 1) * (x[i] - x[i-1]); + result[i - 1] = m_Radius - m_SegmentHight / 2 - m_SegmentHight * (i - 1) - m_FocalLength / m_SegmentHight * (m_Epsilon - 1) * (x[i] - x[i - 1]); } return result; } - /** This method allows you to output a string that describes a found solution - * in a way that is most suiteable for a given problem. - * @param individual The individual that is to be shown. - * @return The description. - */ + /** + * This method allows you to output a string that describes a found solution + * in a way that is most suiteable for a given problem. + * + * @param individual The individual that is to be shown. + * @return The description. + */ @Override - public String getSolutionRepresentationFor(AbstractEAIndividual individual) { - this.evaluate(individual); - String result = "FX problem:\n"; - result += individual.getStringRepresentation() + "\n"; - result += "Y = " + individual.getFitness(0); - return result; - } - - /** This method allows you to output a string that describes a found solution - * in a way that is most suiteable for a given problem. - * @param optimizer The individual that is to be shown. - * @return The description. - */ - public String getFinalReportOn(InterfaceOptimizer optimizer){ - String result = optimizer.getStringRepresentation() +"\n"; - result += this.getSolutionRepresentationFor(this.m_OverallBest); - return result; - } + public String getSolutionRepresentationFor(AbstractEAIndividual individual) { + this.evaluate(individual); + String result = "FX problem:\n"; + result += individual.getStringRepresentation() + "\n"; + result += "Y = " + individual.getFitness(0); + return result; + } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method allows you to output a string that describes a found solution + * in a way that is most suiteable for a given problem. + * + * @param optimizer The individual that is to be shown. + * @return The description. + */ + public String getFinalReportOn(InterfaceOptimizer optimizer) { + String result = optimizer.getStringRepresentation() + "\n"; + result += this.getSolutionRepresentationFor(this.m_OverallBest); + return result; + } + + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override public String getStringRepresentationForProblem(InterfaceOptimizer opt) { - String result = ""; + String result = ""; - result += "FX Problem:\n"; - result += "Here the individual codes a vector of real number x and FX(x)= x is to be minimized.\n"; - result += "Parameters:\n"; - result += "Dimension : " + this.m_ProblemDimension +"\n"; - result += "Noise level : " + this.m_Noise + "\n"; - result += "Solution representation:\n"; - //result += this.template.getSolutionRepresentationFor(); - return result; - } + result += "FX Problem:\n"; + result += "Here the individual codes a vector of real number x and FX(x)= x is to be minimized.\n"; + result += "Parameters:\n"; + result += "Dimension : " + this.m_ProblemDimension + "\n"; + result += "Noise level : " + this.m_Noise + "\n"; + result += "Solution representation:\n"; + //result += this.template.getSolutionRepresentationFor(); + return result; + } - /** This method allows you to request a graphical representation for a given - * individual. - */ + /** + * This method allows you to request a graphical representation for a given + * individual. + */ @Override - public JComponent drawIndividual(AbstractEAIndividual indy) { - JTextArea tindy = new JTextArea(indy.getStringRepresentation()); - JScrollPane pindy = new JScrollPane(tindy); - tindy.setEditable(false); + public JComponent drawIndividual(AbstractEAIndividual indy) { + JTextArea tindy = new JTextArea(indy.getStringRepresentation()); + JScrollPane pindy = new JScrollPane(tindy); + tindy.setEditable(false); JPanel result = new JPanel(); result.setLayout(new BorderLayout()); result.add(tindy, BorderLayout.NORTH); result.add(pindy, BorderLayout.CENTER); return result; - } + } public static void main(String[] args) { System.out.println("TEST"); FLensProblem f = new FLensProblem(); - System.out.println("Working Dir " +System.getProperty("user.dir")); - GOStandaloneVersion program = new GOStandaloneVersion(); + System.out.println("Working Dir " + System.getProperty("user.dir")); + GOStandaloneVersion program = new GOStandaloneVersion(); OptimizationParameters GO = program.getGOParameters(); GO.setProblem(f); - RNG.setRandomSeed(1); - program.initFrame(); - program.setShow(true); + RNG.setRandomSeed(1); + program.initFrame(); + program.setShow(true); } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the - * name to the current object. - * @return The name. - */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the + * name to the current object. + * + * @return The name. + */ @Override - public String getName() { - return "Lens Problem"; - } + public String getName() { + return "Lens Problem"; + } - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "Focussing of a lens is to be optimized."; - } + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "Focussing of a lens is to be optimized."; + } - /** This method allows you to choose how much noise is to be added to the - * fitness. This can be used to make the optimization problem more difficult. - * @param noise The sigma for a gaussian random number. - */ - public void setNoise(double noise) { - if (noise < 0) { - noise = 0; - } - this.m_Noise = noise; - } - public double getNoise() { - return this.m_Noise; - } - public String noiseTipText() { - return "Noise level on the fitness value."; - } + /** + * This method allows you to choose how much noise is to be added to the + * fitness. This can be used to make the optimization problem more difficult. + * + * @param noise The sigma for a gaussian random number. + */ + public void setNoise(double noise) { + if (noise < 0) { + noise = 0; + } + this.m_Noise = noise; + } - /** This method allows you to set/get an offset for decision variables. - * @param XOffSet The offset for the decision variables. - */ - public void setXOffSet(double XOffSet) { - this.m_XOffSet = XOffSet; - } - public double getXOffSet() { - return this.m_XOffSet; - } - public String xOffSetTipText() { - return "Choose an offset for the decision variable."; - } + public double getNoise() { + return this.m_Noise; + } - /** This method allows you to set/get the offset for the - * objective value. - * @param YOffSet The offset for the objective value. - */ - public void setYOffSet(double YOffSet) { - this.m_YOffSet = YOffSet; - } - public double getYOffSet() { - return this.m_YOffSet; - } - public String yOffSetTipText() { - return "Choose an offset for the objective value."; - } - /** This method allows you to set the number of mulitruns that are to be performed, - * necessary for stochastic optimizers to ensure reliable results. - * @param multiruns The number of multiruns that are to be performed - */ - public void setProblemDimension(int multiruns) { - this.m_ProblemDimension = multiruns; - } - public int getProblemDimension() { - return this.m_ProblemDimension; - } - public String problemDimensionTipText() { - return "Length of the x vector at is to be optimized."; - } - /** This method allows you to toggel the solution representation. - * @param show Whether to show the result or not - */ - public void setShow(boolean show) { - this.m_Show = show; + public String noiseTipText() { + return "Noise level on the fitness value."; + } + + /** + * This method allows you to set/get an offset for decision variables. + * + * @param XOffSet The offset for the decision variables. + */ + public void setXOffSet(double XOffSet) { + this.m_XOffSet = XOffSet; + } + + public double getXOffSet() { + return this.m_XOffSet; + } + + public String xOffSetTipText() { + return "Choose an offset for the decision variable."; + } + + /** + * This method allows you to set/get the offset for the + * objective value. + * + * @param YOffSet The offset for the objective value. + */ + public void setYOffSet(double YOffSet) { + this.m_YOffSet = YOffSet; + } + + public double getYOffSet() { + return this.m_YOffSet; + } + + public String yOffSetTipText() { + return "Choose an offset for the objective value."; + } + + /** + * This method allows you to set the number of mulitruns that are to be performed, + * necessary for stochastic optimizers to ensure reliable results. + * + * @param multiruns The number of multiruns that are to be performed + */ + public void setProblemDimension(int multiruns) { + this.m_ProblemDimension = multiruns; + } + + public int getProblemDimension() { + return this.m_ProblemDimension; + } + + public String problemDimensionTipText() { + return "Length of the x vector at is to be optimized."; + } + + /** + * This method allows you to toggel the solution representation. + * + * @param show Whether to show the result or not + */ + public void setShow(boolean show) { + this.m_Show = show; if (this.m_Show) { - this.initProblemFrame(); - } - else { - this.disposeProblemFrame(); - } - } - public boolean getShow() { - return this.m_Show; - } - public String showTipText() { - return "Toggle the visualization of the solution."; - } + this.initProblemFrame(); + } else { + this.disposeProblemFrame(); + } + } - /** This method allows you to toggle the use of the material constraint. - * @param show Whether to show the result or not - */ - public void setUseMaterialConst(boolean show) { - this.m_UseMaterialConst = show; - } - public boolean getUseMaterialConst() { - return this.m_UseMaterialConst; - } - public String useMaterialConstTipText() { - return "Toggle the use of the material constraint."; - } + public boolean getShow() { + return this.m_Show; + } - /** This method allows you to choose the EA individual + public String showTipText() { + return "Toggle the visualization of the solution."; + } + + /** + * This method allows you to toggle the use of the material constraint. + * + * @param show Whether to show the result or not + */ + public void setUseMaterialConst(boolean show) { + this.m_UseMaterialConst = show; + } + + public boolean getUseMaterialConst() { + return this.m_UseMaterialConst; + } + + public String useMaterialConstTipText() { + return "Toggle the use of the material constraint."; + } + + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setEAIndividual(InterfaceDataTypeDouble indy) { - this.template = (AbstractEAIndividual)indy; - } - public InterfaceDataTypeDouble getEAIndividual() { - return (InterfaceDataTypeDouble)this.template; + this.template = (AbstractEAIndividual) indy; } - /** This method allows you to set the EA individual type - * Beware: Trap! - * @param indy The new EA individual type. - */ - public void setEAIndividualTrap(AbstractEAIndividual indy) { - if (indy instanceof InterfaceDataTypeDouble) { - this.setEAIndividual((InterfaceDataTypeDouble)indy); - } - } - - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceHasSolutionViewer#getSolutionViewer() - */ + public InterfaceDataTypeDouble getEAIndividual() { + return (InterfaceDataTypeDouble) this.template; + } + + /** + * This method allows you to set the EA individual type + * Beware: Trap! + * + * @param indy The new EA individual type. + */ + public void setEAIndividualTrap(AbstractEAIndividual indy) { + if (indy instanceof InterfaceDataTypeDouble) { + this.setEAIndividual((InterfaceDataTypeDouble) indy); + } + } + + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceHasSolutionViewer#getSolutionViewer() + */ @Override - public InterfaceSolutionViewer getSolutionViewer() { - return m_Panel; - } + public InterfaceSolutionViewer getSolutionViewer() { + return m_Panel; + } } \ No newline at end of file diff --git a/src/eva2/optimization/problems/FM0Problem.java b/src/eva2/optimization/problems/FM0Problem.java index ec15aca4..32ac1c82 100644 --- a/src/eva2/optimization/problems/FM0Problem.java +++ b/src/eva2/optimization/problems/FM0Problem.java @@ -1,6 +1,7 @@ package eva2.optimization.problems; import eva2.optimization.individuals.ESIndividualDoubleData; + import java.io.Serializable; /** @@ -11,8 +12,8 @@ import java.io.Serializable; * To change this template use Options | File Templates. */ public class FM0Problem extends AbstractMultiModalProblemKnown implements InterfaceOptimizationProblem, Interface2DBorderProblem, InterfaceMultimodalProblemKnown, Serializable { - - public FM0Problem() { + + public FM0Problem() { this.problemDimension = 2; this.template = new ESIndividualDoubleData(); // this.m_Extrema = new double[2]; @@ -26,44 +27,48 @@ public class FM0Problem extends AbstractMultiModalProblemKnown implements Interf } @Override - public double getRangeUpperBound(int dim) { - if (dim == 0) { - return 2.0; - } - else { - return 2.8; - } - } - - @Override - public double getRangeLowerBound(int dim) { - return -1*getRangeUpperBound(dim); - } - - public FM0Problem(FM0Problem b) { - cloneObjects(b); + public double getRangeUpperBound(int dim) { + if (dim == 0) { + return 2.0; + } else { + return 2.8; + } } - /** This method returns a deep clone of the problem. - * @return the clone + @Override + public double getRangeLowerBound(int dim) { + return -1 * getRangeUpperBound(dim); + } + + public FM0Problem(FM0Problem b) { + cloneObjects(b); + } + + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new FM0Problem(this); } - /** This method returns the unnormalized function value for an maximization problem - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + /** + * This method returns the unnormalized function value for an maximization problem + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] evalUnnormalized(double[] x) { double[] result = new double[1]; - result[0] = Math.sin(2*x[0] - 0.5*Math.PI) + 1 + 2*Math.cos(x[1]) + 0.5*x[0]; + result[0] = Math.sin(2 * x[0] - 0.5 * Math.PI) + 1 + 2 * Math.cos(x[1]) + 0.5 * x[0]; return result; } - /** This method will prepare the problem to return a list of all optima + /** + * This method will prepare the problem to return a list of all optima * if possible and to return quality measures like NumberOfOptimaFound and * the MaximumPeakRatio. This method should be called by the user. */ @@ -81,8 +86,10 @@ public class FM0Problem extends AbstractMultiModalProblemKnown implements Interf /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -90,7 +97,9 @@ public class FM0Problem extends AbstractMultiModalProblemKnown implements Interf return "M0 Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/GPFunctionProblem.java b/src/eva2/optimization/problems/GPFunctionProblem.java index 4d7599c4..e708410f 100644 --- a/src/eva2/optimization/problems/GPFunctionProblem.java +++ b/src/eva2/optimization/problems/GPFunctionProblem.java @@ -12,150 +12,150 @@ import eva2.tools.EVAERROR; * function by scaling it logarithmically. This avoids ugly functions in GP. To activate scaling, * set the scStart and scLimit parameters to positive values. Function values y with |y|>scStart * will be rescaled to values below scLimit. - * - * @author mkron * + * @author mkron */ public class GPFunctionProblem extends AbstractProblemDouble implements InterfaceProgramProblem { - InterfaceProgram gpProblem = null; - GPArea gpArea = new GPArea(); - double[] pos = null; - int dim = 2; - double scalingStart=10.; - double scalingLimit=20.; - - public static boolean hideFromGOE = true; - - /** - * Initialize a default GP function problem in 2D with scaling. - * @param gpProb - * @param area - */ - public GPFunctionProblem(InterfaceProgram gpProb, GPArea area) { - this(gpProb, area, 0., 0.); - } - - /** - * By default, a 2-D problem is initialized with given scaling bounds. Set the scaling limit to 0 to - * deactivate scaling. - * - * @param gpProb - * @param area - * @param scStart - * @param scLim - */ - public GPFunctionProblem(InterfaceProgram gpProb, GPArea area, double scStart, double scLim) { - this(gpProb, area, 2, scStart, scLim); - } - - /** - * A GP function problem is initialized with given scaling bounds. Set the scaling limit to 0 to - * deactivate scaling. - * - * @param gpProb - * @param area - * @param scStart - * @param scLim - */ - public GPFunctionProblem(InterfaceProgram gpProb, GPArea area, int pDim, double scStart, double scLim) { - dim = pDim; - ((ESIndividualDoubleData) template).setDoubleDataLength(dim); - gpProblem = gpProb; - gpArea = area; - scalingStart=scStart; - scalingLimit=scLim; - } - - public GPFunctionProblem(GPFunctionProblem functionProblem) { - dim = functionProblem.dim; - if (functionProblem.pos != null) { - pos = new double[dim]; - System.arraycopy(functionProblem.pos, 0, pos, 0, dim); - } - gpArea = (GPArea) functionProblem.gpArea.clone(); - gpProblem = functionProblem.gpProblem; - } + InterfaceProgram gpProblem = null; + GPArea gpArea = new GPArea(); + double[] pos = null; + int dim = 2; + double scalingStart = 10.; + double scalingLimit = 20.; - @Override - public Object clone() { - return new GPFunctionProblem(this); - } + public static boolean hideFromGOE = true; - @Override - public double[] eval(double[] x) { - if (x.length != dim) { - EVAERROR.errorMsgOnce("mismatching dimension of GPFunctionProblem! Setting to " + x.length); - setProblemDimension(x.length); - } - x = rotateMaybe(x); - pos = x; - Double res = (Double) gpProblem.evaluate(this); - double[] fit = new double[1]; - fit[0] = scaleFit(res.doubleValue()); - return fit; - } + /** + * Initialize a default GP function problem in 2D with scaling. + * + * @param gpProb + * @param area + */ + public GPFunctionProblem(InterfaceProgram gpProb, GPArea area) { + this(gpProb, area, 0., 0.); + } - /** - * Set the problem dimension. Make sure that the associated GP tree is still valid - * and does not explicitely use more dimensions than defined here, for instance. - * @param newDim - */ - public void setProblemDimension(int newDim) { - dim = newDim; - ((ESIndividualDoubleData) template).setDoubleDataLength(dim); - } + /** + * By default, a 2-D problem is initialized with given scaling bounds. Set the scaling limit to 0 to + * deactivate scaling. + * + * @param gpProb + * @param area + * @param scStart + * @param scLim + */ + public GPFunctionProblem(InterfaceProgram gpProb, GPArea area, double scStart, double scLim) { + this(gpProb, area, 2, scStart, scLim); + } - /** - * Scale the allover fitness value. - * - * @param doubleValue - * @return - */ - public double scaleFit(double v) { - if (scalingLimit==0.) { + /** + * A GP function problem is initialized with given scaling bounds. Set the scaling limit to 0 to + * deactivate scaling. + * + * @param gpProb + * @param area + * @param scStart + * @param scLim + */ + public GPFunctionProblem(InterfaceProgram gpProb, GPArea area, int pDim, double scStart, double scLim) { + dim = pDim; + ((ESIndividualDoubleData) template).setDoubleDataLength(dim); + gpProblem = gpProb; + gpArea = area; + scalingStart = scStart; + scalingLimit = scLim; + } + + public GPFunctionProblem(GPFunctionProblem functionProblem) { + dim = functionProblem.dim; + if (functionProblem.pos != null) { + pos = new double[dim]; + System.arraycopy(functionProblem.pos, 0, pos, 0, dim); + } + gpArea = (GPArea) functionProblem.gpArea.clone(); + gpProblem = functionProblem.gpProblem; + } + + @Override + public Object clone() { + return new GPFunctionProblem(this); + } + + @Override + public double[] eval(double[] x) { + if (x.length != dim) { + EVAERROR.errorMsgOnce("mismatching dimension of GPFunctionProblem! Setting to " + x.length); + setProblemDimension(x.length); + } + x = rotateMaybe(x); + pos = x; + Double res = (Double) gpProblem.evaluate(this); + double[] fit = new double[1]; + fit[0] = scaleFit(res.doubleValue()); + return fit; + } + + /** + * Set the problem dimension. Make sure that the associated GP tree is still valid + * and does not explicitely use more dimensions than defined here, for instance. + * + * @param newDim + */ + public void setProblemDimension(int newDim) { + dim = newDim; + ((ESIndividualDoubleData) template).setDoubleDataLength(dim); + } + + /** + * Scale the allover fitness value. + * + * @param doubleValue + * @return + */ + public double scaleFit(double v) { + if (scalingLimit == 0.) { + return v; + } else { + double aV = Math.abs(v); + if (aV > scalingStart) { + double logVal = Math.log(aV) / Math.log(scalingStart); + double tmp = 1. / (logVal); + return (scalingLimit - tmp) * Math.signum(v); + } else { return v; } - else { - double aV = Math.abs(v); - if (aV > scalingStart) { - double logVal=Math.log(aV)/Math.log(scalingStart); - double tmp=1./(logVal); - return (scalingLimit - tmp)*Math.signum(v); - } else { - return v; - } - } - } + } + } // public static void main(String[] args) { // for (double x=1.; x<100000000; x*=10.) { // System.out.println("x: " + -x + " sc: " + scaleFit(-x)); // } // } - - @Override - public int getProblemDimension() { - return dim; - } @Override - public String getStringRepresentationForProblem(InterfaceOptimizer opt) { - return "GP find a function problem"; - } + public int getProblemDimension() { + return dim; + } @Override - public Object getSensorValue(String sensor) { - return PSymbolicRegression.getSensorValue(sensor, pos, null); - } + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + return "GP find a function problem"; + } @Override - public void setActuatorValue(String actuator, Object parameter) { - // nothing to do here - } + public Object getSensorValue(String sensor) { + return PSymbolicRegression.getSensorValue(sensor, pos, null); + } @Override - public GPArea getArea() { - return gpArea; - } + public void setActuatorValue(String actuator, Object parameter) { + // nothing to do here + } + + @Override + public GPArea getArea() { + return gpArea; + } } diff --git a/src/eva2/optimization/problems/I1Problem.java b/src/eva2/optimization/problems/I1Problem.java index 48c4f6a7..133ff360 100644 --- a/src/eva2/optimization/problems/I1Problem.java +++ b/src/eva2/optimization/problems/I1Problem.java @@ -1,48 +1,53 @@ package eva2.optimization.problems; - import eva2.optimization.strategies.InterfaceOptimizer; /** * The integer hyper-sphere problem. - * + *

* User: streiche, mkron */ public class I1Problem extends AbstractProblemInteger implements java.io.Serializable { - public I1Problem() { - } - - public I1Problem(I1Problem o) { - super.cloneObjects(o); - } + public I1Problem() { + } - /** This method returns a deep clone of the problem. - * @return the clone + public I1Problem(I1Problem o) { + super.cloneObjects(o); + } + + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new I1Problem(this); } - /** Ths method allows you to evaluate a simple bit string to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + /** + * Ths method allows you to evaluate a simple bit string to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ @Override public double[] eval(int[] x) { double[] result = new double[1]; - result[0] = 0; + result[0] = 0; for (int i = 0; i < x.length; i++) { - result[0] += Math.pow(x[i], 2); + result[0] += Math.pow(x[i], 2); } result[0] += 1; return result; } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -52,14 +57,15 @@ public class I1Problem extends AbstractProblemInteger implements java.io.Seriali result += "I1 Problem:\n"; result += "Here the individual codes a vector of int numbers x and F1(x)= x^2 is to be minimized.\n"; result += "Parameters:\n"; - result += "Dimension : " + this.m_ProblemDimension +"\n"; + result += "Dimension : " + this.m_ProblemDimension + "\n"; result += "Solution representation:\n"; return result; } -/********************************************************************************************************************** - * These are for GUI - */ + /** + * ******************************************************************************************************************* + * These are for GUI + */ @Override public String getName() { diff --git a/src/eva2/optimization/problems/Interface2DBorderProblem.java b/src/eva2/optimization/problems/Interface2DBorderProblem.java index 3e8c7a48..559a2d68 100644 --- a/src/eva2/optimization/problems/Interface2DBorderProblem.java +++ b/src/eva2/optimization/problems/Interface2DBorderProblem.java @@ -3,27 +3,29 @@ package eva2.optimization.problems; /** * An interface refactored from InterfaceMultiModalProblem, having only methods used for * plotting nice colored graphs in GUI using the TopoPlot class. - * + * * @author mkron */ public interface Interface2DBorderProblem { - /** This method returns the 2d borders of the problem + /** + * This method returns the 2d borders of the problem + * * @return double[][] */ public double[][] get2DBorder(); - /** + /** * This method returns the double value at a given position. The value should be * based on the same projection delivered by the project2DPoint function. - * - * @param point The double[2] that is queried. + * + * @param point The double[2] that is queried. * @return double */ public double functionValue(double[] point); - + /** * Project a 2D point to the default higher-dimensional cut to be displayed (if required for plotting). - * + * * @param point the double[2] that is queried * @return a (higher dimensional) projection of the point */ diff --git a/src/eva2/optimization/problems/InterfaceAdditionalPopulationInformer.java b/src/eva2/optimization/problems/InterfaceAdditionalPopulationInformer.java index 8d4c6c93..cee60d85 100644 --- a/src/eva2/optimization/problems/InterfaceAdditionalPopulationInformer.java +++ b/src/eva2/optimization/problems/InterfaceAdditionalPopulationInformer.java @@ -7,30 +7,31 @@ import eva2.optimization.population.PopulationInterface; * This may be statistics depending on specific optimization methods or a specific application * problem. * For every additional field, a field name (header) and a value at every iteration must be provided. - * - * @author mkron * + * @author mkron */ public interface InterfaceAdditionalPopulationInformer { - /** - * This method returns the header for additional statistical data. - * @param pop The population of the optimization run. - * @return String - */ - public String[] getAdditionalDataHeader(); + /** + * This method returns the header for additional statistical data. + * + * @param pop The population of the optimization run. + * @return String + */ + public String[] getAdditionalDataHeader(); - /** - * Optionally return informative descriptions of the data fields. - * - * @param pop - * @return - */ - public String[] getAdditionalDataInfo(); - - /** - * This method returns additional statistical data. - * @param pop The population that is to be refined. - * @return String - */ - public Object[] getAdditionalDataValue(PopulationInterface pop); + /** + * Optionally return informative descriptions of the data fields. + * + * @param pop + * @return + */ + public String[] getAdditionalDataInfo(); + + /** + * This method returns additional statistical data. + * + * @param pop The population that is to be refined. + * @return String + */ + public Object[] getAdditionalDataValue(PopulationInterface pop); } diff --git a/src/eva2/optimization/problems/InterfaceFirstOrderDerivableProblem.java b/src/eva2/optimization/problems/InterfaceFirstOrderDerivableProblem.java index a050532e..66d39a17 100644 --- a/src/eva2/optimization/problems/InterfaceFirstOrderDerivableProblem.java +++ b/src/eva2/optimization/problems/InterfaceFirstOrderDerivableProblem.java @@ -2,20 +2,20 @@ package eva2.optimization.problems; /** * An interface for first-order derivable problems which can be used for gradient descent. - * - * @author hplanatscher, mkron * + * @author hplanatscher, mkron */ public interface InterfaceFirstOrderDerivableProblem { - /** - * Calculate the first order gradients of this problem. - * If you implement this, be aware that some types of AbstractProblemDouble may be rotated, - * so you may have to use x = rotateMaybe(x) first. - * @param x - * @return the first order gradients of this problem - */ - public double[] getFirstOrderGradients(double[] x); + /** + * Calculate the first order gradients of this problem. + * If you implement this, be aware that some types of AbstractProblemDouble may be rotated, + * so you may have to use x = rotateMaybe(x) first. + * + * @param x + * @return the first order gradients of this problem + */ + public double[] getFirstOrderGradients(double[] x); // public double getFirstOrderGradient(int paramindex,double[] x); } diff --git a/src/eva2/optimization/problems/InterfaceHasInitRange.java b/src/eva2/optimization/problems/InterfaceHasInitRange.java index 28f79c55..6afd88ee 100644 --- a/src/eva2/optimization/problems/InterfaceHasInitRange.java +++ b/src/eva2/optimization/problems/InterfaceHasInitRange.java @@ -3,19 +3,18 @@ package eva2.optimization.problems; /** * An interface for optimization problems having an extra initial range * opposed to the global search range. This makes sense mainly for double - * and integer data types such as ESIndividuals and GIIndividuals. For binary types, - * the search range is defined by the bit length of the individual, respectively the + * and integer data types such as ESIndividuals and GIIndividuals. For binary types, + * the search range is defined by the bit length of the individual, respectively the * dimension of the problem. - * - * @author mkron * + * @author mkron */ public interface InterfaceHasInitRange { - /** - * The method should return the type expected by the individual type, e.g. double[][] or int[][]. - * It may return null, in that case the global search range is used as initial range. - * - * @return An initial search range or null in case it is equal to the global search range. - */ - public Object getInitRange(); + /** + * The method should return the type expected by the individual type, e.g. double[][] or int[][]. + * It may return null, in that case the global search range is used as initial range. + * + * @return An initial search range or null in case it is equal to the global search range. + */ + public Object getInitRange(); } diff --git a/src/eva2/optimization/problems/InterfaceHasSolutionViewer.java b/src/eva2/optimization/problems/InterfaceHasSolutionViewer.java index 49e2bd36..35f3d001 100644 --- a/src/eva2/optimization/problems/InterfaceHasSolutionViewer.java +++ b/src/eva2/optimization/problems/InterfaceHasSolutionViewer.java @@ -2,10 +2,9 @@ package eva2.optimization.problems; /** * An interface for problems which have a specific viewer. - * - * @author mkron * + * @author mkron */ public interface InterfaceHasSolutionViewer { - public InterfaceSolutionViewer getSolutionViewer(); + public InterfaceSolutionViewer getSolutionViewer(); } diff --git a/src/eva2/optimization/problems/InterfaceInterestingHistogram.java b/src/eva2/optimization/problems/InterfaceInterestingHistogram.java index 651c71e0..5cd22aac 100644 --- a/src/eva2/optimization/problems/InterfaceInterestingHistogram.java +++ b/src/eva2/optimization/problems/InterfaceInterestingHistogram.java @@ -3,18 +3,17 @@ package eva2.optimization.problems; import eva2.optimization.operator.postprocess.SolutionHistogram; /** - * Target functions may provide an idea which fitness values are + * Target functions may provide an idea which fitness values are * interesting. - * - * @author mkron * + * @author mkron */ public interface InterfaceInterestingHistogram { - /** - * For this specific instance, provide an empty histogram defining in which - * area interesting solutions would lie. - * - * @return - */ - public SolutionHistogram getHistogram(); + /** + * For this specific instance, provide an empty histogram defining in which + * area interesting solutions would lie. + * + * @return + */ + public SolutionHistogram getHistogram(); } diff --git a/src/eva2/optimization/problems/InterfaceLocalSearchable.java b/src/eva2/optimization/problems/InterfaceLocalSearchable.java index 221718aa..7b258104 100644 --- a/src/eva2/optimization/problems/InterfaceLocalSearchable.java +++ b/src/eva2/optimization/problems/InterfaceLocalSearchable.java @@ -7,24 +7,25 @@ import eva2.optimization.population.Population; *

Description:

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author planatsc * @version 1.0 */ public interface InterfaceLocalSearchable extends InterfaceOptimizationProblem { - /** - * Perform a single local search step on each of the given individuals. - * - * @param pop - */ - public void doLocalSearch(Population pop); + /** + * Perform a single local search step on each of the given individuals. + * + * @param pop + */ + public void doLocalSearch(Population pop); - /** - * Estimate the cost of one local search step -- more precisely the cost of the doLocalSearch call per one individual. - * - * @return - */ - public double getLocalSearchStepFunctionCallEquivalent(); + /** + * Estimate the cost of one local search step -- more precisely the cost of the doLocalSearch call per one individual. + * + * @return + */ + public double getLocalSearchStepFunctionCallEquivalent(); } diff --git a/src/eva2/optimization/problems/InterfaceMultiObjectiveDeNovoProblem.java b/src/eva2/optimization/problems/InterfaceMultiObjectiveDeNovoProblem.java index 40bdc9b5..5e57d5be 100644 --- a/src/eva2/optimization/problems/InterfaceMultiObjectiveDeNovoProblem.java +++ b/src/eva2/optimization/problems/InterfaceMultiObjectiveDeNovoProblem.java @@ -3,7 +3,8 @@ package eva2.optimization.problems; import eva2.optimization.mocco.paretofrontviewer.InterfaceParetoFrontView; import eva2.optimization.mocco.paretofrontviewer.MOCCOViewer; -/** This is a general interface to access a multi-objective optimization +/** + * This is a general interface to access a multi-objective optimization * problem which enables de novo programming and thus MOCCO * Created by IntelliJ IDEA. * User: streiche @@ -13,20 +14,25 @@ import eva2.optimization.mocco.paretofrontviewer.MOCCOViewer; */ public interface InterfaceMultiObjectiveDeNovoProblem { - /** This method allows you to recieve all the optimization + /** + * This method allows you to recieve all the optimization * objectives + * * @return A list of optimization objectives */ public InterfaceOptimizationObjective[] getProblemObjectives(); - /** This method will generate a problem specific view on the Pareto + /** + * This method will generate a problem specific view on the Pareto * front. Nice idea isn't it. This idea was by Jochen, the teamleader * of the CombiChem guys at ALTANA Pharma Konstanz. + * * @return the Panel */ public InterfaceParetoFrontView getParetoFrontViewer4MOCCO(MOCCOViewer t); - /** This method allows MOCCO to deactivate the representation editior + /** + * This method allows MOCCO to deactivate the representation editior * if and only if the specific editor reacts to this signal. This signal * cannot be deactivated! */ diff --git a/src/eva2/optimization/problems/InterfaceMultimodalProblem.java b/src/eva2/optimization/problems/InterfaceMultimodalProblem.java index c5280a95..59ca7679 100644 --- a/src/eva2/optimization/problems/InterfaceMultimodalProblem.java +++ b/src/eva2/optimization/problems/InterfaceMultimodalProblem.java @@ -3,7 +3,6 @@ package eva2.optimization.problems; /** * An interface to tag possibly multimodal problems, but without * further knowledge about the optima. - * */ public interface InterfaceMultimodalProblem { diff --git a/src/eva2/optimization/problems/InterfaceMultimodalProblemKnown.java b/src/eva2/optimization/problems/InterfaceMultimodalProblemKnown.java index fe949ba2..128f60be 100644 --- a/src/eva2/optimization/problems/InterfaceMultimodalProblemKnown.java +++ b/src/eva2/optimization/problems/InterfaceMultimodalProblemKnown.java @@ -4,7 +4,7 @@ import eva2.optimization.population.Population; /** * A multimodal problem which has knowledge of its optima. - * + *

* User: streiche * Date: 23.04.2003 * Time: 10:57:47 @@ -12,7 +12,7 @@ import eva2.optimization.population.Population; */ public interface InterfaceMultimodalProblemKnown extends InterfaceMultimodalProblem { - /** + /** * This method will prepare the problem to return a list of all optima * if possible and to return quality measures like NumberOfOptimaFound and * the MaximumPeakRatio. This method should be called by the user. @@ -21,37 +21,40 @@ public interface InterfaceMultimodalProblemKnown extends InterfaceMultimodalProb /** * Return true if the full list of optima is available, else false. + * * @return */ public boolean fullListAvailable(); - - /** - * This method returns a list of all optima as population or null if + + /** + * This method returns a list of all optima as population or null if * the optima are unknown. - * + * * @return population */ public Population getRealOptima(); - /** - * Return the number of identified optima or -1 if + /** + * Return the number of identified optima or -1 if * the real optima are unknown. - * @param pop A population of possible solutions. + * + * @param pop A population of possible solutions. * @return int */ public int getNumberOfFoundOptima(Population pop); - /** + /** * This method returns the Maximum Peak Ratio. - * @param pop A population of possible solutions. + * + * @param pop A population of possible solutions. * @return double */ public double getMaximumPeakRatio(Population pop); - + /** * Return the maximum normed distance to a known optimum for which the * optimum is considered found. - * + * * @return */ public double getDefaultAccuracy(); diff --git a/src/eva2/optimization/problems/InterfaceOptimizationObjective.java b/src/eva2/optimization/problems/InterfaceOptimizationObjective.java index b0fffe6f..697d354f 100644 --- a/src/eva2/optimization/problems/InterfaceOptimizationObjective.java +++ b/src/eva2/optimization/problems/InterfaceOptimizationObjective.java @@ -10,38 +10,51 @@ package eva2.optimization.problems; public interface InterfaceOptimizationObjective { public Object clone(); - /** This Method returns the name for the optimization target + /** + * This Method returns the name for the optimization target + * * @return the name */ public String getName(); - /** This method allows you to retrieve the name of the optimization target + /** + * This method allows you to retrieve the name of the optimization target + * * @return The name */ public String getIdentName(); - /** This method allows you to retrieve the current optimization mode + /** + * This method allows you to retrieve the current optimization mode * The modes include * - Objective * - Objective + Constraint * - Constraint * (-Goal !?) + * * @return The mode as string */ public String getOptimizationMode(); - public void SetOptimizationMode(String d); - /** This method allows you to retrieve the constraint/goal + public void SetOptimizationMode(String d); + + /** + * This method allows you to retrieve the constraint/goal + * * @return The cosntraint/goal */ public double getConstraintGoal(); - /** This method allows you to set the constraint/goal + /** + * This method allows you to set the constraint/goal + * * @param d the constraint/goal */ public void SetConstraintGoal(double d); - /** This method returns whether or not the given objective is to be minimized + /** + * This method returns whether or not the given objective is to be minimized + * * @return True if to be minimized false else. */ public boolean is2BMinimized(); diff --git a/src/eva2/optimization/problems/InterfaceOptimizationProblem.java b/src/eva2/optimization/problems/InterfaceOptimizationProblem.java index 91d96381..809be499 100644 --- a/src/eva2/optimization/problems/InterfaceOptimizationProblem.java +++ b/src/eva2/optimization/problems/InterfaceOptimizationProblem.java @@ -3,6 +3,7 @@ package eva2.optimization.problems; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; + import javax.swing.*; /** @@ -14,69 +15,89 @@ import javax.swing.*; */ public interface InterfaceOptimizationProblem extends InterfaceAdditionalPopulationInformer { - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ public Object clone(); - /** This method inits the Problem to log multiruns + /** + * This method inits the Problem to log multiruns */ public void initializeProblem(); - /** This method will report whether or not this optimization problem is truly + /** + * This method will report whether or not this optimization problem is truly * multi-objective + * * @return True if multi-objective, else false. */ - public boolean isMultiObjective(); + public boolean isMultiObjective(); /******************** The most important methods ****************************************/ - /** This method inits a given population - * @param population The populations that is to be inited + /** + * This method inits a given population + * + * @param population The populations that is to be inited */ public void initializePopulation(Population population); - /** This method evaluates a given population and set the fitness values + /** + * This method evaluates a given population and set the fitness values * accordingly - * @param population The population that is to be evaluated. + * + * @param population The population that is to be evaluated. */ public void evaluate(Population population); - /** This method evaluate a single individual and sets the fitness values - * @param individual The individual that is to be evalutated + /** + * This method evaluate a single individual and sets the fitness values + * + * @param individual The individual that is to be evalutated */ public void evaluate(AbstractEAIndividual individual); /******************** Some output methods *******************************************/ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ - public String getName(); + public String getName(); - /** This method allows you to output a string that describes a found solution + /** + * This method allows you to output a string that describes a found solution * in a way that is most suiteable for a given problem. - * @param individual The individual that is to be shown. + * + * @param individual The individual that is to be shown. * @return The description. */ public String getSolutionRepresentationFor(AbstractEAIndividual individual); - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ public String getStringRepresentationForProblem(InterfaceOptimizer opt); - /** This method allows you to request a graphical representation for a given + /** + * This method allows you to request a graphical representation for a given * individual. */ public JComponent drawIndividual(int generation, int funCalls, AbstractEAIndividual indy); - /** This method returns a double value that will be displayed in a fitness + /** + * This method returns a double value that will be displayed in a fitness * plot. A fitness that is to be minimized with a global min of zero * would be best, since log y can be used. But the value can depend on the problem. - * @param pop The population that is to be refined. + * + * @param pop The population that is to be refined. * @return Double value */ public Double getDoublePlotValue(Population pop); diff --git a/src/eva2/optimization/problems/InterfaceOptimizationTarget.java b/src/eva2/optimization/problems/InterfaceOptimizationTarget.java index b704e090..50250ca6 100644 --- a/src/eva2/optimization/problems/InterfaceOptimizationTarget.java +++ b/src/eva2/optimization/problems/InterfaceOptimizationTarget.java @@ -11,7 +11,9 @@ public interface InterfaceOptimizationTarget { public Object clone(); - /** This method allows you to retrieve the name of the optimization target + /** + * This method allows you to retrieve the name of the optimization target + * * @return The name */ public String getName(); diff --git a/src/eva2/optimization/problems/InterfaceProblemDouble.java b/src/eva2/optimization/problems/InterfaceProblemDouble.java index b7044823..c99f70ff 100644 --- a/src/eva2/optimization/problems/InterfaceProblemDouble.java +++ b/src/eva2/optimization/problems/InterfaceProblemDouble.java @@ -4,59 +4,58 @@ import eva2.optimization.individuals.InterfaceDataTypeDouble; /** * A minimal interface for double valued problems. - * - * @author mkron * + * @author mkron */ public interface InterfaceProblemDouble { - /** - * Evaluate a double vector, representing the target function. - * - * @param x the vector to evaluate - * @return the target function value - */ - public double[] eval(double[] x); - - /** - * Get the problem dimension. - * - * @return the problem dimension - */ - public int getProblemDimension(); - - /** - * Create a new range array by using the getRangeLowerBound and getRangeUpperBound methods. - * - * @return a range array - */ + /** + * Evaluate a double vector, representing the target function. + * + * @param x the vector to evaluate + * @return the target function value + */ + public double[] eval(double[] x); + + /** + * Get the problem dimension. + * + * @return the problem dimension + */ + public int getProblemDimension(); + + /** + * Create a new range array by using the getRangeLowerBound and getRangeUpperBound methods. + * + * @return a range array + */ public double[][] makeRange(); - + /** * Get the EA individual template currently used by the problem. - * + * * @return the EA individual template currently used */ public InterfaceDataTypeDouble getEAIndividual(); - + /** * Get the upper bound of the double range in the given dimension. Override * this to implement non-symmetric ranges. User setDefaultRange for symmetric ranges. - * - * @see makeRange() - * @see getRangeLowerBound(int dim) + * * @param dim * @return the upper bound of the double range in the given dimension + * @see makeRange() + * @see getRangeLowerBound(int dim) */ public double getRangeUpperBound(int dim); - + /** * Get the lower bound of the double range in the given dimension. Override * this to implement non-symmetric ranges. Use setDefaultRange for symmetric ranges. - * - * @see makeRange() - * @see getRangeUpperBound(int dim) + * * @param dim * @return the lower bound of the double range in the given dimension + * @see makeRange() + * @see getRangeUpperBound(int dim) */ public double getRangeLowerBound(int dim); } diff --git a/src/eva2/optimization/problems/InterfaceProgramProblem.java b/src/eva2/optimization/problems/InterfaceProgramProblem.java index 9d130024..5a557827 100644 --- a/src/eva2/optimization/problems/InterfaceProgramProblem.java +++ b/src/eva2/optimization/problems/InterfaceProgramProblem.java @@ -11,21 +11,26 @@ import eva2.optimization.individuals.codings.gp.GPArea; */ public interface InterfaceProgramProblem extends InterfaceOptimizationProblem { - /** This method allows a GP program to sense the environment, e.g. + /** + * This method allows a GP program to sense the environment, e.g. * input values, current time etc - * @param sensor The identifier for the sensor. + * + * @param sensor The identifier for the sensor. * @return Sensor value */ public Object getSensorValue(String sensor); - /** This method allows a GP program to act in the environment - * @param actuator The identifier for the actuator. - * @param parameter The actuator parameter. + /** + * This method allows a GP program to act in the environment + * + * @param actuator The identifier for the actuator. + * @param parameter The actuator parameter. */ public void setActuatorValue(String actuator, Object parameter); - + /** * Return the GPArea associated with the program problem. + * * @return */ public GPArea getArea(); diff --git a/src/eva2/optimization/problems/InterfaceSolutionViewer.java b/src/eva2/optimization/problems/InterfaceSolutionViewer.java index f2d13729..f8446cd1 100644 --- a/src/eva2/optimization/problems/InterfaceSolutionViewer.java +++ b/src/eva2/optimization/problems/InterfaceSolutionViewer.java @@ -5,24 +5,25 @@ import eva2.optimization.population.Population; /** * A standard interface for solution viewers which display a single (best) solution * or a population of solutions. - * - * @author mkron * + * @author mkron */ public interface InterfaceSolutionViewer { - /** - * Initialize the view for a certain problem. - * @param prob - */ + /** + * Initialize the view for a certain problem. + * + * @param prob + */ public void initView(AbstractOptimizationProblem prob); - + /** * Reset the view. */ public void resetView(); - + /** * Update the view by displaying a population of solutions (often only the best one is shown). + * * @param pop */ public void updateView(Population pop, boolean showAllIfPossible); diff --git a/src/eva2/optimization/problems/MatlabEvalMediator.java b/src/eva2/optimization/problems/MatlabEvalMediator.java index 47a2cb9f..adcd05a9 100644 --- a/src/eva2/optimization/problems/MatlabEvalMediator.java +++ b/src/eva2/optimization/problems/MatlabEvalMediator.java @@ -1,17 +1,18 @@ package eva2.optimization.problems; import eva2.gui.BeanInspector; + import java.util.BitSet; import java.util.concurrent.Semaphore; /** - * This implements a thread acting as a mediator between EvA and Matlab. Thanks to the idea + * This implements a thread acting as a mediator between EvA and Matlab. Thanks to the idea * of Henning Schmidt! * As Java calling Matlab directly causes problems (due to Matlabs single-threadedness), Matlab * now starts a mediator thread which receives the data necessary to perform the evaluation in matlab * from the optimization thread. On receiving this "question" from the optimizer, the mediator thread - * finishes, returning to Matlab and signaling that there is work to do. - * However, the mediator object remains persistent, and the optimization thread keeps running + * finishes, returning to Matlab and signaling that there is work to do. + * However, the mediator object remains persistent, and the optimization thread keeps running * and waits for the mediator to signal that there is a result, which happens if Matlab calls setAnswer(). * Then the optimizer thread resumes, while Matlab has to restart the mediator thread, so that it may * be informed about the next question, and so on. I havent checked how much performance is lost compared @@ -20,89 +21,88 @@ import java.util.concurrent.Semaphore; * Adding sleep time reduces CPU load a lot but reduces efficiency badly at the same time, probably because * theres so much going on. For cases where the evaluation function is very time-consuming, adding sleep time * might be an option. - * - * @author mkron * + * @author mkron */ public class MatlabEvalMediator { - volatile Boolean requesting = false; -// final static boolean TRACE = false; - volatile private Boolean fin = false; - volatile Object question = null; - volatile double[] answer = null; - volatile boolean quit = false; - volatile Object optSolution = null; - volatile Object[] optSolSet = null; - volatile Semaphore requests; - int runID=-1; - volatile MatlabProblem mp = null; - // no good: even when waiting for only 1 ms the Matlab execution time increases by a factor of 5-10 - private int sleepTime = 5; + volatile Boolean requesting = false; + // final static boolean TRACE = false; + volatile private Boolean fin = false; + volatile Object question = null; + volatile double[] answer = null; + volatile boolean quit = false; + volatile Object optSolution = null; + volatile Object[] optSolSet = null; + volatile Semaphore requests; + int runID = -1; + volatile MatlabProblem mp = null; + // no good: even when waiting for only 1 ms the Matlab execution time increases by a factor of 5-10 + private int sleepTime = 5; - /** - * Constructor with integer argument for the sleep time in between requests. Values higher than 0 reduce - * cpu load of the waiting thread but may also reduce allover runtime for fast evaluation functions. - * - * @param threadSleepTime - */ - public MatlabEvalMediator(int threadSleepTime) { - sleepTime=threadSleepTime; - requests=new Semaphore(0); - } - - /** - * Constructor with sleep time set to zero. - */ - public MatlabEvalMediator() { - sleepTime=0; - requests=new Semaphore(0); - } - - public void setMatlabProblem(MatlabProblem theMP) { - mp=theMP; - logMP("setting MP " + theMP + " for MEM " + this + "\n"); - } - - /** - * Request evaluation from Matlab for the given params. - * - * @param x - * @return - */ - double[] requestEval(MatlabProblem mp, Object x) { - this.mp = mp; - question = x; + /** + * Constructor with integer argument for the sleep time in between requests. Values higher than 0 reduce + * cpu load of the waiting thread but may also reduce allover runtime for fast evaluation functions. + * + * @param threadSleepTime + */ + public MatlabEvalMediator(int threadSleepTime) { + sleepTime = threadSleepTime; + requests = new Semaphore(0); + } + + /** + * Constructor with sleep time set to zero. + */ + public MatlabEvalMediator() { + sleepTime = 0; + requests = new Semaphore(0); + } + + public void setMatlabProblem(MatlabProblem theMP) { + mp = theMP; + logMP("setting MP " + theMP + " for MEM " + this + "\n"); + } + + /** + * Request evaluation from Matlab for the given params. + * + * @param x + * @return + */ + double[] requestEval(MatlabProblem mp, Object x) { + this.mp = mp; + question = x; // System.err.println("IN REQUESTEVAL, x is " + BeanInspector.toString(x)); - if (question.getClass().isArray()) { + if (question.getClass().isArray()) { // System.err.println("array of type ** " + Array.get(question, 0).getClass().toString()); // } else if (question instanceof BitSet){ // BitSet b = (BitSet)x; // Integer.decode() // - if (question == null) { - System.err.println("Error: requesting evaluation for null array!"); - } - } else { // if its not an array, it must be a BitSet - if (!(x instanceof BitSet)) { - System.err.println("Error, requesting evaluation for invalid data type! " + question.getClass()); - } - } + if (question == null) { + System.err.println("Error: requesting evaluation for null array!"); + } + } else { // if its not an array, it must be a BitSet + if (!(x instanceof BitSet)) { + System.err.println("Error, requesting evaluation for invalid data type! " + question.getClass()); + } + } // logMPAndSysOut("Synch requesting A requestEval " + getState()); - synchronized(requesting) { //MdP + synchronized (requesting) { //MdP // logMPAndSysOut(" in synch requesting A requestEval " + getState()); - if (requesting) { - String msg="Warning: already in requesting state when request arrived!"; - System.err.println(msg); - logMP(msg); - } - requesting = true; + if (requesting) { + String msg = "Warning: already in requesting state when request arrived!"; + System.err.println(msg); + logMP(msg); + } + requesting = true; // logMPAndSysOut("-- Requesting eval for " + BeanInspector.toString(x) + ", req state is " + requesting + "\n"); - } - - + } + + // logMPAndSysOut("Synch requesting A done " + getState()); - /*int k=0; int mod=25; - while (requesting && !quit) { + /*int k=0; int mod=25; + while (requesting && !quit) { // wait for matlab to answer the question if (sleepTime > 0) try { Thread.sleep(sleepTime); } catch(Exception e) { System.err.println("Exception in sleep (MatlabEvalMediator)"); @@ -116,189 +116,197 @@ public class MatlabEvalMediator { } }*/ - try { - requests.acquire(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - logMP("-- Requesting done\n"); - // matlab is finished, answer is here - //return null; - return getAnswer(); // return to JE with answer - } - - public String getState() { - return "ID: " + runID + ", qu: " + BeanInspector.toString(question) + " quit,fin,req " + quit + "," + fin +"," + requesting; - } + try { + requests.acquire(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logMP("-- Requesting done\n"); + // matlab is finished, answer is here + //return null; + return getAnswer(); // return to JE with answer + } - /** - * Wait loop, wait until the MatlabProblem requests an evaluation (or finishes), then return. - * For debugging, an integer ID for this run may be provided. - */ - public void run(int id) { - logMPOrSysOut("## MEM start run " + id); - runID=id; - int k=0;int mod=25; - while (!requesting && !isFinished() && !quit) { - // wait for JE to pose a question or finish all - if (sleepTime > 0) { - try { Thread.sleep(sleepTime); } catch(Exception e) {} - }; - k++; - if ((k%mod)==0) { - logMPOrSysOut("MEM waiting for JE to ask... (" + mod +") " + getState()); - mod*=2; - if (mod<=0) { - mod = Integer.MAX_VALUE; - } - } - } - if (requesting) { - logMPOrSysOut("-- MEM Request arrived in MP thread " + runID); + public String getState() { + return "ID: " + runID + ", qu: " + BeanInspector.toString(question) + " quit,fin,req " + quit + "," + fin + "," + requesting; + } + + /** + * Wait loop, wait until the MatlabProblem requests an evaluation (or finishes), then return. + * For debugging, an integer ID for this run may be provided. + */ + public void run(int id) { + logMPOrSysOut("## MEM start run " + id); + runID = id; + int k = 0; + int mod = 25; + while (!requesting && !isFinished() && !quit) { + // wait for JE to pose a question or finish all + if (sleepTime > 0) { + try { + Thread.sleep(sleepTime); + } catch (Exception e) { + } } - else { - logMPOrSysOut("-- MEM finished or quit " + runID); - } - // requesting is true, now finish and let Matlab work - } - - /** - * Wait loop, wait until the MatlabProblem requests an evaluation (or finishes), then return. - * Calls the {@link #run(int)} method with ID zero. - */ - public void run() { - run(0); - } - - private void logMPOrSysOut(String msg) { + ; + k++; + if ((k % mod) == 0) { + logMPOrSysOut("MEM waiting for JE to ask... (" + mod + ") " + getState()); + mod *= 2; + if (mod <= 0) { + mod = Integer.MAX_VALUE; + } + } + } + if (requesting) { + logMPOrSysOut("-- MEM Request arrived in MP thread " + runID); + } else { + logMPOrSysOut("-- MEM finished or quit " + runID); + } + // requesting is true, now finish and let Matlab work + } + + /** + * Wait loop, wait until the MatlabProblem requests an evaluation (or finishes), then return. + * Calls the {@link #run(int)} method with ID zero. + */ + public void run() { + run(0); + } + + private void logMPOrSysOut(String msg) { // System.out.println("Hurz OR"); - logMP(msg); + logMP(msg); // else System.out.println("MEM has no MP! " + msg); - } - - private void logMPAndSysOut(String msg) { + } + + private void logMPAndSysOut(String msg) { // System.out.println("Hurz AND"); // logMP(msg + "\n"); // System.out.println(msg); - } + } - private void logMP(String msg) { - if (mp!=null) { - mp.log(msg + "\n"); - } - } - - /** - * Cancel waiting in any case. - */ - public void quit() { + private void logMP(String msg) { + if (mp != null) { + mp.log(msg + "\n"); + } + } + + /** + * Cancel waiting in any case. + */ + public void quit() { // System.out.println("IN QUIT!"); - quit = true; - } - - /** - * To be called from Matlab. - * @return - */ - public Object getQuestion() { - if (mp!=null) { - logMP("-- Question: " + BeanInspector.toString(question) + "\n"); - } - return question; - } + quit = true; + } - double[] getAnswer() { - if (mp!=null) { - logMP("-- mediator delivering " + BeanInspector.toString(answer) + "\n"); - } - return answer; - } + /** + * To be called from Matlab. + * + * @return + */ + public Object getQuestion() { + if (mp != null) { + logMP("-- Question: " + BeanInspector.toString(question) + "\n"); + } + return question; + } - /** - * To be called from Matlab giving the result of the question. - * - * @param y - */ - public void setAnswer(double[] y) { + double[] getAnswer() { + if (mp != null) { + logMP("-- mediator delivering " + BeanInspector.toString(answer) + "\n"); + } + return answer; + } + + /** + * To be called from Matlab giving the result of the question. + * + * @param y + */ + public void setAnswer(double[] y) { // logMPAndSysOut("Synch requesting B setAnswer " + getState()); - synchronized(requesting) { + synchronized (requesting) { // logMPAndSysOut("In Synch requesting B setAnswer " + getState()); - if (!requesting) { - String msg="Error: not in requesting state when answer arrived!!"; - System.err.println(msg); - logMP(msg); - } + if (!requesting) { + String msg = "Error: not in requesting state when answer arrived!!"; + System.err.println(msg); + logMP(msg); + } // System.err.println("answer is " + BeanInspector.toString(y)); - if (y==null) { - System.err.println("Error: Matlab function returned null array - this is bad."); - System.err.println("X-value was " + BeanInspector.toString(getQuestion())); - } - answer = y; - requesting = false; // answer is finished, break request loop - requests.release(); - logMP("-- setAnswer: " + BeanInspector.toString(y) + ", req state is " + requesting + "\n"); - } + if (y == null) { + System.err.println("Error: Matlab function returned null array - this is bad."); + System.err.println("X-value was " + BeanInspector.toString(getQuestion())); + } + answer = y; + requesting = false; // answer is finished, break request loop + requests.release(); + logMP("-- setAnswer: " + BeanInspector.toString(y) + ", req state is " + requesting + "\n"); + } // logMPAndSysOut("Synch requesting B done " + getState()); - } + } - void setFinished(boolean val) { + void setFinished(boolean val) { // logMPAndSysOut("Synch fin " + getState()); - synchronized (fin) { - if (fin && val) { - String msg="Error: already finished when setFinished(true) was called!"; - System.err.println(msg); - logMP(msg); - } - fin = val; - logMPOrSysOut("MEM setFinished ok"); - } + synchronized (fin) { + if (fin && val) { + String msg = "Error: already finished when setFinished(true) was called!"; + System.err.println(msg); + logMP(msg); + } + fin = val; + logMPOrSysOut("MEM setFinished ok"); + } // logMPAndSysOut("Synch fin done " + getState()); - } + } - /** - * To be called from Matlab signalling when optimizaton is completely finished. - * @return - */ - public boolean isFinished() { - return fin; - } - - void setSolution(Object sol) { + /** + * To be called from Matlab signalling when optimizaton is completely finished. + * + * @return + */ + public boolean isFinished() { + return fin; + } + + void setSolution(Object sol) { // System.err.println("setting obj Sol " + BeanInspector.toString(sol)); - optSolution = sol; - } - - void setSolutionSet(double[][] solSet) { + optSolution = sol; + } + + void setSolutionSet(double[][] solSet) { // System.err.println("setting dbl SolSet " + ((solSet != null) ? solSet.length : 0)); - optSolSet = solSet; - } - - void setSolutionSet(BitSet[] solSet) { + optSolSet = solSet; + } + + void setSolutionSet(BitSet[] solSet) { // System.err.println("setting bs SolSet " + ((solSet != null) ? solSet.length : 0)); - optSolSet = solSet; - } - - void setSolutionSet(int[][] solSet) { + optSolSet = solSet; + } + + void setSolutionSet(int[][] solSet) { // System.err.println("setting int SolSet " + ((solSet != null) ? solSet.length : 0)); - optSolSet = solSet; - } - - /** - * Matlab may retrieve result. - * @return - */ - public Object getSolution() { + optSolSet = solSet; + } + + /** + * Matlab may retrieve result. + * + * @return + */ + public Object getSolution() { // System.err.println("getting Sol " + BeanInspector.toString(optSolution)); - return optSolution; - } - - /** - * Matlab may retrieve result as Object[] containing either double[] or int[]. - * @return - */ - public Object getSolutionSet() { + return optSolution; + } + + /** + * Matlab may retrieve result as Object[] containing either double[] or int[]. + * + * @return + */ + public Object getSolutionSet() { // System.err.println("getting SolSet " + ((optSolSet != null) ? optSolSet.length : 0)); - return optSolSet; - } + return optSolSet; + } } \ No newline at end of file diff --git a/src/eva2/optimization/problems/MatlabProblemDataTypeEnum.java b/src/eva2/optimization/problems/MatlabProblemDataTypeEnum.java index 2e90aaee..3de5b044 100644 --- a/src/eva2/optimization/problems/MatlabProblemDataTypeEnum.java +++ b/src/eva2/optimization/problems/MatlabProblemDataTypeEnum.java @@ -1,5 +1,5 @@ package eva2.optimization.problems; public enum MatlabProblemDataTypeEnum { - typeDouble, typeBinary, typeInteger; + typeDouble, typeBinary, typeInteger; } diff --git a/src/eva2/optimization/problems/PSymbolicRegression.java b/src/eva2/optimization/problems/PSymbolicRegression.java index e11d745c..cf268cf6 100644 --- a/src/eva2/optimization/problems/PSymbolicRegression.java +++ b/src/eva2/optimization/problems/PSymbolicRegression.java @@ -31,6 +31,7 @@ import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.EVAERROR; import eva2.tools.ToolBox; import eva2.tools.math.RNG; + import java.io.Serializable; /** @@ -40,24 +41,24 @@ import java.io.Serializable; * Time: 16:44:25 * To change this template use Options | File Templates. */ -public class PSymbolicRegression extends AbstractOptimizationProblem implements InterfaceProgramProblem, InterfaceAdditionalPopulationInformer, Serializable { +public class PSymbolicRegression extends AbstractOptimizationProblem implements InterfaceProgramProblem, InterfaceAdditionalPopulationInformer, Serializable { - private double[] m_X = new double[1]; - private int m_NumberOfConstants = 3; - private double m_LowerBound = -1; - private double m_UpperBound = 1; - private int m_NumberOfCheckPoints = 20; - transient private InterfaceRegressionFunction m_TargetFunction = new RFKoza_GPI_7_3(); - private double[] m_C = new double[m_NumberOfConstants]; - private boolean m_UseInnerConst = false; - private boolean m_UseLocalHillClimbing = false; - private GPArea m_GPArea = new GPArea(); - protected AbstractEAIndividual m_OverallBest = null; - protected double m_Noise = 0.0; + private double[] m_X = new double[1]; + private int m_NumberOfConstants = 3; + private double m_LowerBound = -1; + private double m_UpperBound = 1; + private int m_NumberOfCheckPoints = 20; + transient private InterfaceRegressionFunction m_TargetFunction = new RFKoza_GPI_7_3(); + private double[] m_C = new double[m_NumberOfConstants]; + private boolean m_UseInnerConst = false; + private boolean m_UseLocalHillClimbing = false; + private GPArea m_GPArea = new GPArea(); + protected AbstractEAIndividual m_OverallBest = null; + protected double m_Noise = 0.0; // This is graphics stuff - transient private Plot m_Plot; - private boolean m_Show = false; + transient private Plot m_Plot; + private boolean m_Show = false; public PSymbolicRegression() { this.template = new GPIndividualProgramData(); @@ -68,17 +69,17 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements public PSymbolicRegression(PSymbolicRegression b) { //AbstractOptimizationProblem if (b.template != null) { - this.template = (AbstractEAIndividual)((AbstractEAIndividual)b.template).clone(); + this.template = (AbstractEAIndividual) ((AbstractEAIndividual) b.template).clone(); } //F1Problem if (b.m_OverallBest != null) { - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); + this.m_OverallBest = (AbstractEAIndividual) ((AbstractEAIndividual) b.m_OverallBest).clone(); } if (b.m_GPArea != null) { - this.m_GPArea = (GPArea)b.m_GPArea.clone(); + this.m_GPArea = (GPArea) b.m_GPArea.clone(); } if (b.m_TargetFunction != null) { - this.m_TargetFunction = (InterfaceRegressionFunction)b.m_TargetFunction.clone(); + this.m_TargetFunction = (InterfaceRegressionFunction) b.m_TargetFunction.clone(); } if (b.m_X != null) { this.m_X = new double[b.m_X.length]; @@ -92,100 +93,108 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements this.m_C[i] = b.m_C[i]; } } - this.m_Noise = b.m_Noise; - this.m_UseInnerConst = b.m_UseInnerConst; + this.m_Noise = b.m_Noise; + this.m_UseInnerConst = b.m_UseInnerConst; this.m_UseLocalHillClimbing = b.m_UseLocalHillClimbing; - this.m_NumberOfConstants = b.m_NumberOfConstants; - this.m_LowerBound = b.m_LowerBound; - this.m_UpperBound = b.m_UpperBound; - this.m_NumberOfCheckPoints = b.m_NumberOfCheckPoints; - this.m_LowerBound = b.m_LowerBound; + this.m_NumberOfConstants = b.m_NumberOfConstants; + this.m_LowerBound = b.m_LowerBound; + this.m_UpperBound = b.m_UpperBound; + this.m_NumberOfCheckPoints = b.m_NumberOfCheckPoints; + this.m_LowerBound = b.m_LowerBound; } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new PSymbolicRegression(this); } - /** This method inits the Problem to log multiruns + /** + * This method inits the Problem to log multiruns */ @Override public void initializeProblem() { if (m_TargetFunction == null) { m_TargetFunction = new RFKoza_GPI_7_3(); } - this.m_OverallBest = null; - this.m_C = new double[this.m_NumberOfConstants]; + this.m_OverallBest = null; + this.m_C = new double[this.m_NumberOfConstants]; for (int i = 0; i < this.m_C.length; i++) { this.m_C[i] = RNG.randomDouble(-10, 10); } - } + } /** * This method compiles the area. Only to be called once in the constructor * to build the basic function set or if the number of constants etc. change. */ private void compileArea() { - // unfortunately this must be cloned or the GUI wont update. - GPArea oldArea=m_GPArea; - m_GPArea = new GPArea(); - - if (m_GPArea.isEmpty()) { - this.m_GPArea.add2CompleteList(new GPNodeOne()); - this.m_GPArea.add2CompleteList(new GPNodePi(), false); - this.m_GPArea.add2CompleteList(new GPNodeAdd()); - this.m_GPArea.add2CompleteList(new GPNodeSub()); - this.m_GPArea.add2CompleteList(new GPNodeDiv()); - this.m_GPArea.add2CompleteList(new GPNodeMult()); - this.m_GPArea.add2CompleteList(new GPNodeAbs(), false); - this.m_GPArea.add2CompleteList(new GPNodeSin(), false); - this.m_GPArea.add2CompleteList(new GPNodeCos(), false); - this.m_GPArea.add2CompleteList(new GPNodeExp(), false); - this.m_GPArea.add2CompleteList(new GPNodeSqrt(), false); - this.m_GPArea.add2CompleteList(new GPNodePow2(), false); - this.m_GPArea.add2CompleteList(new GPNodePow3(), false); - for (int i = 0; i < this.m_X.length; i++) { - this.m_GPArea.add2CompleteList(new GPNodeInput("X"+i)); + // unfortunately this must be cloned or the GUI wont update. + GPArea oldArea = m_GPArea; + m_GPArea = new GPArea(); + + if (m_GPArea.isEmpty()) { + this.m_GPArea.add2CompleteList(new GPNodeOne()); + this.m_GPArea.add2CompleteList(new GPNodePi(), false); + this.m_GPArea.add2CompleteList(new GPNodeAdd()); + this.m_GPArea.add2CompleteList(new GPNodeSub()); + this.m_GPArea.add2CompleteList(new GPNodeDiv()); + this.m_GPArea.add2CompleteList(new GPNodeMult()); + this.m_GPArea.add2CompleteList(new GPNodeAbs(), false); + this.m_GPArea.add2CompleteList(new GPNodeSin(), false); + this.m_GPArea.add2CompleteList(new GPNodeCos(), false); + this.m_GPArea.add2CompleteList(new GPNodeExp(), false); + this.m_GPArea.add2CompleteList(new GPNodeSqrt(), false); + this.m_GPArea.add2CompleteList(new GPNodePow2(), false); + this.m_GPArea.add2CompleteList(new GPNodePow3(), false); + for (int i = 0; i < this.m_X.length; i++) { + this.m_GPArea.add2CompleteList(new GPNodeInput("X" + i)); } - for (int i = 0; i < this.m_C.length; i++) { - this.m_GPArea.add2CompleteList(new GPNodeInput("C"+i), false); + for (int i = 0; i < this.m_C.length; i++) { + this.m_GPArea.add2CompleteList(new GPNodeInput("C" + i), false); } - } - if ((oldArea!=null) && (oldArea.getBlackList()!=null) && (oldArea.getBlackList().size()==m_GPArea.getBlackList().size())) { - m_GPArea.SetBlackList(oldArea.getBlackList()); - } + } + if ((oldArea != null) && (oldArea.getBlackList() != null) && (oldArea.getBlackList().size() == m_GPArea.getBlackList().size())) { + m_GPArea.SetBlackList(oldArea.getBlackList()); + } this.m_GPArea.compileReducedList(); } - /** This method inits a given population - * @param population The populations that is to be inited + /** + * This method inits a given population + * + * @param population The populations that is to be inited */ @Override public void initializePopulation(Population population) { - initPopulation(population, this, m_UseInnerConst, m_NumberOfConstants); + initPopulation(population, this, m_UseInnerConst, m_NumberOfConstants); } - - /** This method inits a given population - * @param population The populations that is to be inited + + /** + * This method inits a given population + * + * @param population The populations that is to be inited */ public static void initPopulation(Population pop, InterfaceProgramProblem prob, boolean useInnerConsts, int numConsts) { AbstractEAIndividual template; - template = ((AbstractOptimizationProblem)prob).getIndividualTemplate(); - GPArea tmpArea[] = new GPArea[1]; - tmpArea[0] = prob.getArea(); - ((InterfaceDataTypeProgram)template).setProgramDataLength(1); - ((InterfaceDataTypeProgram)template).SetFunctionArea(tmpArea); + template = ((AbstractOptimizationProblem) prob).getIndividualTemplate(); + GPArea tmpArea[] = new GPArea[1]; + tmpArea[0] = prob.getArea(); + ((InterfaceDataTypeProgram) template).setProgramDataLength(1); + ((InterfaceDataTypeProgram) template).SetFunctionArea(tmpArea); if ((template instanceof GAPIndividualProgramData) && useInnerConsts) { - ((GAPIndividualProgramData)template).setDoubleDataLength(numConsts); + ((GAPIndividualProgramData) template).setDoubleDataLength(numConsts); } AbstractOptimizationProblem.defaultInitPopulation(pop, template, prob); } - - /** This method init the enviroment panel if necessary. + + /** + * This method init the enviroment panel if necessary. */ private void initEnvironmentPanel() { if (this.m_Plot == null) { @@ -193,39 +202,41 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements } } - /** This method evaluates a given population and set the fitness values + /** + * This method evaluates a given population and set the fitness values * accordingly - * @param population The population that is to be evaluated. + * + * @param population The population that is to be evaluated. */ @Override public void evaluate(Population population) { - AbstractEAIndividual tmpIndy; + AbstractEAIndividual tmpIndy; evaluatePopulationStart(population); for (int i = 0; i < population.size(); i++) { tmpIndy = (AbstractEAIndividual) population.get(i); tmpIndy.resetConstraintViolation(); if ((this.m_UseLocalHillClimbing) && (tmpIndy instanceof GAPIndividualProgramData)) { - AbstractEAIndividual tmpBestConst = (AbstractEAIndividual)((GAPIndividualProgramData)tmpIndy).getNumbers(); - AbstractEAIndividual tmpConst; - this.evaluate(tmpIndy); - tmpBestConst.SetFitness(0, tmpIndy.getFitness(0)); - population.incrFunctionCalls(); - for (int j = 0; j < 10; j++) { - tmpConst = (AbstractEAIndividual)tmpBestConst.clone(); - tmpConst.mutate(); - ((GAPIndividualProgramData)tmpIndy).setNumbers((InterfaceDataTypeDouble)tmpConst); - this.evaluate(tmpIndy); - tmpConst.SetFitness(0, tmpIndy.getFitness(0)); - population.incrFunctionCalls(); - if (tmpBestConst.getFitness(0) > tmpConst.getFitness(0)) { - tmpBestConst = (AbstractEAIndividual)tmpConst.clone(); + AbstractEAIndividual tmpBestConst = (AbstractEAIndividual) ((GAPIndividualProgramData) tmpIndy).getNumbers(); + AbstractEAIndividual tmpConst; + this.evaluate(tmpIndy); + tmpBestConst.SetFitness(0, tmpIndy.getFitness(0)); + population.incrFunctionCalls(); + for (int j = 0; j < 10; j++) { + tmpConst = (AbstractEAIndividual) tmpBestConst.clone(); + tmpConst.mutate(); + ((GAPIndividualProgramData) tmpIndy).setNumbers((InterfaceDataTypeDouble) tmpConst); + this.evaluate(tmpIndy); + tmpConst.SetFitness(0, tmpIndy.getFitness(0)); + population.incrFunctionCalls(); + if (tmpBestConst.getFitness(0) > tmpConst.getFitness(0)) { + tmpBestConst = (AbstractEAIndividual) tmpConst.clone(); } - } - ((GAPIndividualProgramData)tmpIndy).setNumbers((InterfaceDataTypeDouble)tmpBestConst); - tmpIndy.SetFitness(0, tmpBestConst.getFitness(0)); + } + ((GAPIndividualProgramData) tmpIndy).setNumbers((InterfaceDataTypeDouble) tmpBestConst); + tmpIndy.SetFitness(0, tmpBestConst.getFitness(0)); } else { - if (m_UseLocalHillClimbing) { + if (m_UseLocalHillClimbing) { EVAERROR.errorMsgOnce("Error: local hill climbing only works on GAPIndividualProgramData individuals!"); } this.evaluate(tmpIndy); @@ -235,50 +246,50 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements evaluatePopulationEnd(population); } - /** + /** * This method evaluates a single individual and sets the fitness values. In this case, * the averaged square error between represented function and target function per check point is calculated. - * - * @param individual The individual that is to be evaluated + * + * @param individual The individual that is to be evaluated */ @Override public void evaluate(AbstractEAIndividual individual) { - InterfaceProgram program; - double fitness = 0, tmpValue; - InterfaceDataTypeProgram tmpIndy; + InterfaceProgram program; + double fitness = 0, tmpValue; + InterfaceDataTypeProgram tmpIndy; - tmpIndy = (InterfaceDataTypeProgram) individual; - program = tmpIndy.getProgramData()[0]; + tmpIndy = (InterfaceDataTypeProgram) individual; + program = tmpIndy.getProgramData()[0]; if ((tmpIndy instanceof GAPIndividualProgramData) && (this.m_UseInnerConst)) { - this.m_C = ((GAPIndividualProgramData)tmpIndy).getDoubleData(); + this.m_C = ((GAPIndividualProgramData) tmpIndy).getDoubleData(); } - fitness = 0; + fitness = 0; for (int j = 0; j < this.m_NumberOfCheckPoints; j++) { - setCheckPoint(m_X, j); - tmpValue = ((Double)program.evaluate(this)).doubleValue(); - fitness += Math.pow((this.m_TargetFunction.evaluateFunction(this.m_X) - ((Double)program.evaluate(this)).doubleValue()), 2); + setCheckPoint(m_X, j); + tmpValue = ((Double) program.evaluate(this)).doubleValue(); + fitness += Math.pow((this.m_TargetFunction.evaluateFunction(this.m_X) - ((Double) program.evaluate(this)).doubleValue()), 2); } - - fitness /= (double)this.m_NumberOfCheckPoints; + + fitness /= (double) this.m_NumberOfCheckPoints; // add noise to the fitness fitness += RNG.gaussianDouble(this.m_Noise); // set the fitness of the individual individual.SetFitness(0, fitness); - if ((this.m_Plot != null) && (this.m_Plot.getFunctionArea().getContainerSize() ==0)) { + if ((this.m_Plot != null) && (this.m_Plot.getFunctionArea().getContainerSize() == 0)) { this.m_OverallBest = null; } if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { - this.m_OverallBest = (AbstractEAIndividual)individual.clone(); + this.m_OverallBest = (AbstractEAIndividual) individual.clone(); if (this.m_Show) { - if (m_Plot==null) { + if (m_Plot == null) { this.initEnvironmentPanel(); } this.m_Plot.clearAll(); - program = ((InterfaceDataTypeProgram)this.m_OverallBest).getProgramData()[0]; + program = ((InterfaceDataTypeProgram) this.m_OverallBest).getProgramData()[0]; for (int i = 0; i < this.m_NumberOfCheckPoints; i++) { setCheckPoint(m_X, i); - tmpValue = ((Double)program.evaluate(this)).doubleValue(); + tmpValue = ((Double) program.evaluate(this)).doubleValue(); this.m_Plot.setConnectedPoint(this.m_X[0], tmpValue, 0); tmpValue = this.m_TargetFunction.evaluateFunction(this.m_X); this.m_Plot.setConnectedPoint(this.m_X[0], tmpValue, 1); @@ -290,17 +301,20 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements /** * Select a test point - TODO this btw only makes much sense in 1D. + * * @param x * @param j */ - private void setCheckPoint(double[] x, int j) { - for (int i = 0; i < x.length; i++) { - x[i] = this.m_LowerBound +(j*(this.m_UpperBound-this.m_LowerBound)/(this.m_NumberOfCheckPoints-1)); - } - } + private void setCheckPoint(double[] x, int j) { + for (int i = 0; i < x.length; i++) { + x[i] = this.m_LowerBound + (j * (this.m_UpperBound - this.m_LowerBound) / (this.m_NumberOfCheckPoints - 1)); + } + } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -312,49 +326,51 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements /** These methods are for the InterfaceProgramProblem and allow the program to acess to an * artificial environment, e.g. the Artifical Ant World or the x values for Symoblic Regression. */ - /** This method allows a GP program to sense the environment, e.g. + /** + * This method allows a GP program to sense the environment, e.g. * input values, current time etc - * @param sensor The identifier for the sensor. + * + * @param sensor The identifier for the sensor. * @return Sensor value */ @Override public Object getSensorValue(String sensor) { - return PSymbolicRegression.getSensorValue(sensor, m_X, m_C); + return PSymbolicRegression.getSensorValue(sensor, m_X, m_C); // for (int i = 0; i < this.m_X.length; i++) if (sensor.equalsIgnoreCase("X"+i)) return new Double(this.m_X[i]); // for (int i = 0; i < this.m_C.length; i++) if (sensor.equalsIgnoreCase("C"+i)) return new Double(this.m_C[i]); // return new Double(0); } - - /** + + /** * This method allows a GP program to sense the environment, e.g. * input values, current time etc. Specialized to constants and variables * in arrays whose identifiers have the form "Xi" and "Ci". * For an identifier X only, the full vars array is returned. For an * identifier N only, the array dimension is returned. - * - * @param sensor The identifier for the sensor. - * @param vars array of x_i - * @param consts array of c_i + * + * @param sensor The identifier for the sensor. + * @param vars array of x_i + * @param consts array of c_i * @return Sensor value */ public static Object getSensorValue(String sensor, double[] vars, double[] consts) { - if (sensor.charAt(0)=='X') { - try { - if (sensor.length()==1) { - return vars; - } - int index=Integer.parseInt(sensor.substring(1)); - return new Double(vars[index]); - } catch(Exception e) { - System.err.println("Warning, unable to access " + sensor); - return vars; - } - } else if (sensor.charAt(0)=='C') { - int index=Integer.parseInt(sensor.substring(1)); - return new Double(consts[index]); - } else if (sensor.charAt(0)=='N') { - return (double)vars.length; - } else { + if (sensor.charAt(0) == 'X') { + try { + if (sensor.length() == 1) { + return vars; + } + int index = Integer.parseInt(sensor.substring(1)); + return new Double(vars[index]); + } catch (Exception e) { + System.err.println("Warning, unable to access " + sensor); + return vars; + } + } else if (sensor.charAt(0) == 'C') { + int index = Integer.parseInt(sensor.substring(1)); + return new Double(consts[index]); + } else if (sensor.charAt(0) == 'N') { + return (double) vars.length; + } else { return new Double(0); } // for (int i = 0; i < this.m_X.length; i++) if (sensor.equalsIgnoreCase("X"+i)) return new Double(this.m_X[i]); @@ -362,9 +378,11 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements // return new Double(0); } - /** This method allows a GP program to act in the environment - * @param actuator The identifier for the actuator. - * @param parameter The actuator parameter. + /** + * This method allows a GP program to act in the environment + * + * @param actuator The identifier for the actuator. + * @param parameter The actuator parameter. */ @Override public void setActuatorValue(String actuator, Object parameter) { @@ -374,8 +392,10 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -383,16 +403,20 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements return "Symbolic Regression problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "The task is to infer the equation of a system that can only be observed at a number of checkpoints."; } - /** This method allows you to choose how much noise is to be added to the + /** + * This method allows you to choose how much noise is to be added to the * fitness. This can be used to make the optimization problem more difficult. - * @param noise The sigma for a gaussian random number. + * + * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { if (noise < 0) { @@ -400,41 +424,53 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements } this.m_Noise = noise; } + public double getNoise() { return this.m_Noise; } + public String noiseTipText() { return "Noise level on the fitness value."; } - /** This method toggles the use of inner constants. - * @param b The flag to use inner constants. + /** + * This method toggles the use of inner constants. + * + * @param b The flag to use inner constants. */ public void setUseInnerConst(boolean b) { this.m_UseInnerConst = b; } + public boolean getUseInnerConst() { return this.m_UseInnerConst; } + public String useInnerConstTipText() { return "Toggle the use of inner constants."; } - /** This method toggles the use of local hill climbing for inner constants. - * @param b The flag to use local hill climbing for inner constants. + /** + * This method toggles the use of local hill climbing for inner constants. + * + * @param b The flag to use local hill climbing for inner constants. */ public void setUseLocalHillClimbing(boolean b) { this.m_UseLocalHillClimbing = b; } + public boolean getUseLocalHillClimbing() { return this.m_UseLocalHillClimbing; } + public String useLocalHillClimbingTipText() { return "Toggle the use of local hill climbing for inner constants."; } - /** This method allows you to set the number of ephremial constants. - * @param b The new number of ephremial constants. + /** + * This method allows you to set the number of ephremial constants. + * + * @param b The new number of ephremial constants. */ public void setNumberOfConstants(int b) { this.m_NumberOfConstants = b; @@ -442,242 +478,267 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements m_GPArea.clear(); this.compileArea(); } + public int getNumberOfConstants() { return this.m_NumberOfConstants; } + public String numberOfConstantsTipText() { return "Gives the number of ephremal constants."; } - /** This method allows you to set the number of check points. - * @param b The new number of check points. + /** + * This method allows you to set the number of check points. + * + * @param b The new number of check points. */ public void setNumberOfCheckPoints(int b) { if (b < 0) { - b = 1; + b = 1; } this.m_NumberOfCheckPoints = b; } + public int getNumberOfCheckPoints() { return this.m_NumberOfCheckPoints; } + public String numberOfCheckPointsTipText() { return "Choose the number of points where the GP have to compare to the target function."; } - /** This method allows you to toggle the use of the elements in the GPArea. - * @param i Number of maximal steps. + /** + * This method allows you to toggle the use of the elements in the GPArea. + * + * @param i Number of maximal steps. */ public void setArea(GPArea i) { - this.m_GPArea = i; - GPArea tmpArea[] = new GPArea[1]; - tmpArea[0] = this.m_GPArea; - ((InterfaceDataTypeProgram)this.template).setProgramDataLength(1); - ((InterfaceDataTypeProgram)this.template).SetFunctionArea(tmpArea); + this.m_GPArea = i; + GPArea tmpArea[] = new GPArea[1]; + tmpArea[0] = this.m_GPArea; + ((InterfaceDataTypeProgram) this.template).setProgramDataLength(1); + ((InterfaceDataTypeProgram) this.template).SetFunctionArea(tmpArea); } + @Override public GPArea getArea() { - if (m_GPArea==null) { + if (m_GPArea == null) { initializeProblem(); } return this.m_GPArea; } + public String areaTipText() { return "Select function set from the available area."; } - /** This method allows you to toggle path visualisation on and off. - * @param b True if the path is to be shown. + /** + * This method allows you to toggle path visualisation on and off. + * + * @param b True if the path is to be shown. */ public void setShowResult(boolean b) { this.m_Show = b; if (this.m_Show) { this.initEnvironmentPanel(); - } - else if (this.m_Plot != null) { + } else if (this.m_Plot != null) { this.m_Plot.dispose(); this.m_Plot = null; } } + public boolean getShowResult() { return this.m_Show; } + public String showResultTipText() { return "Toggles the result visualisation on/or off."; } - /** This method allows you to choose the target function. - * @param b The target function. + /** + * This method allows you to choose the target function. + * + * @param b The target function. */ public void setTargetFunction(InterfaceRegressionFunction b) { this.m_TargetFunction = b; } + public InterfaceRegressionFunction getTargetFunction() { - if (m_TargetFunction==null) { + if (m_TargetFunction == null) { initializeProblem(); } return this.m_TargetFunction; } + public String targetFunctionTipText() { return "Choose from the available target functions."; } - /** This method allows you to choose the EA individual + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setGPIndividual(InterfaceDataTypeProgram indy) { this.template = (AbstractEAIndividual) indy; } + public InterfaceDataTypeProgram getGPIndividual() { - return (InterfaceDataTypeProgram)this.template; + return (InterfaceDataTypeProgram) this.template; } + public String GPIndividualTipText() { - return "Modify the properties of the template GP individual such as maximum tree depth etc."; + return "Modify the properties of the template GP individual such as maximum tree depth etc."; } - + public double getLowerBound() { - return m_LowerBound; - } - public void setLowerBound(double mLowerBound) { - m_LowerBound = mLowerBound; - } - public String lowerBoundTipText() { - return "The lower bound of the 1D double interval where the target function is sampled."; - } + return m_LowerBound; + } - public double getUpperBound() { - return m_UpperBound; - } - public void setUpperBound(double mUpperBound) { - m_UpperBound = mUpperBound; - } - public String upperBoundTipText() { - return "The upper bound of the 1D double interval where the target function is sampled."; - } + public void setLowerBound(double mLowerBound) { + m_LowerBound = mLowerBound; + } - public String[] customPropertyOrder() { - return new String[] {"lowerBound", "upperBound"}; - } + public String lowerBoundTipText() { + return "The lower bound of the 1D double interval where the target function is sampled."; + } - @Override - public String[] getAdditionalDataHeader() { - String[] superHd = super.getAdditionalDataHeader(); - return ToolBox.appendArrays(new String[]{"bestIndySize","avgIndySize","avgMaxIndyDepth"}, superHd); - } + public double getUpperBound() { + return m_UpperBound; + } - @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - Object[] superDat = super.getAdditionalDataValue(pop); - return ToolBox.appendArrays(new Object[]{getBestIndySize(pop), getAvgIndySize(pop), getAvgIndyDepth(pop)}, superDat); - } + public void setUpperBound(double mUpperBound) { + m_UpperBound = mUpperBound; + } - /** - * Get the average tree depth of the given population (for program individuals). - * - * @see #getIndyDepth(AbstractEAIndividual) - * @param pop - * @return - */ - public static double getAvgIndyDepth(PopulationInterface pop) { - Population p = (Population)pop; - double sum=0; - for (int i=0; i simProb = new SimpleF1(); - protected double m_DefaultRange = 10; - protected double m_Noise = 0; - private int repaintMinWait = 20; - private int repaintCnt = 0; - transient Plot m_plot = null; - transient AbstractEAIndividual bestIndy = null; - String plotFunc = "plotBest"; - transient Class[] plotFuncSig = new Class[]{Plot.class, AbstractEAIndividual.class}; - transient private boolean resetTemplate = true; - - public SimpleProblemWrapper() { - m_plot = null; - initTemplate(); - } - - public SimpleProblemWrapper(SimpleProblemWrapper other) { - other.m_DefaultRange = m_DefaultRange; - other.m_Noise = m_Noise; - // warning! this does no deep copy! - setSimpleProblem(other.simProb); - } - - @Override - public Object clone() { - return new SimpleProblemWrapper(this); - } + InterfaceSimpleProblem simProb = new SimpleF1(); + protected double m_DefaultRange = 10; + protected double m_Noise = 0; + private int repaintMinWait = 20; + private int repaintCnt = 0; + transient Plot m_plot = null; + transient AbstractEAIndividual bestIndy = null; + String plotFunc = "plotBest"; + transient Class[] plotFuncSig = new Class[]{Plot.class, AbstractEAIndividual.class}; + transient private boolean resetTemplate = true; - @Override - public void evaluate(AbstractEAIndividual individual) { - if (simProb instanceof SimpleProblemDouble) { - double[] x; - double[] fitness; + public SimpleProblemWrapper() { + m_plot = null; + initTemplate(); + } - x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; - System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); - // evaluate the vector - fitness = ((SimpleProblemDouble)simProb).eval(x); - // if indicated, add Gaussian noise - if (m_Noise != 0) { - RNG.addNoise(fitness, m_Noise); - } - // set the fitness - individual.setFitness(fitness); - } else if (simProb instanceof SimpleProblemBinary) { - BitSet tmpBitSet; - double[] result; - - tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); - // evaluate the fitness - result = ((SimpleProblemBinary)simProb).eval(tmpBitSet); - // set the fitness - individual.setFitness(result); - } else { - System.err.println("Error in SimpleProblemWrapper: " + simProb.getClass().getName() + " is unknown type!"); - } - } + public SimpleProblemWrapper(SimpleProblemWrapper other) { + other.m_DefaultRange = m_DefaultRange; + other.m_Noise = m_Noise; + // warning! this does no deep copy! + setSimpleProblem(other.simProb); + } @Override - public void evaluatePopulationStart(Population population) { - if (m_plot != null && (!m_plot.isValid())) { - openPlot(); - } - } - + public Object clone() { + return new SimpleProblemWrapper(this); + } + @Override - public void evaluatePopulationEnd(Population population) { - super.evaluatePopulationEnd(population); - repaintCnt += population.size(); - if (m_plot != null) { - if (repaintCnt >= repaintMinWait) { // dont repaint always for small pops - if ((bestIndy == null) || (population.getBestEAIndividual().isDominant(bestIndy.getFitness()))) { - // only paint improvement - bestIndy = population.getBestEAIndividual(); - Object[] args = new Object[2]; - args[0] = m_plot; - args[1] = bestIndy; + public void evaluate(AbstractEAIndividual individual) { + if (simProb instanceof SimpleProblemDouble) { + double[] x; + double[] fitness; + + x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; + System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); + // evaluate the vector + fitness = ((SimpleProblemDouble) simProb).eval(x); + // if indicated, add Gaussian noise + if (m_Noise != 0) { + RNG.addNoise(fitness, m_Noise); + } + // set the fitness + individual.setFitness(fitness); + } else if (simProb instanceof SimpleProblemBinary) { + BitSet tmpBitSet; + double[] result; + + tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); + // evaluate the fitness + result = ((SimpleProblemBinary) simProb).eval(tmpBitSet); + // set the fitness + individual.setFitness(result); + } else { + System.err.println("Error in SimpleProblemWrapper: " + simProb.getClass().getName() + " is unknown type!"); + } + } + + @Override + public void evaluatePopulationStart(Population population) { + if (m_plot != null && (!m_plot.isValid())) { + openPlot(); + } + } + + @Override + public void evaluatePopulationEnd(Population population) { + super.evaluatePopulationEnd(population); + repaintCnt += population.size(); + if (m_plot != null) { + if (repaintCnt >= repaintMinWait) { // dont repaint always for small pops + if ((bestIndy == null) || (population.getBestEAIndividual().isDominant(bestIndy.getFitness()))) { + // only paint improvement + bestIndy = population.getBestEAIndividual(); + Object[] args = new Object[2]; + args[0] = m_plot; + args[1] = bestIndy; // System.out.println(population.getBestEAIndividual().getStringRepresentation()); - BeanInspector.callIfAvailable(simProb, plotFunc, args); - } - repaintCnt = 0; - } - } - } - - @Override - public void initializePopulation(Population population) { + BeanInspector.callIfAvailable(simProb, plotFunc, args); + } + repaintCnt = 0; + } + } + } + + @Override + public void initializePopulation(Population population) { initTemplate(); AbstractOptimizationProblem.defaultInitPopulation(population, template, this); - } + } - @Override - public void initializeProblem() { - bestIndy = null; - initTemplate(); - setSimpleProblem(getSimpleProblem()); // possibly create plot - BeanInspector.callIfAvailable(simProb, "initializeProblem", null); // possibly call initializeProblem of subproblem - } + @Override + public void initializeProblem() { + bestIndy = null; + initTemplate(); + setSimpleProblem(getSimpleProblem()); // possibly create plot + BeanInspector.callIfAvailable(simProb, "initializeProblem", null); // possibly call initializeProblem of subproblem + } - protected void initTemplate() { - if (resetTemplate) { - if (simProb instanceof SimpleProblemDouble) { - this.template = new ESIndividualDoubleData(); - } else if (simProb instanceof SimpleProblemBinary) { - this.template = new GAIndividualBinaryData(); - } - } - if (template instanceof InterfaceDataTypeDouble) { - ((InterfaceDataTypeDouble)this.template).setDoubleDataLength(simProb.getProblemDimension()); - ((InterfaceDataTypeDouble)this.template).SetDoubleRange(makeRange()); - } else if (template instanceof InterfaceDataTypeBinary) { - ((InterfaceDataTypeBinary)this.template).setBinaryDataLength(simProb.getProblemDimension()); - } else { - System.err.println("Individual type not valid!"); + protected void initTemplate() { + if (resetTemplate) { + if (simProb instanceof SimpleProblemDouble) { + this.template = new ESIndividualDoubleData(); + } else if (simProb instanceof SimpleProblemBinary) { + this.template = new GAIndividualBinaryData(); } - } - + } + if (template instanceof InterfaceDataTypeDouble) { + ((InterfaceDataTypeDouble) this.template).setDoubleDataLength(simProb.getProblemDimension()); + ((InterfaceDataTypeDouble) this.template).SetDoubleRange(makeRange()); + } else if (template instanceof InterfaceDataTypeBinary) { + ((InterfaceDataTypeBinary) this.template).setBinaryDataLength(simProb.getProblemDimension()); + } else { + System.err.println("Individual type not valid!"); + } + } + protected double[][] makeRange() { - double[][] range = new double[simProb.getProblemDimension()][2]; - for (int i = 0; i < range.length; i++) { - range[i][0] = getRangeLowerBound(i); - range[i][1] = getRangeUpperBound(i); - } - return range; + double[][] range = new double[simProb.getProblemDimension()][2]; + for (int i = 0; i < range.length; i++) { + range[i][0] = getRangeLowerBound(i); + range[i][1] = getRangeUpperBound(i); + } + return range; } - + protected double getRangeLowerBound(int dim) { - return -m_DefaultRange; + return -m_DefaultRange; } - + protected double getRangeUpperBound(int dim) { - return m_DefaultRange; + return m_DefaultRange; } - - /** - * @return the simProb - */ - public InterfaceSimpleProblem getSimpleProblem() { - return simProb; - } - - private void openPlot() { - m_plot = new Plot("SimpleProblemWrapper", "x", "y", true); - } - /** - * @param simProb the simProb to set - */ - public void setSimpleProblem(InterfaceSimpleProblem simProb) { - this.simProb = simProb; - initTemplate(); - GenericObjectEditor.setShowProperty(getClass(), "noise", (simProb instanceof SimpleProblemDouble)); - GenericObjectEditor.setShowProperty(getClass(), "defaultRange", (simProb instanceof SimpleProblemDouble)); - if (BeanInspector.hasMethod(simProb, plotFunc, plotFuncSig) != null) { - if (m_plot == null) { - openPlot(); - } - else { - if (!m_plot.isValid()) { - m_plot.dispose(); - openPlot(); - } else { - m_plot.clearAll(); - } - } - } else if (m_plot != null) { - m_plot.dispose(); - m_plot = null; - } - } + /** + * @return the simProb + */ + public InterfaceSimpleProblem getSimpleProblem() { + return simProb; + } - /** - * - */ - public String simpleProblemTipText() { - return "Set the simple problem class which is to be optimized"; - } - - /** This method allows you to choose how much noise is to be added to the + private void openPlot() { + m_plot = new Plot("SimpleProblemWrapper", "x", "y", true); + } + + /** + * @param simProb the simProb to set + */ + public void setSimpleProblem(InterfaceSimpleProblem simProb) { + this.simProb = simProb; + initTemplate(); + GenericObjectEditor.setShowProperty(getClass(), "noise", (simProb instanceof SimpleProblemDouble)); + GenericObjectEditor.setShowProperty(getClass(), "defaultRange", (simProb instanceof SimpleProblemDouble)); + if (BeanInspector.hasMethod(simProb, plotFunc, plotFuncSig) != null) { + if (m_plot == null) { + openPlot(); + } else { + if (!m_plot.isValid()) { + m_plot.dispose(); + openPlot(); + } else { + m_plot.clearAll(); + } + } + } else if (m_plot != null) { + m_plot.dispose(); + m_plot = null; + } + } + + /** + * + */ + public String simpleProblemTipText() { + return "Set the simple problem class which is to be optimized"; + } + + /** + * This method allows you to choose how much noise is to be added to the * fitness. This can be used to make the optimization problem more difficult. - * @param noise The sigma for a gaussian random number. + * + * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { if (noise < 0) { @@ -206,57 +209,63 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem { } this.m_Noise = noise; } + public double getNoise() { return this.m_Noise; } + public String noiseTipText() { return "Gaussian noise level on the fitness value."; } - - - /** - * A (symmetric) absolute range limit. - * - * @return value of the absolute range limit - */ - public double getDefaultRange() { - return m_DefaultRange; - } - /** - * Set a (symmetric) absolute range limit. - * - * @param defaultRange - */ - public void setDefaultRange(double defaultRange) { - this.m_DefaultRange = defaultRange; - initTemplate(); - } - public String defaultRangeTipText() { - return "Absolute limit for the symmetric range in any dimension"; - } - - /** - * Take care that all properties which may be hidden (and currently are) send a "hide" message to the Java Bean properties. - * This is called by PropertySheetPanel in use with the GenericObjectEditor. - */ - public void hideHideable() { - setSimpleProblem(getSimpleProblem()); - } - - public void setIndividualTemplate(AbstractEAIndividual indy) { - resetTemplate = false; - template = indy; - } - + + + /** + * A (symmetric) absolute range limit. + * + * @return value of the absolute range limit + */ + public double getDefaultRange() { + return m_DefaultRange; + } + + /** + * Set a (symmetric) absolute range limit. + * + * @param defaultRange + */ + public void setDefaultRange(double defaultRange) { + this.m_DefaultRange = defaultRange; + initTemplate(); + } + + public String defaultRangeTipText() { + return "Absolute limit for the symmetric range in any dimension"; + } + + /** + * Take care that all properties which may be hidden (and currently are) send a "hide" message to the Java Bean properties. + * This is called by PropertySheetPanel in use with the GenericObjectEditor. + */ + public void hideHideable() { + setSimpleProblem(getSimpleProblem()); + } + + public void setIndividualTemplate(AbstractEAIndividual indy) { + resetTemplate = false; + template = indy; + } + @Override - public String individualTemplateTipText() { - return "Set the individual properties for the optimization"; - } - + public String individualTemplateTipText() { + return "Set the individual properties for the optimization"; + } + /////////// for GUI - - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -264,28 +273,32 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem { StringBuffer sb = new StringBuffer(200); sb.append("A wrapped simple problem based on "); sb.append(simProb.getClass().getName()); - sb.append(", Dimension : "); + sb.append(", Dimension : "); sb.append(simProb.getProblemDimension()); return sb.toString(); } - - /** This method allows the CommonJavaObjectEditorPanel to read the + + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override public String getName() { - return "SimpleProblemWrapper"; + return "SimpleProblemWrapper"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { - return "Wrapping simple problem implementations."; + return "Wrapping simple problem implementations."; } - + public String[] getGOEPropertyUpdateLinks() { - return new String[] {"globalInfo", "simpleProblem"}; + return new String[]{"globalInfo", "simpleProblem"}; } } diff --git a/src/eva2/optimization/problems/TF1Problem.java b/src/eva2/optimization/problems/TF1Problem.java index edd05690..7cdc4be9 100644 --- a/src/eva2/optimization/problems/TF1Problem.java +++ b/src/eva2/optimization/problems/TF1Problem.java @@ -10,6 +10,7 @@ import eva2.optimization.operator.paretofrontmetrics.InterfaceParetoFrontMetric; import eva2.optimization.population.Population; import eva2.optimization.strategies.InterfaceOptimizer; import eva2.tools.math.RNG; + import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; @@ -22,37 +23,37 @@ import java.util.ArrayList; * To change this template use File | Settings | File Templates. */ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implements java.io.Serializable { - protected int m_ProblemDimension = 30; - protected int m_OutputDimension = 2; - protected double m_Noise = 0.0; - protected double m_XOffSet = 0.0; - protected double m_YOffSet = 0.0; - protected boolean m_ApplyConstraints = false; + protected int m_ProblemDimension = 30; + protected int m_OutputDimension = 2; + protected double m_Noise = 0.0; + protected double m_XOffSet = 0.0; + protected double m_YOffSet = 0.0; + protected boolean m_ApplyConstraints = false; // transient private GraphPointSet mySet; - + public TF1Problem() { - super(1.); + super(1.); } - + public TF1Problem(double borderHigh) { - super(borderHigh); + super(borderHigh); } - + public TF1Problem(TF1Problem b) { //AbstractOptimizationProblem if (b.template != null) { - this.template = (AbstractEAIndividual)((AbstractEAIndividual)b.template).clone(); + this.template = (AbstractEAIndividual) ((AbstractEAIndividual) b.template).clone(); } //AbstractMultiObjectiveOptimizationProblem if (b.m_MOSOConverter != null) { - this.m_MOSOConverter = (InterfaceMOSOConverter)b.m_MOSOConverter.clone(); + this.m_MOSOConverter = (InterfaceMOSOConverter) b.m_MOSOConverter.clone(); } if (b.m_Metric != null) { - this.m_Metric = (InterfaceParetoFrontMetric)b.m_Metric.clone(); + this.m_Metric = (InterfaceParetoFrontMetric) b.m_Metric.clone(); } if (b.m_ParetoFront != null) { - this.m_ParetoFront = (Population)b.m_ParetoFront.clone(); + this.m_ParetoFront = (Population) b.m_ParetoFront.clone(); } if (b.m_Border != null) { this.m_Border = new double[b.m_Border.length][2]; @@ -64,28 +65,32 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem if (b.m_AreaConst4Parallelization != null) { this.m_AreaConst4Parallelization = new ArrayList(); for (int i = 0; i < b.m_AreaConst4Parallelization.size(); i++) { - this.m_AreaConst4Parallelization.add(((InterfaceConstraint)b.m_AreaConst4Parallelization.get(i)).clone()); + this.m_AreaConst4Parallelization.add(((InterfaceConstraint) b.m_AreaConst4Parallelization.get(i)).clone()); } } // TF1Problem this.m_ApplyConstraints = b.m_ApplyConstraints; this.m_ProblemDimension = b.m_ProblemDimension; - this.m_OutputDimension = b.m_OutputDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; + this.m_OutputDimension = b.m_OutputDimension; + this.m_Noise = b.m_Noise; + this.m_XOffSet = b.m_XOffSet; + this.m_YOffSet = b.m_YOffSet; } - /** This method returns a deep clone of the problem. - * @return the clone + /** + * This method returns a deep clone of the problem. + * + * @return the clone */ @Override public Object clone() { return (Object) new TF1Problem(this); } - /** This method inits a given population - * @param population The populations that is to be inited + /** + * This method inits a given population + * + * @param population The populations that is to be inited */ @Override public void initializePopulation(Population population) { @@ -93,32 +98,34 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem double[][] newRange = makeRange(); - ((InterfaceDataTypeDouble)this.template).setDoubleDataLength(this.m_ProblemDimension); - ((InterfaceDataTypeDouble)this.template).SetDoubleRange(newRange); - + ((InterfaceDataTypeDouble) this.template).setDoubleDataLength(this.m_ProblemDimension); + ((InterfaceDataTypeDouble) this.template).SetDoubleRange(newRange); + AbstractOptimizationProblem.defaultInitPopulation(population, template, this); } - - protected double[][] makeRange() { - return makeRange(0, 1); - } - - protected double[][] makeRange(double lower, double upper) { - double[][] newRange = new double[this.m_ProblemDimension][2]; + + protected double[][] makeRange() { + return makeRange(0, 1); + } + + protected double[][] makeRange(double lower, double upper) { + double[][] newRange = new double[this.m_ProblemDimension][2]; for (int i = 0; i < this.m_ProblemDimension; i++) { newRange[i][0] = lower; newRange[i][1] = upper; } - return newRange; - } + return newRange; + } - /** This method evaluate a single individual and sets the fitness values - * @param individual The individual that is to be evalutated + /** + * This method evaluate a single individual and sets the fitness values + * + * @param individual The individual that is to be evalutated */ @Override public void evaluate(AbstractEAIndividual individual) { - double[] x; - double[] fitness; + double[] x; + double[] fitness; x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); @@ -132,41 +139,45 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem fitness[i] += this.m_YOffSet; // set the fitness of the individual individual.SetFitness(i, fitness[i]); - } + } if (this.m_ApplyConstraints) { if (fitness[0] > 0.5) { - individual.addConstraintViolation(fitness[0]-0.5); + individual.addConstraintViolation(fitness[0] - 0.5); } if (x[1] > 0.1) { - individual.addConstraintViolation(x[1]-0.1); + individual.addConstraintViolation(x[1] - 0.1); } if (x[2] > 0.1) { - individual.addConstraintViolation(x[2]-0.1); + individual.addConstraintViolation(x[2] - 0.1); } if (x[3] > 0.1) { - individual.addConstraintViolation(x[3]-0.1); + individual.addConstraintViolation(x[3] - 0.1); } } individual.checkAreaConst4Parallelization(this.m_AreaConst4Parallelization); } - /** Ths method allows you to evaluate a simple bit string to determine the fitness - * @param x The n-dimensional input vector - * @return The m-dimensional output vector. + /** + * Ths method allows you to evaluate a simple bit string to determine the fitness + * + * @param x The n-dimensional input vector + * @return The m-dimensional output vector. */ public double[] doEvaluation(double[] x) { double[] result = new double[2]; - double g = 0; + double g = 0; - result[0] = x[0]; - g = this.g(x); - result[1] = g * this.h(result[0], g); + result[0] = x[0]; + g = this.g(x); + result[1] = g * this.h(result[0], g); return result; } - /** The g function - * @param x The decision variables. + /** + * The g function + * + * @param x The decision variables. * @return Objective variable. */ protected double g(double[] x) { @@ -175,29 +186,33 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem for (int i = 1; i < x.length; i++) { result += x[i]; } - result = result * 9/(x.length-1); + result = result * 9 / (x.length - 1); result += 1; return result; } - /** The h function - * @param x The decision variables. + /** + * The h function + * + * @param x The decision variables. * @return Objective variable. */ protected double h(double x, double y) { double result = 0; - result = 1 - Math.sqrt(Math.abs(x/y)); + result = 1 - Math.sqrt(Math.abs(x / y)); return result; } @Override public void drawAdditionalData(Plot plot, Population pop, int index) { - AbstractMultiObjectiveOptimizationProblem.drawWithConstraints(plot, pop, m_Border, index); - } + AbstractMultiObjectiveOptimizationProblem.drawWithConstraints(plot, pop, m_Border, index); + } - /** This method returns a string describing the optimization problem. - * @param opt The Optimizer that is used or had been used. + /** + * This method returns a string describing the optimization problem. + * + * @param opt The Optimizer that is used or had been used. * @return The description. */ @Override @@ -207,7 +222,7 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem result += "T1 Problem:\n"; result += "Here the individual codes a vector of real number x and T1(x)= x is to be minimized.\n"; result += "Parameters:\n"; - result += "Dimension : " + this.m_ProblemDimension +"\n"; + result += "Dimension : " + this.m_ProblemDimension + "\n"; result += "Noise level : " + this.m_Noise + "\n"; result += "Solution representation:\n"; //result += this.template.getSolutionRepresentationFor(); @@ -216,10 +231,10 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem public static void main(String[] args) { int points = 500; - String base = System.getProperty("user.dir"); - String FS = System.getProperty("file.separator"); - PropertyFilePath fileOutPath = PropertyFilePath.getFilePathFromResource("MOPReference"+FS+"T1_"+points+".txt"); - BufferedWriter writer = null; + String base = System.getProperty("user.dir"); + String FS = System.getProperty("file.separator"); + PropertyFilePath fileOutPath = PropertyFilePath.getFilePathFromResource("MOPReference" + FS + "T1_" + points + ".txt"); + BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(fileOutPath.getCompleteFilePath())); } catch (java.io.IOException ed) { @@ -227,29 +242,31 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem return; } TF1Problem problem = new TF1Problem(); - System.out.println("This method generates a reference set for the T1 problem with "+points+" sample points."); - double ub = 1, lb = 0; - double x1, x2; - String tmpStr; + System.out.println("This method generates a reference set for the T1 problem with " + points + " sample points."); + double ub = 1, lb = 0; + double x1, x2; + String tmpStr; tmpStr = "x1 \t x2"; - for (int i = 0; i < points+1; i++) { - x1 = (ub-lb)/((double)points) * i; + for (int i = 0; i < points + 1; i++) { + x1 = (ub - lb) / ((double) points) * i; x2 = problem.h(x1, 1); - tmpStr += "\n"+x1+"\t"+x2; + tmpStr += "\n" + x1 + "\t" + x2; } try { writer.write(tmpStr); writer.close(); } catch (java.io.IOException e) { - System.out.println("DAMM IOException "+e); + System.out.println("DAMM IOException " + e); } } /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ @Override @@ -257,16 +274,20 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem return "T1 Problem"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "T1 is to be minimized."; } - /** This method allows you to choose how much noise is to be added to the + /** + * This method allows you to choose how much noise is to be added to the * fitness. This can be used to make the optimization problem more difficult. - * @param noise The sigma for a gaussian random number. + * + * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { if (noise < 0) { @@ -274,48 +295,63 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem } this.m_Noise = noise; } + public double getNoise() { return this.m_Noise; } + public String noiseTipText() { return "Noise level on the fitness value."; } - /** This method allows you to set/get an offset for decision variables. - * @param XOffSet The offset for the decision variables. + /** + * This method allows you to set/get an offset for decision variables. + * + * @param XOffSet The offset for the decision variables. */ public void setXOffSet(double XOffSet) { this.m_XOffSet = XOffSet; } + public double getXOffSet() { return this.m_XOffSet; } + public String xOffSetTipText() { return "Choose an offset for the decision variable."; } - /** This method allows you to set/get the offset for the + /** + * This method allows you to set/get the offset for the * objective value. - * @param YOffSet The offset for the objective value. + * + * @param YOffSet The offset for the objective value. */ public void setYOffSet(double YOffSet) { this.m_YOffSet = YOffSet; } + public double getYOffSet() { return this.m_YOffSet; } + public String yOffSetTipText() { return "Choose an offset for the objective value."; } - /** This method allows you to set the input dimension of the problem. - * @param d The number of input dimensions + + /** + * This method allows you to set the input dimension of the problem. + * + * @param d The number of input dimensions */ public void setProblemDimension(int d) { this.m_ProblemDimension = d; } + public int getProblemDimension() { return this.m_ProblemDimension; } + public String problemDimensionTipText() { return "Length of the x vector at is to be optimized."; } @@ -338,29 +374,36 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem // return "Number of objective variables."; // } - /** This method allows you to choose the EA individual + /** + * This method allows you to choose the EA individual + * * @param indy The EAIndividual type */ public void setEAIndividual(InterfaceDataTypeDouble indy) { this.template = (AbstractEAIndividual) indy; } + public InterfaceDataTypeDouble getEAIndividual() { - return (InterfaceDataTypeDouble)this.template; + return (InterfaceDataTypeDouble) this.template; } - /** This method allows you to set a Multiobjective to + /** + * This method allows you to set a Multiobjective to * Singleobjective converter if you choose to. - * @param b The new MO2SO converter. + * + * @param b The new MO2SO converter. */ @Override public void setMOSOConverter(InterfaceMOSOConverter b) { this.m_MOSOConverter = b; this.m_MOSOConverter.setOutputDimension(this.m_OutputDimension); } + @Override public InterfaceMOSOConverter getMOSOConverter() { return this.m_MOSOConverter; } + @Override public String mOSOConverterTipText() { return "Choose a Multiobjective to Singleobjective converter."; @@ -379,19 +422,22 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem // return "Toggle application of constraint (works only for T1)."; // } - /** + /** * Since you can apply single objective optimization algorithms on * multi-objective problems, the problem needs a way to log the pareto- * front for such algorithms. This is especially the case for the * dynamically weighted fitness MOSO. - * @param pop The pareto-front archive. + * + * @param pop The pareto-front archive. */ public void setParetoFront(Population pop) { this.m_ParetoFront = pop; } + public Population getParetoFront() { return this.m_ParetoFront; } + public String paretoFrontTipText() { return "Choose the properties of the local log of the pareto-front."; } diff --git a/src/eva2/optimization/problems/WaitForEvARunnable.java b/src/eva2/optimization/problems/WaitForEvARunnable.java index 7ad57fb2..937f10ca 100644 --- a/src/eva2/optimization/problems/WaitForEvARunnable.java +++ b/src/eva2/optimization/problems/WaitForEvARunnable.java @@ -3,65 +3,66 @@ package eva2.optimization.problems; import eva2.OptimizerRunnable; import eva2.gui.BeanInspector; import eva2.optimization.individuals.AbstractEAIndividual; + import java.io.PrintWriter; import java.io.StringWriter; class WaitForEvARunnable implements Runnable { - OptimizerRunnable runnable; - MatlabProblem mp; + OptimizerRunnable runnable; + MatlabProblem mp; - public WaitForEvARunnable(OptimizerRunnable runnable, MatlabProblem mp) { - this.runnable = runnable; - this.mp = mp; - mp.log("Created WaitForEvARunnable " + this + "\n"); - } + public WaitForEvARunnable(OptimizerRunnable runnable, MatlabProblem mp) { + this.runnable = runnable; + this.mp = mp; + mp.log("Created WaitForEvARunnable " + this + "\n"); + } @Override - public void run() { - if (runnable != null) { - mp.log("\nStarting optimize runnable!\n"); - synchronized (runnable) { - try { - // whole optimization thread goes in here - new Thread(runnable).start(); - mp.log("Started optimize thread\n"); - runnable.wait(); - // wait for the runnable to finish - mp.log("runnable continues...\n"); - } catch (InterruptedException e) { - e.printStackTrace(); - mp.log("WaitForEvARunnable was interrupted with " + e.getMessage()); - } - } - try { - mp.log("runnable.getDoubleSolution: " + BeanInspector.toString(runnable.getDoubleSolution()) + "\n"); - mp.log("runnable.getIntegerSolution: " + BeanInspector.toString(runnable.getIntegerSolution()) + "\n"); - mp.log("getAllSols best: " + AbstractEAIndividual.getDefaultDataString(runnable.getGOParams().getOptimizer().getAllSolutions().getSolutions().getBestEAIndividual()) + "\n"); - mp.log("\n"); - // write results back to matlab - mp.exportResultToMatlab(runnable); - mp.exportResultPopulationToMatlab(runnable.getResultPopulation()); - mp.log("reported results.\n"); - mp.notifyFinished(); - mp.log("notified finish.\n"); - if (mp.verbosityLevel > 0) { - System.out.println("Optimization finished: " + mp.getInfoString()); - } - } catch (Exception e) { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - mp.log("error in callback: " + e.getMessage() + " " + sw.toString() + "\n"); - } - } else { - System.err.println("Invalid optimization call."); - mp.log("invalid call, no optimization started.\n"); - mp.exportResultToMatlab(null); - mp.exportResultPopulationToMatlab(null); - mp.log("notifying finish...\n"); - mp.notifyFinished(); - mp.log("notified finish.\n"); - } + public void run() { + if (runnable != null) { + mp.log("\nStarting optimize runnable!\n"); + synchronized (runnable) { + try { + // whole optimization thread goes in here + new Thread(runnable).start(); + mp.log("Started optimize thread\n"); + runnable.wait(); + // wait for the runnable to finish + mp.log("runnable continues...\n"); + } catch (InterruptedException e) { + e.printStackTrace(); + mp.log("WaitForEvARunnable was interrupted with " + e.getMessage()); + } + } + try { + mp.log("runnable.getDoubleSolution: " + BeanInspector.toString(runnable.getDoubleSolution()) + "\n"); + mp.log("runnable.getIntegerSolution: " + BeanInspector.toString(runnable.getIntegerSolution()) + "\n"); + mp.log("getAllSols best: " + AbstractEAIndividual.getDefaultDataString(runnable.getGOParams().getOptimizer().getAllSolutions().getSolutions().getBestEAIndividual()) + "\n"); + mp.log("\n"); + // write results back to matlab + mp.exportResultToMatlab(runnable); + mp.exportResultPopulationToMatlab(runnable.getResultPopulation()); + mp.log("reported results.\n"); + mp.notifyFinished(); + mp.log("notified finish.\n"); + if (mp.verbosityLevel > 0) { + System.out.println("Optimization finished: " + mp.getInfoString()); + } + } catch (Exception e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + mp.log("error in callback: " + e.getMessage() + " " + sw.toString() + "\n"); + } + } else { + System.err.println("Invalid optimization call."); + mp.log("invalid call, no optimization started.\n"); + mp.exportResultToMatlab(null); + mp.exportResultPopulationToMatlab(null); + mp.log("notifying finish...\n"); + mp.notifyFinished(); + mp.log("notified finish.\n"); + } - } + } } \ No newline at end of file diff --git a/src/eva2/optimization/problems/regression/InterfaceRegressionFunction.java b/src/eva2/optimization/problems/regression/InterfaceRegressionFunction.java index 2ffc9804..410074bd 100644 --- a/src/eva2/optimization/problems/regression/InterfaceRegressionFunction.java +++ b/src/eva2/optimization/problems/regression/InterfaceRegressionFunction.java @@ -9,13 +9,17 @@ package eva2.optimization.problems.regression; */ public interface InterfaceRegressionFunction { - /** This mehtod allows you to get a deep clone + /** + * This mehtod allows you to get a deep clone + * * @return The clone. */ public Object clone(); - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ public double evaluateFunction(double[] x); diff --git a/src/eva2/optimization/problems/regression/RFKoza_GPI_10_1.java b/src/eva2/optimization/problems/regression/RFKoza_GPI_10_1.java index 59855fca..e4b2eef7 100644 --- a/src/eva2/optimization/problems/regression/RFKoza_GPI_10_1.java +++ b/src/eva2/optimization/problems/regression/RFKoza_GPI_10_1.java @@ -22,15 +22,17 @@ public class RFKoza_GPI_10_1 implements InterfaceRegressionFunction, java.io.Ser return (Object) new RFKoza_GPI_10_1(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override public double evaluateFunction(double[] x) { double result = 0; for (int i = 0; i < x.length; i++) { - result += Math.cos(2*x[i]); + result += Math.cos(2 * x[i]); } return result; } @@ -38,15 +40,19 @@ public class RFKoza_GPI_10_1 implements InterfaceRegressionFunction, java.io.Ser /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Koza GP I 10.1"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/regression/RFKoza_GPI_10_2.java b/src/eva2/optimization/problems/regression/RFKoza_GPI_10_2.java index 777d73ba..a9675558 100644 --- a/src/eva2/optimization/problems/regression/RFKoza_GPI_10_2.java +++ b/src/eva2/optimization/problems/regression/RFKoza_GPI_10_2.java @@ -22,15 +22,17 @@ public class RFKoza_GPI_10_2 implements InterfaceRegressionFunction, java.io.Ser return (Object) new RFKoza_GPI_10_2(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override public double evaluateFunction(double[] x) { double result = 0; for (int i = 0; i < x.length; i++) { - result += 3.1416*x[i] + 2.718 * Math.pow(x[i], 2); + result += 3.1416 * x[i] + 2.718 * Math.pow(x[i], 2); } return result; } @@ -38,15 +40,19 @@ public class RFKoza_GPI_10_2 implements InterfaceRegressionFunction, java.io.Ser /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Koza GP I 10.2"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3.java b/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3.java index fc5d81cf..a1ecb1f0 100644 --- a/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3.java +++ b/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3.java @@ -22,15 +22,17 @@ public class RFKoza_GPI_7_3 implements InterfaceRegressionFunction, java.io.Seri return (Object) new RFKoza_GPI_7_3(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override public double evaluateFunction(double[] x) { double result = 0; for (int i = 0; i < x.length; i++) { - result += Math.pow(x[i], 4) + Math.pow(x[i], 3) + Math.pow(x[i], 2) + x[i]; + result += Math.pow(x[i], 4) + Math.pow(x[i], 3) + Math.pow(x[i], 2) + x[i]; } return result; } @@ -38,15 +40,19 @@ public class RFKoza_GPI_7_3 implements InterfaceRegressionFunction, java.io.Seri /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Koza GP I 7.3"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3_extended.java b/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3_extended.java index 3d821bc7..6f6a3c88 100644 --- a/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3_extended.java +++ b/src/eva2/optimization/problems/regression/RFKoza_GPI_7_3_extended.java @@ -22,15 +22,17 @@ public class RFKoza_GPI_7_3_extended implements InterfaceRegressionFunction, jav return (Object) new RFKoza_GPI_7_3_extended(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override public double evaluateFunction(double[] x) { double result = 0; for (int i = 0; i < x.length; i++) { - result += 0.12345*Math.pow(x[i], 4) + (Math.PI/4)*Math.pow(x[i], 3) + (Math.E/2)*Math.pow(x[i], 2) + 1.23456*Math.pow(x[i], 1); + result += 0.12345 * Math.pow(x[i], 4) + (Math.PI / 4) * Math.pow(x[i], 3) + (Math.E / 2) * Math.pow(x[i], 2) + 1.23456 * Math.pow(x[i], 1); } return result; } @@ -38,15 +40,19 @@ public class RFKoza_GPI_7_3_extended implements InterfaceRegressionFunction, jav /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Koza GP I 7.3"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/regression/RFRaidl_F1.java b/src/eva2/optimization/problems/regression/RFRaidl_F1.java index b73b087b..b2f77808 100644 --- a/src/eva2/optimization/problems/regression/RFRaidl_F1.java +++ b/src/eva2/optimization/problems/regression/RFRaidl_F1.java @@ -22,8 +22,10 @@ public class RFRaidl_F1 implements InterfaceRegressionFunction, java.io.Serializ return (Object) new RFRaidl_F1(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override @@ -38,15 +40,19 @@ public class RFRaidl_F1 implements InterfaceRegressionFunction, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Raidl F1"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/regression/RFRaidl_F2.java b/src/eva2/optimization/problems/regression/RFRaidl_F2.java index b45f85f1..83f8d5e2 100644 --- a/src/eva2/optimization/problems/regression/RFRaidl_F2.java +++ b/src/eva2/optimization/problems/regression/RFRaidl_F2.java @@ -22,15 +22,17 @@ public class RFRaidl_F2 implements InterfaceRegressionFunction, java.io.Serializ return (Object) new RFRaidl_F2(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override public double evaluateFunction(double[] x) { double result = 0; for (int i = 0; i < x.length; i++) { - result += Math.exp(x[i]/3)*Math.cos(3*x[i])/2; + result += Math.exp(x[i] / 3) * Math.cos(3 * x[i]) / 2; } return result; } @@ -38,15 +40,19 @@ public class RFRaidl_F2 implements InterfaceRegressionFunction, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Raidl F2"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/problems/regression/RFRaidl_F3.java b/src/eva2/optimization/problems/regression/RFRaidl_F3.java index b5019a7a..26af6926 100644 --- a/src/eva2/optimization/problems/regression/RFRaidl_F3.java +++ b/src/eva2/optimization/problems/regression/RFRaidl_F3.java @@ -22,15 +22,17 @@ public class RFRaidl_F3 implements InterfaceRegressionFunction, java.io.Serializ return (Object) new RFRaidl_F3(this); } - /** This method will return the y value for a given x vector - * @param x Input vector. + /** + * This method will return the y value for a given x vector + * + * @param x Input vector. * @return y the function result. */ @Override public double evaluateFunction(double[] x) { double result = 0; for (int i = 0; i < x.length; i++) { - result += Math.log(4+2*Math.sin(x[i]*Math.sin(8*x[i])))*Math.exp(Math.cos(3*x[i])); + result += Math.log(4 + 2 * Math.sin(x[i] * Math.sin(8 * x[i]))) * Math.exp(Math.cos(3 * x[i])); } return result; } @@ -38,15 +40,19 @@ public class RFRaidl_F3 implements InterfaceRegressionFunction, java.io.Serializ /********************************************************************************************************************** * These are for GUI */ - /** This method allows the CommonJavaObjectEditorPanel to read the + /** + * This method allows the CommonJavaObjectEditorPanel to read the * name to the current object. + * * @return The name. */ public String getName() { return "Raidl F3"; } - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { diff --git a/src/eva2/optimization/stat/EvAStatisticalEvaluationParams.java b/src/eva2/optimization/stat/EvAStatisticalEvaluationParams.java index e0c13464..1b99df8e 100644 --- a/src/eva2/optimization/stat/EvAStatisticalEvaluationParams.java +++ b/src/eva2/optimization/stat/EvAStatisticalEvaluationParams.java @@ -1,56 +1,62 @@ package eva2.optimization.stat; import eva2.tools.StringSelection; + import java.io.Serializable; import java.util.List; import javax.swing.JButton; public class EvAStatisticalEvaluationParams implements Serializable { - private StringSelection singleStats = new StringSelection(StatsOnSingleDataSetEnum.mean, StatsOnSingleDataSetEnum.getInfoStrings()); - private StringSelection twoSampledStats = new StringSelection(StatsOnTwoSampledDataEnum.tTestUneqLenEqVar, StatsOnTwoSampledDataEnum.getInfoStrings()); - private List additionalButtons = null; + private StringSelection singleStats = new StringSelection(StatsOnSingleDataSetEnum.mean, StatsOnSingleDataSetEnum.getInfoStrings()); + private StringSelection twoSampledStats = new StringSelection(StatsOnTwoSampledDataEnum.tTestUneqLenEqVar, StatsOnTwoSampledDataEnum.getInfoStrings()); + private List additionalButtons = null; - public void setGenericAdditionalButtons(List buts) { - this.additionalButtons = buts; - } - - public StringSelection getTwoSampledStats() { - return twoSampledStats; - } - public void setTwoSampledStats(StringSelection twoSStats) { - this.twoSampledStats = twoSStats; - } - public String twoSampledStatsTipText() { - return "Statistical tests on two-sampled data"; - } - - public StringSelection getOneSampledStats() { - return singleStats; - } - public void setOneSampledStats(StringSelection singleStats) { - this.singleStats = singleStats; - } - public String oneSampledStatsTipText() { - return "Statistical tests on one-sampled data"; - } - - public String getName() { - return "Statistical evaluation parameters"; - } - - public String globalInfo() { - return "Select statistical values to be calculated and tests to be performed."; - } - - public List getAdditionalButtons() { - return additionalButtons; - } - - public boolean withGenericOkButton() { - return false; - } - public boolean withGenericLoadSafeButtons() { - return false; - } + public void setGenericAdditionalButtons(List buts) { + this.additionalButtons = buts; + } + + public StringSelection getTwoSampledStats() { + return twoSampledStats; + } + + public void setTwoSampledStats(StringSelection twoSStats) { + this.twoSampledStats = twoSStats; + } + + public String twoSampledStatsTipText() { + return "Statistical tests on two-sampled data"; + } + + public StringSelection getOneSampledStats() { + return singleStats; + } + + public void setOneSampledStats(StringSelection singleStats) { + this.singleStats = singleStats; + } + + public String oneSampledStatsTipText() { + return "Statistical tests on one-sampled data"; + } + + public String getName() { + return "Statistical evaluation parameters"; + } + + public String globalInfo() { + return "Select statistical values to be calculated and tests to be performed."; + } + + public List getAdditionalButtons() { + return additionalButtons; + } + + public boolean withGenericOkButton() { + return false; + } + + public boolean withGenericLoadSafeButtons() { + return false; + } } diff --git a/src/eva2/optimization/stat/GenericStatistics.java b/src/eva2/optimization/stat/GenericStatistics.java index a08b0fed..3c4bafcd 100644 --- a/src/eva2/optimization/stat/GenericStatistics.java +++ b/src/eva2/optimization/stat/GenericStatistics.java @@ -9,9 +9,11 @@ package eva2.optimization.stat; * $Date: 2007-12-06 16:05:11 +0100 (Thu, 06 Dec 2007) $ * $Author: mkron $ */ + import eva2.gui.plot.DataViewer; import eva2.gui.plot.DataViewerInterface; import eva2.gui.plot.Graph; + import java.io.Serializable; import java.lang.reflect.Field; import java.util.logging.Logger; diff --git a/src/eva2/optimization/stat/GraphSelectionEnum.java b/src/eva2/optimization/stat/GraphSelectionEnum.java index f266a452..c70b4500 100644 --- a/src/eva2/optimization/stat/GraphSelectionEnum.java +++ b/src/eva2/optimization/stat/GraphSelectionEnum.java @@ -4,39 +4,38 @@ import eva2.tools.StringSelection; /** * An Enum to be used in the statistics classes for identifying data fields. - * - * @see AbstractStatistics - * @author mkron * + * @author mkron + * @see AbstractStatistics */ public enum GraphSelectionEnum { - // DONT change this order, or the relation to AbstractStatistics will be lost - currentBest, meanFit, currentWorst, runBest, currentBestFeasible, runBestFeasible, - avgEucPopDistance, maxEucPopDistance, avgPopMetricDist, maxPopMetricDist; - - private static String[] toolTips = { - "The current best fitness within the population", - "The mean fitness within the population", - "The current worst fitness within the population", - "The best fitness up to the current generation", - "The best feasible fitness within the population", - "The best feasible fitness up to the current generation", - "The average euclidean distance of individuals in the current population", - "The maximum euclidean distance of individuals in the current population", - "The average distance of individuals in the current population metric", - "The maximum distance of individuals in the current population metric", - }; - - public static String[] getInfoStrings() { - if (GraphSelectionEnum.values().length != toolTips.length) { - System.err.println("Error, mismatching length of info strings in GraphSelectionEnum"); - return null; - } else { - return toolTips; - } - } - -// public static boolean doPlotCurrentBest(StringSelection sel) { + // DONT change this order, or the relation to AbstractStatistics will be lost + currentBest, meanFit, currentWorst, runBest, currentBestFeasible, runBestFeasible, + avgEucPopDistance, maxEucPopDistance, avgPopMetricDist, maxPopMetricDist; + + private static String[] toolTips = { + "The current best fitness within the population", + "The mean fitness within the population", + "The current worst fitness within the population", + "The best fitness up to the current generation", + "The best feasible fitness within the population", + "The best feasible fitness up to the current generation", + "The average euclidean distance of individuals in the current population", + "The maximum euclidean distance of individuals in the current population", + "The average distance of individuals in the current population metric", + "The maximum distance of individuals in the current population metric", + }; + + public static String[] getInfoStrings() { + if (GraphSelectionEnum.values().length != toolTips.length) { + System.err.println("Error, mismatching length of info strings in GraphSelectionEnum"); + return null; + } else { + return toolTips; + } + } + + // public static boolean doPlotCurrentBest(StringSelection sel) { // return sel.isSelected(GraphSelectionEnum.currentBest.ordinal()); // } // @@ -44,14 +43,15 @@ public enum GraphSelectionEnum { // return sel.isSelected(GraphSelectionEnum.runBest.ordinal()); // } // - public static boolean doPlotWorst(StringSelection sel) { - return sel.isSelected(GraphSelectionEnum.currentWorst.ordinal()); - } - - public static boolean doPlotMean(StringSelection sel) { - return sel.isSelected(GraphSelectionEnum.meanFit.ordinal()); - } -// public static boolean doPlotCurrentBestFeasible(StringSelection sel) { + public static boolean doPlotWorst(StringSelection sel) { + return sel.isSelected(GraphSelectionEnum.currentWorst.ordinal()); + } + + public static boolean doPlotMean(StringSelection sel) { + return sel.isSelected(GraphSelectionEnum.meanFit.ordinal()); + } + + // public static boolean doPlotCurrentBestFeasible(StringSelection sel) { // return sel.isSelected(GraphSelectionEnum.currentBestFeasible.ordinal()); // } // @@ -59,19 +59,19 @@ public enum GraphSelectionEnum { // return sel.isSelected(GraphSelectionEnum.runBestFeasible.ordinal()); // } // - public static boolean doPlotAvgEucDist(StringSelection sel) { - return sel.isSelected(GraphSelectionEnum.avgEucPopDistance.ordinal()); - } - - public static boolean doPlotMaxEucDist(StringSelection sel) { - return sel.isSelected(GraphSelectionEnum.maxEucPopDistance.ordinal()); - } - - public static boolean doPlotAvgPopMetricDist(StringSelection sel) { - return sel.isSelected(GraphSelectionEnum.avgPopMetricDist.ordinal()); - } - - public static boolean doPlotMaxPopMetricDist(StringSelection sel) { - return sel.isSelected(GraphSelectionEnum.maxPopMetricDist.ordinal()); - } + public static boolean doPlotAvgEucDist(StringSelection sel) { + return sel.isSelected(GraphSelectionEnum.avgEucPopDistance.ordinal()); + } + + public static boolean doPlotMaxEucDist(StringSelection sel) { + return sel.isSelected(GraphSelectionEnum.maxEucPopDistance.ordinal()); + } + + public static boolean doPlotAvgPopMetricDist(StringSelection sel) { + return sel.isSelected(GraphSelectionEnum.avgPopMetricDist.ordinal()); + } + + public static boolean doPlotMaxPopMetricDist(StringSelection sel) { + return sel.isSelected(GraphSelectionEnum.maxPopMetricDist.ordinal()); + } } diff --git a/src/eva2/optimization/stat/InterfaceStatistics.java b/src/eva2/optimization/stat/InterfaceStatistics.java index e0960a7d..f48ed994 100644 --- a/src/eva2/optimization/stat/InterfaceStatistics.java +++ b/src/eva2/optimization/stat/InterfaceStatistics.java @@ -5,30 +5,44 @@ import eva2.optimization.population.PopulationInterface; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.optimization.strategies.InterfaceOptimizer; + import java.util.List; /** * */ public interface InterfaceStatistics { - /** - * Initialize statistics computations. - */ - void startOptPerformed(String InfoString,int runnumber, Object params, List informerList); // called from processor - /** - * Finalize statistics computations. - */ - void stopOptPerformed(boolean normal, String stopMessage); // called from processor - void addDataListener(InterfaceStatisticsListener listener); - boolean removeDataListener(InterfaceStatisticsListener listener); - void addTextListener(InterfaceTextListener listener); - boolean removeTextListener(InterfaceTextListener listener); - void printToTextListener(String s); - void createNextGenerationPerformed(PopulationInterface Pop, InterfaceOptimizer opt, List informerList); - void createNextGenerationPerformed(double[] bestfit,double[] worstfit,int calls); - InterfaceStatisticsParameter getStatisticsParameter(); // called from moduleadapter - IndividualInterface getRunBestSolution(); // return the best fitness of the last run (may not be equal to the last population) - IndividualInterface getBestSolution(); // returns the best overall solution - double[] getBestFitness(); // returns the best overall fitness - void postProcessingPerformed(Population resultPop); // called from processor + /** + * Initialize statistics computations. + */ + void startOptPerformed(String InfoString, int runnumber, Object params, List informerList); // called from processor + + /** + * Finalize statistics computations. + */ + void stopOptPerformed(boolean normal, String stopMessage); // called from processor + + void addDataListener(InterfaceStatisticsListener listener); + + boolean removeDataListener(InterfaceStatisticsListener listener); + + void addTextListener(InterfaceTextListener listener); + + boolean removeTextListener(InterfaceTextListener listener); + + void printToTextListener(String s); + + void createNextGenerationPerformed(PopulationInterface Pop, InterfaceOptimizer opt, List informerList); + + void createNextGenerationPerformed(double[] bestfit, double[] worstfit, int calls); + + InterfaceStatisticsParameter getStatisticsParameter(); // called from moduleadapter + + IndividualInterface getRunBestSolution(); // return the best fitness of the last run (may not be equal to the last population) + + IndividualInterface getBestSolution(); // returns the best overall solution + + double[] getBestFitness(); // returns the best overall fitness + + void postProcessingPerformed(Population resultPop); // called from processor } \ No newline at end of file diff --git a/src/eva2/optimization/stat/InterfaceStatisticsListener.java b/src/eva2/optimization/stat/InterfaceStatisticsListener.java index ce90ec69..258ae573 100644 --- a/src/eva2/optimization/stat/InterfaceStatisticsListener.java +++ b/src/eva2/optimization/stat/InterfaceStatisticsListener.java @@ -3,58 +3,57 @@ package eva2.optimization.stat; import java.util.List; /** - * An interface to listen to statistical data of an optimization run. - * + * An interface to listen to statistical data of an optimization run. + * + * @author mkron * @see AbstractStatistics * @see InterfaceStatisticsParameter - * @author mkron - * */ public interface InterfaceStatisticsListener { - /** - * Method called by the statistics class with the current data header, raw Objects and - * Double values (as far as the raw objects could be converted to double - otherwise null). - * - * @param header - * @param statObjects - * @param statDoubles - */ - public void notifyGenerationPerformed(String[] header, Object[] statObjects, Double[] statDoubles); - - /** - * Method called at the start of a single run. - * - * @param runNumber the number of the new run, starting with 0 - * @param plannedMultiRuns the number of planned multi-runs - * @param header field names of the data - * @param metaInfo additional meta information on the data fields - */ - public void notifyRunStarted(int runNumber, int plannedMultiRuns, String[] header, String[] metaInfo); + /** + * Method called by the statistics class with the current data header, raw Objects and + * Double values (as far as the raw objects could be converted to double - otherwise null). + * + * @param header + * @param statObjects + * @param statDoubles + */ + public void notifyGenerationPerformed(String[] header, Object[] statObjects, Double[] statDoubles); - /** - * Method called at the end of a single run. - * - * @param runsPerformed the number of runs performed - * @param completedLastRun true, if the last run was stopped normally, otherwise false, e.g. indicating a user break - */ - public void notifyRunStopped(int runsPerformed, boolean completedLastRun); - - /** - * Receive the list of last data lines for a set of multiruns. The data list may be null if no runs were - * performed or no data was collected. The method will only be called if a multi-run experiment was performed. - * - * @see InterfaceStatisticsParameter - * @see AbstractStatistics - * @param header - * @param multiRunFinalObjectData - */ - public void finalMultiRunResults(String[] header, List multiRunFinalObjectData); - - /** - * Called after the job is finished. Return true if the listener should be removed after this multi-run. - * - * @param header - * @param multiRunFinalObjectData - */ - public boolean notifyMultiRunFinished(String[] header, List multiRunFinalObjectData); + /** + * Method called at the start of a single run. + * + * @param runNumber the number of the new run, starting with 0 + * @param plannedMultiRuns the number of planned multi-runs + * @param header field names of the data + * @param metaInfo additional meta information on the data fields + */ + public void notifyRunStarted(int runNumber, int plannedMultiRuns, String[] header, String[] metaInfo); + + /** + * Method called at the end of a single run. + * + * @param runsPerformed the number of runs performed + * @param completedLastRun true, if the last run was stopped normally, otherwise false, e.g. indicating a user break + */ + public void notifyRunStopped(int runsPerformed, boolean completedLastRun); + + /** + * Receive the list of last data lines for a set of multiruns. The data list may be null if no runs were + * performed or no data was collected. The method will only be called if a multi-run experiment was performed. + * + * @param header + * @param multiRunFinalObjectData + * @see InterfaceStatisticsParameter + * @see AbstractStatistics + */ + public void finalMultiRunResults(String[] header, List multiRunFinalObjectData); + + /** + * Called after the job is finished. Return true if the listener should be removed after this multi-run. + * + * @param header + * @param multiRunFinalObjectData + */ + public boolean notifyMultiRunFinished(String[] header, List multiRunFinalObjectData); } diff --git a/src/eva2/optimization/stat/InterfaceStatisticsParameter.java b/src/eva2/optimization/stat/InterfaceStatisticsParameter.java index da160dbe..a7cff48d 100644 --- a/src/eva2/optimization/stat/InterfaceStatisticsParameter.java +++ b/src/eva2/optimization/stat/InterfaceStatisticsParameter.java @@ -9,48 +9,60 @@ import eva2.tools.StringSelection; * @see StatsParameter */ public interface InterfaceStatisticsParameter { - String getName(); - void saveInstance(); - void setMultiRuns(int x); - int getMultiRuns(); - String multiRunsTipText(); + String getName(); - - /** - * Use averaged graph for multi-run plots or not. - * - * @return If an average graph is used or not - */ - boolean getUseStatPlot(); - - /** - * Activate averaged graph for multi-run plots. - * - * @param x If averaged graph should be activated. - */ - void setUseStatPlot(boolean x); - - StringSelection getFieldSelection(); - void setFieldSelection(StringSelection v); - - String getResultFilePrefix(); - void setResultFilePrefix(String x); - - void setConvergenceRateThreshold(double x); - double getConvergenceRateThreshold(); + void saveInstance(); - void setShowTextOutput(boolean show); - boolean isShowTextOutput(); - - boolean isOutputAllFieldsAsText(); - void setOutputAllFieldsAsText(boolean bShowFullText); - - void setOutputVerbosity(SelectedTag sTag); - SelectedTag getOutputVerbosity(); - - int getOutputVerbosityK(); - void setOutputVerbosityK(int k); - - void setOutputTo(SelectedTag sTag); - SelectedTag getOutputTo(); + void setMultiRuns(int x); + + int getMultiRuns(); + + String multiRunsTipText(); + + + /** + * Use averaged graph for multi-run plots or not. + * + * @return If an average graph is used or not + */ + boolean getUseStatPlot(); + + /** + * Activate averaged graph for multi-run plots. + * + * @param x If averaged graph should be activated. + */ + void setUseStatPlot(boolean x); + + StringSelection getFieldSelection(); + + void setFieldSelection(StringSelection v); + + String getResultFilePrefix(); + + void setResultFilePrefix(String x); + + void setConvergenceRateThreshold(double x); + + double getConvergenceRateThreshold(); + + void setShowTextOutput(boolean show); + + boolean isShowTextOutput(); + + boolean isOutputAllFieldsAsText(); + + void setOutputAllFieldsAsText(boolean bShowFullText); + + void setOutputVerbosity(SelectedTag sTag); + + SelectedTag getOutputVerbosity(); + + int getOutputVerbosityK(); + + void setOutputVerbosityK(int k); + + void setOutputTo(SelectedTag sTag); + + SelectedTag getOutputTo(); } \ No newline at end of file diff --git a/src/eva2/optimization/stat/InterfaceTextListener.java b/src/eva2/optimization/stat/InterfaceTextListener.java index e2e96b28..00d33dc9 100644 --- a/src/eva2/optimization/stat/InterfaceTextListener.java +++ b/src/eva2/optimization/stat/InterfaceTextListener.java @@ -2,11 +2,11 @@ package eva2.optimization.stat; /** * A very simple interface class to receive raw String data. - * - * @author mkron * + * @author mkron */ public interface InterfaceTextListener { - public void print(String str); - public void println(String str); + public void print(String str); + + public void println(String str); } diff --git a/src/eva2/optimization/stat/MovingAverage.java b/src/eva2/optimization/stat/MovingAverage.java index 799909cb..273bb6a6 100644 --- a/src/eva2/optimization/stat/MovingAverage.java +++ b/src/eva2/optimization/stat/MovingAverage.java @@ -5,60 +5,65 @@ package eva2.optimization.stat; * */ public class MovingAverage { - private int m_size = 0; - private int m_index = 0; - private double m_Average; - private double[] m_array; - private boolean m_overflow = false; - /** - * - */ - public MovingAverage(int size) { - m_size = size; - m_array = new double[size]; - } - /** - * - */ - private MovingAverage(MovingAverage Source) { - m_size = Source.m_size; - m_index = Source.m_index; - m_Average = Source.m_Average; - m_array = (double[])Source.m_array.clone(); - m_overflow = Source.m_overflow; - } - /** - * - */ - public MovingAverage getClone() { - return new MovingAverage(this); - } - /** - * - */ - public void add (double value) { - m_array[m_index] = value; - m_index++; - if (m_index==m_size) { - m_index=0; - m_overflow = true; + private int m_size = 0; + private int m_index = 0; + private double m_Average; + private double[] m_array; + private boolean m_overflow = false; + + /** + * + */ + public MovingAverage(int size) { + m_size = size; + m_array = new double[size]; } - // - m_Average = 0; - int tail = m_index; - //if (m_overflow=true) - if (m_overflow) { - tail = m_size; - } - for (int i=0;i * A job contains data fields of a multi-run experiment and header strings describing the data. - * - * @author mkron * + * @author mkron */ public class OptimizationJob implements Serializable, InterfaceStatisticsListener { - private static final boolean TRACE = false; - - private InterfaceOptimizationParameters params = null; - private String[] fieldHeaders = null; - private List multiRunFinalObjectData = null; - private int jobID=0; - private static int jobIDCounter=0; - private int numRuns = 0; - private boolean lastRunIncompl = false; -// private boolean jobFinished = false; - private StateEnum state = StateEnum.idle; - - private enum StateEnum { running, idle, complete, incomplete}; - - public OptimizationJob() { - jobID=jobIDCounter; - jobIDCounter++; - } - - public OptimizationJob(InterfaceOptimizationParameters params, InterfaceStatistics sts) { - this(); - this.params = params; - if (sts instanceof AbstractStatistics) { - fieldHeaders=((AbstractStatistics)sts).getCurrentFieldHeaders(); - } - sts.addDataListener(this); - } - - /** - * Clear the job by resetting its state and clearing all data (which will be lost!). - * The parameters of course remain. - */ - public void resetJob() { - numRuns = 0; - state=StateEnum.idle; - lastRunIncompl=false; + private static final boolean TRACE = false; + + private InterfaceOptimizationParameters params = null; + private String[] fieldHeaders = null; + private List multiRunFinalObjectData = null; + private int jobID = 0; + private static int jobIDCounter = 0; + private int numRuns = 0; + private boolean lastRunIncompl = false; + // private boolean jobFinished = false; + private StateEnum state = StateEnum.idle; + + private enum StateEnum {running, idle, complete, incomplete} + + ; + + public OptimizationJob() { + jobID = jobIDCounter; + jobIDCounter++; + } + + public OptimizationJob(InterfaceOptimizationParameters params, InterfaceStatistics sts) { + this(); + this.params = params; + if (sts instanceof AbstractStatistics) { + fieldHeaders = ((AbstractStatistics) sts).getCurrentFieldHeaders(); + } + sts.addDataListener(this); + } + + /** + * Clear the job by resetting its state and clearing all data (which will be lost!). + * The parameters of course remain. + */ + public void resetJob() { + numRuns = 0; + state = StateEnum.idle; + lastRunIncompl = false; // jobFinished=false; - fieldHeaders=null; - multiRunFinalObjectData=null; - } - - public InterfaceOptimizationParameters getParams() { - return params; - } + fieldHeaders = null; + multiRunFinalObjectData = null; + } - /** - * Set the GO parameters for this instance. - * - * @param params - */ - public void setParams(InterfaceOptimizationParameters params) { - // how should this be treated? In case the run is already finished, changing - // the parameters will be evil, so avoid that case. - if (state==StateEnum.complete) { - System.err.println("Warning, ignoring changed parameters for finished job!"); - } else { - this.params = params; - } - } + public InterfaceOptimizationParameters getParams() { + return params; + } - public String getName() { - if (params==null) { - return "Invalid Job ("+jobID+")"; - } - else { - String name=getStateTag(); - name = name+" Job ("+jobID+"), "; // +params.getName(); - name=name+params.getOptimizer().getName()+"/"+params.getProblem().getName(); + /** + * Set the GO parameters for this instance. + * + * @param params + */ + public void setParams(InterfaceOptimizationParameters params) { + // how should this be treated? In case the run is already finished, changing + // the parameters will be evil, so avoid that case. + if (state == StateEnum.complete) { + System.err.println("Warning, ignoring changed parameters for finished job!"); + } else { + this.params = params; + } + } + + public String getName() { + if (params == null) { + return "Invalid Job (" + jobID + ")"; + } else { + String name = getStateTag(); + name = name + " Job (" + jobID + "), "; // +params.getName(); + name = name + params.getOptimizer().getName() + "/" + params.getProblem().getName(); // name=name+( (onlineData==null) ? ", empty" : (onlineData.size()+" records")); - name += (", " + numRuns + " runs"); - if (fieldHeaders!=null) { - name += (", " + fieldHeaders.length + " fields"); - } + name += (", " + numRuns + " runs"); + if (fieldHeaders != null) { + name += (", " + fieldHeaders.length + " fields"); + } // if (jobFinished) name=name+", finished"; // if (lastRunIncompl) name=name+", incomplete"; - return name; - } - } - - private String getStateTag() { - String tag = null; - switch(state) { - case complete: tag="*"; break; - case incomplete: tag="?"; break; - case idle: tag="."; break; - case running: tag="!"; break; - } - - tag = tag+numRuns+" "; - return tag; + return name; + } + } + + private String getStateTag() { + String tag = null; + switch (state) { + case complete: + tag = "*"; + break; + case incomplete: + tag = "?"; + break; + case idle: + tag = "."; + break; + case running: + tag = "!"; + break; + } + + tag = tag + numRuns + " "; + return tag; // if (isFinishedAndComplete()) return "*"; // else if (jobFinished && !lastRunIncompl) return "?"; // else if (!jobFinished && lastRunIncompl) return "-"; @@ -115,168 +124,166 @@ public class OptimizationJob implements Serializable, InterfaceStatisticsListene // System.err.println("Invalid state of job " + this.toString()); // return "?"; // } - } + } - public String globalInfo() { - return "Job: " + BeanInspector.niceToString(params); - } + public String globalInfo() { + return "Job: " + BeanInspector.niceToString(params); + } - public boolean isFinishedAndComplete() { + public boolean isFinishedAndComplete() { // return (jobFinished && !lastRunIncompl); - return (state==StateEnum.complete) && !lastRunIncompl; - } - - public String[] getFieldHeaders() { - return fieldHeaders; - } - - public List getJobData() { - return multiRunFinalObjectData; - } - - public InterfaceOptimizationParameters getGOParams() { - return params; - } - - @Override - public void finalMultiRunResults(String[] header, - List multiRunFinalObjDat) { - fieldHeaders=header; - multiRunFinalObjectData = multiRunFinalObjDat; - } + return (state == StateEnum.complete) && !lastRunIncompl; + } + + public String[] getFieldHeaders() { + return fieldHeaders; + } + + public List getJobData() { + return multiRunFinalObjectData; + } + + public InterfaceOptimizationParameters getGOParams() { + return params; + } @Override - public void notifyGenerationPerformed(String[] header, - Object[] statObjects, Double[] statDoubles) { - fieldHeaders=header; - if (state!=StateEnum.running) { - throw new RuntimeException("Sent data to job with invalid state!"); - } + public void finalMultiRunResults(String[] header, + List multiRunFinalObjDat) { + fieldHeaders = header; + multiRunFinalObjectData = multiRunFinalObjDat; + } + + @Override + public void notifyGenerationPerformed(String[] header, + Object[] statObjects, Double[] statDoubles) { + fieldHeaders = header; + if (state != StateEnum.running) { + throw new RuntimeException("Sent data to job with invalid state!"); + } // if (onlineData==null) onlineData = new ArrayList(10); // onlineData.add(statObjects); - } + } @Override - public void notifyRunStarted(int runNumber, int plannedMultiRuns, - String[] header, String[] metaInfo) { - state=StateEnum.running; + public void notifyRunStarted(int runNumber, int plannedMultiRuns, + String[] header, String[] metaInfo) { + state = StateEnum.running; // onlineData = null; // multiRunFinalObjectData = null; - } + } @Override - public void notifyRunStopped(int runsPerformed, boolean completedLastRun) { - numRuns=runsPerformed; - lastRunIncompl = !completedLastRun; - if (TRACE) { - System.out.println("OptimizationJob.notifyRunStopped, " + runsPerformed + " " + completedLastRun); - } - } - + public void notifyRunStopped(int runsPerformed, boolean completedLastRun) { + numRuns = runsPerformed; + lastRunIncompl = !completedLastRun; + if (TRACE) { + System.out.println("OptimizationJob.notifyRunStopped, " + runsPerformed + " " + completedLastRun); + } + } + @Override - public boolean notifyMultiRunFinished(String[] header, List multiRunFinalObjDat) { - fieldHeaders=header; - multiRunFinalObjectData = multiRunFinalObjDat; - if (lastRunIncompl) { - state=StateEnum.incomplete; - } - else { - state=StateEnum.complete; - } + public boolean notifyMultiRunFinished(String[] header, List multiRunFinalObjDat) { + fieldHeaders = header; + multiRunFinalObjectData = multiRunFinalObjDat; + if (lastRunIncompl) { + state = StateEnum.incomplete; + } else { + state = StateEnum.complete; + } // jobFinished=true; - if (TRACE) { - System.out.println("multi run finished!"); - } - return true; - } + if (TRACE) { + System.out.println("multi run finished!"); + } + return true; + } - /** - * Retrieve the index of a data field within the data lines. - * Returns -1 if the field has not been found. - * - * @param field - * @return - */ - public int getFieldIndex(String field) { - if (fieldHeaders!=null) { - for (int i=0; i=0) { - double[] data = new double[getNumRuns()]; - for (int i=0; i= 0) { + double[] data = new double[getNumRuns()]; + for (int i = 0; i < getNumRuns(); i++) { + Object o = multiRunFinalObjectData.get(i)[index]; + try { + if ((o instanceof Double)) { + data[i] = (Double) o; + } else { + data[i] = Double.parseDouble(o + ""); + } + } catch (Exception e) { + return null; + } } - } - - /** - * Retrieve a single column of data indicated by a field name. If the field is unknown - * or there is no data, null is returned. - * - * @param field - * @return - */ - public Object[] getDataColumn(String field) { - int index = getFieldIndex(field); - if (index>=0) { - Object[] data = new Object[getNumRuns()]; - for (int i=0; i= 0) { + Object[] data = new Object[getNumRuns()]; + for (int i = 0; i < getNumRuns(); i++) { + data[i] = multiRunFinalObjectData.get(i)[index]; } - return newSel; - } + return data; + } else { + return null; + } + } + + public StringSelection getFieldSelection(StringSelection curSelection) { + StringSelection newSel = (StringSelection) curSelection.clone(); + + curSelection.setAllSelectionStates(false); + if (fieldHeaders != null) { + for (String field : fieldHeaders) { + curSelection.setSelected(field, true); + } + } else { + System.err.println("Warning, empty field selection in job " + this); + } + return newSel; + } } \ No newline at end of file diff --git a/src/eva2/optimization/stat/OptimizationJobList.java b/src/eva2/optimization/stat/OptimizationJobList.java index dd9e4561..0b31e0c9 100644 --- a/src/eva2/optimization/stat/OptimizationJobList.java +++ b/src/eva2/optimization/stat/OptimizationJobList.java @@ -10,6 +10,7 @@ import eva2.optimization.modules.AbstractModuleAdapter; import eva2.optimization.modules.GenericModuleAdapter; import eva2.optimization.modules.ModuleAdapter; import eva2.tools.Serializer; + import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -28,7 +29,6 @@ import javax.swing.JOptionPane; * statistical data. * * @author mkron - * */ public class OptimizationJobList extends PropertySelectableList implements Serializable, InterfaceTextListener { diff --git a/src/eva2/optimization/stat/StatisticsDummy.java b/src/eva2/optimization/stat/StatisticsDummy.java index 3521bba7..859730f8 100644 --- a/src/eva2/optimization/stat/StatisticsDummy.java +++ b/src/eva2/optimization/stat/StatisticsDummy.java @@ -6,128 +6,131 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.optimization.strategies.InterfaceOptimizer; + import java.util.List; /** * This may be given to a Processor if no further stats are required. It speeds up * optimization especially with small populations (e.g. HC as local search operator). - * - * @author mkron * + * @author mkron */ public class StatisticsDummy implements InterfaceStatistics, InterfaceTextListener { - boolean consoleOut = false; - StatisticsParameter sParams = null; - AbstractEAIndividual bestCurrentIndividual, bestRunIndy, bestIndividualAllover; - - public StatisticsDummy() { - bestIndividualAllover = null; - sParams = new StatisticsParameter(); - sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE); - } - - public StatisticsDummy(boolean doConsoleOut) { - bestIndividualAllover = null; - sParams = new StatisticsParameter(); - sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE); - consoleOut = doConsoleOut; - } - - @Override - public void addTextListener(InterfaceTextListener listener) { - System.err.println("addTextListener not provided!"); - } + boolean consoleOut = false; + StatisticsParameter sParams = null; + AbstractEAIndividual bestCurrentIndividual, bestRunIndy, bestIndividualAllover; + + public StatisticsDummy() { + bestIndividualAllover = null; + sParams = new StatisticsParameter(); + sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE); + } + + public StatisticsDummy(boolean doConsoleOut) { + bestIndividualAllover = null; + sParams = new StatisticsParameter(); + sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE); + consoleOut = doConsoleOut; + } @Override - public void createNextGenerationPerformed(PopulationInterface pop, InterfaceOptimizer opt, - List informerList) { - bestCurrentIndividual = (AbstractEAIndividual)pop.getBestIndividual(); - if ((bestIndividualAllover == null) || (AbstractStatistics.secondIsBetter(bestIndividualAllover, bestCurrentIndividual))) { - bestIndividualAllover = bestCurrentIndividual; - } - if ((bestIndividualAllover == null) || (AbstractStatistics.secondIsBetter(bestIndividualAllover, bestCurrentIndividual))) { - bestIndividualAllover = bestCurrentIndividual; - } - } + public void addTextListener(InterfaceTextListener listener) { + System.err.println("addTextListener not provided!"); + } @Override - public void createNextGenerationPerformed(double[] bestfit, - double[] worstfit, int calls) { - } + public void createNextGenerationPerformed(PopulationInterface pop, InterfaceOptimizer opt, + List informerList) { + bestCurrentIndividual = (AbstractEAIndividual) pop.getBestIndividual(); + if ((bestIndividualAllover == null) || (AbstractStatistics.secondIsBetter(bestIndividualAllover, bestCurrentIndividual))) { + bestIndividualAllover = bestCurrentIndividual; + } + if ((bestIndividualAllover == null) || (AbstractStatistics.secondIsBetter(bestIndividualAllover, bestCurrentIndividual))) { + bestIndividualAllover = bestCurrentIndividual; + } + } @Override - public double[] getBestFitness() { - if (bestIndividualAllover != null) { - return bestCurrentIndividual.getFitness(); - } - else { - return null; - } - } + public void createNextGenerationPerformed(double[] bestfit, + double[] worstfit, int calls) { + } @Override - public IndividualInterface getBestSolution() { - return bestIndividualAllover; - } - - @Override - public IndividualInterface getRunBestSolution() { - return bestRunIndy; - } - - @Override - public InterfaceStatisticsParameter getStatisticsParameter() { - return sParams; - } + public double[] getBestFitness() { + if (bestIndividualAllover != null) { + return bestCurrentIndividual.getFitness(); + } else { + return null; + } + } @Override - public void printToTextListener(String s) { - if (consoleOut) { - System.out.println(s); - } - } + public IndividualInterface getBestSolution() { + return bestIndividualAllover; + } @Override - public boolean removeTextListener(InterfaceTextListener listener) { - System.err.println("removeTextListener not provided!"); - return false; - } + public IndividualInterface getRunBestSolution() { + return bestRunIndy; + } @Override - public void startOptPerformed(String InfoString, int runnumber, - Object params, List informerList) { - if (runnumber==0) { - bestIndividualAllover = null; - } - bestRunIndy = null; - } + public InterfaceStatisticsParameter getStatisticsParameter() { + return sParams; + } @Override - public void stopOptPerformed(boolean normal, String stopMessage) {} - @Override - public void postProcessingPerformed(Population resultPop) {} - - @Override - public void print(String str) { - if (consoleOut) { - System.out.print(str); - } - } - @Override - public void println(String str) { - if (consoleOut) { - System.out.println(str); - } - } + public void printToTextListener(String s) { + if (consoleOut) { + System.out.println(s); + } + } @Override - public void addDataListener(InterfaceStatisticsListener l) { - System.err.println("addDataListener not provided!"); - } - + public boolean removeTextListener(InterfaceTextListener listener) { + System.err.println("removeTextListener not provided!"); + return false; + } + @Override - public boolean removeDataListener(InterfaceStatisticsListener l) { - System.err.println("removeDataListener not provided!"); - return false; - } + public void startOptPerformed(String InfoString, int runnumber, + Object params, List informerList) { + if (runnumber == 0) { + bestIndividualAllover = null; + } + bestRunIndy = null; + } + + @Override + public void stopOptPerformed(boolean normal, String stopMessage) { + } + + @Override + public void postProcessingPerformed(Population resultPop) { + } + + @Override + public void print(String str) { + if (consoleOut) { + System.out.print(str); + } + } + + @Override + public void println(String str) { + if (consoleOut) { + System.out.println(str); + } + } + + @Override + public void addDataListener(InterfaceStatisticsListener l) { + System.err.println("addDataListener not provided!"); + } + + @Override + public boolean removeDataListener(InterfaceStatisticsListener l) { + System.err.println("removeDataListener not provided!"); + return false; + } } diff --git a/src/eva2/optimization/stat/StatisticsParameter.java b/src/eva2/optimization/stat/StatisticsParameter.java index ddcff424..2adafc4e 100644 --- a/src/eva2/optimization/stat/StatisticsParameter.java +++ b/src/eva2/optimization/stat/StatisticsParameter.java @@ -8,6 +8,7 @@ import eva2.tools.EVAERROR; import eva2.tools.SelectedTag; import eva2.tools.Serializer; import eva2.tools.StringSelection; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -24,9 +25,9 @@ import java.util.logging.Logger; * Data entries can be selected using a StringSelection instance. * There is a switch called "output full data as text" which will be interpreted by AbstractStatistics showing * all or only the selected entities. - * - * @see AbstractStatistics + * * @author mkron + * @see AbstractStatistics */ public class StatisticsParameter implements InterfaceStatisticsParameter, InterfaceNotifyOnInformers, Serializable { private static final long serialVersionUID = -8681061379203108390L; @@ -149,7 +150,7 @@ public class StatisticsParameter implements InterfaceStatisticsParameter, Interf public static String globalInfo() { return "Configure statistics and output of the optimization run. Changes to the data selection state will not take effect during a run."; } - + /** * */ @@ -173,6 +174,7 @@ public class StatisticsParameter implements InterfaceStatisticsParameter, Interf public String multiRunsTipText() { return "Number of independent optimization runs to evaluate."; } + /** * */ @@ -236,7 +238,7 @@ public class StatisticsParameter implements InterfaceStatisticsParameter, Interf return outputTo.getSelectedTagID() > 0; } -// /** + // /** // * // */ // public String resultFileNameTipText() { @@ -247,7 +249,6 @@ public class StatisticsParameter implements InterfaceStatisticsParameter, Interf } /** - * * @param x */ @Override diff --git a/src/eva2/optimization/stat/StatisticsStandalone.java b/src/eva2/optimization/stat/StatisticsStandalone.java index f7e744d9..6ee2e23a 100644 --- a/src/eva2/optimization/stat/StatisticsStandalone.java +++ b/src/eva2/optimization/stat/StatisticsStandalone.java @@ -13,8 +13,10 @@ package eva2.optimization.stat; /*==========================================================================* * IMPORTS *==========================================================================*/ + import eva2.optimization.population.PopulationInterface; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; + import java.io.Serializable; import java.net.InetAddress; import java.util.ArrayList; @@ -23,22 +25,22 @@ import java.util.List; /** * This simple statistics implementation can collect all Object data available during runs. * Be aware that the memory requirements can be excessive depending on the data produced by - * the additional informers, and depending on the selected fields to be collected. + * the additional informers, and depending on the selected fields to be collected. * Therefore, the default is not to log the data but just print it using the super class. - * + * * @see InterfaceAdditionalPopulationInformer * @see AbstractStatistics */ public class StatisticsStandalone extends AbstractStatistics implements InterfaceStatistics, Serializable { - private static final long serialVersionUID = -8451652609212653368L; + private static final long serialVersionUID = -8451652609212653368L; - private static String m_MyHostName = "unknown"; + private static String m_MyHostName = "unknown"; + + // private String m_InfoString; + private ArrayList> m_ResultData = null; + private ArrayList m_ResultHeaderStrings = null; + private boolean collectData = false; -// private String m_InfoString; - private ArrayList> m_ResultData = null; - private ArrayList m_ResultHeaderStrings = null; - private boolean collectData = false; - // private boolean m_useMedian = false; // private double m_MeanFinalFitness; @@ -46,73 +48,72 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac // private double[] m_LastBestCurrentFit; // private double m_FitnessMedianofALL; - public StatisticsStandalone(InterfaceStatisticsParameter statParams) { - super(); - m_StatsParams = statParams; - try { - m_MyHostName = InetAddress.getLocalHost().getHostName(); - } catch (Exception e) { - System.err.println("ERROR getting HostName " + e.getMessage()); - } - } + public StatisticsStandalone(InterfaceStatisticsParameter statParams) { + super(); + m_StatsParams = statParams; + try { + m_MyHostName = InetAddress.getLocalHost().getHostName(); + } catch (Exception e) { + System.err.println("ERROR getting HostName " + e.getMessage()); + } + } - public StatisticsStandalone(String resultFileName) { - this(resultFileName, 1, resultFileName==null ? StatisticsParameter.VERBOSITY_NONE : StatisticsParameter.VERBOSITY_FINAL, false); - } - - public StatisticsStandalone(String resultFileName, int multiRuns, int verbosity, boolean outputAllFieldsAsText) { - this(StatisticsParameter.getInstance(false)); - m_StatsParams.setMultiRuns(multiRuns); - m_StatsParams.setOutputVerbosity(m_StatsParams.getOutputVerbosity().setSelectedTag(verbosity)); - m_StatsParams.setResultFilePrefix(resultFileName); - m_StatsParams.setOutputAllFieldsAsText(outputAllFieldsAsText); - if (resultFileName==null) { - m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_WINDOW); - } - else { - m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_FILE)); - } - } - - public StatisticsStandalone() { - this(new StatisticsParameter()); - } + public StatisticsStandalone(String resultFileName) { + this(resultFileName, 1, resultFileName == null ? StatisticsParameter.VERBOSITY_NONE : StatisticsParameter.VERBOSITY_FINAL, false); + } + + public StatisticsStandalone(String resultFileName, int multiRuns, int verbosity, boolean outputAllFieldsAsText) { + this(StatisticsParameter.getInstance(false)); + m_StatsParams.setMultiRuns(multiRuns); + m_StatsParams.setOutputVerbosity(m_StatsParams.getOutputVerbosity().setSelectedTag(verbosity)); + m_StatsParams.setResultFilePrefix(resultFileName); + m_StatsParams.setOutputAllFieldsAsText(outputAllFieldsAsText); + if (resultFileName == null) { + m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_WINDOW); + } else { + m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_FILE)); + } + } + + public StatisticsStandalone() { + this(new StatisticsParameter()); + } @Override - protected void initPlots(PopulationInterface pop, List informerList) { - if (collectData) { - m_ResultData = new ArrayList>(m_StatsParams.getMultiRuns()); - List description = getOutputHeaderFieldNames(informerList); - m_ResultHeaderStrings = new ArrayList(); - for (String str : description) { + protected void initPlots(PopulationInterface pop, List informerList) { + if (collectData) { + m_ResultData = new ArrayList>(m_StatsParams.getMultiRuns()); + List description = getOutputHeaderFieldNames(informerList); + m_ResultHeaderStrings = new ArrayList(); + for (String str : description) { m_ResultHeaderStrings.add(str); } - for (int i = 0; i < m_StatsParams.getMultiRuns(); i++) { + for (int i = 0; i < m_StatsParams.getMultiRuns(); i++) { m_ResultData.add(new ArrayList()); } - } else { - m_ResultData=null; - m_ResultHeaderStrings = null; - } - } - - @Override - protected void plotCurrentResults() { - if (collectData && (m_ResultData!=null)) { - m_ResultData.get(optRunsPerformed).add(currentStatObjectData); - } - } + } else { + m_ResultData = null; + m_ResultHeaderStrings = null; + } + } @Override - public void plotSpecificData(PopulationInterface pop, List informerList) { - double[] specificData = pop.getSpecificData(); - if (specificData != null) { - for (int i = 0; i < specificData.length; i++) { + protected void plotCurrentResults() { + if (collectData && (m_ResultData != null)) { + m_ResultData.get(optRunsPerformed).add(currentStatObjectData); + } + } + + @Override + public void plotSpecificData(PopulationInterface pop, List informerList) { + double[] specificData = pop.getSpecificData(); + if (specificData != null) { + for (int i = 0; i < specificData.length; i++) { // ((ArrayList[]) m_Result.get(i))[optRunsPerformed].add(new Double[] {new Double(functionCalls), specificData[i]}); - m_ResultData.get(optRunsPerformed).add(new Object[] {new Double(functionCalls), specificData}); - } - } - } + m_ResultData.get(optRunsPerformed).add(new Object[]{new Double(functionCalls), specificData}); + } + } + } // public void startOptPerformed(String infoString, int runNumber, Object params) { // super.startOptPerformed(infoString, runNumber, params); @@ -127,7 +128,7 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac // } // m_InfoString = infoString; // } - + // public void stopOptPerformed(boolean normal, String stopMessage) { // super.stopOptPerformed(normal, stopMessage); // if (bestCurrentIndy != null) { @@ -267,40 +268,41 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac // public double getBestFitnessMedianofALL() { // return m_FitnessMedianofALL; // } - + @Override - public String getHostName() { - return m_MyHostName; - } + public String getHostName() { + return m_MyHostName; + } - /** - * Check whether data collection is activated, which stores an Object[] for every iteration and - * every multi-run. - * @return - */ - public boolean isCollectData() { - return collectData; - } + /** + * Check whether data collection is activated, which stores an Object[] for every iteration and + * every multi-run. + * + * @return + */ + public boolean isCollectData() { + return collectData; + } - /** - * Set state of full data collection, which stores an Object[] for every iteration and - * every multi-run. - * - * @param collectFullData - */ - public void setCollectData(boolean collectFullData) { - this.collectData = collectFullData; - } - - public ArrayList> getCollectedData() { - return m_ResultData; - } + /** + * Set state of full data collection, which stores an Object[] for every iteration and + * every multi-run. + * + * @param collectFullData + */ + public void setCollectData(boolean collectFullData) { + this.collectData = collectFullData; + } - public ArrayList getCollectedRunData(int runIndex) { - return m_ResultData.get(runIndex); - } - - public ArrayList getCollectedDataHeaders() { - return m_ResultHeaderStrings; - } + public ArrayList> getCollectedData() { + return m_ResultData; + } + + public ArrayList getCollectedRunData(int runIndex) { + return m_ResultData.get(runIndex); + } + + public ArrayList getCollectedDataHeaders() { + return m_ResultHeaderStrings; + } } \ No newline at end of file diff --git a/src/eva2/optimization/stat/StatisticsWithGUI.java b/src/eva2/optimization/stat/StatisticsWithGUI.java index eed6cf99..6bdb86ef 100644 --- a/src/eva2/optimization/stat/StatisticsWithGUI.java +++ b/src/eva2/optimization/stat/StatisticsWithGUI.java @@ -10,6 +10,7 @@ package eva2.optimization.stat; * $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007) $ * $Author: mkron $ */ + import eva2.gui.BeanInspector; import eva2.gui.plot.Graph; import eva2.gui.plot.GraphWindow; @@ -21,6 +22,7 @@ import eva2.optimization.population.PopulationInterface; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.tools.EVAERROR; import eva2.tools.Pair; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -99,7 +101,7 @@ public class StatisticsWithGUI extends AbstractStatistics implements Serializabl for (int j = 0; j < fitnessGraph[i].length; j++) { statGraph[i][j].setInfoString( (fitnessGraph[i][j].getInfo().length() > 0 ? (fitnessGraph[i][j].getInfo() + "_") : "") - + "Mean_of_" + fullRuns + " ", + + "Mean_of_" + fullRuns + " ", (float) 2.0); if (normal && fitnessFrame[i].isValid() && (fitnessGraph[i][j].getPointCount() > 0)) { statGraph[i][j].addGraph(fitnessGraph[i][j]); @@ -150,7 +152,7 @@ public class StatisticsWithGUI extends AbstractStatistics implements Serializabl // this is where the column string for ascii export is created! Uah! fitnessGraph[i][j] = fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_" - + graphInfoString); + + graphInfoString); fitnessGraph[i][j].jump(); } } diff --git a/src/eva2/optimization/stat/StatsOnSingleDataSetEnum.java b/src/eva2/optimization/stat/StatsOnSingleDataSetEnum.java index 3fe849dc..49940712 100644 --- a/src/eva2/optimization/stat/StatsOnSingleDataSetEnum.java +++ b/src/eva2/optimization/stat/StatsOnSingleDataSetEnum.java @@ -1,9 +1,9 @@ package eva2.optimization.stat; public enum StatsOnSingleDataSetEnum { - mean, median, variance, stdDev; - - public static String[] getInfoStrings(){ - return new String[] {"The mean value", "The median value", "The variance", "The standard deviation"}; - } + mean, median, variance, stdDev; + + public static String[] getInfoStrings() { + return new String[]{"The mean value", "The median value", "The variance", "The standard deviation"}; + } } diff --git a/src/eva2/optimization/stat/StatsOnTwoSampledDataEnum.java b/src/eva2/optimization/stat/StatsOnTwoSampledDataEnum.java index 63b36b8e..4cfcb3fc 100644 --- a/src/eva2/optimization/stat/StatsOnTwoSampledDataEnum.java +++ b/src/eva2/optimization/stat/StatsOnTwoSampledDataEnum.java @@ -1,12 +1,12 @@ package eva2.optimization.stat; public enum StatsOnTwoSampledDataEnum { - tTestEqLenEqVar, tTestUneqLenEqVar, tTestUneqLenUneqVar, mannWhitney; - - public static String[] getInfoStrings(){ - return new String[] {"Two-sampled t-Test with equal sized data sets", - "Two-sampled t-Test with unequal sized data sets", - "Two-sampled t-Test with unequal data sets and unequal variances", - "Two-sampled Mann-Whitney test"}; - } + tTestEqLenEqVar, tTestUneqLenEqVar, tTestUneqLenUneqVar, mannWhitney; + + public static String[] getInfoStrings() { + return new String[]{"Two-sampled t-Test with equal sized data sets", + "Two-sampled t-Test with unequal sized data sets", + "Two-sampled t-Test with unequal data sets and unequal variances", + "Two-sampled Mann-Whitney test"}; + } } diff --git a/src/eva2/optimization/strategies/ANPSO.java b/src/eva2/optimization/strategies/ANPSO.java index be97b6a0..c0e91974 100644 --- a/src/eva2/optimization/strategies/ANPSO.java +++ b/src/eva2/optimization/strategies/ANPSO.java @@ -19,83 +19,86 @@ import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.tools.ToolBox; import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointSet; + import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; /** - * The Adaptive Niching PSO(ANPSO)[1] extends the particle swarm optimizer (PSO) - * by Kennedy and Eberhart to locate multiple optima of a multimodal objective function. - * The Algorithm uses similar concepts as the NichePSO such as a main swarm to explore - * the search space and subswarms to refine and represent single niches. - * The implemented version uses the "inertness weight" PSO to train the main swarm. - * mainSwarmInertness sets the inertia weight omega and weights the particles tendency to follow its former movement. - * This controls exploration (favored by larger values) against exploitation (favored by smaller values). - * mainSwarmPhi1 sets Phi1 and weights the cognitive component. - * The term corresponds to the particles tendency to return to its personal best position. - * mainSwarmPhi2 sets Phi2 and weights the social component. + * The Adaptive Niching PSO(ANPSO)[1] extends the particle swarm optimizer (PSO) + * by Kennedy and Eberhart to locate multiple optima of a multimodal objective function. + * The Algorithm uses similar concepts as the NichePSO such as a main swarm to explore + * the search space and subswarms to refine and represent single niches. + * The implemented version uses the "inertness weight" PSO to train the main swarm. + * mainSwarmInertness sets the inertia weight omega and weights the particles tendency to follow its former movement. + * This controls exploration (favored by larger values) against exploitation (favored by smaller values). + * mainSwarmPhi1 sets Phi1 and weights the cognitive component. + * The term corresponds to the particles tendency to return to its personal best position. + * mainSwarmPhi2 sets Phi2 and weights the social component. * The term corresonds to the particles tendency to be attracted towards its neighborhood best position. - * A small value for mainSwarmPhi2 reduces the influence of the neighborhood and each particle tend to - * perfom a local search on its own. This results in a high exploration ability of the main swarm and - * potentially leads to a good amount of identified optima. - * Larger values for mainSwarmPhi2 on the other hand might help to concentrate on fewer optima with superior fitness values. - * - * To avoid further parameters and the need to specify adequate values, which are often difficult to decide, - * the following adaption mechanism is employed: - * ANPSO adaptively determines a threshold parameter r during every generation by computing the average - * distance a particle has to its neighbor. Subsequently, a so called s-matrix is calculated that keeps - * track of how long any two particles are close (i.e. within r) to each other. - * The s-matrix is used to build a niche graph that represents particles as vertices and connects all particles - * that have been close to each other for at least two consecutive generations. - * Particles that are connected in the niche graph form a subswarm. - * The implemented version uses a strategy to deactivate subswarms when all containing particles converged on a solution. - * Furthermore, different neighborhood topologies can be choosen for the main swarm. + * A small value for mainSwarmPhi2 reduces the influence of the neighborhood and each particle tend to + * perfom a local search on its own. This results in a high exploration ability of the main swarm and + * potentially leads to a good amount of identified optima. + * Larger values for mainSwarmPhi2 on the other hand might help to concentrate on fewer optima with superior fitness values. + *

+ * To avoid further parameters and the need to specify adequate values, which are often difficult to decide, + * the following adaption mechanism is employed: + * ANPSO adaptively determines a threshold parameter r during every generation by computing the average + * distance a particle has to its neighbor. Subsequently, a so called s-matrix is calculated that keeps + * track of how long any two particles are close (i.e. within r) to each other. + * The s-matrix is used to build a niche graph that represents particles as vertices and connects all particles + * that have been close to each other for at least two consecutive generations. + * Particles that are connected in the niche graph form a subswarm. + * The implemented version uses a strategy to deactivate subswarms when all containing particles converged on a solution. + * Furthermore, different neighborhood topologies can be choosen for the main swarm. * In case the Multi-Swarm topology is used, the species radius is adaptively determined as well. - * - * [1] S. Bird and X. Li: - * Adaptively choosing niching parameters in a PSO. - * In: GECCO '06: Proceedings of the 8th annual conference on Genetic and evolutionary computation, - * Seiten 3--10, New York, NY, USA, 2006. ACM - * + *

+ * [1] S. Bird and X. Li: + * Adaptively choosing niching parameters in a PSO. + * In: GECCO '06: Proceedings of the 8th annual conference on Genetic and evolutionary computation, + * Seiten 3--10, New York, NY, USA, 2006. ACM + * * @author aschoff, mkron */ -public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAdditionalPopulationInformer, java.io.Serializable { +public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAdditionalPopulationInformer, java.io.Serializable { -/********************************************************************************************************************** - * members - */ - // for ANPSO it is necessary to keep an own archiv of inactive subswarms, because the standard set of - // subswarms is completely renewed every iteration. - public Vector inactiveSubSwarms = new Vector(); - - // the s matrix keeps track of how long particles are close to each other - int[][] s = new int[mainSwarmSize][mainSwarmSize]; - - // the niche graph represents particles as vertices and connects all particles that - // have been close to each other for at least two consecutive generations - protected NicheGraph nicheGraph = new NicheGraph(); - - // defines the minimal distance for neighboring particles at which they form a subswarm - // (this is proposed by Bird and Lee for further investigation) - protected double minimalR = 0; - private double updateRadius = 0.; - // maximum subswarm size - private int maxInitialSubSwarmSize = 0; + /** + * ******************************************************************************************************************* + * members + */ + // for ANPSO it is necessary to keep an own archiv of inactive subswarms, because the standard set of + // subswarms is completely renewed every iteration. + public Vector inactiveSubSwarms = new Vector(); - private int maxNeighborCntNicheGraph = 4; // maximum for neighborhood matrix - private int minNeighborCntNicheGraph = 0; // minimum for neighborhood matrix - private int neighborCntNicheGraphForEdge = 2; // number of steps req. to build an edge - -/********************************************************************************************************************** - * ctors, clone - */ - public ANPSO() { + // the s matrix keeps track of how long particles are close to each other + int[][] s = new int[mainSwarmSize][mainSwarmSize]; + + // the niche graph represents particles as vertices and connects all particles that + // have been close to each other for at least two consecutive generations + protected NicheGraph nicheGraph = new NicheGraph(); + + // defines the minimal distance for neighboring particles at which they form a subswarm + // (this is proposed by Bird and Lee for further investigation) + protected double minimalR = 0; + private double updateRadius = 0.; + // maximum subswarm size + private int maxInitialSubSwarmSize = 0; + + private int maxNeighborCntNicheGraph = 4; // maximum for neighborhood matrix + private int minNeighborCntNicheGraph = 0; // minimum for neighborhood matrix + private int neighborCntNicheGraphForEdge = 2; // number of steps req. to build an edge + + /** + * ******************************************************************************************************************* + * ctors, clone + */ + public ANPSO() { // NichePSO.stdNPSO(anpso, problem, randSeed, evalCnt); // NichePSO.stdNPSO((ANPSO)this, (AbstractOptimizationProblem)this.problem, 0, 1000); - /////////// from NichePSO + /////////// from NichePSO // super.initMainSwarm(); // not really necessary if init is called before optimization but this way init doesnt change the parameters of a newly constructed object // super.initSubswarmOptimizerTemplate(); // setMergingStrategy(new StandardMergingStrategy(0.001)); @@ -103,34 +106,34 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // setSubswarmCreationStrategy(new StandardSubswarmCreationStrategy(0.0001)); // // setMaxAllowedSwarmRadius(0.0001); // formally limits the swarm radius of the subswarms - - // Parameter for the mainswarm + + // Parameter for the mainswarm // npso.getMainSwarm().setSpeedLimit(avgRange/2.); // npso.getMainSwarm().setCheckSpeedLimit(true); - - // parameter for the subswarms + + // parameter for the subswarms // System.out.println(BeanInspector.niceToString(getSubswarmOptimizerTemplate())); // getSubswarmOptimizerTemplate().setGcpso(true); // getSubswarmOptimizerTemplate().setRho(0.1); // on 2D Problems empirically better than default value 1 // getSubswarmOptimizerTemplate().setAlgoType(new SelectedTag("Constriction")); // getSubswarmOptimizerTemplate().setConstriction(2.05, 2.05); // System.out.println(BeanInspector.niceToString(getSubswarmOptimizerTemplate())); - - ///////////end from NichePSO - getMainSwarm().setPhi1(2.05); - getMainSwarm().setPhi2(2.05); - getMainSwarm().setInertnessOrChi(0.7298437881283576); + + ///////////end from NichePSO + getMainSwarm().setPhi1(2.05); + getMainSwarm().setPhi2(2.05); + getMainSwarm().setInertnessOrChi(0.7298437881283576); // setMainSwarmInertness(new NoParameterAging(0.7298437881283576)); - setMainSwarmAlgoType(getMainSwarm().getAlgoType().setSelectedTag("Constriction")); // constriction - setMaxInitialSubSwarmSize(0); // deactivate early reinits - setMainSwarmTopology(PSOTopologyEnum.grid); - setMainSwarmTopologyRange(1); - setDeactivationStrategy(new StandardDeactivationStrategy(0.000001, 8)); - setMainSwarmSize(100); - } - + setMainSwarmAlgoType(getMainSwarm().getAlgoType().setSelectedTag("Constriction")); // constriction + setMaxInitialSubSwarmSize(0); // deactivate early reinits + setMainSwarmTopology(PSOTopologyEnum.grid); + setMainSwarmTopologyRange(1); + setDeactivationStrategy(new StandardDeactivationStrategy(0.000001, 8)); + setMainSwarmSize(100); + } + /*public ANPSO(){ - // Parameter for the mainswarm + // Parameter for the mainswarm // //Earlier standard settings: // this.setMainSwarmAlgoType(getMainSwarm().getAlgoType().setSelectedTag("Inertness")); // this.mainSwarmPhi1 = 1.2; @@ -150,133 +153,137 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi hideHideable(); initMainSwarm(); }*/ - - public ANPSO(int mainSwarmSize, double phi1, double phi2, PSOTopologyEnum mainSwarmTopo, int mainSwarmTopoRange, int maxInitialSubSwarmSize) { - this(); - setMainSwarmSize(mainSwarmSize); - getMainSwarm().setPhi1(phi1); - getMainSwarm().setPhi2(phi2); + + public ANPSO(int mainSwarmSize, double phi1, double phi2, PSOTopologyEnum mainSwarmTopo, int mainSwarmTopoRange, int maxInitialSubSwarmSize) { + this(); + setMainSwarmSize(mainSwarmSize); + getMainSwarm().setPhi1(phi1); + getMainSwarm().setPhi2(phi2); // setMainSwarmPhi1(phi1); // setMainSwarmPhi2(phi2); - setMainSwarmTopologyRange(mainSwarmTopoRange); - setMainSwarmTopology(mainSwarmTopo); - setMaxInitialSubSwarmSize(maxInitialSubSwarmSize); - } - - /** - * Take care that all properties which may be hidden (and currently are) send a "hide" message to the Java Bean properties. - * This is called by PropertySheetPanel in use with the GenericObjectEditor. - */ - @Override - public void hideHideable() { - // hide the following unused properties from the GUI - GenericObjectEditor.setHideProperty(getClass(), "subswarmCreationStrategy", true); - GenericObjectEditor.setHideProperty(getClass(), "mergingStrategy", true); - GenericObjectEditor.setHideProperty(getClass(), "absorptionStrategy", true); - GenericObjectEditor.setHideProperty(getClass(), "maxAllowedSwarmRadius", true); - GenericObjectEditor.setHideProperty(getClass(), "mainSwarmTopologyRange", mainSwarmTopology == PSOTopologyEnum.multiSwarm); // "Multi-Swarm" has no topologyRange + setMainSwarmTopologyRange(mainSwarmTopoRange); + setMainSwarmTopology(mainSwarmTopo); + setMaxInitialSubSwarmSize(maxInitialSubSwarmSize); + } - // population size is set via setMainSwarmSize - GenericObjectEditor.setHideProperty(getClass(), "population", true); + /** + * Take care that all properties which may be hidden (and currently are) send a "hide" message to the Java Bean properties. + * This is called by PropertySheetPanel in use with the GenericObjectEditor. + */ + @Override + public void hideHideable() { + // hide the following unused properties from the GUI + GenericObjectEditor.setHideProperty(getClass(), "subswarmCreationStrategy", true); + GenericObjectEditor.setHideProperty(getClass(), "mergingStrategy", true); + GenericObjectEditor.setHideProperty(getClass(), "absorptionStrategy", true); + GenericObjectEditor.setHideProperty(getClass(), "maxAllowedSwarmRadius", true); + GenericObjectEditor.setHideProperty(getClass(), "mainSwarmTopologyRange", mainSwarmTopology == PSOTopologyEnum.multiSwarm); // "Multi-Swarm" has no topologyRange + + // population size is set via setMainSwarmSize + GenericObjectEditor.setHideProperty(getClass(), "population", true); // setGOEShowProperties(getClass()); - } - - public ANPSO(ANPSO o){ - super(o); - this.inactiveSubSwarms = (Vector)o.inactiveSubSwarms.clone(); - this.s = new int[mainSwarmSize][mainSwarmSize]; - for (int i = 0; i < s.length; ++i){ - System.arraycopy(o.s[i], 0, s[i], 0, s[i].length); - } - - this.nicheGraph = (NicheGraph)nicheGraph.clone(); - this.minimalR = o.minimalR; - this.minNeighborCntNicheGraph = o.minNeighborCntNicheGraph; - this.maxNeighborCntNicheGraph = o.maxNeighborCntNicheGraph; - this.neighborCntNicheGraphForEdge = o.neighborCntNicheGraphForEdge; - } - + } + + public ANPSO(ANPSO o) { + super(o); + this.inactiveSubSwarms = (Vector) o.inactiveSubSwarms.clone(); + this.s = new int[mainSwarmSize][mainSwarmSize]; + for (int i = 0; i < s.length; ++i) { + System.arraycopy(o.s[i], 0, s[i], 0, s[i].length); + } + + this.nicheGraph = (NicheGraph) nicheGraph.clone(); + this.minimalR = o.minimalR; + this.minNeighborCntNicheGraph = o.minNeighborCntNicheGraph; + this.maxNeighborCntNicheGraph = o.maxNeighborCntNicheGraph; + this.neighborCntNicheGraphForEdge = o.neighborCntNicheGraphForEdge; + } + @Override - public Object clone(){ - return (Object) new ANPSO(this); - } - -/********************************************************************************************************************** - * inits - */ + public Object clone() { + return (Object) new ANPSO(this); + } + + /** + * ******************************************************************************************************************* + * inits + */ @Override - public void init() { // MOE: wird vor Optimierung / n�chstem multirun 1x aufgerufen - super.init(); - initMainSwarm(); - initSTo(0); - initNicheGraph(); - - inactiveSubSwarms = new Vector(); // dont want to use subswarms from old optimization run (especially not in multiruns)... - } + public void init() { // MOE: wird vor Optimierung / n�chstem multirun 1x aufgerufen + super.init(); + initMainSwarm(); + initSTo(0); + initNicheGraph(); - /** - * resets all entries of the s matrix that correspond to any - * particle in the given subswarm - * @param subswarm - */ - private void resetSMatrixEntriesFor(ParticleSubSwarmOptimization subswarm) { - Population pop = subswarm.getPopulation(); - for (int i = 0; i < pop.size(); ++i){ - //Integer index = pop.getEAIndividual(i).getIndividualIndex();(Integer)pop.getEAIndividual(i).getData("particleIndex"); - resetSMatrixForIndex(pop.getEAIndividual(i).getIndividualIndex(),0); - } - } + inactiveSubSwarms = new Vector(); // dont want to use subswarms from old optimization run (especially not in multiruns)... + } - /** - * sets the given row and column to the given value - * (i.e. all entries corresponding to a specific particle) - * @param index - * @param val - */ - private void resetSMatrixForIndex(int index, int val) { - for (int i = 0 ; i < s.length; ++i){ - for (int j = 0; j < s[i].length; ++j){ - if (i == index || j == index){ - s[i][j] = val; - } - } - } - } + /** + * resets all entries of the s matrix that correspond to any + * particle in the given subswarm + * + * @param subswarm + */ + private void resetSMatrixEntriesFor(ParticleSubSwarmOptimization subswarm) { + Population pop = subswarm.getPopulation(); + for (int i = 0; i < pop.size(); ++i) { + //Integer index = pop.getEAIndividual(i).getIndividualIndex();(Integer)pop.getEAIndividual(i).getData("particleIndex"); + resetSMatrixForIndex(pop.getEAIndividual(i).getIndividualIndex(), 0); + } + } - /** - * sets every entry of the s matrix to the given value - * @param val - */ - private void initSTo(int val) { - for (int i = 0 ; i < s.length; ++i){ - for (int j = 0; j < s[i].length; ++j){ - s[i][j] = val; - } - } - } + /** + * sets the given row and column to the given value + * (i.e. all entries corresponding to a specific particle) + * + * @param index + * @param val + */ + private void resetSMatrixForIndex(int index, int val) { + for (int i = 0; i < s.length; ++i) { + for (int j = 0; j < s[i].length; ++j) { + if (i == index || j == index) { + s[i][j] = val; + } + } + } + } - /** - * this inits the "niche graph". - * Every particle is represented as a vertex in the "niche graph". - */ - private void initNicheGraph(){ - nicheGraph = new NicheGraph(); - Population activePop = getActivePopulation(); - for (int i = 0; i < activePop.size(); ++i){ - //Integer index = activePop.getEAIndividual(i).getParticleIndex();//(Integer)activePop.getEAIndividual(i).getData("particleIndex"); - String vertex = ""+activePop.getEAIndividual(i).getIndividualIndex(); - nicheGraph.addVertex(vertex); - } - } + /** + * sets every entry of the s matrix to the given value + * + * @param val + */ + private void initSTo(int val) { + for (int i = 0; i < s.length; ++i) { + for (int j = 0; j < s[i].length; ++j) { + s[i][j] = val; + } + } + } + + /** + * this inits the "niche graph". + * Every particle is represented as a vertex in the "niche graph". + */ + private void initNicheGraph() { + nicheGraph = new NicheGraph(); + Population activePop = getActivePopulation(); + for (int i = 0; i < activePop.size(); ++i) { + //Integer index = activePop.getEAIndividual(i).getParticleIndex();//(Integer)activePop.getEAIndividual(i).getData("particleIndex"); + String vertex = "" + activePop.getEAIndividual(i).getIndividualIndex(); + nicheGraph.addVertex(vertex); + } + } /********************************************************************************************************************** * ANPSO core - -// /** -// * @param pop -// * @param normalized use a normalized metric to compute distances? -// * @return ave distance to neighbor in the given population -// */ + + // /** + // * @param pop + // * @param normalized use a normalized metric to compute distances? + // * @return ave distance to neighbor in the given population + // */ // public double getAveDistToClosestNeighbor(Population pop, boolean normalized){ // PhenotypeMetric metric = new PhenotypeMetric(); //// ArrayList distances = new ArrayList(pop.size()); @@ -340,411 +347,415 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // return pop.getEAIndividual(index); // } - /** - * Builds the s matrix and the niche graph. - * The s matrix keeps track of the number of generations - * each particle has been close to every other particle. - * The niche graph connects particles that have been close - * for at least two consecutive generations. - */ - public void updateSMatrixAndNicheGraph(){ - // init the niche graph (all particles as vertices, no edges): - initNicheGraph(); - - // compute population statistic for parameter r: - Population metapop = getActivePopulation(); - if (metapop.size()<2) { - // this might happen if all but a single individual are scheduled to be reinitialized after species convergence + /** + * Builds the s matrix and the niche graph. + * The s matrix keeps track of the number of generations + * each particle has been close to every other particle. + * The niche graph connects particles that have been close + * for at least two consecutive generations. + */ + public void updateSMatrixAndNicheGraph() { + // init the niche graph (all particles as vertices, no edges): + initNicheGraph(); + + // compute population statistic for parameter r: + Population metapop = getActivePopulation(); + if (metapop.size() < 2) { + // this might happen if all but a single individual are scheduled to be reinitialized after species convergence // System.err.println("Warning, active population of size " + metapop.size() +", radius will not be updated..."); - } else { - updateRadius = metapop.getAvgDistToClosestNeighbor(false, false)[0]; - } // use all particles not mainswarm particles only... - if (isVerbose()) { - System.out.print(" radius is " + updateRadius); - } - - // build the s matrix and add edges to the niche graph: - // get particles i and j (unique in all swarms)... - AbstractEAIndividual[] sortedPop = sortActivePopByParticleIndex(); // sort once to reduce cpu-time spend for accessing members... + } else { + updateRadius = metapop.getAvgDistToClosestNeighbor(false, false)[0]; + } // use all particles not mainswarm particles only... + if (isVerbose()) { + System.out.print(" radius is " + updateRadius); + } + + // build the s matrix and add edges to the niche graph: + // get particles i and j (unique in all swarms)... + AbstractEAIndividual[] sortedPop = sortActivePopByParticleIndex(); // sort once to reduce cpu-time spend for accessing members... // System.out.println("metapop size is " + metapop.size()); - for (int i = 0; i < s.length-1; ++i){ - AbstractEAIndividual indy_i = sortedPop[i]; - if (indy_i==null) { - continue; - } // may happen is some sub swarm was deactivated and the indies are scheduled for reinit - for (int j = i+1; j < s[i].length; ++j){ - // call hotspot - AbstractEAIndividual indy_j = sortedPop[j]; - if (indy_j==null) { - continue; - } // may happen is some sub swarm was deactivated and the indies are scheduled for reinit - if (indy_i == null || indy_j == null){ - System.out.println("updateSMatrixAndNicheGraph: indices problem"); - } - - // ...check if they are "close to each other" - double dist = getMainSwarm().distance(indy_i, indy_j); - if (dist < updateRadius || dist < minimalR){ - // increment entry that counts the number of generations - // i and j have been close to each other - ++s[i][j]; + for (int i = 0; i < s.length - 1; ++i) { + AbstractEAIndividual indy_i = sortedPop[i]; + if (indy_i == null) { + continue; + } // may happen is some sub swarm was deactivated and the indies are scheduled for reinit + for (int j = i + 1; j < s[i].length; ++j) { + // call hotspot + AbstractEAIndividual indy_j = sortedPop[j]; + if (indy_j == null) { + continue; + } // may happen is some sub swarm was deactivated and the indies are scheduled for reinit + if (indy_i == null || indy_j == null) { + System.out.println("updateSMatrixAndNicheGraph: indices problem"); + } - // values must not exceed 4 to allow a particle to leave a niche - // in case it is further than r for two consecutive steps - if (s[i][j]>maxNeighborCntNicheGraph) { - s[i][j]=maxNeighborCntNicheGraph; - } + // ...check if they are "close to each other" + double dist = getMainSwarm().distance(indy_i, indy_j); + if (dist < updateRadius || dist < minimalR) { + // increment entry that counts the number of generations + // i and j have been close to each other + ++s[i][j]; - // if i and j had been close to each other for at least two generations - // they are connected by an edge - if (s[i][j] >= neighborCntNicheGraphForEdge){ - String pi = ""+i; - String pj = ""+j; - nicheGraph.addEdge(pi, pj); - } - }else{ - // decrement entry that counts the number of generations - // i and j have been close to each other - --s[i][j]; - if (s[i][j] < minNeighborCntNicheGraph) { - s[i][j] = minNeighborCntNicheGraph; - } - } - } - } - } + // values must not exceed 4 to allow a particle to leave a niche + // in case it is further than r for two consecutive steps + if (s[i][j] > maxNeighborCntNicheGraph) { + s[i][j] = maxNeighborCntNicheGraph; + } - /** - * The returned array may contain null entries (for indies scheduled for reinitialization). - * @param pop - * @return an array of references sorted according to the particle indices - * (i.e. returnedArray[i] = individual with individualIndex i) - */ - protected AbstractEAIndividual[] sortActivePopByParticleIndex() { - Population pop = getActivePopulation(); - AbstractEAIndividual[] sorted; - if (pop.size()= neighborCntNicheGraphForEdge) { + String pi = "" + i; + String pj = "" + j; + nicheGraph.addEdge(pi, pj); + } + } else { + // decrement entry that counts the number of generations + // i and j have been close to each other + --s[i][j]; + if (s[i][j] < minNeighborCntNicheGraph) { + s[i][j] = minNeighborCntNicheGraph; + } + } + } + } + } + + /** + * The returned array may contain null entries (for indies scheduled for reinitialization). + * + * @param pop + * @return an array of references sorted according to the particle indices + * (i.e. returnedArray[i] = individual with individualIndex i) + */ + protected AbstractEAIndividual[] sortActivePopByParticleIndex() { + Population pop = getActivePopulation(); + AbstractEAIndividual[] sorted; + if (pop.size() < mainSwarmSize) { + int reinitSize = 0; + if (indicesToReinit != null) { + for (int i = 0; i < indicesToReinit.size(); i++) { + reinitSize += indicesToReinit.get(i).length; + } + } + if (pop.size() + reinitSize == mainSwarmSize) { // good case, extend pop size; null entries are to be tolerated. + sorted = new AbstractEAIndividual[pop.size() + reinitSize]; + } else { + throw new RuntimeException("Error, invalid size of active population (ANPSO.sortActivePopByParticleIndex()"); + } + } else { + sorted = new AbstractEAIndividual[pop.size()]; + } + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual indy = pop.getEAIndividual(i); + if (sorted[indy.getIndividualIndex()] != null) { + System.err.println("error in sortByParticleIndex!"); + } + if (sorted[indy.getIndividualIndex()] != null) { throw new RuntimeException("Error, inconsistency in ANPSO! (index wrong)"); } - sorted[indy.getIndividualIndex()] = indy; - } - return sorted; - } + sorted[indy.getIndividualIndex()] = indy; + } + return sorted; + } - /** - * uses the sets of particles as different subswarms and removes the particles from the mainswarm - * @param setOfSubswarms - */ - public void useAsSubSwarms(Vector setOfSubswarms){ - Vector newSubSwarms = new Vector(); + /** + * uses the sets of particles as different subswarms and removes the particles from the mainswarm + * + * @param setOfSubswarms + */ + public void useAsSubSwarms(Vector setOfSubswarms) { + Vector newSubSwarms = new Vector(); - for (int i = 0; i < setOfSubswarms.size(); ++i){ - Population pop = setOfSubswarms.get(i); - ParticleSubSwarmOptimization subswarm = getNewSubSwarmOptimizer(); - subswarm.getPopulation().clear(); - subswarm.getPopulation().addAll(pop); - subswarm.populationSizeHasChanged(); - newSubSwarms.add(subswarm); - getMainSwarm().removeSubPopulation(pop, true); // the new subswarm can also come from an earlier subswarm - getMainSwarm().populationSizeHasChanged(); - } - if (isVerbose()) { - System.out.println(); - for (int i=0; i do not count them in getPopulation a second time - int calls = 0; - for (int i = 0; i < getSubSwarms().size(); ++i){ - ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); - calls += subswarm.getPopulation().getFunctionCalls(); - } - getMainSwarm().getPopulation().incrFunctionCallsBy(calls); - - this.SetSubSwarms(newSubSwarms); - } - - /** - * uses the population as the mainswarm - * @param pop - */ - public void useAsMainSwarm(Population pop){ - int generations = getMainSwarm().getPopulation().getGeneration(); - int calls = getMainSwarm().getPopulation().getFunctionCalls(); - getMainSwarm().setPopulation(pop); - getMainSwarm().populationSizeHasChanged(); - getMainSwarm().getPopulation().setGenerationTo(generations); - getMainSwarm().getPopulation().SetFunctionCalls(calls); - } - - /** - * creates subswarms from all particles that correspond to connected vertices in the niche graph. - * Particles corresponding to unconnected vertices belong to the mainswarm. - */ - public void createSubswarmsFromNicheGraph(){ - // get all sets of vertices that are connected in the niche graph... - //(subSwarms = new Vector(); // too early, particles would be lost... - List> connectedComps = nicheGraph.getConnectedComponents(); - - Population tmpPop = new Population(), newMainPop = new Population(); - Vector setOfSubswarms = new Vector(); - boolean reinitSuperfl = true; - boolean TRACEMTHD = false; - - // ... and use the corresponding particles to create the subswarms - if (TRACEMTHD) { - System.out.println("---------"); + for (int i = 0; i < setOfSubswarms.size(); ++i) { + Population pop = setOfSubswarms.get(i); + ParticleSubSwarmOptimization subswarm = getNewSubSwarmOptimizer(); + subswarm.getPopulation().clear(); + subswarm.getPopulation().addAll(pop); + subswarm.populationSizeHasChanged(); + newSubSwarms.add(subswarm); + getMainSwarm().removeSubPopulation(pop, true); // the new subswarm can also come from an earlier subswarm + getMainSwarm().populationSizeHasChanged(); + } + if (isVerbose()) { + System.out.println(); + for (int i = 0; i < newSubSwarms.size(); i++) { + System.out.println("Swarm " + i + " (" + newSubSwarms.get(i).getPopulation().size() + "), best " + newSubSwarms.get(i).getBestIndividual()); } - for (Set connSet : connectedComps){ - if (connSet.size() > 1){// create niche - Population pop = new Population(connSet.size()); - for (String indexStr : connSet){ - Integer index = Integer.valueOf(indexStr); - AbstractEAIndividual indy = getIndyByParticleIndex(index.intValue()); // may be taken from a main swarm or current subwarm - if (indy == null){ - System.err.println("createNichesFromNicheGraph problem -> getIndyByParticleIndex returned null"); - } - pop.add(indy); - } - if (TRACEMTHD) { - System.out.print(" subswarm size ssize " + pop.size()); - } - if (maxInitialSubSwarmSize > 0 && (pop.size() > maxInitialSubSwarmSize)) { - if (TRACEMTHD) { - System.out.print(" removing " + (pop.size()-maxInitialSubSwarmSize)); - } - tmpPop = pop.getWorstNIndividuals(pop.size()-maxInitialSubSwarmSize, -1); - tmpPop.synchSize(); + } + // add the function calls from the subswarms of the last iteration to the mainswarm before forgetting them + // the function calls from the inactivated subswarms are transfered to the mainswarm as well + // -> do not count them in getPopulation a second time + int calls = 0; + for (int i = 0; i < getSubSwarms().size(); ++i) { + ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); + calls += subswarm.getPopulation().getFunctionCalls(); + } + getMainSwarm().getPopulation().incrFunctionCallsBy(calls); + + this.SetSubSwarms(newSubSwarms); + } + + /** + * uses the population as the mainswarm + * + * @param pop + */ + public void useAsMainSwarm(Population pop) { + int generations = getMainSwarm().getPopulation().getGeneration(); + int calls = getMainSwarm().getPopulation().getFunctionCalls(); + getMainSwarm().setPopulation(pop); + getMainSwarm().populationSizeHasChanged(); + getMainSwarm().getPopulation().setGenerationTo(generations); + getMainSwarm().getPopulation().SetFunctionCalls(calls); + } + + /** + * creates subswarms from all particles that correspond to connected vertices in the niche graph. + * Particles corresponding to unconnected vertices belong to the mainswarm. + */ + public void createSubswarmsFromNicheGraph() { + // get all sets of vertices that are connected in the niche graph... + //(subSwarms = new Vector(); // too early, particles would be lost... + List> connectedComps = nicheGraph.getConnectedComponents(); + + Population tmpPop = new Population(), newMainPop = new Population(); + Vector setOfSubswarms = new Vector(); + boolean reinitSuperfl = true; + boolean TRACEMTHD = false; + + // ... and use the corresponding particles to create the subswarms + if (TRACEMTHD) { + System.out.println("---------"); + } + for (Set connSet : connectedComps) { + if (connSet.size() > 1) {// create niche + Population pop = new Population(connSet.size()); + for (String indexStr : connSet) { + Integer index = Integer.valueOf(indexStr); + AbstractEAIndividual indy = getIndyByParticleIndex(index.intValue()); // may be taken from a main swarm or current subwarm + if (indy == null) { + System.err.println("createNichesFromNicheGraph problem -> getIndyByParticleIndex returned null"); + } + pop.add(indy); + } + if (TRACEMTHD) { + System.out.print(" subswarm size ssize " + pop.size()); + } + if (maxInitialSubSwarmSize > 0 && (pop.size() > maxInitialSubSwarmSize)) { + if (TRACEMTHD) { + System.out.print(" removing " + (pop.size() - maxInitialSubSwarmSize)); + } + tmpPop = pop.getWorstNIndividuals(pop.size() - maxInitialSubSwarmSize, -1); + tmpPop.synchSize(); // Population testPop=(Population)pop.clone(); - pop.removeMembers(tmpPop, true); - if (reinitSuperfl) { - for (int i=0; i it = connSet.iterator(); - Integer index = Integer.valueOf(it.next()); - AbstractEAIndividual indy = getIndyByParticleIndex(index.intValue()); - newMainPop.add(indy); - } - } + pop.removeMembers(tmpPop, true); + if (reinitSuperfl) { + for (int i = 0; i < tmpPop.size(); i++) { + AbstractEAIndividual indy = tmpPop.getEAIndividual(i); + indy.init(m_Problem); + indy.resetFitness(Double.MAX_VALUE); // TODO this is not so nice... they should be collected in a reinit-list and inserted at the beginning of the next optimize step + ParticleSwarmOptimization.initIndividualDefaults(indy, 0.2); + ParticleSwarmOptimization.initIndividualMemory(indy); + ParticleSubSwarmOptimization.initSubSwarmDefaultsOf(indy); + } + } + newMainPop.addPopulation(tmpPop); + pop.synchSize(); + } + setOfSubswarms.add(pop); + if (TRACEMTHD) { + System.out.print("\nNew subswarm of size: " + pop.size()); + } + } else { // move particles corresponding to unconnected vertices to the mainswarm + Iterator it = connSet.iterator(); + Integer index = Integer.valueOf(it.next()); + AbstractEAIndividual indy = getIndyByParticleIndex(index.intValue()); + newMainPop.add(indy); + } + } // for (int i=0; i 1)) { //Multi-Swarm - double aveDistToNeighInMain = getMainSwarm().getPopulation().getAvgDistToClosestNeighbor(true, false)[0]; - getMainSwarm().setSubSwarmRadius(aveDistToNeighInMain); - } + if (isVerbose()) { + System.out.print("active swarms: " + countActiveSubswarms() + " of " + getSubSwarms().size()); + } - if (isVerbose()) { - System.out.println(); - } - firePropertyChangedEvent("NextGenerationPerformed"); // calls Listener that sth changed... - - /** plotting **********************************************************************************/ - if (isPlot()){ - doPlot(); - } + // build the s matrix and the niche graph + // these data structures represent particles that have been close to each other + // for at least two consecutive generations + updateSMatrixAndNicheGraph(); + + // create subswarms from the particles corresponding to connected vertices in the niche graph + createSubswarmsFromNicheGraph(); + + // one might create additional subswarms from the main swarm + // using the standard strategie from the NichePSO + // createSubswarmIfPossible(); + + // adapt the species radius of the SPSO using similar population statistics as for the radius parameter r + if ((mainSwarm.getTopology() == PSOTopologyEnum.multiSwarm) && (mainSwarm.getMaxSubSwarmSize() > 1)) { //Multi-Swarm + double aveDistToNeighInMain = getMainSwarm().getPopulation().getAvgDistToClosestNeighbor(true, false)[0]; + getMainSwarm().setSubSwarmRadius(aveDistToNeighInMain); + } + + if (isVerbose()) { + System.out.println(); + } + firePropertyChangedEvent("NextGenerationPerformed"); // calls Listener that sth changed... + + /** plotting **********************************************************************************/ + if (isPlot()) { + doPlot(); + } // System.out.println(); - /** end plotting *******************************************************************************/ - - // reset flags etc for: - // deactivation - deactivationOccured = false; - deactivatedSwarm = new Vector(); - //reinitedSwarm = new Vector(); - // merging - mergingOccurd = false; - borg = new Vector(); - others = new Vector(); - borgbest = new Vector(); - othersbest = new Vector(); - // absorbtion - absorbtionOccurd = false; - indytoabsorb = new Vector(); - // subswarmcreation - creationOccurd = false; - indyconverged = new Vector(); - convergedneighbor = new Vector(); - //clearing - deprecated - //reinitoccurd = false; - - } + /** end plotting *******************************************************************************/ + + // reset flags etc for: + // deactivation + deactivationOccured = false; + deactivatedSwarm = new Vector(); + //reinitedSwarm = new Vector(); + // merging + mergingOccurd = false; + borg = new Vector(); + others = new Vector(); + borgbest = new Vector(); + othersbest = new Vector(); + // absorbtion + absorbtionOccurd = false; + indytoabsorb = new Vector(); + // subswarmcreation + creationOccurd = false; + indyconverged = new Vector(); + convergedneighbor = new Vector(); + //clearing - deprecated + //reinitoccurd = false; + + } -/********************************************************************************************************************** - * Deactivation - */ - + /** + * ******************************************************************************************************************* + * Deactivation + */ + @Override - protected void deactivationEventFor(ParticleSubSwarmOptimization subswarm) { - super.deactivationEventFor(subswarm); - resetSMatrixEntriesFor(subswarm); - inactiveSubSwarms.add(subswarm); // ANPSO will later remove the inactive subswarm from the standard set of subswarms... - } + protected void deactivationEventFor(ParticleSubSwarmOptimization subswarm) { + super.deactivationEventFor(subswarm); + resetSMatrixEntriesFor(subswarm); + inactiveSubSwarms.add(subswarm); // ANPSO will later remove the inactive subswarm from the standard set of subswarms... + } /********************************************************************************************************************** * setter, getter - */ - /** @tested ps - * sets the !initial! size of the mainswarm population - * use this instead of getPopulation.setPopulationSize() - * @param size - */ + */ + /** + * @param size + * @tested ps + * sets the !initial! size of the mainswarm population + * use this instead of getPopulation.setPopulationSize() + */ @Override - public void setMainSwarmSize(int size){ - // set member - this.mainSwarmSize = size; - // pass on to the mainswarm optimizer - getMainSwarm().getPopulation().setTargetSize(size); - // update s - s = new int[size][size]; - initSTo(0); - initNicheGraph(); - } - - /** - * @param includeInactive - * @return a population with clones from all subswarms - */ - public Population getSubswarmMetapop(boolean includeInactive){ - // construct a metapop with clones from all subswarms - Population metapop = new Population(); - for (int i = 0; i < getSubSwarms().size(); ++i){ - ParticleSubSwarmOptimization currentsubswarm = getSubSwarms().get(i); - if (includeInactive || currentsubswarm.isActive()){ - Population currentsubswarmpop = (Population)currentsubswarm.getPopulation().clone(); - metapop.addPopulation(currentsubswarmpop); - } - } - return metapop; - } - - /** @tested junit - * returns a population consisting of copies from the mainswarm and all subswarms - * (active and inactive, so the size of this Population is not necessarily constant). - * Especially important for the call back regarding the output file... - * Beware: getPopulation().getPopulationSize() returns the !initial! size of the main swarm, - * the actual size of the complete population is accessed via getPopulation().size() - * @return a population consisting of copies from the mainswarm and all subswarms. - */ + public void setMainSwarmSize(int size) { + // set member + this.mainSwarmSize = size; + // pass on to the mainswarm optimizer + getMainSwarm().getPopulation().setTargetSize(size); + // update s + s = new int[size][size]; + initSTo(0); + initNicheGraph(); + } + + /** + * @param includeInactive + * @return a population with clones from all subswarms + */ + public Population getSubswarmMetapop(boolean includeInactive) { + // construct a metapop with clones from all subswarms + Population metapop = new Population(); + for (int i = 0; i < getSubSwarms().size(); ++i) { + ParticleSubSwarmOptimization currentsubswarm = getSubSwarms().get(i); + if (includeInactive || currentsubswarm.isActive()) { + Population currentsubswarmpop = (Population) currentsubswarm.getPopulation().clone(); + metapop.addPopulation(currentsubswarmpop); + } + } + return metapop; + } + + /** + * @return a population consisting of copies from the mainswarm and all subswarms. + * @tested junit + * returns a population consisting of copies from the mainswarm and all subswarms + * (active and inactive, so the size of this Population is not necessarily constant). + * Especially important for the call back regarding the output file... + * Beware: getPopulation().getPopulationSize() returns the !initial! size of the main swarm, + * the actual size of the complete population is accessed via getPopulation().size() + */ @Override - public Population getPopulation() { - // construct a metapop with clones from the mainswarm and all subswarms - Population metapop = (Population)getMainSwarm().getPopulation().clone(); - Population currentsubswarm = new Population(); - for (int i = 0; i < getSubSwarms().size(); ++i){ - currentsubswarm = (Population)getSubSwarms().get(i).getPopulation().clone(); - metapop.addPopulation(currentsubswarm); - } - for (int i = 0; i < inactiveSubSwarms.size(); ++i){ // in the case of ANPSO - currentsubswarm = (Population)inactiveSubSwarms.get(i).getPopulation().clone(); - metapop.addPopulation(currentsubswarm); - } - // add the best pbest particle to the population + public Population getPopulation() { + // construct a metapop with clones from the mainswarm and all subswarms + Population metapop = (Population) getMainSwarm().getPopulation().clone(); + Population currentsubswarm = new Population(); + for (int i = 0; i < getSubSwarms().size(); ++i) { + currentsubswarm = (Population) getSubSwarms().get(i).getPopulation().clone(); + metapop.addPopulation(currentsubswarm); + } + for (int i = 0; i < inactiveSubSwarms.size(); ++i) { // in the case of ANPSO + currentsubswarm = (Population) inactiveSubSwarms.get(i).getPopulation().clone(); + metapop.addPopulation(currentsubswarm); + } + // add the best pbest particle to the population // if (metapop.size() != 0){ // AbstractEAIndividual hero = (AbstractEAIndividual)metapop.getEAIndividual(0).getData("PersonalBestKey"); // for (int i = 0; i < metapop.size(); ++i){ @@ -755,157 +766,160 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // } // metapop.add(hero); // } - - // set correct number of generations - metapop.setGenerationTo(getMainSwarm().getPopulation().getGeneration()); - - // set correct number of function calls - int calls = getMainSwarm().getPopulation().getFunctionCalls(); - for (int i = 0; i < getSubSwarms().size(); ++i){ - ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); - // if (subswarm.isActive()){ - calls += subswarm.getPopulation().getFunctionCalls(); - // } - } - // calls from inactivated subswarms were transfered to the mainswarm, see useAsSubSwarms method - - metapop.SetFunctionCalls(calls); - - return metapop; - } - - /** @tested junit - * returns the cloned global best individuals (ie best of all time) from every subswarm - * @return array with copies of the gbest individuals - */ - public Population getSubswarmRepresentatives(){ - //boolean includeMainSwarm = false; - int mainSize = 0; - //if (includeMainSwarm) mainSize = getMainSwarm().getPopulation().size(); - Population elitePop = new Population(getSubSwarms().size()+inactiveSubSwarms.size()+mainSize); + + // set correct number of generations + metapop.setGenerationTo(getMainSwarm().getPopulation().getGeneration()); + + // set correct number of function calls + int calls = getMainSwarm().getPopulation().getFunctionCalls(); + for (int i = 0; i < getSubSwarms().size(); ++i) { + ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); + // if (subswarm.isActive()){ + calls += subswarm.getPopulation().getFunctionCalls(); + // } + } + // calls from inactivated subswarms were transfered to the mainswarm, see useAsSubSwarms method + + metapop.SetFunctionCalls(calls); + + return metapop; + } + + /** + * @return array with copies of the gbest individuals + * @tested junit + * returns the cloned global best individuals (ie best of all time) from every subswarm + */ + public Population getSubswarmRepresentatives() { + //boolean includeMainSwarm = false; + int mainSize = 0; + //if (includeMainSwarm) mainSize = getMainSwarm().getPopulation().size(); + Population elitePop = new Population(getSubSwarms().size() + inactiveSubSwarms.size() + mainSize); // if (includeMainSwarm){ // for (int i = 0; i < mainSize; ++i){ // elite[i] = getMainSwarm().getPopulation().getEAIndividual(i); // } // } - for (int i = 0; i < getSubSwarms().size(); ++i){ - AbstractEAIndividual bestSS = ((ParticleSubSwarmOptimization)getSubSwarms().get(i)).getBestIndividual(); - elitePop.addIndividual((AbstractEAIndividual)((ParticleSubSwarmOptimization)getSubSwarms().get(i)).m_BestIndividual.clone()); - } - for (int i = 0; i < inactiveSubSwarms.size(); ++i){ - elitePop.addIndividual((AbstractEAIndividual)((ParticleSubSwarmOptimization)inactiveSubSwarms.get(i)).m_BestIndividual.clone()); - } - return elitePop; - } - - /** @tested emp - * returns a string that lists the global best individuals (ie best of all time) from every subswarm - * @return descriptive string of the elite - */ - public String getSubswarmRepresentativesAsString(){ - String result = "\nSubswarmRepresentatives: \n"; - Population elite = getSubswarmRepresentatives(); - for (int i = 0; i < getSubSwarms().size()+inactiveSubSwarms.size(); ++i){ - result += elite.getEAIndividual(i).getStringRepresentation() + "\n"; - } - //result += "\n"; - return result; - } - - /** @tested - * plots all subswarms as connected lines to their respective best individual - */ + for (int i = 0; i < getSubSwarms().size(); ++i) { + AbstractEAIndividual bestSS = ((ParticleSubSwarmOptimization) getSubSwarms().get(i)).getBestIndividual(); + elitePop.addIndividual((AbstractEAIndividual) ((ParticleSubSwarmOptimization) getSubSwarms().get(i)).m_BestIndividual.clone()); + } + for (int i = 0; i < inactiveSubSwarms.size(); ++i) { + elitePop.addIndividual((AbstractEAIndividual) ((ParticleSubSwarmOptimization) inactiveSubSwarms.get(i)).m_BestIndividual.clone()); + } + return elitePop; + } + + /** + * @return descriptive string of the elite + * @tested emp + * returns a string that lists the global best individuals (ie best of all time) from every subswarm + */ + public String getSubswarmRepresentativesAsString() { + String result = "\nSubswarmRepresentatives: \n"; + Population elite = getSubswarmRepresentatives(); + for (int i = 0; i < getSubSwarms().size() + inactiveSubSwarms.size(); ++i) { + result += elite.getEAIndividual(i).getStringRepresentation() + "\n"; + } + //result += "\n"; + return result; + } + + /** + * @tested plots all subswarms as connected lines to their respective best individual + */ @Override protected void plotSubSwarms() { - if (this.m_Problem instanceof Interface2DBorderProblem) { - //DPointSet popRep = new DPointSet(); - InterfaceDataTypeDouble tmpIndy1; - - //cleanPlotSubSwarms(); + if (this.m_Problem instanceof Interface2DBorderProblem) { + //DPointSet popRep = new DPointSet(); + InterfaceDataTypeDouble tmpIndy1; - // for all inactive SubSwarms from ANPSO... - for (int i = 0; i < this.inactiveSubSwarms.size(); i++) { - ParticleSubSwarmOptimization currentsubswarm = this.inactiveSubSwarms.get(i); - InterfaceDataTypeDouble best = (InterfaceDataTypeDouble)currentsubswarm.m_BestIndividual; - plotCircleForIndy((AbstractEAIndividual)best,"[I]"); - } - - // for all SubSwarms... - for (int i = 0; i < this.getSubSwarms().size(); i++) { - ParticleSubSwarmOptimization currentsubswarm = this.getSubSwarms().get(i); - Population currentsubswarmpop = (Population)currentsubswarm.getPopulation(); - //InterfaceDataTypeDouble best = (InterfaceDataTypeDouble)currentsubswarmpop.getBestIndividual(); - InterfaceDataTypeDouble best = (InterfaceDataTypeDouble)currentsubswarm.m_BestIndividual; - DPointSet popRep = new DPointSet(); - - //...draw SubSwarm as points - for (int j = 0; j < currentsubswarmpop.size(); j++) { - popRep.setConnected(false); - tmpIndy1 = (InterfaceDataTypeDouble)currentsubswarmpop.get(j); - popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); - } - this.m_TopologySwarm.getFunctionArea().addDElement(popRep); // time consuming + //cleanPlotSubSwarms(); - //...draw circle for best - if (!currentsubswarm.isActive()){ - plotCircleForIndy((AbstractEAIndividual)best,"[I]"); - }else{ - if (!getSubswarmOptimizerTemplate().isGcpso()){ - //plotCircleForIndy((AbstractEAIndividual)best,getMaxStdDevFromSwarmAsString(currentsubswarm)); - } - if (getSubswarmOptimizerTemplate().isGcpso()){ - String rhoAsString = String.format("%6.3f", currentsubswarm.getRho()); - //plotCircleForIndy((AbstractEAIndividual)best,rhoAsString); - if (currentsubswarm.gbestParticle != null){ - //plotCircleForIndy((AbstractEAIndividual)currentsubswarm.gbestParticle,"gbest"); - } - } - } - - //...draw SubSwarm as connected lines to best - popRep = new DPointSet(); - for (int j = 0; j < currentsubswarmpop.size(); j++) { - //popRep.setConnected(false); - tmpIndy1 = (InterfaceDataTypeDouble)currentsubswarmpop.get(j); - //popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); - - popRep.setConnected(true); - popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); - popRep.addDPoint(new DPoint(best.getDoubleData()[0], best.getDoubleData()[1])); - } - this.m_TopologySwarm.getFunctionArea().addDElement(popRep); // time consuming - } - } // endif - } - - /** @tested - * method not used any more - * @param index - * @return inactive particles with given index - * (may return more than one particle for a given index because indizes are reused during deactivation - * and the reinitialized particle may be deactivated again...) - */ - public Vector getInactiveIndiesByParticleIndex(Integer index){ - Vector indies = null; - AbstractEAIndividual indy = null; - for (int i = 0; i < inactiveSubSwarms.size(); ++i){ - Population pop = inactiveSubSwarms.get(i).getPopulation(); - indy = getIndyByParticleIndexAndPopulation(pop, index); // fix if needed: only returns the first occurence... - if (indy != null){ - indies.add(indy); - } - } - return indies; + // for all inactive SubSwarms from ANPSO... + for (int i = 0; i < this.inactiveSubSwarms.size(); i++) { + ParticleSubSwarmOptimization currentsubswarm = this.inactiveSubSwarms.get(i); + InterfaceDataTypeDouble best = (InterfaceDataTypeDouble) currentsubswarm.m_BestIndividual; + plotCircleForIndy((AbstractEAIndividual) best, "[I]"); + } + + // for all SubSwarms... + for (int i = 0; i < this.getSubSwarms().size(); i++) { + ParticleSubSwarmOptimization currentsubswarm = this.getSubSwarms().get(i); + Population currentsubswarmpop = (Population) currentsubswarm.getPopulation(); + //InterfaceDataTypeDouble best = (InterfaceDataTypeDouble)currentsubswarmpop.getBestIndividual(); + InterfaceDataTypeDouble best = (InterfaceDataTypeDouble) currentsubswarm.m_BestIndividual; + DPointSet popRep = new DPointSet(); + + //...draw SubSwarm as points + for (int j = 0; j < currentsubswarmpop.size(); j++) { + popRep.setConnected(false); + tmpIndy1 = (InterfaceDataTypeDouble) currentsubswarmpop.get(j); + popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); + } + this.m_TopologySwarm.getFunctionArea().addDElement(popRep); // time consuming + + //...draw circle for best + if (!currentsubswarm.isActive()) { + plotCircleForIndy((AbstractEAIndividual) best, "[I]"); + } else { + if (!getSubswarmOptimizerTemplate().isGcpso()) { + //plotCircleForIndy((AbstractEAIndividual)best,getMaxStdDevFromSwarmAsString(currentsubswarm)); + } + if (getSubswarmOptimizerTemplate().isGcpso()) { + String rhoAsString = String.format("%6.3f", currentsubswarm.getRho()); + //plotCircleForIndy((AbstractEAIndividual)best,rhoAsString); + if (currentsubswarm.gbestParticle != null) { + //plotCircleForIndy((AbstractEAIndividual)currentsubswarm.gbestParticle,"gbest"); + } + } + } + + //...draw SubSwarm as connected lines to best + popRep = new DPointSet(); + for (int j = 0; j < currentsubswarmpop.size(); j++) { + //popRep.setConnected(false); + tmpIndy1 = (InterfaceDataTypeDouble) currentsubswarmpop.get(j); + //popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); + + popRep.setConnected(true); + popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); + popRep.addDPoint(new DPoint(best.getDoubleData()[0], best.getDoubleData()[1])); + } + this.m_TopologySwarm.getFunctionArea().addDElement(popRep); // time consuming + } + } // endif } - - /** @tested nn - * This method will return a naming String - * @return The name of the algorithm - */ + + /** + * @param index + * @return inactive particles with given index + * (may return more than one particle for a given index because indizes are reused during deactivation + * and the reinitialized particle may be deactivated again...) + * @tested method not used any more + */ + public Vector getInactiveIndiesByParticleIndex(Integer index) { + Vector indies = null; + AbstractEAIndividual indy = null; + for (int i = 0; i < inactiveSubSwarms.size(); ++i) { + Population pop = inactiveSubSwarms.get(i).getPopulation(); + indy = getIndyByParticleIndexAndPopulation(pop, index); // fix if needed: only returns the first occurence... + if (indy != null) { + indies.add(indy); + } + } + return indies; + } + + /** + * @return The name of the algorithm + * @tested nn + * This method will return a naming String + */ @Override - public String getName() { - return "ANPSO-"+getMainSwarmSize(); - } + public String getName() { + return "ANPSO-" + getMainSwarmSize(); + } // // public double getMinimalR() { @@ -913,19 +927,21 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // } - public void SetMinimalR(double minimalR) { - this.minimalR = minimalR; - } - - public int getMaxInitialSubSwarmSize() { - return maxInitialSubSwarmSize; - } - public String maxInitialSubSwarmSizeTipText() { - return "The maximum size of sub swarms at creation time."; - } - public void setMaxInitialSubSwarmSize(int maxSubSwarmSize) { - this.maxInitialSubSwarmSize = maxSubSwarmSize; - } + public void SetMinimalR(double minimalR) { + this.minimalR = minimalR; + } + + public int getMaxInitialSubSwarmSize() { + return maxInitialSubSwarmSize; + } + + public String maxInitialSubSwarmSizeTipText() { + return "The maximum size of sub swarms at creation time."; + } + + public void setMaxInitialSubSwarmSize(int maxSubSwarmSize) { + this.maxInitialSubSwarmSize = maxSubSwarmSize; + } // public void setMainSwarmPhi2(double mainSwarmPhi2) { // super.SetMainSwarmPhi2(mainSwarmPhi2); @@ -933,7 +949,7 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // public String mainSwarmPhi2TipText(){ // return "weights the social component for the PSO used to train the main swarm"; // } - + // /** This method allows you to choose the topology type. // * @param s The type. // */ @@ -942,149 +958,150 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // this.mainSwarmTopologyTag = s.getSelectedTagID(); // GenericObjectEditor.setHideProperty(getClass(), "mainSwarmTopologyRange", mainSwarmTopologyTag == 3); // "Multi-Swarm" has no topologyRange // } - - public String mainSwarmTopologyTipText(){ - return "sets the topology type used to train the main swarm"; - } - - public String mainSwarmTopologyRangeTipText(){ - return "sets the range of the neighborhood topology for the main swarm"; - } - - public static final OptimizationParameters aNichePSO(AbstractOptimizationProblem problem, long randSeed, InterfaceTerminator term) { - ANPSO anpso = new ANPSO(); - anpso.setMainSwarmSize(75); - return OptimizerFactory.makeParams(anpso, 75, problem, randSeed, term); - } - - /** - * Creates a standard ANPSO variant with default constricted PSO parameters and a grid topology. - * - * @param problem - * @param randSeed - * @param evalCnt - * @return - */ - public static final OptimizationParameters stdANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { - ANPSO anpso = new ANPSO(); - NichePSO.stdNPSO(anpso, problem, randSeed, evalCnt); - - anpso.getMainSwarm().setPhi1(2.05); - anpso.getMainSwarm().setPhi2(2.05); - anpso.getMainSwarm().setInertnessOrChi(0.7298437881283576); - anpso.setMainSwarmAlgoType(anpso.getMainSwarm().getAlgoType().setSelectedTag("Constriction")); // constriction - anpso.setMaxInitialSubSwarmSize(0); // deactivate early reinits - anpso.setMainSwarmTopology(PSOTopologyEnum.grid); - anpso.setMainSwarmTopologyRange(1); - anpso.setDeactivationStrategy(new StandardDeactivationStrategy(0.000001, 8)); - + public String mainSwarmTopologyTipText() { + return "sets the topology type used to train the main swarm"; + } + + public String mainSwarmTopologyRangeTipText() { + return "sets the range of the neighborhood topology for the main swarm"; + } + + public static final OptimizationParameters aNichePSO(AbstractOptimizationProblem problem, long randSeed, InterfaceTerminator term) { + ANPSO anpso = new ANPSO(); + anpso.setMainSwarmSize(75); + + return OptimizerFactory.makeParams(anpso, 75, problem, randSeed, term); + } + + /** + * Creates a standard ANPSO variant with default constricted PSO parameters and a grid topology. + * + * @param problem + * @param randSeed + * @param evalCnt + * @return + */ + public static final OptimizationParameters stdANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { + ANPSO anpso = new ANPSO(); + NichePSO.stdNPSO(anpso, problem, randSeed, evalCnt); + + anpso.getMainSwarm().setPhi1(2.05); + anpso.getMainSwarm().setPhi2(2.05); + anpso.getMainSwarm().setInertnessOrChi(0.7298437881283576); + anpso.setMainSwarmAlgoType(anpso.getMainSwarm().getAlgoType().setSelectedTag("Constriction")); // constriction + anpso.setMaxInitialSubSwarmSize(0); // deactivate early reinits + anpso.setMainSwarmTopology(PSOTopologyEnum.grid); + anpso.setMainSwarmTopologyRange(1); + anpso.setDeactivationStrategy(new StandardDeactivationStrategy(0.000001, 8)); + // es gibt kein species size limit wie im orig-paper, aber sie berichten dort, dass sie für // höhere dimensionsn (3,4), eh keines benutzen. - - return OptimizerFactory.makeParams(anpso, anpso.getMainSwarmSize(), problem, randSeed, new EvaluationTerminator(evalCnt)); - } - - public static final OptimizationParameters starANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { - ANPSO anpso = new ANPSO(); - NichePSO.starNPSO(anpso, problem, randSeed, evalCnt); - anpso.getMainSwarm().setParameterControl(new ParamAdaption[]{new LinearParamAdaption("inertnessOrChi", 0.7, 0.2)}); + return OptimizerFactory.makeParams(anpso, anpso.getMainSwarmSize(), problem, randSeed, new EvaluationTerminator(evalCnt)); + } + + public static final OptimizationParameters starANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { + ANPSO anpso = new ANPSO(); + NichePSO.starNPSO(anpso, problem, randSeed, evalCnt); + + anpso.getMainSwarm().setParameterControl(new ParamAdaption[]{new LinearParamAdaption("inertnessOrChi", 0.7, 0.2)}); // anpso.setMainSwarmInertness(new LinearParameterAging(0.7, 0.2, evalCnt/anpso.getMainSwarmSize())); - - anpso.setMainSwarmAlgoType(anpso.getMainSwarm().getAlgoType().setSelectedTag("Inertness")); - anpso.getMainSwarm().setPhi1(1.2); - anpso.getMainSwarm().setPhi2(0.6); // ANPSO uses communication in the main swarm - //Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", "HPSO", "Random" in that order starting by 0. - anpso.SetMainSwarmTopologyTag(3); //"Multi-Swarm" favors the formation of groups in the main swarm - anpso.setMainSwarmTopologyRange(2); // range for topologies like random, grid etc. (does not affect "Multi-Swarm") - anpso.setMaxInitialSubSwarmSize(0); // deactivate early reinits - + + anpso.setMainSwarmAlgoType(anpso.getMainSwarm().getAlgoType().setSelectedTag("Inertness")); + anpso.getMainSwarm().setPhi1(1.2); + anpso.getMainSwarm().setPhi2(0.6); // ANPSO uses communication in the main swarm + //Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", "HPSO", "Random" in that order starting by 0. + anpso.SetMainSwarmTopologyTag(3); //"Multi-Swarm" favors the formation of groups in the main swarm + anpso.setMainSwarmTopologyRange(2); // range for topologies like random, grid etc. (does not affect "Multi-Swarm") + anpso.setMaxInitialSubSwarmSize(0); // deactivate early reinits + // es gibt kein species size limit wie im orig-paper, aber sie berichten dort, dass sie für // höhere dimensionsn (3,4), eh keines benutzen. - return OptimizerFactory.makeParams(anpso, anpso.getMainSwarmSize(), problem, randSeed, new EvaluationTerminator(evalCnt)); - } - - public static final OptimizationParameters gmakANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { - ANPSO anpso = new ANPSO(); - NichePSO.starNPSO(anpso, problem, randSeed, evalCnt); + return OptimizerFactory.makeParams(anpso, anpso.getMainSwarmSize(), problem, randSeed, new EvaluationTerminator(evalCnt)); + } + + public static final OptimizationParameters gmakANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { + ANPSO anpso = new ANPSO(); + NichePSO.starNPSO(anpso, problem, randSeed, evalCnt); + + anpso.getMainSwarm().setParameterControl(new ParamAdaption[]{new LinearParamAdaption("inertnessOrChi", 0.7, 0.2)}); + + anpso.setMainSwarmAlgoType(anpso.getMainSwarm().getAlgoType().setSelectedTag("Inertness")); + anpso.getMainSwarm().setPhi1(1.2); + anpso.getMainSwarm().setPhi2(1.2); // ANPSO uses communication in the main swarm + //Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", "HPSO", "Random" in that order starting by 0. + anpso.SetMainSwarmTopologyTag(3); //"Multi-Swarm" favors the formation of groups in the main swarm + anpso.setMainSwarmTopologyRange(4); // range for topologies like random, grid etc. (does not affect "Multi-Swarm") - anpso.getMainSwarm().setParameterControl(new ParamAdaption[]{new LinearParamAdaption("inertnessOrChi", 0.7, 0.2)}); - - anpso.setMainSwarmAlgoType(anpso.getMainSwarm().getAlgoType().setSelectedTag("Inertness")); - anpso.getMainSwarm().setPhi1(1.2); - anpso.getMainSwarm().setPhi2(1.2); // ANPSO uses communication in the main swarm - //Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", "HPSO", "Random" in that order starting by 0. - anpso.SetMainSwarmTopologyTag(3); //"Multi-Swarm" favors the formation of groups in the main swarm - anpso.setMainSwarmTopologyRange(4); // range for topologies like random, grid etc. (does not affect "Multi-Swarm") - // es gibt kein species size limit wie im orig-paper, aber sie berichten dort, dass sie für // höhere dimensionsn (3,4), eh keines benutzen. - - anpso.getSubswarmOptimizerTemplate().setRho(1); - anpso.getSubswarmOptimizerTemplate().SetRhoIncreaseFactor(2); - anpso.getSubswarmOptimizerTemplate().SetRhoDecreaseFactor(0.5); - - return OptimizerFactory.makeParams(anpso, anpso.getMainSwarmSize(), problem, randSeed, new EvaluationTerminator(evalCnt)); - } - - /** - * Create a grid-star-ANPSO with range 2. - * @param problem - * @param randSeed - * @param evalCnt - * @return - */ - public static final OptimizationParameters sgANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt) { - return starTopoANPSO(problem, randSeed, evalCnt, 1, 2); - } - - /** - * Create a starANPSO with a given main swarm topology. - * - * @param problem - * @param randSeed - * @param evalCnt - * @param topology - * @param topologyRange - * @return - */ - public static final OptimizationParameters starTopoANPSO(AbstractOptimizationProblem problem, long randSeed, int evalCnt, int topology, int topologyRange) { - OptimizationParameters params = starANPSO(problem, randSeed, evalCnt); - ((ANPSO)params.getOptimizer()).SetMainSwarmTopologyTag(topology); - ((ANPSO)params.getOptimizer()).setMainSwarmTopologyRange(topologyRange); - ((ANPSO)params.getOptimizer()).getMainSwarm().setInertnessOrChi(0.73); - return params; - } - - @Override - public String[] getAdditionalDataHeader() { - return ToolBox.appendArrays(super.getAdditionalDataHeader(), new String[] {"mainSwarmBestFit", "swarmRad"}); - } - - @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - return ToolBox.appendArrays(super.getAdditionalDataValue(pop), new Object[] {getMainSwarm().getPopulation().getBestFitness()[0],updateRadius}); - } - - @Override - public String[] getAdditionalDataInfo() { - return ToolBox.appendArrays(super.getAdditionalDataInfo(), new String[]{"The best fitness within the main swarm", "The current value of the adapted swarm radius"}); - } - - @Override - public Population getSubswarmRepresentatives(boolean onlyInactive){ - - Population representatives = super.getSubswarmRepresentatives(onlyInactive); - // this vector does not yet contain the archived solutions - for (int i=0; i swarms) { - Population pop = new Population(swarms.size()); - for (int i=0; i swarms) { - Population pop = new Population(swarms.size()); - for (int i=0; i swarms) { + Population pop = new Population(swarms.size()); + for (int i = 0; i < swarms.size(); i++) { + if (swarms.get(i) != null) { + pop.addIndividual(swarms.get(i).getBestIndividual()); + } + } + return pop.getCorrelations()[3]; + } + + /** + * Return the mean distance of the best individuals of the given set of swarms. + * + * @param swarms + * @return + */ + private double getMeanDist( + Vector swarms) { + Population pop = new Population(swarms.size()); + for (int i = 0; i < swarms.size(); i++) { + if (swarms.get(i) != null) { + pop.addIndividual(swarms.get(i).getBestIndividual()); + } + } + return pop.getPopulationMeasures()[0]; + } + + @Override + protected int getNumArchived() { + return (inactiveSubSwarms.size()); + } } diff --git a/src/eva2/optimization/strategies/BOA.java b/src/eva2/optimization/strategies/BOA.java index d3cfe108..3f30d00c 100644 --- a/src/eva2/optimization/strategies/BOA.java +++ b/src/eva2/optimization/strategies/BOA.java @@ -16,6 +16,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.Pair; import eva2.tools.math.BayNet; import eva2.tools.math.RNG; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -32,18 +33,17 @@ import java.util.logging.Logger; /** * Basic implementation of the Bayesian Optimization Algorithm - * + *

* Martin Pelikan, David E. Goldberg and Erick Cantu-Paz: 'BOA: The Bayesian * Optimization Algorithm' the works by Martin Pelikan and David E. Goldberg. * Genetic and Evolutionary Computation Conference (GECCO-99), pp. 525-532 * (1999) * * @author seitz - * */ public class BOA implements InterfaceOptimizer, java.io.Serializable { -// private static boolean TRACE = false; + // private static boolean TRACE = false; private static final Logger LOGGER = Logger.getLogger(BOA.class.getName()); transient private InterfacePopulationChangedEventListener m_Listener = null; private String m_Identifier = "BOA"; @@ -73,9 +73,9 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { } public BOA(int numberOfParents, int popSize, BOAScoringMethods method, - double learningSetRatio, double resampleRatio, String outputFolder, - double upperProbLimit, double lowerProbLimit, boolean printNetworks, - boolean printEdgeRate, boolean printMetrics, boolean printTimestamps) { + double learningSetRatio, double resampleRatio, String outputFolder, + double upperProbLimit, double lowerProbLimit, boolean printNetworks, + boolean printEdgeRate, boolean printMetrics, boolean printTimestamps) { this.numberOfParents = numberOfParents; this.PopSize = popSize; this.scoringMethod = method; @@ -187,7 +187,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { } else { throw new RuntimeException( "Unable to get binary representation for " - + indy.getClass()); + + indy.getClass()); } } @@ -294,7 +294,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { // add the edge to the list of possible new edges bestNetworks .add(new Pair(i, - j)); + j)); // if we have a better score } else { // delete the current possible edges @@ -302,7 +302,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { // add the edge to the list fo possible new edges bestNetworks .add(new Pair(i, - j)); + j)); // adapt the score score = tmpScore; // we could improve the network @@ -716,7 +716,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { return new String[]{"learningRatio", "resamplingRatio"}; } -// public boolean isPrintExtraOutput() { + // public boolean isPrintExtraOutput() { // return this.printExtraOutput; // } // public void setPrintExtraOutput(boolean b) { diff --git a/src/eva2/optimization/strategies/BinaryScatterSearch.java b/src/eva2/optimization/strategies/BinaryScatterSearch.java index 8096a341..a44d1d7a 100644 --- a/src/eva2/optimization/strategies/BinaryScatterSearch.java +++ b/src/eva2/optimization/strategies/BinaryScatterSearch.java @@ -22,6 +22,7 @@ import eva2.optimization.problems.B1Problem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.Pair; import eva2.tools.math.RNG; + import java.util.ArrayList; import java.util.BitSet; @@ -29,10 +30,10 @@ import java.util.BitSet; * A BinaryScatterSearch implementation taken mainly from [i]. * * @author Alex - * - * F. Gortazar, A. Duarte, M. Laguna and R. Marti: Black Box Scatter Search for - * General Classes of Binary Optimization Problems Computers and Operations - * research, vol. 37, no. 11, pp. 1977-1986 (2010) + *

+ * F. Gortazar, A. Duarte, M. Laguna and R. Marti: Black Box Scatter Search for + * General Classes of Binary Optimization Problems Computers and Operations + * research, vol. 37, no. 11, pp. 1977-1986 (2010) */ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener { @@ -92,15 +93,15 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * Create a new BinaryScatterSearch with the given Parameters * - * @param refSetS the refSetSize - * @param poolS the poolSize - * @param lowerThreshold the lower Boundary for the local Search - * @param upperThreshold the upper Boundary for the local Search - * @param perCentFirstIndGenerator how many individuals (in prospect of the - * poolSize) are generated through the first Generator - * @param perCentSecondIndGenerator how many individuals (in prospect of the - * poolSize) are generated through the second Generator - * @param prob the Problem + * @param refSetS the refSetSize + * @param poolS the poolSize + * @param lowerThreshold the lower Boundary for the local Search + * @param upperThreshold the upper Boundary for the local Search + * @param perCentFirstIndGenerator how many individuals (in prospect of the + * poolSize) are generated through the first Generator + * @param perCentSecondIndGenerator how many individuals (in prospect of the + * poolSize) are generated through the second Generator + * @param prob the Problem */ public BinaryScatterSearch( int refSetS, int poolS, double lowerThreshold, double upperThreshold, @@ -117,16 +118,16 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * Create a new BinaryScatterSearch with the given Parameters * - * @param refSetS the refSetSize - * @param poolS the poolSize - * @param lowerThreshold the lower Boundary for the local Search - * @param upperThreshold the upper Boundary for the local Search - * @param perCentFirstIndGenerator how many individuals (in prospect of the - * poolSize) are generated through the first Generator - * @param perCentSecondIndGenerator how many individuals (in prospect of the - * poolSize) are generated through the second Generator - * @param prob the Problem - * @param cross the Crossover-Operators + * @param refSetS the refSetSize + * @param poolS the poolSize + * @param lowerThreshold the lower Boundary for the local Search + * @param upperThreshold the upper Boundary for the local Search + * @param perCentFirstIndGenerator how many individuals (in prospect of the + * poolSize) are generated through the first Generator + * @param perCentSecondIndGenerator how many individuals (in prospect of the + * poolSize) are generated through the second Generator + * @param prob the Problem + * @param cross the Crossover-Operators */ public BinaryScatterSearch( int refSetS, int poolS, double lowerThreshold, double upperThreshold, @@ -226,7 +227,6 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ } /** - * * @return a new diversified Population */ private Population diversify() { @@ -234,10 +234,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ } /** - * - * @param pop the initial Population + * @param pop the initial Population * @return a diversified Population with all the Individuals in the initial - * Population + * Population */ private Population diversify(Population pop) { int numToInit = this.poolSize - pop.size(); @@ -263,8 +262,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * 000...000, then 010101...01, 101010...10, 001001001...001, * 110110110...110 and so on The returned population is evaluated. * - * @param pop the initial Population - * @return the new Population + * @param pop the initial Population + * @return the new Population */ private Population generateG1(int numToInit) { Population pop = generateG1Pop(numToInit, this.template); @@ -279,8 +278,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * 000...000, then 010101...01, 101010...10, 001001001...001, * 110110110...110 and so on * - * @param pop the initial Population - * @return the new Population + * @param pop the initial Population + * @return the new Population */ public static Population generateG1Pop(int targetSize, AbstractEAIndividual template) { boolean method1 = true; @@ -320,8 +319,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * Generate new Individuals that have the individuals of the given * Population as a base * - * @param pop the population - * @return the new Population + * @param pop the population + * @return the new Population */ private Population generateG2(Population pop, int numToInit) { int origSize = pop.size(); @@ -348,8 +347,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * Generate new Individuals that have the individuals of the given * Population as a base * - * @param pop the population - * @return the new Population + * @param pop the population + * @return the new Population */ private Population generateG3(Population pop, int numToInit) { int origSize = pop.size(); @@ -376,9 +375,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * calculate the number of individuals in the given Population that have a 1 * at the i-th position * - * @param i the position - * @param pop the population - * @return The number of individuals that have a '1' on the i-th position + * @param i the position + * @param pop the population + * @return The number of individuals that have a '1' on the i-th position */ private static double calculateNumberOFPI1(int i, Population pop) { int result = 0; @@ -396,9 +395,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * calculate the number of individuals in the given Population that have a 0 * at the i-th position * - * @param i the position - * @param pop the population - * @return The number of individuals that have a '0' on the i-th position + * @param i the position + * @param pop the population + * @return The number of individuals that have a '0' on the i-th position */ private static double calculateNumberOFPI0(int i, Population pop) { int result = 0; @@ -426,9 +425,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * calculate the sum of all the FitnessValues of the individuals that have a * '0' at the i-th position * - * @param i the position - * @param pop the population - * @return the sum + * @param i the position + * @param pop the population + * @return the sum */ private static double calculateSumPI0(int i, Population pop) { double result = 0; @@ -446,9 +445,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * calculate the sum of all the FitnessValues of the individuals that have a * '0' at the i-th position * - * @param i the position - * @param pop the population - * @return the sum + * @param i the position + * @param pop the population + * @return the sum */ private static double calculateSumPI1(int i, Population pop) { double result = 0; @@ -468,9 +467,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * the Bit is probably set correct. If the bit is set to '0' and you get a * low score then the Bit is probably set correct. * - * @param i the position - * @param pop the population - * @return the score + * @param i the position + * @param pop the population + * @return the score */ public static double score(int i, Population pop) { double sumPI1 = calculateSumPI1(i, pop); @@ -484,7 +483,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * calculate the first RefSet with the given Population as a reference Point * - * @param pop the generated Pool + * @param pop the generated Pool */ private void initRefSet(Population pop) { this.problem.evaluatePopulationStart(this.refSet); @@ -506,8 +505,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * Update the reference Set * - * @param replaceWorstHalf replaces the worst half of the RefSet if set - * @return has the Population changed + * @param replaceWorstHalf replaces the worst half of the RefSet if set + * @return has the Population changed */ private boolean refSetUpdate(boolean replaceWorstHalf) { boolean refSetChanged = false; @@ -559,8 +558,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * Order the given List according to the score of the given values * - * @param list the initial List - * @return the ordered List + * @param list the initial List + * @return the ordered List */ private ArrayList order(ArrayList list) { ArrayList result = new ArrayList(); @@ -586,8 +585,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * Do a local search * - * @param indy the individual that will be improved - * @return the new improved individual + * @param indy the individual that will be improved + * @return the new improved individual */ private AbstractEAIndividual improve(AbstractEAIndividual indy) { AbstractEAIndividual tmpIndy = (AbstractEAIndividual) indy.clone(); @@ -651,7 +650,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * Combine all the individuals in the reference Set (always 2) * - * @return the List with all the combinations + * @return the List with all the combinations */ public ArrayList generateSubsets() { ArrayList result = new ArrayList(); @@ -669,8 +668,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * combine the first individual with the second one * - * @param pop the Population - * @return the new Individual + * @param pop the Population + * @return the new Individual */ public AbstractEAIndividual combineSolution(Population pop) { AbstractEAIndividual result = (AbstractEAIndividual) template.clone(); @@ -696,9 +695,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ /** * look if the individual is already in the population * - * @param indy the Individual to be tested - * @param pop the population in where to search - * @return is the individual already in the Population + * @param indy the Individual to be tested + * @param pop the population in where to search + * @return is the individual already in the Population */ private boolean contains(InterfaceDataTypeBinary indy, Population pop) { if (pop.size() <= 0) { diff --git a/src/eva2/optimization/strategies/CBNPSO.java b/src/eva2/optimization/strategies/CBNPSO.java index 4703cf4e..e2467996 100644 --- a/src/eva2/optimization/strategies/CBNPSO.java +++ b/src/eva2/optimization/strategies/CBNPSO.java @@ -16,20 +16,21 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.optimization.problems.InterfaceProblemDouble; import eva2.tools.EVAERROR; import eva2.tools.ToolBox; + import java.io.Serializable; public class CBNPSO extends ClusterBasedNichingEA implements Serializable { - private boolean forceUpperClustDist = true; - - /** - * Standard constructur with fixed frequency (no fitness threshold based frequency adaption) - */ - public CBNPSO() { - this(false); - } - - public CBNPSO(boolean threshAdaption) { - this(10, 15, 0.001, 1e-10, 15, 100, threshAdaption); + private boolean forceUpperClustDist = true; + + /** + * Standard constructur with fixed frequency (no fitness threshold based frequency adaption) + */ + public CBNPSO() { + this(false); + } + + public CBNPSO(boolean threshAdaption) { + this(10, 15, 0.001, 1e-10, 15, 100, threshAdaption); // super(); // setDifferentiationCA(new ClusteringDensityBased(getClusterDiffDist(), 10, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); // setMergingCA(new ClusteringDensityBased(0.001, 3, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); @@ -41,226 +42,226 @@ public class CBNPSO extends ClusterBasedNichingEA implements Serializable { // setParameterControl(defAdpt); // if (threshAdaption) addParameterControl(getDefaultThreshAdaption()); // setPopulationSize(100); - } - - public CBNPSO(int minSpecSize, int maxSpecSize, double sigmaMerge, double epsilonConv, int haltingWindow, int popSize, boolean threshAdaption) { - super(); - setDifferentiationCA(new ClusteringDensityBased(getClusterDiffDist(), minSpecSize, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); - setMergingCA(new ClusteringDensityBased(sigmaMerge, 3, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); - setEpsilonBound(epsilonConv); - setHaltingWindow(haltingWindow); - setMaxSpeciesSize(maxSpecSize); - setOptimizer(new ParticleSwarmOptimization(popSize, 2.05, 2.05, PSOTopologyEnum.grid, 2)); - ParamAdaption[] defAdpt = new ParamAdaption[]{getDefaultSinusoidalAdaption()}; - setParameterControl(defAdpt); - if (threshAdaption) { - addParameterControl(getDefaultThreshAdaption()); - } - setPopulationSize(popSize); - } - - private ParamAdaption getDefaultSinusoidalAdaption() { - return new SinusoidalParamAdaption(0.1, 1., 10000, 0, "clusterDiffDist"); - } + } - private ParamAdaption getDefaultThreshAdaption() { - return new CbpsoFitnessThresholdBasedAdaption(); - } - - @Override - public void setProblem(InterfaceOptimizationProblem problem) { - super.setProblem(problem); - if (problem instanceof AbstractProblemDouble) { - AbstractProblemDouble dblProb = ((AbstractProblemDouble)problem); - adaptMinMaxSwarmSizeByDim(dblProb); - } - } + public CBNPSO(int minSpecSize, int maxSpecSize, double sigmaMerge, double epsilonConv, int haltingWindow, int popSize, boolean threshAdaption) { + super(); + setDifferentiationCA(new ClusteringDensityBased(getClusterDiffDist(), minSpecSize, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); + setMergingCA(new ClusteringDensityBased(sigmaMerge, 3, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); + setEpsilonBound(epsilonConv); + setHaltingWindow(haltingWindow); + setMaxSpeciesSize(maxSpecSize); + setOptimizer(new ParticleSwarmOptimization(popSize, 2.05, 2.05, PSOTopologyEnum.grid, 2)); + ParamAdaption[] defAdpt = new ParamAdaption[]{getDefaultSinusoidalAdaption()}; + setParameterControl(defAdpt); + if (threshAdaption) { + addParameterControl(getDefaultThreshAdaption()); + } + setPopulationSize(popSize); + } - /** - * Return the period of the sinusoidal sigma adaption or -1 if not applicable. - * - * @param p - */ - public int getSigmaAdaptionPeriod() { - ParamAdaption[] prmAd = getParameterControl(); - for (int i=0; i0) { - String addInfo="adpt"; - if (getParameterControl()[0] instanceof SinusoidalParamAdaption) { - addInfo="SinT"+((SinusoidalParamAdaption)getParameterControl()[0]).getIterationPeriod(); - } - else if (getParameterControl()[0] instanceof LinearParamAdaption) { - addInfo="Lin"+((LinearParamAdaption)getParameterControl()[0]).getStartV()+"-"+((LinearParamAdaption)getParameterControl()[0]).getEndV(); - } - return "CBN-PSO-"+addInfo; - } else { - return "CBN-PSO"; - } - } - - public static String globalInfo() { - return "A CBN-EA variant employing PSO and dynamic variation of the clustering parameter by default."; - } + private ParamAdaption getDefaultThreshAdaption() { + return new CbpsoFitnessThresholdBasedAdaption(); + } - public void setForceUpperClustDist(boolean forceUpperClustDist) { - this.forceUpperClustDist = forceUpperClustDist; - } - public boolean isForceUpperClustDist() { - return forceUpperClustDist; - } - public String forceUpperClustDistTipText() { - return "Activate to force cluster distance to be maximal corresponding to the CBN-PSO settings."; - } - - /** - * Return the ratio of interesting solutions per archived solutions, which - * is in [0,1] if any solutions have been identified, or -1 if the archive - * is empty. - * - * @param cbpso - * @param pop - * @param iteration - * @param maxIteration - * @return - */ - public double getInterestingSolutionRatio() { - InterfaceOptimizationProblem prob = getProblem(); - double fitThres = 100; - if (prob instanceof InterfaceInterestingHistogram) { - fitThres = ((InterfaceInterestingHistogram)prob).getHistogram().getUpperBound(); - } else { - EVAERROR.errorMsgOnce("Warning, problem does not define a fitness threshold!"); - } - - SolutionSet solSet = getAllSolutions(); - Population archived = solSet.getSolutions(); - Population interesting = archived.filterByFitness(fitThres, 0); - -// Population archived = getArchivedSolutions(); -// Population interesting = archived.filterByFitness(fitThres, 0); - - if (archived.size()>0) { - return ((double)interesting.size())/((double)archived.size()); - } else { - return -1; - } - } + @Override + public void setProblem(InterfaceOptimizationProblem problem) { + super.setProblem(problem); + if (problem instanceof AbstractProblemDouble) { + AbstractProblemDouble dblProb = ((AbstractProblemDouble) problem); + adaptMinMaxSwarmSizeByDim(dblProb); + } + } - @Override - public String[] getAdditionalDataHeader() { - String[] addVals = {"interestingRatio"}; - if (getCurrentPeriod()>=0) { - addVals = new String[]{"interestingRatio", "adaptPeriod"}; - } - return ToolBox.appendArrays(super.getAdditionalDataHeader(), addVals); - } - - @Override - public String[] getAdditionalDataInfo() { - String[] addVals = {"Ratio of interesting solutions within all archived solutions"}; - if (getCurrentPeriod()>=0) { - addVals = new String[]{"Ratio of interesting solutions within all archived solutions", - "Current sigma adaptation period"}; - } - return ToolBox.appendArrays(super.getAdditionalDataInfo(), addVals); - } - - /** - * Retrieve the current period of the sinusoidal sigma adaption (in case it is controlled by a threshold adaption) - * or -1 if this does not apply. - * - * @return - */ - private int getCurrentPeriod() { - ParamAdaption[] adaptors = super.getParameterControl(); - SinusoidalParamAdaption sinA=null; - CbpsoFitnessThresholdBasedAdaption ftA=null; - if (adaptors!=null) { - for (int i = 0; i=0) { - addVals = new Object[]{getInterestingSolutionRatio(), freq}; + /** + * Set the period of the sinusoidal sigma adaption, if a fitting ParamAdaption + * instance is found. Otherwise, nothing happens. + * + * @param p + */ + public void setSigmaAdaptionPeriod(int p) { + ParamAdaption[] prmAd = getParameterControl(); + for (int i = 0; i < prmAd.length; i++) { + if (prmAd[i] instanceof SinusoidalParamAdaption) { + if (prmAd[i].getControlledParam().equals("clusterDiffDist")) { + ((SinusoidalParamAdaption) prmAd[i]).setIterationPeriod(p); + return; + } } - else { - addVals = new Object[]{getInterestingSolutionRatio()}; + } + System.err.println("Error: unable to set adaption period " + p + ", no sinusoidal adaption instance found."); + } + + public void setSigmaAdaptionShift(int s) { + ParamAdaption[] prmAd = getParameterControl(); + for (int i = 0; i < prmAd.length; i++) { + if (prmAd[i] instanceof SinusoidalParamAdaption) { + if (prmAd[i].getControlledParam().equals("clusterDiffDist")) { + ((SinusoidalParamAdaption) prmAd[i]).setInitialShift(s); + return; + } } - return ToolBox.appendArrays(super.getAdditionalDataValue(pop), addVals); - } + } + System.err.println("Error: unable to set adaption shift " + s + ", no sinusoidal adaption instance found."); + } + + private void adaptMinMaxSwarmSizeByDim(AbstractProblemDouble dblProb) { + // TODO Auto-generated method stub + + } + + @Override + public void init() { + super.init(); + if (getProblem() instanceof InterfaceProblemDouble) { + if (isForceUpperClustDist()) { + setUpperBoundClustDiff((InterfaceProblemDouble) getProblem()); + } + } else { + System.err.println("Can set upper bound of clustering parameter only for AbstractProblemDouble types, not for " + getProblem().getClass().getName()); + } + } + + @Override + public String getName() { + if (getParameterControl().length > 0) { + String addInfo = "adpt"; + if (getParameterControl()[0] instanceof SinusoidalParamAdaption) { + addInfo = "SinT" + ((SinusoidalParamAdaption) getParameterControl()[0]).getIterationPeriod(); + } else if (getParameterControl()[0] instanceof LinearParamAdaption) { + addInfo = "Lin" + ((LinearParamAdaption) getParameterControl()[0]).getStartV() + "-" + ((LinearParamAdaption) getParameterControl()[0]).getEndV(); + } + return "CBN-PSO-" + addInfo; + } else { + return "CBN-PSO"; + } + } + + public static String globalInfo() { + return "A CBN-EA variant employing PSO and dynamic variation of the clustering parameter by default."; + } + + public void setForceUpperClustDist(boolean forceUpperClustDist) { + this.forceUpperClustDist = forceUpperClustDist; + } + + public boolean isForceUpperClustDist() { + return forceUpperClustDist; + } + + public String forceUpperClustDistTipText() { + return "Activate to force cluster distance to be maximal corresponding to the CBN-PSO settings."; + } + + /** + * Return the ratio of interesting solutions per archived solutions, which + * is in [0,1] if any solutions have been identified, or -1 if the archive + * is empty. + * + * @param cbpso + * @param pop + * @param iteration + * @param maxIteration + * @return + */ + public double getInterestingSolutionRatio() { + InterfaceOptimizationProblem prob = getProblem(); + double fitThres = 100; + if (prob instanceof InterfaceInterestingHistogram) { + fitThres = ((InterfaceInterestingHistogram) prob).getHistogram().getUpperBound(); + } else { + EVAERROR.errorMsgOnce("Warning, problem does not define a fitness threshold!"); + } + + SolutionSet solSet = getAllSolutions(); + Population archived = solSet.getSolutions(); + Population interesting = archived.filterByFitness(fitThres, 0); + +// Population archived = getArchivedSolutions(); +// Population interesting = archived.filterByFitness(fitThres, 0); + + if (archived.size() > 0) { + return ((double) interesting.size()) / ((double) archived.size()); + } else { + return -1; + } + } + + @Override + public String[] getAdditionalDataHeader() { + String[] addVals = {"interestingRatio"}; + if (getCurrentPeriod() >= 0) { + addVals = new String[]{"interestingRatio", "adaptPeriod"}; + } + return ToolBox.appendArrays(super.getAdditionalDataHeader(), addVals); + } + + @Override + public String[] getAdditionalDataInfo() { + String[] addVals = {"Ratio of interesting solutions within all archived solutions"}; + if (getCurrentPeriod() >= 0) { + addVals = new String[]{"Ratio of interesting solutions within all archived solutions", + "Current sigma adaptation period"}; + } + return ToolBox.appendArrays(super.getAdditionalDataInfo(), addVals); + } + + /** + * Retrieve the current period of the sinusoidal sigma adaption (in case it is controlled by a threshold adaption) + * or -1 if this does not apply. + * + * @return + */ + private int getCurrentPeriod() { + ParamAdaption[] adaptors = super.getParameterControl(); + SinusoidalParamAdaption sinA = null; + CbpsoFitnessThresholdBasedAdaption ftA = null; + if (adaptors != null) { + for (int i = 0; i < adaptors.length; i++) { + if (adaptors[i] instanceof SinusoidalParamAdaption) { + sinA = (SinusoidalParamAdaption) adaptors[i]; + } else if (adaptors[i] instanceof CbpsoFitnessThresholdBasedAdaption) { + ftA = (CbpsoFitnessThresholdBasedAdaption) adaptors[i]; + } + } + } + if (sinA != null && (ftA != null)) { + return sinA.getIterationPeriod(); + } else { + return -1; + } + } + + @Override + public Object[] getAdditionalDataValue(PopulationInterface pop) { + Object[] addVals = null; + double freq = getCurrentPeriod(); + if (freq >= 0) { + addVals = new Object[]{getInterestingSolutionRatio(), freq}; + } else { + addVals = new Object[]{getInterestingSolutionRatio()}; + } + return ToolBox.appendArrays(super.getAdditionalDataValue(pop), addVals); + } } diff --git a/src/eva2/optimization/strategies/CHCAdaptiveSearchAlgorithm.java b/src/eva2/optimization/strategies/CHCAdaptiveSearchAlgorithm.java index 2d3a4662..cfd1ae68 100644 --- a/src/eva2/optimization/strategies/CHCAdaptiveSearchAlgorithm.java +++ b/src/eva2/optimization/strategies/CHCAdaptiveSearchAlgorithm.java @@ -12,6 +12,7 @@ import eva2.optimization.population.SolutionSet; import eva2.optimization.problems.B1Problem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; + import java.util.BitSet; /** @@ -22,7 +23,7 @@ import java.util.BitSet; * implementation of the CHC Adaptive Search Algorithm (Cross generational * elitist selection, Heterogeneous recombination and Cataclysmic mutation). * Citation: - * + *

* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer * Architecture * @@ -81,7 +82,7 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -370,6 +371,7 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S // public String normationMethodTipText() { // return "Select the normation method."; // } + /** * Enable/disable elitism. * diff --git a/src/eva2/optimization/strategies/ClusterBasedNichingEA.java b/src/eva2/optimization/strategies/ClusterBasedNichingEA.java index 58c3ffba..cea0356a 100644 --- a/src/eva2/optimization/strategies/ClusterBasedNichingEA.java +++ b/src/eva2/optimization/strategies/ClusterBasedNichingEA.java @@ -35,6 +35,7 @@ import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointSet; import eva2.tools.math.Mathematics; + import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; @@ -44,16 +45,16 @@ import java.util.PriorityQueue; /** * The infamous clustering based niching EA, still under construction. It should * be able to identify and track multiple global/local optima at the same time. - * + *

* Notes: For std. GA, the mutation rate may have to reduced, because the * initial step size tends to be rel. large and easily disperse clustered * species (so that they fall below the minimum swarm size and the local optimum * is lost). - * + *

* For the CBN-PSO remember to use the IndividualDataMetric so that the * remembered positions are used for clustering (which are rel. stable - so that * species clustering actually makes sense). - * + *

* Copyright: Copyright (c) 2010 Company: University of Tuebingen, Computer * Architecture * @@ -227,7 +228,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -338,7 +339,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } public static void plotLine(TopoPlot tp, AbstractEAIndividual indy1, - AbstractEAIndividual indy2) { + AbstractEAIndividual indy2) { // DPointSet popRep; double[] pos1, pos2; if (indy1 instanceof InterfaceDataTypeDouble) { @@ -382,7 +383,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis //@todo: crossover between species is to be implemented optimizationProblem.initializePopulation(result); optimizationProblem.evaluate(result); - optimizer.setPopulation(result); // for some initialization by the optimizer, such as PSO memory + optimizer.setPopulation(result); // for some initialization by the optimizer, such as PSO memory // capMutationRate(result, RNG.randomDouble(0.001, 0.1)); return result; } @@ -459,7 +460,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis * @param firstIndy * @param secIndy * @return true if the second individual has improved in relation to the - * first one + * first one */ private boolean testSecondForImprovement(AbstractEAIndividual firstIndy, AbstractEAIndividual secIndy) { if (epsilonBound > 0) { @@ -551,7 +552,8 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } if (TRACE) { System.out.println("NumIndies: " + countIndies); - }; + } + ; if (this.showCycle > 0) { if (undifferentiatedPopulation.getGeneration() <= 1) { plot(undifferentiatedPopulation.getGeneration()); @@ -900,7 +902,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis /** * Initialize the clustering method for differentiation. - * */ private void initClustering() { if (getClusterDiffDist() > 0) { // assume that it should be set @@ -931,6 +932,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // pop.synchSize(); // return pop; // } + /** * Replace the undifferentiated population with the given one. * @@ -1041,11 +1043,12 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // } // return k; // } + /** * This method allows an optimizer to register a change in the optimizer. * * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. + * @param name Could be used to indicate the nature of the event. */ @Override public void registerPopulationStateChanged(Object source, String name) { @@ -1209,6 +1212,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // public String applyClearingTipText() { // return "Clearing removes all but the best individuals from an identified species."; // } + /** * This method allows you to set/get the switch that toggles the use of * species convergence. @@ -1292,11 +1296,12 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // public String useArchiveTipText() { // return "Toggle usage of an archive where converged species are saved and the individuals reinitialized."; // } + /** * Determines how often species differentation/convergence is performed. * * @return This number gives the generations when specification is - * performed. + * performed. */ public int getSpeciesCycle() { return this.speciesCycle; @@ -1314,7 +1319,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis * TDetermines how often show is performed. * * @return This number gives the generations when specification is - * performed. + * performed. */ public int getShowCycle() { return this.showCycle; @@ -1358,6 +1363,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // public double getMuLambdaRatio() { // return muLambdaRatio; // } + /** * This is now set if an ES is set as optimizer. * @@ -1412,6 +1418,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // this.distrDefaultStrength = distrDefaultStrength; // distraction.setDefaultStrength(distrDefaultStrength); // } + /** * @return the sleepTime */ @@ -1451,35 +1458,35 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis @Override public String[] getAdditionalDataHeader() { return new String[]{"numUndiff", "numActSpec", "avgSpecMeas", "numArchived", - "archivedMedCorr", "archivedMeanDist", "numCollisions", "clustSig"}; + "archivedMedCorr", "archivedMeanDist", "numCollisions", "clustSig"}; } @Override public String[] getAdditionalDataInfo() { return new String[]{ - "The number of exploring individuals in the main population", - "The number of active species (sub-populations)", - "The average of the mean distance of individuals within a species", - "The number of stored potential local optima", - "The median correlation of archived solutions", - "The mean distance of archived solutions", - "The number of collisions events that happened so far", - "The clustering distance" - }; + "The number of exploring individuals in the main population", + "The number of active species (sub-populations)", + "The average of the mean distance of individuals within a species", + "The number of stored potential local optima", + "The median correlation of archived solutions", + "The mean distance of archived solutions", + "The number of collisions events that happened so far", + "The clustering distance" + }; } @Override public Object[] getAdditionalDataValue(PopulationInterface pop) { // int actives = countActiveSpec(); return new Object[]{ - undifferentiatedPopulation.size(), - species.size(), - getAvgSpeciesMeasures()[0], - poulationArchive.size(), - poulationArchive.getCorrelations()[3], - poulationArchive.getPopulationMeasures()[0], - collisions, - getClusterDiffDist()}; + undifferentiatedPopulation.size(), + species.size(), + getAvgSpeciesMeasures()[0], + poulationArchive.size(), + poulationArchive.getCorrelations()[3], + poulationArchive.getPopulationMeasures()[0], + collisions, + getClusterDiffDist()}; // return undifferentiatedPopulation.size() + " \t " + species.size() + " \t " + BeanInspector.toString(getAvgSpeciesMeasures()[0]) + " \t " + (poulationArchive.size()); } @@ -1534,7 +1541,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis return new String[]{"mergingCA", "differentiationCA"}; } -// public void setHistComparator(AbstractEAIndividualComparator histComparator) { + // public void setHistComparator(AbstractEAIndividualComparator histComparator) { // this.histComparator = histComparator; // } public AbstractEAIndividualComparator getHistComparator() { @@ -1561,7 +1568,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis * Calculate the clustering parameter in such a way that about one q-th part * of the range of the given problem is within one hyper sphere of the * clustering parameter. - * + *

* For certain types of parameter adaption schemes, this automatically sets * the upper limit if the clustering parameter is controlled. * diff --git a/src/eva2/optimization/strategies/ClusteringHillClimbing.java b/src/eva2/optimization/strategies/ClusteringHillClimbing.java index 71e51c8b..705d7be5 100644 --- a/src/eva2/optimization/strategies/ClusteringHillClimbing.java +++ b/src/eva2/optimization/strategies/ClusteringHillClimbing.java @@ -14,6 +14,7 @@ import eva2.optimization.problems.F1Problem; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.Pair; + import java.io.Serializable; /** @@ -24,7 +25,7 @@ import java.io.Serializable; * a cluster, only a subset of representatives of the cluster is taken over to * the next HC step while the rest is discarded. This means that the population * size may be reduced. - * + *

* As soon as the improvement by HC lies below a threshold, the mutation step * size is decreased. If the step size is decreased below a certain threshold, * the current population is stored to an archive and reinitialized. Thus, the @@ -32,7 +33,6 @@ import java.io.Serializable; * than the population size. * * @author mkron - * */ public class ClusteringHillClimbing implements InterfacePopulationChangedEventListener, InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { @@ -46,7 +46,7 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi private int hcEvalCycle = 1000; private int initialPopSize = 100; private int loopCnt = 0; -// private int baseEvalCnt = 0; + // private int baseEvalCnt = 0; private int notifyGuiEvery = 50; private double sigmaClust = 0.01; private double minImprovement = 0.000001; @@ -156,7 +156,7 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override diff --git a/src/eva2/optimization/strategies/DifferentialEvolution.java b/src/eva2/optimization/strategies/DifferentialEvolution.java index 57ac84c2..f790bd38 100644 --- a/src/eva2/optimization/strategies/DifferentialEvolution.java +++ b/src/eva2/optimization/strategies/DifferentialEvolution.java @@ -29,7 +29,6 @@ import java.util.Vector; * crossover operators selected. Added aging mechanism to provide for * dynamically changing problems. If an individual reaches the age limit, it is * doomed and replaced by the next challenge vector, even if its worse. - * */ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serializable { @@ -63,7 +62,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * A constructor. - * */ public DifferentialEvolution() { // sets DE2 as default @@ -121,7 +119,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -210,7 +208,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial private double[] fetchDeltaCurrentRandom(Population pop, InterfaceDataTypeDouble indy) { double[] x1, x2; double[] result; - boolean isEmpty; + boolean isEmpty; int iterations = 0; @@ -258,7 +256,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * This method will return the delta vector to the best individual * - * @param pop The population to choose the best from + * @param pop The population to choose the best from * @param indy The current individual * @return the delta vector */ @@ -312,6 +310,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // result[1] = indy2.getDGenotype(); // return result; // } + /** * This method will generate one new individual from the given population * @@ -523,7 +522,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial * slightly worse for schemes that rely on current best individuals, because * improvements are not immediately incorporated as in the steady state DE. * However it may be easier to parallelize. - * */ public void optimizeGenerational() { // AbstractEAIndividual indy = null, orig; @@ -571,7 +569,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } else { parentIndex = RNG.randomInt(0, this.m_Population.size() - 1); } - if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one + if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one m_Population.replaceIndividualAt(nextDoomed, indy); nextDoomed = getNextDoomed(m_Population, nextDoomed + 1); } else { @@ -633,7 +631,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // else indy = this.generateNewIndividual(this.m_Population, -1); this.m_Problem.evaluate(indy); this.m_Population.incrFunctionCalls(); - if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one + if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one m_Population.replaceIndividualAt(nextDoomed, indy); nextDoomed = getNextDoomed(m_Population, nextDoomed + 1); } else { @@ -710,9 +708,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial * younger, -1 is returned. The start index of the search may be provided to * make iterative search efficient. * - * @param pop Population to search - * @param startIndex index to start the search from - * @return index of an overaged individual or -1 + * @param pop Population to search + * @param startIndex index to start the search from + * @return index of an overaged individual or -1 */ protected int getNextDoomed(Population pop, int startIndex) { if (maximumAge > 0) { @@ -963,7 +961,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * @return the maximumAge - * */ public int getMaximumAge() { return maximumAge; @@ -971,7 +968,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * @param maximumAge the maximumAge to set - * */ public void setMaximumAge(int maximumAge) { this.maximumAge = maximumAge; @@ -1013,7 +1009,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial return "If true, values for k, f, lambda are randomly sampled around +/- 20% of the given values."; } -// public boolean isCyclePop() { + // public boolean isCyclePop() { // return cyclePop; // } // @@ -1062,7 +1058,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * @return the maximumAge - * */ public boolean isReEvaluate() { return reEvaluate; @@ -1070,7 +1065,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial /** * @param maximumAge the maximumAge to set - * */ public void setReEvaluate(boolean reEvaluate) { this.reEvaluate = reEvaluate; diff --git a/src/eva2/optimization/strategies/DynamicParticleSwarmOptimization.java b/src/eva2/optimization/strategies/DynamicParticleSwarmOptimization.java index d5f79245..cac2c19a 100644 --- a/src/eva2/optimization/strategies/DynamicParticleSwarmOptimization.java +++ b/src/eva2/optimization/strategies/DynamicParticleSwarmOptimization.java @@ -11,50 +11,49 @@ import eva2.tools.SelectedTag; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; -/** +/** * This extends our particle swarm implementation to dynamic optimization problems. - * + *

* User: marcekro * Date: 2007 * Time: 11:23:21 */ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization { - private boolean envHasChanged = false; + private boolean envHasChanged = false; // private boolean useCurrentFit = true; /** * switch for the speed adaptation mechanism */ - protected boolean doSpeedAdaptation = false; - private double phi0 = 0.005; - private double phi3 = 0.0; - private double highEnergyRaise = 2.; - private double highEnergyRatio = .2; - private double quantumRatio = 0.1; - private double quantumCloudDia = 0.2; + protected boolean doSpeedAdaptation = false; + private double phi0 = 0.005; + private double phi3 = 0.0; + private double highEnergyRaise = 2.; + private double highEnergyRatio = .2; + private double quantumRatio = 0.1; + private double quantumCloudDia = 0.2; // the detectAnchor may be an Individual ID which will be ommitted by the update to check for env. changes. - private int detectAnchor = 0; - private double[] detectFit = null; - /** + private int detectAnchor = 0; + private double[] detectFit = null; + /** * the change detection strategy */ - protected SelectedTag changeDetectStrategy; - - private double maxSpeedLimit = 0.1; - private double minSpeedLimit = .003; - - private boolean plotBestOnly = false; - private transient double[] lastBestPlot = null; - - /** - * constant indication quantum particles - */ - public static final int quantumType = 1; + protected SelectedTag changeDetectStrategy; - /** - * A standard constructor. - * - */ + private double maxSpeedLimit = 0.1; + private double minSpeedLimit = .003; + + private boolean plotBestOnly = false; + private transient double[] lastBestPlot = null; + + /** + * constant indication quantum particles + */ + public static final int quantumType = 1; + + /** + * A standard constructor. + */ public DynamicParticleSwarmOptimization() { super(); this.changeDetectStrategy = new SelectedTag("Random Anchor", "Assume change", "Assume no change"); @@ -62,23 +61,23 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization /** * The copy constructor. - * + * * @param a another DynPSO object */ public DynamicParticleSwarmOptimization(DynamicParticleSwarmOptimization a) { - super(a); - envHasChanged = a.envHasChanged; - doSpeedAdaptation = a.doSpeedAdaptation; - phi0 = a.phi0; - highEnergyRaise = a.highEnergyRaise; - highEnergyRatio = a.highEnergyRatio; - quantumRatio = a.quantumRatio; - quantumCloudDia = a.quantumCloudDia; - detectAnchor = a.detectAnchor; - detectFit = a.detectFit; - maxSpeedLimit = a.maxSpeedLimit; - minSpeedLimit = a.minSpeedLimit; - changeDetectStrategy.setSelectedAs(a.changeDetectStrategy); + super(a); + envHasChanged = a.envHasChanged; + doSpeedAdaptation = a.doSpeedAdaptation; + phi0 = a.phi0; + highEnergyRaise = a.highEnergyRaise; + highEnergyRatio = a.highEnergyRatio; + quantumRatio = a.quantumRatio; + quantumCloudDia = a.quantumCloudDia; + detectAnchor = a.detectAnchor; + detectFit = a.detectFit; + maxSpeedLimit = a.maxSpeedLimit; + minSpeedLimit = a.minSpeedLimit; + changeDetectStrategy.setSelectedAs(a.changeDetectStrategy); } @Override @@ -91,12 +90,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization */ @Override public void hideHideable() { - super.hideHideable(); - setQuantumRatio(quantumRatio); - setDoSpeedAdaptation(doSpeedAdaptation); - setHighEnergyRatio(highEnergyRatio); + super.hideHideable(); + setQuantumRatio(quantumRatio); + setDoSpeedAdaptation(doSpeedAdaptation); + setHighEnergyRatio(highEnergyRatio); } - + /** * Adapts the swarm speed limit to give room to the favourite tracking speed. This is currently * done by approaching a speed limit value at two times the EMA speed. @@ -104,404 +103,404 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization * @param range */ public void adaptTrackingSpeed(double[][] range) { - double incFact = 1.1; - double decFact = .97; - double upperChgLim = .6; - double lowerChgLim = .4; - double normEmaSpd = getRelativeEMASpeed(range); - double spdLim = getSpeedLimit(); - - if (normEmaSpd > (upperChgLim*spdLim)) { + double incFact = 1.1; + double decFact = .97; + double upperChgLim = .6; + double lowerChgLim = .4; + double normEmaSpd = getRelativeEMASpeed(range); + double spdLim = getSpeedLimit(); + + if (normEmaSpd > (upperChgLim * spdLim)) { setSpeedLimit(Math.min(maxSpeedLimit, incFact * spdLim)); - } - else if (normEmaSpd < (lowerChgLim*spdLim)) { - setSpeedLimit(Math.max(minSpeedLimit, decFact*spdLim)); + } else if (normEmaSpd < (lowerChgLim * spdLim)) { + setSpeedLimit(Math.max(minSpeedLimit, decFact * spdLim)); } } - + /** * Returns the favourite speed-limit for the current average speed, which currently is - * twice the EMA speed. Range is required to calculate the speed relative to the playground size. + * twice the EMA speed. Range is required to calculate the speed relative to the playground size. * - * @param range range values for the optimization problem - * @return the favourite speed limit. + * @param range range values for the optimization problem + * @return the favourite speed limit. */ public double getFavTrackingSpeed(double[][] range) { - return 2*Mathematics.getRelativeLength(getEMASpeed(), range); + return 2 * Mathematics.getRelativeLength(getEMASpeed(), range); } - /** + /** * This method will update a quantum individual. - * - * @param index The individual to update. - * @param pop The current population. - * @param best The best individual found so far. + * + * @param index The individual to update. + * @param pop The current population. + * @param best The best individual found so far. */ private void updateQuantumIndividual(int index, AbstractEAIndividual indy, Population pop) { - InterfaceDataTypeDouble endy = (InterfaceDataTypeDouble) indy; + InterfaceDataTypeDouble endy = (InterfaceDataTypeDouble) indy; // search for the local best position - - double[] localBestPosition; - double[] position = endy.getDoubleData(); - + + double[] localBestPosition; + double[] position = endy.getDoubleData(); + localBestPosition = findNeighbourhoodOptimum(index, pop); - double[] newPos = new double[position.length]; - double[][] range = endy.getDoubleRange(); - + double[] newPos = new double[position.length]; + double[][] range = endy.getDoubleRange(); + System.arraycopy(localBestPosition, 0, newPos, 0, newPos.length); double[] rand = getNormalRandVect(position.length, range, quantumCloudDia); //double[] rand = getUniformRandVect(position.length, range); - - Mathematics.vvAdd(newPos, rand, newPos); - if (m_CheckRange) { - Mathematics.projectToRange(newPos, range); - } - - if (indy instanceof InterfaceDataTypeDouble) { - ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(newPos); + + Mathematics.vvAdd(newPos, rand, newPos); + if (m_CheckRange) { + Mathematics.projectToRange(newPos, range); } - else { + + if (indy instanceof InterfaceDataTypeDouble) { + ((InterfaceDataTypeDouble) indy).SetDoubleGenotype(newPos); + } else { endy.SetDoubleGenotype(newPos); - } - - resetFitness(indy); - - plotIndy(position, null, (Integer)(indy.getData(indexKey))); + } + + resetFitness(indy); + + plotIndy(position, null, (Integer) (indy.getData(indexKey))); // if (this.m_Show) { // this.m_Plot.setUnconnectedPoint(position[0], position[1], (Integer)(indy.getData(indexKey))); - //this.m_Plot.setConnectedPoint(curPosition[0] + curVelocity[0], curPosition[1] + curVelocity[1], index+1); + //this.m_Plot.setConnectedPoint(curPosition[0] + curVelocity[0], curPosition[1] + curVelocity[1], index+1); // } //System.out.println("quantum particle " + index + " set to " + newPos[0] + "/" + newPos[1]); } - + private void plotBestIndy() { - if (m_Plot != null) { - double[] curPosition = ((InterfaceDataTypeDouble)m_Population.getBestEAIndividual()).getDoubleData(); - - if (lastBestPlot != null) { + if (m_Plot != null) { + double[] curPosition = ((InterfaceDataTypeDouble) m_Population.getBestEAIndividual()).getDoubleData(); + + if (lastBestPlot != null) { this.m_Plot.setConnectedPoint(lastBestPlot[0], lastBestPlot[1], 0); } - this.m_Plot.setConnectedPoint(curPosition[0], curPosition[1], 0); - lastBestPlot = curPosition.clone(); - } + this.m_Plot.setConnectedPoint(curPosition[0], curPosition[1], 0); + lastBestPlot = curPosition.clone(); + } } - + @Override - protected void plotIndy(double[] curPosition, double[] curVelocity, int index) { - if (this.m_Show) { - if (plotBestOnly) { - if (index != ((Integer)(m_Population.getBestEAIndividual().getData(indexKey)))) { - return; - } - else { + protected void plotIndy(double[] curPosition, double[] curVelocity, int index) { + if (this.m_Show) { + if (plotBestOnly) { + if (index != ((Integer) (m_Population.getBestEAIndividual().getData(indexKey)))) { + return; + } else { // if (lastBestPlot != null) this.m_Plot.setConnectedPoint(lastBestPlot[0], lastBestPlot[1], index); // this.m_Plot.setConnectedPoint(curPosition[0], curPosition[1], index); - this.m_Plot.setUnconnectedPoint(curPosition[0], curPosition[1], index); - lastBestPlot = curPosition.clone(); - } - } else { - if (curVelocity == null) { - - this.m_Plot.setUnconnectedPoint(curPosition[0], curPosition[1], index); - } else { - this.m_Plot.setConnectedPoint(curPosition[0], curPosition[1], index); - this.m_Plot.setConnectedPoint(curPosition[0] + curVelocity[0], curPosition[1] + curVelocity[1], index); - } - } - } - } + this.m_Plot.setUnconnectedPoint(curPosition[0], curPosition[1], index); + lastBestPlot = curPosition.clone(); + } + } else { + if (curVelocity == null) { + + this.m_Plot.setUnconnectedPoint(curPosition[0], curPosition[1], index); + } else { + this.m_Plot.setConnectedPoint(curPosition[0], curPosition[1], index); + this.m_Plot.setConnectedPoint(curPosition[0] + curVelocity[0], curPosition[1] + curVelocity[1], index); + } + } + } + } /** * Return a uniformly distributed position vector within a sphere of radius r in relation to the given range. * - * @param vlen vector length - * @param range range of the playground in any axis - * @param r radius of the sphere relative to the range - * @return a uniformly distributed vector within a sphere of radius r in relation to the given range + * @param vlen vector length + * @param range range of the playground in any axis + * @param r radius of the sphere relative to the range + * @return a uniformly distributed vector within a sphere of radius r in relation to the given range */ - protected double[] getUniformRandVect(int vlen, double[][] range, double r) { - double normfact = 0.; - double[] rand = new double[vlen]; - for (int i=0; i= ((double)(m_Population.size() * highEnergyRatio))) { + if (index >= ((double) (m_Population.size() * highEnergyRatio))) { return m_SpeedLimit; - } - else { - if (highEnergyRaise == 0.) { + } else { + if (highEnergyRaise == 0.) { return maxSpeedLimit; - } - else { + } else { return m_SpeedLimit * highEnergyRaise; - } - } + } + } } - + /////////////////////////////////////////// these are called from the optimize loop @Override protected void startOptimize() { - super.startOptimize(); - if (detectAnchor >= 0) { // set the new detection anchor individual - detectAnchor = RNG.randomInt(0, m_Population.size()-1); - if (detectFit == null) { + super.startOptimize(); + if (detectAnchor >= 0) { // set the new detection anchor individual + detectAnchor = RNG.randomInt(0, m_Population.size() - 1); + if (detectFit == null) { detectFit = (m_Population.getIndividual(detectAnchor).getFitness()).clone(); - } - else { + } else { System.arraycopy(m_Population.getIndividual(detectAnchor).getFitness(), 0, detectFit, 0, detectFit.length); } - } + } } - - /** This method will init the optimizer with a given population - * @param pop The initial population - * @param reset If true the population is reset. - */ - @Override - public void initByPopulation(Population pop, boolean reset) { - super.initByPopulation(pop, reset); - double quantumCount = 0.; - // do what the usual function does plus announce quantum particles - if (quantumRatio > 0.) { - for (int i = 0; i < this.m_Population.size(); i++) { - AbstractEAIndividual indy = (AbstractEAIndividual)m_Population.get(i); - if (i>=quantumCount) { - indy.putData(partTypeKey, quantumType); - quantumCount += 1./quantumRatio; - } - } - } - } - - /** This method will update a given individual - * according to the PSO method - * @param index The individual to update. - * @param pop The current population. - * @param indy The best individual found so far. - */ - @Override - protected void updateIndividual(int index, AbstractEAIndividual indy, Population pop) { - if (index != detectAnchor) { // only for non anchor individuals (its -1 if other detect strategy is used) - if (indy instanceof InterfaceDataTypeDouble) { - int type=(Integer)indy.getData(partTypeKey); - switch (type) { - case quantumType: - updateQuantumIndividual(index, indy, pop); - break; - default: // handles the standard way of updating a particle - super.updateIndividual(index, indy, pop); - break; - } - } else { - throw new RuntimeException("Could not perform PSO update, because individual is not instance of InterfaceESIndividual!"); - } - } - //if (AbstractEAIndividual.getDoublePosition(indy)[0]<500000) { - // System.err.println(indy.getStringRepresentation()); - //} - } - /** This method will evaluate the current population using the + /** + * This method will init the optimizer with a given population + * + * @param pop The initial population + * @param reset If true the population is reset. + */ + @Override + public void initByPopulation(Population pop, boolean reset) { + super.initByPopulation(pop, reset); + double quantumCount = 0.; + // do what the usual function does plus announce quantum particles + if (quantumRatio > 0.) { + for (int i = 0; i < this.m_Population.size(); i++) { + AbstractEAIndividual indy = (AbstractEAIndividual) m_Population.get(i); + if (i >= quantumCount) { + indy.putData(partTypeKey, quantumType); + quantumCount += 1. / quantumRatio; + } + } + } + } + + /** + * This method will update a given individual + * according to the PSO method + * + * @param index The individual to update. + * @param pop The current population. + * @param indy The best individual found so far. + */ + @Override + protected void updateIndividual(int index, AbstractEAIndividual indy, Population pop) { + if (index != detectAnchor) { // only for non anchor individuals (its -1 if other detect strategy is used) + if (indy instanceof InterfaceDataTypeDouble) { + int type = (Integer) indy.getData(partTypeKey); + switch (type) { + case quantumType: + updateQuantumIndividual(index, indy, pop); + break; + default: // handles the standard way of updating a particle + super.updateIndividual(index, indy, pop); + break; + } + } else { + throw new RuntimeException("Could not perform PSO update, because individual is not instance of InterfaceESIndividual!"); + } + } + //if (AbstractEAIndividual.getDoublePosition(indy)[0]<500000) { + // System.err.println(indy.getStringRepresentation()); + //} + } + + /** + * This method will evaluate the current population using the * given problem. + * * @param population The population that is to be evaluated */ @Override - protected void evaluatePopulation(Population population) { - envHasChanged = false; + protected void evaluatePopulation(Population population) { + envHasChanged = false; super.evaluatePopulation(population); - if (m_Show && plotBestOnly) { - plotBestIndy(); - } - - envHasChanged = detectChange(m_Population); - + if (m_Show && plotBestOnly) { + plotBestIndy(); + } + + envHasChanged = detectChange(m_Population); + // if (envHasChanged) { // System.out.println("environmental change detected!"); // } - if (doSpeedAdaptation) { - adaptTrackingSpeed(((InterfaceDataTypeDouble)population.get(0)).getDoubleRange()); - } + if (doSpeedAdaptation) { + adaptTrackingSpeed(((InterfaceDataTypeDouble) population.get(0)).getDoubleRange()); + } // if (problem instanceof DynLocalizationProblem) { // ((DynLocalizationProblem)problem).adaptPSOByPopulation(population, this); // } } - - @Override - protected boolean isIndividualToUpdate(AbstractEAIndividual indy) { - return (envHasChanged || super.isIndividualToUpdate(indy)); - } @Override - protected void logBestIndividual() { - // log the best individual of the population - if (envHasChanged || (this.m_Population.getBestEAIndividual().isDominatingDebConstraints(this.m_BestIndividual))) { - this.m_BestIndividual = (AbstractEAIndividual)this.m_Population.getBestEAIndividual().clone(); - this.m_BestIndividual.putData(partBestFitKey, this.m_BestIndividual.getFitness()); - this.m_BestIndividual.putData(partBestPosKey, ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData()); - //System.out.println("-- best ind set to " + ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData()[0] + "/" + ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData()[1]); - } + protected boolean isIndividualToUpdate(AbstractEAIndividual indy) { + return (envHasChanged || super.isIndividualToUpdate(indy)); } - + + @Override + protected void logBestIndividual() { + // log the best individual of the population + if (envHasChanged || (this.m_Population.getBestEAIndividual().isDominatingDebConstraints(this.m_BestIndividual))) { + this.m_BestIndividual = (AbstractEAIndividual) this.m_Population.getBestEAIndividual().clone(); + this.m_BestIndividual.putData(partBestFitKey, this.m_BestIndividual.getFitness()); + this.m_BestIndividual.putData(partBestPosKey, ((InterfaceDataTypeDouble) this.m_BestIndividual).getDoubleData()); + //System.out.println("-- best ind set to " + ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData()[0] + "/" + ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData()[1]); + } + } + /////////////////////////////// end optimize loop /** * Checks for env change depending on the detection strategy. * For anchor detection, if detectAnchor is a valid ID, it returns true if the anchor individuals fitness has changed. * For assume change, true is returned, for assume no change, false is returned. - * - * @param population the population to check for a change + * + * @param population the population to check for a change * @return true if the population has changed as to the detect strategy, else false */ protected boolean detectChange(Population population) { - switch (changeDetectStrategy.getSelectedTag().getID()) { - case 0: - if (detectAnchor >= 0) { - return !(java.util.Arrays.equals(detectFit, m_Population.getIndividual(detectAnchor).getFitness())); + switch (changeDetectStrategy.getSelectedTag().getID()) { + case 0: + if (detectAnchor >= 0) { + return !(java.util.Arrays.equals(detectFit, m_Population.getIndividual(detectAnchor).getFitness())); + } else { + System.err.println("warning, inconsistency in detectChange"); + } + break; + case 1: + return true; + case 2: + return false; } - else { - System.err.println("warning, inconsistency in detectChange"); - } - break; - case 1: - return true; - case 2: - return false; - } - System.err.println("warning, inconsistency in detectChange"); - return false; - } - - @Override - public void setPopulation(Population pop) { - super.setPopulation(pop); - if (detectAnchor>=pop.size()) { - detectAnchor=0; - } - } - - @Override - public void init() { - super.init(); - setEmaPeriods(15); - if (doSpeedAdaptation) { - setSpeedLimit(2*getInitialVelocity()); - } + System.err.println("warning, inconsistency in detectChange"); + return false; } - @Override - public void setProblem (InterfaceOptimizationProblem problem) { - super.setProblem(problem); - if (problem instanceof AbstractOptimizationProblem) { - ((AbstractOptimizationProblem)problem).informAboutOptimizer(this); - } + public void setPopulation(Population pop) { + super.setPopulation(pop); + if (detectAnchor >= pop.size()) { + detectAnchor = 0; + } } - - /** This method will return a string describing all properties of the optimizer + + @Override + public void init() { + super.init(); + setEmaPeriods(15); + if (doSpeedAdaptation) { + setSpeedLimit(2 * getInitialVelocity()); + } + } + + + @Override + public void setProblem(InterfaceOptimizationProblem problem) { + super.setProblem(problem); + if (problem instanceof AbstractOptimizationProblem) { + ((AbstractOptimizationProblem) problem).informAboutOptimizer(this); + } + } + + /** + * This method will return a string describing all properties of the optimizer * and the applied methods. + * * @return A descriptive string */ @Override public String getStringRepresentation() { - StringBuilder strB = new StringBuilder(200); - strB.append("Dynamic Particle Swarm Optimization:\nOptimization Problem: "); + StringBuilder strB = new StringBuilder(200); + strB.append("Dynamic Particle Swarm Optimization:\nOptimization Problem: "); strB.append(this.m_Problem.getStringRepresentationForProblem(this)); strB.append("\n"); strB.append(this.m_Population.getStringRepresentation()); @@ -512,13 +511,18 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization /********************************************************************************************************************** * These are for GUI */ - /** This method returns a global info string + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { return "Particle Swarm Optimization tuned for tracking a dynamic target"; } - /** This method will return a naming String + + /** + * This method will return a naming String + * * @return The name of the algorithm */ @Override @@ -526,193 +530,191 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization return "DynPSO"; } - /** - * @return the quantumCloudDia - **/ - public double getQuantumCloudDia() { - return quantumCloudDia; - } + /** + * @return the quantumCloudDia + */ + public double getQuantumCloudDia() { + return quantumCloudDia; + } - /** - * @param quantumCloudDia the quantumCloudDia to set - **/ - public void setQuantumCloudDia(double quantumCloudDia) { - this.quantumCloudDia = quantumCloudDia; - } + /** + * @param quantumCloudDia the quantumCloudDia to set + */ + public void setQuantumCloudDia(double quantumCloudDia) { + this.quantumCloudDia = quantumCloudDia; + } - /** - * @return the quantumRatio - **/ - public double getQuantumRatio() { - return quantumRatio; - } + /** + * @return the quantumRatio + */ + public double getQuantumRatio() { + return quantumRatio; + } - /** - * @param quantumRatio the quantumRatio to set - **/ - public void setQuantumRatio(double quantumRatio) { - this.quantumRatio = quantumRatio; - if (quantumRatio == 0.) { - GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", true); - } - else { - GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", false); - } - } + /** + * @param quantumRatio the quantumRatio to set + */ + public void setQuantumRatio(double quantumRatio) { + this.quantumRatio = quantumRatio; + if (quantumRatio == 0.) { + GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", true); + } else { + GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", false); + } + } - /** - * @return the highEnergyRaise - **/ - public double getHighEnergyRaise() { - return highEnergyRaise; - } + /** + * @return the highEnergyRaise + */ + public double getHighEnergyRaise() { + return highEnergyRaise; + } - /** - * @param highEnergyRaise the highEnergyRaise to set - **/ - public void setHighEnergyRaise(double highEnergyRaise) { - this.highEnergyRaise = highEnergyRaise; - } + /** + * @param highEnergyRaise the highEnergyRaise to set + */ + public void setHighEnergyRaise(double highEnergyRaise) { + this.highEnergyRaise = highEnergyRaise; + } - /** - * @return the highEnergyRatio - **/ - public double getHighEnergyRatio() { - return highEnergyRatio; - } + /** + * @return the highEnergyRatio + */ + public double getHighEnergyRatio() { + return highEnergyRatio; + } - /** - * @param highEnergyRatio the highEnergyRatio to set - **/ - public void setHighEnergyRatio(double highEnergyRatio) { - this.highEnergyRatio = highEnergyRatio; - if (highEnergyRatio == 0.) { - GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", true); - } - else { - GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", false); - } - } + /** + * @param highEnergyRatio the highEnergyRatio to set + */ + public void setHighEnergyRatio(double highEnergyRatio) { + this.highEnergyRatio = highEnergyRatio; + if (highEnergyRatio == 0.) { + GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", true); + } else { + GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", false); + } + } - /** - * @return the maxSpeedLimit - **/ - public double getMaxSpeedLimit() { - return maxSpeedLimit; - } + /** + * @return the maxSpeedLimit + */ + public double getMaxSpeedLimit() { + return maxSpeedLimit; + } - /** - * @param maxSpeedLimit the maxSpeedLimit to set - **/ - public void setMaxSpeedLimit(double maxSpeedLimit) { - this.maxSpeedLimit = maxSpeedLimit; - } + /** + * @param maxSpeedLimit the maxSpeedLimit to set + */ + public void setMaxSpeedLimit(double maxSpeedLimit) { + this.maxSpeedLimit = maxSpeedLimit; + } - /** - * @return the minSpeedLimit - **/ - public double getMinSpeedLimit() { - return minSpeedLimit; - } + /** + * @return the minSpeedLimit + */ + public double getMinSpeedLimit() { + return minSpeedLimit; + } - /** - * @param minSpeedLimit the minSpeedLimit to set - **/ - public void setMinSpeedLimit(double minSpeedLimit) { - this.minSpeedLimit = minSpeedLimit; - } + /** + * @param minSpeedLimit the minSpeedLimit to set + */ + public void setMinSpeedLimit(double minSpeedLimit) { + this.minSpeedLimit = minSpeedLimit; + } - /** - * @return the doSpeedAdaptation - **/ - public boolean isDoSpeedAdaptation() { - return doSpeedAdaptation; - } + /** + * @return the doSpeedAdaptation + */ + public boolean isDoSpeedAdaptation() { + return doSpeedAdaptation; + } - /** - * @param doSpeedAdaptation the doSpeedAdaptation to set - **/ - public void setDoSpeedAdaptation(boolean doSpeedAdaptation) { - this.doSpeedAdaptation = doSpeedAdaptation; - if (doSpeedAdaptation && getEmaPeriods()<1) { - int newEmaP=15; - System.err.println("warning: EMA periods at " + getEmaPeriods() + " and speed adaption set to true... setting it to "+ newEmaP); - setEmaPeriods(newEmaP); - } - GenericObjectEditor.setHideProperty(getClass(), "minSpeedLimit", !doSpeedAdaptation); - GenericObjectEditor.setHideProperty(getClass(), "maxSpeedLimit", !doSpeedAdaptation); - } + /** + * @param doSpeedAdaptation the doSpeedAdaptation to set + */ + public void setDoSpeedAdaptation(boolean doSpeedAdaptation) { + this.doSpeedAdaptation = doSpeedAdaptation; + if (doSpeedAdaptation && getEmaPeriods() < 1) { + int newEmaP = 15; + System.err.println("warning: EMA periods at " + getEmaPeriods() + " and speed adaption set to true... setting it to " + newEmaP); + setEmaPeriods(newEmaP); + } + GenericObjectEditor.setHideProperty(getClass(), "minSpeedLimit", !doSpeedAdaptation); + GenericObjectEditor.setHideProperty(getClass(), "maxSpeedLimit", !doSpeedAdaptation); + } - /** - * @return the changeDetectStrategy - **/ - public SelectedTag getChangeDetectStrategy() { - return changeDetectStrategy; - } + /** + * @return the changeDetectStrategy + */ + public SelectedTag getChangeDetectStrategy() { + return changeDetectStrategy; + } - /** - * @param changeDetectStrategy the changeDetectStrategy to set - **/ - public void setChangeDetectStrategy(SelectedTag changeDetectStrategy) { - this.changeDetectStrategy = changeDetectStrategy; - if (changeDetectStrategy.getSelectedTag().getID() == 0) { // random anchor - detectAnchor = 0; // this will be set to a random individual - } else { - detectAnchor = -1; - } - } + /** + * @param changeDetectStrategy the changeDetectStrategy to set + */ + public void setChangeDetectStrategy(SelectedTag changeDetectStrategy) { + this.changeDetectStrategy = changeDetectStrategy; + if (changeDetectStrategy.getSelectedTag().getID() == 0) { // random anchor + detectAnchor = 0; // this will be set to a random individual + } else { + detectAnchor = -1; + } + } - public String phi0TipText() { - return "the random perturbation factor in relation to the problem range"; - } - - /** - * @return the phi0 value - **/ - public double getPhi0() { - return phi0; - } + public String phi0TipText() { + return "the random perturbation factor in relation to the problem range"; + } - /** - * @param phi0 the phi0 to set - **/ - public void setPhi0(double phi0) { - this.phi0 = phi0; - } + /** + * @return the phi0 value + */ + public double getPhi0() { + return phi0; + } - /** - * @return the phi3 - */ - public double getPhi3() { - return phi3; - } + /** + * @param phi0 the phi0 to set + */ + public void setPhi0(double phi0) { + this.phi0 = phi0; + } - /** - * @param phi3 the phi3 to set - */ - public void setPhi3(double phi3) { - this.phi3 = phi3; - } - - public String phi3TipText() { - return "Acceleration of the problem specific attractor"; - } - - public Plot getPlot() { - return m_Plot; - } + /** + * @return the phi3 + */ + public double getPhi3() { + return phi3; + } - /** - * @return the plotBestOnly - */ - public boolean isPlotBestOnly() { - return plotBestOnly; - } + /** + * @param phi3 the phi3 to set + */ + public void setPhi3(double phi3) { + this.phi3 = phi3; + } - /** - * @param plotBestOnly the plotBestOnly to set - */ - public void setPlotBestOnly(boolean plotBestOnly) { - this.plotBestOnly = plotBestOnly; - } + public String phi3TipText() { + return "Acceleration of the problem specific attractor"; + } + + public Plot getPlot() { + return m_Plot; + } + + /** + * @return the plotBestOnly + */ + public boolean isPlotBestOnly() { + return plotBestOnly; + } + + /** + * @param plotBestOnly the plotBestOnly to set + */ + public void setPlotBestOnly(boolean plotBestOnly) { + this.plotBestOnly = plotBestOnly; + } } \ No newline at end of file diff --git a/src/eva2/optimization/strategies/EsDpiNiching.java b/src/eva2/optimization/strategies/EsDpiNiching.java index 14302d3a..836cabd4 100644 --- a/src/eva2/optimization/strategies/EsDpiNiching.java +++ b/src/eva2/optimization/strategies/EsDpiNiching.java @@ -28,6 +28,7 @@ import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.io.Serializable; import java.util.Arrays; import java.util.Formatter; @@ -40,7 +41,7 @@ import java.util.Formatter; * iteration. Thus, in relation to the standard ES, some new parameters are due. * On the other hand, the selection schemes are predefined. This is done * according to Shir&Bäck, Niching in Evolution Strategies, Tec.Report 2005. - * + *

* Unfortunately the algorithm was not described in every detail. It remained * unclear how exactly the peak population where filled and esp. what happens if * DPI returns less than q peaks. In this implementation, this is solved by @@ -48,49 +49,47 @@ import java.util.Formatter; * population, only the best muPerPeak remain and the rest is assigned to the * unclustered set. From these, pseudo-peaks are then formed until the expected * number of peak populations is produced. - * + *

* Also, they gave a general rule for setting the niche radius depending on the * problem domain, however in their experiments, they were able to identify * optima which were much closer (i.e., on Ackley's), so it is unclear which * niche radius was actually used there - * + *

* Due to the "non-standard" environmental selection mechanism (a fixed * proportion is chosen from the children, the rest from the parents), a * preselection mechanism was implemented here, slightly breaking the ES * framework which is still used to optimize the single peak populations. - * + *

* This class should also cover "Dynamic niching in evolution strategies with * covariance matrix adaptation" by Shir & Bäck, CEC 2005, when employing * SelectBest as parent selection and muPerPeak=1. - * + *

* Some notes: - * + *

* If strictNiching is deactivated, niches are disappearing because they are * sometimes assigned the global opt. and in that niche are very bad so they get * thrown away due to the maximum niche count if strictNiching is activated, * niches are very small - or even empty. Why is that? This can hardly be * sensible esp. with a very small niche radius for F8. This would mean that in * the beginning, nearly all offspring are created from very few pairs of peaks. - * + *

* The mu/lambda information was lost on the way to the MutateESRankMuCMA * class... I added it now as additional pop.data which is only loaded if the * mu/lambda ratio deduced from the orig/selected population sizes does not make * sense. - * + *

* With the explorer peaks reinited every 100 generations or so, the course of * the MPR for a *single* run will not be a clear logistic function, because * "finding" additional peaks produces small steps in the MPR. - * + *

* The Niching ES is now using the Population to catch the generational events, * not producing it itself, similar to Tribes, ScatterSearch or IPOP-ES. Thus it * could be used with a dynamic population size without too much hassle. - * + *

* TODO Add adaptive niche radius. Add parameter to every indy which is adapted * after all new peaks have been found. * - * * @author mkron - * */ public class EsDpiNiching implements InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer, InterfacePopulationChangedEventListener { @@ -283,10 +282,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface * Use the deactivation of converged species, storing them to an archive, * with the given parameters. If windowLen <= 0, the deactivation mechanism * is disabled. This provides for semi-sequential niching with DPI-ES - * - * - * - * * @param threshold * @param windowLen @@ -650,7 +645,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface } } -// /** + // /** // * For each new cluster copy the additional data from the closest parent population. // * // * @param clusteredPeakPops @@ -724,12 +719,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface * appended to the given cluster list and returned (as a new array * instance). * - * @param origClusters the original clusters, where index 0 is the - * unclustered rest - * @param cntPerNewSpecies the number of indies to use per new peak - * population + * @param origClusters the original clusters, where index 0 is the + * unclustered rest + * @param cntPerNewSpecies the number of indies to use per new peak + * population * @param fromUnclusteredOrRandomly if true, use unclustered indies as new - * pops, otherwise create them randomly + * pops, otherwise create them randomly * @return */ private Population[] generateMissingSpecies(Population[] origClusters, int cntPerNewSpecies, int newPops, boolean fromUnclusteredOrRandomly) { @@ -854,7 +849,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface * @param indy */ private static void replaceWorstAndAllBetterIndiesBy(Population pop, - AbstractEAIndividual indy) { + AbstractEAIndividual indy) { int lastIndex = -1; if (!pop.contains(indy)) { // replace best int bestIndex = pop.getIndexOfBestIndividualPrefFeasible(); @@ -881,7 +876,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface * @return the vector of Population instances */ private static Population[] performDPSGenerationalAdaption(Population collectedPop, - Population dps, EvolutionStrategies[] opts) { + Population dps, EvolutionStrategies[] opts) { // loop over all dps individuals and // clone the new mutator instance from the original population // call the generational adaption for the new instance @@ -1262,8 +1257,8 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface @Override public String[] getAdditionalDataInfo() { return new String[]{"The niche radius employed for Dynamic Peak Identificatio", "The number of expected peaks", - "The number of stored potential local optima", "Mean distance of archived solutions", - "The number of collisions detected so far"}; + "The number of stored potential local optima", "Mean distance of archived solutions", + "The number of collisions detected so far"}; } @Override diff --git a/src/eva2/optimization/strategies/EsDpiNichingCma.java b/src/eva2/optimization/strategies/EsDpiNichingCma.java index e73a4c9e..aaf4306b 100644 --- a/src/eva2/optimization/strategies/EsDpiNichingCma.java +++ b/src/eva2/optimization/strategies/EsDpiNichingCma.java @@ -4,44 +4,44 @@ import eva2.optimization.operator.selection.SelectBestSingle; public class EsDpiNichingCma extends EsDpiNiching { - /** - * Preset all values according to the (1,lambda)-ES. This activates the automatic niche radius estimation - * (which frequently overestimates) and expects 10 peaks. - */ - public EsDpiNichingCma() { - this(10, 10, 0, 0); - } - - /** - * Preset all values according to the (1,lambda)-ES - */ - public EsDpiNichingCma(double nicheRadius, int lambda, int expectedPeaks) { - this(nicheRadius, lambda, expectedPeaks, 0, 0); - } - - /** - * Preset all values according to the (1,lambda)-ES - */ - public EsDpiNichingCma(int lambda, int expectedPeaks, int explorerPeaks, int resetExplInterval) { - this(-1, lambda, expectedPeaks, explorerPeaks, resetExplInterval); - } - - /** - * Preset all values according to the (1,lambda)-ES - */ - public EsDpiNichingCma(double nicheRadius, int lambda, int expectedPeaks, int explorerPeaks, int resetExplInterval) { - super(nicheRadius, 1, lambda, expectedPeaks, 0, explorerPeaks, resetExplInterval, 0); - setParentSelection(new SelectBestSingle()); - setAllowSingularPeakPops(true); - } - - @Override - public String getName() { - return "CMA-"+super.getName(); - } - - public static String globalInfo() { - return "A variant of the DPI Niching ES to be usable with CMA-Mutation (Shir&Bäck, CEC'05). " + - "Remember to turn off crossover for lambda=1, and to set CMA as mutation in the individual template."; - } + /** + * Preset all values according to the (1,lambda)-ES. This activates the automatic niche radius estimation + * (which frequently overestimates) and expects 10 peaks. + */ + public EsDpiNichingCma() { + this(10, 10, 0, 0); + } + + /** + * Preset all values according to the (1,lambda)-ES + */ + public EsDpiNichingCma(double nicheRadius, int lambda, int expectedPeaks) { + this(nicheRadius, lambda, expectedPeaks, 0, 0); + } + + /** + * Preset all values according to the (1,lambda)-ES + */ + public EsDpiNichingCma(int lambda, int expectedPeaks, int explorerPeaks, int resetExplInterval) { + this(-1, lambda, expectedPeaks, explorerPeaks, resetExplInterval); + } + + /** + * Preset all values according to the (1,lambda)-ES + */ + public EsDpiNichingCma(double nicheRadius, int lambda, int expectedPeaks, int explorerPeaks, int resetExplInterval) { + super(nicheRadius, 1, lambda, expectedPeaks, 0, explorerPeaks, resetExplInterval, 0); + setParentSelection(new SelectBestSingle()); + setAllowSingularPeakPops(true); + } + + @Override + public String getName() { + return "CMA-" + super.getName(); + } + + public static String globalInfo() { + return "A variant of the DPI Niching ES to be usable with CMA-Mutation (Shir&Bäck, CEC'05). " + + "Remember to turn off crossover for lambda=1, and to set CMA as mutation in the individual template."; + } } diff --git a/src/eva2/optimization/strategies/EvolutionStrategies.java b/src/eva2/optimization/strategies/EvolutionStrategies.java index caf76f91..70ac542a 100644 --- a/src/eva2/optimization/strategies/EvolutionStrategies.java +++ b/src/eva2/optimization/strategies/EvolutionStrategies.java @@ -102,7 +102,7 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -302,7 +302,7 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ * * @param myu * @param lambda - * @param plus True if plus, false if comma strategy + * @param plus True if plus, false if comma strategy */ public void setGenerationStrategy(int myu, int lambda, boolean plus) { this.mu = myu; diff --git a/src/eva2/optimization/strategies/EvolutionStrategyIPOP.java b/src/eva2/optimization/strategies/EvolutionStrategyIPOP.java index 9b7d3549..21c8b70a 100644 --- a/src/eva2/optimization/strategies/EvolutionStrategyIPOP.java +++ b/src/eva2/optimization/strategies/EvolutionStrategyIPOP.java @@ -13,6 +13,7 @@ import eva2.optimization.operator.terminators.PopulationMeasureTerminator.Stagna import eva2.optimization.population.Population; import eva2.optimization.population.SolutionSet; import eva2.optimization.problems.InterfaceAdditionalPopulationInformer; + import java.util.Arrays; import java.util.LinkedList; @@ -20,67 +21,66 @@ import java.util.LinkedList; * This implements the IPOP (increased population size restart) strategy ES, which increases * the ES population size (lambda) after phases or stagnation and restarts the optimization. * Stagnation is for this implementation defined by a FitnessConvergenceTerminator instance - * which terminates if the absolute change in fitness is below a threshold (default 10e-12) for a + * which terminates if the absolute change in fitness is below a threshold (default 10e-12) for a * certain number of generations (default: 10+floor(30*n/lambda) for problem dimension n). - * + *

* If the MutateESRankMuCMA mutation operator is used, additional criteria are used for restarts, * such as numeric conditions of the covariance matrix. * Lambda is increased multiplicatively for every restart, and typical initial values are * mu=5, lambda=10, incFact=2. * The IPOP-CMA-ES won the CEC 2005 benchmark challenge. - * Refer to Auger&Hansen 05 for more details. - * + * Refer to Auger&Hansen 05 for more details. + *

* A.Auger & N.Hansen. A Restart CMA Evolution Strategy With Increasing Population Size. CEC 2005. - * - * @author mkron * + * @author mkron */ public class EvolutionStrategyIPOP extends EvolutionStrategies implements InterfacePopulationChangedEventListener, InterfaceAdditionalPopulationInformer { - private static final long serialVersionUID = 4102736881931867818L; - int dim = -1; - int initialLambda = 10; + private static final long serialVersionUID = 4102736881931867818L; + int dim = -1; + int initialLambda = 10; - private double stagThreshold = 10e-12; -// private int stagTime = -1; - private int stagTimeArbitrary = 10; - private boolean useArbitraryStagTime = false; - - double incPopSizeFact = 2.; - FitnessConvergenceTerminator fitConvTerm = null; - LinkedList bestList = null; - AbstractEAIndividual best = null; - - public EvolutionStrategyIPOP(int mu, int lambda, boolean usePlus) { - super(mu, lambda, usePlus); - setForceOrigPopSize(false); - setInitialLambda(lambda); - } - - public EvolutionStrategyIPOP() { - super(); - setForceOrigPopSize(false); - setMu(5); - setLambda(10); - } - - public EvolutionStrategyIPOP(EvolutionStrategyIPOP other) { - super(other); - dim = other.dim; - initialLambda = other.initialLambda; - incPopSizeFact = other.incPopSizeFact; - stagThreshold = other.stagThreshold; + private double stagThreshold = 10e-12; + // private int stagTime = -1; + private int stagTimeArbitrary = 10; + private boolean useArbitraryStagTime = false; + + double incPopSizeFact = 2.; + FitnessConvergenceTerminator fitConvTerm = null; + LinkedList bestList = null; + AbstractEAIndividual best = null; + + public EvolutionStrategyIPOP(int mu, int lambda, boolean usePlus) { + super(mu, lambda, usePlus); + setForceOrigPopSize(false); + setInitialLambda(lambda); + } + + public EvolutionStrategyIPOP() { + super(); + setForceOrigPopSize(false); + setMu(5); + setLambda(10); + } + + public EvolutionStrategyIPOP(EvolutionStrategyIPOP other) { + super(other); + dim = other.dim; + initialLambda = other.initialLambda; + incPopSizeFact = other.incPopSizeFact; + stagThreshold = other.stagThreshold; // stagTime = other.stagTime; - - if (other.fitConvTerm != null) { - fitConvTerm = new FitnessConvergenceTerminator(other.fitConvTerm); - } - } - + + if (other.fitConvTerm != null) { + fitConvTerm = new FitnessConvergenceTerminator(other.fitConvTerm); + } + } + @Override - public Object clone() { - return new EvolutionStrategyIPOP(this); - } - + public Object clone() { + return new EvolutionStrategyIPOP(this); + } + @Override public void optimize() { // Population nextGeneration, parents; @@ -101,320 +101,327 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf // setPop(getReplacePop(nextGeneration)); // // this.firePropertyChangedEvent(Population.nextGenerationPerformed); - ////////////////////////// - super.optimize(); - - // remember the best indy - if ((best == null) || !best.isDominating(getPopulation().getBestEAIndividual())) { - best = getPopulation().getBestEAIndividual(); - } - if (EvolutionStrategyIPOP.testIPOPStopCrit(fitConvTerm, getPopulation())) { - // reinitialize population with increased mu,lambda - boostPopSize(); - } + ////////////////////////// + super.optimize(); + + // remember the best indy + if ((best == null) || !best.isDominating(getPopulation().getBestEAIndividual())) { + best = getPopulation().getBestEAIndividual(); + } + if (EvolutionStrategyIPOP.testIPOPStopCrit(fitConvTerm, getPopulation())) { + // reinitialize population with increased mu,lambda + boostPopSize(); + } } @Override public void hideHideable() { - GenericObjectEditor.setHideProperty(this.getClass(), "population", true); - setStagnationTimeUserDef(isStagnationTimeUserDef()); + GenericObjectEditor.setHideProperty(this.getClass(), "population", true); + setStagnationTimeUserDef(isStagnationTimeUserDef()); } - - /** - * Reinitialize population with increased mu,lambda - **/ - private void boostPopSize() { - // potentially increase pop size, increase by at least one if the factor is > 1. - int newLambda = Math.max((int)(getLambda()*incPopSizeFact), getLambda() + ((incPopSizeFact > 1.) ? 1 : 0)); - setLambda(newLambda); - checkPopulationConstraints(); - // update the stagnation time in the terminator - if (!isStagnationTimeUserDef() && (fitConvTerm != null)) { - fitConvTerm.setStagnationTime(calcDefaultStagnationTime()); - fitConvTerm.init(getProblem()); - } - bestList.add(best); - best = null; - Population newPop = getPopulation().cloneWithoutInds(); - getProblem().initializePopulation(newPop); // this is where the reinit event of Pop is called, meaning that the rank-mu-cma matrix is reinitialized as well - double[] badFit = getPopulation().getBestFitness().clone(); - Arrays.fill(badFit, Double.MAX_VALUE); - newPop.setAllFitnessValues(badFit); - getPopulation().clear(); - getPopulation().addAll(newPop); - getProblem().evaluate(getPopulation()); - } - + + /** + * Reinitialize population with increased mu,lambda + */ + private void boostPopSize() { + // potentially increase pop size, increase by at least one if the factor is > 1. + int newLambda = Math.max((int) (getLambda() * incPopSizeFact), getLambda() + ((incPopSizeFact > 1.) ? 1 : 0)); + setLambda(newLambda); + checkPopulationConstraints(); + // update the stagnation time in the terminator + if (!isStagnationTimeUserDef() && (fitConvTerm != null)) { + fitConvTerm.setStagnationTime(calcDefaultStagnationTime()); + fitConvTerm.init(getProblem()); + } + bestList.add(best); + best = null; + Population newPop = getPopulation().cloneWithoutInds(); + getProblem().initializePopulation(newPop); // this is where the reinit event of Pop is called, meaning that the rank-mu-cma matrix is reinitialized as well + double[] badFit = getPopulation().getBestFitness().clone(); + Arrays.fill(badFit, Double.MAX_VALUE); + newPop.setAllFitnessValues(badFit); + getPopulation().clear(); + getPopulation().addAll(newPop); + getProblem().evaluate(getPopulation()); + } + @Override protected void firePropertyChangedEvent(String name) { - if (name.equals(Population.funCallIntervalReached)) { - super.firePropertyChangedEvent(Population.nextGenerationPerformed); - } else {} // nothing, evt is produced in #registerPopulationStateChanged, dont forward original due to changing pop size + if (name.equals(Population.funCallIntervalReached)) { + super.firePropertyChangedEvent(Population.nextGenerationPerformed); + } else { + } // nothing, evt is produced in #registerPopulationStateChanged, dont forward original due to changing pop size } - + @Override public void init() { // setMu(initialMu); - if (getMu()>initialLambda) { - System.err.println("mu is " + getMu() + ", initial lambda was "+initialLambda); - setMu((initialLambda/2)+1); - System.err.println("Warning, too small initial lambda, adapting mu to " + getMu()); - } - super.setLambda(initialLambda); - checkPopulationConstraints(); - setForceOrigPopSize(false); - getPopulation().setNotifyEvalInterval(Math.max(initialLambda, 100)); - super.init(); - bestList = new LinkedList(); - best = getPopulation().getBestEAIndividual(); - dim = AbstractEAIndividual.getDoublePositionShallow(getPopulation().getEAIndividual(0)).length; - fitConvTerm = new FitnessConvergenceTerminator(stagThreshold, (isStagnationTimeUserDef()) ? stagTimeArbitrary : calcDefaultStagnationTime(), StagnationTypeEnum.generationBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease); // gen. based, absolute - getPopulation().addPopulationChangedEventListener(this); - getPopulation().setNotifyEvalInterval(initialLambda); + if (getMu() > initialLambda) { + System.err.println("mu is " + getMu() + ", initial lambda was " + initialLambda); + setMu((initialLambda / 2) + 1); + System.err.println("Warning, too small initial lambda, adapting mu to " + getMu()); + } + super.setLambda(initialLambda); + checkPopulationConstraints(); + setForceOrigPopSize(false); + getPopulation().setNotifyEvalInterval(Math.max(initialLambda, 100)); + super.init(); + bestList = new LinkedList(); + best = getPopulation().getBestEAIndividual(); + dim = AbstractEAIndividual.getDoublePositionShallow(getPopulation().getEAIndividual(0)).length; + fitConvTerm = new FitnessConvergenceTerminator(stagThreshold, (isStagnationTimeUserDef()) ? stagTimeArbitrary : calcDefaultStagnationTime(), StagnationTypeEnum.generationBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease); // gen. based, absolute + getPopulation().addPopulationChangedEventListener(this); + getPopulation().setNotifyEvalInterval(initialLambda); } /** * The default stagnation time in generations as suggested by Auger&Hansen 05. - * + * * @return */ - private int calcDefaultStagnationTime() { - return (int)(10+Math.floor(30*dim/getLambda())); - } - + private int calcDefaultStagnationTime() { + return (int) (10 + Math.floor(30 * dim / getLambda())); + } + /** * Test for the IPOP stopping criteria. + * * @param population * @return */ - public static boolean testIPOPStopCrit(InterfaceTerminator term, Population pop) { - boolean ret=false; - - int curGen = pop.getGeneration(); - MutateESRankMuCMA rcmaMute = null; - if (pop.getEAIndividual(0).getMutationOperator() instanceof MutateESRankMuCMA) { - rcmaMute = (MutateESRankMuCMA)pop.getEAIndividual(0).getMutationOperator(); - } - - // stop if the range of the best fitness of the last 10 + flor(30 n /lambda) generations is zero - // or if the range of these values and all fit values of the recent generation is below Tolfun = 10^-12 - //// interpret it a bit differently using FitnessConvergenceTerminator - if (term.isTerminated(new SolutionSet(pop))) { + public static boolean testIPOPStopCrit(InterfaceTerminator term, Population pop) { + boolean ret = false; + + int curGen = pop.getGeneration(); + MutateESRankMuCMA rcmaMute = null; + if (pop.getEAIndividual(0).getMutationOperator() instanceof MutateESRankMuCMA) { + rcmaMute = (MutateESRankMuCMA) pop.getEAIndividual(0).getMutationOperator(); + } + + // stop if the range of the best fitness of the last 10 + flor(30 n /lambda) generations is zero + // or if the range of these values and all fit values of the recent generation is below Tolfun = 10^-12 + //// interpret it a bit differently using FitnessConvergenceTerminator + if (term.isTerminated(new SolutionSet(pop))) { // System.out.println(fitConvTerm.lastTerminationMessage()); - ret = true; - } else { - if (rcmaMute != null) { - // stop if the std dev of the normal distribution is smaller than TolX in all coords - // and sigma p_c is smaller than TolX in all components; TolX = 10^-12 sigma_0 + ret = true; + } else { + if (rcmaMute != null) { + // stop if the std dev of the normal distribution is smaller than TolX in all coords + // and sigma p_c is smaller than TolX in all components; TolX = 10^-12 sigma_0 - if (rcmaMute.testAllDistBelow(pop, 10e-12*rcmaMute.getFirstSigma(pop))) { - ret = true; - } + if (rcmaMute.testAllDistBelow(pop, 10e-12 * rcmaMute.getFirstSigma(pop))) { + ret = true; + } - // stop if adding a 0.1 std dev vector in a principal axis dir. of C does not change _w^g - if (!ret && (rcmaMute.testNoChangeAddingDevAxis(pop, 0.1, curGen))) { - ret = true; - } + // stop if adding a 0.1 std dev vector in a principal axis dir. of C does not change _w^g + if (!ret && (rcmaMute.testNoChangeAddingDevAxis(pop, 0.1, curGen))) { + ret = true; + } - // stop if adding a 0.2 std dev in each coordinate does (not???) change _w^g - if (!ret && (rcmaMute.testNoEffectCoord(pop, 0.2))) { - ret = true; - } + // stop if adding a 0.2 std dev in each coordinate does (not???) change _w^g + if (!ret && (rcmaMute.testNoEffectCoord(pop, 0.2))) { + ret = true; + } - // stop if the condition number of C exceeds 10^14 - if (!ret && (rcmaMute.testCCondition(pop, 10e14))) { - ret = true; - } + // stop if the condition number of C exceeds 10^14 + if (!ret && (rcmaMute.testCCondition(pop, 10e14))) { + ret = true; + } // System.out.println("ret is " + ret); - } - } - return ret; - } + } + } + return ret; + } - /** - * Returns the current population and a set of best individuals found (best current - * and best single ones before - * reinitializing the population after boosting the population size). - * - * @return A solution set of the current population and possibly earlier solutions - */ + /** + * Returns the current population and a set of best individuals found (best current + * and best single ones before + * reinitializing the population after boosting the population size). + * + * @return A solution set of the current population and possibly earlier solutions + */ @Override - public SolutionSet getAllSolutions() { - Population sols = getPopulation().cloneWithoutInds(); - if (bestList != null) { - sols.addAll(bestList); - } - if (best != null) { - sols.add(best); - } - else { - sols.add(getPopulation().getBestEAIndividual()); - } - - SolutionSet solSet = new SolutionSet(getPopulation(), sols); - return solSet; - } - + public SolutionSet getAllSolutions() { + Population sols = getPopulation().cloneWithoutInds(); + if (bestList != null) { + sols.addAll(bestList); + } + if (best != null) { + sols.add(best); + } else { + sols.add(getPopulation().getBestEAIndividual()); + } + + SolutionSet solSet = new SolutionSet(getPopulation(), sols); + return solSet; + } + @Override - public void registerPopulationStateChanged(Object source, String name) { - if (name.equals(Population.funCallIntervalReached)) { - getPopulation().SetFunctionCalls(((Population)source).getFunctionCalls()); // TODO this is ugly - super.firePropertyChangedEvent(Population.nextGenerationPerformed); - } else { + public void registerPopulationStateChanged(Object source, String name) { + if (name.equals(Population.funCallIntervalReached)) { + getPopulation().SetFunctionCalls(((Population) source).getFunctionCalls()); // TODO this is ugly + super.firePropertyChangedEvent(Population.nextGenerationPerformed); + } else { // System.err.println("Not forwarding event " + name); - } - } - + } + } + @Override - public String getName() { - return getIncPopSizeFact()+"-IPOP-ES"; - } - - public static String globalInfo() { - return "An ES with increasing population size."; - } + public String getName() { + return getIncPopSizeFact() + "-IPOP-ES"; + } + + public static String globalInfo() { + return "An ES with increasing population size."; + } // // protected void checkPopulationConstraints() { // if (getLambda()!=initialLambda) setLambda(initialLambda); // if (getMu()>getLambda()) System.err.println("Invalid mu/lambda ratio!"); // super.checkPopulationConstraints(); // } - - /** Set an initial population size (if smaller lambda this is ignored). - * @param l The inital population size. + + /** + * Set an initial population size (if smaller lambda this is ignored). + * + * @param l The inital population size. */ - public void setInitialLambda(int l) { - initialLambda = l; + public void setInitialLambda(int l) { + initialLambda = l; // if (initialLambda < getMu()) setMu((initialLambda/2)+1); // do this on init - } - - public int getInitialLambda() { - return initialLambda; - } - - public String initialLambdaTipText() { + } + + public int getInitialLambda() { + return initialLambda; + } + + public String initialLambdaTipText() { return "Set the initial population size (lambda); mu should be about lambda/2"; } - /** - * @return the incPopSizeFact - */ - public double getIncPopSizeFact() { - return incPopSizeFact; - } - - /** - * @param incPopSizeFact the incPopSizeFact to set - */ - public void setIncPopSizeFact(double incPopSizeFact) { - this.incPopSizeFact = incPopSizeFact; - } - - public String incPopSizeFactTipText() { - return "Factor by which to increase lambda for each restart event, default is 2."; + /** + * @return the incPopSizeFact + */ + public double getIncPopSizeFact() { + return incPopSizeFact; } - /** - * @return the stagThreshold - */ - public double getStagThreshold() { - return stagThreshold; - } - /** - * @param stagThreshold the stagThreshold to set - */ - public void setStagThreshold(double stagThreshold) { - this.stagThreshold = stagThreshold; - if (fitConvTerm != null) { - fitConvTerm.setConvergenceThreshold(stagThreshold); - } - } - public String getStagThresholdTipText() { - return "Trigger new aera if the fitness does not change more than this threshold within certain no. iterations."; - } + /** + * @param incPopSizeFact the incPopSizeFact to set + */ + public void setIncPopSizeFact(double incPopSizeFact) { + this.incPopSizeFact = incPopSizeFact; + } - /** - * @return the stagTime - */ - public int getStagnationGenerations() { - return stagTimeArbitrary; - } - /** - * @param stagTime the stagTime to set - */ - public void setStagnationGenerations(int stagTime) { - this.stagTimeArbitrary = stagTime; - if (isStagnationTimeUserDef()) { - if (fitConvTerm != null) { - fitConvTerm.setStagnationTime(stagTime); - } - } - } - public String stagnationGenerationsTipText() { - return "Set a user defined stagnation time in generations."; - } - - /** - * @return the useArbitraryStagTime - */ - public boolean isStagnationTimeUserDef() { - return useArbitraryStagTime; - } - /** - * @param useArbitraryStagTime the useArbitraryStagTime to set - */ - public void setStagnationTimeUserDef(boolean useArbitraryStagTime) { - this.useArbitraryStagTime = useArbitraryStagTime; - GenericObjectEditor.setShowProperty(this.getClass(), "stagnationGenerations", useArbitraryStagTime); - if (fitConvTerm != null) { - if (useArbitraryStagTime) { - fitConvTerm.setStagnationTime(getStagnationGenerations()); + public String incPopSizeFactTipText() { + return "Factor by which to increase lambda for each restart event, default is 2."; + } + + /** + * @return the stagThreshold + */ + public double getStagThreshold() { + return stagThreshold; + } + + /** + * @param stagThreshold the stagThreshold to set + */ + public void setStagThreshold(double stagThreshold) { + this.stagThreshold = stagThreshold; + if (fitConvTerm != null) { + fitConvTerm.setConvergenceThreshold(stagThreshold); + } + } + + public String getStagThresholdTipText() { + return "Trigger new aera if the fitness does not change more than this threshold within certain no. iterations."; + } + + /** + * @return the stagTime + */ + public int getStagnationGenerations() { + return stagTimeArbitrary; + } + + /** + * @param stagTime the stagTime to set + */ + public void setStagnationGenerations(int stagTime) { + this.stagTimeArbitrary = stagTime; + if (isStagnationTimeUserDef()) { + if (fitConvTerm != null) { + fitConvTerm.setStagnationTime(stagTime); } - else { + } + } + + public String stagnationGenerationsTipText() { + return "Set a user defined stagnation time in generations."; + } + + /** + * @return the useArbitraryStagTime + */ + public boolean isStagnationTimeUserDef() { + return useArbitraryStagTime; + } + + /** + * @param useArbitraryStagTime the useArbitraryStagTime to set + */ + public void setStagnationTimeUserDef(boolean useArbitraryStagTime) { + this.useArbitraryStagTime = useArbitraryStagTime; + GenericObjectEditor.setShowProperty(this.getClass(), "stagnationGenerations", useArbitraryStagTime); + if (fitConvTerm != null) { + if (useArbitraryStagTime) { + fitConvTerm.setStagnationTime(getStagnationGenerations()); + } else { fitConvTerm.setStagnationTime(calcDefaultStagnationTime()); } - } - } - public String stagnationTimeUserDefTipText() { - return "Set or unset the user defined stagnation time."; - } + } + } - private double getMeanArchivedDist() { - if (bestList==null) { - return 0.; - } - else { - Population tmpPop=new Population(bestList.size()); - tmpPop.addAll(bestList); - tmpPop.synchSize(); - return tmpPop.getPopulationMeasures()[0]; - } - } - - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataHeader() - */ - @Override - public String[] getAdditionalDataHeader() { - return new String[] {"numArchived", "archivedMeanDist", "lambda"}; - } + public String stagnationTimeUserDefTipText() { + return "Set or unset the user defined stagnation time."; + } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataInfo() - */ - @Override - public String[] getAdditionalDataInfo() { - return new String[] {"Number of archived solutions", "Mean distance of archived solutions", "Current population size parameter lambda"}; - } + private double getMeanArchivedDist() { + if (bestList == null) { + return 0.; + } else { + Population tmpPop = new Population(bestList.size()); + tmpPop.addAll(bestList); + tmpPop.synchSize(); + return tmpPop.getPopulationMeasures()[0]; + } + } - /* - * (non-Javadoc) - * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataValue(eva2.optimization.PopulationInterface) - */ + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataHeader() + */ @Override - public Object[] getAdditionalDataValue(PopulationInterface pop) { - return new Object[]{(bestList==null) ? ((int)0) : bestList.size(), (getMeanArchivedDist()), getLambda()}; - } + public String[] getAdditionalDataHeader() { + return new String[]{"numArchived", "archivedMeanDist", "lambda"}; + } + + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataInfo() + */ + @Override + public String[] getAdditionalDataInfo() { + return new String[]{"Number of archived solutions", "Mean distance of archived solutions", "Current population size parameter lambda"}; + } + + /* + * (non-Javadoc) + * @see eva2.optimization.problems.InterfaceAdditionalPopulationInformer#getAdditionalDataValue(eva2.optimization.PopulationInterface) + */ + @Override + public Object[] getAdditionalDataValue(PopulationInterface pop) { + return new Object[]{(bestList == null) ? ((int) 0) : bestList.size(), (getMeanArchivedDist()), getLambda()}; + } } diff --git a/src/eva2/optimization/strategies/EvolutionaryProgramming.java b/src/eva2/optimization/strategies/EvolutionaryProgramming.java index 69e01438..d06fa4e1 100644 --- a/src/eva2/optimization/strategies/EvolutionaryProgramming.java +++ b/src/eva2/optimization/strategies/EvolutionaryProgramming.java @@ -15,7 +15,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * local search strategy solely based on mutation. To prevent any confusion, the * mutation rate is temporaily set to 1.0. Potential citation: the PhD thesis of * David B. Fogel (1992). - * + *

* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer * Architecture * diff --git a/src/eva2/optimization/strategies/GradientDescentAlgorithm.java b/src/eva2/optimization/strategies/GradientDescentAlgorithm.java index c34ad596..2046161d 100644 --- a/src/eva2/optimization/strategies/GradientDescentAlgorithm.java +++ b/src/eva2/optimization/strategies/GradientDescentAlgorithm.java @@ -16,7 +16,7 @@ import eva2.tools.ReflectPackage; /** * A gradient descent algorithm by hannes planatscher don't expect any * descriptions here... *big sigh* - * + *

* mkron added some! * * @author not attributable @@ -308,6 +308,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser this.firePropertyChangedEvent(Population.nextGenerationPerformed); } + private double momentumweigth = 0.1; protected void firePropertyChangedEvent(String name) { @@ -510,7 +511,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser return "Factor for decreasing the step size in adaption."; } -//////////////// concerning recovery + //////////////// concerning recovery public boolean isRecovery() { return recovery; } diff --git a/src/eva2/optimization/strategies/HillClimbing.java b/src/eva2/optimization/strategies/HillClimbing.java index b6443387..c5c35616 100644 --- a/src/eva2/optimization/strategies/HillClimbing.java +++ b/src/eva2/optimization/strategies/HillClimbing.java @@ -24,7 +24,7 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceMutation mutator = null; -// private int m_MultiRuns = 100; + // private int m_MultiRuns = 100; // private int m_FitnessCalls = 100; // private int m_FitnessCallsNeeded = 0; // GAIndividualBinaryData m_Best, m_Test; @@ -183,6 +183,7 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { // TmpMeanFitness = TmpMeanFitness/program.m_MultiRuns; // System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); // } + /** * This method allows you to add the LectureGUI as listener to the Optimizer * diff --git a/src/eva2/optimization/strategies/InterfaceOptimizer.java b/src/eva2/optimization/strategies/InterfaceOptimizer.java index 48a45111..e4c5746b 100644 --- a/src/eva2/optimization/strategies/InterfaceOptimizer.java +++ b/src/eva2/optimization/strategies/InterfaceOptimizer.java @@ -6,85 +6,100 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.InterfaceOptimizationProblem; -/** The general interface for optimizers giving the main methods necessary +/** + * The general interface for optimizers giving the main methods necessary * to perform a population based search. * This is a simple implementation of Population Based Incremental Learning. * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture - * @author Felix Streichert - * @version: $Revision: 306 $ - * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ - * $Author: mkron $ + * + * @author Felix Streichert + * @version: $Revision: 306 $ + * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ + * $Author: mkron $ */ public interface InterfaceOptimizer { - /** This method will return deep clone of the optimizer + /** + * This method will return deep clone of the optimizer + * * @return The clone */ Object clone(); - /** This method will return a naming String + /** + * This method will return a naming String + * * @return The name of the algorithm */ String getName(); - /** + /** * This method allows you to add a listener to the Optimizer. + * * @param ea */ void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea); - - /** + + /** * This method removes a listener from the Optimizer. It returns true on success, * false if the listener could not be found. + * * @param ea */ boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea); - - /** This method will init the optimizer + + /** + * This method will init the optimizer */ void init(); - /** + /** * This method will init the optimizer with a given population. - * - * @param pop The initial population - * @param reset If true the population is reinitialized and reevaluated. + * + * @param pop The initial population + * @param reset If true the population is reinitialized and reevaluated. */ void initByPopulation(Population pop, boolean reset); - /** This method will optimize for a single iteration, after this step + /** + * This method will optimize for a single iteration, after this step * the population should be as big as possible (ie. the size of lambda * and not mu) and all individual should be evaluated. This allows more * usefull statistics on the population. */ void optimize(); - /** Assuming that all optimizer will store their data in a population + /** + * Assuming that all optimizer will store their data in a population * we will allow access to this population to query to current state * of the optimizer. + * * @return The population of current solutions to a given problem. */ Population getPopulation(); + void setPopulation(Population pop); - + /** * Return all found solutions (local optima) if they are not contained in the current population. Be * sure to set the Population properties, especially function calls and generation, with respect * to the ongoing optimization. - * May return the the same set as getPopulation if the optimizer makes no distinction, i.e. does + * May return the the same set as getPopulation if the optimizer makes no distinction, i.e. does * not collect solutions outside the current population. - * + * * @return A solution set of the current population and possibly earlier solutions. */ InterfaceSolutionSet getAllSolutions(); - - /** + + /** * This method allows you to set an identifier for the algorithm - * @param name The identifier + * + * @param name The identifier */ void setIdentifier(String name); + String getIdentifier(); /** @@ -93,11 +108,14 @@ public interface InterfaceOptimizer { * * @param problem */ - void setProblem (InterfaceOptimizationProblem problem); - InterfaceOptimizationProblem getProblem (); + void setProblem(InterfaceOptimizationProblem problem); - /** This method will return a string describing all properties of the optimizer + InterfaceOptimizationProblem getProblem(); + + /** + * This method will return a string describing all properties of the optimizer * and the applied methods. + * * @return A descriptive string */ String getStringRepresentation(); diff --git a/src/eva2/optimization/strategies/InterfaceSpeciesAware.java b/src/eva2/optimization/strategies/InterfaceSpeciesAware.java index 18be4bc1..b2092821 100644 --- a/src/eva2/optimization/strategies/InterfaceSpeciesAware.java +++ b/src/eva2/optimization/strategies/InterfaceSpeciesAware.java @@ -5,28 +5,28 @@ import eva2.optimization.population.Population; /** * An interface for optimizers which are to be notified in case of species * based optimization; namely merging and split events. - * - * @author mkron * + * @author mkron */ public interface InterfaceSpeciesAware { - // these can be used to tag a population as explorer or local search population. - public final static String populationTagKey="specAwarePopulationTag"; - public final static Integer explorerPopTag=23; - public final static Integer localPopTag=42; - - /** - * Two species have been merged to the first one. - * @param p1 - * @param p2 - */ - public void mergeToFirstPopulationEvent(Population p1, Population p2); - - /** - * Notify that a split has occurred separating p2 from p1. - * - * @param p1 - * @param p2 - */ - public void splitFromFirst(Population p1, Population p2); + // these can be used to tag a population as explorer or local search population. + public final static String populationTagKey = "specAwarePopulationTag"; + public final static Integer explorerPopTag = 23; + public final static Integer localPopTag = 42; + + /** + * Two species have been merged to the first one. + * + * @param p1 + * @param p2 + */ + public void mergeToFirstPopulationEvent(Population p1, Population p2); + + /** + * Notify that a split has occurred separating p2 from p1. + * + * @param p1 + * @param p2 + */ + public void splitFromFirst(Population p1, Population p2); } diff --git a/src/eva2/optimization/strategies/IslandModelEA.java b/src/eva2/optimization/strategies/IslandModelEA.java index fd1ddc0d..87d5a5af 100644 --- a/src/eva2/optimization/strategies/IslandModelEA.java +++ b/src/eva2/optimization/strategies/IslandModelEA.java @@ -27,13 +27,13 @@ import eva2.optimization.problems.TF1Problem; * to allow fast and reliable computation. This is still usefull, since it is * less prone to premature convergence and also an heterogenuous island model * can be used. - * + *

* A population of the same size is sent to all nodes and evaluated there * independently for a cycle (more precisely: for MigrationRate generations) * after which a communication step is performed according to the migration * model. Only after migration is a main cycle complete, the statistics updated * etc. - * + *

* Created by IntelliJ IDEA. User: streiche Date: 12.09.2004 Time: 14:48:20 To * change this template use File | Settings | File Templates. */ @@ -43,7 +43,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm(); private InterfaceMigration m_Migration = new SOBestMigration(); private InterfaceOptimizationProblem m_Problem = new F8Problem(); -// private String[] m_NodesList; + // private String[] m_NodesList; private int m_MigrationRate = 10; private boolean m_HeterogenuousProblems = false; // These are the processor to run on @@ -462,7 +462,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I * This method allows an optimizer to register a change in the EA-lecture * * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. + * @param name Could be used to indicate the nature of the event. */ @Override public void registerPopulationStateChanged(Object source, String name) { diff --git a/src/eva2/optimization/strategies/LTGA.java b/src/eva2/optimization/strategies/LTGA.java index 4f769b1e..09fc579f 100644 --- a/src/eva2/optimization/strategies/LTGA.java +++ b/src/eva2/optimization/strategies/LTGA.java @@ -13,6 +13,7 @@ import eva2.optimization.problems.BKnapsackProblem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.Pair; import eva2.tools.math.SpecialFunction; + import java.util.BitSet; import java.util.HashSet; import java.util.Set; @@ -109,7 +110,7 @@ public class LTGA implements InterfaceOptimizer, java.io.Serializable, Interface } else { throw new RuntimeException( "Unable to get binary representation for " - + indy.getClass()); + + indy.getClass()); } } @@ -246,13 +247,13 @@ public class LTGA implements InterfaceOptimizer, java.io.Serializable, Interface this.problem.evaluatePopulationStart(this.population); Stack> linkageTree = this.buildLinkageTree(); Population newPop = new Population(this.popSize); - if(elitism){ + if (elitism) { Population firstIndies = this.population.getBestNIndividuals(2, fitCrit); Population firstNewIndies = buildNewIndies(firstIndies, linkageTree); newPop.addAll(firstNewIndies); } for (int i = 0; i < (this.popSize / 2); i++) { - if(this.elitism && i==0){ + if (this.elitism && i == 0) { continue; } Population indies = this.population.getRandNIndividuals(2); @@ -265,15 +266,15 @@ public class LTGA implements InterfaceOptimizer, java.io.Serializable, Interface } private Population buildNewIndies(Population indies, - Stack> linkageTree) { + Stack> linkageTree) { if (indies.size() != 2) { return indies; } AbstractEAIndividual indy1 = indies.getEAIndividual(0); AbstractEAIndividual indy2 = indies.getEAIndividual(1); for (Set mask : linkageTree) { - BitSet gen1 = getBinaryData(indy1); - BitSet gen2 = getBinaryData(indy2); + BitSet gen1 = getBinaryData(indy1); + BitSet gen2 = getBinaryData(indy2); BitSet newGene1 = (BitSet) gen1.clone(); BitSet newGene2 = (BitSet) gen2.clone(); boolean same = true; @@ -341,16 +342,16 @@ public class LTGA implements InterfaceOptimizer, java.io.Serializable, Interface public void setProblem(InterfaceOptimizationProblem problem) { this.problem = (AbstractOptimizationProblem) problem; } - - public boolean getElitism(){ + + public boolean getElitism() { return this.elitism; } - - public void setElitism(boolean b){ + + public void setElitism(boolean b) { this.elitism = b; } - - public String elitismTipText(){ + + public String elitismTipText() { return "use elitism?"; } diff --git a/src/eva2/optimization/strategies/MLTGA.java b/src/eva2/optimization/strategies/MLTGA.java index 5b86ffe7..1993b155 100644 --- a/src/eva2/optimization/strategies/MLTGA.java +++ b/src/eva2/optimization/strategies/MLTGA.java @@ -13,6 +13,7 @@ import eva2.optimization.problems.BKnapsackProblem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.Pair; import eva2.tools.math.SpecialFunction; + import java.util.BitSet; import java.util.HashSet; import java.util.Set; @@ -109,7 +110,7 @@ public class MLTGA implements InterfaceOptimizer, java.io.Serializable, Interfac } else { throw new RuntimeException( "Unable to get binary representation for " - + indy.getClass()); + + indy.getClass()); } } @@ -265,7 +266,7 @@ public class MLTGA implements InterfaceOptimizer, java.io.Serializable, Interfac } private AbstractEAIndividual buildNewIndy(AbstractEAIndividual indy, - Stack> linkageTree) { + Stack> linkageTree) { for (Set mask : linkageTree) { BitSet gen = getBinaryData(indy); BitSet newGene = (BitSet) gen.clone(); diff --git a/src/eva2/optimization/strategies/MemeticAlgorithm.java b/src/eva2/optimization/strategies/MemeticAlgorithm.java index 7875fd4a..c2e41df4 100644 --- a/src/eva2/optimization/strategies/MemeticAlgorithm.java +++ b/src/eva2/optimization/strategies/MemeticAlgorithm.java @@ -10,6 +10,7 @@ import eva2.optimization.population.SolutionSet; import eva2.optimization.problems.F1Problem; import eva2.optimization.problems.InterfaceLocalSearchable; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.util.Hashtable; /** @@ -262,6 +263,7 @@ public class MemeticAlgorithm implements InterfaceOptimizer, * ======================================================================================== * These are for GUI */ + /** * This method returns a global info string * diff --git a/src/eva2/optimization/strategies/MonteCarloSearch.java b/src/eva2/optimization/strategies/MonteCarloSearch.java index 36c61e8a..61089db3 100644 --- a/src/eva2/optimization/strategies/MonteCarloSearch.java +++ b/src/eva2/optimization/strategies/MonteCarloSearch.java @@ -14,7 +14,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * complexity of the search space. This implements a Random Walk Search using * the initialization method of the problem instance, meaning that the random * characteristics may be problem dependent. - * + *

* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer * Architecture * @@ -67,7 +67,7 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override diff --git a/src/eva2/optimization/strategies/MultiObjectiveCMAES.java b/src/eva2/optimization/strategies/MultiObjectiveCMAES.java index cac81f37..309e87a0 100644 --- a/src/eva2/optimization/strategies/MultiObjectiveCMAES.java +++ b/src/eva2/optimization/strategies/MultiObjectiveCMAES.java @@ -11,13 +11,12 @@ import eva2.optimization.population.Population; import eva2.optimization.population.SolutionSet; import eva2.optimization.problems.AbstractOptimizationProblem; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.io.Serializable; import java.util.HashMap; /** - * * @author mkron - * */ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable { @@ -27,18 +26,18 @@ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable { private static final long serialVersionUID = 1L; /** - * * @author mkron - * */ class CounterClass { public CounterClass(int i) { value = i; } + public int value; public boolean seen = false; } + private String m_Identifier = "MOCMAES"; private Population m_Population; private AbstractOptimizationProblem m_Problem; diff --git a/src/eva2/optimization/strategies/MultiObjectiveEA.java b/src/eva2/optimization/strategies/MultiObjectiveEA.java index 4f039953..2ff9ff48 100644 --- a/src/eva2/optimization/strategies/MultiObjectiveEA.java +++ b/src/eva2/optimization/strategies/MultiObjectiveEA.java @@ -51,7 +51,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl } public MultiObjectiveEA(InterfaceOptimizer subOpt, InterfaceArchiving archiving, int archiveSize, - InterfaceInformationRetrieval infoRetrieval, AbstractOptimizationProblem problem) { + InterfaceInformationRetrieval infoRetrieval, AbstractOptimizationProblem problem) { setOptimizer(subOpt); setArchivingStrategy(archiving); setArchiveSize(archiveSize); @@ -74,7 +74,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override diff --git a/src/eva2/optimization/strategies/NelderMeadSimplex.java b/src/eva2/optimization/strategies/NelderMeadSimplex.java index 9bd8f48a..bb056576 100644 --- a/src/eva2/optimization/strategies/NelderMeadSimplex.java +++ b/src/eva2/optimization/strategies/NelderMeadSimplex.java @@ -11,6 +11,7 @@ import eva2.optimization.problems.AbstractOptimizationProblem; import eva2.optimization.problems.AbstractProblemDouble; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Mathematics; + import java.io.Serializable; import java.util.Vector; @@ -20,7 +21,6 @@ import java.util.Vector; * available by projection at the bounds. * * @author mkron - * */ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, InterfacePopulationChangedEventListener { @@ -364,13 +364,13 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte /** * This method creates a Nelder-Mead instance. * - * @param pop The size of the population - * @param problem The problem to be optimized + * @param pop The size of the population + * @param problem The problem to be optimized * @param listener * @return An optimization procedure that performs nelder mead optimization. */ public static final NelderMeadSimplex createNelderMeadSimplex(AbstractOptimizationProblem problem, - InterfacePopulationChangedEventListener listener) { + InterfacePopulationChangedEventListener listener) { problem.initializeProblem(); NelderMeadSimplex nms = new NelderMeadSimplex(); @@ -394,17 +394,16 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte * with given perturbation ratio or randomly across the search range if the * perturbation ratio is zero or below zero. * - * - * @param problem The problem to be optimized - * @param candidate starting point of the search + * @param problem The problem to be optimized + * @param candidate starting point of the search * @param perturbationRatio perturbation ratio relative to the problem range - * for the initial simplex creation + * for the initial simplex creation * @param listener * @return An optimization procedure that performs nelder mead optimization. */ public static final NelderMeadSimplex createNelderMeadSimplexLocal(AbstractOptimizationProblem problem, - AbstractEAIndividual candidate, double perturbationRatio, - InterfacePopulationChangedEventListener listener) { + AbstractEAIndividual candidate, double perturbationRatio, + InterfacePopulationChangedEventListener listener) { // TODO this method might be superfluous when using PostProcess problem.initializeProblem(); @@ -459,7 +458,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte } private static void addPerturbedPopulation(double perturbationRatio, - Population initialPop, double[][] range, AbstractEAIndividual candidate) { + Population initialPop, double[][] range, AbstractEAIndividual candidate) { AbstractEAIndividual indy = (AbstractEAIndividual) candidate.clone(); // span by perturbation, every new individual i is modified in dimension i by // a value of perturbRatio*range_i such that a simplex of relative side length perturbRatio is created. diff --git a/src/eva2/optimization/strategies/NicheGraph.java b/src/eva2/optimization/strategies/NicheGraph.java index 288087ce..3b3447d3 100644 --- a/src/eva2/optimization/strategies/NicheGraph.java +++ b/src/eva2/optimization/strategies/NicheGraph.java @@ -9,131 +9,136 @@ import java.util.TreeMap; import java.util.TreeSet; /** - * This is a small implementation of an undirected graph which is able - * to compute the connected components. + * This is a small implementation of an undirected graph which is able + * to compute the connected components. * This class is used to represent the NicheGraph for the ANPSO algorithm. */ public class NicheGraph implements java.io.Serializable { -/********************************************************************************************************************** - * members - */ - // key is vertex, value is set of adjacent vertices - protected TreeMap> graphTable; - - // set of visited vertices in bfs - protected HashSet set; + /** + * ******************************************************************************************************************* + * members + */ + // key is vertex, value is set of adjacent vertices + protected TreeMap> graphTable; -/********************************************************************************************************************** - * ctor - */ - public NicheGraph(){ - graphTable = new TreeMap>(); - set = new HashSet(); - } - - - public NicheGraph(NicheGraph o){ - this.graphTable = (TreeMap>)o.graphTable.clone(); - this.set = (HashSet)o.set.clone(); - } + // set of visited vertices in bfs + protected HashSet set; + + /** + * ******************************************************************************************************************* + * ctor + */ + public NicheGraph() { + graphTable = new TreeMap>(); + set = new HashSet(); + } + + + public NicheGraph(NicheGraph o) { + this.graphTable = (TreeMap>) o.graphTable.clone(); + this.set = (HashSet) o.set.clone(); + } @Override - public Object clone(){ - return (Object) new NicheGraph(this); - } + public Object clone() { + return (Object) new NicheGraph(this); + } /********************************************************************************************************************** * vertices and edges */ - /** - * adds a new vertex without neighbors - * @param v - */ - public void addVertex(String v){ - if (!containsVertex(v)) { - graphTable.put(v, new TreeSet()); - } - } - - /** - * adds an edge to the graph (previously adds the vertices if necessary) - * @param v1 - * @param v2 - */ - public void addEdge(String v1, String v2){ - if (!containsVertex(v1)) { - addVertex(v1); - } - if (!containsVertex(v2)) { - addVertex(v2); - } - // mutually add the vertices as neighbors - graphTable.get(v1).add(v2); - graphTable.get(v2).add(v1); - } + /** + * adds a new vertex without neighbors + * + * @param v + */ + public void addVertex(String v) { + if (!containsVertex(v)) { + graphTable.put(v, new TreeSet()); + } + } + + /** + * adds an edge to the graph (previously adds the vertices if necessary) + * + * @param v1 + * @param v2 + */ + public void addEdge(String v1, String v2) { + if (!containsVertex(v1)) { + addVertex(v1); + } + if (!containsVertex(v2)) { + addVertex(v2); + } + // mutually add the vertices as neighbors + graphTable.get(v1).add(v2); + graphTable.get(v2).add(v1); + } + + public boolean containsVertex(String v) { + return graphTable.containsKey(v); + } - public boolean containsVertex(String v) { - return graphTable.containsKey(v); - } - // return iterator over all vertices in graph public Iterable getVertexIterator() { - return graphTable.keySet(); + return graphTable.keySet(); } - + // return an iterator over the neighbors of vertex v public Iterable getNeighborIterator(String v) { - return graphTable.get(v); + return graphTable.get(v); } - -/********************************************************************************************************************** - * BFS, getConnectedComponents - */ + + /** + * ******************************************************************************************************************* + * BFS, getConnectedComponents + */ // run BFS from given root vertex r public void runBFS(String r) { - set = new HashSet(); + set = new HashSet(); - // put root on the queue - java.util.Queue q = new LinkedList(); - q.offer(r); - set.add(r); + // put root on the queue + java.util.Queue q = new LinkedList(); + q.offer(r); + set.add(r); - // remove next vertex and put all neighbors on queue (if not visited)... - while (!q.isEmpty()) { - String v = q.poll(); - for (String w : getNeighborIterator(v)) { - if (!set.contains(w)){ - q.offer(w); - set.add(w); - } - } - } + // remove next vertex and put all neighbors on queue (if not visited)... + while (!q.isEmpty()) { + String v = q.poll(); + for (String w : getNeighborIterator(v)) { + if (!set.contains(w)) { + q.offer(w); + set.add(w); + } + } + } } - + /** * @return connected components of the graph */ - public List> getConnectedComponents(){ - ArrayList> l = new ArrayList>(); - - for (String v : getVertexIterator()){ - if (!isComponent(v,l)){ - // use current vertex to start a bfs - runBFS(v); - // add visited vertices to the set of connected components - l.add(set); - } - } - return l; + public List> getConnectedComponents() { + ArrayList> l = new ArrayList>(); + + for (String v : getVertexIterator()) { + if (!isComponent(v, l)) { + // use current vertex to start a bfs + runBFS(v); + // add visited vertices to the set of connected components + l.add(set); + } + } + return l; } - + private boolean isComponent(String v, ArrayList> l) { - for (Set set : l){ - if (set.contains(v)) { + for (Set set : l) { + if (set.contains(v)) { return true; } - } - return false; - } + } + return false; + } } diff --git a/src/eva2/optimization/strategies/NichePSO.java b/src/eva2/optimization/strategies/NichePSO.java index 1f12fcb5..966efb2f 100644 --- a/src/eva2/optimization/strategies/NichePSO.java +++ b/src/eva2/optimization/strategies/NichePSO.java @@ -43,6 +43,7 @@ import eva2.tools.chart2d.DElement; import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointSet; + import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; @@ -61,17 +62,17 @@ import java.util.Vector; * search space. Subswarms are formed from that main swarm to refine and * represent single niches which are assumed to correspond to local or global * optima. - * + *

* Different strategies are employed in order to: create subswarms from the main * swarm merge subswarms if they converge to the same solution absorb main swarm * particles into a subswarm in case a particle enters the area covered by the * subswarm deactivate subswarms when all containing particles converged on a * solution - * + *

* Some implementations of these strategies and the deactivation strategy itself * extend the original algorithm. As proposed in [1], NichePSO uses the * "cognition only" model of the "inertness weight" PSO to train the main swarm. - * + *

* mainSwarmInertness sets the inertia weight omega and weights the particles * tendency to follow its former movement. This controls exploration (favored by * larger values) against exploitation (favored by smaller values). @@ -85,13 +86,12 @@ import java.util.Vector; * NichePSO. Experiments showed a good performance for relatively small values * of maxAllowedSwarmRadius <= 0.0001 on lower dimensional problems. For higher * dimensional problems, larger values may be preferable. - * + *

* [1] R. Brits, A. P. Engelbrecht and B. Bergh. A Niching Particle Swarm * Optimizer In Proceedings of the 4th Asia-Pacific Conference on Simulated * Evolution and Learning (SEAL'02), 2002, 2, 692-696 [2] E. �zcan and M. * Yilmaz. Particle Swarms for Multimodal Optimization. In: ICANNGA (1), Seiten * 366�375, 2007 - * */ public class NichePSO implements InterfaceAdditionalPopulationInformer, InterfaceOptimizer, java.io.Serializable { @@ -112,7 +112,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac protected PSOTopologyEnum mainSwarmTopology = PSOTopologyEnum.grid; // = 1; protected int mainSwarmTopologyRange = 0; private int mainSwarmAlgoType = 0; // 0: inertness, 1: constriction -// private InterfaceParameterAging mainSwarmParamAging = new LinearParameterAging(); + // private InterfaceParameterAging mainSwarmParamAging = new LinearParameterAging(); protected ParameterControlManager paramControl = new ParameterControlManager(); boolean returnRepresentativeSolutionsOnly = true; // if true only the representatives of every subswarm are returned, else every particles pbest boolean partlyInactive = false; // used to inactivate parts of the optimizer to see the effect on the performance @@ -174,7 +174,6 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac */ /** * @tested - * */ public NichePSO() { if (log) { @@ -282,7 +281,6 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * @tested inits the template used for creating subswarms this is only * called in the ctor not via init() (would overwrite changes set from * outside for the next run) - * */ protected void initSubswarmOptimizerTemplate() { // pass on the parameters set via NichePSO (done in the analogous nichePSO-Setters as well -> no init() necessary) @@ -306,9 +304,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @return an optimizer with parameters set according to the nichePSO * @tested returns the optimizer that should be used to create a new * subswarm - * @return an optimizer with parameters set according to the nichePSO */ public ParticleSubSwarmOptimization getNewSubSwarmOptimizer() { //initSubswarmOptimizerTemplate(); @@ -464,9 +462,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Schedule new particles to be added to this swarm, rndly inited over the * search space by the problem * - * @param size number of particles to be created + * @param size number of particles to be created * @param particleIndices set of indices that should be used for the added - * particles, if null new indices are created + * particles, if null new indices are created */ public void scheduleNewParticlesToPopulation(int[] particleIndices) { if (particleIndices != null) { @@ -630,11 +628,11 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Absorbtion */ /** - * @tested adds indy to an active subswarm, then removes indy from the - * mainswarm. * @param indy * @param subswarm * @return + * @tested adds indy to an active subswarm, then removes indy from the + * mainswarm. */ protected void absorbtionEventFor(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm) { if (isVerbose()) { @@ -730,9 +728,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @param ea * @tested This method allows you to add the LectureGUI as listener to the * Optimizer - * @param ea */ @Override public void addPopulationChangedEventListener( @@ -761,8 +759,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac */ /** * @tested nn (non-Javadoc) - * @see - * eva2.optimization.strategies.InterfaceOptimizer#setPopulation(javaeva.server.oa.go.Populations.Population) + * @see eva2.optimization.strategies.InterfaceOptimizer#setPopulation(javaeva.server.oa.go.Populations.Population) */ @Override public void setPopulation(Population pop) { @@ -771,9 +768,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested junit, junit& * @return a population consisting of copies from the mainswarm and all - * active subswarms + * active subswarms + * @tested junit, junit& */ public Population getActivePopulation() { // construct a metapop with clones from the mainswarm and all active subswarms @@ -803,6 +800,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @return a population consisting of copies from the mainswarm and all + * subswarms. * @tested junit returns a population consisting of copies from the * mainswarm and all subswarms (active and inactive, so the size of this * Population is not necessarily constant). (Especially important for the @@ -810,8 +809,6 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * getPopulation().getPopulationSize() returns the !initial! size of the * main swarm, the actual size of the complete population is accessed via * getPopulation().size() - * @return a population consisting of copies from the mainswarm and all - * subswarms. */ @Override public Population getPopulation() { @@ -864,10 +861,10 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @return a population consisting of the personal best solutions of every + * particle in the mainswarm and all subswarms * @tested junit (non-Javadoc) * @see eva2.optimization.strategies.InterfaceOptimizer#getAllSolutions() - * @return a population consisting of the personal best solutions of every - * particle in the mainswarm and all subswarms */ @Override public SolutionSet getAllSolutions() { @@ -896,8 +893,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested junit * @return the best solution found by any particle in any swarm + * @tested junit */ public AbstractEAIndividual getGlobalBestSolution() { Population metapop = getPopulation(); @@ -916,9 +913,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @return array with copies of the gbest individuals * @tested junit returns the cloned global best individuals (ie best of all * time) from every subswarm and the main swarm - * @return array with copies of the gbest individuals */ public Population getSubswarmRepresentatives(boolean onlyInactive) { Population representatives = new Population(getSubSwarms().size() + 1); @@ -944,9 +941,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @param size * @tested ps sets the !initial! size of the mainswarm population use this * instead of getPopulation.setPopulationSize() - * @param size */ public void setMainSwarmSize(int size) { // set member @@ -956,8 +953,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested nn returns the !initial! size of the mainswarm population * @return the !initial! size of the mainswarm population + * @tested nn returns the !initial! size of the mainswarm population */ public int getMainSwarmSize() { return this.mainSwarmSize; @@ -968,9 +965,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @param val * @tested ps defines the maximal allowed subswarm radius for absorption and * merging - * @param val */ public void setMaxAllowedSwarmRadius(double val) { // set member @@ -984,8 +981,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested nn * @return + * @tested nn */ public double getMaxAllowedSwarmRadius() { return this.maxAllowedSwarmRadius; @@ -995,7 +992,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac return "no subswarm radius is allowed to (formally) exceed this threshold (see help for details)"; } -// public double getMainSwarmPhi1() { + // public double getMainSwarmPhi1() { // return mainSwarmPhi1; // } // @@ -1027,7 +1024,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac return "weights the cognitive component for the PSO used to train the main swarm"; } -// public void setMainSwarmPhi2(double p2) { + // public void setMainSwarmPhi2(double p2) { // this.SetMainSwarmPhi2(p2); // } // @@ -1103,16 +1100,16 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested nn * @param val + * @tested nn */ public void SetPartlyInactive(boolean val) { this.partlyInactive = val; } /** - * @tested nn * @return + * @tested nn */ public boolean isPartlyInactive() { return partlyInactive; @@ -1215,7 +1212,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac return mainSwarm; } -// public InterfaceParameterAging getMainSwarmInertness(){ + // public InterfaceParameterAging getMainSwarmInertness(){ // return mainSwarmParamAging; //// return this.mainSwarm.getInertnessAging(); // } @@ -1307,8 +1304,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested ps This method will set the problem that is to be optimized * @param problem + * @tested ps This method will set the problem that is to be optimized */ @Override public void setProblem(InterfaceOptimizationProblem problem) { @@ -1323,8 +1320,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested nn This method allows you to set an identifier for the algorithm * @param name The indenifier + * @tested nn This method allows you to set an identifier for the algorithm */ @Override public void setIdentifier(String name) { @@ -1358,9 +1355,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested junit * @param vals * @return + * @tested junit */ public double getMedian(double[] vals) { java.util.Arrays.sort(vals); @@ -1443,8 +1440,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * setter, getter: infostrings */ /** - * @tested nn This method will return a naming String * @return The name of the algorithm + * @tested nn This method will return a naming String */ @Override public String getName() { @@ -1452,9 +1449,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @return A descriptive string * @tested nn This method will return a string describing all properties of * the optimizer and the applied methods. - * @return A descriptive string */ @Override public String getStringRepresentation() { @@ -1465,9 +1462,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @return descriptive string of the elite * @tested emp returns a string that lists the global best individuals (ie * best of all time) from every subswarm - * @return descriptive string of the elite */ public String getSubswarmRepresentativesAsString(boolean onlyInactive) { String result = "\nSubswarmRepresentatives: \n"; @@ -1480,8 +1477,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested emp * @return + * @tested emp */ public String getPerformanceAsString() { if (!(m_Problem instanceof InterfaceMultimodalProblem)) { @@ -1567,8 +1564,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested emp writes something to the LogFile * @param line string to be written + * @tested emp writes something to the LogFile */ protected void writeToLogFile(String line) { String write = line + "\n"; @@ -1590,9 +1587,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * getter for debugging and analysing */ /** - * @tested @param pop * @param index * @return particle with given index + * @tested @param pop */ public AbstractEAIndividual getIndyByParticleIndexAndPopulation(Population pop, Integer index) { for (int i = 0; i < pop.size(); ++i) { @@ -1607,8 +1604,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested @param index * @return main swarm particle with given index + * @tested @param index */ public AbstractEAIndividual getIndyByParticleIndex(Integer index) { AbstractEAIndividual indy = null; @@ -1744,8 +1741,8 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested plots all std devs < boundary for the respective particles * @param boundary + * @tested plots all std devs < boundary for the respective particles */ protected void plotBoundStdDevInMainSwarm(double boundary) { InterfaceDataTypeDouble tmpIndy1; @@ -1771,9 +1768,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested plots a circle around the individual and adds some information * @param index index of the particle - * @param text information to be added + * @param text information to be added + * @tested plots a circle around the individual and adds some information */ protected void plotCircleForIndy(int index, String text) { AbstractEAIndividual indy = getIndyByParticleIndex(new Integer(index)); @@ -1786,9 +1783,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** - * @tested plots a circle around the individual and adds some information * @param indy invidual * @param text information to be added + * @tested plots a circle around the individual and adds some information */ protected void plotCircleForIndy(AbstractEAIndividual indy, String text) { InterfaceDataTypeDouble tmpIndy1 = (InterfaceDataTypeDouble) indy; @@ -2046,9 +2043,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } /** + * @param indy * @tested plots the old position, new position, personal best position and * neighborhood best position for a given individual - * @param indy */ protected void plotStatusForIndy(AbstractEAIndividual indy) { //plot newPos @@ -2086,7 +2083,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac this.m_TopologySwarm.getFunctionArea().addDElement(point); } -// protected void saveCurrentPlotAsJPG(String filename){ + // protected void saveCurrentPlotAsJPG(String filename){ // if (getDirForCurrentExperiment().equals("unset")) { // System.out.println("saveCurrentPlotAsJPG: no directory for output specified, please use setDirForCurrentExperiment first"); // return; @@ -2151,7 +2148,7 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Create a Niche PSO with parameters as to Brits, Engelbrecht & Bergh: A * Niching Particle Swarm Optimizer. SEAL 2002. Exeption: the swarm size is * 200 by default, because 30 (of the orig. paper) seems way too low. - * + *

* The evaluation count is required currently due to the * generation-dependent intertness decay used by the std. variant. To alter * the terminator, use OptimizationParameters.setTerminator(), and mind the intertness @@ -2176,12 +2173,12 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Optimizer. SEAL 2002. Exeption: the swarm size is 100 by default, because * 30 (of the orig. paper) seems way too low. * - * @see #stdNPSO(AbstractOptimizationProblem, long, int) - * @param an already existing NichePSO instance or null to create a new one + * @param an already existing NichePSO instance or null to create a new one * @param problem * @param randSeed * @param evalCnt * @return + * @see #stdNPSO(AbstractOptimizationProblem, long, int) */ public static final OptimizationParameters stdNPSO(NichePSO npso, AbstractOptimizationProblem problem, long randSeed, int evalCnt) { if (npso == null) { @@ -2226,12 +2223,12 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Optimizer. SEAL 2002. Exeption: the swarm size is 200 by default, because * 30 (of the orig. paper) seems way too low. * - * @see #stdNPSO(AbstractOptimizationProblem, long, int) - * @param an already existing NichePSO instance or null to create a new one + * @param an already existing NichePSO instance or null to create a new one * @param problem * @param randSeed * @param evalCnt * @return + * @see #stdNPSO(AbstractOptimizationProblem, long, int) */ public static final OptimizationParameters starNPSO(NichePSO npso, AbstractOptimizationProblem problem, long randSeed, int evalCnt) { starNPSO(npso, evalCnt); @@ -2285,12 +2282,12 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac @Override public String[] getAdditionalDataInfo() { return new String[]{"Size of the main swarm of explorers", - "Number of sub-swarms currently active", - "Average sub-swarm size", - "The number of stored potential local optima", - "The median correlation of stored solutions", - "The mean distance of stored solutions", - "Current inertness of the main swarm"}; + "Number of sub-swarms currently active", + "Average sub-swarm size", + "The number of stored potential local optima", + "The median correlation of stored solutions", + "The mean distance of stored solutions", + "Current inertness of the main swarm"}; } @Override @@ -2301,12 +2298,12 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac double medCor = inactives.getCorrelations()[3]; // median correlation of best indies of inactive subswarms double meanDist = inactives.getPopulationMeasures()[0]; return new Object[]{getMainSwarm().getPopulation().size(), - actSwarms, - avgSpSize, - getNumArchived(), - medCor, - meanDist, - getMainSwarm().getInertnessOrChi()}; + actSwarms, + avgSpSize, + getNumArchived(), + medCor, + meanDist, + getMainSwarm().getInertnessOrChi()}; } /** diff --git a/src/eva2/optimization/strategies/PDDifferentialEvolution.java b/src/eva2/optimization/strategies/PDDifferentialEvolution.java index dc31563d..42f872af 100644 --- a/src/eva2/optimization/strategies/PDDifferentialEvolution.java +++ b/src/eva2/optimization/strategies/PDDifferentialEvolution.java @@ -18,6 +18,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.util.Vector; /** @@ -27,7 +28,6 @@ import java.util.Vector; * crossover operators selected. Added aging mechanism to provide for * dynamically changing problems. If an individual reaches the age limit, it is * doomed and replaced by the next challenge vector, even if its worse. - * */ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Serializable { @@ -54,7 +54,6 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * A constructor. - * */ public PDDifferentialEvolution() { // sets DE2 as default @@ -111,7 +110,7 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -246,7 +245,7 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * This method will return the delta vector to the best individual * - * @param pop The population to choose the best from + * @param pop The population to choose the best from * @param indy The current individual * @return the delta vector */ @@ -489,7 +488,6 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri * slightly worse for schemes that rely on current best individuals, because * improvements are not immediately incorporated as in the steady state DE. * However it may be easier to parallelize. - * */ public void optimizeGenerational() { int parentIndex; @@ -535,7 +533,7 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri } else { parentIndex = RNG.randomInt(0, this.m_Population.size() - 1); } - if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one + if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one m_Population.replaceIndividualAt(nextDoomed, indy); nextDoomed = getNextDoomed(m_Population, nextDoomed + 1); } else { @@ -594,7 +592,7 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri indy = generateNewIndividual(m_Population, index); this.m_Problem.evaluate(indy); this.m_Population.incrFunctionCalls(); - if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one + if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one m_Population.replaceIndividualAt(nextDoomed, indy); nextDoomed = getNextDoomed(m_Population, nextDoomed + 1); } else { @@ -628,9 +626,9 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri * younger, -1 is returned. The start index of the search may be provided to * make iterative search efficient. * - * @param pop Population to search - * @param startIndex index to start the search from - * @return index of an overaged individual or -1 + * @param pop Population to search + * @param startIndex index to start the search from + * @return index of an overaged individual or -1 */ protected int getNextDoomed(Population pop, int startIndex) { if (maximumAge > 0) { @@ -881,7 +879,6 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * @return the maximumAge - * */ public int getMaximumAge() { return maximumAge; @@ -889,7 +886,6 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * @param maximumAge the maximumAge to set - * */ public void setMaximumAge(int maximumAge) { this.maximumAge = maximumAge; @@ -969,7 +965,6 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * @return the maximumAge - * */ public boolean isReEvaluate() { return reEvaluate; @@ -977,7 +972,6 @@ public class PDDifferentialEvolution implements InterfaceOptimizer, java.io.Seri /** * @param maximumAge the maximumAge to set - * */ public void setReEvaluate(boolean reEvaluate) { this.reEvaluate = reEvaluate; diff --git a/src/eva2/optimization/strategies/ParticleFilterOptimization.java b/src/eva2/optimization/strategies/ParticleFilterOptimization.java index 4973264b..4810f4ad 100644 --- a/src/eva2/optimization/strategies/ParticleFilterOptimization.java +++ b/src/eva2/optimization/strategies/ParticleFilterOptimization.java @@ -23,7 +23,7 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * here and not completely checked whether this works on arbitrary problem * instances. MK did some adaptations, this should work on real valued problems * now. - * + *

* This is a implementation of Genetic Algorithms. Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture * @@ -116,7 +116,7 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -142,7 +142,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * This method will resample the given population using EA parent selection. - * */ protected Population resample(Population pop) { Population parents; @@ -238,7 +237,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * Optimization loop of a resampling particle filter, restructured by MK. - * */ @Override public void optimize() { @@ -411,7 +409,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * @return the withShow - * */ public boolean isWithShow() { return withShow; @@ -436,7 +433,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * @param withShow the withShow to set - * */ public void setWithShow(boolean wShow) { this.withShow = wShow; @@ -459,7 +455,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * @return the sleepTime - * */ public int getSleepTime() { return sleepTime; @@ -467,7 +462,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * @param sleepTime the sleepTime to set - * */ public void setSleepTime(int sleepTime) { this.sleepTime = sleepTime; @@ -475,7 +469,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * @return the mutationSigma - * */ public double getMutationSigma() { return mutationSigma; @@ -483,7 +476,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S /** * @param mutationSigma the mutationSigma to set - * */ public void setMutationSigma(double mutationSigma) { this.mutationSigma = mutationSigma; diff --git a/src/eva2/optimization/strategies/ParticleSubSwarmOptimization.java b/src/eva2/optimization/strategies/ParticleSubSwarmOptimization.java index 47883222..fdbf09a4 100644 --- a/src/eva2/optimization/strategies/ParticleSubSwarmOptimization.java +++ b/src/eva2/optimization/strategies/ParticleSubSwarmOptimization.java @@ -9,362 +9,375 @@ import eva2.optimization.population.Population; import eva2.optimization.problems.AbstractOptimizationProblem; import eva2.optimization.problems.InterfaceOptimizationProblem; import eva2.tools.math.Mathematics; + import java.util.Vector; /** * This implements a particle swarm optimizer which is used by the NichePSO and ANPSO * to represent and train the mainswarm or any subswarm. - * This is done by extending the standard particle swarm optimizer so that + * This is done by extending the standard particle swarm optimizer so that * - additional member variables (characterizing and parameterizing the subswarm) are available * - additional information is added to the particles during an optimization loop * - additional functions to add, remove and reinitialize particles are available */ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO { - - protected double maxAllowedSwarmRadiusNormal; // maximal allowed swarmradius (relative to the search space) - public static boolean hideFromGOE = true; // dont want it to be available in the GUI - protected boolean active; // marks the swarm active or inactive - - protected double maxPosDist; // maximal possible distance in the search space, depends on problem -> initMaxPosDist() - private int particleIndexCounter; // used to give each particle a unique index (for debbugging and plotting) - private int fitnessArchiveSize = 15; // maximal number of fitnessvalues remembered from former iterations - //ParameterupdateStrategies + protected double maxAllowedSwarmRadiusNormal; // maximal allowed swarmradius (relative to the search space) + public static boolean hideFromGOE = true; // dont want it to be available in the GUI + protected boolean active; // marks the swarm active or inactive + + protected double maxPosDist; // maximal possible distance in the search space, depends on problem -> initMaxPosDist() + private int particleIndexCounter; // used to give each particle a unique index (for debbugging and plotting) + private int fitnessArchiveSize = 15; // maximal number of fitnessvalues remembered from former iterations + + //ParameterupdateStrategies // InterfaceParameterAging inertnessAging = new NoParameterAging(); /********************************************************************************************************************** * ctors, clone */ - /** @tested ps - * ctor - */ - public ParticleSubSwarmOptimization() { - updateMaxPosDist(); - this.maxAllowedSwarmRadiusNormal = 0.1; // set similar to "particle swarms for multimodal optimization" by Oezcan and Yilmaz - this.active = true; - particleIndexCounter = getPopulation().size(); // newly added particles will start at this index + /** + * @tested ps + * ctor + */ + public ParticleSubSwarmOptimization() { + updateMaxPosDist(); + this.maxAllowedSwarmRadiusNormal = 0.1; // set similar to "particle swarms for multimodal optimization" by Oezcan and Yilmaz + this.active = true; + particleIndexCounter = getPopulation().size(); // newly added particles will start at this index // setInitialVelocity(1.); - } + } - /** @tested - * cpyctor - */ - public ParticleSubSwarmOptimization(ParticleSubSwarmOptimization a) { - super(a); - if (a.m_BestIndividual != null){ - m_BestIndividual = (AbstractEAIndividual)a.m_BestIndividual.clone(); - } - - maxAllowedSwarmRadiusNormal = a.maxAllowedSwarmRadiusNormal; - active = a.active; - maxPosDist = a.maxPosDist; - particleIndexCounter = a.particleIndexCounter; + /** + * @tested cpyctor + */ + public ParticleSubSwarmOptimization(ParticleSubSwarmOptimization a) { + super(a); + if (a.m_BestIndividual != null) { + m_BestIndividual = (AbstractEAIndividual) a.m_BestIndividual.clone(); + } + + maxAllowedSwarmRadiusNormal = a.maxAllowedSwarmRadiusNormal; + active = a.active; + maxPosDist = a.maxPosDist; + particleIndexCounter = a.particleIndexCounter; // inertnessAging = (InterfaceParameterAging)a.inertnessAging.clone(); - fitnessArchiveSize = a.fitnessArchiveSize; - } - - /** @tested - * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#clone() - */ + fitnessArchiveSize = a.fitnessArchiveSize; + } + + /** + * @tested (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#clone() + */ @Override - public Object clone() { - return (Object) new ParticleSubSwarmOptimization(this); - } - - + public Object clone() { + return (Object) new ParticleSubSwarmOptimization(this); + } + + /********************************************************************************************************************** * inits */ - /** @tested ps - * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#init() - */ + /** + * @tested ps + * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#init() + */ @Override - public void init(){ - super.init(); - - initIndividuals(); + public void init() { + super.init(); - updateMBestIndividual(); - updateMaxPosDist(); - particleIndexCounter = getPopulation().size(); + initIndividuals(); + + updateMBestIndividual(); + updateMaxPosDist(); + particleIndexCounter = getPopulation().size(); // setInertnessOrChi(inertnessAging.getStartValue()); - } - - /** @tested ps - * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#initByPopulation(javaeva.server.oa.go.Populations.Population, boolean) - */ + } + + /** + * @tested ps + * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#initByPopulation(javaeva.server.oa.go.Populations.Population, boolean) + */ @Override - public void initByPopulation(Population pop, boolean reset){ - super.initByPopulation(pop, reset); - initIndividuals(); + public void initByPopulation(Population pop, boolean reset) { + super.initByPopulation(pop, reset); + initIndividuals(); - updateMBestIndividual(); - updateMaxPosDist(); - particleIndexCounter = getPopulation().size(); - } - - /** @tested junit& - * adds a vector for fitnessvalues to all individuals in the swarm - * and sets the current fitness as the first value - */ - protected void initIndividuals(){ - for (int i = 0; i < m_Population.size(); ++i){ - AbstractEAIndividual indy = (AbstractEAIndividual)(m_Population.getEAIndividual(i)); - initSubSwarmDefaultsOf(indy); - } - } + updateMBestIndividual(); + updateMaxPosDist(); + particleIndexCounter = getPopulation().size(); + } - public static void initSubSwarmDefaultsOf(AbstractEAIndividual indy) { - initFitnessArchiveOf(indy); - initFitnessStdDevOf(indy); - initPersonalBestOf(indy); - initPBestImprInARowOf(indy); - } + /** + * @tested junit& + * adds a vector for fitnessvalues to all individuals in the swarm + * and sets the current fitness as the first value + */ + protected void initIndividuals() { + for (int i = 0; i < m_Population.size(); ++i) { + AbstractEAIndividual indy = (AbstractEAIndividual) (m_Population.getEAIndividual(i)); + initSubSwarmDefaultsOf(indy); + } + } - public static void initFitnessArchiveOf(AbstractEAIndividual indy) { - Vector vec = new Vector(); - double scalarFitness = sum(indy.getFitness()); // if multiobjective, use the sum of all fitnessvalues (dont use the norm because fitnessvalues may be negative) - vec.add(new Double(scalarFitness)); - indy.putData(NichePSO.fitArchiveKey, vec); - } - - /** @tested emp - * adds a std deviation value to an individual - * and initially sets this value to infinity. - */ - public static void initFitnessStdDevOf(AbstractEAIndividual indy) { - // init stddev to inf, dont want immediate convergence... - indy.putData(NichePSO.stdDevKey, new Double(Double.POSITIVE_INFINITY)); - } + public static void initSubSwarmDefaultsOf(AbstractEAIndividual indy) { + initFitnessArchiveOf(indy); + initFitnessStdDevOf(indy); + initPersonalBestOf(indy); + initPBestImprInARowOf(indy); + } - public static void initPBestImprInARowOf(AbstractEAIndividual indy) { - indy.putData("PBestImprovementsInARow", new Integer(0)); - } - - /** @tested junit - * adds a representation of the personal best to an individual - * and initially sets the current individual as its personal best. - */ - public static void initPersonalBestOf(AbstractEAIndividual indy) { - AbstractEAIndividual newpbest = (AbstractEAIndividual)indy.clone(); - newpbest.putData("PersonalBestKey", null); // dont want to have a chain of pbests - indy.putData("PersonalBestKey", newpbest); - } + public static void initFitnessArchiveOf(AbstractEAIndividual indy) { + Vector vec = new Vector(); + double scalarFitness = sum(indy.getFitness()); // if multiobjective, use the sum of all fitnessvalues (dont use the norm because fitnessvalues may be negative) + vec.add(new Double(scalarFitness)); + indy.putData(NichePSO.fitArchiveKey, vec); + } + + /** + * @tested emp + * adds a std deviation value to an individual + * and initially sets this value to infinity. + */ + public static void initFitnessStdDevOf(AbstractEAIndividual indy) { + // init stddev to inf, dont want immediate convergence... + indy.putData(NichePSO.stdDevKey, new Double(Double.POSITIVE_INFINITY)); + } + + public static void initPBestImprInARowOf(AbstractEAIndividual indy) { + indy.putData("PBestImprovementsInARow", new Integer(0)); + } + + /** + * @tested junit + * adds a representation of the personal best to an individual + * and initially sets the current individual as its personal best. + */ + public static void initPersonalBestOf(AbstractEAIndividual indy) { + AbstractEAIndividual newpbest = (AbstractEAIndividual) indy.clone(); + newpbest.putData("PersonalBestKey", null); // dont want to have a chain of pbests + indy.putData("PersonalBestKey", newpbest); + } /********************************************************************************************************************** * Optimization - */ - /** @tested ps - * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#optimize() - */ + */ + /** + * @tested ps + * (non-Javadoc) @see javaeva.server.oa.go.Strategies.ParticleSwarmOptimization#optimize() + */ @Override - public void optimize(){ - super.optimize(); - updateFitnessArchives(); - updateFitnessStdDev(); - updatePersonalBest(); - updateMBestIndividual(); + public void optimize() { + super.optimize(); + updateFitnessArchives(); + updateFitnessStdDev(); + updatePersonalBest(); + updateMBestIndividual(); // updateParameters(); - } - - public void reinitIndividuals(Vector indicesToReinit) { - for (int[] indices : indicesToReinit) { - addNewParticlesToPopulation(indices); - } - } - - /** - * Get the next set of indices increasing the internal particle counter. - * Should only be called immediately before adding the new individuals. - * - * @param num - * @return - */ - private int[] getNextIndices(int num) { - int[] indices = new int[num]; - for (int i = 0; i < num; ++i){ - indices[i] = particleIndexCounter; - ++particleIndexCounter; - } - return indices; - } - - public void reinitIndividuals(int numIndies) { - addNewParticlesToPopulation(getNextIndices(numIndies)); - } - -/********************************************************************************************************************** - * updateTopology - */ - - protected AbstractEAIndividual getIndyByParticleIndexAndPopulation(Population pop, Integer index){ - for (int i = 0; i < pop.size(); ++i) - { - AbstractEAIndividual indy = pop.getEAIndividual(i); -// Integer tmp = (Integer)indy.getData("particleIndex"); // CPU-Time Hotspot -// if (index.equals(tmp)) return indy; - if (index.intValue() == indy.getIndividualIndex()) { - return indy; - } - } - return null; } - /* (non-Javadoc) - * @see eva2.optimization.strategies.ParticleSwarmOptimization#addSortedIndizesTo(eva2.optimization.populations.Population) - */ + public void reinitIndividuals(Vector indicesToReinit) { + for (int[] indices : indicesToReinit) { + addNewParticlesToPopulation(indices); + } + } + + /** + * Get the next set of indices increasing the internal particle counter. + * Should only be called immediately before adding the new individuals. + * + * @param num + * @return + */ + private int[] getNextIndices(int num) { + int[] indices = new int[num]; + for (int i = 0; i < num; ++i) { + indices[i] = particleIndexCounter; + ++particleIndexCounter; + } + return indices; + } + + public void reinitIndividuals(int numIndies) { + addNewParticlesToPopulation(getNextIndices(numIndies)); + } + + /** + * ******************************************************************************************************************* + * updateTopology + */ + + protected AbstractEAIndividual getIndyByParticleIndexAndPopulation(Population pop, Integer index) { + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual indy = pop.getEAIndividual(i); +// Integer tmp = (Integer)indy.getData("particleIndex"); // CPU-Time Hotspot +// if (index.equals(tmp)) return indy; + if (index.intValue() == indy.getIndividualIndex()) { + return indy; + } + } + return null; + } + + /* (non-Javadoc) + * @see eva2.optimization.strategies.ParticleSwarmOptimization#addSortedIndizesTo(eva2.optimization.populations.Population) + */ @Override - protected void addSortedIndicesTo(Object[] sortedPopulation, Population pop) { - int origIndex; - for (int i=0; i bestindypbest). - // This is necessary because the current m_BestIndividual my came from - // an individual that left the swarm and would never be replaced if it - // would dominate all remaining positions in the swarm. - AbstractEAIndividual bestindy = getPopulation().getBestEAIndividual(); - AbstractEAIndividual bestindypbest = (AbstractEAIndividual)bestindy.getData("PersonalBestKey"); - m_BestIndividual = (AbstractEAIndividual)bestindypbest.clone(); - for (int i = 0; i < getPopulation().size(); ++i){ - AbstractEAIndividual currentindy = getPopulation().getEAIndividual(i); - AbstractEAIndividual currentindypbest = (AbstractEAIndividual)currentindy.getData("PersonalBestKey"); - if (currentindypbest.isDominating(m_BestIndividual)){ - m_BestIndividual = (AbstractEAIndividual)currentindypbest.clone(); + */ + /** + * @tested ps + * when particles enter or leave the population, + * call this method to update the status of the population + */ + public void populationSizeHasChanged() { + updateMBestIndividual(); + } + + /** + * @tested junit& + * updates the m_BestIndividual member which represents the gbest individual + * (i.e. the best position and fitness encountered by any particle of the swarm) + * Beware: if a particle enters the swarm its knowledge about its pbest enters the swarm, + * on the other side: if a particle leaves the swarm its knowledge leaves the swarm as well. + */ + protected void updateMBestIndividual() { + if (getPopulation().size() == 0) { + return; + } + // First: set m_BestIndividual to any personal best position in the swarm (-> bestindypbest). + // This is necessary because the current m_BestIndividual my came from + // an individual that left the swarm and would never be replaced if it + // would dominate all remaining positions in the swarm. + AbstractEAIndividual bestindy = getPopulation().getBestEAIndividual(); + AbstractEAIndividual bestindypbest = (AbstractEAIndividual) bestindy.getData("PersonalBestKey"); + m_BestIndividual = (AbstractEAIndividual) bestindypbest.clone(); + for (int i = 0; i < getPopulation().size(); ++i) { + AbstractEAIndividual currentindy = getPopulation().getEAIndividual(i); + AbstractEAIndividual currentindypbest = (AbstractEAIndividual) currentindy.getData("PersonalBestKey"); + if (currentindypbest.isDominating(m_BestIndividual)) { + m_BestIndividual = (AbstractEAIndividual) currentindypbest.clone(); // ++gbestImprovmentsInARow; - } //else gbestImprovmentsInARow = 0; - } - } - - /** @tested junit, dbg - * adds the current fitnessvalue to the fitnessarchive for every individual in the swarm. - * Keeps the fitnessarchive at a limited size (lim+1). - */ - public void updateFitnessArchives(){ - //int lim = 3; // maximal number of fitnessvalues remembered from former iterations - for (int i = 0; i < m_Population.size(); ++i){ - AbstractEAIndividual indy = (AbstractEAIndividual)m_Population.getEAIndividual(i); - Vector fitArchive_old = (Vector)(indy.getData(NichePSO.fitArchiveKey)); - double scalarFitness = sum(indy.getFitness()); // if multiobjective, use the sum of all fitnessvalues (dont use the norm because fitnessvalues may be negative) - Double fitness = new Double(scalarFitness); - - Vector fitArchive_new = new Vector(); - int end = fitArchive_old.size(); - int start = 0; - if (end >= fitnessArchiveSize) { - start = end-fitnessArchiveSize; - } - - for (int j = start; j < end; ++j){ - fitArchive_new.add(fitArchive_old.get(j)); - } - fitArchive_new.add(fitness); - indy.putData(NichePSO.fitArchiveKey, fitArchive_new); - } - } - - /** @tested junit - * sets the std dev value of all individuals in the swarm - * to the std deviation over the last 3 fitness values - */ - public void updateFitnessStdDev(){ - for (int i = 0; i < m_Population.size(); ++i){ - AbstractEAIndividual currentindy = m_Population.getEAIndividual(i); - Vector fitnessArchive = (Vector)(currentindy.getData(NichePSO.fitArchiveKey)); - // the stddev is computed over 3 values as suggested in - // "a niching particle swarm optimizer" by Brits et al. - double sd = stdDev(fitnessArchive,NichePSO.defaultFitStdDevHorizon); - currentindy.putData(NichePSO.stdDevKey, new Double(sd)); - } - } - - /** @tested junit&, junit - * update the personal best representation if the current individual is better than the pbest - */ - public void updatePersonalBest(){ - for (int i = 0; i < m_Population.size(); ++i){ - AbstractEAIndividual currentindy = m_Population.getEAIndividual(i); - AbstractEAIndividual pbest = (AbstractEAIndividual)currentindy.getData("PersonalBestKey"); - if (currentindy.isDominating(pbest)){ - initPersonalBestOf(currentindy); - - //PBestImprovementsInARow - Integer counter = (Integer)currentindy.getData("PBestImprovementsInARow"); - counter = new Integer(counter.intValue()+1); - currentindy.putData("PBestImprovementsInARow",counter); - }else{ - initPBestImprInARowOf(currentindy); - } - } - } - - /** @tested junit .. - * updates the member representing the maximal possible distance in the current searchspace - */ - public void updateMaxPosDist(){ - // compute the maximal possible distance in the search space: - AbstractOptimizationProblem prob = (AbstractOptimizationProblem)m_Problem; - // problem must have called initializeProblem, so that the template is set correctly. This shouls always be the case here... - AbstractEAIndividual template = prob.getIndividualTemplate(); - if (template == null){ - System.out.println("Problem does not implement getIndividualTemplate, updateMaxPosDist could not infer dimensions"); - return; - } - if (!(template instanceof ESIndividualDoubleData) && !(template instanceof InterfaceDataTypeDouble)){ - System.out.println("Problem does not use ESIndividualDoubleData or InterfaceDataTypeDouble. UpdateMaxPosDist could not infer dimensions."); - return; - } + } //else gbestImprovmentsInARow = 0; + } + } + + /** + * @tested junit, dbg + * adds the current fitnessvalue to the fitnessarchive for every individual in the swarm. + * Keeps the fitnessarchive at a limited size (lim+1). + */ + public void updateFitnessArchives() { + //int lim = 3; // maximal number of fitnessvalues remembered from former iterations + for (int i = 0; i < m_Population.size(); ++i) { + AbstractEAIndividual indy = (AbstractEAIndividual) m_Population.getEAIndividual(i); + Vector fitArchive_old = (Vector) (indy.getData(NichePSO.fitArchiveKey)); + double scalarFitness = sum(indy.getFitness()); // if multiobjective, use the sum of all fitnessvalues (dont use the norm because fitnessvalues may be negative) + Double fitness = new Double(scalarFitness); + + Vector fitArchive_new = new Vector(); + int end = fitArchive_old.size(); + int start = 0; + if (end >= fitnessArchiveSize) { + start = end - fitnessArchiveSize; + } + + for (int j = start; j < end; ++j) { + fitArchive_new.add(fitArchive_old.get(j)); + } + fitArchive_new.add(fitness); + indy.putData(NichePSO.fitArchiveKey, fitArchive_new); + } + } + + /** + * @tested junit + * sets the std dev value of all individuals in the swarm + * to the std deviation over the last 3 fitness values + */ + public void updateFitnessStdDev() { + for (int i = 0; i < m_Population.size(); ++i) { + AbstractEAIndividual currentindy = m_Population.getEAIndividual(i); + Vector fitnessArchive = (Vector) (currentindy.getData(NichePSO.fitArchiveKey)); + // the stddev is computed over 3 values as suggested in + // "a niching particle swarm optimizer" by Brits et al. + double sd = stdDev(fitnessArchive, NichePSO.defaultFitStdDevHorizon); + currentindy.putData(NichePSO.stdDevKey, new Double(sd)); + } + } + + /** + * @tested junit&, junit + * update the personal best representation if the current individual is better than the pbest + */ + public void updatePersonalBest() { + for (int i = 0; i < m_Population.size(); ++i) { + AbstractEAIndividual currentindy = m_Population.getEAIndividual(i); + AbstractEAIndividual pbest = (AbstractEAIndividual) currentindy.getData("PersonalBestKey"); + if (currentindy.isDominating(pbest)) { + initPersonalBestOf(currentindy); + + //PBestImprovementsInARow + Integer counter = (Integer) currentindy.getData("PBestImprovementsInARow"); + counter = new Integer(counter.intValue() + 1); + currentindy.putData("PBestImprovementsInARow", counter); + } else { + initPBestImprInARowOf(currentindy); + } + } + } + + /** + * @tested junit .. + * updates the member representing the maximal possible distance in the current searchspace + */ + public void updateMaxPosDist() { + // compute the maximal possible distance in the search space: + AbstractOptimizationProblem prob = (AbstractOptimizationProblem) m_Problem; + // problem must have called initializeProblem, so that the template is set correctly. This shouls always be the case here... + AbstractEAIndividual template = prob.getIndividualTemplate(); + if (template == null) { + System.out.println("Problem does not implement getIndividualTemplate, updateMaxPosDist could not infer dimensions"); + return; + } + if (!(template instanceof ESIndividualDoubleData) && !(template instanceof InterfaceDataTypeDouble)) { + System.out.println("Problem does not use ESIndividualDoubleData or InterfaceDataTypeDouble. UpdateMaxPosDist could not infer dimensions."); + return; + } // ESIndividualDoubleData min = (ESIndividualDoubleData)template.clone(); // ESIndividualDoubleData max = (ESIndividualDoubleData)template.clone(); - double[][] range = null; - if (template instanceof ESIndividualDoubleData) { - range = ((ESIndividualDoubleData)template).getDoubleRange(); - } - else { - range = ((InterfaceDataTypeDouble)template).getDoubleRange(); - } - double[] minValInDim = new double[range.length]; - double[] maxValInDim = new double[range.length]; - for (int i = 0; i < minValInDim.length; ++i){ - minValInDim[i] = range[i][0]; // get lower boarder for dimension i - maxValInDim[i] = range[i][1]; // get upper boarder for dimension i - } + double[][] range = null; + if (template instanceof ESIndividualDoubleData) { + range = ((ESIndividualDoubleData) template).getDoubleRange(); + } else { + range = ((InterfaceDataTypeDouble) template).getDoubleRange(); + } + double[] minValInDim = new double[range.length]; + double[] maxValInDim = new double[range.length]; + for (int i = 0; i < minValInDim.length; ++i) { + minValInDim[i] = range[i][0]; // get lower boarder for dimension i + maxValInDim[i] = range[i][1]; // get upper boarder for dimension i + } // min.SetDoubleGenotype(minValInDim); // set all dimensions to min // max.SetDoubleGenotype(maxValInDim); // set all dimensions to max - this.maxPosDist = Mathematics.euclidianDist(minValInDim, maxValInDim); - } - + this.maxPosDist = Mathematics.euclidianDist(minValInDim, maxValInDim); + } + // /** // * Parametervalues of the optimizer may change over time // */ @@ -373,196 +386,207 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO // } /********************************************************************************************************************** * dist, mean, stddev, sum - */ - /** @tested junit - * returns the euclidean distance in the search space between indy1 and indy2. - * @param indy1 - * @param indy2 - * @return - */ - public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2){ - return EuclideanMetric.euclideanDistance(AbstractEAIndividual.getDoublePositionShallow(indy1), - AbstractEAIndividual.getDoublePositionShallow(indy2)); - } - - /** @tested junit - * returns the mean value for the provided data vec but only for a given number of values. - * If range > vec.size() the mean is computed only for the available data. - * @param vec - * @param range number of values (beginning at the end of vec!) considered to compute the mean - * @return - */ - protected static double mean(Vector vec,int range){ - if (vec.size() < range) { - range = vec.size(); - } - double sum = 0; - for (int i = vec.size()-range; i < vec.size(); ++i){ - sum += vec.get(i).doubleValue(); - } - return sum/range; - } - - /** @tested junit - * returns the std deviation for the provided data vec but only for a given number of values - * @param vec data - * @param range number of values (beginning at the end of vec!) considered to compute the std deviation - * @return - */ - public static double stdDev(Vector vec, int range){ - double ssum = 0; - if (vec.size()-range < 0 || range < 2) { - return Double.POSITIVE_INFINITY; - } // not enough values, dont risk early convergence - double mean = mean(vec,range); - for (int i = vec.size()-range; i < vec.size(); ++i){ - ssum += Math.pow(vec.get(i).doubleValue()-mean,2); - } - double result = Math.sqrt(ssum/(range-1)); - return result; - } + */ + /** + * @param indy1 + * @param indy2 + * @return + * @tested junit + * returns the euclidean distance in the search space between indy1 and indy2. + */ + public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { + return EuclideanMetric.euclideanDistance(AbstractEAIndividual.getDoublePositionShallow(indy1), + AbstractEAIndividual.getDoublePositionShallow(indy2)); + } + + /** + * @param vec + * @param range number of values (beginning at the end of vec!) considered to compute the mean + * @return + * @tested junit + * returns the mean value for the provided data vec but only for a given number of values. + * If range > vec.size() the mean is computed only for the available data. + */ + protected static double mean(Vector vec, int range) { + if (vec.size() < range) { + range = vec.size(); + } + double sum = 0; + for (int i = vec.size() - range; i < vec.size(); ++i) { + sum += vec.get(i).doubleValue(); + } + return sum / range; + } + + /** + * @param vec data + * @param range number of values (beginning at the end of vec!) considered to compute the std deviation + * @return + * @tested junit + * returns the std deviation for the provided data vec but only for a given number of values + */ + public static double stdDev(Vector vec, int range) { + double ssum = 0; + if (vec.size() - range < 0 || range < 2) { + return Double.POSITIVE_INFINITY; + } // not enough values, dont risk early convergence + double mean = mean(vec, range); + for (int i = vec.size() - range; i < vec.size(); ++i) { + ssum += Math.pow(vec.get(i).doubleValue() - mean, 2); + } + double result = Math.sqrt(ssum / (range - 1)); + return result; + } + + private static double sum(double[] fitness) { + double ret = 0.; + for (double d : fitness) { + ret += d; + } + return ret; + } + + /** + * @param normalisedRadius + * @return + * @tested ps + * Interpretes the given maximal radius as normalised according to the current search space. + * Values from [0,1], 1 means the radius can be as large as the maximal possible distance + * (between any two points) in the search space. + * Because the swarmradius and distances (e.g. in merging and absortion) are given in a standard euclidean metric, + * this function converts the normalised distance into the standard euclidean distance. + */ + public double interpreteAsNormalisedSwarmRadius(double normalisedRadius) { + if (normalisedRadius > 1 || normalisedRadius < 0) { + System.out.println("interpreteAsNormalisedSwarmRadius: Radius not normalised to [0,1]"); + } + // compute standard euclidean radius from normalised radius: + return normalisedRadius * maxPosDist; + } - private static double sum(double[] fitness) { - double ret = 0.; - for(double d : fitness){ - ret += d; - } - return ret; - } - - /** @tested ps - * Interpretes the given maximal radius as normalised according to the current search space. - * Values from [0,1], 1 means the radius can be as large as the maximal possible distance - * (between any two points) in the search space. - * Because the swarmradius and distances (e.g. in merging and absortion) are given in a standard euclidean metric, - * this function converts the normalised distance into the standard euclidean distance. - * @param normalisedRadius - * @return - */ - public double interpreteAsNormalisedSwarmRadius(double normalisedRadius){ - if(normalisedRadius > 1 || normalisedRadius < 0){ - System.out.println("interpreteAsNormalisedSwarmRadius: Radius not normalised to [0,1]"); - } - // compute standard euclidean radius from normalised radius: - return normalisedRadius*maxPosDist; - } - /********************************************************************************************************************** * addNewParticlesToPopulation ... - */ - - /** @tested junit ... - * adds new particles to this swarm, rndly inited over the search space by the problem - * @param particleIndices set of indices that should be used for the added particles, if null new indices are created - */ - private void addNewParticlesToPopulation(int[] particleIndices) { - if (particleIndices == null) { - throw new RuntimeException("Error, unable to use null index array (ParticleSubSwarmOptimization.addNewParticlesToPOpulation)"); - } + */ - Population tmp = new Population(); - tmp.setTargetSize(particleIndices.length); - ////////////// - AbstractOptimizationProblem prob = (AbstractOptimizationProblem)m_Problem; - AbstractEAIndividual template = prob.getIndividualTemplate(); // problem must be inited at this point - AbstractEAIndividual tmpIndy; - - for (int i = 0; i < tmp.getTargetSize(); i++) { - tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)template).clone(); + /** + * @param particleIndices set of indices that should be used for the added particles, if null new indices are created + * @tested junit ... + * adds new particles to this swarm, rndly inited over the search space by the problem + */ + private void addNewParticlesToPopulation(int[] particleIndices) { + if (particleIndices == null) { + throw new RuntimeException("Error, unable to use null index array (ParticleSubSwarmOptimization.addNewParticlesToPOpulation)"); + } + + Population tmp = new Population(); + tmp.setTargetSize(particleIndices.length); + ////////////// + AbstractOptimizationProblem prob = (AbstractOptimizationProblem) m_Problem; + AbstractEAIndividual template = prob.getIndividualTemplate(); // problem must be inited at this point + AbstractEAIndividual tmpIndy; + + for (int i = 0; i < tmp.getTargetSize(); i++) { + tmpIndy = (AbstractEAIndividual) ((AbstractEAIndividual) template).clone(); tmpIndy.init(prob); tmp.add(tmpIndy); } - tmp.init(); + tmp.init(); /////////// - - ParticleSubSwarmOptimization tmpopt = new ParticleSubSwarmOptimization(); - tmpopt.setProblem(this.m_Problem); - tmpopt.evaluatePopulation(tmp); - tmpopt.initByPopulation(tmp, false); // + size FCs - - if (particleIndices != null){ // use given indices - for (int i = 0; i < tmpopt.getPopulation().size(); ++i){ - AbstractEAIndividual indy = tmpopt.getPopulation().getEAIndividual(i); - indy.SetIndividualIndex(particleIndices[i]);//SetData("particleIndex", new Integer(particleIndices[i])); - indy.putData("newParticleFlag",new Boolean(true)); // for plotting - } - } - addPopulation(tmpopt); // add to the mainswarm (FCs will be considered) - populationSizeHasChanged(); - } - + ParticleSubSwarmOptimization tmpopt = new ParticleSubSwarmOptimization(); + tmpopt.setProblem(this.m_Problem); + tmpopt.evaluatePopulation(tmp); + tmpopt.initByPopulation(tmp, false); // + size FCs + + if (particleIndices != null) { // use given indices + for (int i = 0; i < tmpopt.getPopulation().size(); ++i) { + AbstractEAIndividual indy = tmpopt.getPopulation().getEAIndividual(i); + indy.SetIndividualIndex(particleIndices[i]);//SetData("particleIndex", new Integer(particleIndices[i])); + indy.putData("newParticleFlag", new Boolean(true)); // for plotting + } + } + + addPopulation(tmpopt); // add to the mainswarm (FCs will be considered) + populationSizeHasChanged(); + } + /********************************************************************************************************************** * add and remove functions that keep the function calls of the population "accurate" * (here "accurate" applies to the situation where an added population is always deleted in the next step, like in merging...) - */ - /** @tested nn - * adds a population and its function calls to this.population - * @param pop - */ - public void addPopulation(ParticleSubSwarmOptimization pop){ - addPopulation(pop.getPopulation()); - } - - /** @tested junit& .. - * adds a population and its function calls to this.population - * @param pop - */ - public void addPopulation(Population pop){ - m_Population.addPopulation(pop); + */ + /** + * @param pop + * @tested nn + * adds a population and its function calls to this.population + */ + public void addPopulation(ParticleSubSwarmOptimization pop) { + addPopulation(pop.getPopulation()); + } - // dont peculate the function calls from the added population (which is going to be deleted in NichePSO) - m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); - } - - /** @tested nn - * adss an inidividual - * @param ind - * @return - */ - public boolean addIndividual(IndividualInterface ind) { - // nothing to do regarding function calls - // old calls were counted in old population new calls are now counted in this population - return m_Population.addIndividual(ind); - } - - /** @tested nn + /** + * @param pop + * @tested junit& .. + * adds a population and its function calls to this.population + */ + public void addPopulation(Population pop) { + m_Population.addPopulation(pop); + + // dont peculate the function calls from the added population (which is going to be deleted in NichePSO) + m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); + } + + /** + * @param ind + * @return + * @tested nn + * adss an inidividual + */ + public boolean addIndividual(IndividualInterface ind) { + // nothing to do regarding function calls + // old calls were counted in old population new calls are now counted in this population + return m_Population.addIndividual(ind); + } + + /** * @param o * @return + * @tested nn */ public boolean add(Object o) { - return addIndividual((IndividualInterface)o); + return addIndividual((IndividualInterface) o); } - - /** @tested nn - * adds indy to the swarm - * @param indy - */ - public void add(AbstractEAIndividual indy){ - addIndividual(indy); - } - - /** @tested nn - * removes an individual - * @param ind - */ - public boolean removeSubIndividual (IndividualInterface ind) { - return m_Population.removeMember(ind); - } - - public void removeSubPopulation(Population pop, boolean allowMissing) { // this is very slow... - for (int i = 0; i < pop.size(); ++i){ - AbstractEAIndividual indy = pop.getEAIndividual(i); - if (!removeSubIndividual(indy)) { - if (!allowMissing) { - throw new RuntimeException("Warning, assumed sub population was not contained (ParticleSubSwarmOptimization)."); - } - } - } - } - + + /** + * @param indy + * @tested nn + * adds indy to the swarm + */ + public void add(AbstractEAIndividual indy) { + addIndividual(indy); + } + + /** + * @param ind + * @tested nn + * removes an individual + */ + public boolean removeSubIndividual(IndividualInterface ind) { + return m_Population.removeMember(ind); + } + + public void removeSubPopulation(Population pop, boolean allowMissing) { // this is very slow... + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual indy = pop.getEAIndividual(i); + if (!removeSubIndividual(indy)) { + if (!allowMissing) { + throw new RuntimeException("Warning, assumed sub population was not contained (ParticleSubSwarmOptimization)."); + } + } + } + } + /* - public void removeNIndividuals(int n) { + public void removeNIndividuals(int n) { } public void removeDoubleInstances() { } @@ -574,120 +598,127 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO /********************************************************************************************************************** * getter, setter */ - /** @tested ps - * This method will set the problem that is to be optimized - * @param problem - */ + /** + * @param problem + * @tested ps + * This method will set the problem that is to be optimized + */ @Override - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - updateMaxPosDist(); - } - - /** @tested junit - * @return the maximal euclidean distance between the swarms gbest and any other particle in the swarm. - */ - public double getSwarmRadius(){ - if (getPopulation().size() == 0 || getPopulation().size() == 1) { - return 0; + public void setProblem(InterfaceOptimizationProblem problem) { + this.m_Problem = problem; + updateMaxPosDist(); + } + + /** + * @return the maximal euclidean distance between the swarms gbest and any other particle in the swarm. + * @tested junit + */ + public double getSwarmRadius() { + if (getPopulation().size() == 0 || getPopulation().size() == 1) { + return 0; + } + + double max = Double.NEGATIVE_INFINITY; + //PhenotypeMetric metric = new PhenotypeMetric(); + + for (int i = 0; i < m_Population.size(); ++i) { + AbstractEAIndividual indy = m_Population.getEAIndividual(i); + //double dist = metric.distance(m_BestIndividual, indy); + double sqrdDist = EuclideanMetric.squaredEuclideanDistance(AbstractEAIndividual.getDoublePositionShallow(m_BestIndividual), + AbstractEAIndividual.getDoublePositionShallow(indy)); + + //dist = distance(m_BestIndividual, indy); + if (sqrdDist > max) { + max = sqrdDist; } - - double max = Double.NEGATIVE_INFINITY; - //PhenotypeMetric metric = new PhenotypeMetric(); - - for (int i = 0; i < m_Population.size(); ++i){ - AbstractEAIndividual indy = m_Population.getEAIndividual(i); - //double dist = metric.distance(m_BestIndividual, indy); - double sqrdDist = EuclideanMetric.squaredEuclideanDistance(AbstractEAIndividual.getDoublePositionShallow(m_BestIndividual), - AbstractEAIndividual.getDoublePositionShallow(indy)); - - //dist = distance(m_BestIndividual, indy); - if (sqrdDist > max){ - max = sqrdDist; - } - } - return Math.sqrt(max); - } - - /** @tested ps - * returns the maximal distance between the gbest position and any individual in the swarm - * this distance is not allowed to exceed a given threshold - * @return - */ - public double getBoundSwarmRadius(){ - // convert the normalised (i.e. relative) maxrad to a standard euclidean (i.e. absolute) maxrad - double maxAllowedSwarmRadiusAbs = getMaxAllowedSwarmRadiusAbs(); - // only compare (absolute) euclidean distances - return Math.min(getSwarmRadius(), maxAllowedSwarmRadiusAbs); - } + } + return Math.sqrt(max); + } - public double getMaxAllowedSwarmRadiusAbs() { - // convert the normalised (i.e. relative) maxrad to a standard euclidean (i.e. absolute) maxrad - return interpreteAsNormalisedSwarmRadius(maxAllowedSwarmRadiusNormal); - } - - /** - * @return the average distance a particle has to its neighbor - */ - public double getAveDistToNeighbor() { - Population pop = getPopulation(); - double sum = 0; - for (int i = 0; i < pop.size(); ++i){ - AbstractEAIndividual indy = pop.getEAIndividual(i); - AbstractEAIndividual neigbor = getMemberNeighbor(indy); - if (neigbor == null) { - return -1; - } - sum += distance(indy, neigbor); - } - return sum/(double)pop.size(); - } + /** + * @return + * @tested ps + * returns the maximal distance between the gbest position and any individual in the swarm + * this distance is not allowed to exceed a given threshold + */ + public double getBoundSwarmRadius() { + // convert the normalised (i.e. relative) maxrad to a standard euclidean (i.e. absolute) maxrad + double maxAllowedSwarmRadiusAbs = getMaxAllowedSwarmRadiusAbs(); + // only compare (absolute) euclidean distances + return Math.min(getSwarmRadius(), maxAllowedSwarmRadiusAbs); + } - /** - * @return a measure for the diversity of the swarm - */ - public double getEuclideanDiversity(){ - double meanDistanceFromGBestPos = 0; - AbstractEAIndividual gbest = getGBestIndividual(); - for (int i = 0; i < getPopulation().size(); ++i){ - AbstractEAIndividual indy = getPopulation().getEAIndividual(i); - meanDistanceFromGBestPos += distance(gbest, indy); - } - meanDistanceFromGBestPos /= (double)getPopulation().size(); - return meanDistanceFromGBestPos; - } + public double getMaxAllowedSwarmRadiusAbs() { + // convert the normalised (i.e. relative) maxrad to a standard euclidean (i.e. absolute) maxrad + return interpreteAsNormalisedSwarmRadius(maxAllowedSwarmRadiusNormal); + } - /** @tested nn - * binds the swarmradius to the given normalised value - * (f.e. 1 means, that the swarmradius is allowed to take the maximal possible range in the search space) - * @param maxAllowedSwarmRadius value from the intervall [0,1] - */ - public void SetMaxAllowedSwarmRadius(double maxAllowedSwarmRadius) { - this.maxAllowedSwarmRadiusNormal = maxAllowedSwarmRadius; - } + /** + * @return the average distance a particle has to its neighbor + */ + public double getAveDistToNeighbor() { + Population pop = getPopulation(); + double sum = 0; + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual indy = pop.getEAIndividual(i); + AbstractEAIndividual neigbor = getMemberNeighbor(indy); + if (neigbor == null) { + return -1; + } + sum += distance(indy, neigbor); + } + return sum / (double) pop.size(); + } + + /** + * @return a measure for the diversity of the swarm + */ + public double getEuclideanDiversity() { + double meanDistanceFromGBestPos = 0; + AbstractEAIndividual gbest = getGBestIndividual(); + for (int i = 0; i < getPopulation().size(); ++i) { + AbstractEAIndividual indy = getPopulation().getEAIndividual(i); + meanDistanceFromGBestPos += distance(gbest, indy); + } + meanDistanceFromGBestPos /= (double) getPopulation().size(); + return meanDistanceFromGBestPos; + } + + /** + * @param maxAllowedSwarmRadius value from the intervall [0,1] + * @tested nn + * binds the swarmradius to the given normalised value + * (f.e. 1 means, that the swarmradius is allowed to take the maximal possible range in the search space) + */ + public void SetMaxAllowedSwarmRadius(double maxAllowedSwarmRadius) { + this.maxAllowedSwarmRadiusNormal = maxAllowedSwarmRadius; + } + + /** + * @return + * @tested nn + */ + public double getMaxAllowedSwarmRadius() { + return this.maxAllowedSwarmRadiusNormal; + } + + /** + * @param active + * @tested nn + * marks the swarm as active or inactive + */ + public void SetActive(boolean active) { + this.active = active; + } + + /** + * @return + * @tested nn + */ + public boolean isActive() { + return active; + } - /** @tested nn - * @return - */ - public double getMaxAllowedSwarmRadius() { - return this.maxAllowedSwarmRadiusNormal; - } - - /** @tested nn - * marks the swarm as active or inactive - * @param active - */ - public void SetActive(boolean active) { - this.active = active; - } - - /** @tested nn - * @return - */ - public boolean isActive() { - return active; - } - // public InterfaceParameterAging getInertnessAging() { // return inertnessAging; // } @@ -700,84 +731,87 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO // this.inertnessAging = inertnessAging; // } - /** @tested junit - * returns the particle with the minimal distance to indy - * @param indy particle should be from this swarm - * @return null if there is no neighbor else neighbor - */ - public AbstractEAIndividual getMemberNeighbor(AbstractEAIndividual indy){ - if (getPopulation().size() == 0){ - System.out.println("getNeighbor: swarm empty"); - return null; - } - // check if there is at least a second particle... - if (getPopulation().size() == 1){ - //System.out.println("getNeighbor: swarm too small, no neighbor available"); - //return (AbstractEAIndividual)indy.clone(); // would conflict with constant size for overall population... - return null; - } - - // get the neighbor... - int index = -1; - double mindist = Double.POSITIVE_INFINITY; - boolean found=false; - for (int i = 0; i < getPopulation().size(); ++i){ - AbstractEAIndividual currentindy = getPopulation().getEAIndividual(i); - if (indy.getIndyID()!=currentindy.getIndyID()){ // dont compare particle to itself or a copy of itself - double dist = distance(indy,currentindy); - if (dist < mindist){ - mindist = dist; - index = i; - } - } else { - found=true; - } - } - - if (!found) { - System.err.println("getNeighbor: particle searching for neighbor is not part of the swarm"); - } - return getPopulation().getEAIndividual(index); - } - - public AbstractEAIndividual getGBestIndividual(){ - return m_BestIndividual; - } - - /** - * @param indyToExclude - * @return particle with worst personal best position in the swarm. The given particle is excluded. - */ - public AbstractEAIndividual getParticleWithWorstPBestButNot(AbstractEAIndividual indyToExclude) { - Population pop = getPopulation(); - if (pop.size() < 2){ - System.out.println("getParticleWithWorstPBestButNot: Population < 2 - returning null"); - return null; - } - AbstractEAIndividual indyWithWorstPBest = pop.getEAIndividual(0); - if (indyWithWorstPBest == indyToExclude){ - indyWithWorstPBest = pop.getEAIndividual(1); - } - AbstractEAIndividual worstPBest = (AbstractEAIndividual)indyWithWorstPBest.getData("PersonalBestKey"); - for (int i = 0; i < pop.size(); ++i){ - AbstractEAIndividual currentindy = pop.getEAIndividual(i); - AbstractEAIndividual currentpbest = (AbstractEAIndividual)currentindy.getData("PersonalBestKey"); - if (currentindy!=indyToExclude && worstPBest.isDominating(currentpbest)){ - indyWithWorstPBest = currentindy; - worstPBest = currentpbest; - } - } - return indyWithWorstPBest; - } + /** + * @param indy particle should be from this swarm + * @return null if there is no neighbor else neighbor + * @tested junit + * returns the particle with the minimal distance to indy + */ + public AbstractEAIndividual getMemberNeighbor(AbstractEAIndividual indy) { + if (getPopulation().size() == 0) { + System.out.println("getNeighbor: swarm empty"); + return null; + } + // check if there is at least a second particle... + if (getPopulation().size() == 1) { + //System.out.println("getNeighbor: swarm too small, no neighbor available"); + //return (AbstractEAIndividual)indy.clone(); // would conflict with constant size for overall population... + return null; + } - - public int getFitnessArchiveSize() { - return fitnessArchiveSize; - } - public void setFitnessArchiveSize(int fitnessArchiveSize) { - this.fitnessArchiveSize = fitnessArchiveSize; - } - public String fitnessArchiveSizeTipText() { - return "The number of fitness values stored per individual for deactivation strategies."; - } + // get the neighbor... + int index = -1; + double mindist = Double.POSITIVE_INFINITY; + boolean found = false; + for (int i = 0; i < getPopulation().size(); ++i) { + AbstractEAIndividual currentindy = getPopulation().getEAIndividual(i); + if (indy.getIndyID() != currentindy.getIndyID()) { // dont compare particle to itself or a copy of itself + double dist = distance(indy, currentindy); + if (dist < mindist) { + mindist = dist; + index = i; + } + } else { + found = true; + } + } + + if (!found) { + System.err.println("getNeighbor: particle searching for neighbor is not part of the swarm"); + } + return getPopulation().getEAIndividual(index); + } + + public AbstractEAIndividual getGBestIndividual() { + return m_BestIndividual; + } + + /** + * @param indyToExclude + * @return particle with worst personal best position in the swarm. The given particle is excluded. + */ + public AbstractEAIndividual getParticleWithWorstPBestButNot(AbstractEAIndividual indyToExclude) { + Population pop = getPopulation(); + if (pop.size() < 2) { + System.out.println("getParticleWithWorstPBestButNot: Population < 2 - returning null"); + return null; + } + AbstractEAIndividual indyWithWorstPBest = pop.getEAIndividual(0); + if (indyWithWorstPBest == indyToExclude) { + indyWithWorstPBest = pop.getEAIndividual(1); + } + AbstractEAIndividual worstPBest = (AbstractEAIndividual) indyWithWorstPBest.getData("PersonalBestKey"); + for (int i = 0; i < pop.size(); ++i) { + AbstractEAIndividual currentindy = pop.getEAIndividual(i); + AbstractEAIndividual currentpbest = (AbstractEAIndividual) currentindy.getData("PersonalBestKey"); + if (currentindy != indyToExclude && worstPBest.isDominating(currentpbest)) { + indyWithWorstPBest = currentindy; + worstPBest = currentpbest; + } + } + return indyWithWorstPBest; + } + + + public int getFitnessArchiveSize() { + return fitnessArchiveSize; + } + + public void setFitnessArchiveSize(int fitnessArchiveSize) { + this.fitnessArchiveSize = fitnessArchiveSize; + } + + public String fitnessArchiveSizeTipText() { + return "The number of fitness values stored per individual for deactivation strategies."; + } } diff --git a/src/eva2/optimization/strategies/ParticleSwarmOptimization.java b/src/eva2/optimization/strategies/ParticleSwarmOptimization.java index 6df0c036..29cb8f6b 100644 --- a/src/eva2/optimization/strategies/ParticleSwarmOptimization.java +++ b/src/eva2/optimization/strategies/ParticleSwarmOptimization.java @@ -27,6 +27,7 @@ import eva2.tools.chart2d.DPointSet; import eva2.tools.math.Jama.Matrix; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.util.ArrayList; import java.util.Arrays; import java.util.Vector; @@ -37,10 +38,9 @@ import java.util.Vector; * range constraints on the decision variables. I've implemented 'brakes' before * an individual is updated it is checked whether the new individual would * violate range constraints, if so the velocity vector is reduced. - * + *

* Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", * "HPSO", "Random" in that order starting by 0. - * */ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Serializable, InterfaceAdditionalPopulationInformer { @@ -146,10 +146,10 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * Constructor for most common parameters with constriction based approach. * - * @param popSize swarm size - * @param p1 the value for phi1 - * @param p2 the value for phi1 - * @param topo type of the neighbourhood topology + * @param popSize swarm size + * @param p1 the value for phi1 + * @param p2 the value for phi1 + * @param topo type of the neighbourhood topology * @param topoRange range of the neighbourhood topology */ public ParticleSwarmOptimization(int popSize, double p1, double p2, PSOTopologyEnum topo, int topoRange) { @@ -161,7 +161,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se topology = topo; } -// /** + // /** // * Constructor for most common parameters with constriction based approach and local search. // * // * @param popSize swarm size @@ -222,7 +222,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * Set the initial random velocity vector. * - * @param indy the individual to work on + * @param indy the individual to work on * @param initialV initial velocity relative to the range */ public static void initIndividualDefaults(AbstractEAIndividual indy, double initialV) { @@ -314,16 +314,15 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * the last entry. The velocity vector key is to be passed over. Optionally, * an additional identifier is tested - they may be null. * + * @param pop the swarm population + * @param calcModeSwitch mode switch + * @param velocityKey String to access velocity vector within + * AbstractEAIndividual + * @param typeString optional type string to access individual type + * @param requiredType optional required type identifier of the individual. + * @return double array containing the vectorial sum of particle velocities + * or an array containing the average absolute speed * @see AbstractEAIndividual.getData(String) - * - * @param pop the swarm population - * @param calcModeSwitch mode switch - * @param velocityKey String to access velocity vector within - * AbstractEAIndividual - * @param typeString optional type string to access individual type - * @param requiredType optional required type identifier of the individual. - * @return double array containing the vectorial sum of particle velocities - * or an array containing the average absolute speed */ public static double[] getPopulationVelSpeed(Population pop, int calcModeSwitch, final String velocityKey, final String typeString, final Object requiredType) { AbstractEAIndividual indy = (AbstractEAIndividual) pop.get(0); @@ -345,11 +344,11 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se double[] velocity = (double[]) indy.getData(velocityKey); if (velocity != null) { if (calcVectVelocity) { - retSize += velocity.length; // entries for cumulative velocity + retSize += velocity.length; // entries for cumulative velocity } if (calcAbsSpeedAverage) { - retSize++; // one entry for average absolute speed - } // return length of the array depends on what should be calculated + retSize++; // one entry for average absolute speed + } // return length of the array depends on what should be calculated ret = new double[retSize]; double[] cumulVeloc = new double[velocity.length]; @@ -404,8 +403,8 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * Check particle type and return true if the particle is 'standard', i.e. * it has a speed property. * - * @param indy the individual to check - * @return true if the particle has a speed property + * @param indy the individual to check + * @return true if the particle has a speed property */ protected boolean particleHasSpeed(AbstractEAIndividual indy) { return isParticleType(indy, defaultType); @@ -424,7 +423,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * given population. * * @param pop - * @return vectorial sum of the particle velocities + * @return vectorial sum of the particle velocities */ public double[] getPopulationVelocity(Population pop) { return getPopulationVelSpeed(pop, 1, partVelKey, partTypeKey, defaultType); @@ -445,7 +444,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * This method will init the optimizer with a given population or, if pop is * null, initialize the current population as if it was new. * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -625,8 +624,8 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * This method will update a given individual according to the PSO method * * @param index The individual to update. - * @param pop The current population. - * @param best The best individual found so far. + * @param pop The current population. + * @param best The best individual found so far. */ protected void updateIndividual(int index, AbstractEAIndividual indy, Population pop) { if (indy instanceof InterfaceDataTypeDouble) { @@ -719,7 +718,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * Loop the population and update each individual props if indicated by * isIndividualToUpdate. * - * @param pop the population to work on + * @param pop the population to work on */ protected void updateSwarmMemory(Population pop) { for (int i = 0; i < pop.size(); i++) { @@ -751,7 +750,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * Write current fitness and position as best fitness and position into * individual properties. * - * @param srcIndy the individual to update + * @param srcIndy the individual to update */ protected void updateIndProps(AbstractEAIndividual trgIndy, AbstractEAIndividual srcIndy) { trgIndy.putData(partBestFitKey, srcIndy.getFitness().clone()); @@ -957,6 +956,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se // //vecSum.normalize(); // //System.out.println(vec.toString() + " -> " + vecSum.toString()); // } + /** * Return a random vector after a gaussian distribution oriented along dir, * meaning that variance is len(dir) along dir and len(dir)/scale in any @@ -1021,11 +1021,11 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * In the topology range for the given index, find the best stored * individual and return its position. * - * @param index index of the individual for which to check - * @param pop the current swarm - * @param best the currently best individual - * @return a copy of the position of the best remembered individual in the - * neigbourhood + * @param index index of the individual for which to check + * @param pop the current swarm + * @param best the currently best individual + * @return a copy of the position of the best remembered individual in the + * neigbourhood */ protected double[] findNeighbourhoodOptimum(int index, Population pop) { double[] localBestPosition = null; @@ -1081,7 +1081,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se case multiSwarm: // self-organised multi-swarms AbstractEAIndividual leader = (AbstractEAIndividual) indy.getData(multiSwTypeKey); - if (leader != null) { // refer to position of leader, this may be the individual itself + if (leader != null) { // refer to position of leader, this may be the individual itself if ((leader == indy) && ((Integer) indy.getData(multiSwSizeKey) < minSubSwarmSize)) { // swarm too small this.compareAndSetAttractor(localBestFitness, localBestPosition, bestIndy, useHistoric); @@ -1100,7 +1100,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se case tree: // Sorted Tree sortedIndex = (Integer) ((AbstractEAIndividual) sortedPop[index]).getData(sortedIndexKey); - if (sortedIndex > 0) { // its found and its not the root. root has no parent to check for + if (sortedIndex > 0) { // its found and its not the root. root has no parent to check for k = getParentIndex(m_TopologyRange, sortedIndex, pop.size()); compareAndSetAttractor(localBestFitness, localBestPosition, (AbstractEAIndividual) sortedPop[k], useHistoric); } @@ -1268,9 +1268,9 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * Test a position for range violation efficiently. * - * @param pos the position vector to test - * @param range the range array - * @return true, if pos violoates range, else false + * @param pos the position vector to test + * @param range the range array + * @return true, if pos violoates range, else false */ protected boolean isOutOfRange(double[] pos, double[][] range) { boolean violatesRange = false; @@ -1289,9 +1289,9 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * factor. Requires the range array because the speed is handled relative to * the range. * - * @param curVelocity the velocity vector to be modified - * @param range the range array - * @param speedLim the speed limit relative to the range + * @param curVelocity the velocity vector to be modified + * @param range the range array + * @param speedLim the speed limit relative to the range */ protected void enforceSpeedLimit(double[] curVelocity, double[][] range, double speedLim) { while (Mathematics.getRelativeLength(curVelocity, range) > speedLim) { @@ -1306,9 +1306,9 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * remains inside the range array. Therefore, the velocity may be repeatedly * multiplied by reduceSpeedOnConstViolation. * - * @param pos the current particle position - * @param velocity the current particle velocity to be modified - * @param range the range array + * @param pos the current particle position + * @param velocity the current particle velocity to be modified + * @param range the range array */ protected void ensureConstraints(double[] pos, double[] velocity, double[][] range) { double[] newPos = new double[pos.length]; @@ -1327,7 +1327,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se if (!Mathematics.isInRange(newPos[i], range[i][0], range[i][1])) { if ((pos[i] == range[i][0]) || (pos[i] == range[i][1])) { // bounce? - velocity[i] *= reduceSpeedOnConstViolation; // bounce velocity and reduce + velocity[i] *= reduceSpeedOnConstViolation; // bounce velocity and reduce if (((pos[i] == range[i][0]) && (newPos[i] < range[i][0])) || ((pos[i] == range[i][1]) && (newPos[i] > range[i][1]))) { velocity[i] *= -1; // bounce only if leaving in this direction. } @@ -1415,7 +1415,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * Do some preparations in the beginning of the loop. - * */ protected void startOptimize() { if (TRACE) { @@ -1435,7 +1434,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * Log the best individual so far. - * */ protected void logBestIndividual() { if (this.m_Population.getBestEAIndividual().isDominatingDebConstraints(this.m_BestIndividual)) { @@ -1448,7 +1446,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * Loop over the population and trigger the individual update. - * */ protected void updatePopulation() { @@ -1521,7 +1518,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se for (int i = 0; i < leaders.size(); i++) { dist = metric.distance((AbstractEAIndividual) sortedPop[cur], leaders.get(i)); //System.out.println("dist is "+dist); - if ((m_swarmRadius * 2.) > dist) { // a formal leader is found + if ((m_swarmRadius * 2.) > dist) { // a formal leader is found int sSize = (Integer) (leaders.get(i)).getData(multiSwSizeKey); if ((maxSubSwarmSize > 0) && (sSize >= maxSubSwarmSize)) { // swarm is too big already @@ -1650,6 +1647,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se // } // return perm; // } + /** * This method is simply for debugging. */ @@ -2055,7 +2053,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * @return true if swarm visualization is turned on - * */ public boolean isShow() { return m_Show; @@ -2063,7 +2060,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * @param set swarm visualization (2D) - * */ public void setShow(boolean show) { m_Show = show; @@ -2078,7 +2074,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * @return the checkSpeedLimit - * */ public boolean isCheckSpeedLimit() { return checkSpeedLimit; @@ -2086,7 +2081,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * @param checkSpeedLimit the checkSpeedLimit to set - * */ public void setCheckSpeedLimit(boolean checkSpeedLimit) { this.checkSpeedLimit = checkSpeedLimit; @@ -2103,9 +2097,9 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se // public void setEMAPeriods(int emaP) { // this.emaPeriods = emaP; // } + /** * @return the sleepTime - * */ public int getSleepTime() { return sleepTime; @@ -2113,7 +2107,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se /** * @param sleepTime the sleepTime to set - * */ public void setSleepTime(int sleepTime) { this.sleepTime = sleepTime; @@ -2155,7 +2148,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se this.treeStruct = treeStruct; } -// This was for testing rotation operators + // This was for testing rotation operators // public boolean isUseAlternative() { // return useAlternative; // } @@ -2254,7 +2247,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se return "The number of generations after which new subswarms are randomly formed."; } -// public boolean isDoLocalSearch() { + // public boolean isDoLocalSearch() { // return doLocalSearch; // } // diff --git a/src/eva2/optimization/strategies/ParticleSwarmOptimizationGCPSO.java b/src/eva2/optimization/strategies/ParticleSwarmOptimizationGCPSO.java index 5a125a0d..693010f7 100644 --- a/src/eva2/optimization/strategies/ParticleSwarmOptimizationGCPSO.java +++ b/src/eva2/optimization/strategies/ParticleSwarmOptimizationGCPSO.java @@ -4,279 +4,285 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.tools.math.RNG; /** - * This extends the particle swarm optimization implementation - * so that the guaranteed global convergence pso can be used as suggested by + * This extends the particle swarm optimization implementation + * so that the guaranteed global convergence pso can be used as suggested by * Franz van den Bergh in "An Analysis of Particle Swarm Optimizers". * In this modification the velocity of the global best particle is updated differently. */ public class ParticleSwarmOptimizationGCPSO extends ParticleSwarmOptimization { - // choosable parameters: - protected boolean gcpso; - protected int sc; - protected int fc; - protected double rhoIncreaseFactor; - protected double rhoDecreaseFactor; - // members updated via updateGCPSOMember: - protected int gbestParticleIndex = -1; - protected boolean gbestParticleHasChanged; - protected int numOfSuccesses; - protected int numOfFailures; - protected AbstractEAIndividual gbestParticle; - private double rho; //initial rho value can be chosen + // choosable parameters: + protected boolean gcpso; + protected int sc; + protected int fc; + protected double rhoIncreaseFactor; + protected double rhoDecreaseFactor; + // members updated via updateGCPSOMember: + protected int gbestParticleIndex = -1; + protected boolean gbestParticleHasChanged; + protected int numOfSuccesses; + protected int numOfFailures; + protected AbstractEAIndividual gbestParticle; + private double rho; //initial rho value can be chosen + + protected int getAccelerationForGlobalBestParticleCounter = 0; // only for testing - protected int getAccelerationForGlobalBestParticleCounter = 0; // only for testing - /********************************************************************************************************************** * ctors, inits - */ - /** @tested ps - * ctor - sets default values according to - * "An Analyis of Paricle Swarm Optimizers" by Franz van den Bergh - */ - public ParticleSwarmOptimizationGCPSO(){ - setGcpso(true); - gbestParticleIndex = -1; - //gbestParticle - gbestParticleHasChanged = false; - numOfSuccesses = 0; - numOfFailures = 0; - setRho(1); - SetSc(15); - SetFc(5); - SetRhoIncreaseFactor(2.0); - SetRhoDecreaseFactor(0.5); - } + */ + /** + * @tested ps + * ctor - sets default values according to + * "An Analyis of Paricle Swarm Optimizers" by Franz van den Bergh + */ + public ParticleSwarmOptimizationGCPSO() { + setGcpso(true); + gbestParticleIndex = -1; + //gbestParticle + gbestParticleHasChanged = false; + numOfSuccesses = 0; + numOfFailures = 0; + setRho(1); + SetSc(15); + SetFc(5); + SetRhoIncreaseFactor(2.0); + SetRhoDecreaseFactor(0.5); + } - /** @tested ps - * @param a - */ - public ParticleSwarmOptimizationGCPSO(ParticleSwarmOptimizationGCPSO a){ - super(a); - this.setGcpso(a.gcpso); - this.gbestParticleIndex = a.gbestParticleIndex; - if (a.gbestParticle != null){ - this.gbestParticle = (AbstractEAIndividual)a.gbestParticle.clone(); - double[] aFitness= (double[])a.gbestParticle.getData(partBestFitKey); - this.gbestParticle.putData(partBestFitKey, aFitness.clone()); - } - this.gbestParticleHasChanged = a.gbestParticleHasChanged; - this.numOfSuccesses = a.numOfSuccesses; - this.numOfFailures = a.numOfFailures; - this.setRho(a.getRho()); - this.SetSc(a.getSc()); - this.SetFc(a.getFc()); - this.SetRhoIncreaseFactor(a.getRhoIncreaseFactor()); - this.SetRhoDecreaseFactor(a.getRhoDecreaseFactor()); - } + /** + * @param a + * @tested ps + */ + public ParticleSwarmOptimizationGCPSO(ParticleSwarmOptimizationGCPSO a) { + super(a); + this.setGcpso(a.gcpso); + this.gbestParticleIndex = a.gbestParticleIndex; + if (a.gbestParticle != null) { + this.gbestParticle = (AbstractEAIndividual) a.gbestParticle.clone(); + double[] aFitness = (double[]) a.gbestParticle.getData(partBestFitKey); + this.gbestParticle.putData(partBestFitKey, aFitness.clone()); + } + this.gbestParticleHasChanged = a.gbestParticleHasChanged; + this.numOfSuccesses = a.numOfSuccesses; + this.numOfFailures = a.numOfFailures; + this.setRho(a.getRho()); + this.SetSc(a.getSc()); + this.SetFc(a.getFc()); + this.SetRhoIncreaseFactor(a.getRhoIncreaseFactor()); + this.SetRhoDecreaseFactor(a.getRhoDecreaseFactor()); + } + + /** + * This method returns a global info string + * + * @return description + */ + public static String globalInfo() { + return "Guaranteed Convergence Particle Swarm Optimiser (GCPSO) " + + "as proposed by F. van den Bergh."; + } - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "Guaranteed Convergence Particle Swarm Optimiser (GCPSO) " + - "as proposed by F. van den Bergh."; - } - /********************************************************************************************************************** * overwritten - */ - /** @tested - * (non-Javadoc) @see javaeva.server.go.strategies.ParticleSwarmOptimization#optimize() - */ + */ + /** + * @tested (non-Javadoc) @see javaeva.server.go.strategies.ParticleSwarmOptimization#optimize() + */ @Override - public void optimize() { - super.optimize(); //updatePopulation->updateIndividual->updateVelocity (s.u.) - updateGCPSOMember(); - } + public void optimize() { + super.optimize(); //updatePopulation->updateIndividual->updateVelocity (s.u.) + updateGCPSOMember(); + } - /** @tested junit& - * (non-Javadoc) @see javaeva.server.go.strategies.ParticleSwarmOptimization#updateVelocity(int, double[], double[], double[], double[], double[][]) - * uses a special velocity update strategy for the gobal best particle. - */ + /** + * @tested junit& + * (non-Javadoc) @see javaeva.server.go.strategies.ParticleSwarmOptimization#updateVelocity(int, double[], double[], double[], double[], double[][]) + * uses a special velocity update strategy for the gobal best particle. + */ @Override - protected double[] updateVelocity(int index, double[] lastVelocity, double[] personalBestPos, double[] curPosition, double[] neighbourBestPos, double[][] range) { - double[] accel, curVelocity = new double[lastVelocity.length]; + protected double[] updateVelocity(int index, double[] lastVelocity, double[] personalBestPos, double[] curPosition, double[] neighbourBestPos, double[][] range) { + double[] accel, curVelocity = new double[lastVelocity.length]; - if (useAlternative) { - accel = getAccelerationAlternative(index, personalBestPos, neighbourBestPos, curPosition, range); - } else { - if (index == gbestParticleIndex && isGcpso()) { - accel = getAccelerationForGlobalBestParticle(personalBestPos, neighbourBestPos, curPosition, range); - } - else { - accel = getAcceleration(personalBestPos, neighbourBestPos, curPosition, range); - } - } - for (int i = 0; i < lastVelocity.length; i++) { - curVelocity[i] = this.m_InertnessOrChi * lastVelocity[i]; - curVelocity[i] += accel[i]; - } - return curVelocity; - } + if (useAlternative) { + accel = getAccelerationAlternative(index, personalBestPos, neighbourBestPos, curPosition, range); + } else { + if (index == gbestParticleIndex && isGcpso()) { + accel = getAccelerationForGlobalBestParticle(personalBestPos, neighbourBestPos, curPosition, range); + } else { + accel = getAcceleration(personalBestPos, neighbourBestPos, curPosition, range); + } + } + for (int i = 0; i < lastVelocity.length; i++) { + curVelocity[i] = this.m_InertnessOrChi * lastVelocity[i]; + curVelocity[i] += accel[i]; + } + return curVelocity; + } /********************************************************************************************************************** * GCPSO core - */ - /** @tested ps - * @return the acceleration component. - * Should only be called for the global best particle - * (i.e. the particle with the best personal best position) - */ - private double[] getAccelerationForGlobalBestParticle( - double[] personalBestPos, double[] neighbourBestPos, - double[] curPosition, double[][] range) - { - ++getAccelerationForGlobalBestParticleCounter; - double[] accel = new double[curPosition.length]; - for (int i = 0; i < personalBestPos.length; i++) { - // reset position to the global best position - accel[i] = -curPosition[i]+personalBestPos[i]; //pbestpos of gbestparticle is gbestpos - // random search around the global best position - accel[i] += getRho()*(1.0-2.0*RNG.randomDouble(0,1)); - } - //System.out.println("rho: " +getVecNorm(accel)); - //System.out.println("accel: " +getVecNorm(accel)); - return accel; - } + */ + /** + * @return the acceleration component. + * Should only be called for the global best particle + * (i.e. the particle with the best personal best position) + * @tested ps + */ + private double[] getAccelerationForGlobalBestParticle( + double[] personalBestPos, double[] neighbourBestPos, + double[] curPosition, double[][] range) { + ++getAccelerationForGlobalBestParticleCounter; + double[] accel = new double[curPosition.length]; + for (int i = 0; i < personalBestPos.length; i++) { + // reset position to the global best position + accel[i] = -curPosition[i] + personalBestPos[i]; //pbestpos of gbestparticle is gbestpos + // random search around the global best position + accel[i] += getRho() * (1.0 - 2.0 * RNG.randomDouble(0, 1)); + } + //System.out.println("rho: " +getVecNorm(accel)); + //System.out.println("accel: " +getVecNorm(accel)); + return accel; + } + + /** + * @return the index of the particle with the best personal best position + * (i.e. the index of the global best particle) + * @tested junit + */ + protected int getIndexOfGlobalBestParticle() { + if (getPopulation().size() == 0) { + System.out.println("getIndexOfGlobalBestParticle error: no particle in population"); + return -1; + } + int index = 0; + double[] gbestFitness = (double[]) getPopulation().getEAIndividual(0).getData(partBestFitKey); + for (int i = 1; i < getPopulation().size(); ++i) { + AbstractEAIndividual indy = getPopulation().getEAIndividual(i); + double[] currentBestFitness = (double[]) indy.getData(partBestFitKey); + if (AbstractEAIndividual.isDominatingFitness(currentBestFitness, gbestFitness)) { + gbestFitness = currentBestFitness; + index = i; + } + } + return index; + } - /** @tested junit - * @return the index of the particle with the best personal best position - * (i.e. the index of the global best particle) - */ - protected int getIndexOfGlobalBestParticle() { - if (getPopulation().size() == 0){ - System.out.println("getIndexOfGlobalBestParticle error: no particle in population"); - return -1; - } - int index = 0; - double[] gbestFitness = (double[])getPopulation().getEAIndividual(0).getData(partBestFitKey); - for (int i = 1; i < getPopulation().size(); ++i){ - AbstractEAIndividual indy = getPopulation().getEAIndividual(i); - double[] currentBestFitness = (double[])indy.getData(partBestFitKey); - if (AbstractEAIndividual.isDominatingFitness(currentBestFitness,gbestFitness)){ - gbestFitness = currentBestFitness; - index = i; - } - } - return index; - } - /********************************************************************************************************************** * updateGCPSOMember - */ - /** @tested junit - * updates: gbestParticleIndex,gbestParticleHasChanged,numOfSuccesses,numOfFailures,gbestParticle,rho - */ - protected void updateGCPSOMember() { - int index = getIndexOfGlobalBestParticle(); + */ + /** + * @tested junit + * updates: gbestParticleIndex,gbestParticleHasChanged,numOfSuccesses,numOfFailures,gbestParticle,rho + */ + protected void updateGCPSOMember() { + int index = getIndexOfGlobalBestParticle(); - /** gbestParticleIndex,gbestParticleHasChanged */ - // check if the gbestParticle changed in the last optimization loop - if (index != gbestParticleIndex) - { - gbestParticleHasChanged = true; - gbestParticleIndex = index; - } else { - gbestParticleHasChanged = false; - } + /** gbestParticleIndex,gbestParticleHasChanged */ + // check if the gbestParticle changed in the last optimization loop + if (index != gbestParticleIndex) { + gbestParticleHasChanged = true; + gbestParticleIndex = index; + } else { + gbestParticleHasChanged = false; + } + + /** numOfSuccesses,numOfFailures */ + // check if the gbestParticle improved over the last iteration + if (gbestParticle == null) { // no previous gbest on first call available + AbstractEAIndividual gbestParticleCurrent = (AbstractEAIndividual) getPopulation().getEAIndividual(gbestParticleIndex); + gbestParticle = (AbstractEAIndividual) gbestParticleCurrent.clone(); + } + AbstractEAIndividual gbestParticleOld = gbestParticle; + double[] gbestParticleFitnessOld = (double[]) gbestParticleOld.getData(partBestFitKey); + AbstractEAIndividual gbestParticleCurrent = (AbstractEAIndividual) getPopulation().getEAIndividual(gbestParticleIndex); + double[] gbestParticleFitnessCurrent = (double[]) gbestParticleCurrent.getData(partBestFitKey); - /** numOfSuccesses,numOfFailures */ - // check if the gbestParticle improved over the last iteration - if (gbestParticle == null){ // no previous gbest on first call available - AbstractEAIndividual gbestParticleCurrent = (AbstractEAIndividual)getPopulation().getEAIndividual(gbestParticleIndex); - gbestParticle = (AbstractEAIndividual)gbestParticleCurrent.clone(); - } - AbstractEAIndividual gbestParticleOld = gbestParticle; - double[] gbestParticleFitnessOld = (double[])gbestParticleOld.getData(partBestFitKey); - AbstractEAIndividual gbestParticleCurrent = (AbstractEAIndividual)getPopulation().getEAIndividual(gbestParticleIndex); - double[] gbestParticleFitnessCurrent = (double[])gbestParticleCurrent.getData(partBestFitKey); - // if (gbestParticleHasChanged && false){ // reset rho on change? // numOfFailures = 0; // numOfSuccesses = 0; // setRho(1); // } else { - if (AbstractEAIndividual.isDominatingFitnessNotEqual(gbestParticleFitnessCurrent,gbestParticleFitnessOld)){ - ++numOfSuccesses; - numOfFailures = 0; - } else{ - ++numOfFailures; - numOfSuccesses = 0; - } + if (AbstractEAIndividual.isDominatingFitnessNotEqual(gbestParticleFitnessCurrent, gbestParticleFitnessOld)) { + ++numOfSuccesses; + numOfFailures = 0; + } else { + ++numOfFailures; + numOfSuccesses = 0; + } // } - /** gbestParticle */ - gbestParticle = (AbstractEAIndividual)gbestParticleCurrent.clone(); - - /** rho */ - if (numOfSuccesses > getSc()) { - setRho(getRhoIncreaseFactor()*getRho()); - //System.out.println("rho increased"); - } - //System.out.println(getRhoIncreaseFactor()); - if (numOfFailures > getFc()) { - setRho(getRhoDecreaseFactor()*getRho()); - //System.out.println("rho decreased"); - } - //System.out.println(getRhoDecreaseFactor()); - } - -/********************************************************************************************************************** - * getter, setter - */ - public void setGcpso(boolean gcpso) { - this.gcpso = gcpso; - } + /** gbestParticle */ + gbestParticle = (AbstractEAIndividual) gbestParticleCurrent.clone(); - public boolean isGcpso() { - return gcpso; - } - - public String gcpsoTipText(){ - return "deactivate to use the standard PSO by Kennedy and Eberhart"; - } + /** rho */ + if (numOfSuccesses > getSc()) { + setRho(getRhoIncreaseFactor() * getRho()); + //System.out.println("rho increased"); + } + //System.out.println(getRhoIncreaseFactor()); + if (numOfFailures > getFc()) { + setRho(getRhoDecreaseFactor() * getRho()); + //System.out.println("rho decreased"); + } + //System.out.println(getRhoDecreaseFactor()); + } - public void SetSc(int sc) { - this.sc = sc; - } + /** + * ******************************************************************************************************************* + * getter, setter + */ + public void setGcpso(boolean gcpso) { + this.gcpso = gcpso; + } - public int getSc() { - return sc; - } + public boolean isGcpso() { + return gcpso; + } - public void SetFc(int fc) { - this.fc = fc; - } + public String gcpsoTipText() { + return "deactivate to use the standard PSO by Kennedy and Eberhart"; + } - public int getFc() { - return fc; - } + public void SetSc(int sc) { + this.sc = sc; + } - public void SetRhoIncreaseFactor(double rhoIncreaseFactor) { - this.rhoIncreaseFactor = rhoIncreaseFactor; - } + public int getSc() { + return sc; + } - public double getRhoIncreaseFactor() { - return rhoIncreaseFactor; - } + public void SetFc(int fc) { + this.fc = fc; + } - public void SetRhoDecreaseFactor(double rhoDecreaseFactor) { - this.rhoDecreaseFactor = rhoDecreaseFactor; - } + public int getFc() { + return fc; + } - public double getRhoDecreaseFactor() { - return rhoDecreaseFactor; - } + public void SetRhoIncreaseFactor(double rhoIncreaseFactor) { + this.rhoIncreaseFactor = rhoIncreaseFactor; + } - public void setRho(double rho) { - this.rho = rho; - } - - public String rhoTipText(){ - return "controls the initial radius of a random search in an area surrounding the global best position of the swarm"; - } + public double getRhoIncreaseFactor() { + return rhoIncreaseFactor; + } - public double getRho() { - return rho; - } + public void SetRhoDecreaseFactor(double rhoDecreaseFactor) { + this.rhoDecreaseFactor = rhoDecreaseFactor; + } + + public double getRhoDecreaseFactor() { + return rhoDecreaseFactor; + } + + public void setRho(double rho) { + this.rho = rho; + } + + public String rhoTipText() { + return "controls the initial radius of a random search in an area surrounding the global best position of the swarm"; + } + + public double getRho() { + return rho; + } } diff --git a/src/eva2/optimization/strategies/PopulationBasedIncrementalLearning.java b/src/eva2/optimization/strategies/PopulationBasedIncrementalLearning.java index 41236388..ea9406d5 100644 --- a/src/eva2/optimization/strategies/PopulationBasedIncrementalLearning.java +++ b/src/eva2/optimization/strategies/PopulationBasedIncrementalLearning.java @@ -18,11 +18,11 @@ import eva2.optimization.problems.InterfaceOptimizationProblem; * also allows to simulate ant systems due to the flexible update rule of V. But * both are limited to binary genotypes. This is a simple implementation of * Population Based Incremental Learning. - * + *

* Nicolas Monmarché , Eric Ramat , Guillaume Dromel , Mohamed Slimane , Gilles * Venturini: On the similarities between AS, BSC and PBIL: toward the birth of * a new meta-heuristic. TecReport 215. Univ. de Tours, 1999. - * + *

* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer * Architecture * @@ -81,7 +81,7 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override diff --git a/src/eva2/optimization/strategies/ScatterSearch.java b/src/eva2/optimization/strategies/ScatterSearch.java index da249b13..db639849 100644 --- a/src/eva2/optimization/strategies/ScatterSearch.java +++ b/src/eva2/optimization/strategies/ScatterSearch.java @@ -22,6 +22,7 @@ import eva2.tools.Pair; import eva2.tools.SelectedTag; import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; + import java.util.ArrayList; /** @@ -35,10 +36,10 @@ import java.util.ArrayList; * first fitness criterion is regarded). * * @author mkron - * - * [1] M.Rodiguez-Fernandez, J.Egea, J.Banga: Novel metaheuristic for parameter - * estimation in nonlinear dynamic biological systems. BMC Bioinformatics 2006, - * 7:483. BioMed Central 2006. + *

+ * [1] M.Rodiguez-Fernandez, J.Egea, J.Banga: Novel metaheuristic for parameter + * estimation in nonlinear dynamic biological systems. BMC Bioinformatics 2006, + * 7:483. BioMed Central 2006. */ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener { @@ -63,7 +64,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, private int generationCycle = 50; private int fitCrit = -1; protected boolean checkRange = true; -// private int lastLocalSearch = -1; + // private int lastLocalSearch = -1; // // nr of generations between local searches // protected int localSearchInterval = 10; // below this threshold a local search will be performed @@ -184,7 +185,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } } -// public double eval(double[] x) { + // public double eval(double[] x) { // AbstractEAIndividual indy = (AbstractEAIndividual)template.clone(); // ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(x); // problem.evaluate(indy); @@ -360,7 +361,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, * * @param refSet * @param candidates - * @param oldRefSet only to be used as for phenotypic diversity measure + * @param oldRefSet only to be used as for phenotypic diversity measure */ private void updateRefSet(Population refSet, Population candidates, Population oldRefSet) { int bestIndex = candidates.getIndexOfBestIndividualPrefFeasible(); @@ -738,7 +739,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, return RNG.randomDouble(lowB, upB); } -///////////// Trivials... + ///////////// Trivials... @Override public void setIdentifier(String name) { m_Identifier = name; @@ -871,6 +872,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } ////////////////////////////////////////////7 + /** * This method performs a scatter search runnable. */ diff --git a/src/eva2/optimization/strategies/SimulatedAnnealing.java b/src/eva2/optimization/strategies/SimulatedAnnealing.java index c4ccf0b8..4661994e 100644 --- a/src/eva2/optimization/strategies/SimulatedAnnealing.java +++ b/src/eva2/optimization/strategies/SimulatedAnnealing.java @@ -65,7 +65,7 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override diff --git a/src/eva2/optimization/strategies/SqPSO.java b/src/eva2/optimization/strategies/SqPSO.java index 7c4b8e9e..418a6306 100644 --- a/src/eva2/optimization/strategies/SqPSO.java +++ b/src/eva2/optimization/strategies/SqPSO.java @@ -9,38 +9,37 @@ import eva2.optimization.operator.paramcontrol.ParamAdaption; * A thunk class preconfiguring CBN-EA to function as a sequential niching method. This * is to be comparable to parallel and semi-sequential niching (esp. using the same convergence * criterion). - * - * @author mkron * + * @author mkron */ public class SqPSO extends ClusterBasedNichingEA { - public SqPSO() { - this(1e-10, 15, 15); // default values - } - - public SqPSO(double epsilonConv, int haltingWindow, int popSize) { - super(); - setClusterDiffDist(Double.MAX_VALUE); - setMaxSpeciesSize(-1); - // dummy: cluster all always - setDifferentiationCA(new ClusteringDensityBased(Double.MAX_VALUE, 1, - new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); - // just a dummy - setMergingCA(new ClusteringDensityBased(0., 0, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); - setEpsilonBound(epsilonConv); - setHaltingWindow(haltingWindow); - setMaxSpeciesSize(popSize); - setOptimizer(new ParticleSwarmOptimization(popSize, 2.05, 2.05, PSOTopologyEnum.grid, 2)); - ParamAdaption[] defAdpt = new ParamAdaption[]{}; - setParameterControl(defAdpt); + public SqPSO() { + this(1e-10, 15, 15); // default values + } + + public SqPSO(double epsilonConv, int haltingWindow, int popSize) { + super(); + setClusterDiffDist(Double.MAX_VALUE); + setMaxSpeciesSize(-1); + // dummy: cluster all always + setDifferentiationCA(new ClusteringDensityBased(Double.MAX_VALUE, 1, + new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); + // just a dummy + setMergingCA(new ClusteringDensityBased(0., 0, new IndividualDataMetric(ParticleSwarmOptimization.partBestPosKey))); + setEpsilonBound(epsilonConv); + setHaltingWindow(haltingWindow); + setMaxSpeciesSize(popSize); + setOptimizer(new ParticleSwarmOptimization(popSize, 2.05, 2.05, PSOTopologyEnum.grid, 2)); + ParamAdaption[] defAdpt = new ParamAdaption[]{}; + setParameterControl(defAdpt); // if (threshAdaption) addParameterControl(getDefaultThreshAdaption()); - setPopulationSize(popSize); - } + setPopulationSize(popSize); + } // public void hideHideable() - + @Override - public String getName() { - return "SqPSO"; - } + public String getName() { + return "SqPSO"; + } } diff --git a/src/eva2/optimization/strategies/StarANPSO.java b/src/eva2/optimization/strategies/StarANPSO.java index e6ed704f..13dd94dd 100644 --- a/src/eva2/optimization/strategies/StarANPSO.java +++ b/src/eva2/optimization/strategies/StarANPSO.java @@ -4,36 +4,36 @@ import eva2.optimization.operator.paramcontrol.LinearParamAdaption; import eva2.optimization.operator.paramcontrol.ParamAdaption; public class StarANPSO extends ANPSO { - private int defaultEvalCnt=10000; - - public StarANPSO() { - super(); + private int defaultEvalCnt = 10000; - NichePSO.starNPSO(this, defaultEvalCnt); - setMainSwarmAlgoType(getMainSwarm().getAlgoType().setSelectedTag("Inertness")); - getMainSwarm().setParameterControl(new ParamAdaption[]{new LinearParamAdaption("inertnessOrChi", 0.7, 0.2)}); + public StarANPSO() { + super(); + + NichePSO.starNPSO(this, defaultEvalCnt); + setMainSwarmAlgoType(getMainSwarm().getAlgoType().setSelectedTag("Inertness")); + getMainSwarm().setParameterControl(new ParamAdaption[]{new LinearParamAdaption("inertnessOrChi", 0.7, 0.2)}); // setMainSwarmInertness(new LinearParameterAging(0.7, 0.2, defaultEvalCnt/getMainSwarmSize())); - - getMainSwarm().setPhi1(1.2); - getMainSwarm().setPhi2(0.6); // ANPSO uses communication in the main swarm - //Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", "HPSO", "Random" in that order starting by 0. - SetMainSwarmTopologyTag(3); //"Multi-Swarm" favors the formation of groups in the main swarm - setMainSwarmTopologyRange(2); // range for topologies like random, grid etc. (does not affect "Multi-Swarm") - setMaxInitialSubSwarmSize(0); // deactivate early reinits - } + + getMainSwarm().setPhi1(1.2); + getMainSwarm().setPhi2(0.6); // ANPSO uses communication in the main swarm + //Possible topologies are: "Linear", "Grid", "Star", "Multi-Swarm", "Tree", "HPSO", "Random" in that order starting by 0. + SetMainSwarmTopologyTag(3); //"Multi-Swarm" favors the formation of groups in the main swarm + setMainSwarmTopologyRange(2); // range for topologies like random, grid etc. (does not affect "Multi-Swarm") + setMaxInitialSubSwarmSize(0); // deactivate early reinits + } // public void setEvaluationCount(int evalCnt) { // setMainSwarmInertness(new LinearParameterAging(0.7, 0.2, evalCnt/getMainSwarmSize())); // } - - public StarANPSO(StarANPSO o) { - super(o); - this.defaultEvalCnt=o.defaultEvalCnt; - } - @Override - public String getName() { - return "Star-"+super.getName(); - } + public StarANPSO(StarANPSO o) { + super(o); + this.defaultEvalCnt = o.defaultEvalCnt; + } + + @Override + public String getName() { + return "Star-" + super.getName(); + } } diff --git a/src/eva2/optimization/strategies/ThresholdAlgorithm.java b/src/eva2/optimization/strategies/ThresholdAlgorithm.java index 29c6eab1..2b93d8fb 100644 --- a/src/eva2/optimization/strategies/ThresholdAlgorithm.java +++ b/src/eva2/optimization/strategies/ThresholdAlgorithm.java @@ -61,7 +61,7 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override diff --git a/src/eva2/optimization/strategies/Tribes.java b/src/eva2/optimization/strategies/Tribes.java index beb2f9af..af1c5761 100644 --- a/src/eva2/optimization/strategies/Tribes.java +++ b/src/eva2/optimization/strategies/Tribes.java @@ -15,6 +15,7 @@ import eva2.optimization.strategies.tribes.TribesExplorer; import eva2.optimization.strategies.tribes.TribesParam; import eva2.optimization.strategies.tribes.TribesPosition; import eva2.optimization.strategies.tribes.TribesSwarm; + import java.util.Iterator; import java.util.List; @@ -31,19 +32,18 @@ import java.util.List; * the CEC 2005 benchmarks (see the corresponding class) - I widely kept the * original comments, except for places I changed the code so much that they * might mislead - thats all, I think - * + *

* I could produce similar results as Clerc's on Rosenbrock and Griewank, (in * his book on p. 148), I couldnt reproduce the 100% success rate on Ackley, * though. * * @author Maurice Clerc, Marcel Kronfeld - * @date 2007-09-13 - * - * Original notes: - * @version 2006-02 21 * @author Maurice.Clerc@WriteMe.com {@link http://mauriceclerc.net} - * {@link http://clerc.maurice.free.fr/pso/} - * + * {@link http://clerc.maurice.free.fr/pso/} + * @version 2006-02 21 + * @date 2007-09-13 + *

+ * Original notes: */ /* Last updates (M.Clerc) 2006-02-21 Added a repelling option (see variable "repel" in Tribes). Not very convincing @@ -228,7 +228,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { population.clear(); population.addAll(swarm.toPopulation()); - population.init(); // necessary to allow for multi-runs + population.init(); // necessary to allow for multi-runs if (m_Show) { show(); @@ -264,7 +264,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { public void optimize() { int initOption = 0; - if (iter == 0) { // first iteration! + if (iter == 0) { // first iteration! if (initRange == null) { rangeInitType = 0; } else { @@ -530,7 +530,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { * evalF; if (evalF < pb.maxEval) { temp[2] = 1; } else { temp[2] = 0; } * * return temp; } - * + * */ /** * Population will be hidden. @@ -592,7 +592,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { // return population and memories? Population all = (Population) population.clone(); List mems = swarm.collectMem(); - for (Iterator iterator = mems.iterator(); iterator.hasNext();) { + for (Iterator iterator = mems.iterator(); iterator.hasNext(); ) { TribesPosition tp = iterator.next(); all.add(positionToExplorer(tp)); } @@ -728,6 +728,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { // public void setUseAnchor(boolean useAnchor) { // this.useAnchor = useAnchor; // } + /** * @return the m_Show */ diff --git a/src/eva2/optimization/strategies/WingedMultiObjectiveEA.java b/src/eva2/optimization/strategies/WingedMultiObjectiveEA.java index 3422f1ec..5d0ca206 100644 --- a/src/eva2/optimization/strategies/WingedMultiObjectiveEA.java +++ b/src/eva2/optimization/strategies/WingedMultiObjectiveEA.java @@ -94,7 +94,7 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria /** * This method will init the optimizer with a given population * - * @param pop The initial population + * @param pop The initial population * @param reset If true the population is reset. */ @Override @@ -181,7 +181,6 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria /** * This method implements the migration between the optimzers - * */ private void migrate() { AbstractEAIndividual[] bestIndys = new AbstractEAIndividual[this.m_OutputDimension]; diff --git a/src/eva2/optimization/strategies/tribes/Tribe.java b/src/eva2/optimization/strategies/tribes/Tribe.java index 43af08bc..b63bd8d1 100644 --- a/src/eva2/optimization/strategies/tribes/Tribe.java +++ b/src/eva2/optimization/strategies/tribes/Tribe.java @@ -6,189 +6,190 @@ import eva2.tools.math.RNG; public class Tribe implements java.io.Serializable { - /** - * - */ - private static final long serialVersionUID = 739772857862893332L; - int explorerNb, memoryNb; - TribesExplorer explorer[] = new TribesExplorer[Tribes.maxExplorerNb]; // Les explorateurs - TribesMemory memory[] = new TribesMemory[Tribes.maxMemoryNb]; // La mémoire de la tribu - int shaman; // La meilleure mémoire (son rang, en fait) - int status; // -1=mauvais, 1=bon, 0=les deux! - int worst; + /** + * + */ + private static final long serialVersionUID = 739772857862893332L; + int explorerNb, memoryNb; + TribesExplorer explorer[] = new TribesExplorer[Tribes.maxExplorerNb]; // Les explorateurs + TribesMemory memory[] = new TribesMemory[Tribes.maxMemoryNb]; // La mémoire de la tribu + int shaman; // La meilleure mémoire (son rang, en fait) + int status; // -1=mauvais, 1=bon, 0=les deux! + int worst; - public Tribe() {} + public Tribe() { + } // private void print(String string, OutputStream output) { // output.out.append(string); // } - - public int getNumExplorers() { - return explorerNb; - } - - public int getNumMemories() { - return memoryNb; - } - - public TribesExplorer[] getExplorers() { - return explorer; - } - - public TribesMemory[] getMemories() { - return memory; - } - - public void newTribe(int eNb, TribesExplorer[] expl, - int mNb, TribesMemory[] memo) { - /* + + public int getNumExplorers() { + return explorerNb; + } + + public int getNumMemories() { + return memoryNb; + } + + public TribesExplorer[] getExplorers() { + return explorer; + } + + public TribesMemory[] getMemories() { + return memory; + } + + public void newTribe(int eNb, TribesExplorer[] expl, + int mNb, TribesMemory[] memo) { + /* Generate a new tribe with the new particles that have been generated during a previous time step. At the very beginning explorer[] and memory[] are empty so the tribe is generated from scratch */ - int n; + int n; - explorerNb = eNb; - memoryNb = mNb; + explorerNb = eNb; + memoryNb = mNb; - for (n = 0; n < explorerNb; n++) { - explorer[n] = expl[n].clone(); - } - for (n = 0; n < memoryNb; n++) { - memory[n] = memo[n].clone(); - } + for (n = 0; n < explorerNb; n++) { + explorer[n] = expl[n].clone(); + } + for (n = 0; n < memoryNb; n++) { + memory[n] = memo[n].clone(); + } // Define contacts - for (n = 0; n < explorerNb; n++) { - explorer[n].contact = n; - } + for (n = 0; n < explorerNb; n++) { + explorer[n].contact = n; + } // Status of the tribe - statusTribe(); + statusTribe(); // Look for the shaman - findShaman(); + findShaman(); - } + } - public int moveTribe(double[][] range, TribesParam pb, int tribeRank, - TribesSwarm swarm, int informOption, InterfaceOptimizationProblem prob) { + public int moveTribe(double[][] range, TribesParam pb, int tribeRank, + TribesSwarm swarm, int informOption, InterfaceOptimizationProblem prob) { - int n, m; - double f1, f2; + int n, m; + double f1, f2; - // Shift the memories - for (m = 0; m < memoryNb; m++) { - memory[m].setPrevPos(memory[m].getPos().clone()); - memory[m].status = 0; - } + // Shift the memories + for (m = 0; m < memoryNb; m++) { + memory[m].setPrevPos(memory[m].getPos().clone()); + memory[m].status = 0; + } /* Move the explorers Note: sequential. A bit more effective than parallel mode */ // int evals = 0; - for (n = 0; n < explorerNb; n++) { - - boolean eval = explorer[n].moveExplorer(tribeRank, n, swarm, informOption, prob); + for (n = 0; n < explorerNb; n++) { + + boolean eval = explorer[n].moveExplorer(tribeRank, n, swarm, informOption, prob); // if (eval) evals++; if (pb.constraint) { - explorer[n].constraint(pb.gNb, pb.hNb, pb.ups); + explorer[n].constraint(pb.gNb, pb.hNb, pb.ups); } - // Confidence coefficient(s) update - // Useful only for some strategy(ies) - // explorer[n].confCoeffUpdate(explorer[n].confCoeff[1]); - explorer[n].confCoeffUpdate(explorer[n].confCoeff[0]); + // Confidence coefficient(s) update + // Useful only for some strategy(ies) + // explorer[n].confCoeffUpdate(explorer[n].confCoeff[1]); + explorer[n].confCoeffUpdate(explorer[n].confCoeff[0]); - // Update the contact - f1 = explorer[n].position.getTotalError(); - m = explorer[n].contact; - f2 = memory[m].getPos().getTotalError(); + // Update the contact + f1 = explorer[n].position.getTotalError(); + m = explorer[n].contact; + f2 = memory[m].getPos().getTotalError(); - if (f1 < f2) { - // Update the memory - memory[m].setPos(explorer[n].position.clone()); - memory[m].status = 1; - // Redefine the shaman - if (f1 < memory[shaman].getPos().getTotalError()) { - shaman = m; - } - } + if (f1 < f2) { + // Update the memory + memory[m].setPos(explorer[n].position.clone()); + memory[m].status = 1; + // Redefine the shaman + if (f1 < memory[shaman].getPos().getTotalError()) { + shaman = m; + } + } // if (swarm.notifyAfter(evals)) swarm.registerStateChanged(); - } + } // Update status - statusTribe(); + statusTribe(); // return evals; - return 0; - } + return 0; + } - public void reinitTribe(TribesSwarm swarm, InterfaceOptimizationProblem prob, int initType) { - // System.out.print("\n reinitTribe"); - int contact; - int n; - int option; - - // Reinitialise explorers - for (n = 0; n < explorerNb; n++) { - contact = explorer[n].contact; // Keep the same contact - option = RNG.randomInt(3); - TribesSwarm emptySwarm= new TribesSwarm(null, swarm.getRange(), swarm.getInitRange()); - TribesPosition emptyPos=new TribesPosition(swarm.getProblemDim()); - explorer[n] = emptySwarm.generateExplorer(emptyPos, -1, option, -1, initType, prob, true); - explorer[n].contact = contact; - } - // Reinitialise contacts, except shaman - for (n = 0; n < explorerNb; n++) { - contact = explorer[n].contact; - if (contact != shaman) { - memory[contact].setPos(explorer[n].position.clone()); - memory[contact].setPrevPos(explorer[n].position.clone()); - memory[contact].status = 0; - } - } - // Redefine shaman - findShaman(); + public void reinitTribe(TribesSwarm swarm, InterfaceOptimizationProblem prob, int initType) { + // System.out.print("\n reinitTribe"); + int contact; + int n; + int option; + + // Reinitialise explorers + for (n = 0; n < explorerNb; n++) { + contact = explorer[n].contact; // Keep the same contact + option = RNG.randomInt(3); + TribesSwarm emptySwarm = new TribesSwarm(null, swarm.getRange(), swarm.getInitRange()); + TribesPosition emptyPos = new TribesPosition(swarm.getProblemDim()); + explorer[n] = emptySwarm.generateExplorer(emptyPos, -1, option, -1, initType, prob, true); + explorer[n].contact = contact; + } + // Reinitialise contacts, except shaman + for (n = 0; n < explorerNb; n++) { + contact = explorer[n].contact; + if (contact != shaman) { + memory[contact].setPos(explorer[n].position.clone()); + memory[contact].setPrevPos(explorer[n].position.clone()); + memory[contact].status = 0; + } + } + // Redefine shaman + findShaman(); // Update status - statusTribe(); + statusTribe(); - } + } - public void findShaman() { - int n; - shaman = 0; - if (memoryNb > 1) { - for (n = 1; n < memoryNb; n++) { - if (memory[n].getPos().getTotalError() < memory[shaman]. - getPos().getTotalError()) { - shaman = n; - } - } - } - } + public void findShaman() { + int n; + shaman = 0; + if (memoryNb > 1) { + for (n = 1; n < memoryNb; n++) { + if (memory[n].getPos().getTotalError() < memory[shaman]. + getPos().getTotalError()) { + shaman = n; + } + } + } + } - public void statusTribe() { - /* + public void statusTribe() { + /* -1 = "bad" tribe 1 = "good" tribe 0 = neutral */ - int improvementNb = 0; - int n; + int improvementNb = 0; + int n; - // Nb of memories that have improved their position - for (n = 0; n < memoryNb; n++) { - if (memory[n].status >= 1) { - improvementNb++; - } - } + // Nb of memories that have improved their position + for (n = 0; n < memoryNb; n++) { + if (memory[n].status >= 1) { + improvementNb++; + } + } /* The following rules can of course be modified The more a tribe is easily said "bad", the faster the swarm increases, @@ -196,27 +197,27 @@ public class Tribe implements java.io.Serializable { NOTE: with the current rules a tribe is never neutral */ - status = 0; + status = 0; - // if(improvementNb f1) { - worst = m; - f1 = f2; - } - } - } + for (m = 1; m < explorerNb; m++) { + f2 = memory[explorer[m].contact].getPos().getTotalError(); + if (f2 > f1) { + worst = m; + f1 = f2; + } + } + } - public void deleteExplorer(int worstRank) { - int k; + public void deleteExplorer(int worstRank) { + int k; - if (worstRank < explorerNb - 1) { - for (k = worstRank; k < explorerNb - 1; k++) { - explorer[k] = explorer[k + 1]; - } - } - explorerNb--; - } + if (worstRank < explorerNb - 1) { + for (k = worstRank; k < explorerNb - 1; k++) { + explorer[k] = explorer[k + 1]; + } + } + explorerNb--; + } - public void migrateAccept(TribesExplorer explorerNew) { + public void migrateAccept(TribesExplorer explorerNew) { - int contact; + int contact; - explorer[explorerNb] = explorerNew; - // Add a contact at random - contact = RNG.randomInt(0, memoryNb-1); - explorer[explorerNb].contact = contact; + explorer[explorerNb] = explorerNew; + // Add a contact at random + contact = RNG.randomInt(0, memoryNb - 1); + explorer[explorerNb].contact = contact; - // Update contact - if (explorerNew.position.getTotalError() < - this.memory[contact].getPos().getTotalError()) { - this.memory[contact].setPos(explorerNew.position.clone()); - this.memory[contact].status = 1; - } + // Update contact + if (explorerNew.position.getTotalError() < + this.memory[contact].getPos().getTotalError()) { + this.memory[contact].setPos(explorerNew.position.clone()); + this.memory[contact].status = 1; + } - explorerNb++; - } + explorerNb++; + } // public void displayTribe(out out) { // int n; diff --git a/src/eva2/optimization/strategies/tribes/TribesExplorer.java b/src/eva2/optimization/strategies/tribes/TribesExplorer.java index 3c0a7348..2918b6e1 100644 --- a/src/eva2/optimization/strategies/tribes/TribesExplorer.java +++ b/src/eva2/optimization/strategies/tribes/TribesExplorer.java @@ -9,16 +9,16 @@ import eva2.tools.math.RNG; public class TribesExplorer extends AbstractEAIndividual implements InterfaceDataTypeDouble { /** - * - */ - private static final long serialVersionUID = 1L; - TribesPosition positionT_2; // Position at time t-2 + * + */ + private static final long serialVersionUID = 1L; + TribesPosition positionT_2; // Position at time t-2 TribesPosition positionT_1; // Position at time t-1 TribesPosition position; // Current position - TribesPosition velocity; + TribesPosition velocity; double[][] range = null; protected double objectiveValueFirstDim = 0.; - + // int informant[] = new int[4]; /* informant[0] = tribe rank in the swarm @@ -38,15 +38,15 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat int strategy; // Moving strategy int status; // 1 to 9 int label; - + public TribesExplorer(double[][] range, double objFirstDim) { - init(range.length, Tribes.maxTribeNb); - SetDoubleRange(range); - objectiveValueFirstDim = objFirstDim; + init(range.length, Tribes.maxTribeNb); + SetDoubleRange(range); + objectiveValueFirstDim = objFirstDim; } - + public TribesExplorer(TribesExplorer expl) { - this(expl.getDoubleRange(), expl.objectiveValueFirstDim); + this(expl.getDoubleRange(), expl.objectiveValueFirstDim); int n; for (n = 0; n < 2; n++) { // Clone.informant[n] = explorer.informant[n]; @@ -65,76 +65,76 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat iGroup[n][0] = expl.iGroup[n][0]; } } - + public void init(int maxDimension, int maxTribeNb) { - initPositions(maxDimension); - iGroup = new int[maxTribeNb][2]; + initPositions(maxDimension); + iGroup = new int[maxTribeNb][2]; } - protected void initPositions(int maxDimension) { - positionT_2 = new TribesPosition(maxDimension); // Position at time t-2 - positionT_1 = new TribesPosition(maxDimension); // Position at time t-1 - position = new TribesPosition(maxDimension); // Current position - velocity = new TribesPosition(maxDimension); - } + protected void initPositions(int maxDimension) { + positionT_2 = new TribesPosition(maxDimension); // Position at time t-2 + positionT_1 = new TribesPosition(maxDimension); // Position at time t-1 + position = new TribesPosition(maxDimension); // Current position + velocity = new TribesPosition(maxDimension); + } // private void print(String string, out output) { // output.out.append(string); // } - + @Override public double[] getFitness() { - return position.getFitness(); + return position.getFitness(); } - + @Override public double getFitness(int index) { - return position.getFitness()[index]; + return position.getFitness()[index]; } - + /** * Be aware that for a TribesExplorer, an objective value might be taken into account * by reducing the fitness (in the first dimension). */ @Override public void setFitness(double[] fitness) { - position.fitness = fitness; - super.setFitness(fitness); - fitness[0] -= objectiveValueFirstDim; - position.setTotalError(); + position.fitness = fitness; + super.setFitness(fitness); + fitness[0] -= objectiveValueFirstDim; + position.setTotalError(); } - + /** * Be aware that for a TribesExplorer, an objective value might be taken into account * by reducing the fitness (in the first dimension). */ @Override public void SetFitness(int index, double fitness) { - super.SetFitness(index, fitness); - if (index > position.fitness.length) { - double[] newFit = new double[index+1]; - System.arraycopy(position.fitness, 0, newFit, 0, position.fitness.length); - position.fitness = newFit; - } - if (index == 0) { - position.fitness[index] = (fitness-objectiveValueFirstDim); - } else { - position.fitness[index] = fitness; - } - position.setTotalError(); + super.SetFitness(index, fitness); + if (index > position.fitness.length) { + double[] newFit = new double[index + 1]; + System.arraycopy(position.fitness, 0, newFit, 0, position.fitness.length); + position.fitness = newFit; + } + if (index == 0) { + position.fitness[index] = (fitness - objectiveValueFirstDim); + } else { + position.fitness[index] = fitness; + } + position.setTotalError(); } @Override public TribesExplorer clone() { - return new TribesExplorer(this); + return new TribesExplorer(this); } - + /** * Resets all positions and velocity. */ public void clearPosVel() { - initPositions(position.getMaxDimension()); + initPositions(position.getMaxDimension()); } - + // // public int generateExplorer(TribesParam pb, // TribesSwarm swarm, TribesPosition center, double radius, @@ -285,33 +285,33 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat // double pseudoGradient, pseudoGradientBest; switch (informOption) { - default: - System.err.println("moveExplorer error"); - break; - case -1: // The "true" best informant + default: + System.err.println("moveExplorer error"); + break; + case -1: // The "true" best informant /* In the tribe it should be the shaman */ - iGroup[0][0] = tribeRank; - iGroup[0][1] = swarm.tribes[tribeRank].shaman; + iGroup[0][0] = tribeRank; + iGroup[0][1] = swarm.tribes[tribeRank].shaman; /* System.out.print("\ninformExplorer " + iGroup[0][0]+ " " + iGroup[0][1] + " "); */ //For the shaman, links to the other shamans - m = 1; - for (n = 0; n < swarm.tribeNb; n++) { - if (n == fromTribe) { - continue; + m = 1; + for (n = 0; n < swarm.tribeNb; n++) { + if (n == fromTribe) { + continue; + } + iGroup[m][0] = n; + iGroup[m][1] = swarm.tribes[n].shaman; + m++; } - iGroup[m][0] = n; - iGroup[m][1] = swarm.tribes[n].shaman; - m++; - } - break; + break; /* case 1: // Depending on pseudo-gradient f1 = position.totalError; @@ -363,7 +363,7 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat public boolean moveExplorer(int fromTribe, int rank, TribesSwarm swarm, - int informOption, InterfaceOptimizationProblem prob) { + int informOption, InterfaceOptimizationProblem prob) { int i; boolean fitnessEval; int n; @@ -400,11 +400,11 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat // May use repelling if (Tribes.repel && (swarm.tribes[fromTribe].explorerNb > 2) && - (rank == swarm.tribes[fromTribe].worst)) { + (rank == swarm.tribes[fromTribe].worst)) { for (i = 0; i < velocity.x.length; i++) { velocity.x[i] = -velocity.x[i]; } - //System.out.print("\n repelling"); + //System.out.print("\n repelling"); } // Update position @@ -441,17 +441,17 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat // System.out.print("\n fitness before move "+movedExplorer.position.fitness); if (fitnessEval) { if (swarm.masterTribe.isCheckConstraints() || !outH) { // certainly within range - prob.evaluate(this); - swarm.masterTribe.incEvalCnt(); + prob.evaluate(this); + swarm.masterTribe.incEvalCnt(); // evalF = position.fitnessEval(pb.function, pb.objective, // pb.fitnessSize, eval); } else { // Artificial fitness by using penalties for (n = 0; n < position.fitness.length; n++) { - SetFitness(n, swarm.tribes[fromTribe].memory[ - contact]. - getPos(). - fitness[n] + - keepInPenalty(range, position)); + SetFitness(n, swarm.tribes[fromTribe].memory[ + contact]. + getPos(). + fitness[n] + + keepInPenalty(range, position)); } // position.totalError(position.fitness); // MK: this wont actually do anything } @@ -506,53 +506,53 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat */ switch (status) { - default: + default: - // strategy = RNG.randomInt(4); // 0 to 3 - strategy = 1 + RNG.randomInt(3); // 1 to 3 + // strategy = RNG.randomInt(4); // 0 to 3 + strategy = 1 + RNG.randomInt(3); // 1 to 3 - case 1: - strategy = 1 + RNG.randomInt(3); - break; - case 2: - strategy = 1 + RNG.randomInt(3); - break; - case 3: - strategy = 1 + RNG.randomInt(3); - break; + case 1: + strategy = 1 + RNG.randomInt(3); + break; + case 2: + strategy = 1 + RNG.randomInt(3); + break; + case 3: + strategy = 1 + RNG.randomInt(3); + break; - case 4: - strategy = 1 + RNG.randomInt(3); - break; - case 5: - strategy = 1 + RNG.randomInt(3); - break; + case 4: + strategy = 1 + RNG.randomInt(3); + break; + case 5: + strategy = 1 + RNG.randomInt(3); + break; - case 6: + case 6: - break; + break; - case 7: - if (statusTribe == 1) { - strategy = RNG.randomInt(2); - } - break; - case 8: - if (statusTribe == 1) { - strategy = RNG.randomInt(2); - } - break; + case 7: + if (statusTribe == 1) { + strategy = RNG.randomInt(2); + } + break; + case 8: + if (statusTribe == 1) { + strategy = RNG.randomInt(2); + } + break; - case 9: - if (statusTribe == 1) { - strategy = RNG.randomInt(2); - } else if (Tribes.blind > 0) { - strategy = 6; // Keep moving the same way - } else { - //strategy = 4; // Quasi-gradient (questionable) - strategy = 5; // Adaptive coefficients - } - break; + case 9: + if (statusTribe == 1) { + strategy = RNG.randomInt(2); + } else if (Tribes.blind > 0) { + strategy = 6; // Keep moving the same way + } else { + //strategy = 4; // Quasi-gradient (questionable) + strategy = 5; // Adaptive coefficients + } + break; } /* // Bias in favor of strategy 5 @@ -568,8 +568,8 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat */ //strategy=9; //*** TEST non adaptive parametric strategy (cf. velocitClass) - // For information. Will be displayed - Tribes.strategies[strategy - 1]++; + // For information. Will be displayed + Tribes.strategies[strategy - 1]++; } // public void displayExplorer(out out) { @@ -583,7 +583,7 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat // } // } -// public void initExplorerSpace(int D, double[] xmin, double[] xmax) { + // public void initExplorerSpace(int D, double[] xmin, double[] xmax) { // // Random initialisation of position // int d; // double r; @@ -616,6 +616,7 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat confCoeff[1] = (r + 1) * (r + 2) / 4; // Mean value (Cf. "Stagnation Analysis") } + private double keepInPenalty(double[][] range, TribesPosition pos) { int d; double penalty = 0; @@ -675,7 +676,7 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat } -// int gNb; // Number of g constraints (<=0) + // int gNb; // Number of g constraints (<=0) // int hNb; // Number of h constraints (pas d'amélioration 1 => amélioration */ - int label; + int label; + public TribesMemory(int problemDim) { - position = new TribesPosition(problemDim); - positionPrev = new TribesPosition(problemDim); + position = new TribesPosition(problemDim); + positionPrev = new TribesPosition(problemDim); } // private void print(String string, out output) { @@ -22,20 +23,20 @@ public class TribesMemory implements java.io.Serializable { // } public TribesPosition getPos() { - return position; + return position; } public void setPos(TribesPosition pos) { - position = pos; + position = pos; } - + public void setPrevPos(TribesPosition ppos) { - positionPrev = ppos; + positionPrev = ppos; } - + public TribesExplorer asDummyExplorer(double[][] range, double objFirstDim) { - TribesExplorer exp = new TribesExplorer(range, objFirstDim); - exp.position = getPos().clone(); + TribesExplorer exp = new TribesExplorer(range, objFirstDim); + exp.position = getPos().clone(); exp.contact = -1; exp.positionT_2 = null; exp.positionT_1 = null; @@ -44,16 +45,16 @@ public class TribesMemory implements java.io.Serializable { exp.status = -1; exp.iGroupNb = -1; - return exp; + return exp; } - + public TribesPosition getPrevPos() { - return positionPrev; + return positionPrev; } - + @Override public TribesMemory clone() { - TribesMemory clone = new TribesMemory(position.x.length); + TribesMemory clone = new TribesMemory(position.x.length); clone.status = status; clone.position = position.clone(); clone.positionPrev = positionPrev.clone(); @@ -61,13 +62,13 @@ public class TribesMemory implements java.io.Serializable { } - public int statusMemory(TribesMemory memory,int functionNb,int fitnessSize) { + public int statusMemory(TribesMemory memory, int functionNb, int fitnessSize) { /* On cherche un minimum, donc amélioration si la valeur de la position a diminué */ - if (position.firstIsBetter(position.getFitness(),positionPrev.getFitness())) { - return 1; + if (position.firstIsBetter(position.getFitness(), positionPrev.getFitness())) { + return 1; } return 0; } diff --git a/src/eva2/optimization/strategies/tribes/TribesParam.java b/src/eva2/optimization/strategies/tribes/TribesParam.java index cc2d313b..95608708 100644 --- a/src/eva2/optimization/strategies/tribes/TribesParam.java +++ b/src/eva2/optimization/strategies/tribes/TribesParam.java @@ -2,14 +2,14 @@ package eva2.optimization.strategies.tribes; /** * This class for now is used only for keeping the door open to the original - * constraint handling, still it is deactivated as of now. + * constraint handling, still it is deactivated as of now. */ public class TribesParam implements java.io.Serializable { -/** - * - */ - private static final long serialVersionUID = 1L; - // double accuracy; + /** + * + */ + private static final long serialVersionUID = 1L; + // double accuracy; // int[] function = new int[Tribes.maxFunctionNb]; // int functionNb; // int maxEval; @@ -24,9 +24,9 @@ public class TribesParam implements java.io.Serializable { double ups; // Tolerance for h constraints boolean constraint; // int fitnessSize; - + public TribesParam() { - // H = new TribesSearchSpace(); - constraint = false; + // H = new TribesSearchSpace(); + constraint = false; } } \ No newline at end of file diff --git a/src/eva2/optimization/strategies/tribes/TribesPosition.java b/src/eva2/optimization/strategies/tribes/TribesPosition.java index 9421b3c7..3b02bd8f 100644 --- a/src/eva2/optimization/strategies/tribes/TribesPosition.java +++ b/src/eva2/optimization/strategies/tribes/TribesPosition.java @@ -2,24 +2,25 @@ package eva2.optimization.strategies.tribes; import eva2.optimization.strategies.Tribes; import eva2.tools.math.RNG; + import java.util.Arrays; public class TribesPosition implements java.io.Serializable { /** - * - */ - private static final long serialVersionUID = 1L; - private boolean TRACE = false; - double x[]; - int[][] maxIsoLink = null; + * + */ + private static final long serialVersionUID = 1L; + private boolean TRACE = false; + double x[]; + int[][] maxIsoLink = null; double[] fitness; private double totalError; double isolation; public TribesPosition(int maxDimension) { - x = new double[maxDimension]; - fitness = new double[1];// new double[maxFunctionNb]; // TODO + x = new double[maxDimension]; + fitness = new double[1];// new double[maxFunctionNb]; // TODO } // public TribesPosition clone(TribesPosition position, int fitnessSize) { @@ -52,47 +53,49 @@ public class TribesPosition implements java.io.Serializable { } public double[] getDoubleArray() { - return x; + return x; } /** * This one makes a deep copy. + * * @param vals */ public void setDoubleArray(double[] vals) { - x = vals.clone(); + x = vals.clone(); } /** * This one makes a shallow copy. + * * @param fit */ public void setFitness(double[] fit) { - fitness = fit; + fitness = fit; } - + public int getMaxDimension() { - return x.length; + return x.length; } - + public double[] getFitness() { - return fitness; + return fitness; } public double[] getPos() { - return x; + return x; } - - public double distanceTo(TribesPosition pos) { - double di, dist=0; - int d; - for(d=0;d one memory - TribesExplorer explorer = new TribesExplorer(range, 0.); // obj value will not be regarded here + TribesExplorer explorer = new TribesExplorer(range, 0.); // obj value will not be regarded here TribesMemory memory = new TribesMemory(range.length); //int link[][] = if ((maxIsoLink == null) || (maxIsoLink.length != swarm.size)) { - maxIsoLink = new int[swarm.size][swarm.size]; + maxIsoLink = new int[swarm.size][swarm.size]; } - for (int i=0; i - swarm.bestMem.getPrevPos().fitness[0]; + swarm.bestMem.getPrevPos().fitness[0]; //swarm.bestMem.position=swarm.bestMem.position.clone(); // MK: whats this?? if (!improv) { @@ -741,16 +744,16 @@ public class TribesPosition implements java.io.Serializable { */ for (n = 0; n < swarm.size; n++) { - Arrays.fill(maxIsoLink[n], 0); + Arrays.fill(maxIsoLink[n], 0); maxIsoLink[n][n] = 1; } for (n = 0; n < swarm.size; n++) { // m = RNG.randomInt(0,neighbourhoodSize-1); // maxIsoLink[n][m] = 1; - for (int k=0; k < neighbourhoodSize; k++) { - m = RNG.randomInt(swarm.size); - maxIsoLink[n][m] = 1; - } + for (int k = 0; k < neighbourhoodSize; k++) { + m = RNG.randomInt(swarm.size); + maxIsoLink[n][m] = 1; + } } } @@ -760,11 +763,11 @@ public class TribesPosition implements java.io.Serializable { fBest = swarm.tribes[0].memory[best].getPos().fitness[0]; for (n = 1; n < swarm.size; n++) { // check neighbors if (maxIsoLink[n][m] == 1) { - f2 = swarm.tribes[0].memory[n].getPos().fitness[0]; - if (f2 > fBest) { - best = n; - fBest = f2; - } + f2 = swarm.tribes[0].memory[n].getPos().fitness[0]; + if (f2 > fBest) { + best = n; + fBest = f2; + } } } @@ -777,9 +780,9 @@ public class TribesPosition implements java.io.Serializable { swarm.tribes[0].explorer[m].velocity.x[d] = c1 * swarm.tribes[0].explorer[m].velocity.x[d] + cmax * r1 * - (swarm.tribes[0].memory[m].getPos().x[d] - xd) + + (swarm.tribes[0].memory[m].getPos().x[d] - xd) + cmax * r2 * - (swarm.tribes[0].memory[best].getPos().x[d] - xd); + (swarm.tribes[0].memory[best].getPos().x[d] - xd); swarm.tribes[0].explorer[m].position.x[d] = xd + swarm.tribes[0].explorer[m].velocity.x[d]; @@ -831,7 +834,7 @@ public class TribesPosition implements java.io.Serializable { for(d=0;d collectMem() { - ArrayList bestList = new ArrayList(); - - for (int n = 0; n < tribeNb; n++) { - for (int m = 0; m < tribes[n].memoryNb; m++) { - bestList.add(tribes[n].memory[m].getPos()); - } - } - return bestList; + ArrayList bestList = new ArrayList(); + + for (int n = 0; n < tribeNb; n++) { + for (int m = 0; m < tribes[n].memoryNb; m++) { + bestList.add(tribes[n].memory[m].getPos()); + } + } + return bestList; } - + /** * This searches for the best memory, and also sets the bestMem member of the swarm. * @@ -224,7 +226,7 @@ public class TribesSwarm implements java.io.Serializable{ * @see find(boolean switchBest) */ public int[] findBest() { - int best[] = find(true); + int best[] = find(true); bestMem = tribes[best[0]].memory[best[1]].clone(); return best; @@ -266,7 +268,7 @@ public class TribesSwarm implements java.io.Serializable{ // } // } - return find(false); + return find(false); } public void addTribe(int explorerNb, TribesExplorer explorer[]) { @@ -327,7 +329,7 @@ public class TribesSwarm implements java.io.Serializable{ Compute the number of explorers WARNING: it does NOT compute the number of memories */ - size = numExplorers(); + size = numExplorers(); } // public void displaySwarm(TribesSwarm swarm, out out) { @@ -341,7 +343,7 @@ public class TribesSwarm implements java.io.Serializable{ // } /** - * + * */ public void adaptSwarm(int initType, InterfaceOptimizationProblem prob) { int centerRank = 0; // Arbitrary value to avoid compiler error @@ -350,7 +352,7 @@ public class TribesSwarm implements java.io.Serializable{ int gmax = 4; // int[] gener = {0,1,2,0}; // For gmax kinds of particles to generate - int[] gener = {0,1,1,2}; // For gmax kinds of particles to generate + int[] gener = {0, 1, 1, 2}; // For gmax kinds of particles to generate /* 0 => at random anywhere in the search space 1 => on bounds @@ -367,8 +369,8 @@ public class TribesSwarm implements java.io.Serializable{ and the other around it Only 2 and a variant of strategy 3 (around the center) are then used */ - - int n; + + int n; int explorerNb = 0; double radius = -1; int shaman; @@ -376,97 +378,97 @@ public class TribesSwarm implements java.io.Serializable{ int worstRank; TribesExplorer explorer[] = new TribesExplorer[ - Tribes.maxExplorerNb]; + Tribes.maxExplorerNb]; for (n = 0; n < tribeNb; n++) { switch (tribes[n].status) { - default: // Do nothing - break; - - case -1: // Bad tribe => generation - - // Number of particles to generate - particlesToGenerate = Tribes.particleNb(range.length, tribeNb); - if (particlesToGenerate < 2) { - particlesToGenerate = 2; - } - - // If too many particles, do nothing in order to avoid memory overflow - if (explorerNb >= Tribes.maxExplorerNb - particlesToGenerate - 1) { + default: // Do nothing break; - } - //Generate some particles - switch (gMode) { - default: // According to gener[] - shaman = tribes[n].shaman; + case -1: // Bad tribe => generation - for (int g = 0; g < particlesToGenerate; g++) { - gOption = g % gmax; - explorer[explorerNb] = generateExplorer(tribes[n].memory[shaman].getPos(), -1, gener[gOption], n, 0, prob, true); + // Number of particles to generate + particlesToGenerate = Tribes.particleNb(range.length, tribeNb); + if (particlesToGenerate < 2) { + particlesToGenerate = 2; + } + + // If too many particles, do nothing in order to avoid memory overflow + if (explorerNb >= Tribes.maxExplorerNb - particlesToGenerate - 1) { + break; + } + + //Generate some particles + switch (gMode) { + default: // According to gener[] + shaman = tribes[n].shaman; + + for (int g = 0; g < particlesToGenerate; g++) { + gOption = g % gmax; + explorer[explorerNb] = generateExplorer(tribes[n].memory[shaman].getPos(), -1, gener[gOption], n, 0, prob, true); // explorer[explorerNb].generateExplorer(pb, swarm, // tribes[n].memory[shaman].position, -1, // gener[gOption], // n, 0, evalF); - explorerNb++; - } - break; + explorerNb++; + } + break; - case 1: /* First particle in the biggest not yet searched area + case 1: /* First particle in the biggest not yet searched area and the other around it */ - if (explorerNb == 0) { // Generate the center in an "empty" area - centerRank = 0; // - explorer[explorerNb] = generateExplorer(null, -1, 2, n, initType, prob, true); + if (explorerNb == 0) { // Generate the center in an "empty" area + centerRank = 0; // + explorer[explorerNb] = generateExplorer(null, -1, 2, n, initType, prob, true); - radius = explorer[explorerNb].position.isolation; - explorerNb++; - gMin = 1; - } else { - gMin = 0; + radius = explorer[explorerNb].position.isolation; + explorerNb++; + gMin = 1; + } else { + gMin = 0; + } + + //System.out.print("\nadaptSwarm " + explorer[centerRank].position.Dimension); + // Generate the other around the center + + for (int g = gMin; g < particlesToGenerate; g++) { + explorer[explorerNb] = generateExplorer(explorer[centerRank].position, radius, 3, n, initType, prob, true); + explorerNb++; + + } + break; } - //System.out.print("\nadaptSwarm " + explorer[centerRank].position.Dimension); - // Generate the other around the center + break; - for (int g = gMin; g < particlesToGenerate; g++) { - explorer[explorerNb] = generateExplorer(explorer[centerRank].position, radius, 3, n, initType, prob, true); - explorerNb++; + case 1: - } - break; - } - - break; - - case 1: - - // Possibly remove a particle + // Possibly remove a particle /* Possible SIMPLIFICATION: this situation occurs quite rarely. So all this part could be easily removed. It would just mean that no explorer would be removed or exilated. */ - // If the tribe has already no explorer anymore, do nothing - if (tribes[n].explorerNb > 0) { - // Look for the worst explorer of the tribe - // worstRank = tribeClass.worstExplorer(tribes[n]); - tribes[n].worstExplorer(); - worstRank = tribes[n].worst; + // If the tribe has already no explorer anymore, do nothing + if (tribes[n].explorerNb > 0) { + // Look for the worst explorer of the tribe + // worstRank = tribeClass.worstExplorer(tribes[n]); + tribes[n].worstExplorer(); + worstRank = tribes[n].worst; - // Check if exile is possible - welcomeTribe = migrateCheck(worstRank, n); + // Check if exile is possible + welcomeTribe = migrateCheck(worstRank, n); /* If exile is possible, add the particle to the tribe that accept it */ - if (welcomeTribe >= 0) { - tribes[welcomeTribe].migrateAccept(tribes[n].explorer[worstRank]); - // System.out.print("\n EXIL "+n+ " => "+worstRank); - } + if (welcomeTribe >= 0) { + tribes[welcomeTribe].migrateAccept(tribes[n].explorer[worstRank]); + // System.out.print("\n EXIL "+n+ " => "+worstRank); + } /* In any case, remove the explorer from the tribe @@ -477,9 +479,9 @@ public class TribesSwarm implements java.io.Serializable{ */ // System.out.print("\ntribe " + n + " deletes"); - tribes[n].deleteExplorer(worstRank); - } - break; + tribes[n].deleteExplorer(worstRank); + } + break; } } @@ -558,7 +560,7 @@ public class TribesSwarm implements java.io.Serializable{ mTot += w; queen.position.x[d] += w * tribes[t].memory[tribes[t].shaman]. - getPos().x[d]; + getPos().x[d]; } } @@ -579,178 +581,177 @@ public class TribesSwarm implements java.io.Serializable{ // } /** - * * @param center * @param radius - * @param option Options: 0 - random, 1 - on the bounds, 2 - sunny spell, 3 - around a center + * @param option Options: 0 - random, 1 - on the bounds, 2 - sunny spell, 3 - around a center * @param fromTribe * @param initType: for options 0,1: 1 means use initRange, 0 use default range * @param prob * @return */ public TribesExplorer generateExplorer(/*double[][] range, double[][] initRange,*/ - TribesPosition center, double radius, - int option, int fromTribe, - int initType, InterfaceOptimizationProblem prob, boolean notify) { - /* + TribesPosition center, double radius, + int option, int fromTribe, + int initType, InterfaceOptimizationProblem prob, boolean notify) { + /* Generation of a new explorer ("scout") If fromTribe=-1, this is the very first generation */ - TribesExplorer expl = new TribesExplorer(range, masterTribe.getObjectiveFirstDim()); - expl.SetDoubleRange(range); + TribesExplorer expl = new TribesExplorer(range, masterTribe.getObjectiveFirstDim()); + expl.SetDoubleRange(range); // System.out.println("generating expl, option " + option + ", init " + initType + ", from tribe " + fromTribe); - int d, dmax, dmod; - int m; - // int rank; - // int shaman; - double rho; - int D = range.length; - TribesPosition posTemp = new TribesPosition(range.length); - double[] rand_i; + int d, dmax, dmod; + int m; + // int rank; + // int shaman; + double rho; + int D = range.length; + TribesPosition posTemp = new TribesPosition(range.length); + double[] rand_i; - if (Tribes.TRACE) { - System.out.println("+ generateExplorer option " + option); - } - switch (option) { - case 3: // around a "center" - if (Tribes.TRACE) { - System.out.println("+ around center "); - } - if (radius < 0) { - // Choose at random a memory - m = RNG.randomInt(this.tribes[fromTribe].memoryNb); + if (Tribes.TRACE) { + System.out.println("+ generateExplorer option " + option); + } + switch (option) { + case 3: // around a "center" + if (Tribes.TRACE) { + System.out.println("+ around center "); + } + if (radius < 0) { + // Choose at random a memory + m = RNG.randomInt(this.tribes[fromTribe].memoryNb); - // Compute the distance to the "center" = radius - rho = center.distanceTo(this.tribes[fromTribe].memory[m].getPos()); - } else { - rho = radius; - } + // Compute the distance to the "center" = radius + rho = center.distanceTo(this.tribes[fromTribe].memory[m].getPos()); + } else { + rho = radius; + } - // Define a random point in the hypersphere (center, rho) - expl.position.setDoubleArray(RNG.randHypersphere(center.getDoubleArray(), rho, 1.5)); + // Define a random point in the hypersphere (center, rho) + expl.position.setDoubleArray(RNG.randHypersphere(center.getDoubleArray(), rho, 1.5)); - // Define another random point - rand_i = RNG.randHypersphere(center.getDoubleArray(), rho, 1.5); + // Define another random point + rand_i = RNG.randHypersphere(center.getDoubleArray(), rho, 1.5); - // Derive a random velocity - for (d = 0; d < D; d++) { - expl.velocity.x[d] = rand_i[d] - expl.position.x[d]; - } + // Derive a random velocity + for (d = 0; d < D; d++) { + expl.velocity.x[d] = rand_i[d] - expl.position.x[d]; + } - break; + break; - case 2: /* In the biggest "terra incognita" ("no man's land") + case 2: /* In the biggest "terra incognita" ("no man's land") In order to do that all memorizez positions are used, including de "dead" ones See SunnySpell */ - if (Tribes.TRACE) { - System.out.println("+ sunny spell "); - } + if (Tribes.TRACE) { + System.out.println("+ sunny spell "); + } - // if only initRange should be used for initialization, give that one to the sspell - expl.position = expl.position.maxIsolated((initRange == null) ? range : initRange, this); + // if only initRange should be used for initialization, give that one to the sspell + expl.position = expl.position.maxIsolated((initRange == null) ? range : initRange, this); - // At this point, fitness[0] contains the "isolation" value - rand_i = RNG.randHypersphere(expl.position.getDoubleArray(), expl.position.fitness[0], 1.5); - for (d = 0; d < D; d++) { - expl.velocity.x[d] = rand_i[d] - expl.position.x[d]; - } + // At this point, fitness[0] contains the "isolation" value + rand_i = RNG.randHypersphere(expl.position.getDoubleArray(), expl.position.fitness[0], 1.5); + for (d = 0; d < D; d++) { + expl.velocity.x[d] = rand_i[d] - expl.position.x[d]; + } - break; + break; - default: - // For pure random (0) method, or option 1 (on the bounds) - if (initType==1) { // use initRange - if (Tribes.TRACE) { + default: + // For pure random (0) method, or option 1 (on the bounds) + if (initType == 1) { // use initRange + if (Tribes.TRACE) { System.out.println("+ in initRange "); } - if (initRange == null) { + if (initRange == null) { System.err.println("unexpected null initRange!"); } - // this allows for a random position plus a random (but valid) last velocity - expl.initExplorerSpace(initRange); - posTemp = expl.position.clone(); - expl.initExplorerSpace(initRange); - } else { // use default range - if (Tribes.TRACE) { + // this allows for a random position plus a random (but valid) last velocity + expl.initExplorerSpace(initRange); + posTemp = expl.position.clone(); + expl.initExplorerSpace(initRange); + } else { // use default range + if (Tribes.TRACE) { System.out.println("+ in whole range "); } - //default: // In the whole search space - expl.initExplorerSpace(range); - posTemp = expl.position.clone(); - expl.initExplorerSpace(range); - } - for (d = 0; d < range.length; d++) { - expl.velocity.x[d] = posTemp.x[d] - expl.position.x[d]; - } - if (option == 1) { - /* On the boundary of the search space + //default: // In the whole search space + expl.initExplorerSpace(range); + posTemp = expl.position.clone(); + expl.initExplorerSpace(range); + } + for (d = 0; d < range.length; d++) { + expl.velocity.x[d] = posTemp.x[d] - expl.position.x[d]; + } + if (option == 1) { + /* On the boundary of the search space For some dimensions, set the coordinate to the min or the max */ - dmax = RNG.randomInt(D); // For a random number of dimensions - // dmax=D-1; // For all dimensions - for (dmod = 0; dmod <= dmax; dmod++) { - // m = Tribes.generator.nextInt(2); - // if(m==0) continue; // With a probability of 1/2 + dmax = RNG.randomInt(D); // For a random number of dimensions + // dmax=D-1; // For all dimensions + for (dmod = 0; dmod <= dmax; dmod++) { + // m = Tribes.generator.nextInt(2); + // if(m==0) continue; // With a probability of 1/2 - d = RNG.randomInt(D); // 0,1, ... D-1 - m = RNG.randomInt(2); // 0 or 1 - if ((initRange == null) || (initType == 0)) { - expl.position.x[d] = range[d][m]; - } else { - expl.position.x[d] = initRange[d][m]; - } - // velocity.v[d] = 0; - } - } - break; - - } - - // Complete the explorer - prob.evaluate(expl); - if (notify) { - masterTribe.incEvalCnt(); + d = RNG.randomInt(D); // 0,1, ... D-1 + m = RNG.randomInt(2); // 0 or 1 + if ((initRange == null) || (initType == 0)) { + expl.position.x[d] = range[d][m]; + } else { + expl.position.x[d] = initRange[d][m]; + } + // velocity.v[d] = 0; } + } + break; + + } + + // Complete the explorer + prob.evaluate(expl); + if (notify) { + masterTribe.incEvalCnt(); + } /* necessary for initialization when not all explorers have a valid fitness * to avoid zero fitness plot from population.getBest. */ - expl.positionT_1 = expl.position.clone(); - expl.positionT_2 = expl.position.clone(); - expl.label = explorerLabel++; + expl.positionT_1 = expl.position.clone(); + expl.positionT_2 = expl.position.clone(); + expl.label = explorerLabel++; - expl.status = 5; // At the beginning, neutral status + expl.status = 5; // At the beginning, neutral status /* By which tribe the explorer is generated. The value of "fromTribe" has been arbitrarily set to -1 for the very first generation (initialisation) */ - if (fromTribe >= 0) { - expl.iGroup[0][0] = fromTribe; - expl.iGroup[0][1] = this.tribes[fromTribe].shaman; + if (fromTribe >= 0) { + expl.iGroup[0][0] = fromTribe; + expl.iGroup[0][1] = this.tribes[fromTribe].shaman; /* Note : at this point the "contact" (i.e. the memory to update) is not yet defined */ - } else { - expl.iGroupNb = 0; - } - return expl; + } else { + expl.iGroupNb = 0; + } + return expl; } - public void reinitTribe(int tribeIndex, int initType, InterfaceOptimizationProblem prob) { - tribes[tribeIndex].reinitTribe(this, prob, initType); - } - - public double[][] getRange() { - return range; - } + public void reinitTribe(int tribeIndex, int initType, InterfaceOptimizationProblem prob) { + tribes[tribeIndex].reinitTribe(this, prob, initType); + } - public double[][] getInitRange() { - return initRange; - } + public double[][] getRange() { + return range; + } + + public double[][] getInitRange() { + return initRange; + } } diff --git a/src/eva2/optimization/tools/AbstractObjectEditor.java b/src/eva2/optimization/tools/AbstractObjectEditor.java index 74da1292..107657a6 100644 --- a/src/eva2/optimization/tools/AbstractObjectEditor.java +++ b/src/eva2/optimization/tools/AbstractObjectEditor.java @@ -4,6 +4,7 @@ package eva2.optimization.tools; import eva2.gui.*; import eva2.gui.editor.GenericObjectEditor; import eva2.tools.EVAHELP; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -14,7 +15,7 @@ import javax.swing.*; /** * TODO * This class should be unified with GenericObjectEditor. - * + *

* Created by IntelliJ IDEA. * User: streiche * Date: 24.08.2004 @@ -23,171 +24,202 @@ import javax.swing.*; */ public abstract class AbstractObjectEditor implements PropertyEditor, java.beans.PropertyChangeListener { - /** Handles property change notification */ - public PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The Object that is to be edited*/ - public Object m_Object; - public Object m_Backup; - public GeneralGenericObjectEditorPanel m_EditorComponent; - public Hashtable m_Editors = new Hashtable(); + /** + * Handles property change notification + */ + public PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The Object that is to be edited + */ + public Object m_Object; + public Object m_Backup; + public GeneralGenericObjectEditorPanel m_EditorComponent; + public Hashtable m_Editors = new Hashtable(); - /********************************* java.beans.PropertyChangeListener *************************/ + /** + * ****************************** java.beans.PropertyChangeListener ************************ + */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.addPropertyChangeListener(l); + m_Support.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) { + if (m_Support == null) { m_Support = new PropertyChangeSupport(this); } - m_Support.removePropertyChangeListener(l); + m_Support.removePropertyChangeListener(l); } - /** This will wait for the GenericObjectEditor to finish + + /** + * This will wait for the GenericObjectEditor to finish * editing an object. + * * @param evt */ @Override - public void propertyChange(PropertyChangeEvent evt) { + public void propertyChange(PropertyChangeEvent evt) { System.out.println("------------- here-----------------"); this.updateCenterComponent(evt); // Let our panel update before guys downstream m_Support.firePropertyChange("", m_Backup, m_Object); } /********************************* PropertyEditor *************************/ - /** Returns true since the Object can be shown + /** + * Returns true since the Object can be shown + * * @return true */ @Override abstract public boolean isPaintable(); - /** Paints a representation of the current classifier. + /** + * Paints a representation of the current classifier. + * * @param gfx the graphics context to use * @param box the area we are allowed to paint into */ @Override abstract public void paintValue(Graphics gfx, Rectangle box); - /** Returns true because we do support a custom editor. - * @return true - */ + /** + * Returns true because we do support a custom editor. + * + * @return true + */ @Override abstract public boolean supportsCustomEditor(); - /** Returns the array editing component. - * @return a value of type 'java.awt.Component' - */ + /** + * Returns the array editing component. + * + * @return a value of type 'java.awt.Component' + */ @Override abstract public Component getCustomEditor(); @Override abstract public String getAsText(); + @Override abstract public void setAsText(String text) throws IllegalArgumentException; + @Override abstract public String getJavaInitializationString(); + @Override abstract public String[] getTags(); /********************************* AbstractObjectEditor *************************/ - /** This method will make a back up of the current + /** + * This method will make a back up of the current * object value */ abstract public void makeBackup(); - /** This method will use the backup to undo the + /** + * This method will use the backup to undo the * last action. */ abstract public void undoBackup(); - /** This method will fire a property change event - * @param s A describtive string. - * @param old old - * @param n new + /** + * This method will fire a property change event + * + * @param s A describtive string. + * @param old old + * @param n new */ public void firePropertyChange(String s, Object old, Object n) { - m_Support.firePropertyChange(s, old, n); + m_Support.firePropertyChange(s, old, n); } - /** This method allows you to set the current value - * @param obj The new value + /** + * This method allows you to set the current value + * + * @param obj The new value */ @Override abstract public void setValue(Object obj); + @Override public Object getValue() { return this.m_Object; } - /** This method returns the class type + /** + * This method returns the class type + * * @return Class */ abstract public Class getClassType(); // abstract public Vector getClassesFromProperties(); - - /** This method returns a property panel to + + /** + * This method returns a property panel to * edit the parameters + * * @return panel */ public JPanel getPropertyPanel() { - GridBagLayout gbLayout = new GridBagLayout(); - JPanel result = new JPanel(); - JPanel centerWrapper = new JPanel(); + GridBagLayout gbLayout = new GridBagLayout(); + JPanel result = new JPanel(); + JPanel centerWrapper = new JPanel(); this.m_Editors.clear(); result.setLayout(new BorderLayout()); result.setVisible(true); // Define the upper area containing the desription and the help button - String globalInfo = this.getGlobalInfo(); - JTextArea jt = new JTextArea(); - StringBuffer m_HelpText; - String m_ClassName; - JButton m_HelpBut; - m_ClassName = "Genetic Algorithm"; - m_HelpText = new StringBuffer("NAME\n"); + String globalInfo = this.getGlobalInfo(); + JTextArea jt = new JTextArea(); + StringBuffer m_HelpText; + String m_ClassName; + JButton m_HelpBut; + m_ClassName = "Genetic Algorithm"; + m_HelpText = new StringBuffer("NAME\n"); m_HelpText.append(m_ClassName).append("\n\n"); m_HelpText.append("SYNOPSIS\n").append(globalInfo).append("\n\n"); - m_HelpBut = new JButton("Help"); - m_HelpBut.setToolTipText("More information about " + m_ClassName); - m_HelpBut.addActionListener(new ActionListener() { + m_HelpBut = new JButton("Help"); + m_HelpBut.setToolTipText("More information about " + m_ClassName); + m_HelpBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { - HtmlDemo temp = new HtmlDemo(EVAHELP.cutClassName(m_Object.getClass().getName())+".html"); + HtmlDemo temp = new HtmlDemo(EVAHELP.cutClassName(m_Object.getClass().getName()) + ".html"); temp.show(); } }); - jt.setFont(new Font("SansSerif", Font.PLAIN,12)); - jt.setEditable(false); - jt.setLineWrap(true); - jt.setWrapStyleWord(true); - jt.setText(globalInfo); + jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); + jt.setEditable(false); + jt.setLineWrap(true); + jt.setWrapStyleWord(true); + jt.setText(globalInfo); jt.setBackground(result.getBackground()); - JPanel jp = new JPanel(); - jp.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder("Info"), - BorderFactory.createEmptyBorder(0, 5, 5, 5))); - jp.setLayout(new BorderLayout()); - jp.add(jt, BorderLayout.CENTER); + JPanel jp = new JPanel(); + jp.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createTitledBorder("Info"), + BorderFactory.createEmptyBorder(0, 5, 5, 5))); + jp.setLayout(new BorderLayout()); + jp.add(jt, BorderLayout.CENTER); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); if (HtmlDemo.resourceExists(getHelpFileName())) { - p2.add(m_HelpBut, BorderLayout.NORTH); + p2.add(m_HelpBut, BorderLayout.NORTH); } - jp.add(p2, BorderLayout.EAST); - GridBagConstraints gbConstraints = new GridBagConstraints(); - //gbConstraints.anchor = GridBagConstraints.EAST; - gbConstraints.fill = GridBagConstraints.BOTH; - //gbConstraints.gridy = 0; gbConstraints.gridx = 0; - gbConstraints.gridwidth = 2; - gbConstraints.insets = new Insets(0,5,0,5); - gbLayout.setConstraints(jp, gbConstraints); - result.add(jp, BorderLayout.NORTH); + jp.add(p2, BorderLayout.EAST); + GridBagConstraints gbConstraints = new GridBagConstraints(); + //gbConstraints.anchor = GridBagConstraints.EAST; + gbConstraints.fill = GridBagConstraints.BOTH; + //gbConstraints.gridy = 0; gbConstraints.gridx = 0; + gbConstraints.gridwidth = 2; + gbConstraints.insets = new Insets(0, 5, 0, 5); + gbLayout.setConstraints(jp, gbConstraints); + result.add(jp, BorderLayout.NORTH); result.add(this.getCenterComponent(), BorderLayout.CENTER); @@ -196,28 +228,35 @@ public abstract class AbstractObjectEditor implements PropertyEditor, java.beans } public String getHelpFileName() { - return EVAHELP.cutClassName(m_Object.getClass().getName())+".html"; + return EVAHELP.cutClassName(m_Object.getClass().getName()) + ".html"; } - - /** This method return the global info on the current + + /** + * This method return the global info on the current * object. + * * @return The global info. */ abstract public String getGlobalInfo(); - /** This method returns the central editing panel for the current + /** + * This method returns the central editing panel for the current * object. + * * @return The center component. */ abstract public JComponent getCenterComponent(); - /** This method will udate the status of the object taking the values from all + /** + * This method will udate the status of the object taking the values from all * supsequent editors and setting them to my object. */ abstract public void updateCenterComponent(PropertyChangeEvent evt); - /** This method should return the editor for a given property + /** + * This method should return the editor for a given property * from a list of property elements + * * @param prop The property to search for * @param props All properties. * @return PropertyEditor @@ -227,32 +266,32 @@ public abstract class AbstractObjectEditor implements PropertyEditor, java.beans for (int i = 0; i < props.length; i++) { if (props[i].getName().equalsIgnoreCase(prop)) { result = new GeneralGOEProperty(); - Object args[] = { }; - result.m_getMethod = props[i].getReadMethod(); - result.m_setMethod = props[i].getWriteMethod(); - result.m_PropertyType = props[i].getPropertyType(); - result.m_Name = props[i].getDisplayName(); - result.m_Label = new JLabel(result.m_Name, SwingConstants.RIGHT); - result.m_TipText = BeanInspector.getToolTipText(result.m_Name, methods, target); + Object args[] = {}; + result.m_getMethod = props[i].getReadMethod(); + result.m_setMethod = props[i].getWriteMethod(); + result.m_PropertyType = props[i].getPropertyType(); + result.m_Name = props[i].getDisplayName(); + result.m_Label = new JLabel(result.m_Name, SwingConstants.RIGHT); + result.m_TipText = BeanInspector.getToolTipText(result.m_Name, methods, target); try { - result.m_Value = result.m_getMethod.invoke(target, args); + result.m_Value = result.m_getMethod.invoke(target, args); // result.m_Editor = PropertyEditorProvider.findEditor(result.m_Value.getClass()); // if (result.m_Editor == null) result.m_Editor = PropertyEditorProvider.findEditor(result.m_PropertyType); // if (result.m_Editor instanceof GenericObjectEditor) // ((GenericObjectEditor) result.m_Editor).setClassType(result.m_PropertyType); // result.m_Editor.setValue(result.m_Value); // result.m_Editor.addPropertyChangeListener(this); - result.m_Editor = PropertyEditorProvider.findEditor(props[i], result.m_Value); - if (result.m_Editor == null) { + result.m_Editor = PropertyEditorProvider.findEditor(props[i], result.m_Value); + if (result.m_Editor == null) { result.m_Editor = PropertyEditorProvider.findEditor(result.m_PropertyType); } - if (result.m_Editor instanceof GenericObjectEditor) { + if (result.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) result.m_Editor).setClassType(result.m_PropertyType); } - - - result.m_Editor.setValue(result.m_Value); - result.m_Editor.addPropertyChangeListener(this); + + + result.m_Editor.setValue(result.m_Value); + result.m_Editor.addPropertyChangeListener(this); this.findViewFor(result); if (result.m_View != null) { result.m_View.repaint(); @@ -263,20 +302,22 @@ public abstract class AbstractObjectEditor implements PropertyEditor, java.beans return result; } } - if (result==null) { - System.err.println("Warning: unknown property or unable to create editor for property " + prop + ", object " + this.getClass().getName()); + if (result == null) { + System.err.println("Warning: unknown property or unable to create editor for property " + prop + ", object " + this.getClass().getName()); } return result; } - /** This method tries to find a suitable view for a given Property - * @param editor The property the select a view for. + /** + * This method tries to find a suitable view for a given Property + * + * @param editor The property the select a view for. */ public static void findViewFor(GeneralGOEProperty editor) { - editor.m_View = PropertySheetPanel.getView(editor.m_Editor); - if (editor.m_View==null) { + editor.m_View = PropertySheetPanel.getView(editor.m_Editor); + if (editor.m_View == null) { System.out.println("Warning: Property \"" + editor.m_Name - + "\" has non-displayabale editor. Skipping."); + + "\" has non-displayabale editor. Skipping."); } } } \ No newline at end of file diff --git a/src/eva2/optimization/tools/DeNovofilter.java b/src/eva2/optimization/tools/DeNovofilter.java index a73ffbd2..cc989b43 100644 --- a/src/eva2/optimization/tools/DeNovofilter.java +++ b/src/eva2/optimization/tools/DeNovofilter.java @@ -5,6 +5,7 @@ import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.ESIndividualDoubleData; import eva2.optimization.operator.archiving.ArchivingAllDominating; import eva2.optimization.population.Population; + import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; @@ -33,35 +34,36 @@ public class DeNovofilter { System.out.println("Archive " + a.size()); for (int i = 0; i < a.size(); i++) { String s = ""; - double[] d = ((AbstractEAIndividual)a.get(i)).getFitness(); + double[] d = ((AbstractEAIndividual) a.get(i)).getFitness(); for (int j = 0; j < d.length; j++) { - s += ""+d[j]; - if (j < d.length-1) { + s += "" + d[j]; + if (j < d.length - 1) { s += "; "; } } - System.out.println(""+s); + System.out.println("" + s); } } + private void loadData() { pop = new Population(); AbstractEAIndividual indy; - BufferedReader reader= null; + BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("TEST.txt")); } catch (java.io.FileNotFoundException e) { System.out.println("Could not find TEST.txt"); return; } - String currentLine; + String currentLine; try { ArrayList tmpA = new ArrayList(); - while((currentLine=reader.readLine())!=null && currentLine.length()!=0) { + while ((currentLine = reader.readLine()) != null && currentLine.length() != 0) { currentLine = currentLine.trim(); String[] tmpS = currentLine.split(" "); - double[] tmpD = new double[tmpS.length-2]; + double[] tmpD = new double[tmpS.length - 2]; for (int i = 2; i < tmpS.length; i++) { - tmpD[i-2] = new Double(tmpS[i]).doubleValue(); + tmpD[i - 2] = new Double(tmpS[i]).doubleValue(); } indy = new ESIndividualDoubleData(); indy.setFitness(tmpD); diff --git a/src/eva2/optimization/tools/DoubleArrayComparator.java b/src/eva2/optimization/tools/DoubleArrayComparator.java index e34debea..cfaaf49e 100644 --- a/src/eva2/optimization/tools/DoubleArrayComparator.java +++ b/src/eva2/optimization/tools/DoubleArrayComparator.java @@ -1,6 +1,7 @@ package eva2.optimization.tools; import eva2.optimization.individuals.AbstractEAIndividual; + import java.util.Comparator; /** @@ -9,65 +10,62 @@ import java.util.Comparator; * are not comparable. * If a criterion>=0 is specified, only the thereby indexed entry of any array * will be used for comparison (single criterion case). - * */ public class DoubleArrayComparator implements Comparator { - int fitCriterion = -1; - - public DoubleArrayComparator() { - this(-1); - } + int fitCriterion = -1; - /** - * Generic constructor. - * - * @param fitnessCriterion - */ - public DoubleArrayComparator(int criterion) { - fitCriterion = criterion; - } + public DoubleArrayComparator() { + this(-1); + } + + /** + * Generic constructor. + * + * @param fitnessCriterion + */ + public DoubleArrayComparator(int criterion) { + fitCriterion = criterion; + } - public DoubleArrayComparator(DoubleArrayComparator o) { - fitCriterion = o.fitCriterion; - } + public DoubleArrayComparator(DoubleArrayComparator o) { + fitCriterion = o.fitCriterion; + } @Override - public Object clone() { - return new DoubleArrayComparator(this); - } - - /** - * Compare two double arrays based on dominance, return -1 if the first is dominant, 1 if the second is dominant, 0 if they - * are not comparable. - * - * @see #AbstractEAIndividual.isDominatingFitness(double[], double[]) - * @param o1 the first double[] to compare - * @param o2 the second double[] to compare - * @return -1 if the first is dominant, 1 if the second is dominant, otherwise 0 - */ + public Object clone() { + return new DoubleArrayComparator(this); + } + + /** + * Compare two double arrays based on dominance, return -1 if the first is dominant, 1 if the second is dominant, 0 if they + * are not comparable. + * + * @param o1 the first double[] to compare + * @param o2 the second double[] to compare + * @return -1 if the first is dominant, 1 if the second is dominant, otherwise 0 + * @see #AbstractEAIndividual.isDominatingFitness(double[], double[]) + */ @Override - public int compare(Object o1, Object o2) { - boolean o1domO2, o2domO1; - - double[] fit1 = (double[])o1; - double[] fit2 = (double[])o2; - if (fitCriterion < 0) { - o1domO2 = AbstractEAIndividual.isDominatingFitness(fit1, fit2); - o2domO1 = AbstractEAIndividual.isDominatingFitness(fit2, fit1); - } else { - if (fit1[fitCriterion] == fit2[fitCriterion]) { - return 0; - } - else { - return (fit1[fitCriterion] < fit2[fitCriterion]) ? -1 : 1; - } - } - if (o1domO2 ^ o2domO1) { - return (o1domO2 ? -1 : 1); - } - else { + public int compare(Object o1, Object o2) { + boolean o1domO2, o2domO1; + + double[] fit1 = (double[]) o1; + double[] fit2 = (double[]) o2; + if (fitCriterion < 0) { + o1domO2 = AbstractEAIndividual.isDominatingFitness(fit1, fit2); + o2domO1 = AbstractEAIndividual.isDominatingFitness(fit2, fit1); + } else { + if (fit1[fitCriterion] == fit2[fitCriterion]) { return 0; - } // these are not comparable - } + } else { + return (fit1[fitCriterion] < fit2[fitCriterion]) ? -1 : 1; + } + } + if (o1domO2 ^ o2domO1) { + return (o1domO2 ? -1 : 1); + } else { + return 0; + } // these are not comparable + } } diff --git a/src/eva2/optimization/tools/FileTools.java b/src/eva2/optimization/tools/FileTools.java index 4c417da3..565fa209 100644 --- a/src/eva2/optimization/tools/FileTools.java +++ b/src/eva2/optimization/tools/FileTools.java @@ -3,6 +3,7 @@ package eva2.optimization.tools; import eva2.gui.BeanInspector; import eva2.tools.BasicResourceLoader; import eva2.tools.StringTools; + import java.awt.Component; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -29,37 +30,39 @@ import javax.swing.JOptionPane; */ public class FileTools { - /** This method will load a file and will try to do this using the + /** + * This method will load a file and will try to do this using the * BasicResourceLoader and the standart technique. - * @param file The full filename and path + * + * @param file The full filename and path * @return A string[] containing the lines in the file */ static public String[] loadStringsFromFile(String file) { String[] result = null; - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte bytes[] = loader.getBytesFromResourceLocation(file, false); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte bytes[] = loader.getBytesFromResourceLocation(file, false); if (bytes != null) { - String data = new String(bytes); - result = data.split("\n"); + String data = new String(bytes); + result = data.split("\n"); } else { - System.err.println("BasicResourceLoader failed to read "+file); - BufferedReader reader= null; + System.err.println("BasicResourceLoader failed to read " + file); + BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); } catch (java.io.FileNotFoundException e) { System.err.println("Could not find " + file); return result; } - String currentLine; + String currentLine; try { ArrayList tmpA = new ArrayList(); - while((currentLine=reader.readLine()) != null && currentLine.length()!=0) { + while ((currentLine = reader.readLine()) != null && currentLine.length() != 0) { currentLine = currentLine.trim(); tmpA.add(currentLine); } result = new String[tmpA.size()]; for (int i = 0; i < tmpA.size(); i++) { - result[i] = (String)tmpA.get(i); + result[i] = (String) tmpA.get(i); } reader.close(); } catch (java.io.IOException e) { @@ -68,217 +71,217 @@ public class FileTools { } return result; } - - /** - * Write a given string to a file. Uses {@link #createNewFile(String)} to - * create a new file. - * - * @param filename target file name - * @param str String to write - * @return the File instance or null on a failure - */ - public static File writeString(String filename, String str) { - File f = null; - try { - f = createNewFile(filename); - PrintWriter Out = new PrintWriter(new FileOutputStream(f)); - Out.println(str); - Out.flush(); - Out.close(); - } catch (Exception e) { - System.err.println("Error:" + e.getMessage()); - return null; - } - return f; - } + /** + * Write a given string to a file. Uses {@link #createNewFile(String)} to + * create a new file. + * + * @param filename target file name + * @param str String to write + * @return the File instance or null on a failure + */ + public static File writeString(String filename, String str) { + File f = null; + try { + f = createNewFile(filename); + PrintWriter Out = new PrintWriter(new FileOutputStream(f)); + Out.println(str); + Out.flush(); + Out.close(); + } catch (Exception e) { + System.err.println("Error:" + e.getMessage()); + return null; + } + return f; + } - /** - * Try to create a new file. If the filename exists, numbers are appended (with dot) - * until a non-existing file name is found and the new file can be created. - * @param filename - * @return - */ - public static File createNewFile(String filename) { - File f=new File(filename); - try { - if (!f.createNewFile()) { - int i=1; - do { - f = new File(filename+"."+i); - } while (!f.createNewFile()); - return f; - } else { - return f; + /** + * Try to create a new file. If the filename exists, numbers are appended (with dot) + * until a non-existing file name is found and the new file can be created. + * + * @param filename + * @return + */ + public static File createNewFile(String filename) { + File f = new File(filename); + try { + if (!f.createNewFile()) { + int i = 1; + do { + f = new File(filename + "." + i); + } while (!f.createNewFile()); + return f; + } else { + return f; + } + } catch (IOException e) { + System.err.println("IOException when trying to create new file!"); + System.err.println(e.getMessage()); + return null; + } + } + + /** + * Saves the current object to a file selected by the user. Strings are written using + * a PrintWriter while other objects are written using an ObjectOutputStream. + * + * @param parentComponent the parent component + * @param fc a filechooser or null to create a new one + * @param object The object to save. + */ + public static boolean saveObjectWithFileChooser(Component parentComponent, Object object) { + int returnVal; + File sFile; + boolean finished = false; + do { + JFileChooser fc = createFileChooser(); + returnVal = fc.showSaveDialog(parentComponent); + if (returnVal == JFileChooser.APPROVE_OPTION) { + sFile = fc.getSelectedFile(); + if (sFile.exists()) { + int opt = JOptionPane.showConfirmDialog(parentComponent, "File " + sFile.getName() + " exists! Overwrite?", "Confirm to overwrite file", JOptionPane.YES_NO_CANCEL_OPTION); + if (opt == JOptionPane.OK_OPTION) { + finished = true; } - } catch(IOException e) { - System.err.println("IOException when trying to create new file!"); - System.err.println(e.getMessage()); - return null; - } - } - - /** - * Saves the current object to a file selected by the user. Strings are written using - * a PrintWriter while other objects are written using an ObjectOutputStream. - * - * @param parentComponent the parent component - * @param fc a filechooser or null to create a new one - * @param object The object to save. - */ - public static boolean saveObjectWithFileChooser(Component parentComponent, Object object) { - int returnVal; - File sFile; - boolean finished = false; - do { - JFileChooser fc = createFileChooser(); - returnVal = fc.showSaveDialog(parentComponent); - if (returnVal==JFileChooser.APPROVE_OPTION) { - sFile = fc.getSelectedFile(); - if (sFile.exists()) { - int opt = JOptionPane.showConfirmDialog(parentComponent, "File " + sFile.getName() + " exists! Overwrite?", "Confirm to overwrite file", JOptionPane.YES_NO_CANCEL_OPTION); - if (opt==JOptionPane.OK_OPTION) { - finished=true; - } - if (opt==JOptionPane.CANCEL_OPTION) { - return false; - } - } else { - finished=true; - } - } else { + if (opt == JOptionPane.CANCEL_OPTION) { return false; - } // user break - } while (!finished); // wait until user selected valid file + } + } else { + finished = true; + } + } else { + return false; + } // user break + } while (!finished); // wait until user selected valid file - if (returnVal==JFileChooser.APPROVE_OPTION) { - try { - if (object instanceof String) { - PrintWriter Out = new PrintWriter(new FileOutputStream(sFile)); - Out.println((String)object); - Out.flush(); - Out.close(); - } else { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); - oo.writeObject(object); - oo.close(); - } - return true; - } catch (Exception ex) { - JOptionPane.showMessageDialog(parentComponent, - "Couldn't write to file: " - + sFile.getName() - + "\n" + ex.getMessage(), - "Save object", - JOptionPane.ERROR_MESSAGE); - return false; - } - } else { + if (returnVal == JFileChooser.APPROVE_OPTION) { + try { + if (object instanceof String) { + PrintWriter Out = new PrintWriter(new FileOutputStream(sFile)); + Out.println((String) object); + Out.flush(); + Out.close(); + } else { + ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); + oo.writeObject(object); + oo.close(); + } + return true; + } catch (Exception ex) { + JOptionPane.showMessageDialog(parentComponent, + "Couldn't write to file: " + + sFile.getName() + + "\n" + ex.getMessage(), + "Save object", + JOptionPane.ERROR_MESSAGE); return false; } - } - - /** - * Opens an object from a file selected by the user. - * - * @return the loaded object, or null if the operation was cancelled - */ - public static Object openObject(Component parentComponent, Class clazz) { - Object obj=null; - JFileChooser fc = createFileChooser(); - int returnVal = fc.showOpenDialog(parentComponent); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File selected = fc.getSelectedFile(); - try { - ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); - obj = oi.readObject(); - oi.close(); - if (!clazz.isAssignableFrom(obj.getClass())) { - throw new Exception("Object not of type: " + clazz.getName()); - } - } catch (Exception ex) { - JOptionPane.showMessageDialog(parentComponent, - "Couldn't read object: " - + selected.getName() - + "\n" + ex.getMessage(), - "Open object file", - JOptionPane.ERROR_MESSAGE); - } - } - if (fc!=null) { - fc=null; + } else { + return false; + } + } + + /** + * Opens an object from a file selected by the user. + * + * @return the loaded object, or null if the operation was cancelled + */ + public static Object openObject(Component parentComponent, Class clazz) { + Object obj = null; + JFileChooser fc = createFileChooser(); + int returnVal = fc.showOpenDialog(parentComponent); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File selected = fc.getSelectedFile(); + try { + ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); + obj = oi.readObject(); + oi.close(); + if (!clazz.isAssignableFrom(obj.getClass())) { + throw new Exception("Object not of type: " + clazz.getName()); + } + } catch (Exception ex) { + JOptionPane.showMessageDialog(parentComponent, + "Couldn't read object: " + + selected.getName() + + "\n" + ex.getMessage(), + "Open object file", + JOptionPane.ERROR_MESSAGE); } - return obj; - } - - public static JFileChooser createFileChooser() { - JFileChooser fileChooser = new JFileChooser(new File("resources")); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - return fileChooser; - } - - public static boolean saveObjectToFolder(Object object, File folder, boolean forceOverwrite, Component parentComponent) { - String predefName = null; - try { - predefName = (String)BeanInspector.callIfAvailable(object, "getName", null); - predefName=StringTools.simplifySymbols(predefName)+".ser"; - } catch(Exception e){ - predefName=object.getClass().getName(); - predefName=StringTools.simplifySymbols(predefName)+".ser"; - } - - if (!folder.exists()) { - System.err.println("Error, folder " + folder + " does not exist, aborting saveObjectToFolder."); - return false; - } else { - File outFile = new File(folder,predefName); - if (outFile.exists() && !forceOverwrite) { - int opt = JOptionPane.showConfirmDialog(parentComponent, "File " + outFile.getName() + " exists! Overwrite?", "Confirm to overwrite file", JOptionPane.YES_NO_CANCEL_OPTION); - if (opt!=JOptionPane.OK_OPTION) { - return false; - } - } - // we may save the file - String msg; - if ((msg = saveObject(object, outFile))!=null) { - JOptionPane.showMessageDialog(parentComponent, - "Couldn't save object: " - + object - + "\n" + msg, - "Save object to folder", - JOptionPane.ERROR_MESSAGE); - return false; - } else { - return true; - } - } - } - - /** - * Store the given object directly without any testing. Returns null on success, - * otherwise the error message of an exception that occurred. - * - * @param object - * @param target - * @return - */ - public static String saveObject(Object object, File target) { - try { - if (object instanceof String) { - PrintWriter Out = new PrintWriter(new FileOutputStream(target)); - Out.println((String)object); - Out.flush(); - Out.close(); - } else { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(target))); - oo.writeObject(object); - oo.close(); - } - return null; - } catch (Exception ex) { - System.err.println("Unable to write to file " + target.getAbsolutePath()); - return ex.getMessage(); - } - } + } + if (fc != null) { + fc = null; + } + return obj; + } + + public static JFileChooser createFileChooser() { + JFileChooser fileChooser = new JFileChooser(new File("resources")); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + return fileChooser; + } + + public static boolean saveObjectToFolder(Object object, File folder, boolean forceOverwrite, Component parentComponent) { + String predefName = null; + try { + predefName = (String) BeanInspector.callIfAvailable(object, "getName", null); + predefName = StringTools.simplifySymbols(predefName) + ".ser"; + } catch (Exception e) { + predefName = object.getClass().getName(); + predefName = StringTools.simplifySymbols(predefName) + ".ser"; + } + + if (!folder.exists()) { + System.err.println("Error, folder " + folder + " does not exist, aborting saveObjectToFolder."); + return false; + } else { + File outFile = new File(folder, predefName); + if (outFile.exists() && !forceOverwrite) { + int opt = JOptionPane.showConfirmDialog(parentComponent, "File " + outFile.getName() + " exists! Overwrite?", "Confirm to overwrite file", JOptionPane.YES_NO_CANCEL_OPTION); + if (opt != JOptionPane.OK_OPTION) { + return false; + } + } + // we may save the file + String msg; + if ((msg = saveObject(object, outFile)) != null) { + JOptionPane.showMessageDialog(parentComponent, + "Couldn't save object: " + + object + + "\n" + msg, + "Save object to folder", + JOptionPane.ERROR_MESSAGE); + return false; + } else { + return true; + } + } + } + + /** + * Store the given object directly without any testing. Returns null on success, + * otherwise the error message of an exception that occurred. + * + * @param object + * @param target + * @return + */ + public static String saveObject(Object object, File target) { + try { + if (object instanceof String) { + PrintWriter Out = new PrintWriter(new FileOutputStream(target)); + Out.println((String) object); + Out.flush(); + Out.close(); + } else { + ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(target))); + oo.writeObject(object); + oo.close(); + } + return null; + } catch (Exception ex) { + System.err.println("Unable to write to file " + target.getAbsolutePath()); + return ex.getMessage(); + } + } } diff --git a/src/eva2/optimization/tools/GONamingBox.java b/src/eva2/optimization/tools/GONamingBox.java index 4bb95077..88890deb 100644 --- a/src/eva2/optimization/tools/GONamingBox.java +++ b/src/eva2/optimization/tools/GONamingBox.java @@ -12,69 +12,69 @@ import eva2.tools.math.RNG; public class GONamingBox { static String[] m_Names = {"Aleksei", - "Aleksandr", - "Andrei", - "Shurik", - "Andryusha", - "Tolyar", - "Anton", - "Arkadiy", - "Artur", - "Averiy", - "Borya", - "Boris", - "Dmitriy", - "Edik", - "Filipp", - "Fyodor", - "Gennadiy", - "Georgiy", - "Grigoriy", - "Igor", - "Il'ya", - "Innokentiy", - "Kirill", - "Ivan", - "Kirill", - "Konstantin", - "Leonid", - "Lev", - "Maksim", - "Mark", - "Mihail", - "Nikolai", - "Kolya", - "Oleg", - "Pavel", - "Pasha", - "Pyotr", - "Rodion", - "Rodya", - "Roman", - "Ruslan", - "Rustam", - "Semyon", - "Sergei", - "Stanislav", - "Stepan", - "Svyatoslav", - "Timofei", - "Vadim", - "Seryoga", - "Valentin", - "Valeriy", - "Vasiliy", - "Viktor", - "Vitaliy", - "Vladimir", - "Vladislav", - "Vyacheslav", - "Yaroslav", - "Yegor", - "Yevgeniy", - "Yuriy"}; + "Aleksandr", + "Andrei", + "Shurik", + "Andryusha", + "Tolyar", + "Anton", + "Arkadiy", + "Artur", + "Averiy", + "Borya", + "Boris", + "Dmitriy", + "Edik", + "Filipp", + "Fyodor", + "Gennadiy", + "Georgiy", + "Grigoriy", + "Igor", + "Il'ya", + "Innokentiy", + "Kirill", + "Ivan", + "Kirill", + "Konstantin", + "Leonid", + "Lev", + "Maksim", + "Mark", + "Mihail", + "Nikolai", + "Kolya", + "Oleg", + "Pavel", + "Pasha", + "Pyotr", + "Rodion", + "Rodya", + "Roman", + "Ruslan", + "Rustam", + "Semyon", + "Sergei", + "Stanislav", + "Stepan", + "Svyatoslav", + "Timofei", + "Vadim", + "Seryoga", + "Valentin", + "Valeriy", + "Vasiliy", + "Viktor", + "Vitaliy", + "Vladimir", + "Vladislav", + "Vyacheslav", + "Yaroslav", + "Yegor", + "Yevgeniy", + "Yuriy"}; public static String getRandomName() { - return new String(m_Names[RNG.randomInt(0, m_Names.length-1)]); + return new String(m_Names[RNG.randomInt(0, m_Names.length - 1)]); } } diff --git a/src/eva2/optimization/tools/GeneralGEOFaker.java b/src/eva2/optimization/tools/GeneralGEOFaker.java index 8c9c14b7..35626bbb 100644 --- a/src/eva2/optimization/tools/GeneralGEOFaker.java +++ b/src/eva2/optimization/tools/GeneralGEOFaker.java @@ -16,19 +16,19 @@ import javax.swing.*; */ public class GeneralGEOFaker extends JPanel { - private JButton open, save, ok, edit; + private JButton open, save, ok, edit; private JFileChooser m_FileChooser; -// private Vector m_ClassesLongName; + // private Vector m_ClassesLongName; // private SourceCodeEditor m_SourceCodeEditor; // private PropertyDialog m_SourceCodeEditorFrame; - private PropertyEditor m_Editor; - private JPanel m_Interior; - private Class m_ClassType; + private PropertyEditor m_Editor; + private JPanel m_Interior; + private Class m_ClassType; public GeneralGEOFaker(PropertyEditor e, JPanel i) { - this.m_Interior = i; - this.m_Editor = e; - this.m_ClassType = this.m_Editor.getValue().getClass(); + this.m_Interior = i; + this.m_Editor = e; + this.m_ClassType = this.m_Editor.getValue().getClass(); init(); } @@ -92,12 +92,13 @@ public class GeneralGEOFaker extends JPanel { ok.setEnabled(true); ok.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { - if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { - Window w = (Window) getTopLevelAncestor(); - w.dispose(); - } - }}); + public void actionPerformed(ActionEvent e) { + if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { + Window w = (Window) getTopLevelAncestor(); + w.dispose(); + } + } + }); setLayout(new BorderLayout()); add(this.m_Interior, BorderLayout.CENTER); JPanel okcButs = new JPanel(); @@ -110,7 +111,9 @@ public class GeneralGEOFaker extends JPanel { add(okcButs, BorderLayout.SOUTH); } - /** Opens an object from a file selected by the user. + /** + * Opens an object from a file selected by the user. + * * @return the loaded object, or null if the operation was cancelled */ protected Object openObject() { @@ -119,24 +122,26 @@ public class GeneralGEOFaker extends JPanel { } int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { - File selected = m_FileChooser.getSelectedFile(); - try { - ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); - Object obj = oi.readObject(); + File selected = m_FileChooser.getSelectedFile(); + try { + ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); + Object obj = oi.readObject(); oi.close(); if (!m_ClassType.isAssignableFrom(obj.getClass())) { throw new Exception("Object not of type: " + m_ClassType.getName()); } return obj; - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(), "Open object file", JOptionPane.ERROR_MESSAGE); - } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(), "Open object file", JOptionPane.ERROR_MESSAGE); + } } return null; } - /** Saves the current object to a file selected by the user. - * @param object The object to save. + /** + * Saves the current object to a file selected by the user. + * + * @param object The object to save. */ protected void saveObject(Object object) { if (m_FileChooser == null) { @@ -144,16 +149,17 @@ public class GeneralGEOFaker extends JPanel { } int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { - File sFile = m_FileChooser.getSelectedFile(); - try { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); + File sFile = m_FileChooser.getSelectedFile(); + try { + ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); oo.writeObject(object); oo.close(); - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(), "Save object", JOptionPane.ERROR_MESSAGE); - } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(), "Save object", JOptionPane.ERROR_MESSAGE); + } } } + protected void createFileChooser() { m_FileChooser = new JFileChooser(new File("/resources")); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); diff --git a/src/eva2/optimization/tools/GeneralGOEProperty.java b/src/eva2/optimization/tools/GeneralGOEProperty.java index 716e3afa..6cc83c56 100644 --- a/src/eva2/optimization/tools/GeneralGOEProperty.java +++ b/src/eva2/optimization/tools/GeneralGOEProperty.java @@ -12,16 +12,16 @@ import javax.swing.*; * To change this template use File | Settings | File Templates. */ public class GeneralGOEProperty { - public Method m_getMethod; - public Method m_setMethod; - public PropertyEditor m_Editor; - public Object m_Value; - public JComponent m_View; - public JComponent m_ViewWrapper; - public JLabel m_Label; - public Class m_PropertyType; - public String m_Name; - public String m_TipText; + public Method m_getMethod; + public Method m_setMethod; + public PropertyEditor m_Editor; + public Object m_Value; + public JComponent m_View; + public JComponent m_ViewWrapper; + public JLabel m_Label; + public Class m_PropertyType; + public String m_Name; + public String m_TipText; public GeneralGOEProperty() { } diff --git a/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java b/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java index e439f200..936706f5 100644 --- a/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java +++ b/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java @@ -3,6 +3,7 @@ package eva2.optimization.tools; import eva2.gui.editor.GenericObjectEditor; import eva2.tools.EVAHELP; + import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -24,52 +25,72 @@ import javax.swing.*; public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListener { // This is the Object Editor i belong too - private AbstractObjectEditor m_ObjectEditor; - /** The chooser component */ - private JComboBox m_ObjectChooser; - /** The component that performs classifier customization */ + private AbstractObjectEditor m_ObjectEditor; + /** + * The chooser component + */ + private JComboBox m_ObjectChooser; + /** + * The component that performs classifier customization + */ //private PropertySheetPanel m_ChildPropertySheet; - private JPanel m_PPWrapper; - private JPanel m_PropertyPanel; - /** The model containing the list of names to select from */ - private DefaultComboBoxModel m_ObjectNames; - /** Open object from disk */ - private JButton m_OpenBut; - /** Save object to disk */ - private JButton m_SaveBut; - /** ok button */ - public JButton m_okBut; - /** cancel button */ - private JButton m_cancelBut; - /** The filechooser for opening and saving object files */ - private JFileChooser m_FileChooser; - /** Creates the GUI editor component */ - private ArrayList m_ClassesLongName; + private JPanel m_PPWrapper; + private JPanel m_PropertyPanel; + /** + * The model containing the list of names to select from + */ + private DefaultComboBoxModel m_ObjectNames; + /** + * Open object from disk + */ + private JButton m_OpenBut; + /** + * Save object to disk + */ + private JButton m_SaveBut; + /** + * ok button + */ + public JButton m_okBut; + /** + * cancel button + */ + private JButton m_cancelBut; + /** + * The filechooser for opening and saving object files + */ + private JFileChooser m_FileChooser; + /** + * Creates the GUI editor component + */ + private ArrayList m_ClassesLongName; - /** This is the general construtor method - * @param oe A link to the oe; + /** + * This is the general construtor method + * + * @param oe A link to the oe; */ public GeneralGenericObjectEditorPanel(AbstractObjectEditor oe) { - this.m_ObjectEditor = oe; + this.m_ObjectEditor = oe; oe.makeBackup(); - m_ObjectNames = new DefaultComboBoxModel(new String [0]); - m_ObjectChooser = new JComboBox(m_ObjectNames); + m_ObjectNames = new DefaultComboBoxModel(new String[0]); + m_ObjectChooser = new JComboBox(m_ObjectNames); m_ObjectChooser.setEditable(false); - m_PPWrapper = new JPanel(); - m_PropertyPanel = this.m_ObjectEditor.getPropertyPanel(); + m_PPWrapper = new JPanel(); + m_PropertyPanel = this.m_ObjectEditor.getPropertyPanel(); m_PropertyPanel.addPropertyChangeListener(new PropertyChangeListener() { @Override - public void propertyChange(PropertyChangeEvent evt) { - m_ObjectEditor.firePropertyChange("", null, m_ObjectEditor.getValue()); - } + public void propertyChange(PropertyChangeEvent evt) { + m_ObjectEditor.firePropertyChange("", null, m_ObjectEditor.getValue()); + } }); - m_OpenBut = new JButton("Open..."); + m_OpenBut = new JButton("Open..."); m_OpenBut.setToolTipText("Load a configured object"); m_OpenBut.setEnabled(true); m_OpenBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Object object = openObject(); + Object object = openObject(); if (object != null) { // setValue takes care of: Making sure obj is of right type, // and firing property change. @@ -78,17 +99,17 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe // Not sure why. m_ObjectEditor.setValue(object); // <- Hannes ?!?!? } - } + } }); - m_SaveBut = new JButton("Save..."); + m_SaveBut = new JButton("Save..."); m_SaveBut.setToolTipText("Save the current configured object"); m_SaveBut.setEnabled(true); m_SaveBut.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { - saveObject(m_ObjectEditor.getValue()); - } + public void actionPerformed(ActionEvent e) { + saveObject(m_ObjectEditor.getValue()); + } }); // m_editSourceBut = new JButton("Edit Source"); @@ -116,39 +137,39 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe // } // }); - m_okBut = new JButton("OK"); + m_okBut = new JButton("OK"); m_okBut.setEnabled(true); m_okBut.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { - m_ObjectEditor.makeBackup(); - if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { - Window w = (Window) getTopLevelAncestor(); - w.dispose(); - } - } + public void actionPerformed(ActionEvent e) { + m_ObjectEditor.makeBackup(); + if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { + Window w = (Window) getTopLevelAncestor(); + w.dispose(); + } + } }); - m_cancelBut = new JButton("Cancel"); + m_cancelBut = new JButton("Cancel"); m_cancelBut.setEnabled(false); m_cancelBut.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent e) { + public void actionPerformed(ActionEvent e) { m_ObjectEditor.undoBackup(); - updateClassType(); - updateChooser(); - updateChildPropertySheet(); - if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { - Window w = (Window) getTopLevelAncestor(); - w.dispose(); - } - } + updateClassType(); + updateChooser(); + updateChildPropertySheet(); + if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { + Window w = (Window) getTopLevelAncestor(); + w.dispose(); + } + } }); setLayout(new BorderLayout()); add(m_ObjectChooser, BorderLayout.NORTH); // important m_PPWrapper.add(m_PropertyPanel); - add((JComponent)m_PPWrapper, BorderLayout.CENTER); + add((JComponent) m_PPWrapper, BorderLayout.CENTER); // Since we resize to the size of the property sheet, a scrollpane isn't // typically needed // add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER); @@ -163,14 +184,16 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe add(okcButs, BorderLayout.SOUTH); if (this.m_ObjectEditor.getClassType() != null) { - updateClassType(); - updateChooser(); - updateChildPropertySheet(); + updateClassType(); + updateChooser(); + updateChildPropertySheet(); } m_ObjectChooser.addItemListener(this); } - /** Opens an object from a file selected by the user. + /** + * Opens an object from a file selected by the user. + * * @return the loaded object, or null if the operation was cancelled */ protected Object openObject() { @@ -180,28 +203,30 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { - File selected = m_FileChooser.getSelectedFile(); - try { - ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); - Object obj = oi.readObject(); + File selected = m_FileChooser.getSelectedFile(); + try { + ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); + Object obj = oi.readObject(); oi.close(); if (!this.m_ObjectEditor.getClassType().isAssignableFrom(obj.getClass())) { throw new Exception("Object not of type: " + this.m_ObjectEditor.getClassType().getName()); } return obj; - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, - "Couldn't read object: " - + selected.getName() - + "\n" + ex.getMessage(), - "Open object file", - JOptionPane.ERROR_MESSAGE); - } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Couldn't read object: " + + selected.getName() + + "\n" + ex.getMessage(), + "Open object file", + JOptionPane.ERROR_MESSAGE); + } } return null; } - /**Opens an object from a file selected by the user. + /** + * Opens an object from a file selected by the user. + * * @param object the object to save. */ protected void saveObject(Object object) { @@ -210,77 +235,87 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe } int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { - File sFile = m_FileChooser.getSelectedFile(); - try { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); + File sFile = m_FileChooser.getSelectedFile(); + try { + ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); oo.writeObject(object); oo.close(); - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, - "Couldn't write to file: " - + sFile.getName() - + "\n" + ex.getMessage(), - "Save object", - JOptionPane.ERROR_MESSAGE); - } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, + "Couldn't write to file: " + + sFile.getName() + + "\n" + ex.getMessage(), + "Save object", + JOptionPane.ERROR_MESSAGE); + } } } - /** This method creates a file chooser + /** + * This method creates a file chooser */ protected void createFileChooser() { m_FileChooser = new JFileChooser(new File("/resources")); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); } - /**This is used to hook an action listener to the ok button + /** + * This is used to hook an action listener to the ok button + * * @param a The action listener. */ public void addOkListener(ActionListener a) { m_okBut.addActionListener(a); } - /**This is used to hook an action listener to the cancel button + /** + * This is used to hook an action listener to the cancel button + * * @param a The action listener. */ public void addCancelListener(ActionListener a) { m_cancelBut.addActionListener(a); } - /** This is used to remove an action listener from the ok button + /** + * This is used to remove an action listener from the ok button + * * @param a The action listener */ public void removeOkListener(ActionListener a) { m_okBut.removeActionListener(a); } - /** This is used to remove an action listener from the cancel button + /** + * This is used to remove an action listener from the cancel button + * * @param a The action listener */ public void removeCancelListener(ActionListener a) { m_cancelBut.removeActionListener(a); } - /** This method updates the class type* + + /** + * This method updates the class type* */ protected void updateClassType() { m_ClassesLongName = GenericObjectEditor.getClassesFromProperties(m_ObjectEditor.getClassType().getName(), null); m_ObjectChooser.setModel(new DefaultComboBoxModel(m_ClassesLongName.toArray())); if (m_ClassesLongName.size() > 1) { add(m_ObjectChooser, BorderLayout.NORTH); - } - else { + } else { remove(m_ObjectChooser); } } protected void updateChooser() { - String objectName = /*EVAHELP.cutClassName*/ (this.m_ObjectEditor.getValue().getClass().getName()); - boolean found = false; + String objectName = /*EVAHELP.cutClassName*/ (this.m_ObjectEditor.getValue().getClass().getName()); + boolean found = false; for (int i = 0; i < m_ObjectNames.getSize(); i++) { - if (objectName.equals((String)m_ObjectNames.getElementAt(i))) { - found = true; - break; - } + if (objectName.equals((String) m_ObjectNames.getElementAt(i))) { + found = true; + break; + } } if (!found) { m_ObjectNames.addElement(objectName); @@ -288,7 +323,8 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe m_ObjectChooser.getModel().setSelectedItem(objectName); } - /** Updates the child property sheet, and creates if needed.. + /** + * Updates the child property sheet, and creates if needed.. * *what!?* */ public void updateChildPropertySheet() { @@ -305,34 +341,36 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe this.m_PPWrapper.add(this.m_ObjectEditor.getPropertyPanel()); // m_ChildPropertySheet.setTarget(this.m_ObjectEditor.getValue()); // Adjust size of containing window if possible - if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { - ((Window) getTopLevelAncestor()).pack(); + if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { + ((Window) getTopLevelAncestor()).pack(); } } - /** When the chooser selection is changed, ensures that the Object + /** + * When the chooser selection is changed, ensures that the Object * is changed appropriately. + * * @param e a value of type 'ItemEvent' */ @Override public void itemStateChanged(ItemEvent e) { - String className = (String)m_ObjectChooser.getSelectedItem(); + String className = (String) m_ObjectChooser.getSelectedItem(); //System.out.println("Event-Quelle: " + e.getSource().toString()); if ((e.getSource() == m_ObjectChooser) && (e.getStateChange() == ItemEvent.SELECTED)) { - className = (String)m_ObjectChooser.getSelectedItem(); + className = (String) m_ObjectChooser.getSelectedItem(); try { System.out.println(className); - Object n = (Object)Class.forName(className).newInstance(); + Object n = (Object) Class.forName(className).newInstance(); this.m_ObjectEditor.setValue(n); } catch (Exception ex) { - System.out.println("Exeption in itemStateChanged"+ex.getMessage()); + System.out.println("Exeption in itemStateChanged" + ex.getMessage()); m_ObjectChooser.hidePopup(); m_ObjectChooser.setSelectedIndex(0); JOptionPane.showMessageDialog(this, "Could not create an example of\n" - + className + "\n" - + "from the current classpath", + + className + "\n" + + "from the current classpath", "GenericObjectEditor", JOptionPane.ERROR_MESSAGE); EVAHELP.getSystemPropertyString(); diff --git a/src/eva2/optimization/tools/ImpactOfDimensionOnMOEAs.java b/src/eva2/optimization/tools/ImpactOfDimensionOnMOEAs.java index 9e13a784..bbe517af 100644 --- a/src/eva2/optimization/tools/ImpactOfDimensionOnMOEAs.java +++ b/src/eva2/optimization/tools/ImpactOfDimensionOnMOEAs.java @@ -9,6 +9,7 @@ import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.operator.archiving.ArchivingAllDominating; import eva2.optimization.population.Population; import eva2.tools.chart2d.DPoint; + import java.io.*; /** @@ -22,40 +23,40 @@ public class ImpactOfDimensionOnMOEAs { public static void main(String[] args) { ImpactOfDimensionOnMOEAs ikel = new ImpactOfDimensionOnMOEAs(); - int maxDim = 21; - int multiRuns = 25; - int popSize = 100; - int numberofVariables = 30; - double mean; - double[][] log; - log = new double[maxDim][5]; - Plot mPlot; + int maxDim = 21; + int multiRuns = 25; + int popSize = 100; + int numberofVariables = 30; + double mean; + double[][] log; + log = new double[maxDim][5]; + Plot mPlot; GraphPointSet mySet; - DPoint myPoint; - Population pop; + DPoint myPoint; + Population pop; double[] tmpD = new double[2]; tmpD[0] = 1; tmpD[1] = 1; mPlot = new Plot("ImpactOfDimensionOnMOEAs", "ProblemDimensin", "No. of Pareto-opt solutions", true); for (int l = 0; l < 5; l++) { - popSize = 100 + (l*100); + popSize = 100 + (l * 100); mySet = new GraphPointSet(l, mPlot.getFunctionArea()); mySet.setConnectedMode(true); myPoint = new DPoint(0, 0); mySet.addDPoint(myPoint); - myPoint = new DPoint(1, 1/(double)popSize); + myPoint = new DPoint(1, 1 / (double) popSize); mySet.addDPoint(myPoint); log[0][l] = 0; - log[1][l] = 1/(double)popSize; + log[1][l] = 1 / (double) popSize; for (int i = 2; i < maxDim; i++) { mean = 0; for (int j = 0; j < multiRuns; j++) { pop = new Population(); ikel.initPopulation(pop, popSize, numberofVariables); ikel.evaluatePopulation(pop, i); - mean += ikel.numberOfParetoOptimalSolutions(pop)/(double)pop.size(); + mean += ikel.numberOfParetoOptimalSolutions(pop) / (double) pop.size(); } - mean /= (double)multiRuns; + mean /= (double) multiRuns; myPoint = new DPoint(i, mean); log[i][l] = mean; mySet.addDPoint(myPoint); @@ -68,7 +69,7 @@ public class ImpactOfDimensionOnMOEAs { String tmpS; BufferedWriter m_OutputFile = null; try { - m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("Impact_Of_Dimension_On_MOEAs.dat"))); + m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Impact_Of_Dimension_On_MOEAs.dat"))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: Impact_Of_Dimension_On_MOEAs.dat"); } @@ -76,10 +77,10 @@ public class ImpactOfDimensionOnMOEAs { tmpS = "Dim;P100;P200;P300;P400;P500\n"; m_OutputFile.write(tmpS); for (int i = 0; i < log.length; i++) { - tmpS = ""+i+";"; + tmpS = "" + i + ";"; for (int j = 0; j < log[i].length; j++) { tmpS += log[i][j]; - if (j < log[i].length-1) { + if (j < log[i].length - 1) { tmpS += ";"; } } @@ -100,20 +101,20 @@ public class ImpactOfDimensionOnMOEAs { AbstractEAIndividual tmpIndy, template; pop.clear(); template = new ESIndividualDoubleData(); - ((InterfaceDataTypeDouble)template).setDoubleDataLength(numberOfVariables); + ((InterfaceDataTypeDouble) template).setDoubleDataLength(numberOfVariables); for (int i = 0; i < popSize; i++) { - tmpIndy = (AbstractEAIndividual)template.clone(); + tmpIndy = (AbstractEAIndividual) template.clone(); tmpIndy.init(null); pop.add(tmpIndy); } } public void evaluatePopulation(Population pop, int objectives) { - double[] fitness; - double[] x; + double[] fitness; + double[] x; for (int i = 0; i < pop.size(); i++) { - x = ((InterfaceDataTypeDouble)pop.get(i)).getDoubleData(); + x = ((InterfaceDataTypeDouble) pop.get(i)).getDoubleData(); fitness = new double[objectives]; for (int j = 0; j < objectives; j++) { fitness[j] = 1; @@ -123,13 +124,12 @@ public class ImpactOfDimensionOnMOEAs { } } if (j < x.length) { - fitness[j] =1/((double)fitness[j]) + x[j]; - } - else { - fitness[j] =1/((double)fitness[j]) + x[j%objectives] + x[(j+1)%objectives]; + fitness[j] = 1 / ((double) fitness[j]) + x[j]; + } else { + fitness[j] = 1 / ((double) fitness[j]) + x[j % objectives] + x[(j + 1) % objectives]; } } - ((AbstractEAIndividual)pop.get(i)).setFitness(fitness); + ((AbstractEAIndividual) pop.get(i)).setFitness(fitness); } } diff --git a/src/eva2/optimization/tools/ParetoFrontLocalTester.java b/src/eva2/optimization/tools/ParetoFrontLocalTester.java index cfbc1a57..55b0b9b3 100644 --- a/src/eva2/optimization/tools/ParetoFrontLocalTester.java +++ b/src/eva2/optimization/tools/ParetoFrontLocalTester.java @@ -17,8 +17,8 @@ import java.util.ArrayList; public class ParetoFrontLocalTester { private Plot m_Plot; - private int index = 0; - private BufferedWriter m_OutputFile = null; + private int index = 0; + private BufferedWriter m_OutputFile = null; private void show() { double[] loss = new double[5]; @@ -50,7 +50,7 @@ public class ParetoFrontLocalTester { risk[3][4] = 0.00; for (int i = 0; i < risk.length; i++) { - for (int j = i+1; j < risk.length; j++) { + for (int j = i + 1; j < risk.length; j++) { risk[j][i] = risk[i][j]; } } @@ -60,20 +60,20 @@ public class ParetoFrontLocalTester { // now calc the stuff ArrayList complete = new ArrayList(); ArrayList elements = new ArrayList(); - double[] tmpD; - double[][] tmpElem; - int res = 100; + double[] tmpD; + double[][] tmpElem; + int res = 100; for (int i = 0; i < loss.length; i++) { - tmpElem = new double[res+1][2]; - for (int j = i+1; j < loss.length; j++) { + tmpElem = new double[res + 1][2]; + for (int j = i + 1; j < loss.length; j++) { double w = 0; - for (int k = 0; k < res+1; k++) { - tmpElem[k][0] = w*loss[i] + (1-w)*loss[j]; - tmpElem[k][1] = (w*w)*risk[i][i] + ((1-w)*(1-w))*risk[j][j] + 2*(w*(1-w)*risk[i][j]); + for (int k = 0; k < res + 1; k++) { + tmpElem[k][0] = w * loss[i] + (1 - w) * loss[j]; + tmpElem[k][1] = (w * w) * risk[i][i] + ((1 - w) * (1 - w)) * risk[j][j] + 2 * (w * (1 - w) * risk[i][j]); tmpD = new double[2]; tmpD[0] = tmpElem[k][0]; tmpD[1] = tmpElem[k][1]; - w += 1/(double)res; + w += 1 / (double) res; complete.add(tmpD); } // now plot this line @@ -86,7 +86,7 @@ public class ParetoFrontLocalTester { private void saveThisStuff(ArrayList c, ArrayList e) { try { - this.m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("CompleteList"))); + this.m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("CompleteList"))); } catch (FileNotFoundException ex) { System.out.println("Could not open output file!"); } @@ -96,7 +96,7 @@ public class ParetoFrontLocalTester { this.writeToFile(line); for (int i = 0; i < c.size(); i++) { tmpD = (double[]) c.get(i); - line = tmpD[1] +"\t" + tmpD[0]; + line = tmpD[1] + "\t" + tmpD[0]; this.writeToFile(line); } try { @@ -105,18 +105,18 @@ public class ParetoFrontLocalTester { } // next file try { - this.m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("ListElements"))); + this.m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ListElements"))); } catch (FileNotFoundException ex) { System.out.println("Could not open output file!"); } int length = e.size(); double[][][] cara = new double[length][][]; for (int i = 0; i < e.size(); i++) { - cara[i] = (double[][])e.get(i); + cara[i] = (double[][]) e.get(i); } line = ""; for (int i = 0; i < cara.length; i++) { - line = "Risk"+i+"\t"+"Loss"+i; + line = "Risk" + i + "\t" + "Loss" + i; } this.writeToFile(line); for (int i = 0; i < cara[0].length; i++) { @@ -132,8 +132,10 @@ public class ParetoFrontLocalTester { } } - /** This method writes Data to file. - * @param line The line that is to be added to the file + /** + * This method writes Data to file. + * + * @param line The line that is to be added to the file */ private void writeToFile(String line) { String write = line + "\n"; @@ -157,7 +159,7 @@ public class ParetoFrontLocalTester { } private void showLine(double[][] elm) { - GraphPointSet mySet = new GraphPointSet(this.index, this.m_Plot.getFunctionArea()); + GraphPointSet mySet = new GraphPointSet(this.index, this.m_Plot.getFunctionArea()); this.index++; for (int i = 0; i < elm.length; i++) { mySet.addDPoint(elm[i][1], elm[i][0]); diff --git a/src/eva2/optimization/tools/PortfolioFrontTester.java b/src/eva2/optimization/tools/PortfolioFrontTester.java index 28fbb156..b62c98f4 100644 --- a/src/eva2/optimization/tools/PortfolioFrontTester.java +++ b/src/eva2/optimization/tools/PortfolioFrontTester.java @@ -17,10 +17,10 @@ import java.util.ArrayList; public class PortfolioFrontTester { private Plot m_Plot; - private int index = 0; - private BufferedWriter m_OutputFile = null; - private double[] loss; - private double[][] risk; + private int index = 0; + private BufferedWriter m_OutputFile = null; + private double[] loss; + private double[][] risk; private void show() { loss = new double[5]; @@ -52,7 +52,7 @@ public class PortfolioFrontTester { risk[3][4] = 0.00; for (int i = 0; i < risk.length; i++) { - for (int j = i+1; j < risk.length; j++) { + for (int j = i + 1; j < risk.length; j++) { risk[j][i] = risk[i][j]; } } @@ -66,20 +66,20 @@ public class PortfolioFrontTester { // now calc the stuff ArrayList complete = new ArrayList(); ArrayList elements = new ArrayList(); - double[] tmpD; - double[][] tmpElem; - int res = 25; + double[] tmpD; + double[][] tmpElem; + int res = 25; for (int i = 0; i < loss.length; i++) { - for (int j = i+1; j < loss.length; j++) { - tmpElem = new double[res+1][2]; + for (int j = i + 1; j < loss.length; j++) { + tmpElem = new double[res + 1][2]; double w = 0; - for (int k = 0; k < res+1; k++) { - tmpElem[k][0] = w*loss[i] + (1-w)*loss[j]; - tmpElem[k][1] = (w*w)*risk[i][i] + ((1-w)*(1-w))*risk[j][j] + 2*(w*(1-w)*risk[i][j]); + for (int k = 0; k < res + 1; k++) { + tmpElem[k][0] = w * loss[i] + (1 - w) * loss[j]; + tmpElem[k][1] = (w * w) * risk[i][i] + ((1 - w) * (1 - w)) * risk[j][j] + 2 * (w * (1 - w) * risk[i][j]); tmpD = new double[2]; tmpD[0] = tmpElem[k][0]; tmpD[1] = tmpElem[k][1]; - w += 1/(double)res; + w += 1 / (double) res; complete.add(tmpD); } // now plot this line @@ -94,17 +94,17 @@ public class PortfolioFrontTester { // now calc the stuff ArrayList complete = new ArrayList(); ArrayList elements = new ArrayList(); - double[] tmpD; - double[][] tmpElem; - int res = 100; + double[] tmpD; + double[][] tmpElem; + int res = 100; for (int i = 0; i < loss.length; i++) { - for (int j = i+1; j < loss.length; j++) { - tmpElem = new double[res+1][2]; + for (int j = i + 1; j < loss.length; j++) { + tmpElem = new double[res + 1][2]; double w = 0; - for (int k = 0; k < res+1; k++) { - if (! ((w > limit) &&((1-w)> limit))) { - tmpElem[k][0] = w*loss[i] + (1-w)*loss[j]; - tmpElem[k][1] = (w*w)*risk[i][i] + ((1-w)*(1-w))*risk[j][j] + 2*(w*(1-w)*risk[i][j]); + for (int k = 0; k < res + 1; k++) { + if (!((w > limit) && ((1 - w) > limit))) { + tmpElem[k][0] = w * loss[i] + (1 - w) * loss[j]; + tmpElem[k][1] = (w * w) * risk[i][i] + ((1 - w) * (1 - w)) * risk[j][j] + 2 * (w * (1 - w) * risk[i][j]); tmpD = new double[2]; tmpD[0] = tmpElem[k][0]; tmpD[1] = tmpElem[k][1]; @@ -113,7 +113,7 @@ public class PortfolioFrontTester { tmpElem[k][0] = loss[i]; tmpElem[k][1] = risk[i][i]; } - w += 1/(double)res; + w += 1 / (double) res; } // now plot this line this.showLine(tmpElem); @@ -127,19 +127,19 @@ public class PortfolioFrontTester { // now calc the stuff ArrayList complete = new ArrayList(); ArrayList elements = new ArrayList(); - double[] tmpD; + double[] tmpD; ArrayList tmpElem; - int res = 20; + int res = 20; for (int i = 0; i < loss.length; i++) { - for (int j = i+1; j < loss.length; j++) { - for (int k = j+1; k < loss.length; k++) { + for (int j = i + 1; j < loss.length; j++) { + for (int k = j + 1; k < loss.length; k++) { tmpElem = new ArrayList(); - for (double t1 = 0; t1 < 1.0; t1 += 1/(double)res) { - for (double t2 = 0; t2 < (1.0 - t1); t2 += 1/(double)res) { + for (double t1 = 0; t1 < 1.0; t1 += 1 / (double) res) { + for (double t2 = 0; t2 < (1.0 - t1); t2 += 1 / (double) res) { tmpD = new double[2]; - tmpD[0] = t1*loss[i] + t2*loss[j] + (1-t1-t2)*loss[k]; - tmpD[1] = (t1*t1)*risk[i][i] + t2*t2*risk[j][j] + (1-t1-t2)*(1-t1-t2)*risk[k][k] - + 2*(t1*t2*risk[i][j]) + 2*((1-t1-t2)*t2*risk[k][j])+ 2*(t1*(1-t1-t2)*risk[i][k]); + tmpD[0] = t1 * loss[i] + t2 * loss[j] + (1 - t1 - t2) * loss[k]; + tmpD[1] = (t1 * t1) * risk[i][i] + t2 * t2 * risk[j][j] + (1 - t1 - t2) * (1 - t1 - t2) * risk[k][k] + + 2 * (t1 * t2 * risk[i][j]) + 2 * ((1 - t1 - t2) * t2 * risk[k][j]) + 2 * (t1 * (1 - t1 - t2) * risk[i][k]); tmpElem.add(tmpD); complete.add(tmpD); } @@ -157,20 +157,20 @@ public class PortfolioFrontTester { // now calc the stuff ArrayList complete = new ArrayList(); ArrayList elements = new ArrayList(); - double[] tmpD; + double[] tmpD; ArrayList tmpElem; - int res = 35; + int res = 35; for (int i = 0; i < loss.length; i++) { - for (int j = i+1; j < loss.length; j++) { - for (int k = j+1; k < loss.length; k++) { + for (int j = i + 1; j < loss.length; j++) { + for (int k = j + 1; k < loss.length; k++) { tmpElem = new ArrayList(); - for (double t1 = 0; t1 < 1.0; t1 += 1/(double)res) { - for (double t2 = 0; t2 < (1.0 - t1); t2 += 1/(double)res) { - if (!(this.exceedingLimit(limit, t1, t2, (1-t1-t2)) > 1)) { + for (double t1 = 0; t1 < 1.0; t1 += 1 / (double) res) { + for (double t2 = 0; t2 < (1.0 - t1); t2 += 1 / (double) res) { + if (!(this.exceedingLimit(limit, t1, t2, (1 - t1 - t2)) > 1)) { tmpD = new double[2]; - tmpD[0] = t1*loss[i] + t2*loss[j] + (1-t1-t2)*loss[k]; - tmpD[1] = (t1*t1)*risk[i][i] + t2*t2*risk[j][j] + (1-t1-t2)*(1-t1-t2)*risk[k][k] - + 2*(t1*t2*risk[i][j]) + 2*((1-t1-t2)*t2*risk[k][j])+ 2*(t1*(1-t1-t2)*risk[i][k]); + tmpD[0] = t1 * loss[i] + t2 * loss[j] + (1 - t1 - t2) * loss[k]; + tmpD[1] = (t1 * t1) * risk[i][i] + t2 * t2 * risk[j][j] + (1 - t1 - t2) * (1 - t1 - t2) * risk[k][k] + + 2 * (t1 * t2 * risk[i][j]) + 2 * ((1 - t1 - t2) * t2 * risk[k][j]) + 2 * (t1 * (1 - t1 - t2) * risk[i][k]); tmpElem.add(tmpD); complete.add(tmpD); } @@ -201,7 +201,7 @@ public class PortfolioFrontTester { private void saveThisStuff(ArrayList c, ArrayList e) { try { - this.m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("PortX_K2_Limits045_CompleteList.txt"))); + this.m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("PortX_K2_Limits045_CompleteList.txt"))); } catch (FileNotFoundException ex) { System.out.println("Could not open output file!"); } @@ -211,7 +211,7 @@ public class PortfolioFrontTester { this.writeToFile(line); for (int i = 0; i < c.size(); i++) { tmpD = (double[]) c.get(i); - line = tmpD[1] +"\t" + tmpD[0]; + line = tmpD[1] + "\t" + tmpD[0]; this.writeToFile(line); } try { @@ -220,18 +220,18 @@ public class PortfolioFrontTester { } // next file try { - this.m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("PortX_K2_Limits045_ListElements.txt"))); + this.m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("PortX_K2_Limits045_ListElements.txt"))); } catch (FileNotFoundException ex) { System.out.println("Could not open output file!"); } int length = e.size(); double[][][] cara = new double[length][][]; for (int i = 0; i < e.size(); i++) { - cara[i] = (double[][])e.get(i); + cara[i] = (double[][]) e.get(i); } line = ""; for (int i = 0; i < cara.length; i++) { - line = "Risk"+i+"\t"+"Loss"+i; + line = "Risk" + i + "\t" + "Loss" + i; } this.writeToFile(line); for (int i = 0; i < cara[0].length; i++) { @@ -249,7 +249,7 @@ public class PortfolioFrontTester { private void saveThisStuffK3(ArrayList c, ArrayList e) { try { - this.m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("PortX_K3_Limits0283_CompleteList.txt"))); + this.m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("PortX_K3_Limits0283_CompleteList.txt"))); } catch (FileNotFoundException ex) { System.out.println("Could not open output file!"); } @@ -259,7 +259,7 @@ public class PortfolioFrontTester { this.writeToFile(line); for (int i = 0; i < c.size(); i++) { tmpD = (double[]) c.get(i); - line = tmpD[1] +"\t" + tmpD[0]; + line = tmpD[1] + "\t" + tmpD[0]; this.writeToFile(line); } try { @@ -268,7 +268,7 @@ public class PortfolioFrontTester { } // next file try { - this.m_OutputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream ("PortX_K3_Limits0283_ListElements.txt"))); + this.m_OutputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("PortX_K3_Limits0283_ListElements.txt"))); } catch (FileNotFoundException ex) { System.out.println("Could not open output file!"); } @@ -276,7 +276,7 @@ public class PortfolioFrontTester { double[][][] cara = new double[length][][]; ArrayList tmpA; for (int i = 0; i < e.size(); i++) { - tmpA = (ArrayList)e.get(i); + tmpA = (ArrayList) e.get(i); cara[i] = new double[tmpA.size()][]; for (int j = 0; j < tmpA.size(); j++) { cara[i][j] = (double[]) tmpA.get(j); @@ -285,7 +285,7 @@ public class PortfolioFrontTester { line = ""; for (int i = 0; i < cara.length; i++) { - line = "Risk"+i+"\t"+"Loss"+i; + line = "Risk" + i + "\t" + "Loss" + i; } this.writeToFile(line); for (int i = 0; i < cara[0].length; i++) { @@ -306,8 +306,10 @@ public class PortfolioFrontTester { } } - /** This method writes Data to file. - * @param line The line that is to be added to the file + /** + * This method writes Data to file. + * + * @param line The line that is to be added to the file */ private void writeToFile(String line) { String write = line + "\n"; @@ -331,17 +333,18 @@ public class PortfolioFrontTester { } private void showLine(double[][] elm) { - GraphPointSet mySet = new GraphPointSet(this.index, this.m_Plot.getFunctionArea()); + GraphPointSet mySet = new GraphPointSet(this.index, this.m_Plot.getFunctionArea()); mySet.setConnectedMode(false); this.index++; for (int i = 0; i < elm.length; i++) { mySet.addDPoint(elm[i][1], elm[i][0]); } } + private void showLine(ArrayList elm) { double[][] res = new double[elm.size()][]; for (int i = 0; i < elm.size(); i++) { - res[i] = (double[])elm.get(i); + res[i] = (double[]) elm.get(i); } this.showLine(res); } diff --git a/src/eva2/optimization/tools/TestingDArea.java b/src/eva2/optimization/tools/TestingDArea.java index 7db4446b..e907f6aa 100644 --- a/src/eva2/optimization/tools/TestingDArea.java +++ b/src/eva2/optimization/tools/TestingDArea.java @@ -1,6 +1,7 @@ package eva2.optimization.tools; import eva2.tools.chart2d.*; + import java.awt.*; import javax.swing.*; diff --git a/src/eva2/tools/BasicResourceLoader.java b/src/eva2/tools/BasicResourceLoader.java index 080ce9e0..7ca35112 100644 --- a/src/eva2/tools/BasicResourceLoader.java +++ b/src/eva2/tools/BasicResourceLoader.java @@ -27,6 +27,7 @@ package eva2.tools; import eva2.EvAInfo; + import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; @@ -48,40 +49,36 @@ import java.util.zip.ZipInputStream; /** - * Loads resource file from directory OR jar file. Now it is easier possible to - * access resource files in a directory structure or a .jar/.zip file. + * Loads resource file from directory OR jar file. Now it is easier possible to + * access resource files in a directory structure or a .jar/.zip file. * * @.author Marcel Kronfeld - * @.author wegnerj - * @.author Robin Friedman, rfriedman@TriadTherapeutics.com - * @.author Gerd Mueller + * @.author wegnerj + * @.author Robin Friedman, rfriedman@TriadTherapeutics.com + * @.author Gerd Mueller * @.license GPL - * @.cvsversion $Revision: 1.3 $, $Date: 2005/02/17 16:48:44 $ + * @.cvsversion $Revision: 1.3 $, $Date: 2005/02/17 16:48:44 $ */ -public class BasicResourceLoader implements ResourceLoader -{ +public class BasicResourceLoader implements ResourceLoader { /** - * Obtain a suitable logger. + * Obtain a suitable logger. */ private static Logger logger = Logger.getLogger(BasicResourceLoader.class.getName()); private static BasicResourceLoader resourceLoader; /** - * Constructor for the ResourceLoader object + * Constructor for the ResourceLoader object */ - private BasicResourceLoader() - { + private BasicResourceLoader() { } /** - * Description of the Method + * Description of the Method * - * @return Description of the Return Value + * @return Description of the Return Value */ - public static synchronized BasicResourceLoader instance() - { - if (resourceLoader == null) - { + public static synchronized BasicResourceLoader instance() { + if (resourceLoader == null) { resourceLoader = new BasicResourceLoader(); } @@ -89,81 +86,72 @@ public class BasicResourceLoader implements ResourceLoader } /** - * Description of the Method + * Description of the Method * - * @param resourceFile Description of the Parameter - * @return Description of the Return Value + * @param resourceFile Description of the Parameter + * @return Description of the Return Value */ - public static List readLines(String resourceFile) - { + public static List readLines(String resourceFile) { return readLines(resourceFile, false); } /** - * Description of the Method + * Description of the Method * - * @param resourceFile Description of the Parameter - * @param ignoreComments Description of the Parameter - * @return Description of the Return Value + * @param resourceFile Description of the Parameter + * @param ignoreComments Description of the Parameter + * @return Description of the Return Value */ public static List readLines(String resourceFile, - boolean ignoreCommentedLines) - { - return readLines(resourceFile, new String[] {"#"}, 0, -1); + boolean ignoreCommentedLines) { + return readLines(resourceFile, new String[]{"#"}, 0, -1); } - + /** - * Read String lines from a file into a list. + * Read String lines from a file into a list. * - * @param resourceFile File to read - * @param ignorePrefix array of prefixes which mark a line to be ignored - * @param lOffset offset of the first line to read - * @param lCnt number of lines to read, if <= 0, all lines are read - * @return List of lines which were read or null on an error + * @param resourceFile File to read + * @param ignorePrefix array of prefixes which mark a line to be ignored + * @param lOffset offset of the first line to read + * @param lCnt number of lines to read, if <= 0, all lines are read + * @return List of lines which were read or null on an error */ public static List readLines(String resourceFile, - String[] ignorePrefix, int lOffset, int lCnt) - { - if (resourceFile == null) - { + String[] ignorePrefix, int lOffset, int lCnt) { + if (resourceFile == null) { return null; } byte[] bytes = BasicResourceLoader.instance() - .getBytesFromResourceLocation( - resourceFile, false); + .getBytesFromResourceLocation( + resourceFile, false); - if (bytes == null) - { + if (bytes == null) { return null; } ByteArrayInputStream sReader = new ByteArrayInputStream(bytes); LineNumberReader lnr = new LineNumberReader(new InputStreamReader( - sReader)); + sReader)); String line; ArrayList lineData = new ArrayList(100); int lineCnt = 0; - try - { - while ((line = lnr.readLine()) != null) - { - line = line.trim(); - if (strStartsWithPrefix(line, ignorePrefix) < 0) { - if (lineCnt >= lOffset) { - lineData.add(line); - } - lineCnt++; - if ((lCnt > 0) && (lineData.size() == lCnt)) { - break; - } - } + try { + while ((line = lnr.readLine()) != null) { + line = line.trim(); + if (strStartsWithPrefix(line, ignorePrefix) < 0) { + if (lineCnt >= lOffset) { + lineData.add(line); + } + lineCnt++; + if ((lCnt > 0) && (lineData.size() == lCnt)) { + break; + } + } } - } - catch (IOException ex) - { + } catch (IOException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } @@ -171,172 +159,170 @@ public class BasicResourceLoader implements ResourceLoader } /** - * Parse columns of a data array containing double data. Columns may be selected by giving their - * indices in an int array. If selectedCols is null, all columns are selected. All selected columns - * are expected to contain double data and to be of same length. If rawData is null, null is returned. - * - * @param rawData Strings containing an array with double data columns - * @param colSplit String regexp for the splitting of a line - * @param selectedCols indices of the columns to retrieve, null for all. - * @see java.util.regex.Pattern - * @return - */ - public static double[][] parseDoubleArray(ArrayList rawData, String colSplit, int[] selectedCols) { - String[] entries; - double dat[][] = null; - if (rawData != null) { - try { - for (int i=0; i= start) && (data[i][col] <= end)) { - if (cnt == 0) { - startIndex = i; - } - cnt++; - } else if (cnt > 0) { - break; - } - } - - double[][] selData = new double[cnt][data[0].length]; - System.arraycopy(data, startIndex, selData, 0, cnt); - return selData; - } - - /** - * Load double data from a text file. An ignore list of prefixes may be specified. The start line and number of lines - * to read may be specified, if lCnt is -1, as many lines as possible are read. The cols array may contain an integer - * list of columns to be read. If null, as many columns as possible are read. - * The data file is expected to be uniform, meaning that all lines which are not ignored, contain double data values - * in all columns. - * - * @param fname file name to read - * @param ignorePrefix lines starting with any of these Strings will be ignored - * @param colSplit String regexp for the splitting of a line - * @param lOffset start at a certain line (0 for top) - * @param lCnt read as many lines, -1 or 0 for all (from offset). Ignored lines are not counted! - * @param selectedCols indices of the columns to retrieve, null for all. - * @return - */ - public static double[][] loadDoubleData(String fname, String[] ignorePrefix, String colSplit, int lOffset, int lCnt, int[] selectedCols) { - return parseDoubleArray((ArrayList)readLines(fname, ignorePrefix, lOffset, lCnt), colSplit, selectedCols); - } - - /** - * Fill a line of an array with double values parsed from a String array. A subset of - * Columns may be selected by giving their indices in an integer array cols. If cols - * is null, all are converted. - * If data is missing from the string array, the double array is filled with NaN. - * If more data is delivered, an error message will be printed and the superfluous data disregarded. - * - * @param dest - * @param lineCnt - * @param entries - * @param cols - */ - public static void fillLine(double[][] dest, int lineCnt, String[] entries, int[] cols) { - if (((cols == null) && (dest[lineCnt].length < entries.length)) || (cols != null && (dest[lineCnt].length != cols.length))) { - System.err.println("error, array dimensions dont match! (BasicResourceLoader)"); - } - if (cols == null) { - for (int i=0; i=entries.length) || (entries[i]==null || (entries[i].length()==0))) { - dest[lineCnt][i]=Double.NaN; - } - else { - dest[lineCnt][i] = Double.valueOf(entries[i]); - } - } catch(NumberFormatException ex) { - System.err.println("Invalid Double format in line " + lineCnt + ", data was " + entries[i]); - dest[lineCnt][i]=Double.NaN; - } - } - } else { - for (int i=0; i=entries.length) || (entries[cols[i]]==null || (entries[cols[i]].length()==0)))) { - dest[lineCnt][i]=Double.NaN; - } - else { - dest[lineCnt][i] = Double.valueOf(entries[cols[i]]); - } - } catch(NumberFormatException ex) { - System.err.println("Invalid Double format in line " + lineCnt + ", data was " + entries[cols[i]]); - dest[lineCnt][i]=Double.NaN; - } - } - } - } - - /** - * Test a string for prefixes. For the first matching prefix, the index - * of the prefix within the prefix array is returned. If there is no match -1 is returned. - * @param str - * @param pref - * @return - */ - public static int strStartsWithPrefix(String str, String[] pref) { - int i=0; - if (pref != null) { - for (String prefix : pref) { - if (str.startsWith(prefix)) { - return i; - } - i++; - } - } - return -1; - } - - /** - * Gets the byte data from a file at the given resource location. + * Parse columns of a data array containing double data. Columns may be selected by giving their + * indices in an int array. If selectedCols is null, all columns are selected. All selected columns + * are expected to contain double data and to be of same length. If rawData is null, null is returned. * - * @param rawResrcLoc Description of the Parameter - * @return the byte array of file. + * @param rawData Strings containing an array with double data columns + * @param colSplit String regexp for the splitting of a line + * @param selectedCols indices of the columns to retrieve, null for all. + * @return + * @see java.util.regex.Pattern + */ + public static double[][] parseDoubleArray(ArrayList rawData, String colSplit, int[] selectedCols) { + String[] entries; + double dat[][] = null; + if (rawData != null) { + try { + for (int i = 0; i < rawData.size(); i++) { + entries = rawData.get(i).split(colSplit); + if (i == 0) { // at the first pass + dat = new double[rawData.size()][(selectedCols == null) ? entries.length : selectedCols.length]; + } + trimAll(entries); + fillLine(dat, i, entries, selectedCols); + } + } catch (Exception e) { + e.printStackTrace(); + System.err.println(e.getMessage()); + } + } + return dat; + } + + private static void trimAll(String[] entries) { + for (int i = 0; i < entries.length; i++) { + if (entries[i] != null) { + entries[i] = entries[i].trim(); + } + } + } + + /** + * Walk through a 2-d-array and retrieve the first bunch of lines for which the given column data lies + * within start and end limits, both inclusively. The original array is not altered. + * + * @param data data array to search + * @param col column to inspect + * @param start first value to start retrieving from + * @param end last value to retrieve + * @return + */ + public static double[][] getLinesByCol(double[][] data, int col, double start, double end) { + int cnt = 0; + int startIndex = 0; + for (int i = 0; i < data.length; i++) { + if ((data[i][col] >= start) && (data[i][col] <= end)) { + if (cnt == 0) { + startIndex = i; + } + cnt++; + } else if (cnt > 0) { + break; + } + } + + double[][] selData = new double[cnt][data[0].length]; + System.arraycopy(data, startIndex, selData, 0, cnt); + return selData; + } + + /** + * Load double data from a text file. An ignore list of prefixes may be specified. The start line and number of lines + * to read may be specified, if lCnt is -1, as many lines as possible are read. The cols array may contain an integer + * list of columns to be read. If null, as many columns as possible are read. + * The data file is expected to be uniform, meaning that all lines which are not ignored, contain double data values + * in all columns. + * + * @param fname file name to read + * @param ignorePrefix lines starting with any of these Strings will be ignored + * @param colSplit String regexp for the splitting of a line + * @param lOffset start at a certain line (0 for top) + * @param lCnt read as many lines, -1 or 0 for all (from offset). Ignored lines are not counted! + * @param selectedCols indices of the columns to retrieve, null for all. + * @return + */ + public static double[][] loadDoubleData(String fname, String[] ignorePrefix, String colSplit, int lOffset, int lCnt, int[] selectedCols) { + return parseDoubleArray((ArrayList) readLines(fname, ignorePrefix, lOffset, lCnt), colSplit, selectedCols); + } + + /** + * Fill a line of an array with double values parsed from a String array. A subset of + * Columns may be selected by giving their indices in an integer array cols. If cols + * is null, all are converted. + * If data is missing from the string array, the double array is filled with NaN. + * If more data is delivered, an error message will be printed and the superfluous data disregarded. + * + * @param dest + * @param lineCnt + * @param entries + * @param cols + */ + public static void fillLine(double[][] dest, int lineCnt, String[] entries, int[] cols) { + if (((cols == null) && (dest[lineCnt].length < entries.length)) || (cols != null && (dest[lineCnt].length != cols.length))) { + System.err.println("error, array dimensions dont match! (BasicResourceLoader)"); + } + if (cols == null) { + for (int i = 0; i < dest[lineCnt].length; i++) { + try { + if ((i >= entries.length) || (entries[i] == null || (entries[i].length() == 0))) { + dest[lineCnt][i] = Double.NaN; + } else { + dest[lineCnt][i] = Double.valueOf(entries[i]); + } + } catch (NumberFormatException ex) { + System.err.println("Invalid Double format in line " + lineCnt + ", data was " + entries[i]); + dest[lineCnt][i] = Double.NaN; + } + } + } else { + for (int i = 0; i < cols.length; i++) { + try { + if ((cols[i] < 0) || ((cols[i] >= entries.length) || (entries[cols[i]] == null || (entries[cols[i]].length() == 0)))) { + dest[lineCnt][i] = Double.NaN; + } else { + dest[lineCnt][i] = Double.valueOf(entries[cols[i]]); + } + } catch (NumberFormatException ex) { + System.err.println("Invalid Double format in line " + lineCnt + ", data was " + entries[cols[i]]); + dest[lineCnt][i] = Double.NaN; + } + } + } + } + + /** + * Test a string for prefixes. For the first matching prefix, the index + * of the prefix within the prefix array is returned. If there is no match -1 is returned. + * + * @param str + * @param pref + * @return + */ + public static int strStartsWithPrefix(String str, String[] pref) { + int i = 0; + if (pref != null) { + for (String prefix : pref) { + if (str.startsWith(prefix)) { + return i; + } + i++; + } + } + return -1; + } + + /** + * Gets the byte data from a file at the given resource location. + * + * @param rawResrcLoc Description of the Parameter + * @return the byte array of file. */ public InputStream getStreamFromResourceLocation(String rawResrcLoc) { String resourceLocation = rawResrcLoc.replace('\\', '/'); //System.out.println("Try to get: "+resourceLocation); - if (resourceLocation == null) - { + if (resourceLocation == null) { return null; } @@ -345,21 +331,20 @@ public class BasicResourceLoader implements ResourceLoader // at the console output !!! resourceLocation = resourceLocation.trim(); InputStream in = null; - + // is a relative path defined ? // this can only be possible, if this is a file resource location if (resourceLocation.startsWith("..") || resourceLocation.startsWith("/") || resourceLocation.startsWith("\\") || ((resourceLocation.length() > 1) && - (resourceLocation.charAt(1) == ':'))) - { + (resourceLocation.charAt(1) == ':'))) { in = getStreamFromFile(resourceLocation); } // InputStream inTest = getStreamFromFile(resourceLocation); - + if (in == null) { - in = ClassLoader.getSystemResourceAsStream(resourceLocation); + in = ClassLoader.getSystemResourceAsStream(resourceLocation); } if (in == null) { @@ -369,19 +354,18 @@ public class BasicResourceLoader implements ResourceLoader } if (in == null) { - // try to search other classpathes...? not really necessary. + // try to search other classpathes...? not really necessary. // in = getStreamFromClassPath(resourceLocation); } - - if (in == null) { - logger.log(Level.FINER, "Unable to open stream for " + resourceLocation); - } - else { - logger.log(Level.FINER, "Stream opened for " + resourceLocation); - } + + if (in == null) { + logger.log(Level.FINER, "Unable to open stream for " + resourceLocation); + } else { + logger.log(Level.FINER, "Stream opened for " + resourceLocation); + } return in; } - + // public InputStream getStreamFromClassPath(String resourceLocation) { // String[] dynCP = ReflectPackage.getValidCPArray(); // Vector found = new Vector(); @@ -406,75 +390,69 @@ public class BasicResourceLoader implements ResourceLoader // } // return getStreamFromFile(found.get(0)); // } + /** - * Gets the byte data from a file at the given resource location. + * Gets the byte data from a file at the given resource location. * - * @param rawResrcLoc Description of the Parameter - * @return the byte array of file. + * @param rawResrcLoc Description of the Parameter + * @return the byte array of file. */ @Override public byte[] getBytesFromResourceLocation(String rawResrcLoc) { - return getBytesFromResourceLocation(rawResrcLoc, false); + return getBytesFromResourceLocation(rawResrcLoc, false); } - + /** - * Gets the byte data from a file at the given resource location. + * Gets the byte data from a file at the given resource location. * - * @param rawResrcLoc Location of the resource - * @param exceptionOnNotFound if true, a RuntimeException is thrown if the resource was not found. - * @return the byte array of file. + * @param rawResrcLoc Location of the resource + * @param exceptionOnNotFound if true, a RuntimeException is thrown if the resource was not found. + * @return the byte array of file. */ - public byte[] getBytesFromResourceLocation(String rawResrcLoc, boolean exceptionOnNotFound) - { + public byte[] getBytesFromResourceLocation(String rawResrcLoc, boolean exceptionOnNotFound) { InputStream in = getStreamFromResourceLocation(rawResrcLoc); byte[] arr = null; if (in != null) { - arr = getBytesFromStream(in); + arr = getBytesFromStream(in); } - if (exceptionOnNotFound && (arr==null)) { - throw new RuntimeException(EvAInfo.resourceNotFoundErrorMessage(rawResrcLoc)); + if (exceptionOnNotFound && (arr == null)) { + throw new RuntimeException(EvAInfo.resourceNotFoundErrorMessage(rawResrcLoc)); } return arr; } /** - * Gets the byte data from a file contained in a JAR or ZIP file. + * Gets the byte data from a file contained in a JAR or ZIP file. * - * @param urlToZipArchive Description of the Parameter - * @param internalArchivePath Description of the Parameter - * @return the byte array of the file. + * @param urlToZipArchive Description of the Parameter + * @param internalArchivePath Description of the Parameter + * @return the byte array of the file. */ private byte[] getBytesFromArchive(String urlToZipArchive, - String internalArchivePath) - { + String internalArchivePath) { URL url = null; int size = -1; byte[] b = null; - try - { + try { url = new URL(urlToZipArchive); // extracts just sizes only. ZipFile zf = new ZipFile(url.getFile()); Enumeration e = zf.entries(); - while (e.hasMoreElements()) - { + while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); - if (ze.getName().equals(internalArchivePath)) - { - if (ze.isDirectory()) - { + if (ze.getName().equals(internalArchivePath)) { + if (ze.isDirectory()) { return null; } // only files with <65536 bytes are allowed - if (ze.getSize() > 65536) - { + if (ze.getSize() > 65536) { System.out.println( - "Resource files should be smaller than 65536 bytes..."); + "Resource files should be smaller than 65536 bytes..."); } size = (int) ze.getSize(); @@ -488,21 +466,17 @@ public class BasicResourceLoader implements ResourceLoader ZipInputStream zis = new ZipInputStream(bis); ZipEntry ze = null; - while ((ze = zis.getNextEntry()) != null) - { - if (ze.getName().equals(internalArchivePath)) - { + while ((ze = zis.getNextEntry()) != null) { + if (ze.getName().equals(internalArchivePath)) { b = new byte[(int) size]; int rb = 0; int chunk = 0; - while (((int) size - rb) > 0) - { + while (((int) size - rb) > 0) { chunk = zis.read(b, rb, (int) size - rb); - if (chunk == -1) - { + if (chunk == -1) { break; } @@ -510,9 +484,7 @@ public class BasicResourceLoader implements ResourceLoader } } } - } - catch (Exception ex) - { + } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); return null; } @@ -521,18 +493,16 @@ public class BasicResourceLoader implements ResourceLoader } /** - * Gets the byte data from a file. + * Gets the byte data from a file. * - * @param fileName Description of the Parameter - * @return the byte array of the file. + * @param fileName Description of the Parameter + * @return the byte array of the file. */ - private FileInputStream getStreamFromFile(String fileName) - { - if (fileName.startsWith("/cygdrive/")) - { + private FileInputStream getStreamFromFile(String fileName) { + if (fileName.startsWith("/cygdrive/")) { int length = "/cygdrive/".length(); fileName = fileName.substring(length, length + 1) + ":" + - fileName.substring(length + 1); + fileName.substring(length + 1); } logger.log(Level.FINER, "Trying to get file from " + fileName); @@ -540,31 +510,28 @@ public class BasicResourceLoader implements ResourceLoader File file = new File(fileName); FileInputStream fis = null; - try - { + try { fis = new FileInputStream(file); return fis; - } - catch (Exception ex) - { - logger.log(Level.SEVERE, ex.getMessage(), ex); + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.getMessage(), ex); return null; } } - + /** - * Gets the byte data from a file. + * Gets the byte data from a file. * - * @param fileName Description of the Parameter - * @return the byte array of the file. + * @param fileName Description of the Parameter + * @return the byte array of the file. */ private byte[] getBytesFromFile(String fileName) { - FileInputStream fis = getStreamFromFile(fileName); - if (fis == null) { - System.err.println("couldnt get file input stream!"); - return null; - } + FileInputStream fis = getStreamFromFile(fileName); + if (fis == null) { + System.err.println("couldnt get file input stream!"); + return null; + } BufferedInputStream bis = new BufferedInputStream(fis); // only files with <65536 bytes are allowed @@ -574,22 +541,17 @@ public class BasicResourceLoader implements ResourceLoader int rb = 0; int chunk = 0; - try - { - while (((int) size - rb) > 0) - { + try { + while (((int) size - rb) > 0) { chunk = bis.read(b, rb, (int) size - rb); - if (chunk == -1) - { + if (chunk == -1) { break; } rb += chunk; } - } - catch (Exception ex) - { + } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); return null; @@ -599,33 +561,28 @@ public class BasicResourceLoader implements ResourceLoader } /** - * Gets the byte data from a file. + * Gets the byte data from a file. * - * @param fileName Description of the Parameter - * @return the byte array of the file. + * @param fileName Description of the Parameter + * @return the byte array of the file. */ - private byte[] getBytesFromStream(InputStream stream) - { - if (stream == null) - { + private byte[] getBytesFromStream(InputStream stream) { + if (stream == null) { return null; } BufferedInputStream bis = new BufferedInputStream(stream); - try - { + try { int size = (int) bis.available(); byte[] b = new byte[size]; int rb = 0; int chunk = 0; - while (((int) size - rb) > 0) - { + while (((int) size - rb) > 0) { chunk = bis.read(b, rb, (int) size - rb); - if (chunk == -1) - { + if (chunk == -1) { break; } @@ -633,52 +590,49 @@ public class BasicResourceLoader implements ResourceLoader } return b; - } - catch (Exception ex) - { + } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); return null; } } - - /** - * - */ - public static Properties readProperties(String resourceName) throws Exception { - Properties prop = new Properties(); - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte bytes[] = loader.getBytesFromResourceLocation(resourceName, false); - if (bytes != null) { - ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - prop.load(bais); - if (prop != null) { - return prop; - } - } - ///////////// + /** + * + */ + public static Properties readProperties(String resourceName) throws Exception { + Properties prop = new Properties(); + BasicResourceLoader loader = BasicResourceLoader.instance(); - int slInd = resourceName.lastIndexOf('/'); - String planBResName; - if (slInd != -1) { - planBResName = resourceName.substring(slInd + 1); + byte bytes[] = loader.getBytesFromResourceLocation(resourceName, false); + if (bytes != null) { + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + prop.load(bais); + if (prop != null) { + return prop; } - else { - planBResName = resourceName; + } + ///////////// + + int slInd = resourceName.lastIndexOf('/'); + String planBResName; + if (slInd != -1) { + planBResName = resourceName.substring(slInd + 1); + } else { + planBResName = resourceName; + } + Properties userProps = new Properties(); + File propFile = new File(File.separatorChar + planBResName); + if (propFile.exists()) { + try { + userProps.load(new FileInputStream(propFile)); + } catch (Exception ex) { + System.err.println("Problem reading user properties: " + propFile); } - Properties userProps = new Properties(); - File propFile = new File(File.separatorChar + planBResName); - if (propFile.exists()) { - try { - userProps.load(new FileInputStream(propFile)); - } catch (Exception ex) { - System.err.println("Problem reading user properties: " + propFile); - } - } else { - System.err.println("Warning in readProperties: neither " + resourceName + " nor " + planBResName + " could be read."); - } - return userProps; - } - - + } else { + System.err.println("Warning in readProperties: neither " + resourceName + " nor " + planBResName + " could be read."); + } + return userProps; + } + + } diff --git a/src/eva2/tools/Cluster.java b/src/eva2/tools/Cluster.java index d1c72551..42afe97a 100644 --- a/src/eva2/tools/Cluster.java +++ b/src/eva2/tools/Cluster.java @@ -5,7 +5,7 @@ package eva2.tools; * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 10 $ + * @version: $Revision: 10 $ * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ @@ -15,33 +15,35 @@ package eva2.tools; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ + /** * This class represents a cluster object in the R^N. */ public class Cluster { - /** - * Number of samples in the cluster. - */ - public int m_SamplesInCluster; - /** - * Center of the cluster. - */ - public double[] m_Center; - /** - * nearest sample (double[]) to the center of the cluster. - */ - public double[] m_NearestSample; - /** - * This class represents a cluster of - * sample points. - * - * @param center center - * @param SamplesInCluster Number of samples in cluster - * @param nearestSample Nearest sample to cluster center. - */ - public Cluster(double[] center,int SamplesInCluster,double[] nearestSample) { - m_SamplesInCluster = SamplesInCluster; - m_Center = center; - m_NearestSample = nearestSample; - } + /** + * Number of samples in the cluster. + */ + public int m_SamplesInCluster; + /** + * Center of the cluster. + */ + public double[] m_Center; + /** + * nearest sample (double[]) to the center of the cluster. + */ + public double[] m_NearestSample; + + /** + * This class represents a cluster of + * sample points. + * + * @param center center + * @param SamplesInCluster Number of samples in cluster + * @param nearestSample Nearest sample to cluster center. + */ + public Cluster(double[] center, int SamplesInCluster, double[] nearestSample) { + m_SamplesInCluster = SamplesInCluster; + m_Center = center; + m_NearestSample = nearestSample; + } } \ No newline at end of file diff --git a/src/eva2/tools/CubicSpline.java b/src/eva2/tools/CubicSpline.java index 6fe41f08..d38ca38e 100644 --- a/src/eva2/tools/CubicSpline.java +++ b/src/eva2/tools/CubicSpline.java @@ -1,214 +1,210 @@ package eva2.tools; -/********************************************************** -* -* Class CubicSpline -* -* Class for performing an interpolation using a cubic spline -* setTabulatedArrays and interpolate adapted from Numerical Recipes in C -* -* WRITTEN BY: Mick Flanagan -* -* DATE: May 2002 -* -* DOCUMENTATION: -* See Michael T Flanagan's JAVA library on-line web page: -* CubicSpline.html -* -**********************************************************/ +/** + * ******************************************************* + *

+ * Class CubicSpline + *

+ * Class for performing an interpolation using a cubic spline + * setTabulatedArrays and interpolate adapted from Numerical Recipes in C + *

+ * WRITTEN BY: Mick Flanagan + *

+ * DATE: May 2002 + *

+ * DOCUMENTATION: + * See Michael T Flanagan's JAVA library on-line web page: + * CubicSpline.html + *

+ * ******************************************************** + */ -public class CubicSpline{ +public class CubicSpline { - private int npoints = 0; // no. of tabulated points - private double[] y = null; // y=f(x) tabulated function - private double[] x = null; // x in tabulated function f(x) - private double[] y2 = null; // returned second derivatives of y - private double yp1 = 0.0D; // first derivative at point one - // default value = zero (natural spline) - private double ypn = 0.0D; // first derivative at point n - // default value = zero (natural spline) + private int npoints = 0; // no. of tabulated points + private double[] y = null; // y=f(x) tabulated function + private double[] x = null; // x in tabulated function f(x) + private double[] y2 = null; // returned second derivatives of y + private double yp1 = 0.0D; // first derivative at point one + // default value = zero (natural spline) + private double ypn = 0.0D; // first derivative at point n + // default value = zero (natural spline) - // Constructors - // Constructor with data arrays initialised to arrays x and y - public CubicSpline(double[] x, double[] y){ - this.npoints=x.length; - if(this.npoints!=y.length) { - throw new IllegalArgumentException("Arrays x and y are of different length"); - } - this.x = new double[npoints]; - this.y = new double[npoints]; - this.y2 = new double[npoints]; - for(int i=0; i 0.99e30){ - y2[0]=u[0]=0.0; - } - else{ - this.y2[0] = -0.5; - u[0]=(3.0/(this.x[1]-this.x[0]))*((this.y[1]-this.y[0])/(this.x[1]-this.x[0])-this.yp1); - } + if (yp1 > 0.99e30) { + y2[0] = u[0] = 0.0; + } else { + this.y2[0] = -0.5; + u[0] = (3.0 / (this.x[1] - this.x[0])) * ((this.y[1] - this.y[0]) / (this.x[1] - this.x[0]) - this.yp1); + } - for(i=1;i<=this.npoints-2;i++){ - sig=(this.x[i]-this.x[i-1])/(this.x[i+1]-this.x[i-1]); - p=sig*this.y2[i-1]+2.0; - this.y2[i]=(sig-1.0)/p; - u[i]=(this.y[i+1]-this.y[i])/(this.x[i+1]-this.x[i]) - (this.y[i]-this.y[i-1])/(this.x[i]-this.x[i-1]); - u[i]=(6.0*u[i]/(this.x[i+1]-this.x[i-1])-sig*u[i-1])/p; - } + for (i = 1; i <= this.npoints - 2; i++) { + sig = (this.x[i] - this.x[i - 1]) / (this.x[i + 1] - this.x[i - 1]); + p = sig * this.y2[i - 1] + 2.0; + this.y2[i] = (sig - 1.0) / p; + u[i] = (this.y[i + 1] - this.y[i]) / (this.x[i + 1] - this.x[i]) - (this.y[i] - this.y[i - 1]) / (this.x[i] - this.x[i - 1]); + u[i] = (6.0 * u[i] / (this.x[i + 1] - this.x[i - 1]) - sig * u[i - 1]) / p; + } - if (this.ypn > 0.99e30){ - qn=un=0.0; - } - else{ - qn=0.5; - un=(3.0/(this.x[npoints-1]-this.x[this.npoints-2]))*(this.ypn-(this.y[this.npoints-1]-this.y[this.npoints-2])/(this.x[this.npoints-1]-x[this.npoints-2])); - } + if (this.ypn > 0.99e30) { + qn = un = 0.0; + } else { + qn = 0.5; + un = (3.0 / (this.x[npoints - 1] - this.x[this.npoints - 2])) * (this.ypn - (this.y[this.npoints - 1] - this.y[this.npoints - 2]) / (this.x[this.npoints - 1] - x[this.npoints - 2])); + } - this.y2[this.npoints-1]=(un-qn*u[this.npoints-2])/(qn*this.y2[this.npoints-2]+1.0); - for(k=this.npoints-2;k>=0;k--){ - this.y2[k]=this.y2[k]*this.y2[k+1]+u[k]; - } - } + this.y2[this.npoints - 1] = (un - qn * u[this.npoints - 2]) / (qn * this.y2[this.npoints - 2] + 1.0); + for (k = this.npoints - 2; k >= 0; k--) { + this.y2[k] = this.y2[k] * this.y2[k + 1] + u[k]; + } + } - // INTERPOLATE - // Returns an interpolated value of y for a value of xfrom a tabulated function y=f(x) - // after the data has been entered via a constructor and the derivatives calculated and - // stored by calcDeriv(). - public double interpolate(double xx){ - int klo=0,khi=0,k=0; - double h=0.0D,b=0.0D,a=0.0D, yy=0.0D; + // INTERPOLATE + // Returns an interpolated value of y for a value of xfrom a tabulated function y=f(x) + // after the data has been entered via a constructor and the derivatives calculated and + // stored by calcDeriv(). + public double interpolate(double xx) { + int klo = 0, khi = 0, k = 0; + double h = 0.0D, b = 0.0D, a = 0.0D, yy = 0.0D; - if (xxthis.x[this.npoints-1]){ + if (xx < this.x[0] || xx > this.x[this.npoints - 1]) { // System.out.println(xx); - xx -= 0.00001; - //throw new IllegalArgumentException("x is outside the range of data points"); - } + xx -= 0.00001; + //throw new IllegalArgumentException("x is outside the range of data points"); + } - klo=0; - khi=this.npoints-1; - while (khi-klo > 1){ - k=(khi+klo) >> 1; - if(this.x[k] > xx){ - khi=k; - } - else{ - klo=k; - } - } - h=this.x[khi]-this.x[klo]; + klo = 0; + khi = this.npoints - 1; + while (khi - klo > 1) { + k = (khi + klo) >> 1; + if (this.x[k] > xx) { + khi = k; + } else { + klo = k; + } + } + h = this.x[khi] - this.x[klo]; - if (h == 0.0){ - throw new IllegalArgumentException("Two values of x are identical"); - } - else{ - a=(this.x[khi]-xx)/h; - b=(xx-this.x[klo])/h; - yy=a*this.y[klo]+b*this.y[khi]+((a*a*a-a)*this.y2[klo]+(b*b*b-b)*this.y2[khi])*(h*h)/6.0; - } - return yy; - } + if (h == 0.0) { + throw new IllegalArgumentException("Two values of x are identical"); + } else { + a = (this.x[khi] - xx) / h; + b = (xx - this.x[klo]) / h; + yy = a * this.y[klo] + b * this.y[khi] + ((a * a * a - a) * this.y2[klo] + (b * b * b - b) * this.y2[khi]) * (h * h) / 6.0; + } + return yy; + } - // Returns an interpolated value of y for a value of x (xx) from a tabulated function y=f(x) - // after the derivatives (deriv) have been calculated independently of and calcDeriv(). - public static double interpolate(double xx, double[] x, double[] y, double[] deriv){ - if(((x.length != y.length) || (x.length != deriv.length)) || (y.length != deriv.length)){ - throw new IllegalArgumentException("array lengths are not all equal"); - } - int n = x.length; - int klo=0, khi=0, k=0; - double h=0.0D, b=0.0D, a=0.0D, yy = 0.0D; + // Returns an interpolated value of y for a value of x (xx) from a tabulated function y=f(x) + // after the derivatives (deriv) have been calculated independently of and calcDeriv(). + public static double interpolate(double xx, double[] x, double[] y, double[] deriv) { + if (((x.length != y.length) || (x.length != deriv.length)) || (y.length != deriv.length)) { + throw new IllegalArgumentException("array lengths are not all equal"); + } + int n = x.length; + int klo = 0, khi = 0, k = 0; + double h = 0.0D, b = 0.0D, a = 0.0D, yy = 0.0D; - klo=0; - khi=n-1; - while(khi-klo > 1){ - k=(khi+klo) >> 1; - if(x[k] > xx){ - khi=k; - } - else{ - klo=k; - } - } - h=x[khi]-x[klo]; + klo = 0; + khi = n - 1; + while (khi - klo > 1) { + k = (khi + klo) >> 1; + if (x[k] > xx) { + khi = k; + } else { + klo = k; + } + } + h = x[khi] - x[klo]; - if (h == 0.0){ - throw new IllegalArgumentException("Two values of x are identical"); - } - else{ - a=(x[khi]-xx)/h; - b=(xx-x[klo])/h; - yy=a*y[klo]+b*y[khi]+((a*a*a-a)*deriv[klo]+(b*b*b-b)*deriv[khi])*(h*h)/6.0; - } - return yy; - } + if (h == 0.0) { + throw new IllegalArgumentException("Two values of x are identical"); + } else { + a = (x[khi] - xx) / h; + b = (xx - x[klo]) / h; + yy = a * y[klo] + b * y[khi] + ((a * a * a - a) * deriv[klo] + (b * b * b - b) * deriv[khi]) * (h * h) / 6.0; + } + return yy; + } } diff --git a/src/eva2/tools/EVAERROR.java b/src/eva2/tools/EVAERROR.java index d2f3c846..6dc2ebb8 100644 --- a/src/eva2/tools/EVAERROR.java +++ b/src/eva2/tools/EVAERROR.java @@ -9,7 +9,7 @@ import java.util.logging.Logger; * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 245 $ + * @version: $Revision: 245 $ * $Date: 2007-11-08 17:24:53 +0100 (Thu, 08 Nov 2007) $ * $Author: mkron $ */ @@ -18,54 +18,55 @@ import java.util.logging.Logger; * */ public class EVAERROR { - private static final Logger logger = Logger.getLogger(EVAERROR.class.getName()); - private static transient HashMap errorMap = null; - /** - * - */ - public static void EXIT(String message) { - logger.log(Level.SEVERE, message); - System.exit(-1); - } + private static final Logger logger = Logger.getLogger(EVAERROR.class.getName()); + private static transient HashMap errorMap = null; - /** - * - */ - public static void EXIT(String message, Exception ex) { - logger.log(Level.SEVERE, message, ex); - System.exit(-1); - } + /** + * + */ + public static void EXIT(String message) { + logger.log(Level.SEVERE, message); + System.exit(-1); + } - /** - * - */ - public static void WARNING(String message) { - logger.log(Level.WARNING, message); - } + /** + * + */ + public static void EXIT(String message, Exception ex) { + logger.log(Level.SEVERE, message, ex); + System.exit(-1); + } - /** - * Send a message only once to System.err. Once means that the msg is stored for the lifetime of - * the VM or until clearMsgCache() is called. - * - * @param message - */ - public static void errorMsgOnce(String message) { - if (errorMap == null) { - errorMap = new HashMap(); - } + /** + * + */ + public static void WARNING(String message) { + logger.log(Level.WARNING, message); + } - if (!errorMap.containsKey(message)) { - logger.log(Level.SEVERE, message); - errorMap.put(message, true); - } - } + /** + * Send a message only once to System.err. Once means that the msg is stored for the lifetime of + * the VM or until clearMsgCache() is called. + * + * @param message + */ + public static void errorMsgOnce(String message) { + if (errorMap == null) { + errorMap = new HashMap(); + } - /** - * Clear the error message cache, so that any error messages are displayed at least once. - */ - public static void clearMsgCache() { - if (errorMap != null) { - errorMap.clear(); - } - } + if (!errorMap.containsKey(message)) { + logger.log(Level.SEVERE, message); + errorMap.put(message, true); + } + } + + /** + * Clear the error message cache, so that any error messages are displayed at least once. + */ + public static void clearMsgCache() { + if (errorMap != null) { + errorMap.clear(); + } + } } diff --git a/src/eva2/tools/EVAHELP.java b/src/eva2/tools/EVAHELP.java index 49ca6e60..a53d78b3 100644 --- a/src/eva2/tools/EVAHELP.java +++ b/src/eva2/tools/EVAHELP.java @@ -5,10 +5,11 @@ package eva2.tools; * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 255 $ + * @version: $Revision: 255 $ * $Date: 2007-11-15 14:58:12 +0100 (Thu, 15 Nov 2007) $ * $Author: mkron $ */ + import java.io.*; import java.net.InetAddress; import java.util.Enumeration; @@ -19,142 +20,142 @@ import java.util.Properties; */ public class EVAHELP { - private static long m_TimeStamp; + private static long m_TimeStamp; - /** - * - */ - /** - * - */ - public static String getmyRUP() { + /** + * + */ + /** + * + */ + public static String getmyRUP() { String Out = new String(); - String HostName = ""; - try { - HostName = InetAddress.getLocalHost().getHostName(); + String HostName = ""; + try { + HostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { - System.out.println("ERROR getting HostName EVAHELP " + e.getMessage()); - } + System.out.println("ERROR getting HostName EVAHELP " + e.getMessage()); + } - try { - BufferedReader in = null; - Process pro = null; + try { + BufferedReader in = null; + Process pro = null; String command = "rup " + HostName; - pro = Runtime.getRuntime().exec(command); + pro = Runtime.getRuntime().exec(command); in = new BufferedReader(new InputStreamReader(pro.getInputStream())); - String line = null; + String line = null; while ((line = in.readLine()) != null) { - //System.out.println(line); + //System.out.println(line); Out += line; - } - } catch (Exception e) { + } + } catch (Exception e) { System.out.println("Error in calling the command:" + e.getMessage()); - } - return Out; - } + } + return Out; + } - /** - * - */ - public static void setTimeStamp() { - m_TimeStamp = System.currentTimeMillis(); - } + /** + * + */ + public static void setTimeStamp() { + m_TimeStamp = System.currentTimeMillis(); + } - /** - * - */ - public static long getTimeStamp() { - return System.currentTimeMillis() - m_TimeStamp; - } + /** + * + */ + public static long getTimeStamp() { + return System.currentTimeMillis() - m_TimeStamp; + } - /** - * - */ - public static void returnForExit() { + /** + * + */ + public static void returnForExit() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - System.out.println("return for exit:"); - try { - in.readLine(); - } catch (Exception e) { - System.out.println(e.getMessage()); + System.out.println("return for exit:"); + try { + in.readLine(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } } - } - /** - * - */ - public static String getSystemPropertyString() { - StringBuffer sBuf = new StringBuffer(); - Properties prop = System.getProperties(); - Enumeration list = prop.propertyNames(); - while (list.hasMoreElements()) { - Object o = list.nextElement(); - //System.out.println("o="+o.toString()); - sBuf.append(o.toString()); - sBuf.append(" = "); - sBuf.append(System.getProperty(o.toString())); - sBuf.append("\n"); + /** + * + */ + public static String getSystemPropertyString() { + StringBuffer sBuf = new StringBuffer(); + Properties prop = System.getProperties(); + Enumeration list = prop.propertyNames(); + while (list.hasMoreElements()) { + Object o = list.nextElement(); + //System.out.println("o="+o.toString()); + sBuf.append(o.toString()); + sBuf.append(" = "); + sBuf.append(System.getProperty(o.toString())); + sBuf.append("\n"); + } + return sBuf.toString(); } - return sBuf.toString(); - } - /** - * @param longName The FQDN of a class - * @return Returns the class Name without package. - */ - public static String cutClassName(final String longName) { - final int dotPos = longName.lastIndexOf('.'); - String className = longName; - if (dotPos != -1) { - className = className.substring(dotPos + 1); + /** + * @param longName The FQDN of a class + * @return Returns the class Name without package. + */ + public static String cutClassName(final String longName) { + final int dotPos = longName.lastIndexOf('.'); + String className = longName; + if (dotPos != -1) { + className = className.substring(dotPos + 1); + } + return className; // now is shortName } - return className; // now is shortName - } - /** - * - */ - public static void freeMemory() { - Runtime currR = Runtime.getRuntime(); - long freeM = currR.freeMemory(); - freeM = (long) (freeM / 1024); - //System.out.println("Available memory : "+freeM+" Kbytes"); - System.gc(); - currR = Runtime.getRuntime(); - freeM = currR.freeMemory(); - freeM = (long) (freeM / 1024); - //System.out.println("after gc:Available memory : "+freeM+" bytes"); - } - - /** + /** + * + */ + public static void freeMemory() { + Runtime currR = Runtime.getRuntime(); + long freeM = currR.freeMemory(); + freeM = (long) (freeM / 1024); + //System.out.println("Available memory : "+freeM+" Kbytes"); + System.gc(); + currR = Runtime.getRuntime(); + freeM = currR.freeMemory(); + freeM = (long) (freeM / 1024); + //System.out.println("after gc:Available memory : "+freeM+" bytes"); + } + + /** * Log a String to a log-file indicated by the file name. If the file * exists, the String is appended. - * - * @param msg - * @param fileName - */ - public static void logString(String msg, String fileName) { - final File logFile = new File(fileName); - try { - BufferedWriter bW = new BufferedWriter( + * + * @param msg + * @param fileName + */ + public static void logString(String msg, String fileName) { + final File logFile = new File(fileName); + try { + BufferedWriter bW = new BufferedWriter( new PrintWriter(new FileOutputStream(logFile, logFile.exists()))); - bW.write(msg); - bW.close(); - } catch (IOException ex) { - System.err.println("couldnt log to destination " + fileName + ": " + ex.getMessage()); - } - } - - /** + bW.write(msg); + bW.close(); + } catch (IOException ex) { + System.err.println("couldnt log to destination " + fileName + ": " + ex.getMessage()); + } + } + + /** * Deletes the given file in the current directory. If the file does not * exist nothing happens. - * - * @param fileName The name of the log file - */ - public static void clearLog(String fileName) { - File logFile = new File(fileName); - if (logFile.exists()) { - logFile.delete(); - } - } + * + * @param fileName The name of the log file + */ + public static void clearLog(String fileName) { + File logFile = new File(fileName); + if (logFile.exists()) { + logFile.delete(); + } + } } \ No newline at end of file diff --git a/src/eva2/tools/JPasswordDialog.java b/src/eva2/tools/JPasswordDialog.java index 2dd4b2b8..53898590 100644 --- a/src/eva2/tools/JPasswordDialog.java +++ b/src/eva2/tools/JPasswordDialog.java @@ -11,7 +11,7 @@ import javax.swing.*; * A modal dialog that asks the user for a user name and password. * More information about this class is available from ostermiller.org. - * + *

* *

  * PasswordDialog p = new PasswordDialog(null, "Test");
@@ -88,11 +88,10 @@ public class JPasswordDialog extends JDialog {
      * before the dialog is displayed.
      *
      * @param name default name to be displayed.
-     *
      * @since ostermillerutils 1.00.00
      */
     @Override
-    public void setName(String name){
+    public void setName(String name) {
         this.name.setText(name);
     }
 
@@ -102,10 +101,9 @@ public class JPasswordDialog extends JDialog {
      * before the dialog is displayed.
      *
      * @param pass default password to be displayed.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public void setPass(String pass){
+    public void setPass(String pass) {
         this.pass.setText(pass);
     }
 
@@ -114,10 +112,9 @@ public class JPasswordDialog extends JDialog {
      * The default is a localized string.
      *
      * @param ok label for the ok button.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public void setOKText(String ok){
+    public void setOKText(String ok) {
         this.okButton.setText(ok);
         pack();
     }
@@ -127,10 +124,9 @@ public class JPasswordDialog extends JDialog {
      * The default is a localized string.
      *
      * @param cancel label for the cancel button.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public void setCancelText(String cancel){
+    public void setCancelText(String cancel) {
         this.cancelButton.setText(cancel);
         pack();
     }
@@ -140,10 +136,9 @@ public class JPasswordDialog extends JDialog {
      * The default is a localized string.
      *
      * @param name label for the name field.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public void setNameLabel(String name){
+    public void setNameLabel(String name) {
         this.nameLabel.setText(name);
         pack();
     }
@@ -153,10 +148,9 @@ public class JPasswordDialog extends JDialog {
      * The default is a localized string.
      *
      * @param pass label for the password field.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public void setPassLabel(String pass){
+    public void setPassLabel(String pass) {
         this.passLabel.setText(pass);
         pack();
     }
@@ -166,11 +160,10 @@ public class JPasswordDialog extends JDialog {
      * the dialog was closed.
      *
      * @return the name from the name field.
-     *
      * @since ostermillerutils 1.00.00
      */
     @Override
-    public String getName(){
+    public String getName() {
         return name.getText();
     }
 
@@ -179,10 +172,9 @@ public class JPasswordDialog extends JDialog {
      * the dialog was closed.
      *
      * @return the password from the password field.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public String getPass(){
+    public String getPass() {
         return new String(pass.getPassword());
     }
 
@@ -194,10 +186,9 @@ public class JPasswordDialog extends JDialog {
      * are not.
      *
      * @return true if the the user hit OK, false if the user canceled.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public boolean okPressed(){
+    public boolean okPressed() {
         return pressed_OK;
     }
 
@@ -212,8 +203,7 @@ public class JPasswordDialog extends JDialog {
      * Create this dialog with the given parent and title.
      *
      * @param parent window from which this dialog is launched
-     * @param title the title for the dialog box window
-     *
+     * @param title  the title for the dialog box window
      * @since ostermillerutils 1.00.00
      */
     public JPasswordDialog(Frame parent, String title) {
@@ -221,10 +211,10 @@ public class JPasswordDialog extends JDialog {
         super(parent, title, true);
 
 
-        if (title==null){
+        if (title == null) {
             setTitle(labels.getString("dialog.title"));
         }
-        if (parent != null){
+        if (parent != null) {
             setLocationRelativeTo(parent);
         }
         // super calls dialogInit, so we don't need to do it again.
@@ -234,7 +224,6 @@ public class JPasswordDialog extends JDialog {
      * Create this dialog with the given parent and the default title.
      *
      * @param parent window from which this dialog is launched
-     *
      * @since ostermillerutils 1.00.00
      */
     public JPasswordDialog(Frame parent) {
@@ -256,7 +245,7 @@ public class JPasswordDialog extends JDialog {
      * @since ostermillerutils 1.00.00
      */
     @Override
-    protected void dialogInit(){
+    protected void dialogInit() {
 
 
         name = new JTextField("", 20);
@@ -269,15 +258,15 @@ public class JPasswordDialog extends JDialog {
 
         KeyListener keyListener = (new KeyAdapter() {
             @Override
-            public void keyPressed(KeyEvent e){
+            public void keyPressed(KeyEvent e) {
                 if (e.getKeyCode() == KeyEvent.VK_ESCAPE ||
                         (e.getSource() == cancelButton
-                        && e.getKeyCode() == KeyEvent.VK_ENTER)){
+                                && e.getKeyCode() == KeyEvent.VK_ENTER)) {
                     pressed_OK = false;
                     JPasswordDialog.this.hide();
                 }
                 if (e.getSource() == okButton &&
-                        e.getKeyCode() == KeyEvent.VK_ENTER){
+                        e.getKeyCode() == KeyEvent.VK_ENTER) {
                     pressed_OK = true;
                     JPasswordDialog.this.hide();
                 }
@@ -287,9 +276,9 @@ public class JPasswordDialog extends JDialog {
 
         ActionListener actionListener = new ActionListener() {
             @Override
-            public void actionPerformed(ActionEvent e){
+            public void actionPerformed(ActionEvent e) {
                 Object source = e.getSource();
-                if (source == name){
+                if (source == name) {
                     // the user pressed enter in the name field.
                     name.transferFocus();
                 } else {
@@ -348,10 +337,9 @@ public class JPasswordDialog extends JDialog {
      * Shows the dialog and returns true if the user pressed ok.
      *
      * @return true if the the user hit OK, false if the user canceled.
-     *
      * @since ostermillerutils 1.00.00
      */
-    public boolean showDialog(){
+    public boolean showDialog() {
         show();
         return okPressed();
     }
@@ -362,18 +350,17 @@ public class JPasswordDialog extends JDialog {
      * is treated as the default name, the second as the default password
      *
      * @param args command line arguments: name and password (optional)
-     *
      * @since ostermillerutils 1.00.00
      */
-    private static void main(String[] args){
+    private static void main(String[] args) {
         JPasswordDialog p = new JPasswordDialog();
-        if(args.length > 0){
+        if (args.length > 0) {
             p.setName(args[0]);
         }
-        if(args.length > 1){
+        if (args.length > 1) {
             p.setPass(args[1]);
         }
-        if(p.showDialog()){
+        if (p.showDialog()) {
             System.out.println("Name: " + p.getName());
             System.out.println("Pass: " + p.getPass());
         } else {
diff --git a/src/eva2/tools/JarResources.java b/src/eva2/tools/JarResources.java
index 6c9f6c83..46ba8464 100644
--- a/src/eva2/tools/JarResources.java
+++ b/src/eva2/tools/JarResources.java
@@ -5,13 +5,14 @@ package eva2.tools;
  * Copyright:    Copyright (c) 2003
  * Company:      University of Tuebingen, Computer Architecture
  * @author Holger Ulmer, Felix Streichert, Hannes Planatscher
- * @version:  $Revision: 10 $
+ * @version: $Revision: 10 $
  *            $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $
  *            $Author: streiche $
  */
 /*==========================================================================*
  * IMPORTS
  *==========================================================================*/
+
 import java.io.*;
 import java.util.*;
 import java.util.zip.*;
@@ -23,156 +24,159 @@ import java.util.zip.*;
  */
 public final class JarResources {
 
-   // external debug flag
-   public boolean debugOn=false;
+    // external debug flag
+    public boolean debugOn = false;
 
-   // jar resource mapping tables
-   private Hashtable htSizes=new Hashtable();
-   private Hashtable htJarContents=new Hashtable();
+    // jar resource mapping tables
+    private Hashtable htSizes = new Hashtable();
+    private Hashtable htJarContents = new Hashtable();
 
-   // a jar file
-   private String jarFileName;
+    // a jar file
+    private String jarFileName;
 
-   /**
-    * creates a JarResources. It extracts all resources from a Jar
-    * into an internal hashtable, keyed by resource names.
-    * @param jarFileName a jar or zip file
-    */
-   public JarResources(String jarFileName) {
-      this.jarFileName=jarFileName;
-      init();
-   }
+    /**
+     * creates a JarResources. It extracts all resources from a Jar
+     * into an internal hashtable, keyed by resource names.
+     *
+     * @param jarFileName a jar or zip file
+     */
+    public JarResources(String jarFileName) {
+        this.jarFileName = jarFileName;
+        init();
+    }
 
-   /**
-    * Extracts a jar resource as a blob.
-    * @param name a resource name.
-    */
-   public byte[] getResource(String name) {
-      return (byte[])htJarContents.get(name);
-   }
+    /**
+     * Extracts a jar resource as a blob.
+     *
+     * @param name a resource name.
+     */
+    public byte[] getResource(String name) {
+        return (byte[]) htJarContents.get(name);
+    }
 
-   /**
-    * initializes internal hash tables with Jar file resources.
-    */
-   private void init() {
-      try {
-          // extracts just sizes only.
-          ZipFile zf=new ZipFile(jarFileName);
-          Enumeration e=zf.entries();
-          while (e.hasMoreElements()) {
-              ZipEntry ze=(ZipEntry)e.nextElement();
-              if (debugOn) {
-                 System.out.println(dumpZipEntry(ze));
-              }
-              htSizes.put(ze.getName(),new Integer((int)ze.getSize()));
-          }
-          zf.close();
+    /**
+     * initializes internal hash tables with Jar file resources.
+     */
+    private void init() {
+        try {
+            // extracts just sizes only.
+            ZipFile zf = new ZipFile(jarFileName);
+            Enumeration e = zf.entries();
+            while (e.hasMoreElements()) {
+                ZipEntry ze = (ZipEntry) e.nextElement();
+                if (debugOn) {
+                    System.out.println(dumpZipEntry(ze));
+                }
+                htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
+            }
+            zf.close();
 
-          // extract resources and put them into the hashtable.
-          FileInputStream fis=new FileInputStream(jarFileName);
-          BufferedInputStream bis=new BufferedInputStream(fis);
-          ZipInputStream zis=new ZipInputStream(bis);
-          ZipEntry ze=null;
-          while ((ze=zis.getNextEntry())!=null) {
-             if (ze.isDirectory()) {
-                continue;
-             }
-             if (debugOn) {
-                System.out.println(
-                   "ze.getName()="+ze.getName()+","+"getSize()="+ze.getSize()
-                   );
-             }
-             int size=(int)ze.getSize();
-             // -1 means unknown size.
-             if (size==-1) {
-                size=((Integer)htSizes.get(ze.getName())).intValue();
-             }
-             byte[] b=new byte[(int)size];
-             int rb=0;
-             int chunk=0;
-             while (((int)size - rb) > 0) {
-                 chunk=zis.read(b,rb,(int)size - rb);
-                 if (chunk==-1) {
-                    break;
-                 }
-                 rb+=chunk;
-             }
-             // add to internal resource hashtable
-             htJarContents.put(ze.getName(),b);
-             if (debugOn) {
-                System.out.println(
-                   ze.getName()+"  rb="+rb+
-                   ",size="+size+
-                   ",csize="+ze.getCompressedSize()
-                   );
-             }
-          }
-       } catch (NullPointerException e) {
-          System.out.println("done.");
-       } catch (FileNotFoundException e) {
-          e.printStackTrace();
-       } catch (IOException e) {
-          e.printStackTrace();
-       }
-   }
+            // extract resources and put them into the hashtable.
+            FileInputStream fis = new FileInputStream(jarFileName);
+            BufferedInputStream bis = new BufferedInputStream(fis);
+            ZipInputStream zis = new ZipInputStream(bis);
+            ZipEntry ze = null;
+            while ((ze = zis.getNextEntry()) != null) {
+                if (ze.isDirectory()) {
+                    continue;
+                }
+                if (debugOn) {
+                    System.out.println(
+                            "ze.getName()=" + ze.getName() + "," + "getSize()=" + ze.getSize()
+                    );
+                }
+                int size = (int) ze.getSize();
+                // -1 means unknown size.
+                if (size == -1) {
+                    size = ((Integer) htSizes.get(ze.getName())).intValue();
+                }
+                byte[] b = new byte[(int) size];
+                int rb = 0;
+                int chunk = 0;
+                while (((int) size - rb) > 0) {
+                    chunk = zis.read(b, rb, (int) size - rb);
+                    if (chunk == -1) {
+                        break;
+                    }
+                    rb += chunk;
+                }
+                // add to internal resource hashtable
+                htJarContents.put(ze.getName(), b);
+                if (debugOn) {
+                    System.out.println(
+                            ze.getName() + "  rb=" + rb +
+                                    ",size=" + size +
+                                    ",csize=" + ze.getCompressedSize()
+                    );
+                }
+            }
+        } catch (NullPointerException e) {
+            System.out.println("done.");
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
 
-   /**
-    * Dumps a zip entry into a string.
-    * @param ze a ZipEntry
-    */
-   private String dumpZipEntry(ZipEntry ze) {
-       StringBuffer sb=new StringBuffer();
-       if (ze.isDirectory()) {
-          sb.append("d ");
-       } else {
-          sb.append("f ");
-       }
-       if (ze.getMethod()==ZipEntry.STORED) {
-          sb.append("stored   ");
-       } else {
-          sb.append("defalted ");
-       }
-       sb.append(ze.getName());
-       sb.append("\t");
-       sb.append(""+ze.getSize());
-       if (ze.getMethod()==ZipEntry.DEFLATED) {
-          sb.append("/"+ze.getCompressedSize());
-       }
-       return (sb.toString());
-   }
+    /**
+     * Dumps a zip entry into a string.
+     *
+     * @param ze a ZipEntry
+     */
+    private String dumpZipEntry(ZipEntry ze) {
+        StringBuffer sb = new StringBuffer();
+        if (ze.isDirectory()) {
+            sb.append("d ");
+        } else {
+            sb.append("f ");
+        }
+        if (ze.getMethod() == ZipEntry.STORED) {
+            sb.append("stored   ");
+        } else {
+            sb.append("defalted ");
+        }
+        sb.append(ze.getName());
+        sb.append("\t");
+        sb.append("" + ze.getSize());
+        if (ze.getMethod() == ZipEntry.DEFLATED) {
+            sb.append("/" + ze.getCompressedSize());
+        }
+        return (sb.toString());
+    }
 
-   /**
-    * Is a test driver. Given a jar file and a resource name, it trys to
-    * extract the resource and then tells us whether it could or not.
-    *
-    * Example
-    * Let's say you have a JAR file which jarred up a bunch of gif image
-    * files. Now, by using JarResources, you could extract, create, and display
-    * those images on-the-fly.
-    * 
-    *     ...
-    *     JarResources JR=new JarResources("GifBundle.jar");
-    *     Image image=Toolkit.createImage(JR.getResource("logo.gif");
-    *     Image logo=Toolkit.getDefaultToolkit().createImage(
-    *                   JR.getResources("logo.gif")
-    *                   );
-    *     ...
-    * 
- */ - public static void main(String[] args) throws IOException { - if (args.length!=2) { - System.err.println( - "usage: java JarResources " - ); - System.exit(1); - } - JarResources jr=new JarResources(args[0]); - byte[] buff=jr.getResource(args[1]); - if (buff==null) { - System.out.println("Could not find "+args[1]+"."); - } else { - System.out.println("Found "+args[1]+ " (length="+buff.length+")."); - } - } + /** + * Is a test driver. Given a jar file and a resource name, it trys to + * extract the resource and then tells us whether it could or not. + *

+ * Example + * Let's say you have a JAR file which jarred up a bunch of gif image + * files. Now, by using JarResources, you could extract, create, and display + * those images on-the-fly. + *

+     *     ...
+     *     JarResources JR=new JarResources("GifBundle.jar");
+     *     Image image=Toolkit.createImage(JR.getResource("logo.gif");
+     *     Image logo=Toolkit.getDefaultToolkit().createImage(
+     *                   JR.getResources("logo.gif")
+     *                   );
+     *     ...
+     * 
+ */ + public static void main(String[] args) throws IOException { + if (args.length != 2) { + System.err.println( + "usage: java JarResources " + ); + System.exit(1); + } + JarResources jr = new JarResources(args[0]); + byte[] buff = jr.getResource(args[1]); + if (buff == null) { + System.out.println("Could not find " + args[1] + "."); + } else { + System.out.println("Found " + args[1] + " (length=" + buff.length + ")."); + } + } -} // End of JarResources class. +} // End of JarResources class. diff --git a/src/eva2/tools/KMEANSJAVA.java b/src/eva2/tools/KMEANSJAVA.java index cf5e87c8..95e28f5b 100644 --- a/src/eva2/tools/KMEANSJAVA.java +++ b/src/eva2/tools/KMEANSJAVA.java @@ -5,158 +5,169 @@ package eva2.tools; * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 10 $ + * @version: $Revision: 10 $ * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ /*==========================================================================* * IMPORTS *==========================================================================*/ + import eva2.tools.math.RNG; + import java.util.Comparator; + /** * */ public class KMEANSJAVA { - static public boolean TRACE = false; - protected double[][] m_C; - protected int[] m_IDX; - /** - * - */ - public double[][] getC() { - return m_C; - } - /** - * - */ - public int[] getIDX() { - return m_IDX; - } - /** - * - */ - private double dist (double[] x1,double[] x2) { - double ret = 0; - for (int i=0;isamples.length) { - K = samples.length; - } - int counter=0; - m_C = new double[K][]; - for (int i=0;idist(samples[i],m_C[j])) { - mindist=dist(samples[i],m_C[j]); - index_nc = j; - } + if (K > samples.length) { + K = samples.length; } - m_IDX[i] = index_nc; - } - // determine m_IDX end ! - // determine the new centers - for (int indexofc=0;indexofc x2 ) { - return -1; - } - if (x1 <= x2 ) { - return 1; - } - return 0; - } - /** - * - */ + public int compare(Object p1, Object p2) { + int x1 = ((Cluster) p1).m_SamplesInCluster; + int x2 = ((Cluster) p2).m_SamplesInCluster; + if (x1 > x2) { + return -1; + } + if (x1 <= x2) { + return 1; + } + return 0; + } + + /** + * + */ @Override - public boolean equals (Object x) { - return false; - } + public boolean equals(Object x) { + return false; + } } \ No newline at end of file diff --git a/src/eva2/tools/MultirunRefiner.java b/src/eva2/tools/MultirunRefiner.java index a199b400..89fde44a 100644 --- a/src/eva2/tools/MultirunRefiner.java +++ b/src/eva2/tools/MultirunRefiner.java @@ -12,84 +12,88 @@ import java.io.*; import java.util.*; import javax.swing.*; -/** MultirunRefiner +/** + * MultirunRefiner * Description: This is a small programm . * Copyright: Copyright (c) 2001 * Company: University of Tuebingen, Computer Architecture - * @author Felix Streichert - * @version: $Revision: 10 $ - * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ - * $Author: streiche $ - * @since JDK 1.3.0_02 + * + * @author Felix Streichert + * @version: $Revision: 10 $ + * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ + * $Author: streiche $ + * @since JDK 1.3.0_02 */ public class MultirunRefiner { - private JFrame m_Frame; - private JPanel myPanel, myJButtonJPanel; - private JButton refineJButton, exitJButton; -// private JButton confidenceJButton; - private JTextArea m_InputText, m_OutputText; - private JScrollPane m_SP1, m_SP2; - private JMenuBar m_MenuBar; - private JMenu m_FileJMenu; - private JMenuItem m_LoadExpItem, m_SaveExpItem; - private JMenuItem m_ExitItem; - - /** Creates a new instance of MultirunRefiner */ + private JFrame m_Frame; + private JPanel myPanel, myJButtonJPanel; + private JButton refineJButton, exitJButton; + // private JButton confidenceJButton; + private JTextArea m_InputText, m_OutputText; + private JScrollPane m_SP1, m_SP2; + private JMenuBar m_MenuBar; + private JMenu m_FileJMenu; + private JMenuItem m_LoadExpItem, m_SaveExpItem; + private JMenuItem m_ExitItem; + + /** + * Creates a new instance of MultirunRefiner + */ public MultirunRefiner() { } - + public MultirunRefiner(File f) { - starter(); - if (!readFile(f)) { + starter(); + if (!readFile(f)) { System.err.println("Error, couldnt open file " + f); } } - + public MultirunRefiner(String fileName) { - starter(); - File f=new File(fileName); - if (!readFile(f)) { + starter(); + File f = new File(fileName); + if (!readFile(f)) { System.err.println("Error, couldnt open file " + f); } } public MultirunRefiner(String text, int numRuns) { - starter(); - m_InputText.setText(text); + starter(); + m_InputText.setText(text); } - + public void starter() { this.m_Frame = new JFrame("MultirunRefiner\u2122"); // The menuebar - this.m_MenuBar = new JMenuBar(); - this.m_FileJMenu = new JMenu("File"); - this.m_LoadExpItem = new JMenuItem("Load"); - this.m_LoadExpItem.setEnabled(true); - this.m_LoadExpItem.addActionListener(new ActionListener() { + this.m_MenuBar = new JMenuBar(); + this.m_FileJMenu = new JMenu("File"); + this.m_LoadExpItem = new JMenuItem("Load"); + this.m_LoadExpItem.setEnabled(true); + this.m_LoadExpItem.addActionListener(new ActionListener() { @Override - public void actionPerformed(ActionEvent ev) { - loadFile(); - } - }); - this.m_SaveExpItem = new JMenuItem("Save"); - this.m_SaveExpItem.setEnabled(true); - this.m_SaveExpItem.addActionListener (new java.awt.event.ActionListener () { + public void actionPerformed(ActionEvent ev) { + loadFile(); + } + }); + this.m_SaveExpItem = new JMenuItem("Save"); + this.m_SaveExpItem.setEnabled(true); + this.m_SaveExpItem.addActionListener(new java.awt.event.ActionListener() { @Override - public void actionPerformed (java.awt.event.ActionEvent evt) { - writeFile(); - } - }); - this.m_ExitItem = new JMenuItem("Exit"); - this.m_ExitItem.setEnabled(true); - this.m_ExitItem.addActionListener (new java.awt.event.ActionListener () { + public void actionPerformed(java.awt.event.ActionEvent evt) { + writeFile(); + } + }); + this.m_ExitItem = new JMenuItem("Exit"); + this.m_ExitItem.setEnabled(true); + this.m_ExitItem.addActionListener(new java.awt.event.ActionListener() { @Override - public void actionPerformed (java.awt.event.ActionEvent evt) { - System.exit(0); - } - }); + public void actionPerformed(java.awt.event.ActionEvent evt) { + System.exit(0); + } + }); this.m_FileJMenu.add(this.m_LoadExpItem); this.m_FileJMenu.add(this.m_SaveExpItem); @@ -97,17 +101,17 @@ public class MultirunRefiner { this.m_MenuBar.add(this.m_ExitItem); this.m_Frame.setJMenuBar(this.m_MenuBar); - this.m_Frame.setSize(300,300); + this.m_Frame.setSize(300, 300); this.m_Frame.setLocation(0, 150); this.m_Frame.addWindowListener(new WindowAdapter() { @Override - public void windowClosing(WindowEvent ev) { - System.exit(0); - } + public void windowClosing(WindowEvent ev) { + System.exit(0); + } }); this.myPanel = new JPanel(); - this.myPanel.setLayout(new GridLayout(1,2)); + this.myPanel.setLayout(new GridLayout(1, 2)); this.m_InputText = new JTextArea(); this.m_OutputText = new JTextArea(); this.m_SP1 = new JScrollPane(this.m_InputText); @@ -116,14 +120,14 @@ public class MultirunRefiner { this.myPanel.add(this.m_SP2); this.m_Frame.getContentPane().add(this.myPanel, BorderLayout.CENTER); - this.myJButtonJPanel = new JPanel(); + this.myJButtonJPanel = new JPanel(); this.myJButtonJPanel.setLayout(new GridLayout(2, 2)); this.m_Frame.getContentPane().add(this.myJButtonJPanel, BorderLayout.SOUTH); refineJButton = new JButton("Refine Multiruns"); - refineJButton.addMouseListener (new java.awt.event.MouseAdapter () { + refineJButton.addMouseListener(new java.awt.event.MouseAdapter() { @Override - public void mouseClicked (java.awt.event.MouseEvent evt) { + public void mouseClicked(java.awt.event.MouseEvent evt) { m_OutputText.setText(refineToText(refine(m_InputText.getText()))); } }); @@ -134,10 +138,10 @@ public class MultirunRefiner { // } // }); exitJButton = new JButton("EXIT"); - exitJButton.addMouseListener (new java.awt.event.MouseAdapter () { + exitJButton.addMouseListener(new java.awt.event.MouseAdapter() { @Override - public void mouseClicked (java.awt.event.MouseEvent evt) { - System.exit (0); + public void mouseClicked(java.awt.event.MouseEvent evt) { + System.exit(0); } }); this.myJButtonJPanel.add(refineJButton); @@ -148,7 +152,8 @@ public class MultirunRefiner { m_Frame.setVisible(true); } - /** This method lets you select a file that is then opened and + /** + * This method lets you select a file that is then opened and * displayed. */ public void loadFile() { @@ -157,7 +162,7 @@ public class MultirunRefiner { fc.setFileFilter(new TXTFileFilter()); int returnVal = fc.showDialog(this.m_Frame, "Load Multirun.TXT"); if (returnVal == 0) { - readFile(fc.getSelectedFile()); + readFile(fc.getSelectedFile()); this.m_Frame.validate(); } } @@ -165,18 +170,18 @@ public class MultirunRefiner { protected boolean readFile(File f) { FileReader fileStream; clearInputText(); - try { - fileStream = new FileReader(f); - this.m_InputText.read( fileStream, f); - return true; - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - clearInputText(); - return false; - } + try { + fileStream = new FileReader(f); + this.m_InputText.read(fileStream, f); + return true; + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + clearInputText(); + return false; + } } - + public void clearInputText() { this.m_InputText.setText(""); } @@ -186,10 +191,11 @@ public class MultirunRefiner { } public void addOutputText(String t) { - this.m_OutputText.setText(this.m_OutputText.getText()+t); + this.m_OutputText.setText(this.m_OutputText.getText() + t); } - /** This method lets you select a destination file to save the + /** + * This method lets you select a destination file to save the * current XML document */ private void writeFile() { @@ -203,102 +209,105 @@ public class MultirunRefiner { try { FileWriter fileStream = new FileWriter(fc.getSelectedFile()); this.m_OutputText.write(fileStream); - } catch (java.io.IOException ioe) {} + } catch (java.io.IOException ioe) { + } } } protected static boolean hasNextLine(String txt) { - return (txt != null && (txt.length() > 0)); + return (txt != null && (txt.length() > 0)); } - + protected static String readLine(BufferedReader br) { - String line; - try { - line = br.readLine(); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - return line; + String line; + try { + line = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + return line; } - - /** This method will refine multiple run into on mean element + + /** + * This method will refine multiple run into on mean element */ public static ArrayList refine(String text) { - double[] tmp; - double[] mean = new double[3]; - int numExp = 0, iteration = 0, lineCnt = 0; - ArrayList result = new ArrayList(); + double[] tmp; + double[] mean = new double[3]; + int numExp = 0, iteration = 0, lineCnt = 0; + ArrayList result = new ArrayList(); String line; String runHeader = "Fun.calls Best Mean Worst Solution"; String runFinalizer = " Best solution: "; boolean readRun = false; - + BufferedReader br = new BufferedReader(new StringReader(text)); - + while ((line = readLine(br)) != null) { // Pair p = popNextLine(text); - lineCnt++; + lineCnt++; // line = p.car(); // text = p.cdr(); - if (line.startsWith(runHeader)) { - numExp++; - readRun = true; - iteration = 0; - System.out.println("Experiment starts at line " + lineCnt); - continue; - } else if (line.startsWith(runFinalizer)) { - System.out.println("Experiment ends at line " + lineCnt); - readRun = false; - continue; - } - if (readRun) { - tmp = parseStringForDouble(line); - if (tmp.length > 3) { - if (numExp==1) { - mean = new double[3]; - result.add(iteration, mean); - } else { - mean = result.get(iteration); - } - mean[0] += tmp[1]; - mean[1] += tmp[2]; - mean[2] += tmp[3]; - } else { - System.err.println("Error in MultiRunRefiner!"); + if (line.startsWith(runHeader)) { + numExp++; + readRun = true; + iteration = 0; + System.out.println("Experiment starts at line " + lineCnt); + continue; + } else if (line.startsWith(runFinalizer)) { + System.out.println("Experiment ends at line " + lineCnt); + readRun = false; + continue; + } + if (readRun) { + tmp = parseStringForDouble(line); + if (tmp.length > 3) { + if (numExp == 1) { + mean = new double[3]; + result.add(iteration, mean); + } else { + mean = result.get(iteration); } - iteration++; - } + mean[0] += tmp[1]; + mean[1] += tmp[2]; + mean[2] += tmp[3]; + } else { + System.err.println("Error in MultiRunRefiner!"); + } + iteration++; + } } System.out.println(lineCnt + " lines parsed. " + numExp + " experiments with " + result.size() + " events each."); - for(int i = 0; i < result.size(); i++) { - mean = ((double[])(result.get(i))); - for (int k=0; k result) { - double[] mean; - StringBuffer sbuf = new StringBuffer("Event\tBest\tMean\tWorst\n"); - - for(int i = 0; i < result.size(); i++) { - mean = ((double[])(result.get(i))); - sbuf.append(i+"\t"+mean[0]+"\t"+mean[1]+"\t"+mean[2]+"\n"); + double[] mean; + StringBuffer sbuf = new StringBuffer("Event\tBest\tMean\tWorst\n"); + + for (int i = 0; i < result.size(); i++) { + mean = ((double[]) (result.get(i))); + sbuf.append(i + "\t" + mean[0] + "\t" + mean[1] + "\t" + mean[2] + "\n"); } return sbuf.toString(); } - + public static String refineToText(String input) { - return refineToText(refine(input)); + return refineToText(refine(input)); } - + // public void compute() { // double[] tmp; // double[] mean = new double[3]; @@ -329,57 +338,60 @@ public class MultirunRefiner { // } // } - /** A simple method to read doubles from a string. - * @param String The string to be searched. - * @return The array of doubles found. + /** + * A simple method to read doubles from a string. + * + * @param String The string to be searched. + * @return The array of doubles found. */ - public static double[] parseStringForDouble (String searchme) { - double [] output; - Vector tmpOutput; - int positionInString = 0, from, to, i, tmp; - boolean EndOfStringReached = false; - String tmpString; - char tmpchar; + public static double[] parseStringForDouble(String searchme) { + double[] output; + Vector tmpOutput; + int positionInString = 0, from, to, i, tmp; + boolean EndOfStringReached = false; + String tmpString; + char tmpchar; // because new Double(tmpString) does not regonize 2,3 as float(double) i need to replace ','=>'.' if ((searchme.startsWith("calls")) || (searchme == null)) { output = new double[0]; return output; } - searchme = searchme.replace(',', '.'); - tmpOutput = new Vector(10); - from = positionInString; - to = positionInString; + searchme = searchme.replace(',', '.'); + tmpOutput = new Vector(10); + from = positionInString; + to = positionInString; i = 0; while (to < searchme.length()) { - while ((to < searchme.length()-1) && (searchme.charAt(to) != 9) &&(! Character.isSpaceChar(searchme.charAt(to))) && (searchme.charAt(to) != '\n')) { + while ((to < searchme.length() - 1) && (searchme.charAt(to) != 9) && (!Character.isSpaceChar(searchme.charAt(to))) && (searchme.charAt(to) != '\n')) { tmp = searchme.charAt(to); to++; } if (to < searchme.length()) { - if (to == searchme.length()-1) { + if (to == searchme.length() - 1) { to = searchme.length(); } tmpString = searchme.substring(from, to); try { tmpOutput.add(i, new Double(tmpString)); - i ++; + i++; } catch (java.lang.NumberFormatException e) { } } to++; from = to; } - output = new double[i]; + output = new double[i]; for (int j = 0; j < i; j++) { - output[j] = ((Double)tmpOutput.elementAt(j)).doubleValue(); + output[j] = ((Double) tmpOutput.elementAt(j)).doubleValue(); } return output; } + /** - * A example for a standalone GO optimization. + * A example for a standalone GO optimization. */ - public static void main (String[] x) { + public static void main(String[] x) { MultirunRefiner universalprogram = new MultirunRefiner(); universalprogram.starter(); } diff --git a/src/eva2/tools/Pair.java b/src/eva2/tools/Pair.java index f9a6af2d..58e5d890 100644 --- a/src/eva2/tools/Pair.java +++ b/src/eva2/tools/Pair.java @@ -4,129 +4,121 @@ import java.io.Serializable; /** * Simple pair structure of two types, Scheme style, but typed. - * + * * @author mkron - * */ public class Pair implements Serializable { - /** - * - */ - private static final long serialVersionUID = -3620465393975181451L; - public S head; - public T tail; + /** + * + */ + private static final long serialVersionUID = -3620465393975181451L; + public S head; + public T tail; - /** - * - * @param head - * @param tail - */ - public Pair(S head, T tail) { - this.head = head; - this.tail = tail; - } + /** + * @param head + * @param tail + */ + public Pair(S head, T tail) { + this.head = head; + this.tail = tail; + } - public Pair() { - } - /** - * - * @return - */ - public S car() { - return head; - } + public Pair() { + } - /** - * - * @return - */ - public T cdr() { - return tail; - } + /** + * @return + */ + public S car() { + return head; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#clone() - */ + /** + * @return + */ + public T cdr() { + return tail; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#clone() + */ @Override - public Pair clone() { - return new Pair(head, tail); - } + public Pair clone() { + return new Pair(head, tail); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return toString().hashCode(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return toString().hashCode(); + } - /** - * - * @return - */ - public S head() { - return head; - } - - /** - * - * @return - */ - public S getHead() { - return head; - } - - public String headTipText() { - return "First pair entry"; - } - - /** - * - * @return - */ - public T tail() { - return tail; - } + /** + * @return + */ + public S head() { + return head; + } - public T getTail() { - return tail; - } - - public String tailTipText() { - return "Last pair entry"; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "(" + head.toString() + "," + tail.toString() + ")"; - } + /** + * @return + */ + public S getHead() { + return head; + } - public String getName() { - return this.toString(); - } - - /** - * - * @param head - */ - public void setHead(S head) { - this.head = head; - } + public String headTipText() { + return "First pair entry"; + } - /** - * - * @param tail - */ - public void setTail(T tail) { - this.tail = tail; - } + /** + * @return + */ + public T tail() { + return tail; + } + + public T getTail() { + return tail; + } + + public String tailTipText() { + return "Last pair entry"; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "(" + head.toString() + "," + tail.toString() + ")"; + } + + public String getName() { + return this.toString(); + } + + /** + * @param head + */ + public void setHead(S head) { + this.head = head; + } + + /** + * @param tail + */ + public void setTail(T tail) { + this.tail = tail; + } } \ No newline at end of file diff --git a/src/eva2/tools/PairComparator.java b/src/eva2/tools/PairComparator.java index 66034256..b469cbf3 100644 --- a/src/eva2/tools/PairComparator.java +++ b/src/eva2/tools/PairComparator.java @@ -1,46 +1,45 @@ package eva2.tools; import eva2.gui.BeanInspector; + import java.util.Comparator; -public class PairComparator implements Comparator> { - boolean useHead = true; - - /** - * A constructor. Set useHd to true to compare based on the head, otherwise - * based on the tail. - */ - public PairComparator(boolean useHd) { - useHead = useHead; - } - - /** - * Compare two Pairs of which head or tail is a primitive type that - * can be converted to double. - * Return 1 if the first is larger, -1 if the second is larger, 0 if they - * are equal or not comparable. - */ +public class PairComparator implements Comparator> { + boolean useHead = true; + + /** + * A constructor. Set useHd to true to compare based on the head, otherwise + * based on the tail. + */ + public PairComparator(boolean useHd) { + useHead = useHead; + } + + /** + * Compare two Pairs of which head or tail is a primitive type that + * can be converted to double. + * Return 1 if the first is larger, -1 if the second is larger, 0 if they + * are equal or not comparable. + */ @Override - public int compare(Pair o1, Pair o2) { - Pair p1=(Pair)o1; - Pair p2=(Pair)o2; - double d1, d2; - try { - d1=BeanInspector.toDouble(useHead ? p1.head() : p1.tail()); - d2=BeanInspector.toDouble(useHead ? p2.head() : p2.tail()); - } catch (IllegalArgumentException e) { - System.err.println("Error, mismatching types, thus uncomparable Pairs: " + p1.toString() + " / " + p2.toString()); - return 0; - } - - if (d1==d2) { - return 0; - } - else if (d1 > d2) { - return 1; - } - else { - return -1; - } - } + public int compare(Pair o1, Pair o2) { + Pair p1 = (Pair) o1; + Pair p2 = (Pair) o2; + double d1, d2; + try { + d1 = BeanInspector.toDouble(useHead ? p1.head() : p1.tail()); + d2 = BeanInspector.toDouble(useHead ? p2.head() : p2.tail()); + } catch (IllegalArgumentException e) { + System.err.println("Error, mismatching types, thus uncomparable Pairs: " + p1.toString() + " / " + p2.toString()); + return 0; + } + + if (d1 == d2) { + return 0; + } else if (d1 > d2) { + return 1; + } else { + return -1; + } + } } diff --git a/src/eva2/tools/ReflectPackage.java b/src/eva2/tools/ReflectPackage.java index 32709881..710c84da 100644 --- a/src/eva2/tools/ReflectPackage.java +++ b/src/eva2/tools/ReflectPackage.java @@ -1,6 +1,7 @@ package eva2.tools; import eva2.gui.BeanInspector; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -24,458 +25,456 @@ import javax.management.ObjectName; * Allow for java to list Classes that exist in one package and can be instantiated from * the classpath, either directly or through a jar on the classpath. * So far, jars which are located within another jar will not be searched. - * - * @author mkron * + * @author mkron */ public class ReflectPackage { - - final static boolean TRACE = false; - static int missedJarsOnClassPath = 0; - static boolean useFilteredClassPath = true; -// static boolean usePathMap = true; - static String[] dynCP = null; + + final static boolean TRACE = false; + static int missedJarsOnClassPath = 0; + static boolean useFilteredClassPath = true; + // static boolean usePathMap = true; + static String[] dynCP = null; // static HashMap> pathMap = new HashMap>(); - - static class ClassComparator implements Comparator { + + static class ClassComparator implements Comparator { @Override - public int compare(Object o1, Object o2) { - return (o1.toString().compareTo(o2.toString())); - } - } - - /** - * Collect classes of a given package from the file system. - * - * @param pckgname - * @return - * @throws ClassNotFoundException - */ - public static int getClassesFromFilesFltr(HashSet set, String path, String pckgname, boolean includeSubs, Class reqSuperCls) { - try { - // Get a File object for the package - File directory = null; - String dir = null; - try { - ClassLoader cld = ClassLoader.getSystemClassLoader(); - if (cld == null) { - throw new ClassNotFoundException("Can't get class loader."); - } - dir = path + "/" + pckgname.replace(".","/"); + public int compare(Object o1, Object o2) { + return (o1.toString().compareTo(o2.toString())); + } + } - if (TRACE) { - System.out.println(".. opening " + path); - } + /** + * Collect classes of a given package from the file system. + * + * @param pckgname + * @return + * @throws ClassNotFoundException + */ + public static int getClassesFromFilesFltr(HashSet set, String path, String pckgname, boolean includeSubs, Class reqSuperCls) { + try { + // Get a File object for the package + File directory = null; + String dir = null; + try { + ClassLoader cld = ClassLoader.getSystemClassLoader(); + if (cld == null) { + throw new ClassNotFoundException("Can't get class loader."); + } + dir = path + "/" + pckgname.replace(".", "/"); - directory = new File(dir); + if (TRACE) { + System.out.println(".. opening " + path); + } + + directory = new File(dir); + + } catch (NullPointerException x) { + if (TRACE) { + System.err.println(directory.getPath() + " not found in " + path); + System.err.println("directory " + (directory.exists() ? "exists" : "doesnt exist")); + } + return 0; + } + if (directory.exists()) { + // Get the list of the files contained in the package + return getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls); + } else { + if (TRACE) { + System.err.println(directory.getPath() + " doesnt exist in " + path + ", dir was " + dir); + } + return 0; + } + } catch (ClassNotFoundException e) { + System.err.println(e.getMessage()); + e.printStackTrace(); + return 0; + } + } - } catch (NullPointerException x) { - if (TRACE) { - System.err.println(directory.getPath()+ " not found in " + path); - System.err.println("directory " + (directory.exists() ? "exists" : "doesnt exist")); - } - return 0; - } - if (directory.exists()) { - // Get the list of the files contained in the package - return getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls); - } else { - if (TRACE) { - System.err.println(directory.getPath() + " doesnt exist in " + path + ", dir was " + dir); - } - return 0; - } - } catch(ClassNotFoundException e) { - System.err.println(e.getMessage()); - e.printStackTrace(); - return 0; - } - } - // public static ArrayList getClassesFromDir(File directory, String pckgname, boolean includeSubs) { // return getClassesFromDirFltr(directory, pckgname, includeSubs, null); // } - - public static int getClassesFromDirFltr(HashSet set, File directory, String pckgname, boolean includeSubs, Class reqSuperCls) { - int cntAdded = 0; - if (directory.exists()) { - // Get the list of the files contained in the package - String[] files = directory.list(); - for (int i = 0; i < files.length; i++) { - // we are only interested in .class files - if (files[i].endsWith(".class")) { - // removes the .class extension - try { - Class cls = Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6)); - if (reqSuperCls != null) { - if (reqSuperCls.isAssignableFrom(cls)) { - cntAdded += addClass(set, cls); - } - } else { - cntAdded += addClass(set, cls); - } - } catch (Exception e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for "+pckgname+'.'+files[i]+": "+e.getMessage()); - } catch (Error e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for "+pckgname+'.'+files[i]+": "+e.getMessage()); - } - } else if (includeSubs) { - // do a recursive search over subdirs - File subDir = new File(directory.getAbsolutePath()+File.separatorChar+files[i]); - if (subDir.exists() && subDir.isDirectory()) { - cntAdded += getClassesFromDirFltr(set, subDir, pckgname+"."+files[i], includeSubs, reqSuperCls); - } - } - } - } - return cntAdded; - } - /** - * If valid classpath entries are stored but you want to reset them, use this method. The classpath - * will then be rescanned on the next request. - */ - public static void resetDynCP() { - dynCP = null; - } - - private static int addClass(HashSet set, Class cls) { - if (TRACE) { - System.out.println("adding class " + cls.getName()); - } - if (set.contains(cls)) { - System.err.println("warning, Class " + cls.getName() + " not added twice!"); - return 0; - } else { - set.add(cls); - return 1; - } - } - - public static ArrayList filterAssignableClasses(ArrayList classes, Class reqSuperCls) { - ArrayList assClasses = new ArrayList(); - for (int i=0; i set, File directory, String pckgname, boolean includeSubs, Class reqSuperCls) { + int cntAdded = 0; + if (directory.exists()) { + // Get the list of the files contained in the package + String[] files = directory.list(); + for (int i = 0; i < files.length; i++) { + // we are only interested in .class files + if (files[i].endsWith(".class")) { + // removes the .class extension + try { + Class cls = Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6)); + if (reqSuperCls != null) { + if (reqSuperCls.isAssignableFrom(cls)) { + cntAdded += addClass(set, cls); } - assClasses.add(classes.get(i)); - } - } - return assClasses; - } - - /** - * Collect classes of a given package from a jar file. - * - * @param jarName - * @param packageName - * @return - */ - public static int getClassesFromJarFltr(HashSet set, String jarName, String packageName, boolean includeSubs, Class reqSuperCls){ - boolean isInSubPackage = true; - int cntAdded = 0; - - packageName = packageName.replaceAll("\\." , "/"); - if (TRACE) { - System.out.println("Jar " + jarName + " looking for " + packageName); + } else { + cntAdded += addClass(set, cls); + } + } catch (Exception e) { + System.err.println("ReflectPackage: Couldnt get Class from jar for " + pckgname + '.' + files[i] + ": " + e.getMessage()); + } catch (Error e) { + System.err.println("ReflectPackage: Couldnt get Class from jar for " + pckgname + '.' + files[i] + ": " + e.getMessage()); + } + } else if (includeSubs) { + // do a recursive search over subdirs + File subDir = new File(directory.getAbsolutePath() + File.separatorChar + files[i]); + if (subDir.exists() && subDir.isDirectory()) { + cntAdded += getClassesFromDirFltr(set, subDir, pckgname + "." + files[i], includeSubs, reqSuperCls); + } + } } - try{ - JarInputStream jarFile = new JarInputStream - (new FileInputStream (jarName)); - JarEntry jarEntry; + } + return cntAdded; + } - while((jarEntry = jarFile.getNextJarEntry()) != null) { - String jarEntryName = jarEntry.getName(); + /** + * If valid classpath entries are stored but you want to reset them, use this method. The classpath + * will then be rescanned on the next request. + */ + public static void resetDynCP() { + dynCP = null; + } + + private static int addClass(HashSet set, Class cls) { + if (TRACE) { + System.out.println("adding class " + cls.getName()); + } + if (set.contains(cls)) { + System.err.println("warning, Class " + cls.getName() + " not added twice!"); + return 0; + } else { + set.add(cls); + return 1; + } + } + + public static ArrayList filterAssignableClasses(ArrayList classes, Class reqSuperCls) { + ArrayList assClasses = new ArrayList(); + for (int i = 0; i < classes.size(); i++) { + if (reqSuperCls.isAssignableFrom(classes.get(i))) { + if (TRACE) { + System.out.println(" taking over " + classes.get(i)); + } + assClasses.add(classes.get(i)); + } + } + return assClasses; + } + + /** + * Collect classes of a given package from a jar file. + * + * @param jarName + * @param packageName + * @return + */ + public static int getClassesFromJarFltr(HashSet set, String jarName, String packageName, boolean includeSubs, Class reqSuperCls) { + boolean isInSubPackage = true; + int cntAdded = 0; + + packageName = packageName.replaceAll("\\.", "/"); + if (TRACE) { + System.out.println("Jar " + jarName + " looking for " + packageName); + } + try { + JarInputStream jarFile = new JarInputStream + (new FileInputStream(jarName)); + JarEntry jarEntry; + + while ((jarEntry = jarFile.getNextJarEntry()) != null) { + String jarEntryName = jarEntry.getName(); // if (TRACE) System.out.println("- " + jarEntry.getName()); - if((jarEntryName.startsWith(packageName)) && - (jarEntryName.endsWith (".class")) ) { + if ((jarEntryName.startsWith(packageName)) && + (jarEntryName.endsWith(".class"))) { // subpackages are hit here as well! - if (!includeSubs) { // check if the class belongs to a subpackage - int lastDash = jarEntryName.lastIndexOf('/'); - if (lastDash > packageName.length()+1) { - isInSubPackage = true; - } - else { - isInSubPackage = false; - } - } - if (includeSubs || !isInSubPackage) { // take the right ones - String clsName = jarEntryName.replace("/", "."); - try { - // removes the .class extension - Class cls = Class.forName(clsName.substring(0, jarEntryName.length() - 6)); - if (reqSuperCls != null) { - if (reqSuperCls.isAssignableFrom(cls)) { - cntAdded += addClass(set, cls); - } - } else { - cntAdded += addClass(set, cls); - } - } catch(Exception e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for "+clsName+": "+e.getMessage()); - } catch(Error e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for "+clsName+": "+e.getMessage()); - } - } - + if (!includeSubs) { // check if the class belongs to a subpackage + int lastDash = jarEntryName.lastIndexOf('/'); + if (lastDash > packageName.length() + 1) { + isInSubPackage = true; + } else { + isInSubPackage = false; + } + } + if (includeSubs || !isInSubPackage) { // take the right ones + String clsName = jarEntryName.replace("/", "."); + try { + // removes the .class extension + Class cls = Class.forName(clsName.substring(0, jarEntryName.length() - 6)); + if (reqSuperCls != null) { + if (reqSuperCls.isAssignableFrom(cls)) { + cntAdded += addClass(set, cls); + } + } else { + cntAdded += addClass(set, cls); + } + } catch (Exception e) { + System.err.println("ReflectPackage: Couldnt get Class from jar for " + clsName + ": " + e.getMessage()); + } catch (Error e) { + System.err.println("ReflectPackage: Couldnt get Class from jar for " + clsName + ": " + e.getMessage()); + } + } + // classes.add (jarEntry.getName().replaceAll("/", "\\.")); - } - } - } catch(IOException e) { - missedJarsOnClassPath++; - if (missedJarsOnClassPath == 0) { - System.err.println("Couldnt open jar from class path: " + e.getMessage()); - System.err.println("Dirty class path?"); - } else if (missedJarsOnClassPath == 2) { - System.err.println("Couldnt open jar from class path more than once..."); + } + } + } catch (IOException e) { + missedJarsOnClassPath++; + if (missedJarsOnClassPath == 0) { + System.err.println("Couldnt open jar from class path: " + e.getMessage()); + System.err.println("Dirty class path?"); + } else if (missedJarsOnClassPath == 2) { + System.err.println("Couldnt open jar from class path more than once..."); + } + //e.printStackTrace(); + } + return cntAdded; + } + + /** + * Collect all classes from a given package on the classpath. If includeSubs is true, + * the sub-packages are listed as well. + * + * @param pckg + * @param includeSubs + * @param bSort sort alphanumerically by class name + * @return An ArrayList of Class objects contained in the package which may be empty if an error occurs. + */ + public static Class[] getAllClassesInPackage(String pckg, boolean includeSubs, boolean bSort) { + return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, null); + } + + /** + * Collect classes from a given package on the classpath which have the given Class + * as superclass or superinterface. If includeSubs is true, + * the sub-packages are listed as well. + * + * @param pckg + * @return + * @see Class.assignableFromClass(Class cls) + */ + public static Class[] getClassesInPackageFltr(HashSet set, String pckg, boolean includeSubs, boolean bSort, Class reqSuperCls) { + String classPath = null; + if (!useFilteredClassPath || (dynCP == null)) { + classPath = System.getProperty("java.class.path", "."); + if (useFilteredClassPath) { + try { + dynCP = getValidCPArray(); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } else { + dynCP = getClassPathElements(); + } + } + + if (TRACE) { + System.out.println("classpath is " + classPath); + } + for (int i = 0; i < dynCP.length; i++) { + if (TRACE) { + System.out.println("reading element " + dynCP[i]); + } + if (dynCP[i].endsWith(".jar")) { + getClassesFromJarFltr(set, dynCP[i], pckg, includeSubs, reqSuperCls); + } else { + if (TRACE) { + System.out.println("reading from files: " + dynCP[i] + " " + pckg); + } + getClassesFromFilesFltr(set, dynCP[i], pckg, includeSubs, reqSuperCls); + } + } + Object[] clsArr = set.toArray(); + if (bSort) { + Arrays.sort(clsArr, new ClassComparator()); + } + + List list; + list = Arrays.asList(clsArr); + return (Class[]) list.toArray(new Class[list.size()]); + } + + /** + * Request a valid absolute resource path from a relative resource path + * by searching the classpath entries. Returns null if the resource is not found. + * + * @param res + */ + public static String getResourcePathFromCP(String res) { + String[] cpEntries = getClassPathElements(); + URL url = ClassLoader.getSystemResource(res); + if (TRACE) { + System.out.println(res + ((url == null) ? " not" : " was") + " found by classloader."); + } + if (url != null) { + File f; + try { + f = new File(url.toURI()); + } catch (URISyntaxException e) { + f = new File(url.getPath()); + } + return f.getPath(); + } + + File f; + String fNameSep; + if (res.startsWith(System.getProperty("file.separator"))) { + fNameSep = res; + } else { + fNameSep = System.getProperty("file.separator") + res; + } + + for (int i = 0; i < cpEntries.length; i++) { + if (!cpEntries[i].endsWith(".jar")) { // its a fs directory (hopefully) + if (TRACE) { + System.out.println("reading element " + cpEntries[i]); + } + f = new File(cpEntries[i] + fNameSep); + if (TRACE) { + System.out.println(res + ((!f.exists()) ? " not" : " was") + " found in " + cpEntries[i]); + } + if (f.exists()) { + return f.getAbsolutePath(); + } + } + } + return null; + } + + /** + * Request a valid absolute resource path from a relative resource path + * by searching the classpath entries. Returns null if the resource is not found. + * + * @param res + */ + public static InputStream getResourceStreamFromCP(String res) { + + InputStream in = BasicResourceLoader.instance().getStreamFromResourceLocation(res); + if (TRACE) { + System.out.println(res + ((in == null) ? " not" : " was") + " found by classloader."); + } + if (in != null) { + return in; + } + + String[] cpEntries = getClassPathElements(); + + File f; + String fNameSep; + if (res.startsWith(System.getProperty("file.separator"))) { + fNameSep = res; + } else { + fNameSep = System.getProperty("file.separator") + res; + } + + for (int i = 0; i < cpEntries.length; i++) { + if (!cpEntries[i].endsWith(".jar")) { // its a fs directory (hopefully) + if (TRACE) { + System.out.println("reading element " + cpEntries[i]); + } + f = new File(cpEntries[i] + fNameSep); + if (TRACE) { + System.out.println(res + ((!f.exists()) ? " not" : " was") + " found in " + cpEntries[i]); + } + if (f.exists()) { + try { + return new FileInputStream(f); + } catch (Exception e) { + System.err.println("error reading file " + f.getAbsolutePath() + ": " + e.getMessage()); } - //e.printStackTrace(); - } - return cntAdded; - } - - /** - * Collect all classes from a given package on the classpath. If includeSubs is true, - * the sub-packages are listed as well. - * - * @param pckg - * @param includeSubs - * @param bSort sort alphanumerically by class name - * @return An ArrayList of Class objects contained in the package which may be empty if an error occurs. - */ - public static Class[] getAllClassesInPackage(String pckg, boolean includeSubs, boolean bSort) { - return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, null); - } - - /** - * Collect classes from a given package on the classpath which have the given Class - * as superclass or superinterface. If includeSubs is true, - * the sub-packages are listed as well. - * - * @see Class.assignableFromClass(Class cls) - * @param pckg - * @return - */ - public static Class[] getClassesInPackageFltr(HashSet set, String pckg, boolean includeSubs, boolean bSort, Class reqSuperCls) { - String classPath = null; - if (!useFilteredClassPath || (dynCP==null)) { - classPath = System.getProperty("java.class.path","."); - if (useFilteredClassPath) { - try { - dynCP = getValidCPArray(); - } catch (Exception e) { - System.err.println(e.getMessage()); - } - } else { - dynCP = getClassPathElements(); - } - } + } + } + } + return null; + } - if (TRACE) { - System.out.println("classpath is " + classPath); - } - for (int i=0; i getValidCPEntries() { - String[] pathElements = getClassPathElements(); - File f; - ArrayList valids = new ArrayList(pathElements.length); - for (int i=0; i getValidCPEntries() { + String[] pathElements = getClassPathElements(); + File f; + ArrayList valids = new ArrayList(pathElements.length); + for (int i = 0; i < pathElements.length; i++) { // System.err.println(pathElements[i]); - f = new File(pathElements[i]); + f = new File(pathElements[i]); // if (f.canRead()) {valids.add(pathElements[i]);} - if (f.exists() && f.canRead()) { - valids.add(pathElements[i]); - } - } - return valids; - } - - public static String[] getValidCPArray() { - ArrayList valids = getValidCPEntries(); + if (f.exists() && f.canRead()) { + valids.add(pathElements[i]); + } + } + return valids; + } + + public static String[] getValidCPArray() { + ArrayList valids = getValidCPEntries(); // vp = valids.toArray(dynCP); // this causes Matlab to crash meanly. - String[] vp = new String[valids.size()]; - for (int i=0; i[] getAssignableClassesInPackage(String pckg, Class reqSuperCls, boolean includeSubs, boolean bSort) { - if (TRACE) { - System.out.println("requesting classes assignable from " + reqSuperCls.getName()); + return vp; + } + + /** + * Retrieve assignable classes of the given package from classpath given by package name and Class instance. + * + * @param pckg String denoting the package + * @param reqSuperCls + * @return + */ + public static Class[] getAssignableClassesInPackage(String pckg, Class reqSuperCls, boolean includeSubs, boolean bSort) { + if (TRACE) { + System.out.println("requesting classes assignable from " + reqSuperCls.getName()); + } + return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, reqSuperCls); + } + + /** + * Retrieve assignable classes of the given package from classpath given by full class and package String, + * such as eva2.optimization.problems.AbstractOptimizationProblem. + * + * @param pckg String denoting the package + * @param reqSuperCls + * @return + */ + public static Class[] getAssignableClasses(String pckgClassName, boolean includeSubs, boolean bSort) { + int dotIndex = pckgClassName.lastIndexOf('.'); + if (dotIndex <= 0) { + System.err.println("warning: " + pckgClassName + " is not a package!"); + return null; + } else { + String pckg = pckgClassName.substring(0, pckgClassName.lastIndexOf('.')); + Class[] clsArr; + try { + clsArr = ReflectPackage.getAssignableClassesInPackage(pckg, Class.forName(pckgClassName), includeSubs, bSort); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + clsArr = null; } - return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, reqSuperCls); - } - - /** - * Retrieve assignable classes of the given package from classpath given by full class and package String, - * such as eva2.optimization.problems.AbstractOptimizationProblem. - * - * @param pckg String denoting the package - * @param reqSuperCls - * @return - */ - public static Class[] getAssignableClasses(String pckgClassName, boolean includeSubs, boolean bSort) { - int dotIndex = pckgClassName.lastIndexOf('.'); - if (dotIndex <= 0) { - System.err.println("warning: " + pckgClassName + " is not a package!"); - return null; - } else { - String pckg = pckgClassName.substring(0, pckgClassName.lastIndexOf('.')); - Class[] clsArr; - try { - clsArr = ReflectPackage.getAssignableClassesInPackage(pckg, Class.forName(pckgClassName), includeSubs, bSort); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - clsArr = null; - } - return clsArr; - } - } - - public static void main(String[] args) { - ClassLoader cld = Thread.currentThread().getContextClassLoader(); - System.out.println("1: " + cld.getResource("/eva2/server")); - System.out.println("2: " + cld.getResource("eva2/server")); + return clsArr; + } + } + + public static void main(String[] args) { + ClassLoader cld = Thread.currentThread().getContextClassLoader(); + System.out.println("1: " + cld.getResource("/eva2/server")); + System.out.println("2: " + cld.getResource("eva2/server")); // BasicResourceLoader rld = BasicResourceLoader.instance(); // byte[] b = rld.getBytesFromResourceLocation("images/Sub24.gif"); // System.out.println((b == null) ? "null" : b.toString()); // b = rld.getBytesFromResourceLocation("src/eva2/client/SplashScreen.java"); // System.out.println((b == null) ? "null" : b.toString()); - HashSet h = new HashSet (20); - - for (int i=0; i<20; i++) { - h.add("String "+ (i%10)); - } - for (String string : h) { - System.out.println("+ "+string); - } - + HashSet h = new HashSet(20); + + for (int i = 0; i < 20; i++) { + h.add("String " + (i % 10)); + } + for (String string : h) { + System.out.println("+ " + string); + } + // String[] pathElements = getClassPathElements(); // for (int i=0; i> paramValuePairs) { - return instantiateWithParams(clsName, new Object[]{}, paramValuePairs); - } - /** - * Instantiate a class given by full name (with package) and try to set the member values given - * in the pair-value list. Returns null if the instance could not be created or any name-value - * pair could not be set. Otherwise the created object is returned. - * - * @param clsName name of the target class with full package path - * @param args constructor arguments - * @param paramValuePairs pairs of values to set using generic setter methods - * @see BeanInspector.setMem(Object,String,Object) - * @return - */ - public static Object instantiateWithParams(String clsName, Object[] args, List> paramValuePairs) { - Object o = getInstance(clsName, args); - if (o!=null) { - if (paramValuePairs!=null) { - for (Pair nameVal : paramValuePairs) { - boolean succ = BeanInspector.setMem(o, nameVal.head, nameVal.tail); - if (!succ) { - System.err.println("Error, unable to set " + nameVal.head + " to " + nameVal.tail + " in object " + o); - return null; - } else if (TRACE) { - System.out.println("Successfully set " + nameVal.head + " to " + nameVal.tail + " in object " + o); - } - } + /** + * Instantiate a class given by full name (with package) and try to set the member values given + * in the pair-value list. Returns null if the instance could not be created or any name-value + * pair could not be set. Otherwise the created object is returned. + * + * @param clsName + * @param paramValuePairs + * @return + */ + public static Object instantiateWithParams(String clsName, List> paramValuePairs) { + return instantiateWithParams(clsName, new Object[]{}, paramValuePairs); + } + + /** + * Instantiate a class given by full name (with package) and try to set the member values given + * in the pair-value list. Returns null if the instance could not be created or any name-value + * pair could not be set. Otherwise the created object is returned. + * + * @param clsName name of the target class with full package path + * @param args constructor arguments + * @param paramValuePairs pairs of values to set using generic setter methods + * @return + * @see BeanInspector.setMem(Object,String,Object) + */ + public static Object instantiateWithParams(String clsName, Object[] args, List> paramValuePairs) { + Object o = getInstance(clsName, args); + if (o != null) { + if (paramValuePairs != null) { + for (Pair nameVal : paramValuePairs) { + boolean succ = BeanInspector.setMem(o, nameVal.head, nameVal.tail); + if (!succ) { + System.err.println("Error, unable to set " + nameVal.head + " to " + nameVal.tail + " in object " + o); + return null; + } else if (TRACE) { + System.out.println("Successfully set " + nameVal.head + " to " + nameVal.tail + " in object " + o); } - return o; - } else { - System.err.println("Error in instantiateWithParams!"); - return null; - } - } - - /** - * Retrieve an instance of a generic object with arbitrary arguments. Note that the - * full package path must be given and the argument array must match a signature of - * an existing constructor. - * Returns null on a failure and the constructed object otherwise. - * - * @param clsName - * @param args - * @return - */ - public static Object getInstance(String clsName, Object[] args) { - Object o; - try { - Class clz = Class.forName(clsName); - Class[] argClz=new Class[args.length]; - for (int i=0; i ct; - try { - ct = clz.getConstructor(argClz); - o=ct.newInstance(args); - } catch (Exception e) { - System.err.println("Unable to retrieve constructor of " + clsName + ", arguments " + BeanInspector.toString(args)+"\n"+e.getClass()); - System.err.println(e.getMessage()); - e.printStackTrace(); - o=null; - } - } catch (Exception e) { - System.err.println("Unable to create instance of " + clsName + ", arguments " + BeanInspector.toString(args) + "\n"+e.getMessage()); - e.printStackTrace(System.err); - o=null; - } - return o; - } + return o; + } else { + System.err.println("Error in instantiateWithParams!"); + return null; + } + } + + /** + * Retrieve an instance of a generic object with arbitrary arguments. Note that the + * full package path must be given and the argument array must match a signature of + * an existing constructor. + * Returns null on a failure and the constructed object otherwise. + * + * @param clsName + * @param args + * @return + */ + public static Object getInstance(String clsName, Object[] args) { + Object o; + try { + Class clz = Class.forName(clsName); + Class[] argClz = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + argClz[i] = args[i].getClass(); + } + Constructor ct; + try { + ct = clz.getConstructor(argClz); + o = ct.newInstance(args); + } catch (Exception e) { + System.err.println("Unable to retrieve constructor of " + clsName + ", arguments " + BeanInspector.toString(args) + "\n" + e.getClass()); + System.err.println(e.getMessage()); + e.printStackTrace(); + o = null; + } + } catch (Exception e) { + System.err.println("Unable to create instance of " + clsName + ", arguments " + BeanInspector.toString(args) + "\n" + e.getMessage()); + e.printStackTrace(System.err); + o = null; + } + return o; + } } \ No newline at end of file diff --git a/src/eva2/tools/ResourceLoader.java b/src/eva2/tools/ResourceLoader.java index 759002ed..8d424579 100644 --- a/src/eva2/tools/ResourceLoader.java +++ b/src/eva2/tools/ResourceLoader.java @@ -30,19 +30,18 @@ package eva2.tools; /** * TODO description. * - * @.author wegnerj - * @.license GPL + * @.author wegnerj + * @.license GPL * @.cvsversion $Revision: 1.8 $, $Date: 2005/02/17 16:48:44 $ */ -public interface ResourceLoader -{ +public interface ResourceLoader { //~ Methods //////////////////////////////////////////////////////////////// /** - * Gets the byte data from a file at the given resource location. + * Gets the byte data from a file at the given resource location. * - * @param rawResrcLoc Description of the Parameter - * @return the byte array of file. + * @param rawResrcLoc Description of the Parameter + * @return the byte array of file. */ byte[] getBytesFromResourceLocation(String rawResrcLoc); } diff --git a/src/eva2/tools/SelectedTag.java b/src/eva2/tools/SelectedTag.java index 35149f3c..1b948f44 100644 --- a/src/eva2/tools/SelectedTag.java +++ b/src/eva2/tools/SelectedTag.java @@ -6,200 +6,202 @@ package eva2.tools; */ public class SelectedTag implements java.io.Serializable { - protected int m_Selected; - protected Tag[] m_Tags; + protected int m_Selected; + protected Tag[] m_Tags; @Override - public Object clone() { - SelectedTag result = new SelectedTag(this.m_Selected, this.m_Tags); - return (Object) result; - } + public Object clone() { + SelectedTag result = new SelectedTag(this.m_Selected, this.m_Tags); + return (Object) result; + } - /** - * Constructor from a String array, creates a Tag array where the IDs correspond to array index. - * Standard selection is 0. - * - * @param strings - */ + /** + * Constructor from a String array, creates a Tag array where the IDs correspond to array index. + * Standard selection is 0. + * + * @param strings + */ - public SelectedTag(String ... strings) { - init(0, strings); - } - - /** - * Constructor from a String array, creates a Tag array where the IDs correspond to array index. - * - * @param selID - * @param tagStrings - */ - public SelectedTag(int selID, String ... strings) { - init(selID, strings); - } + public SelectedTag(String... strings) { + init(0, strings); + } - /** - * Constructor with a given Tag array. The IDs should correspond to the array index. - * - * @param selID - * @param tags - */ - public SelectedTag(int selID, Tag[] tags) { - m_Tags = tags; - m_Selected = -1; - for (int i = 0; i < tags.length; i++) { - if (i!=tags[i].getID()) { - System.err.println("warning, SelectedTag with inconsistent ID, this may cause problems"); - } - if (tags[i].getID() == selID) { - m_Selected = i; - } - } - if (m_Selected == -1) { - throw new IllegalArgumentException("Selected tag is not valid"); + /** + * Constructor from a String array, creates a Tag array where the IDs correspond to array index. + * + * @param selID + * @param tagStrings + */ + public SelectedTag(int selID, String... strings) { + init(selID, strings); + } + + /** + * Constructor with a given Tag array. The IDs should correspond to the array index. + * + * @param selID + * @param tags + */ + public SelectedTag(int selID, Tag[] tags) { + m_Tags = tags; + m_Selected = -1; + for (int i = 0; i < tags.length; i++) { + if (i != tags[i].getID()) { + System.err.println("warning, SelectedTag with inconsistent ID, this may cause problems"); } - } - - private void init(int selID, String[] tagStrings) { - m_Tags = new Tag[tagStrings.length]; - m_Selected = -1; - for (int i = 0; i < m_Tags.length; i++) { - m_Tags[i] = new Tag(i, tagStrings[i]); - if (selID == i) { - m_Selected = i; - } - } - if (m_Selected == -1) { - throw new IllegalArgumentException("Selected tag is not valid"); - } - } - - //~ Methods //////////////////////////////////////////////////////////////// - - - /** - * Set the selected tag by index. - * - * @param i The new selected tag index - */ - public SelectedTag setSelectedTag(int i) { - if ((i >= 0) && (i < this.m_Tags.length)) { - this.m_Selected = i; + if (tags[i].getID() == selID) { + m_Selected = i; } - return this; - } - - /** - * Set the selected tag by String tag name. If the given name doesnt exist, nothing - * will change and an error message will be printed to System.err. This should of course - * be avoided. - * - * @param str The new selected tag name - */ - public SelectedTag setSelectedTag(String str) { - for (int i=0; i= 0) && (i < this.m_Tags.length)) { + this.m_Selected = i; + } + return this; + } + + /** + * Set the selected tag by String tag name. If the given name doesnt exist, nothing + * will change and an error message will be printed to System.err. This should of course + * be avoided. + * + * @param str The new selected tag name + */ + public SelectedTag setSelectedTag(String str) { + for (int i = 0; i < m_Tags.length; i++) { + if (m_Tags[i].m_String.compareTo(str) == 0) { + m_Selected = i; + return this; + } + } + System.err.println("Warning, trying to select unknown string (SelectedTag::setSelectedTag(String)"); + return this; + } + + /** + * Sets the local selection to the same ID currently selected by the given instance. + * If the ID is not valid, nothing is changed. + * + * @param o another SelectedTag instance, preferably with the same tags + */ + public void setSelectedAs(SelectedTag o) { + setSelectedTag(o.getSelectedTag().getID()); + } + + /** + * + */ + public Tag getSelectedTag() { + return m_Tags[m_Selected]; + } + + /** + * + */ + public int getSelectedTagID() { + return m_Tags[m_Selected].getID(); + } + + public String getSelectedString() { + return m_Tags[m_Selected].getString(); + } + + public int getTagIDByString(String str) { + for (int i = 0; i < m_Tags.length; i++) { + if (m_Tags[i].equals(str)) { + return m_Tags[i].getID(); + } + } + return -1; + } + + /** + * Returns true if the given String is equivalent to the currently selected Tags string component, + * else false. + * + * @param str String to compare to + * @return true if the given string is equivalent to the currently selected Tags string component + */ + public boolean isSelectedString(String str) { + return str.equals(getSelectedTag().getString()); + } + + /** + * + */ + public Tag[] getTags() { + return m_Tags; + } + + /** + * + */ @Override - public boolean equals(Object o) { - if ((o == null) || !(o.getClass().equals(this.getClass()))) { - return false; - } + public boolean equals(Object o) { + if ((o == null) || !(o.getClass().equals(this.getClass()))) { + return false; + } - SelectedTag s = (SelectedTag) o; + SelectedTag s = (SelectedTag) o; + + if ((s.getTags() == m_Tags) && + (s.getSelectedTag() == m_Tags[m_Selected])) { + return true; + } else { + return false; + } + } + + /** + * Check if the given object has the same string tags as this one and return true if so, else false. + * + * @param selT + * @return + */ + public boolean hasSameTags(SelectedTag selT) { + Tag[] oTags = selT.getTags(); + if (oTags.length != m_Tags.length) { + return false; + } else { + for (int i = 0; i < oTags.length; i++) { + if (oTags[i].getString().compareTo(m_Tags[i].getString()) != 0) { + return false; + } + } + return true; + } + } - if ((s.getTags() == m_Tags) && - (s.getSelectedTag() == m_Tags[m_Selected])) { - return true; - } else { - return false; - } - } - - /** - * Check if the given object has the same string tags as this one and return true if so, else false. - * @param selT - * @return - */ - public boolean hasSameTags(SelectedTag selT) { - Tag[] oTags = selT.getTags(); - if (oTags.length != m_Tags.length) { - return false; - } else { - for (int i=0;i e, String[] tips) { @@ -97,7 +97,7 @@ public class StringSelection implements Serializable { * @param headerFields */ public StringSelection(Enum e, String[] enumTips, - List headerFields, String[] addTips) { + List headerFields, String[] addTips) { this(ToolBox.appendEnumAndArray(e, headerFields.toArray(new String[headerFields.size()])), ToolBox.appendArrays(enumTips, addTips)); enumClass = e.getClass(); @@ -119,7 +119,7 @@ public class StringSelection implements Serializable { /** * Return a descriptive String for element i or null if none is provided. * - * @param i index of the string element + * @param i index of the string element * @return a descriptive String for element i or null */ public String getElementInfo(int i) { diff --git a/src/eva2/tools/StringTools.java b/src/eva2/tools/StringTools.java index 9dcf3349..e6260e86 100644 --- a/src/eva2/tools/StringTools.java +++ b/src/eva2/tools/StringTools.java @@ -1,6 +1,7 @@ package eva2.tools; import eva2.gui.BeanInspector; + import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -12,11 +13,12 @@ import java.util.regex.Pattern; * @author Fabian Becker, Marcel Kronfeld */ public final class StringTools { - + /** * Private constructor to prevent instantiation. */ - private StringTools() { } + private StringTools() { + } /** * Returns a HTML formatted String, in which each line is at most lineBreak @@ -32,7 +34,7 @@ public final class StringTools { return ""; } StringBuilder sBuf = new StringBuilder(sTok.nextToken()); - + int length = sBuf.length(); while (sTok.hasMoreElements()) { if (length >= lineBreak) { @@ -49,39 +51,37 @@ public final class StringTools { sBuf.append(""); return sBuf.toString(); } - + public static boolean arrayContains(String[] arr, String key, boolean ignoreCase) { - return (searchStringArray(arr, key, 0, ignoreCase))>=0; + return (searchStringArray(arr, key, 0, ignoreCase)) >= 0; + } + + /** + * Convert an integer to a String filling it with zeros from the left, so + * that is it of the same length as the Integer maxSize would achieve. + * Note that this only works for positive values. + * + * @param index + * @param maxSize + * @return + */ + public static String expandPrefixZeros(int index, int maxSize) { + if (maxSize < 10) { + return "" + index; + } else if (maxSize < 100) { + return ((index < 10) ? "0" : "") + index; + } else { + int lenZeros = (int) Math.log10(maxSize) - (int) Math.log10(index); + char[] zerArr = new char[lenZeros]; + Arrays.fill(zerArr, '0'); + return new String(zerArr) + index; + } } - - /** - * Convert an integer to a String filling it with zeros from the left, so - * that is it of the same length as the Integer maxSize would achieve. - * Note that this only works for positive values. - * - * @param index - * @param maxSize - * @return - */ - public static String expandPrefixZeros(int index, int maxSize) { - if (maxSize<10) { - return ""+index; - } - else if (maxSize<100) { - return ((index<10) ? "0" : "")+index; - } - else { - int lenZeros = (int)Math.log10(maxSize)-(int)Math.log10(index); - char[] zerArr = new char[lenZeros]; - Arrays.fill(zerArr, '0'); - return new String(zerArr)+index; - } - } /** * Search a String array for a given String and return its index if it is found. * If it is not found, -1 is returned. - * + * * @param arr * @param key * @param startIndex @@ -89,366 +89,364 @@ public final class StringTools { * @return */ public static int searchStringArray(String[] arr, String key, int startIndex, boolean ignoreCase) { - for (int i=startIndex; i unrecogs=new LinkedList(); - //for (String string : argsArr) args.add(string); // create a linked list copy - for (int i=0; i=args.length)) { - break; - } // if a key was found look at next argument - if ((ignoreCase && (args[i].equalsIgnoreCase(keys[k]))) - || (!ignoreCase && (args[i].equals(keys[k])))) { // if the key was found - found=true; - if (arities[k]==0) { - values[k]=new String("true"); - } // and its zero-arity, just return true as its value - else { // else return an array of size arity with following strings - try { - if (arities[k]==1) { - values[k]=args[i+1]; - } else { // create String array and fill with following args depending on arity - values[k]=new String[arities[k]]; - if (arities[k]>0) { - for (int j=0; j unrecogs = new LinkedList(); + //for (String string : argsArr) args.add(string); // create a linked list copy + for (int i = 0; i < args.length; i++) { // loop all arguments + boolean found = false; + for (int k = 0; k < keys.length; k++) { // loop all keys + if (found || (i >= args.length)) { + break; + } // if a key was found look at next argument + if ((ignoreCase && (args[i].equalsIgnoreCase(keys[k]))) + || (!ignoreCase && (args[i].equals(keys[k])))) { // if the key was found + found = true; + if (arities[k] == 0) { + values[k] = new String("true"); + } // and its zero-arity, just return true as its value + else { // else return an array of size arity with following strings + try { + if (arities[k] == 1) { + values[k] = args[i + 1]; + } else { // create String array and fill with following args depending on arity + values[k] = new String[arities[k]]; + if (arities[k] > 0) { + for (int j = 0; j < arities[k]; j++) { + ((String[]) values[k])[j] = args[i + j + 1]; + } + i += (arities[k] - 1); // jump one more for every arity beyond 1 + } + } + } catch (ArrayIndexOutOfBoundsException e) { + String errMsg = "Not enough parameters for option " + keys[k] + ", expected number of arguments: " + arities[k]; + System.err.println(errMsg); + throw new RuntimeException(errMsg); + } + i++; // jump one cause we had at least arity 1 + } + } + } + if (!found) { unrecogs.add(i); } - } - return unrecogs.toArray(new Integer[unrecogs.size()]); + } + return unrecogs.toArray(new Integer[unrecogs.size()]); } - + /** * Store the arguments in a hash map. - * - * @see #parseArguments(String[], String[], int[], Object[], boolean) + * * @param args * @param keys * @param arities * @param ignoreCase * @return + * @see #parseArguments(String[], String[], int[], Object[], boolean) */ public static HashMap parseArguments(String[] args, String[] keys, int[] arities, boolean ignoreCase, boolean printErrorsOnUnrecog) { - Object[] values = new Object[keys.length]; - Integer[] unrecogs = parseArguments(args, keys, arities, values, ignoreCase); - if (printErrorsOnUnrecog) { - if (unrecogs.length>0) { - System.err.println("Unrecognized command line options: "); - for (int i=0; i 0) { + System.err.println("Unrecognized command line options: "); + for (int i = 0; i < unrecogs.length; i++) { System.err.println(" " + args[unrecogs[i]]); } - } - } - HashMap map = new HashMap(); - for (int i=0; i map = new HashMap(); + for (int i = 0; i < keys.length; i++) { + map.put(keys[i], values[i]); + } + return map; } - - /** - * Check whether an object is a valid String of String array and if so return the i-th String. - * Returns null otherwise. - * - * @param key - * @param object - * @param i - * @return - */ - public static String checkSingleStringArg(String key, Object object, int i) { - if (object==null) { + + /** + * Check whether an object is a valid String of String array and if so return the i-th String. + * Returns null otherwise. + * + * @param key + * @param object + * @param i + * @return + */ + public static String checkSingleStringArg(String key, Object object, int i) { + if (object == null) { + return null; + } + if (object instanceof String) { + if (i == 0) { + return (String) object; + } else { + System.err.println("Invalid argument; cannot access element " + i + " for " + key + " as only one was given."); return null; } - if (object instanceof String) { - if (i==0) { - return (String)object; - } - else { - System.err.println("Invalid argument; cannot access element " + i + " for " + key + " as only one was given."); - return null; - } - } - if (object instanceof String[]) { - String[] arr = (String[])object; - if (i0) { - if (rest.length()<=maxLen) { - nextBreak = rest.length()-1; - } else { - nextBreak = getNextBreak(minLen, maxLen, breakChars, rest); // search for a break character in a certain interval - if (nextBreak<0) { - nextBreak = len; - } // if none found force the break at the intended length - } - if (res.length()>0) { - res.append("\n"); - } // insert newline - res.append(rest.substring(0, nextBreak+1)); - rest = rest.substring(nextBreak+1); - } - return res.toString(); - } - - public static int getNextBreak(int startIndex, int endIndex, char[] brkChars, String str) { - int index; - for (int i=0; i=0 && (index <= endIndex)) { - return index; - } - } - return -1; - } + /** + * Rewrap a given string to lines of approx. length len. + * + * @param str + * @param len + * @return + */ + public static String wrapLine(String str, int len, double tolerancePerCent) { + return wrapLine(str, new char[]{' ', '-', ',', '.'}, len, tolerancePerCent); + } - /** - * Concatenate a list of Strings using a given delimiter string. - * - * @param strings List of Strings to concatenate - * @param delim Delimiter for concatenation - * @return String representation - */ - public static String concatFields(final List strings, - final String delim) { - StringBuilder sBuilder = new StringBuilder(); - int cnt = 0; - for (String field : strings) { - if (cnt > 0) { - sBuilder.append(delim); - } - sBuilder.append(field); - cnt++; - } - return sBuilder.toString(); - } - - /** - * Concatenate a list of Objects using a given delimiter string. - * The objects are converted to strings using the BeanInspector class. - * - * @param headlineFields - * @param delim - * @return - */ - public static String concatValues(List objects, - final String delim) { - StringBuilder sb = new StringBuilder(); - int cnt = 0; - for (Object v : objects) { - if (cnt > 0) { - sb.append(delim); - } - sb.append(BeanInspector.toString(v)); - cnt++; - } - return sb.toString(); - } + /** + * Rewrap a given string to lines of approx. length len. + * + * @param str + * @param len + * @return + */ + public static String wrapLine(String str, char[] breakChars, int len, double tolerancePerCent) { + StringBuffer res = new StringBuffer(); + String rest = str; + int minLen = (int) ((1. - tolerancePerCent) * (double) len); + int maxLen = (int) ((1. + tolerancePerCent) * (double) len); + int nextBreak = -1; + while (rest.length() > 0) { + if (rest.length() <= maxLen) { + nextBreak = rest.length() - 1; + } else { + nextBreak = getNextBreak(minLen, maxLen, breakChars, rest); // search for a break character in a certain interval + if (nextBreak < 0) { + nextBreak = len; + } // if none found force the break at the intended length + } + if (res.length() > 0) { + res.append("\n"); + } // insert newline + res.append(rest.substring(0, nextBreak + 1)); + rest = rest.substring(nextBreak + 1); + } + return res.toString(); + } - public static String concatFields(String[] strs, - String delim) { - StringBuilder sb = new StringBuilder(); - int cnt = 0; - for (String str : strs) { - if (cnt > 0) { - sb.append(delim); - } - sb.append(str); - cnt++; - } - return sb.toString(); - } + public static int getNextBreak(int startIndex, int endIndex, char[] brkChars, String str) { + int index; + for (int i = 0; i < brkChars.length; i++) { + //indices[i] = str.indexOf(""+brkChars[i], startIndex); + index = str.indexOf("" + brkChars[i], startIndex); + if (index >= 0 && (index <= endIndex)) { + return index; + } + } + return -1; + } - /** - * Remove or replace blanks, braces, etc. from a string for use as a file name. - * - * @param predefName - * @return - */ - public static String simplifySymbols(String str) { - char[] toUnderscore = new char[] {' ', '\t', '\n'}; - for (char c : toUnderscore) { - str = str.replace(c, '_'); - } - char[] toDash = new char[] {',', ';', '/', '\\'}; - for (char c : toDash) { - str = str.replace(c, '-'); - } - char[] toRemove = new char[] {')', '(', '[', ']', '{', '}', '*'}; - for (char c : toRemove) { - str = deleteChar(c, str); - } - str = str.replaceAll("--", "-"); - str = str.replaceAll("__", "_"); - str = str.replaceAll("-_", "_"); - str = str.replaceAll("_-", "_"); + /** + * Concatenate a list of Strings using a given delimiter string. + * + * @param strings List of Strings to concatenate + * @param delim Delimiter for concatenation + * @return String representation + */ + public static String concatFields(final List strings, + final String delim) { + StringBuilder sBuilder = new StringBuilder(); + int cnt = 0; + for (String field : strings) { + if (cnt > 0) { + sBuilder.append(delim); + } + sBuilder.append(field); + cnt++; + } + return sBuilder.toString(); + } - return str; - } + /** + * Concatenate a list of Objects using a given delimiter string. + * The objects are converted to strings using the BeanInspector class. + * + * @param headlineFields + * @param delim + * @return + */ + public static String concatValues(List objects, + final String delim) { + StringBuilder sb = new StringBuilder(); + int cnt = 0; + for (Object v : objects) { + if (cnt > 0) { + sb.append(delim); + } + sb.append(BeanInspector.toString(v)); + cnt++; + } + return sb.toString(); + } - /** - * Delete a certain character from a string. - * - * @param c Character to delete - * @param str String to remove c from. - * @return String with character c removed. - */ - public static String deleteChar(final char c, final String str) { - StringBuilder sBuilder = new StringBuilder(); - for (int i = 0; i < str.length(); i++) { - if (c != str.charAt(i)) { - sBuilder.append(str.charAt(i)); - } - } - return sBuilder.toString(); - } + public static String concatFields(String[] strs, + String delim) { + StringBuilder sb = new StringBuilder(); + int cnt = 0; + for (String str : strs) { + if (cnt > 0) { + sb.append(delim); + } + sb.append(str); + cnt++; + } + return sb.toString(); + } - /** - * Return the substring after the last occurrence of a character. If the - * character does not occur, the full string is returned. - * - * @param str - * @param c - * @return - */ - public static String getSubstringAfterLast(String str, char c) { - int p = str.lastIndexOf(c); - return str.substring(p+1); // for -1 this just works as well - } - - /** - * Converts a camelCase to a more human form, with spaces. - * E.g. 'Camel Case'. - * - * @param word Word to convert to a readable String - * @return Readable String representation of input word - */ - public static String humaniseCamelCase(final String word) { - Pattern pattern = Pattern.compile("([A-Z]|[a-z])[a-z]*"); + /** + * Remove or replace blanks, braces, etc. from a string for use as a file name. + * + * @param predefName + * @return + */ + public static String simplifySymbols(String str) { + char[] toUnderscore = new char[]{' ', '\t', '\n'}; + for (char c : toUnderscore) { + str = str.replace(c, '_'); + } + char[] toDash = new char[]{',', ';', '/', '\\'}; + for (char c : toDash) { + str = str.replace(c, '-'); + } + char[] toRemove = new char[]{')', '(', '[', ']', '{', '}', '*'}; + for (char c : toRemove) { + str = deleteChar(c, str); + } + str = str.replaceAll("--", "-"); + str = str.replaceAll("__", "_"); + str = str.replaceAll("-_", "_"); + str = str.replaceAll("_-", "_"); - List tokens = new ArrayList(); - Matcher matcher = pattern.matcher(word); - String acronym = ""; - while (matcher.find()) { - String found = matcher.group(); - if (found.matches("^[A-Z]$")) { - acronym += found; - } else { - if (acronym.length() > 0) { - //we have an acronym to add before we continue - tokens.add(acronym); - acronym = ""; - } - tokens.add(upcaseFirst(found)); + return str; + } + + /** + * Delete a certain character from a string. + * + * @param c Character to delete + * @param str String to remove c from. + * @return String with character c removed. + */ + public static String deleteChar(final char c, final String str) { + StringBuilder sBuilder = new StringBuilder(); + for (int i = 0; i < str.length(); i++) { + if (c != str.charAt(i)) { + sBuilder.append(str.charAt(i)); + } + } + return sBuilder.toString(); + } + + /** + * Return the substring after the last occurrence of a character. If the + * character does not occur, the full string is returned. + * + * @param str + * @param c + * @return + */ + public static String getSubstringAfterLast(String str, char c) { + int p = str.lastIndexOf(c); + return str.substring(p + 1); // for -1 this just works as well + } + + /** + * Converts a camelCase to a more human form, with spaces. + * E.g. 'Camel Case'. + * + * @param word Word to convert to a readable String + * @return Readable String representation of input word + */ + public static String humaniseCamelCase(final String word) { + Pattern pattern = Pattern.compile("([A-Z]|[a-z])[a-z]*"); + + List tokens = new ArrayList(); + Matcher matcher = pattern.matcher(word); + String acronym = ""; + while (matcher.find()) { + String found = matcher.group(); + if (found.matches("^[A-Z]$")) { + acronym += found; + } else { + if (acronym.length() > 0) { + //we have an acronym to add before we continue + tokens.add(acronym); + acronym = ""; } + tokens.add(upcaseFirst(found)); } - - if (acronym.length() > 0) { - tokens.add(acronym); - } - - if (!tokens.isEmpty()) { - return concatFields(tokens, " "); - } - - return upcaseFirst(word); } - /** - * Takes a string and returns it with the first character - * converted to uppercase. - * - * @param word Word to modify - * @return Parameter with its first character converted to uppercase - */ - public static String upcaseFirst(final String word) { - return word.substring(0, 1).toUpperCase() + word.substring(1); + if (acronym.length() > 0) { + tokens.add(acronym); } + + if (!tokens.isEmpty()) { + return concatFields(tokens, " "); + } + + return upcaseFirst(word); + } + + /** + * Takes a string and returns it with the first character + * converted to uppercase. + * + * @param word Word to modify + * @return Parameter with its first character converted to uppercase + */ + public static String upcaseFirst(final String word) { + return word.substring(0, 1).toUpperCase() + word.substring(1); + } } diff --git a/src/eva2/tools/TXTFileFilter.java b/src/eva2/tools/TXTFileFilter.java index fdfae8dc..a7dcb3ad 100644 --- a/src/eva2/tools/TXTFileFilter.java +++ b/src/eva2/tools/TXTFileFilter.java @@ -8,20 +8,24 @@ package eva2.tools; import javax.swing.filechooser.FileFilter; -/** TXTFileFilter +/** + * TXTFileFilter * Description: A simple File Filter for *.txt files. * Copyright: Copyright (c) 2001 * Company: University of Tuebingen, Computer Architecture - * @author Felix Streichert - * @version: $Revision: 10 $ - * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ - * $Author: streiche $ - * @since JDK 1.3.0_02 + * + * @author Felix Streichert + * @version: $Revision: 10 $ + * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ + * $Author: streiche $ + * @since JDK 1.3.0_02 */ public class TXTFileFilter extends FileFilter { - /** Creates a new instance of TXTFileFilter */ + /** + * Creates a new instance of TXTFileFilter + */ public TXTFileFilter() { } @@ -31,11 +35,10 @@ public class TXTFileFilter extends FileFilter { return true; } String fileName = file.getName(); - if ((fileName.substring(fileName.lastIndexOf('.')+1, fileName.length()).equals("TXT")) || - (fileName.substring(fileName.lastIndexOf('.')+1, fileName.length()).equals("txt"))) { + if ((fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()).equals("TXT")) || + (fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()).equals("txt"))) { return true; - } - else { + } else { return false; } } diff --git a/src/eva2/tools/Tag.java b/src/eva2/tools/Tag.java index 57303ea0..6d9e36b7 100644 --- a/src/eva2/tools/Tag.java +++ b/src/eva2/tools/Tag.java @@ -1,39 +1,46 @@ package eva2.tools; + /** * Title: EvA2 * Description: * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture + * * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 10 $ - * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ - * $Author: streiche $ + * @version: $Revision: 10 $ + * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ + * $Author: streiche $ */ /*==========================================================================* * IMPORTS *==========================================================================*/ public class Tag implements java.io.Serializable { - private static final long serialVersionUID = 1L; - protected int m_ID; - protected String m_String; - public Tag(){} - /** - * - */ - public Tag(int ident, String str) { - m_ID = ident; - m_String = str; - } - /** - * - */ - public int getID() { - return m_ID; - } - /** - * - */ - public String getString() { - return m_String; - } + private static final long serialVersionUID = 1L; + protected int m_ID; + protected String m_String; + + public Tag() { + } + + /** + * + */ + public Tag(int ident, String str) { + m_ID = ident; + m_String = str; + } + + /** + * + */ + public int getID() { + return m_ID; + } + + /** + * + */ + public String getString() { + return m_String; + } } diff --git a/src/eva2/tools/ToolBox.java b/src/eva2/tools/ToolBox.java index bfe1941d..14100fd5 100644 --- a/src/eva2/tools/ToolBox.java +++ b/src/eva2/tools/ToolBox.java @@ -1,50 +1,51 @@ package eva2.tools; import eva2.gui.BeanInspector; + import java.util.ArrayList; import java.util.List; /** * Collection of miscellaneous static helper methods. - * - * @author mkron * + * @author mkron */ public final class ToolBox { /** * Private constructor to prevent instances of module class. */ - private ToolBox() { } + private ToolBox() { + } - /** - * Convert all items of an enum to a String array and append the given String array at the end. - * - * @param additionals - * @return - */ - public static String[] appendEnumAndArray(Enum e, String[] additionals) { - Enum[] fields = e.getClass().getEnumConstants(); - int enumLen = fields.length; //values().length; - int len = enumLen + additionals.length; - String[] ret = new String[len]; - for (int i = 0; i < enumLen; i++) { + /** + * Convert all items of an enum to a String array and append the given String array at the end. + * + * @param additionals + * @return + */ + public static String[] appendEnumAndArray(Enum e, String[] additionals) { + Enum[] fields = e.getClass().getEnumConstants(); + int enumLen = fields.length; //values().length; + int len = enumLen + additionals.length; + String[] ret = new String[len]; + for (int i = 0; i < enumLen; i++) { ret[i] = fields[i].toString(); } - - for (int i = enumLen; i < ret.length; i++) { + + for (int i = enumLen; i < ret.length; i++) { ret[i] = additionals[i - enumLen]; } - return ret; - } - - /** - * Append two String arrays. If both are null, null is returned. - * - * @param strArr1 - * @param strArr2 - * @return - */ - public static String[] appendArrays(String[] strArr1, String[] strArr2) { + return ret; + } + + /** + * Append two String arrays. If both are null, null is returned. + * + * @param strArr1 + * @param strArr2 + * @return + */ + public static String[] appendArrays(String[] strArr1, String[] strArr2) { if (strArr1 == null) { return strArr2; } @@ -77,32 +78,32 @@ public final class ToolBox { System.arraycopy(objArr2, 0, ret, objArr1.length, objArr2.length); return ret; } - - /** - * For a list of objects, generate an array of Double which contains thee.getClass().getEnumConstants() - * converted double arrays whenever this is directly possible, or null otherwise. - * The length of the array will correspond to the length of the given list. - * - * @see BeanInspector.toString(Object) - * @param l - * @return - */ - public static Double[] parseDoubles(List l) { - ArrayList vals = new ArrayList(); - for (Object o : l) { - vals.add(toDouble(o)); // null if unsuccessfull - } - return vals.toArray(new Double[vals.size()]); - } - - /** - * Try to convert a Double from a given Object. Return null - * if conversion fails (e.g. because the Object is a complex data type - * which has no straight-forward numeric representation, e.g. an array). - * - * @param o - * @return - */ + + /** + * For a list of objects, generate an array of Double which contains thee.getClass().getEnumConstants() + * converted double arrays whenever this is directly possible, or null otherwise. + * The length of the array will correspond to the length of the given list. + * + * @param l + * @return + * @see BeanInspector.toString(Object) + */ + public static Double[] parseDoubles(List l) { + ArrayList vals = new ArrayList(); + for (Object o : l) { + vals.add(toDouble(o)); // null if unsuccessfull + } + return vals.toArray(new Double[vals.size()]); + } + + /** + * Try to convert a Double from a given Object. Return null + * if conversion fails (e.g. because the Object is a complex data type + * which has no straight-forward numeric representation, e.g. an array). + * + * @param o + * @return + */ public static Double toDouble(Object o) { if (o instanceof Number) { return ((Number) o).doubleValue(); @@ -116,59 +117,59 @@ public final class ToolBox { } return null; } - - /** - * For an array of objects, generate an array of Double which contains the - * converted double arrays whenever this is directly possible, or null otherwise. - * - * @see BeanInspector.toString(Object) - * @param l - * @return - */ - public static Double[] parseDoubles(Object [] os) { - Double[] vals = new Double[os.length]; - for (int i = 0; i < os.length; i++) { - vals[i] = toDouble(os[i]); - } - return vals; - } - - /** - * Return an array containing only those lines which have values within - * lower and upper bound (included) in the indexed column. - * - * @param dat a 2D double array - * @param i index of the column to look at - * @param lower lower bound of values to filter rows for - * @param upper upper bound of values to filter rows for - * @return a filtered 2D double array where value[*][i] in [lower,upper] - */ - public static double[][] filterBy(double[][] dat, int i, double lower, double upper) { - if (dat==null||dat.length==0) { - return dat; - } - if (i >= dat[0].length) { - System.err.println("Error, invalid column index " + i + " for data array with " + dat[0].length + " columns!"); - } - ArrayList matching = new ArrayList(5); - for (double[] row : dat) { - if (row[i]<=upper && row[i]>=lower) { - matching.add(row); - } - } - - return matching.toArray(new double[matching.size()][dat[0].length]); - } - /** - * Retrieve a given number of columns from a double matrix. The given - * data array must have valid matrix dimensions (equal number of columns per row). - * - * @param data a 2D double array - * @param cols the indices of columns in data to return - * @return a 2D double array containing the indexed columns from data - */ - public static double[][] getCols(double[][] data, int... cols) { + /** + * For an array of objects, generate an array of Double which contains the + * converted double arrays whenever this is directly possible, or null otherwise. + * + * @param l + * @return + * @see BeanInspector.toString(Object) + */ + public static Double[] parseDoubles(Object[] os) { + Double[] vals = new Double[os.length]; + for (int i = 0; i < os.length; i++) { + vals[i] = toDouble(os[i]); + } + return vals; + } + + /** + * Return an array containing only those lines which have values within + * lower and upper bound (included) in the indexed column. + * + * @param dat a 2D double array + * @param i index of the column to look at + * @param lower lower bound of values to filter rows for + * @param upper upper bound of values to filter rows for + * @return a filtered 2D double array where value[*][i] in [lower,upper] + */ + public static double[][] filterBy(double[][] dat, int i, double lower, double upper) { + if (dat == null || dat.length == 0) { + return dat; + } + if (i >= dat[0].length) { + System.err.println("Error, invalid column index " + i + " for data array with " + dat[0].length + " columns!"); + } + ArrayList matching = new ArrayList(5); + for (double[] row : dat) { + if (row[i] <= upper && row[i] >= lower) { + matching.add(row); + } + } + + return matching.toArray(new double[matching.size()][dat[0].length]); + } + + /** + * Retrieve a given number of columns from a double matrix. The given + * data array must have valid matrix dimensions (equal number of columns per row). + * + * @param data a 2D double array + * @param cols the indices of columns in data to return + * @return a 2D double array containing the indexed columns from data + */ + public static double[][] getCols(double[][] data, int... cols) { if (data == null || (data[0] == null)) { return null; } diff --git a/src/eva2/tools/ToolBoxGui.java b/src/eva2/tools/ToolBoxGui.java index fbc1b5dd..dbe9110d 100644 --- a/src/eva2/tools/ToolBoxGui.java +++ b/src/eva2/tools/ToolBoxGui.java @@ -6,56 +6,55 @@ import javax.swing.*; /** * Some helper methods connected to the GUI. - * - * @author mkron * + * @author mkron */ public class ToolBoxGui { - - /** - * Create a modal dialog similar to JOptionPane.showInputDialog, with the difference that an initial - * value can be set. - * - * @see JOptionPane - * @param parent the parent component - * @param title title of the dialog - * @param message message the input field is annotated with - * @param initialVal initial value of the input field - * @return A string the user has entered or null if the user canceled the action. - */ - public static String getInputPaneInitialVal(Component parent, String title, String message, String initialVal) { - return getInputPaneInitialVal(parent, title, message, initialVal, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); - } - /** - * Create a modal dialog similar to JOptionPane.showInputDialog, with the difference that an initial - * value can be set. - * - * @see JOptionPane - * @param parent the parent component - * @param title title of the dialog - * @param message message the input field is annotated with - * @param initialVal initial value of the input field - * @param msgType message type - * @param optType option type - * @return A string the user has entered or null if the user canceled the action. - */ - public static String getInputPaneInitialVal(Component parent, String title, String message, String initialVal, int msgType, int optType) { - JOptionPane jop = new JOptionPane(message, msgType, optType, (Icon)null); - jop.setWantsInput(true); - // its a mess with these initial values - jop.setInputValue(initialVal); // this I expected to work - jop.setInitialValue(initialVal); // this I expected to work next - jop.setInitialSelectionValue(initialVal); // this actually seems to work... - JDialog dialog = jop.createDialog(parent, title); - dialog.setVisible(true); - Object value = jop.getValue(); - if (value != null && (value instanceof Integer) && ((Integer) value) == JOptionPane.OK_OPTION) { + /** + * Create a modal dialog similar to JOptionPane.showInputDialog, with the difference that an initial + * value can be set. + * + * @param parent the parent component + * @param title title of the dialog + * @param message message the input field is annotated with + * @param initialVal initial value of the input field + * @return A string the user has entered or null if the user canceled the action. + * @see JOptionPane + */ + public static String getInputPaneInitialVal(Component parent, String title, String message, String initialVal) { + return getInputPaneInitialVal(parent, title, message, initialVal, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); + } + + /** + * Create a modal dialog similar to JOptionPane.showInputDialog, with the difference that an initial + * value can be set. + * + * @param parent the parent component + * @param title title of the dialog + * @param message message the input field is annotated with + * @param initialVal initial value of the input field + * @param msgType message type + * @param optType option type + * @return A string the user has entered or null if the user canceled the action. + * @see JOptionPane + */ + public static String getInputPaneInitialVal(Component parent, String title, String message, String initialVal, int msgType, int optType) { + JOptionPane jop = new JOptionPane(message, msgType, optType, (Icon) null); + jop.setWantsInput(true); + // its a mess with these initial values + jop.setInputValue(initialVal); // this I expected to work + jop.setInitialValue(initialVal); // this I expected to work next + jop.setInitialSelectionValue(initialVal); // this actually seems to work... + JDialog dialog = jop.createDialog(parent, title); + dialog.setVisible(true); + Object value = jop.getValue(); + if (value != null && (value instanceof Integer) && ((Integer) value) == JOptionPane.OK_OPTION) { return (String) jop.getInputValue(); } else { return null; } - } + } public static JButton createIconifiedButton(final String iconSrc, final String title, final boolean withTitle) { JButton newButton; diff --git a/src/eva2/tools/URLGetter.java b/src/eva2/tools/URLGetter.java index 60942eb3..34a1344b 100644 --- a/src/eva2/tools/URLGetter.java +++ b/src/eva2/tools/URLGetter.java @@ -1,48 +1,51 @@ package eva2.tools; + import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.*; + /** *

Title: EvA2

*

Description:

*

Copyright: Copyright (c) 2003

*

Company:

+ * * @author not attributable * @version 1.0 */ public class URLGetter { - public URLGetter() { - - } - - public static String getData (String urlstr) { - System.getProperties().put("proxySet", "true"); - System.getProperties().put("proxyHost", - "www-cache.informatik.uni-tuebingen.de"); - System.getProperties().put("proxyPort", "3128"); - - StringBuffer res = new StringBuffer(); - try { - URL url = new URL(urlstr); - URLConnection conn = url.openConnection(); - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = rd.readLine()) != null) { - res.append(line+"\n"); - } - - rd.close(); + public URLGetter() { } - catch (Exception ex) { - System.out.println("URLGETTER ERROR: " + ex); + + public static String getData(String urlstr) { + System.getProperties().put("proxySet", "true"); + System.getProperties().put("proxyHost", + "www-cache.informatik.uni-tuebingen.de"); + System.getProperties().put("proxyPort", "3128"); + + StringBuffer res = new StringBuffer(); + try { + URL url = new URL(urlstr); + URLConnection conn = url.openConnection(); + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = rd.readLine()) != null) { + res.append(line + "\n"); + } + + rd.close(); + + } catch (Exception ex) { + System.out.println("URLGETTER ERROR: " + ex); + } + + return res.toString(); } - return res.toString(); - } - public static void main(String[] args) { - URLGetter URLGetter1 = new URLGetter(); - } + public static void main(String[] args) { + URLGetter URLGetter1 = new URLGetter(); + } } diff --git a/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java b/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java index 7ad052ae..cebf17ee 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java +++ b/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java @@ -6,6 +6,7 @@ import eva2.gui.InterfaceSelectablePointIcon; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.mocco.paretofrontviewer.InterfaceRefSolutionListener; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; @@ -20,36 +21,38 @@ import javax.swing.*; */ public class Chart2DDPointContentSelectable implements InterfaceDPointWithContent, InterfaceSelectablePointIcon, DPointIcon { - AbstractEAIndividual m_Indy; - InterfaceOptimizationProblem m_Problem; - private InterfaceRefSolutionListener m_Listener; - private Color m_Border = Color.BLACK; - private Color m_Fill = null; - private int m_Size = 4; + AbstractEAIndividual m_Indy; + InterfaceOptimizationProblem m_Problem; + private InterfaceRefSolutionListener m_Listener; + private Color m_Border = Color.BLACK; + private Color m_Fill = null; + private int m_Size = 4; - /** this method has to be overridden to paint the icon. The point itself lies + /** + * this method has to be overridden to paint the icon. The point itself lies * at coordinates (0, 0) */ @Override - public void paint( Graphics g ){ + public void paint(Graphics g) { Color prev = g.getColor(); if (this.m_Indy.isMarked()) { this.m_Fill = Color.RED; - } - else { + } else { this.m_Fill = Color.LIGHT_GRAY; } g.setColor(m_Fill); - g.fillOval(-this.m_Size, -this.m_Size, 2*this.m_Size +1, 2*this.m_Size +1); + g.fillOval(-this.m_Size, -this.m_Size, 2 * this.m_Size + 1, 2 * this.m_Size + 1); if (this.m_Border != null) { g.setColor(m_Border); } - g.drawOval(-this.m_Size, -this.m_Size, 2*this.m_Size, 2*this.m_Size); + g.drawOval(-this.m_Size, -this.m_Size, 2 * this.m_Size, 2 * this.m_Size); g.setColor(prev); } - /** the border which is necessary to be paint around the DPoint that the whole + /** + * the border which is necessary to be paint around the DPoint that the whole * icon is visible + * * @return the border */ @Override @@ -60,9 +63,11 @@ public class Chart2DDPointContentSelectable implements InterfaceDPointWithConten public void setBorderColor(Color c) { this.m_Border = c; } + public void setFillColor(Color c) { this.m_Fill = c; } + public void setSize(int d) { this.m_Size = d; } @@ -71,8 +76,10 @@ public class Chart2DDPointContentSelectable implements InterfaceDPointWithConten * The InterfaceSelectablePointIcon */ - /** This method allows to add a selection listner to the PointIcon + /** + * This method allows to add a selection listner to the PointIcon * it should need more than one listener to this abstruse event + * * @param a The selection listener */ @Override @@ -80,7 +87,9 @@ public class Chart2DDPointContentSelectable implements InterfaceDPointWithConten this.m_Listener = a; } - /** This method returns the selection listner to the PointIcon + /** + * This method returns the selection listner to the PointIcon + * * @return InterfaceSelectionListener */ @Override @@ -88,43 +97,51 @@ public class Chart2DDPointContentSelectable implements InterfaceDPointWithConten return this.m_Listener; } - /** This method allows to remove the selection listner to the PointIcon + /** + * This method allows to remove the selection listner to the PointIcon */ @Override public void removeSelectionListeners() { this.m_Listener = null; } - /** This method allows you to set the according individual - * @param indy AbstractEAIndividual + /** + * This method allows you to set the according individual + * + * @param indy AbstractEAIndividual */ @Override public void setEAIndividual(AbstractEAIndividual indy) { this.m_Indy = indy; } + @Override public AbstractEAIndividual getEAIndividual() { return this.m_Indy; } - /** This method allows you to set the according optimization problem - * @param problem InterfaceOptimizationProblem + /** + * This method allows you to set the according optimization problem + * + * @param problem InterfaceOptimizationProblem */ @Override public void setProblem(InterfaceOptimizationProblem problem) { this.m_Problem = problem; } + @Override public InterfaceOptimizationProblem getProblem() { return this.m_Problem; } - /** This method allows you to draw additional data of the individual + /** + * This method allows you to draw additional data of the individual */ @Override public void showIndividual() { JFrame newFrame = new JFrame(); - newFrame.setTitle(this.m_Indy.getName()+": "+this.m_Indy); + newFrame.setTitle(this.m_Indy.getName() + ": " + this.m_Indy); newFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent ev) { diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java b/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java index fda8dd8e..c882c3d2 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java @@ -12,25 +12,25 @@ import java.awt.*; */ public class Chart2DDPointIconCircle implements DPointIcon { - private Color m_Border = Color.BLACK; - private Color m_Fill = null; - private int m_Size = 4; + private Color m_Border = Color.BLACK; + private Color m_Fill = null; + private int m_Size = 4; /** * this method has to be overridden to paint the icon. The point itself lies * at coordinates (0, 0) */ @Override - public void paint( Graphics g ){ + public void paint(Graphics g) { Color prev = g.getColor(); if (m_Fill != null) { g.setColor(m_Fill); - g.fillOval(-this.m_Size, -this.m_Size, 2*this.m_Size +1, 2*this.m_Size +1); + g.fillOval(-this.m_Size, -this.m_Size, 2 * this.m_Size + 1, 2 * this.m_Size + 1); } if (this.m_Border != null) { g.setColor(m_Border); } - g.drawOval(-this.m_Size, -this.m_Size, 2*this.m_Size, 2*this.m_Size); + g.drawOval(-this.m_Size, -this.m_Size, 2 * this.m_Size, 2 * this.m_Size); g.setColor(prev); } @@ -48,9 +48,11 @@ public class Chart2DDPointIconCircle implements DPointIcon { public void setBorderColor(Color c) { this.m_Border = c; } + public void setFillColor(Color c) { this.m_Fill = c; } + public void setSize(int d) { this.m_Size = d; } diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconContent.java b/src/eva2/tools/chart2d/Chart2DDPointIconContent.java index 4a760ba2..5e33e522 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconContent.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconContent.java @@ -4,6 +4,7 @@ package eva2.tools.chart2d; import eva2.gui.plot.InterfaceDPointWithContent; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.problems.InterfaceOptimizationProblem; + import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; @@ -18,18 +19,18 @@ import javax.swing.*; */ public class Chart2DDPointIconContent implements InterfaceDPointWithContent, DPointIcon { - AbstractEAIndividual m_Indy; - InterfaceOptimizationProblem m_Problem; + AbstractEAIndividual m_Indy; + InterfaceOptimizationProblem m_Problem; /** * this method has to be overridden to paint the icon. The point itself lies * at coordinates (0, 0) */ @Override - public void paint( Graphics g ){ + public void paint(Graphics g) { g.drawOval(-4, -4, 8, 8); - g.drawLine(-2, 2, 2,-2); - g.drawLine(-2,-2, 2, 2); + g.drawLine(-2, 2, 2, -2); + g.drawLine(-2, -2, 2, 2); } /** @@ -43,31 +44,38 @@ public class Chart2DDPointIconContent implements InterfaceDPointWithContent, DPo return new DBorder(4, 4, 4, 4); } - /** This method allows you to set the according individual - * @param indy AbstractEAIndividual + /** + * This method allows you to set the according individual + * + * @param indy AbstractEAIndividual */ @Override public void setEAIndividual(AbstractEAIndividual indy) { this.m_Indy = indy; } + @Override public AbstractEAIndividual getEAIndividual() { return this.m_Indy; } - /** This method allows you to set the according optimization problem - * @param problem InterfaceOptimizationProblem + /** + * This method allows you to set the according optimization problem + * + * @param problem InterfaceOptimizationProblem */ @Override public void setProblem(InterfaceOptimizationProblem problem) { this.m_Problem = problem; } + @Override public InterfaceOptimizationProblem getProblem() { return this.m_Problem; } - /** This method allows you to draw additional data of the individual + /** + * This method allows you to draw additional data of the individual */ @Override public void showIndividual() { @@ -76,7 +84,7 @@ public class Chart2DDPointIconContent implements InterfaceDPointWithContent, DPo System.out.println("No individual!"); return; } - newFrame.setTitle(this.m_Indy.getName()+": "+this.m_Indy); + newFrame.setTitle(this.m_Indy.getName() + ": " + this.m_Indy); newFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent ev) { diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconCross.java b/src/eva2/tools/chart2d/Chart2DDPointIconCross.java index dcf97021..eb20206d 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconCross.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconCross.java @@ -13,18 +13,18 @@ import java.awt.*; */ public class Chart2DDPointIconCross implements DPointIcon { - private Color m_Color; + private Color m_Color; /** * this method has to be overridden to paint the icon. The point itself lies * at coordinates (0, 0) */ @Override - public void paint( Graphics g ){ + public void paint(Graphics g) { Color prev = g.getColor(); g.setColor(this.m_Color); - g.drawLine(-1, 1, 1,-1); - g.drawLine(-1,-1, 1, 1); + g.drawLine(-1, 1, 1, -1); + g.drawLine(-1, -1, 1, 1); g.setColor(prev); } diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java b/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java index 67dbcbd0..8eef5da1 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java @@ -13,25 +13,25 @@ import java.awt.*; */ public class Chart2DDPointIconPoint implements DPointIcon { - private Color m_Border = Color.BLACK; - private Color m_Fill = Color.BLACK; - private int m_Size = 2; + private Color m_Border = Color.BLACK; + private Color m_Fill = Color.BLACK; + private int m_Size = 2; /** * this method has to be overridden to paint the icon. The point itself lies * at coordinates (0, 0) */ @Override - public void paint( Graphics g ){ + public void paint(Graphics g) { Color prev = g.getColor(); if (m_Fill != null) { g.setColor(m_Fill); - g.fillOval(-this.m_Size, -this.m_Size, 2*this.m_Size, 2*this.m_Size); + g.fillOval(-this.m_Size, -this.m_Size, 2 * this.m_Size, 2 * this.m_Size); } if (this.m_Border != null) { g.setColor(m_Border); } - g.drawOval(-this.m_Size, -this.m_Size, (2*this.m_Size)-1, (2*this.m_Size)-1); + g.drawOval(-this.m_Size, -this.m_Size, (2 * this.m_Size) - 1, (2 * this.m_Size) - 1); g.setColor(prev); } @@ -49,9 +49,11 @@ public class Chart2DDPointIconPoint implements DPointIcon { public void setBorderColor(Color c) { this.m_Border = c; } + public void setFillColor(Color c) { this.m_Fill = c; } + public void setSize(int d) { this.m_Size = d; } diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconText.java b/src/eva2/tools/chart2d/Chart2DDPointIconText.java index aa7e939b..9de9a704 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconText.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconText.java @@ -11,18 +11,20 @@ import java.awt.*; * Time: 16:08:15 * To change this template use File | Settings | File Templates. */ -public class Chart2DDPointIconText implements DPointIcon { +public class Chart2DDPointIconText implements DPointIcon { - private DPointIcon m_Icon = new Chart2DDPointIconCross(); - private String m_Text = " "; - private Color m_Color; + private DPointIcon m_Icon = new Chart2DDPointIconCross(); + private String m_Text = " "; + private Color m_Color; public Chart2DDPointIconText(String s) { m_Text = s; } - /** This method allows you to set an icon - * @param icon The new icon + /** + * This method allows you to set an icon + * + * @param icon The new icon */ public void setIcon(DPointIcon icon) { this.m_Icon = icon; @@ -33,7 +35,7 @@ public class Chart2DDPointIconText implements DPointIcon { * at coordinates (0, 0) */ @Override - public void paint( Graphics g ){ + public void paint(Graphics g) { this.m_Icon.paint(g); g.setColor(m_Color); g.drawString(this.m_Text, 4, 4); @@ -49,13 +51,13 @@ public class Chart2DDPointIconText implements DPointIcon { public DBorder getDBorder() { return new DBorder(4, 4, 4, 4); } - + /** * Set the color for the text. - * + * * @param col */ - public void setColor(Color col) { - m_Color = col; + public void setColor(Color col) { + m_Color = col; } } \ No newline at end of file diff --git a/src/eva2/tools/chart2d/DArea.java b/src/eva2/tools/chart2d/DArea.java index 2ced7acd..43e711d0 100644 --- a/src/eva2/tools/chart2d/DArea.java +++ b/src/eva2/tools/chart2d/DArea.java @@ -13,6 +13,7 @@ package eva2.tools.chart2d; import eva2.tools.print.PagePrinter; + import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; @@ -37,850 +38,810 @@ import javax.swing.border.Border; * JComponents */ public class DArea extends JComponent implements DParent, Printable { - /** - * the default minimal rectangle which is shown - */ - public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, - 2); + /** + * the default minimal rectangle which is shown + */ + public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, + 2); - /** - * - */ - private static final long serialVersionUID = 1461387400381365146L; + /** + * + */ + private static final long serialVersionUID = 1461387400381365146L; - private static final boolean TRACE = false; + private static final boolean TRACE = false; - private boolean auto_focus = false, auto_grid = false, - grid_to_front = false; + private boolean auto_focus = false, auto_grid = false, + grid_to_front = false; - /** - * the container in which all DElements of the area are contained except the - * grid - */ - private DContainer container; + /** + * the container in which all DElements of the area are contained except the + * grid + */ + private DContainer container; - private DBorder dborder = new DBorder(); + private DBorder dborder = new DBorder(); - /** - * the grid of the area - */ - private DGrid grid; + /** + * the grid of the area + */ + private DGrid grid; - /** - * maximal number of grid lines - */ - private int max_grid = 10; + /** + * maximal number of grid lines + */ + private int max_grid = 10; - /** - * the measures of the area it calculates the coordinates - */ - protected DMeasures measures; + /** + * the measures of the area it calculates the coordinates + */ + protected DMeasures measures; - /** - * min_rectangle is set, when all elements are removed the intersection of - * visible_rect and max_rectangle is the currently visible rectangle - */ - protected DRectangle min_rect = DEFAULT_MIN_RECT, - visible_rect = DEFAULT_MIN_RECT; + /** + * min_rectangle is set, when all elements are removed the intersection of + * visible_rect and max_rectangle is the currently visible rectangle + */ + protected DRectangle min_rect = DEFAULT_MIN_RECT, + visible_rect = DEFAULT_MIN_RECT; - protected Double min_x, min_y, max_x, max_y; + protected Double min_x, min_y, max_x, max_y; - /** - * initializes the DArea with the initial capacity of 10 components - */ - public DArea() { - this(10); - } + /** + * initializes the DArea with the initial capacity of 10 components + */ + public DArea() { + this(10); + } - /** - * initializes the DArea with the specialized initial capacity of components - * (@see java.util.Vector) - * - * @param the - * initial capacity - */ - public DArea(int initial_capacity) { - container = new DContainer(); - container.setDParent(this); - grid = new DGrid(visible_rect, 1, 1); - grid.setVisible(false); - grid.setDParent(this); - measures = new DMeasures(this); - } + /** + * initializes the DArea with the specialized initial capacity of components + * (@see java.util.Vector) + * + * @param the initial capacity + */ + public DArea(int initial_capacity) { + container = new DContainer(); + container.setDParent(this); + grid = new DGrid(visible_rect, 1, 1); + grid.setVisible(false); + grid.setDParent(this); + measures = new DMeasures(this); + } - /** - * method 'adds' a certain border around the contained rectangle that means - * that it takes the old border and takes the maxima of the old and the new - * values - * - * @param clip - * the java.awt.Insets object of the new clip - */ + /** + * method 'adds' a certain border around the contained rectangle that means + * that it takes the old border and takes the maxima of the old and the new + * values + * + * @param clip the java.awt.Insets object of the new clip + */ @Override - public void addDBorder(DBorder b) { - dborder.insert(b); - } + public void addDBorder(DBorder b) { + dborder.insert(b); + } - /** - * adds a new component to the area - * - * @param e - * the new DElement - */ + /** + * adds a new component to the area + * + * @param e the new DElement + */ @Override - public void addDElement(DElement e) { - container.addDElement(e); - } + public void addDElement(DElement e) { + container.addDElement(e); + } - /** - * method returns true, if the given element is contained in the container - * - * @param e - * the element - * @return if it is contained - */ + /** + * method returns true, if the given element is contained in the container + * + * @param e the element + * @return if it is contained + */ @Override - public boolean contains(DElement e) { - return container.contains(e); - } + public boolean contains(DElement e) { + return container.contains(e); + } - /** - * method returns the current border around the rectangle - * - * @return the border - */ - public DBorder getDBorder() { - return dborder; - } + /** + * method returns the current border around the rectangle + * + * @return the border + */ + public DBorder getDBorder() { + return dborder; + } - /** - * returnes all DElements in the container - * - * @return the elements of the container - */ + /** + * returnes all DElements in the container + * + * @return the elements of the container + */ @Override - public DElement[] getDElements() { - return container.getDElements(); - } + public DElement[] getDElements() { + return container.getDElements(); + } - /** - * returns the measures of the DArea The DMeasures object calculates the - * different coodinates and contains a Graphics object to paint the - * DElements of the area - * - * @return the measures of the DArea - */ - public DMeasures getDMeasures() { - return measures; - } + /** + * returns the measures of the DArea The DMeasures object calculates the + * different coodinates and contains a Graphics object to paint the + * DElements of the area + * + * @return the measures of the DArea + */ + public DMeasures getDMeasures() { + return measures; + } - /** - * returns the currently visible rectangle in DArea coordinates - * - * @return DRectangle the size and position of the visible area - */ - public DRectangle getDRectangle() { - DRectangle rect = (DRectangle) visible_rect.clone(); - if (min_x != null) { - rect.setX(Math.max(rect.getX(), getMinX())); - } - if (min_y != null) { - rect.setY(Math.max(rect.getY(), getMinY())); - } - if (max_x != null) { - rect.setWidth(Math.min(rect.getWidth(), getMaxX() - getMinX())); - } - if (max_y != null) { - rect.setHeight(Math.min(rect.getHeight(), getMaxY() - getMinY())); - } - return rect; - } + /** + * returns the currently visible rectangle in DArea coordinates + * + * @return DRectangle the size and position of the visible area + */ + public DRectangle getDRectangle() { + DRectangle rect = (DRectangle) visible_rect.clone(); + if (min_x != null) { + rect.setX(Math.max(rect.getX(), getMinX())); + } + if (min_y != null) { + rect.setY(Math.max(rect.getY(), getMinY())); + } + if (max_x != null) { + rect.setWidth(Math.min(rect.getWidth(), getMaxX() - getMinX())); + } + if (max_y != null) { + rect.setHeight(Math.min(rect.getHeight(), getMaxY() - getMinY())); + } + return rect; + } - /** - * method returns the maximal rectangle of the area - * - * @return the maximal rectangle - * @deprecated see getMaxX, getMaxY, getMinX, getMinY - */ - public DRectangle getMaxRectangle() { - return new DRectangle(min_x.doubleValue(), min_y.doubleValue(), max_x - .doubleValue() - - min_x.doubleValue(), max_y.doubleValue() - - min_y.doubleValue()); - } + /** + * method returns the maximal rectangle of the area + * + * @return the maximal rectangle + * @deprecated see getMaxX, getMaxY, getMinX, getMinY + */ + public DRectangle getMaxRectangle() { + return new DRectangle(min_x.doubleValue(), min_y.doubleValue(), max_x + .doubleValue() + - min_x.doubleValue(), max_y.doubleValue() + - min_y.doubleValue()); + } - /** - * method returns the maxmal x-value which can be displayed in the DArea - * - * @return the maxmal x-value - */ - public double getMaxX() { - if (max_x != null) { - return max_x.doubleValue(); - } - return 0; - } + /** + * method returns the maxmal x-value which can be displayed in the DArea + * + * @return the maxmal x-value + */ + public double getMaxX() { + if (max_x != null) { + return max_x.doubleValue(); + } + return 0; + } - /** - * method returns the maximal y-value which can be displayed in the DArea - * - * @return the maximal y-value - */ - public double getMaxY() { - if (max_y != null) { - return max_y.doubleValue(); - } - return 0; - } + /** + * method returns the maximal y-value which can be displayed in the DArea + * + * @return the maximal y-value + */ + public double getMaxY() { + if (max_y != null) { + return max_y.doubleValue(); + } + return 0; + } - // /** - // * method sets the maximal rectangle whioch can be viewed with the - // * DArea. This method can be used if the area is used with scale functions - // * which are not invertible on all reals - // * - // * @param x the minmal x value - // * @param y the minmal y value - // * @param width of the maximal rectangle - // * @param height of the maximal rectangle - // */ - // public void setMaxRectangle( double x, double y, double width, double - // height ){ - // setMaxRectangle( new DRectangle( x, y, width, height ) ); - // } + // /** + // * method sets the maximal rectangle whioch can be viewed with the + // * DArea. This method can be used if the area is used with scale functions + // * which are not invertible on all reals + // * + // * @param x the minmal x value + // * @param y the minmal y value + // * @param width of the maximal rectangle + // * @param height of the maximal rectangle + // */ + // public void setMaxRectangle( double x, double y, double width, double + // height ){ + // setMaxRectangle( new DRectangle( x, y, width, height ) ); + // } - // /** - // * method sets the maximal rectangle whioch can be viewed with the - // * DArea. This method can be used if the area is used with scale functions - // * which are not invertible on all reals - // * - // * @param the rect maximal rectangle of the DArea - // * @deprecated see setMinX, setMinY, setMaxX, setMaxY - // */ - // public void setMaxRectangle( DRectangle rect ){ - // if( !rect.contains( min_rect ) ) throw - // new - // IllegalArgumentException("Maximal rectangle does not contain minmal rectangle"); - // - // setMinX( rect.x ); - // setMinY( rect.y ); - // setMaxX( rect.x + rect.width ); - // setMaxY( rect.y + rect.height ); - // } + // /** + // * method sets the maximal rectangle whioch can be viewed with the + // * DArea. This method can be used if the area is used with scale functions + // * which are not invertible on all reals + // * + // * @param the rect maximal rectangle of the DArea + // * @deprecated see setMinX, setMinY, setMaxX, setMaxY + // */ + // public void setMaxRectangle( DRectangle rect ){ + // if( !rect.contains( min_rect ) ) throw + // new + // IllegalArgumentException("Maximal rectangle does not contain minmal rectangle"); + // + // setMinX( rect.x ); + // setMinY( rect.y ); + // setMaxX( rect.x + rect.width ); + // setMaxY( rect.y + rect.height ); + // } - /** - * method returns the minimal rectangle which is set as the visible when all - * elements are removed and the area is on auto focus - * - * @return the minmal rectangle - */ - public DRectangle getMinRectangle() { - return (DRectangle) min_rect.clone(); - } + /** + * method returns the minimal rectangle which is set as the visible when all + * elements are removed and the area is on auto focus + * + * @return the minmal rectangle + */ + public DRectangle getMinRectangle() { + return (DRectangle) min_rect.clone(); + } - /** - * method returns the minmal x-value which can be displayed in the DArea - * - * @return the minmal x-value - */ - public double getMinX() { - if (min_x != null) { - return min_x.doubleValue(); - } - return 0; - } + /** + * method returns the minmal x-value which can be displayed in the DArea + * + * @return the minmal x-value + */ + public double getMinX() { + if (min_x != null) { + return min_x.doubleValue(); + } + return 0; + } - /** - * method returns the minmal y-value which can be displayed in the DArea - * - * @return the minmal y-value - */ - public double getMinY() { - if (min_y != null) { - return min_y.doubleValue(); - } - return 0; - } + /** + * method returns the minmal y-value which can be displayed in the DArea + * + * @return the minmal y-value + */ + public double getMinY() { + if (min_y != null) { + return min_y.doubleValue(); + } + return 0; + } - /** - * returns the currently visible rectangle in DArea coordinates - * - * @return DRectangle the size and position of the visible area - */ - public SlimRect getSlimRectangle() { - SlimRect srect = new SlimRect(visible_rect.getX(), visible_rect.getY(), - visible_rect.getWidth(), visible_rect.getHeight()); - if (min_x != null) { - srect.x = Math.max(srect.x, getMinX()); - } - if (min_y != null) { - srect.y = Math.max(srect.y, getMinY()); - } - if (max_x != null) { - srect.width = Math.min(srect.width, getMaxX() - getMinX()); - } - if (max_y != null) { - srect.height = Math.min(srect.height, getMaxY() - getMinY()); - } - return srect; - } + /** + * returns the currently visible rectangle in DArea coordinates + * + * @return DRectangle the size and position of the visible area + */ + public SlimRect getSlimRectangle() { + SlimRect srect = new SlimRect(visible_rect.getX(), visible_rect.getY(), + visible_rect.getWidth(), visible_rect.getHeight()); + if (min_x != null) { + srect.x = Math.max(srect.x, getMinX()); + } + if (min_y != null) { + srect.y = Math.max(srect.y, getMinY()); + } + if (max_x != null) { + srect.width = Math.min(srect.width, getMaxX() - getMinX()); + } + if (max_y != null) { + srect.height = Math.min(srect.height, getMaxY() - getMinY()); + } + return srect; + } - public DFunction getYScale() { - return measures.y_scale; - } + public DFunction getYScale() { + return measures.y_scale; + } - /** - * returns if the auto grid is switched on - * - * @return true if the grid is on, else false - */ - public boolean hasAutoGrid() { - return auto_grid; - } + /** + * returns if the auto grid is switched on + * + * @return true if the grid is on, else false + */ + public boolean hasAutoGrid() { + return auto_grid; + } - /** - * returns if the grid is visible true if the grid is visible - * or false if not - * - * @return true or false - */ - public boolean isGridVisible() { - return grid.isVisible(); - } + /** + * returns if the grid is visible true if the grid is visible + * or false if not + * + * @return true or false + */ + public boolean isGridVisible() { + return grid.isVisible(); + } - /** - * returns whether the DArea's auto focus is on or not - * - * @return true or false - */ - public boolean isOnAutoFocus() { - return auto_focus; - } + /** + * returns whether the DArea's auto focus is on or not + * + * @return true or false + */ + public boolean isOnAutoFocus() { + return auto_focus; + } - /** - * Method to check whether or not this {@link DArea} adds a grid to its - * plot. - * - * @return true if this {@link DArea} shows a grid and false otherwise. - */ - public boolean isShowGrid() { - return grid.isVisible(); - } + /** + * Method to check whether or not this {@link DArea} adds a grid to its + * plot. + * + * @return true if this {@link DArea} shows a grid and false otherwise. + */ + public boolean isShowGrid() { + return grid.isVisible(); + } - /** - * paints the DArea by a Graphics object - * - * @param g - * the java.awt.Graphics object - */ + /** + * paints the DArea by a Graphics object + * + * @param g the java.awt.Graphics object + */ @Override - public void paint(Graphics g) { - if (TRACE) { - System.out.println("DArea.paint(Graphics)"); - } - if (auto_focus) { - container.restore(); - visible_rect = (DRectangle) container.getRectangle().clone(); - // grid.updateDistByRect(visible_rect); - } - if (visible_rect.isEmpty()) { - visible_rect = (DRectangle) min_rect.clone(); - // grid.updateDistByRect(visible_rect); - } - super.paint(g); + public void paint(Graphics g) { + if (TRACE) { + System.out.println("DArea.paint(Graphics)"); + } + if (auto_focus) { + container.restore(); + visible_rect = (DRectangle) container.getRectangle().clone(); + // grid.updateDistByRect(visible_rect); + } + if (visible_rect.isEmpty()) { + visible_rect = (DRectangle) min_rect.clone(); + // grid.updateDistByRect(visible_rect); + } + super.paint(g); - measures.setGraphics(g); - if (grid.isVisible() && !grid_to_front) { - paintGrid(measures); - } - container.paint(measures); - if (grid.isVisible() && grid_to_front) { - paintGrid(measures); - } - } + measures.setGraphics(g); + if (grid.isVisible() && !grid_to_front) { + paintGrid(measures); + } + container.paint(measures); + if (grid.isVisible() && grid_to_front) { + paintGrid(measures); + } + } - /** - * method paints the grid how the method paints the grid depends on whether - * the area is wrapped in a ScaledBorder or not and on the - * auto_grid option - */ - private void paintGrid(DMeasures m) { - if (TRACE) { - System.out.println("DArea.paintGrid(DMeasures)"); - } - grid.rectangle = getDRectangle(); - if (auto_grid) { - Border b = getBorder(); - if (b instanceof ScaledBorder) { - ScaledBorder sb = (ScaledBorder) b; - paintGrid(sb, m); - return; - } else { - grid.setDistances(ScaledBorder.aBitBigger(grid.rectangle - .getWidth() - / max_grid), ScaledBorder.aBitBigger(grid.rectangle - .getHeight() - / max_grid)); - } - } - grid.paint(m); - } - - /** - * paints the grid when auto_grid is selected and the area is surrounded by - * an instance of ScaledBorder - * - * @param sb - * the ScaledBorder around the area - * @param m - * the measures of the area - */ - private void paintGrid(ScaledBorder sb, DMeasures m) { - if (TRACE) { - System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)"); - } - Dimension d = getSize(); - FontMetrics fm = m.getGraphics().getFontMetrics(); - grid.setDistances(sb.getSrcdX(fm, d), sb.getSrcdY(fm, d)); - - if (m.x_scale == null && m.y_scale == null) { - grid.paint(m); - } - - else {// selber malen - Graphics g = m.g; - g.setColor(grid.getColor()); - - SlimRect rect = getSlimRectangle(); - SlimRect src_rect = m.getSourceOf(rect); - - int x = (int) (src_rect.x / grid.getHorDist()), y = (int) (src_rect.y / grid - .getVerDist()); - if (x * grid.getHorDist() < src_rect.x) { - x++; - } - if (y * grid.getVerDist() < src_rect.y) { - y++; - } - - // DPoint min = new DPoint( rect.x, rect.y ), - // max = new DPoint( min.x + rect.width, min.y + rect.height ); - double minx = rect.x, miny = rect.y, maxx = minx + rect.width, maxy = miny - + rect.height; - - double pos; - - for (; (pos = x * grid.getHorDist()) < src_rect.x + src_rect.width; x++) { - if (m.x_scale != null) { - pos = m.x_scale.getImageOf(pos); - } - Point p1 = m.getPoint(pos, miny), p2 = m.getPoint(pos, maxy); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - - for (; (pos = y * grid.getVerDist()) < src_rect.y + src_rect.height; y++) { - if (m.y_scale != null) { - pos = m.y_scale.getImageOf(pos); - } - Point p1 = m.getPoint(minx, pos), p2 = m.getPoint(maxx, pos); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - } - } - - /** - * prints the area and it's content - * - * @see java.awt.print.Printable and - * @see java.awt.print.PrintJob - * - * @param g - * the Graphics object - * @param pf - * the @see java.awt.print.PageFormat - * @param pi - * the page index - * - * @return int @see java.awt.print.Printable - */ - @Override - public int print(Graphics g, PageFormat pf, int pi) { - if (TRACE) { - System.out.println("DArea.print(...)"); - } - if (pi > 0) { - return Printable.NO_SUCH_PAGE; - } - - Border sb = getBorder(); - if (!(sb instanceof ScaledBorder)) { - sb = null; - } - else { - ((ScaledBorder) sb).show_outer_border = false; - } - PagePrinter printer = new PagePrinter(this, g, pf); - int ret = printer.print(); - if (sb != null) { - ((ScaledBorder) sb).show_outer_border = true; - } - return ret; - } - - /** - * method resets the maximal x-value - */ - public void releaseMaxX() { - max_x = null; - } - - /** - * method resets the maximal y-value - */ - public void releaseMaxY() { - max_y = null; - } - - /** - * method resets the minimal x-value - */ - public void releaseMinX() { - min_x = null; - } - - /** - * method resets the minimal y-value - */ - public void releaseMinY() { - min_y = null; - } - - /** - * removes all elements from the area - */ - public void removeAllDElements() { - visible_rect = (DRectangle) min_rect.clone(); - container.removeAllDElements(); - } - - /** - * removes a certain element from the area - * - * @param e - * the element to remove - */ - @Override - public boolean removeDElement(DElement e) { - return container.removeDElement(e); - } - - /** - * repaints a part of the visible area - * - * @param r - * the rectangle to repaint - */ - @Override - public void repaint(DRectangle r) { - if (TRACE) { - System.out.println("DArea.repaint(DRectangle)" + r); - } - if (r == null) { - throw new IllegalArgumentException( - "Cannot repaint a null DRectangle"); - } - if (r.isAll() || auto_focus) { - repaint(); - } - else { - Point p1 = measures.getPoint(r.getX(), r.getY()), p2 = measures - .getPoint(r.getX() + r.getWidth(), r.getY() + r.getHeight()); - // Point p1 = measures.getPoint( r.x, r.y ), - // p2 = measures.getPoint( r.x + r.width, r.y + r.height); - if (p1 == null || p2 == null) { - repaint(); - } - else { - DBorder b = getDBorder(); - repaint(p1.x - b.left, p2.y - b.top, p2.x - p1.x + 1 + b.left - + b.right, p1.y - p2.y + 1 + b.top + b.bottom); - } - } - } - - @Override - public void restoreBorder() { - dborder = container.getDBorder(); - if (TRACE) { - System.out.println("DArea.restoreBorder -> " + dborder); - } - } - - /** - * switches the auto focus of this DArea on or off - * - * @param b - * on or off - */ - public void setAutoFocus(boolean b) { - boolean old = auto_focus; - auto_focus = b; - if (old != b) { - repaint(); - } - } - - /** - * sets the auto grid on or off if it's on, the grid's distances (@see - * #setGrid(double, double)) are automatically calculated - * - * @param b - * auto grid on or not - */ - public void setAutoGrid(boolean b) { - if (b) { - grid.rectangle = getDRectangle(); - grid.setVisible(true); - } - if (b == auto_grid) { + /** + * method paints the grid how the method paints the grid depends on whether + * the area is wrapped in a ScaledBorder or not and on the + * auto_grid option + */ + private void paintGrid(DMeasures m) { + if (TRACE) { + System.out.println("DArea.paintGrid(DMeasures)"); + } + grid.rectangle = getDRectangle(); + if (auto_grid) { + Border b = getBorder(); + if (b instanceof ScaledBorder) { + ScaledBorder sb = (ScaledBorder) b; + paintGrid(sb, m); return; + } else { + grid.setDistances(ScaledBorder.aBitBigger(grid.rectangle + .getWidth() + / max_grid), ScaledBorder.aBitBigger(grid.rectangle + .getHeight() + / max_grid)); } - auto_grid = b; - repaint(); - } + } + grid.paint(m); + } - /** - * sets the grid's horizontal and vertical distance that means that the - * grid's lines will have these distances in area coordinates - * - * @param hor_dist - * the horizontal distance - * @param ver_dist - * the vertical distance - */ - public void setGrid(double hor_dist, double ver_dist) { - grid = new DGrid(visible_rect, hor_dist, ver_dist); - grid.setDParent(this); - auto_grid = false; - repaint(); - } + /** + * paints the grid when auto_grid is selected and the area is surrounded by + * an instance of ScaledBorder + * + * @param sb the ScaledBorder around the area + * @param m the measures of the area + */ + private void paintGrid(ScaledBorder sb, DMeasures m) { + if (TRACE) { + System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)"); + } + Dimension d = getSize(); + FontMetrics fm = m.getGraphics().getFontMetrics(); + grid.setDistances(sb.getSrcdX(fm, d), sb.getSrcdY(fm, d)); - /** - * sets the color of the grid - * - * @param java - * .awt.Color - */ - public void setGridColor(Color color) { - grid.setColor(color); - } + if (m.x_scale == null && m.y_scale == null) { + grid.paint(m); + } else {// selber malen + Graphics g = m.g; + g.setColor(grid.getColor()); - /** - * sets the grid to the front that means that the grid is painted as last - * element default value is false - * - * @param aFlag - * grid t front or not - */ - public void setGridToFront(boolean aFlag) { - boolean old = grid_to_front; - grid_to_front = aFlag; - if (old != aFlag && grid.isVisible()) { + SlimRect rect = getSlimRectangle(); + SlimRect src_rect = m.getSourceOf(rect); + + int x = (int) (src_rect.x / grid.getHorDist()), y = (int) (src_rect.y / grid + .getVerDist()); + if (x * grid.getHorDist() < src_rect.x) { + x++; + } + if (y * grid.getVerDist() < src_rect.y) { + y++; + } + + // DPoint min = new DPoint( rect.x, rect.y ), + // max = new DPoint( min.x + rect.width, min.y + rect.height ); + double minx = rect.x, miny = rect.y, maxx = minx + rect.width, maxy = miny + + rect.height; + + double pos; + + for (; (pos = x * grid.getHorDist()) < src_rect.x + src_rect.width; x++) { + if (m.x_scale != null) { + pos = m.x_scale.getImageOf(pos); + } + Point p1 = m.getPoint(pos, miny), p2 = m.getPoint(pos, maxy); + g.drawLine(p1.x, p1.y, p2.x, p2.y); + } + + for (; (pos = y * grid.getVerDist()) < src_rect.y + src_rect.height; y++) { + if (m.y_scale != null) { + pos = m.y_scale.getImageOf(pos); + } + Point p1 = m.getPoint(minx, pos), p2 = m.getPoint(maxx, pos); + g.drawLine(p1.x, p1.y, p2.x, p2.y); + } + } + } + + /** + * prints the area and it's content + * + * @param g the Graphics object + * @param pf the @see java.awt.print.PageFormat + * @param pi the page index + * @return int @see java.awt.print.Printable + * @see java.awt.print.Printable and + * @see java.awt.print.PrintJob + */ + @Override + public int print(Graphics g, PageFormat pf, int pi) { + if (TRACE) { + System.out.println("DArea.print(...)"); + } + if (pi > 0) { + return Printable.NO_SUCH_PAGE; + } + + Border sb = getBorder(); + if (!(sb instanceof ScaledBorder)) { + sb = null; + } else { + ((ScaledBorder) sb).show_outer_border = false; + } + PagePrinter printer = new PagePrinter(this, g, pf); + int ret = printer.print(); + if (sb != null) { + ((ScaledBorder) sb).show_outer_border = true; + } + return ret; + } + + /** + * method resets the maximal x-value + */ + public void releaseMaxX() { + max_x = null; + } + + /** + * method resets the maximal y-value + */ + public void releaseMaxY() { + max_y = null; + } + + /** + * method resets the minimal x-value + */ + public void releaseMinX() { + min_x = null; + } + + /** + * method resets the minimal y-value + */ + public void releaseMinY() { + min_y = null; + } + + /** + * removes all elements from the area + */ + public void removeAllDElements() { + visible_rect = (DRectangle) min_rect.clone(); + container.removeAllDElements(); + } + + /** + * removes a certain element from the area + * + * @param e the element to remove + */ + @Override + public boolean removeDElement(DElement e) { + return container.removeDElement(e); + } + + /** + * repaints a part of the visible area + * + * @param r the rectangle to repaint + */ + @Override + public void repaint(DRectangle r) { + if (TRACE) { + System.out.println("DArea.repaint(DRectangle)" + r); + } + if (r == null) { + throw new IllegalArgumentException( + "Cannot repaint a null DRectangle"); + } + if (r.isAll() || auto_focus) { + repaint(); + } else { + Point p1 = measures.getPoint(r.getX(), r.getY()), p2 = measures + .getPoint(r.getX() + r.getWidth(), r.getY() + r.getHeight()); + // Point p1 = measures.getPoint( r.x, r.y ), + // p2 = measures.getPoint( r.x + r.width, r.y + r.height); + if (p1 == null || p2 == null) { repaint(); + } else { + DBorder b = getDBorder(); + repaint(p1.x - b.left, p2.y - b.top, p2.x - p1.x + 1 + b.left + + b.right, p1.y - p2.y + 1 + b.top + b.bottom); } - } + } + } - /** - * sets the grid visible or not - * - * @param aFlag - * visible or not - */ - public void setGridVisible(boolean aFlag) { - if (TRACE) { - System.out.println("DArea.setGridVisisble: " + aFlag); - } - grid.rectangle = getDRectangle(); - grid.setVisible(aFlag); - } + @Override + public void restoreBorder() { + dborder = container.getDBorder(); + if (TRACE) { + System.out.println("DArea.restoreBorder -> " + dborder); + } + } - /** - * sets the maximal number of grid lines default value is 10 - * - * @param no - * maximal number of grid lines - */ - public void setMaxGrid(int no) { - if (no < 1) { - return; - } - int old = max_grid; - max_grid = no; - if (old != no) { - repaint(); - } - } + /** + * switches the auto focus of this DArea on or off + * + * @param b on or off + */ + public void setAutoFocus(boolean b) { + boolean old = auto_focus; + auto_focus = b; + if (old != b) { + repaint(); + } + } - /** - * method sets the maximal x-value which can be displayed by the DArea might - * be helpful, if scale functions are used which are not defined overall - * - * @param max - * the maximal x-value - */ - public void setMaxX(double max) { - if (max < min_rect.getX() + min_rect.getWidth()) { - throw new IllegalArgumentException( - "Maximal x-value axes intersects minmal rectangle."); - } - max_x = new Double(max); - } + /** + * sets the auto grid on or off if it's on, the grid's distances (@see + * #setGrid(double, double)) are automatically calculated + * + * @param b auto grid on or not + */ + public void setAutoGrid(boolean b) { + if (b) { + grid.rectangle = getDRectangle(); + grid.setVisible(true); + } + if (b == auto_grid) { + return; + } + auto_grid = b; + repaint(); + } - /** - * method sets the maximal y-values which can be displayed by the DArea - * might be helpful, if scale functions are used which are not defined - * overall - * - * @param may - * the maximal y-value - */ - public void setMaxY(double may) { - if (may < min_rect.getY() + min_rect.getHeight()) { - throw new IllegalArgumentException( - "Maximal y-value axes intersects minmal rectangle."); - } - max_y = new Double(may); - } + /** + * sets the grid's horizontal and vertical distance that means that the + * grid's lines will have these distances in area coordinates + * + * @param hor_dist the horizontal distance + * @param ver_dist the vertical distance + */ + public void setGrid(double hor_dist, double ver_dist) { + grid = new DGrid(visible_rect, hor_dist, ver_dist); + grid.setDParent(this); + auto_grid = false; + repaint(); + } - /** - * sets the minimal rectangle - * - * @param x - * @param y - * @param width - * @param height - */ - public void setMinRectangle(double x, double y, double width, double height) { - setMinRectangle(new DRectangle(x, y, width, height)); - } + /** + * sets the color of the grid + * + * @param java .awt.Color + */ + public void setGridColor(Color color) { + grid.setColor(color); + } - /** - * sets the minimal rectangle - * - * @param rect - * the visible DRectangle in DArea coordinates - */ - public void setMinRectangle(DRectangle rect) { - if (rect.isEmpty()) { - min_rect = DEFAULT_MIN_RECT; - } - else { - min_rect = (DRectangle) rect.clone(); - } - } + /** + * sets the grid to the front that means that the grid is painted as last + * element default value is false + * + * @param aFlag grid t front or not + */ + public void setGridToFront(boolean aFlag) { + boolean old = grid_to_front; + grid_to_front = aFlag; + if (old != aFlag && grid.isVisible()) { + repaint(); + } + } - /** - * method sets the minimal x-value which can be displayed by the DArea might - * be helpful, if scale functions are used which are not defined overall - * - * @param mix - * the minimal x-value - */ - public void setMinX(double mix) { - if (mix > min_rect.getX()) { - throw new IllegalArgumentException( - "Mimimal y-value axes intersects minmal rectangle."); - } - min_x = new Double(mix); - } + /** + * sets the grid visible or not + * + * @param aFlag visible or not + */ + public void setGridVisible(boolean aFlag) { + if (TRACE) { + System.out.println("DArea.setGridVisisble: " + aFlag); + } + grid.rectangle = getDRectangle(); + grid.setVisible(aFlag); + } - /** - * method sets the minimal y-value which can be displayed by the DArea might - * be helpful, if scale functions are used which are not defined overall - * - * @param miy - * the minimal y-value - */ - public void setMinY(double miy) { - if (miy > min_rect.getY()) { - throw new IllegalArgumentException( - "Mimimal y-value axes intersects minmal rectangle."); - } - min_y = new Double(miy); - } + /** + * sets the maximal number of grid lines default value is 10 + * + * @param no maximal number of grid lines + */ + public void setMaxGrid(int no) { + if (no < 1) { + return; + } + int old = max_grid; + max_grid = no; + if (old != no) { + repaint(); + } + } - /** - * sets the visible rectangle to this size - * - * @param x - * the x coordinate of the left border - * @param y - * the y coordinate of the bottom border - * @param width - * the width of the area - * @param height - * the height of the area - */ - public void setVisibleRectangle(double x, double y, double width, - double height) { - // System.out.println("DArea.setVisibleRectangle(...)"); - setVisibleRectangle(new DRectangle(x, y, width, height)); - } + /** + * method sets the maximal x-value which can be displayed by the DArea might + * be helpful, if scale functions are used which are not defined overall + * + * @param max the maximal x-value + */ + public void setMaxX(double max) { + if (max < min_rect.getX() + min_rect.getWidth()) { + throw new IllegalArgumentException( + "Maximal x-value axes intersects minmal rectangle."); + } + max_x = new Double(max); + } - /** - * sets the visible rectangle - * - * @param rect - * the visible DRectangle in DArea coordinates - */ - public void setVisibleRectangle(DRectangle rect) { - if (TRACE) { - System.out.println("DArea.setVisibleRectangle(DRectangle)"); - } - if (rect.isEmpty()) { - throw new IllegalArgumentException( - "You should never try to set an empty rectangle\n" - + "as the visible rectangle of an DArea"); - } + /** + * method sets the maximal y-values which can be displayed by the DArea + * might be helpful, if scale functions are used which are not defined + * overall + * + * @param may the maximal y-value + */ + public void setMaxY(double may) { + if (may < min_rect.getY() + min_rect.getHeight()) { + throw new IllegalArgumentException( + "Maximal y-value axes intersects minmal rectangle."); + } + max_y = new Double(may); + } - if (!rect.equals(visible_rect) && rect.getWidth() > 0 - && rect.getHeight() > 0) { - auto_focus = false; - visible_rect = (DRectangle) rect.clone(); - repaint(); - } - } + /** + * sets the minimal rectangle + * + * @param x + * @param y + * @param width + * @param height + */ + public void setMinRectangle(double x, double y, double width, double height) { + setMinRectangle(new DRectangle(x, y, width, height)); + } - /** - * sets a new scale function to the x-axis That means that not the standard - * linear scale is shown but the image of the linear scale under the given - * function - * - * @param x_s - * the scale function for the x-axis - */ - public void setXScale(DFunction x_s) { - if (x_s == null && measures.x_scale == null) { - return; - } - measures.x_scale = x_s; - repaint(); - } + /** + * sets the minimal rectangle + * + * @param rect the visible DRectangle in DArea coordinates + */ + public void setMinRectangle(DRectangle rect) { + if (rect.isEmpty()) { + min_rect = DEFAULT_MIN_RECT; + } else { + min_rect = (DRectangle) rect.clone(); + } + } - /** - * sets a new scale function to the y-axis That means that not the standard - * linear scale is shown but the image of the linear scale under the given - * function - * - * @param y_s - * the scale function for the y-axis - */ - public void setYScale(DFunction y_s) { - if (y_s == null && measures.y_scale == null) { - return; - } - measures.y_scale = y_s; - repaint(); - } + /** + * method sets the minimal x-value which can be displayed by the DArea might + * be helpful, if scale functions are used which are not defined overall + * + * @param mix the minimal x-value + */ + public void setMinX(double mix) { + if (mix > min_rect.getX()) { + throw new IllegalArgumentException( + "Mimimal y-value axes intersects minmal rectangle."); + } + min_x = new Double(mix); + } + + /** + * method sets the minimal y-value which can be displayed by the DArea might + * be helpful, if scale functions are used which are not defined overall + * + * @param miy the minimal y-value + */ + public void setMinY(double miy) { + if (miy > min_rect.getY()) { + throw new IllegalArgumentException( + "Mimimal y-value axes intersects minmal rectangle."); + } + min_y = new Double(miy); + } + + /** + * sets the visible rectangle to this size + * + * @param x the x coordinate of the left border + * @param y the y coordinate of the bottom border + * @param width the width of the area + * @param height the height of the area + */ + public void setVisibleRectangle(double x, double y, double width, + double height) { + // System.out.println("DArea.setVisibleRectangle(...)"); + setVisibleRectangle(new DRectangle(x, y, width, height)); + } + + /** + * sets the visible rectangle + * + * @param rect the visible DRectangle in DArea coordinates + */ + public void setVisibleRectangle(DRectangle rect) { + if (TRACE) { + System.out.println("DArea.setVisibleRectangle(DRectangle)"); + } + if (rect.isEmpty()) { + throw new IllegalArgumentException( + "You should never try to set an empty rectangle\n" + + "as the visible rectangle of an DArea"); + } + + if (!rect.equals(visible_rect) && rect.getWidth() > 0 + && rect.getHeight() > 0) { + auto_focus = false; + visible_rect = (DRectangle) rect.clone(); + repaint(); + } + } + + /** + * sets a new scale function to the x-axis That means that not the standard + * linear scale is shown but the image of the linear scale under the given + * function + * + * @param x_s the scale function for the x-axis + */ + public void setXScale(DFunction x_s) { + if (x_s == null && measures.x_scale == null) { + return; + } + measures.x_scale = x_s; + repaint(); + } + + /** + * sets a new scale function to the y-axis That means that not the standard + * linear scale is shown but the image of the linear scale under the given + * function + * + * @param y_s the scale function for the y-axis + */ + public void setYScale(DFunction y_s) { + if (y_s == null && measures.y_scale == null) { + return; + } + measures.y_scale = y_s; + repaint(); + } } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/DArray.java b/src/eva2/tools/chart2d/DArray.java index 7e9031ae..b0c6afa6 100644 --- a/src/eva2/tools/chart2d/DArray.java +++ b/src/eva2/tools/chart2d/DArray.java @@ -15,269 +15,287 @@ package eva2.tools.chart2d; * For that use, it is important to tell the DPoitSet object, when the data has * been modified. */ -public class DArray implements DIntDoubleMap{ - private int initial_capacity, size; - private double capacity_multiplier = 2, max, min, minPositive=-1; - private double[] value; +public class DArray implements DIntDoubleMap { + private int initial_capacity, size; + private double capacity_multiplier = 2, max, min, minPositive = -1; + private double[] value; - /** - * Constructor for an DArray object with default values for the initial - * capacity (5) and the capacity multiplier (2). - */ - public DArray(){ - this(5, 2); - } + /** + * Constructor for an DArray object with default values for the initial + * capacity (5) and the capacity multiplier (2). + */ + public DArray() { + this(5, 2); + } - /** - * Constructor for an DArray object with default value for the capacity - * multiplier (2). - * - * @param initial_capacity the initial capacity of the array - */ - public DArray(int initial_capacity){ - this(initial_capacity, 2); - } + /** + * Constructor for an DArray object with default value for the capacity + * multiplier (2). + * + * @param initial_capacity the initial capacity of the array + */ + public DArray(int initial_capacity) { + this(initial_capacity, 2); + } - /** - * Constructor for an DArray object - * - * @param initial_capacity the initial capacity of the array - * @param capacity_multiplier the capacity multiplier when the array overflows - */ - public DArray(int initial_capacity, double capacity_multiplier){ - if( initial_capacity < 1 ) { - throw -new IllegalArgumentException("The initial capacity has to be at least 1"); - } - if( capacity_multiplier <= 1 ) { - throw -new IllegalArgumentException("The capacity multiplier has to be bigger than 1"); - } - this.initial_capacity = initial_capacity; - value = new double[initial_capacity]; - this.capacity_multiplier = capacity_multiplier; - } + /** + * Constructor for an DArray object + * + * @param initial_capacity the initial capacity of the array + * @param capacity_multiplier the capacity multiplier when the array overflows + */ + public DArray(int initial_capacity, double capacity_multiplier) { + if (initial_capacity < 1) { + throw + new IllegalArgumentException("The initial capacity has to be at least 1"); + } + if (capacity_multiplier <= 1) { + throw + new IllegalArgumentException("The capacity multiplier has to be bigger than 1"); + } + this.initial_capacity = initial_capacity; + value = new double[initial_capacity]; + this.capacity_multiplier = capacity_multiplier; + } - /** - * method sets the image value to the given source value - * - * @param source the source value - * @param image the image value - */ + /** + * method sets the image value to the given source value + * + * @param source the source value + * @param image the image value + */ @Override - public boolean setImage(int source, double image){ - if(source<0 || source>=size) { - throw -new ArrayIndexOutOfBoundsException(source); - } - boolean min_max_changed = false, restore = false; - if( image < min ){ min = image; min_max_changed = true; } - else if( image > max ){ max = image; min_max_changed = true; } - if( value[source] == min || value[source] == max || (value[source]==minPositive)) { - restore = true; - } - value[source] = image; - if( restore ) { - min_max_changed = restore() || min_max_changed; - } - return min_max_changed; - } + public boolean setImage(int source, double image) { + if (source < 0 || source >= size) { + throw + new ArrayIndexOutOfBoundsException(source); + } + boolean min_max_changed = false, restore = false; + if (image < min) { + min = image; + min_max_changed = true; + } else if (image > max) { + max = image; + min_max_changed = true; + } + if (value[source] == min || value[source] == max || (value[source] == minPositive)) { + restore = true; + } + value[source] = image; + if (restore) { + min_max_changed = restore() || min_max_changed; + } + return min_max_changed; + } - /** - * method returns the image value of the given source value - * - * @param source the source value - * @return the image value - */ + /** + * method returns the image value of the given source value + * + * @param source the source value + * @return the image value + */ // public double getImage(int source){ // if(source<0 || source>=size) throw // new ArrayIndexOutOfBoundsException(source); // return value[source]; // } @Override - public double getImage(int source){ - if(source<0) { + public double getImage(int source) { + if (source < 0) { new ArrayIndexOutOfBoundsException(source); } - if(source>=size && size > 1) { - return value[size-1]; + if (source >= size && size > 1) { + return value[size - 1]; } - return value[source]; - } - - /** - * the given image value becomes the image of (highest source value + 1) - * - * @param image the new image value - * @return true<\code> when the minmal or the maximal image value - * has been changed by this method call, else it returns - * false @see #getMinImageValue(), #getMaxImageValue() - */ - @Override - public boolean addImage(double image){ - if( size >= value.length ){ - int new_length = (int)(value.length * capacity_multiplier); - if( !(new_length > value.length) ) { - new_length++; - } - double[] new_val = new double[new_length]; - System.arraycopy(value,0,new_val,0,value.length); - value = new_val; + return value[source]; } - boolean min_max_changed = false; - if( size == 0 ){ min = image; max = image; min_max_changed = true; if (image>0) { - minPositive=image; - }} - else { - if ((image >0) && ((image max ) { max = image; min_max_changed = true; } - else if( image < min ) { min = image; min_max_changed = true; } + + /** + * the given image value becomes the image of (highest source value + 1) + * + * @param image the new image value + * @return true<\code> when the minmal or the maximal image value + * has been changed by this method call, else it returns + * false @see #getMinImageValue(), #getMaxImageValue() + */ + @Override + public boolean addImage(double image) { + if (size >= value.length) { + int new_length = (int) (value.length * capacity_multiplier); + if (!(new_length > value.length)) { + new_length++; + } + double[] new_val = new double[new_length]; + System.arraycopy(value, 0, new_val, 0, value.length); + value = new_val; + } + boolean min_max_changed = false; + if (size == 0) { + min = image; + max = image; + min_max_changed = true; + if (image > 0) { + minPositive = image; + } + } else { + if ((image > 0) && ((image < minPositive) || (minPositive < 0))) { + minPositive = image; + min_max_changed = true; + } + if (image > max) { + max = image; + min_max_changed = true; + } else if (image < min) { + min = image; + min_max_changed = true; + } + } + value[size++] = image; + return min_max_changed; } - value[size++] = image; - return min_max_changed; - } - /** - * method returns the number of (source,image)-pairs stored in the array - * - * @return the size of the source value set - */ + /** + * method returns the number of (source,image)-pairs stored in the array + * + * @return the size of the source value set + */ @Override - public int getSize(){ - return size; - } - - /** - * this method checks if the minimal and the maximal image value has changed - * - * @return true if one of them changed - */ - @Override - public boolean restore(){ - if( size == 0 ) { - return false; - } - double old_min = min, old_max = max; - min = value[0]; - max = value[0]; - minPositive=Double.POSITIVE_INFINITY; - for( int i=1; i0 && (value[i] max ) { - max = value[i]; - } + public int getSize() { + return size; } - if (Double.isInfinite(minPositive)) { - minPositive=-1; - } - return (old_min != min) || (old_max != max); - } - /** - * throws all information away - */ + /** + * this method checks if the minimal and the maximal image value has changed + * + * @return true if one of them changed + */ @Override - public void reset(){ - size = 0; - value = new double[initial_capacity]; - } - - /** - * returns the minimal image value - * - * @return the minimal image value - */ - @Override - public double getMinImageValue(){ - if( size == 0 ) { - throw -new IllegalArgumentException("DArray is empty. No minimal value exists"); - } - return min; - } - - /** - * Return the minimal positive image value or the maximal value if none is positive. - * @return - */ - @Override - public double getMinPositiveImageValue() { - if ( size==0) { - throw - new IllegalArgumentException("DArray is empty. No minimal value exists"); - } - return (minPositive < 0) ? max : minPositive; - } - /** - * returns the maxmal image value - * - * @return the maxmal image value - */ - @Override - public double getMaxImageValue(){ - if( size == 0 ) { - throw -new IllegalArgumentException("DArray is empty. No maximal value exists"); - } - return max; - } - - /** - * method checks if the given object is equal to this DArray object. - * It looks for differences in the stored image values - * - * @param o the object to compare with - * @return true when the object is an DArray object, containing - * the same values - */ - @Override - public boolean equals(Object o){ - if( !(o instanceof DArray) ) { - return false; - } - DArray comp = (DArray)o; - if( comp.size != size ) { - return false; - } - if( comp.max != max ) { - return false; - } - if( comp.min != min ) { - return false; - } - if( comp.minPositive != minPositive) { - return false; - } - for( int i=0; i 0 && (value[i] < minPositive)) { + minPositive = value[i]; + } + if (value[i] < min) { + min = value[i]; + } else if (value[i] > max) { + max = value[i]; + } + } + if (Double.isInfinite(minPositive)) { + minPositive = -1; + } + return (old_min != min) || (old_max != max); + } + + /** + * throws all information away + */ + @Override + public void reset() { + size = 0; + value = new double[initial_capacity]; + } + + /** + * returns the minimal image value + * + * @return the minimal image value + */ + @Override + public double getMinImageValue() { + if (size == 0) { + throw + new IllegalArgumentException("DArray is empty. No minimal value exists"); + } + return min; + } + + /** + * Return the minimal positive image value or the maximal value if none is positive. + * + * @return + */ + @Override + public double getMinPositiveImageValue() { + if (size == 0) { + throw + new IllegalArgumentException("DArray is empty. No minimal value exists"); + } + return (minPositive < 0) ? max : minPositive; + } + + /** + * returns the maxmal image value + * + * @return the maxmal image value + */ + @Override + public double getMaxImageValue() { + if (size == 0) { + throw + new IllegalArgumentException("DArray is empty. No maximal value exists"); + } + return max; + } + + /** + * method checks if the given object is equal to this DArray object. + * It looks for differences in the stored image values + * + * @param o the object to compare with + * @return true when the object is an DArray object, containing + * the same values + */ + @Override + public boolean equals(Object o) { + if (!(o instanceof DArray)) { + return false; + } + DArray comp = (DArray) o; + if (comp.size != size) { + return false; + } + if (comp.max != max) { + return false; + } + if (comp.min != min) { + return false; + } + if (comp.minPositive != minPositive) { + return false; + } + for (int i = 0; i < size; i++) { + if (comp.value[i] != value[i]) { + return false; + } + } + return true; + } @Override - public String toString(){ - String text = "eva2.tools.chart2d.DArray[size:"+size; - if( size < 11 ) { - for( int i=0; i top ){ top = b.top; changed = true; } - if( b.bottom > bottom ){ bottom = b.bottom; changed = true; } - if( b.left > left ){ left = b.left; changed = true; } - if( b.right > right ){ right = b.right; changed = true; } - return changed; - } + public boolean insert(DBorder b) { + boolean changed = false; + if (b.top > top) { + top = b.top; + changed = true; + } + if (b.bottom > bottom) { + bottom = b.bottom; + changed = true; + } + if (b.left > left) { + left = b.left; + changed = true; + } + if (b.right > right) { + right = b.right; + changed = true; + } + return changed; + } @Override - public boolean equals( Object o ){ - if( o instanceof DBorder ) { - return super.equals( o ); - } - return false; - } + public boolean equals(Object o) { + if (o instanceof DBorder) { + return super.equals(o); + } + return false; + } @Override - public String toString(){ - return "eva2.tools.chart2d.DBorder[top="+top+",left="+left - +",bottom="+bottom+",right="+right+"]"; - } + public String toString() { + return "eva2.tools.chart2d.DBorder[top=" + top + ",left=" + left + + ",bottom=" + bottom + ",right=" + right + "]"; + } } \ No newline at end of file diff --git a/src/eva2/tools/chart2d/DComponent.java b/src/eva2/tools/chart2d/DComponent.java index 4386cf51..2880979c 100644 --- a/src/eva2/tools/chart2d/DComponent.java +++ b/src/eva2/tools/chart2d/DComponent.java @@ -16,7 +16,7 @@ package eva2.tools.chart2d; * IMPORTS *==========================================================================*/ -import java.awt.Color ; +import java.awt.Color; /*==========================================================================* * CLASS DECLARATION @@ -26,147 +26,158 @@ import java.awt.Color ; * DComponent is the mother of all objects which can be displayed * by a DArea object, even when it would be also enough to * implement the DElement interface to an class - * + *

* DComponent is abstract because the paint method has to be overridden */ -public abstract class DComponent implements DElement -{ - /** - * the color of the component - */ - protected Color color; +public abstract class DComponent implements DElement { + /** + * the color of the component + */ + protected Color color; - /** - * the rectangle in which the component lies - */ - protected DRectangle rectangle; + /** + * the rectangle in which the component lies + */ + protected DRectangle rectangle; - /** - * the parent of the component which is responsible for repainting - */ - protected DParent parent; + /** + * the parent of the component which is responsible for repainting + */ + protected DParent parent; - private boolean visible = true; + private boolean visible = true; - - /** - * this border respresents the additional space around the clip of the - * graphics context, which is calculated by the union of all DRectangles of - * the components. For example it is used by DPointIcons or DLabels. - */ - private DBorder border = new DBorder(); + /** + * this border respresents the additional space around the clip of the + * graphics context, which is calculated by the union of all DRectangles of + * the components. For example it is used by DPointIcons or DLabels. + */ + private DBorder border = new DBorder(); - /** - * this constructor is necessary to avoid infinite loops in constructing - * DRectangles - */ - DComponent(boolean is_rect){} - - public DComponent(){ rectangle = DRectangle.getEmpty(); } - - /** - * returns the rectangle in which the object lies - */ - @Override - public DRectangle getRectangle(){ - return (DRectangle)rectangle.clone(); - } - - - /** - * method sets a certain border around the contained rectangle - * - * @param b the new DBorder - */ - @Override - public void setDBorder( DBorder b ){ - if( parent != null ) { - if( border.insert(b) ) { parent.addDBorder( b ); repaint(); } - else { border = b; parent.restoreBorder(); } + /** + * this constructor is necessary to avoid infinite loops in constructing + * DRectangles + */ + DComponent(boolean is_rect) { } - else { - border = b; - } - } - /** - * method returns the current border around the rectangle - * - * @return the DBorder of the DComponent - */ - @Override - public DBorder getDBorder(){ - return border; - } - - /** - * sets the parent of the component, which should take care of painting the - * component to the right time - */ - @Override - public void setDParent( DParent parent ){ - if( this.parent != null && this.parent != parent ){ - this.parent.removeDElement( this ); - this.parent.repaint( getRectangle() ); + public DComponent() { + rectangle = DRectangle.getEmpty(); } - this.parent = parent; - } - /** - * returns the parent of the component - */ + /** + * returns the rectangle in which the object lies + */ @Override - public DParent getDParent(){ return parent; } - - /** - * invoces the parent to repaint the rectangle in which the component lies - */ - @Override - public void repaint(){ - //System.out.println("DComponent.repaint()"); - if( parent != null ) { - parent.repaint( getRectangle() ); - } - } - - /** - * sets the color of the component - */ - @Override - public void setColor( Color color ){ - if( this.color == null || !this.color.equals( color ) ) { - this.color = color; - repaint(); + public DRectangle getRectangle() { + return (DRectangle) rectangle.clone(); } - } - /** - * returns the color of the component - */ - @Override - public Color getColor(){ return color; } - /** - * sets the component visible or not - */ + /** + * method sets a certain border around the contained rectangle + * + * @param b the new DBorder + */ @Override - public void setVisible( boolean aFlag ){ - boolean changed = ( aFlag != visible ); - visible = aFlag; - if( changed ) { - repaint(); - } - } + public void setDBorder(DBorder b) { + if (parent != null) { + if (border.insert(b)) { + parent.addDBorder(b); + repaint(); + } else { + border = b; + parent.restoreBorder(); + } + } else { + border = b; + } + } - /** - * returns if the component should be visible when the parent shows the right - * area - */ + /** + * method returns the current border around the rectangle + * + * @return the DBorder of the DComponent + */ @Override - public boolean isVisible(){ return visible; } + public DBorder getDBorder() { + return border; + } + + /** + * sets the parent of the component, which should take care of painting the + * component to the right time + */ + @Override + public void setDParent(DParent parent) { + if (this.parent != null && this.parent != parent) { + this.parent.removeDElement(this); + this.parent.repaint(getRectangle()); + } + this.parent = parent; + } + + /** + * returns the parent of the component + */ + @Override + public DParent getDParent() { + return parent; + } + + /** + * invoces the parent to repaint the rectangle in which the component lies + */ + @Override + public void repaint() { + //System.out.println("DComponent.repaint()"); + if (parent != null) { + parent.repaint(getRectangle()); + } + } + + /** + * sets the color of the component + */ + @Override + public void setColor(Color color) { + if (this.color == null || !this.color.equals(color)) { + this.color = color; + repaint(); + } + } + + /** + * returns the color of the component + */ + @Override + public Color getColor() { + return color; + } + + /** + * sets the component visible or not + */ + @Override + public void setVisible(boolean aFlag) { + boolean changed = (aFlag != visible); + visible = aFlag; + if (changed) { + repaint(); + } + } + + /** + * returns if the component should be visible when the parent shows the right + * area + */ + @Override + public boolean isVisible() { + return visible; + } } diff --git a/src/eva2/tools/chart2d/DContainer.java b/src/eva2/tools/chart2d/DContainer.java index 3dd7c90d..4d5f93f4 100644 --- a/src/eva2/tools/chart2d/DContainer.java +++ b/src/eva2/tools/chart2d/DContainer.java @@ -23,228 +23,230 @@ import java.util.Vector; * CLASS DECLARATION *==========================================================================*/ -public class DContainer extends DComponent implements DParent{ - /** - * the elements of the container and their keys ( Strings ) - */ - protected Vector elements; - protected Vector keys; +public class DContainer extends DComponent implements DParent { + /** + * the elements of the container and their keys ( Strings ) + */ + protected Vector elements; + protected Vector keys; - public DContainer(){ this(10); } - - public DContainer(int initial_capacity){ - super(); - elements = new Vector(initial_capacity); - keys = new Vector(initial_capacity); - } - - @Override - public void repaint( DRectangle r ){ - DParent parent = getDParent(); - if( parent != null ) { - parent.repaint( r ); - } - } - - /** - * method adds a new DElement to the container - * if the container already contains this element, the method simply returns - * the method checks whether the DElement is an ancestor of the container - * itself. In that case it throws an IllegalArgumentException. - * - * @param e the new DElement to add - */ - @Override - public void addDElement( DElement e ){ - addDElement( null, e ); - } - - - /** - * method adds a new DElement to the container by a certain key name - * if the container already contains this element, the method simply returns - * the method checks whether the DElement is an ancestor of the container - * itself. In that case it throws an IllegalArgumentException. - * - * @param key the name of the DElement in the container - * @param e the new DElement to add - */ - public void addDElement( String key, DElement e ){ - if( elements.contains( e ) ) { - return; - } - if( e instanceof DParent ){ - DParent he = (DParent)e, me = (DParent)this; - if( he == me ) { - throw new -IllegalArgumentException("Adding DParent to itself"); - } - me = getDParent(); - while( me != null ){ - if( he == me ) { - throw new - IllegalArgumentException("Adding DContainer's parent to itself"); - } - if( me instanceof DElement ) { - me = ((DElement)me).getDParent(); - } - else { - me = null; - } - } + public DContainer() { + this(10); } - elements.add( e ); - addDBorder( e.getDBorder() ); - keys.add( key ); - e.setDParent( this ); - DRectangle r = e.getRectangle(); - rectangle.insert( r ); - if( e.isVisible() ) { - repaint( r ); - } - } - /** - * method removes a certain DElement from the container an returns whether it - * contained it before - * - * @param e the DElement to remove - * @return if this was possible - */ - @Override - public boolean removeDElement( DElement e ){ - int index = elements.indexOf( e ); - if( index > -1 ){ - elements.remove( index ); - keys.remove( index ); - repaint( e.getRectangle() ); - restore(); - return true; + public DContainer(int initial_capacity) { + super(); + elements = new Vector(initial_capacity); + keys = new Vector(initial_capacity); } - return false; - } - /** - * method removes all DElements from the container - */ - public void removeAllDElements() - { - elements.removeAllElements(); - keys.removeAllElements(); - rectangle = DRectangle.getEmpty(); - repaint(); - } - - /** - * method returns all DElements of the container - * - * @return the elements of the container - */ @Override - public DElement[] getDElements(){ - DElement[] es = new DElement[ elements.size() ]; - elements.toArray(es); - return es; - } - - /** - * method returns the first DElement of the contaioner belonging to - * the given key - * - * @param key the name of the DElement in the container - * @return the element when it could be found or null else - */ - public DElement getDElement( String key ){ - int index = -1; - for( int i=0; index == -1 && i < keys.size(); i++ ) { - if( ((String)keys.get(i)).equals( key ) ) { - index = i; + public void repaint(DRectangle r) { + DParent parent = getDParent(); + if (parent != null) { + parent.repaint(r); } - } - return (index -1) { + elements.remove(index); + keys.remove(index); + repaint(e.getRectangle()); + restore(); + return true; + } + return false; + } + + /** + * method removes all DElements from the container + */ + public void removeAllDElements() { + elements.removeAllElements(); + keys.removeAllElements(); + rectangle = DRectangle.getEmpty(); + repaint(); + } + + /** + * method returns all DElements of the container + * + * @return the elements of the container + */ + @Override + public DElement[] getDElements() { + DElement[] es = new DElement[elements.size()]; + elements.toArray(es); + return es; + } + + /** + * method returns the first DElement of the contaioner belonging to + * the given key + * + * @param key the name of the DElement in the container + * @return the element when it could be found or null else + */ + public DElement getDElement(String key) { + int index = -1; + for (int i = 0; index == -1 && i < keys.size(); i++) { + if (((String) keys.get(i)).equals(key)) { + index = i; + } + } + return (index < keys.size()) ? (DElement) elements.get(index) : (DElement) null; + } // implementing DComponent: - /** - * method calls all currently visible DElements of the container to paint - * themselves by the given DMeasures object - * - * @param m the DMeasures object - */ + + /** + * method calls all currently visible DElements of the container to paint + * themselves by the given DMeasures object + * + * @param m the DMeasures object + */ @Override - public void paint( DMeasures m ){ - DElement e; - for( int i=0; iDMeasures object to paint the grid - */ + public double getHorDist() { + return hor_dist; + } + + public double getVerDist() { + return ver_dist; + } + + /** + * paints the grid... + * + * @param m the DMeasures object to paint the grid + */ @Override - public void paint( DMeasures m ){ - Graphics g = m.getGraphics(); - if( color != null ) { - g.setColor( color ); - } - double minX, minY, pos; - DPoint p1, p2; - DLine l; + public void paint(DMeasures m) { + Graphics g = m.getGraphics(); + if (color != null) { + g.setColor(color); + } + double minX, minY, pos; + DPoint p1, p2; + DLine l; - minX=Mathematics.firstMultipleAbove(rectangle.getX(), hor_dist); - minY=Mathematics.firstMultipleAbove(rectangle.getY(), ver_dist); + minX = Mathematics.firstMultipleAbove(rectangle.getX(), hor_dist); + minY = Mathematics.firstMultipleAbove(rectangle.getY(), ver_dist); // minX = (int)( rectangle.x / hor_dist ); // if( minX * hor_dist <= rectangle.x ) minX++; // minX *= hor_dist; @@ -107,35 +108,35 @@ public class DGrid extends DComponent // if( minY * ver_dist <= rectangle.y ) minY++; // minY *= ver_dist; - p1 = new DPoint( 0, rectangle.getY() ); - p2 = new DPoint( 0, rectangle.getY() + rectangle.getHeight() ); - for( pos = minX; pos<=rectangle.getX() + rectangle.getWidth(); pos += hor_dist ){ - p1.x = p2.x = pos; - l = new DLine( p1, p2, color ); - l.paint( m ); - } - - p1.x = rectangle.getX(); - p2.x = p1.x + rectangle.getWidth(); - pos = minY; - while ( pos<=rectangle.getY() + rectangle.getHeight()){ - p1.y = p2.y = pos; - l = new DLine( p1, p2, color ); - l.paint( m ); - if (pos+ver_dist<=pos) { - System.err.println("Overflow error in DGrid!"); - pos *= 1.01; - } else { - pos += ver_dist; + p1 = new DPoint(0, rectangle.getY()); + p2 = new DPoint(0, rectangle.getY() + rectangle.getHeight()); + for (pos = minX; pos <= rectangle.getX() + rectangle.getWidth(); pos += hor_dist) { + p1.x = p2.x = pos; + l = new DLine(p1, p2, color); + l.paint(m); } + + p1.x = rectangle.getX(); + p2.x = p1.x + rectangle.getWidth(); + pos = minY; + while (pos <= rectangle.getY() + rectangle.getHeight()) { + p1.y = p2.y = pos; + l = new DLine(p1, p2, color); + l.paint(m); + if (pos + ver_dist <= pos) { + System.err.println("Overflow error in DGrid!"); + pos *= 1.01; + } else { + pos += ver_dist; + } // System.out.println("pos is " + pos + ", loop until " + rectangle.y + rectangle.height); + } } - } @Override - public String toString(){ - return "chart2d.DGrid[ hor: "+hor_dist+", ver: "+ver_dist+" ]"; - } + public String toString() { + return "chart2d.DGrid[ hor: " + hor_dist + ", ver: " + ver_dist + " ]"; + } } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/DIntDoubleMap.java b/src/eva2/tools/chart2d/DIntDoubleMap.java index 23d0c779..d162c05e 100644 --- a/src/eva2/tools/chart2d/DIntDoubleMap.java +++ b/src/eva2/tools/chart2d/DIntDoubleMap.java @@ -19,78 +19,78 @@ package eva2.tools.chart2d; */ public interface DIntDoubleMap { - /** - * implementation should change the map in that way, that from now the - * image of index is v - * - * @param source the preimage of the image - * @param image the new image of the source value - * @return true<\code> when the minmal or the maximal image value - * has been changed by this method call, else it returns - * false @see #getMinImageValue(), #getMaxImageValue() - */ - boolean setImage(int source, double image); + /** + * implementation should change the map in that way, that from now the + * image of index is v + * + * @param source the preimage of the image + * @param image the new image of the source value + * @return true<\code> when the minmal or the maximal image value + * has been changed by this method call, else it returns + * false @see #getMinImageValue(), #getMaxImageValue() + */ + boolean setImage(int source, double image); - /** - * implementation should return the image of source - * - * @param source the preimage - * @return the image value - */ - double getImage(int source); + /** + * implementation should return the image of source + * + * @param source the preimage + * @return the image value + */ + double getImage(int source); - /** - * the image of the highest source value + 1 should be the given image value - * - * @param image the new image value - * @return true<\code> when the minmal or the maximal image value - * has been changed by this method call, else it returns - * false @see #getMinImageValue(), #getMaxImageValue() - */ - boolean addImage(double image); + /** + * the image of the highest source value + 1 should be the given image value + * + * @param image the new image value + * @return true<\code> when the minmal or the maximal image value + * has been changed by this method call, else it returns + * false @see #getMinImageValue(), #getMaxImageValue() + */ + boolean addImage(double image); - /** - * implementation should return the number of source values - * - * @return the number of source values - */ - int getSize(); + /** + * implementation should return the number of source values + * + * @return the number of source values + */ + int getSize(); - /** - * returns the maximal image value - * - * @return the maximal image value - * @throw an IllegalArgumentException when it has no image values - */ - double getMaxImageValue(); + /** + * returns the maximal image value + * + * @return the maximal image value + * @throw an IllegalArgumentException when it has no image values + */ + double getMaxImageValue(); - /** - * returns the minimal image value - * - * @return the minmal image value - * @throw an IllegalArgumentException when it has no image values - */ - double getMinImageValue(); + /** + * returns the minimal image value + * + * @return the minmal image value + * @throw an IllegalArgumentException when it has no image values + */ + double getMinImageValue(); - /** - * returns the minimal image value - * - * @return the minmal image value - * @throw an IllegalArgumentException when it has no image values - */ - double getMinPositiveImageValue(); - - /** - * checks the minimal and the maximal image values and returns true - * when at least one of them has changed - * - * @return true when either the maximal image value or the - * minmal image value has changed - */ - boolean restore(); + /** + * returns the minimal image value + * + * @return the minmal image value + * @throw an IllegalArgumentException when it has no image values + */ + double getMinPositiveImageValue(); - /** - * method removes all image values and sets the size to 0 - */ - void reset(); + /** + * checks the minimal and the maximal image values and returns true + * when at least one of them has changed + * + * @return true when either the maximal image value or the + * minmal image value has changed + */ + boolean restore(); + + /** + * method removes all image values and sets the size to 0 + */ + void reset(); } \ No newline at end of file diff --git a/src/eva2/tools/chart2d/DLine.java b/src/eva2/tools/chart2d/DLine.java index 788bb46f..8b59c306 100644 --- a/src/eva2/tools/chart2d/DLine.java +++ b/src/eva2/tools/chart2d/DLine.java @@ -16,62 +16,68 @@ package eva2.tools.chart2d; * IMPORTS *==========================================================================*/ -import java.awt.* ; +import java.awt.*; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ -public class DLine extends DComponent -{ - DPoint start, end; +public class DLine extends DComponent { + DPoint start, end; - public DLine( double x1, double y1, double x2, double y2 ){ - this( new DPoint( x1, y1 ), new DPoint( x2, y2 ) ); - } - - public DLine( DPoint start, DPoint end ){ - this.start = start; - this.end = end; - } - public DLine( double x1, double y1, double x2, double y2, Color color ){ - this( new DPoint( x1, y1 ), new DPoint( x2, y2 ), color ); - } - - public DLine( DPoint start, DPoint end, Color color ){ - this.start = start; - this.end = end; - this.color = color; - } - - @Override - public DRectangle getRectangle(){ - double x = start.x, y = start.y, width = end.x - x, height = end.y - y; - if( width < 0 ) { x += width; width *= -1; } - if( height < 0 ) { y += height; height *= -1; } - return new DRectangle( x, y, width, height ); - } - - @Override - public void paint( DMeasures m ){ - //System.out.println("DLine.paint(Measures): "+this); - Graphics g = m.getGraphics(); - if( color != null ) { - g.setColor( color ); - } - Point p1 = m.getPoint( start.x, start.y ), - p2 = m.getPoint( end.x, end.y ) ; - if ((p1!=null) && (p2!=null)) { - g.drawLine( p1.x, p1.y, p2.x, p2.y ); - } else { - System.err.println("Couldnt paint rect!"); + public DLine(double x1, double y1, double x2, double y2) { + this(new DPoint(x1, y1), new DPoint(x2, y2)); + } + + public DLine(DPoint start, DPoint end) { + this.start = start; + this.end = end; + } + + public DLine(double x1, double y1, double x2, double y2, Color color) { + this(new DPoint(x1, y1), new DPoint(x2, y2), color); + } + + public DLine(DPoint start, DPoint end, Color color) { + this.start = start; + this.end = end; + this.color = color; } - } @Override - public String toString(){ - return "DLine[("+start.x+","+start.y+") --> ("+end.x+","+end.y+", color: "+color+"]"; - } + public DRectangle getRectangle() { + double x = start.x, y = start.y, width = end.x - x, height = end.y - y; + if (width < 0) { + x += width; + width *= -1; + } + if (height < 0) { + y += height; + height *= -1; + } + return new DRectangle(x, y, width, height); + } + + @Override + public void paint(DMeasures m) { + //System.out.println("DLine.paint(Measures): "+this); + Graphics g = m.getGraphics(); + if (color != null) { + g.setColor(color); + } + Point p1 = m.getPoint(start.x, start.y), + p2 = m.getPoint(end.x, end.y); + if ((p1 != null) && (p2 != null)) { + g.drawLine(p1.x, p1.y, p2.x, p2.y); + } else { + System.err.println("Couldnt paint rect!"); + } + } + + @Override + public String toString() { + return "DLine[(" + start.x + "," + start.y + ") --> (" + end.x + "," + end.y + ", color: " + color + "]"; + } } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/DMeasures.java b/src/eva2/tools/chart2d/DMeasures.java index d4944d2e..43318bff 100644 --- a/src/eva2/tools/chart2d/DMeasures.java +++ b/src/eva2/tools/chart2d/DMeasures.java @@ -10,104 +10,104 @@ import java.io.Serializable; /** * A class mainly for coordinate conversion. Replaced usage of DRectangle by SlimRect * which makes it more efficient. - * - * @author Fabian Hennecke, ulmerh, mkron * + * @author Fabian Hennecke, ulmerh, mkron */ -public class DMeasures implements Serializable -{ - /** - * - */ - private static final long serialVersionUID = 243092480517044848L; - private boolean under_construction = false; - // when in use for a DArea: - Graphics g; - // when in use for a ScaledBorder: - ScaledBorder sb; - // for both: - DFunction x_scale, y_scale; - Component comp; - Insets insets; +public class DMeasures implements Serializable { + /** + * + */ + private static final long serialVersionUID = 243092480517044848L; + private boolean under_construction = false; + // when in use for a DArea: + Graphics g; + // when in use for a ScaledBorder: + ScaledBorder sb; + // for both: + DFunction x_scale, y_scale; + Component comp; + Insets insets; - /** - * package private constructor for the DMeasures object - * the object can be obtained by calling the method getDMeasures of an DArea - * object - * - * @param area the DArea object - */ - DMeasures( DArea area ){ - comp = area; - } - - DMeasures( ScaledBorder sb ){ - this.sb = sb; - } - - /** - * method returns the pixel-point which belongs to the given D-coordinates - * it says where to paint a certain DPoint - * returns null if the double coordinates do not belong to the - * image of the scale functions - * - * @param x the double x D-coordinate - * @param y the double y D-coordinate - * @return the coresponding pixel Point - */ - public Point getPoint( double x, double y ){ - SlimRect rect = getSourceOf(getSlimRectangle()); - if (rect == null) { - return null; + /** + * package private constructor for the DMeasures object + * the object can be obtained by calling the method getDMeasures of an DArea + * object + * + * @param area the DArea object + */ + DMeasures(DArea area) { + comp = area; } - try{ - if( x_scale != null ) { - x = x_scale.getSourceOf( x ); - } - if( y_scale != null ) { - y = y_scale.getSourceOf( y ); - } - } - catch( IllegalArgumentException e ){ return null; } - Point dp = new Point(); - Dimension dim = getInner(); - Insets insets = getInsets(); - dp.x = (int)( dim.width * (x - rect.x)/(double)rect.width ) + insets.left; - dp.y = (int)( dim.height * (1 - (y - rect.y)/(double)rect.height)) + insets.top; - return dp; - } - /** - * method returns the point in D-coordinates which corresponds to the - * given pixel-coordinates - * returns null if the given coordinates can not be calculated to - * the double coordinates, when they represent a point outside of the definition - * area of the scale functions - * - * @param x x-pixel coordinate - * @param y y-pixel coordinate - * @return the coresponding DPoint - */ - public DPoint getDPoint( int x, int y ){ - SlimRect rect = getSourceOf(getSlimRectangle()); - Dimension dim = getInner(); - Insets insets = getInsets(); - x -= insets.left; - y -= insets.top; - double dx, dy; - dx = rect.x + rect.width * x/(double)dim.width; - dy = rect.y + rect.height * (1 - y/(double)dim.height ); - try{ - if( x_scale != null ) { - dx = x_scale.getImageOf( dx ); - } - if( y_scale != null ) { - dy = y_scale.getImageOf( dy ); - } + DMeasures(ScaledBorder sb) { + this.sb = sb; + } + + /** + * method returns the pixel-point which belongs to the given D-coordinates + * it says where to paint a certain DPoint + * returns null if the double coordinates do not belong to the + * image of the scale functions + * + * @param x the double x D-coordinate + * @param y the double y D-coordinate + * @return the coresponding pixel Point + */ + public Point getPoint(double x, double y) { + SlimRect rect = getSourceOf(getSlimRectangle()); + if (rect == null) { + return null; + } + try { + if (x_scale != null) { + x = x_scale.getSourceOf(x); + } + if (y_scale != null) { + y = y_scale.getSourceOf(y); + } + } catch (IllegalArgumentException e) { + return null; + } + Point dp = new Point(); + Dimension dim = getInner(); + Insets insets = getInsets(); + dp.x = (int) (dim.width * (x - rect.x) / (double) rect.width) + insets.left; + dp.y = (int) (dim.height * (1 - (y - rect.y) / (double) rect.height)) + insets.top; + return dp; + } + + /** + * method returns the point in D-coordinates which corresponds to the + * given pixel-coordinates + * returns null if the given coordinates can not be calculated to + * the double coordinates, when they represent a point outside of the definition + * area of the scale functions + * + * @param x x-pixel coordinate + * @param y y-pixel coordinate + * @return the coresponding DPoint + */ + public DPoint getDPoint(int x, int y) { + SlimRect rect = getSourceOf(getSlimRectangle()); + Dimension dim = getInner(); + Insets insets = getInsets(); + x -= insets.left; + y -= insets.top; + double dx, dy; + dx = rect.x + rect.width * x / (double) dim.width; + dy = rect.y + rect.height * (1 - y / (double) dim.height); + try { + if (x_scale != null) { + dx = x_scale.getImageOf(dx); + } + if (y_scale != null) { + dy = y_scale.getImageOf(dy); + } + } catch (IllegalArgumentException nde) { + return null; + } + return new DPoint(dx, dy); } - catch( IllegalArgumentException nde ){ return null; } - return new DPoint( dx, dy ); - } // /** // * returns the visible rectangle in D-coordinates of the shown component @@ -119,71 +119,72 @@ public class DMeasures implements Serializable // if( sb != null ) return getImageOf( sb.src_rect ); // return ((DArea)comp).getDRectangle(); // } - - /** - * Returns the visible rectangle in D-coordinates of the shown component as slim structure. - * - * @return the visible rectangle - */ - public SlimRect getSlimRectangle(){ + + /** + * Returns the visible rectangle in D-coordinates of the shown component as slim structure. + * + * @return the visible rectangle + */ + public SlimRect getSlimRectangle() { // if( under_construction ) System.out.println("DMeasures.getDRectangle"); - if( sb != null ) { - return getImageOf(sb.src_rect.x, sb.src_rect.y, sb.src_rect.width, sb.src_rect.height); - } - return ((DArea)comp).getSlimRectangle(); - } - /** - * returns the current Graphics object, which might be used by components to - * paint themselves - * the method sets the clipping area of the Graphics object to the currently - * visible rectangle - * - * @return the Graphics object ( or null if no object was set ) - */ - public Graphics getGraphics(){ - if( under_construction ) { - System.out.println("DMeasures.getGraphics"); - } - if( g != null ){ - Dimension d = comp.getSize(); - Insets insets = getInsets(); - g.setClip( insets.left + 1, // dann sieht man noch was von der linken Achse - insets.top, - d.width - insets.left - insets.right, - d.height - insets.top - insets.bottom); + if (sb != null) { + return getImageOf(sb.src_rect.x, sb.src_rect.y, sb.src_rect.width, sb.src_rect.height); + } + return ((DArea) comp).getSlimRectangle(); } - return g; - } - /** - * used by DArea to set a new Graphics object - */ - void setGraphics( Graphics g ){ - if( under_construction ) { - System.out.println("DMeasures.setGraphics"); - } - this.g = g; - } + /** + * returns the current Graphics object, which might be used by components to + * paint themselves + * the method sets the clipping area of the Graphics object to the currently + * visible rectangle + * + * @return the Graphics object ( or null if no object was set ) + */ + public Graphics getGraphics() { + if (under_construction) { + System.out.println("DMeasures.getGraphics"); + } + if (g != null) { + Dimension d = comp.getSize(); + Insets insets = getInsets(); + g.setClip(insets.left + 1, // dann sieht man noch was von der linken Achse + insets.top, + d.width - insets.left - insets.right, + d.height - insets.top - insets.bottom); + } + return g; + } - /** - * used by ScaledBorder to update the DMeasures object - * - * @param c the parent component the border - */ - void update( Component c, Insets insets ){ - this.comp = c; - this.insets = insets; - x_scale = sb.x_scale; - y_scale = sb.y_scale; - } + /** + * used by DArea to set a new Graphics object + */ + void setGraphics(Graphics g) { + if (under_construction) { + System.out.println("DMeasures.setGraphics"); + } + this.g = g; + } - private Dimension getInner(){ - Dimension d = comp.getSize(); - Insets insets = getInsets(); - d.width -= insets.left + insets.right; - d.height -= insets.top + insets.bottom; - return d; - } + /** + * used by ScaledBorder to update the DMeasures object + * + * @param c the parent component the border + */ + void update(Component c, Insets insets) { + this.comp = c; + this.insets = insets; + x_scale = sb.x_scale; + y_scale = sb.y_scale; + } + + private Dimension getInner() { + Dimension d = comp.getSize(); + Insets insets = getInsets(); + d.width -= insets.left + insets.right; + d.height -= insets.top + insets.bottom; + return d; + } // /** // * method returns the image rectangle of the given rectangle @@ -213,42 +214,43 @@ public class DMeasures implements Serializable // catch( IllegalArgumentException nde ){ return null; } // return new DRectangle( p1.x, p1.y, p2.x - p1.x, p2.y - p1.y ); // } - - /** - * method returns the image rectangle of the given rectangle - * they differ if there are scale functions selected which are not the identity - * if the given rectangle does not belong to the definition area of the scale - * functions, the method returns null - * - * @param rect the source rectangle - * @return the source of it - */ - SlimRect getImageOf(double xpos, double ypos, double width, double height){ + + /** + * method returns the image rectangle of the given rectangle + * they differ if there are scale functions selected which are not the identity + * if the given rectangle does not belong to the definition area of the scale + * functions, the method returns null + * + * @param rect the source rectangle + * @return the source of it + */ + SlimRect getImageOf(double xpos, double ypos, double width, double height) { // if( under_construction ) System.out.println("DMeasures.getImageOf: "+rect); - if( x_scale == null && y_scale == null ) { - return new SlimRect(xpos, ypos, width, height); - } - double x1 = xpos, y1=ypos, x2=xpos + width, y2=ypos + height; - - try{ - if( x_scale != null ){ - x1 = x_scale.getImageOf( x1 ); - x2 = x_scale.getImageOf( x2 ); - } - if( y_scale != null ){ - y1 = y_scale.getImageOf( y1 ); - y2 = y_scale.getImageOf( y2 ); - } + if (x_scale == null && y_scale == null) { + return new SlimRect(xpos, ypos, width, height); + } + double x1 = xpos, y1 = ypos, x2 = xpos + width, y2 = ypos + height; + + try { + if (x_scale != null) { + x1 = x_scale.getImageOf(x1); + x2 = x_scale.getImageOf(x2); + } + if (y_scale != null) { + y1 = y_scale.getImageOf(y1); + y2 = y_scale.getImageOf(y2); + } + } catch (IllegalArgumentException nde) { + return null; + } + return new SlimRect(x1, y1, x2 - x1, y2 - y1); } - catch( IllegalArgumentException nde ){ return null; } - return new SlimRect( x1, y1, x2 - x1, y2 - y1 ); - } - - SlimRect getImageOf(SlimRect srect) { - return getImageOf(srect.x, srect.y, srect.width, srect.height); - } - + + SlimRect getImageOf(SlimRect srect) { + return getImageOf(srect.x, srect.y, srect.width, srect.height); + } + // /** // * method returns the source rectangle of the given rectangle // * they differ if there are scale functions selected which are not the identity @@ -289,46 +291,48 @@ public class DMeasures implements Serializable // catch( IllegalArgumentException nde ){ return null; } // return new DRectangle( p1.x, p1.y, p2.x - p1.x, p2.y - p1.y ); // } - - /** - * method returns the source rectangle of the given rectangle - * they differ if there are scale functions selected which are not the identity - * if the given rectangle does not belong to the image area of the scale - * functions, the method returns null - * - * Tuning: rect must not be empty - * - * @param rect the image rectangle - * @return the source of it - */ - SlimRect getSourceOf(double x, double y, double width, double height){ -// if( under_construction ) System.out.println("DMeasures.getSourceOf: "+rect); - if( !getSlimRectangle().contains( x, y, width, height ) ) { -// System.out.println("case not contains"); - return null; - //throw new IllegalArgumentException("The rectangle lies not in the currently painted rectangle"); - } - - if( x_scale == null && y_scale == null ) { -// System.out.println("Case scale null"); - return new SlimRect(x, y, width, height); - } - double x1=x, y1=y, x2=x + width, y2=y + height; - try{ - if( x_scale != null ){ - x1 = x_scale.getSourceOf( x1 ); - x2 = x_scale.getSourceOf( x2 ); - } - if( y_scale != null ){ - y1 = y_scale.getSourceOf( y1 ); - y2 = y_scale.getSourceOf( y2 ); - } - } - catch( IllegalArgumentException nde ){ return null; } - catch( NullPointerException npe) {return null;} - return new SlimRect( x1, y1, x2 - x1, y2 - y1 ); - } + /** + * method returns the source rectangle of the given rectangle + * they differ if there are scale functions selected which are not the identity + * if the given rectangle does not belong to the image area of the scale + * functions, the method returns null + *

+ * Tuning: rect must not be empty + * + * @param rect the image rectangle + * @return the source of it + */ + SlimRect getSourceOf(double x, double y, double width, double height) { +// if( under_construction ) System.out.println("DMeasures.getSourceOf: "+rect); + if (!getSlimRectangle().contains(x, y, width, height)) { +// System.out.println("case not contains"); + return null; + //throw new IllegalArgumentException("The rectangle lies not in the currently painted rectangle"); + } + + if (x_scale == null && y_scale == null) { +// System.out.println("Case scale null"); + return new SlimRect(x, y, width, height); + } + + double x1 = x, y1 = y, x2 = x + width, y2 = y + height; + try { + if (x_scale != null) { + x1 = x_scale.getSourceOf(x1); + x2 = x_scale.getSourceOf(x2); + } + if (y_scale != null) { + y1 = y_scale.getSourceOf(y1); + y2 = y_scale.getSourceOf(y2); + } + } catch (IllegalArgumentException nde) { + return null; + } catch (NullPointerException npe) { + return null; + } + return new SlimRect(x1, y1, x2 - x1, y2 - y1); + } // SlimRect getSourceOf( double xpos, double ypos, double width, double height){ // if( !getSlimRectangle().contains( xpos, ypos, width, height ) ) { // System.err.println("The rectangle lies not in the currently painted rectangle"); @@ -338,17 +342,17 @@ public class DMeasures implements Serializable // // MK: this now strangely does the same as getImageOf // return getImageOf(xpos, ypos, width, height); // } - - SlimRect getSourceOf( SlimRect srect){ - return getSourceOf(srect.x, srect.y, srect.width, srect.height); - } - - private Insets getInsets(){ - if( sb != null ) { - return insets; - } - return ((DArea)comp).getInsets(); - } + + SlimRect getSourceOf(SlimRect srect) { + return getSourceOf(srect.x, srect.y, srect.width, srect.height); + } + + private Insets getInsets() { + if (sb != null) { + return insets; + } + return ((DArea) comp).getInsets(); + } } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/DParent.java b/src/eva2/tools/chart2d/DParent.java index cfc55d36..e3a9cf79 100644 --- a/src/eva2/tools/chart2d/DParent.java +++ b/src/eva2/tools/chart2d/DParent.java @@ -17,15 +17,20 @@ package eva2.tools.chart2d; * INTERFACE DECLARATION *==========================================================================*/ -public interface DParent -{ - void addDElement( DElement e ); - boolean removeDElement( DElement e ); - void repaint( DRectangle r ); - DElement[] getDElements(); - boolean contains( DElement e ); - void addDBorder( DBorder b ); - void restoreBorder(); +public interface DParent { + void addDElement(DElement e); + + boolean removeDElement(DElement e); + + void repaint(DRectangle r); + + DElement[] getDElements(); + + boolean contains(DElement e); + + void addDBorder(DBorder b); + + void restoreBorder(); } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/DPoint.java b/src/eva2/tools/chart2d/DPoint.java index 93e0dc51..06ba3ba3 100644 --- a/src/eva2/tools/chart2d/DPoint.java +++ b/src/eva2/tools/chart2d/DPoint.java @@ -16,94 +16,94 @@ package eva2.tools.chart2d; * IMPORTS *==========================================================================*/ -import java.awt.* ; +import java.awt.*; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ -public class DPoint extends DComponent -{ - public double x, y; - public String label; - protected DPointIcon icon = null; - public DPoint( ){ - } - public void initpoint( double x, double y ){ - this.x = x; - this.y = y; - rectangle = new DRectangle( x, y, 0, 0 ); - } - public DPoint( double x, double y ){ - this.x = x; - this.y = y; - rectangle = new DRectangle( x, y, 0, 0 ); - } +public class DPoint extends DComponent { + public double x, y; + public String label; + protected DPointIcon icon = null; + + public DPoint() { + } + + public void initpoint(double x, double y) { + this.x = x; + this.y = y; + rectangle = new DRectangle(x, y, 0, 0); + } + + public DPoint(double x, double y) { + this.x = x; + this.y = y; + rectangle = new DRectangle(x, y, 0, 0); + } @Override - public void paint( DMeasures m ){ - Graphics g = m.getGraphics(); - if( color != null ) { - g.setColor( color ); - } - Point dp = m.getPoint( this.x, this.y ); - if( label != null ){ - FontMetrics fm = g.getFontMetrics(); - g.drawString( label, - dp.x - fm.stringWidth( label ) / 2, + public void paint(DMeasures m) { + Graphics g = m.getGraphics(); + if (color != null) { + g.setColor(color); + } + Point dp = m.getPoint(this.x, this.y); + if (label != null) { + FontMetrics fm = g.getFontMetrics(); + g.drawString(label, + dp.x - fm.stringWidth(label) / 2, dp.y + fm.getAscent() - ); + ); + } + if (icon == null) { + g.drawRect(dp.x, dp.y, 1, 1); + } else { + g.translate(dp.x, dp.y); + icon.paint(g); + g.translate(-dp.x, -dp.y); + } } - if( icon == null ) { - g.drawRect( dp.x, dp.y, 1, 1 ); - } - else{ - g.translate( dp.x, dp.y ); - icon.paint( g ); - g.translate( -dp.x, -dp.y ); + + /** + * method sets an icon for a better displaying of the point + * + * @param icon the DPointIcon + */ + public void setIcon(DPointIcon icon) { + this.icon = icon; + if (icon == null) { + setDBorder(new DBorder(1, 1, 1, 1)); + } else { + setDBorder(icon.getDBorder()); + } } - } - /** - * method sets an icon for a better displaying of the point - * - * @param icon the DPointIcon - */ - public void setIcon( DPointIcon icon ){ - this.icon = icon; - if( icon == null ) { - setDBorder(new DBorder(1,1,1,1)); - } - else { - setDBorder( icon.getDBorder() ); - } - } - - /** - * method returns the current icon of the point - * - * @return the DPointIcon - */ - public DPointIcon getIcon(){ - return icon; - } + /** + * method returns the current icon of the point + * + * @return the DPointIcon + */ + public DPointIcon getIcon() { + return icon; + } @Override - public Object clone(){ - DPoint copy = new DPoint( x, y ); - copy.color = color; - return copy; - } + public Object clone() { + DPoint copy = new DPoint(x, y); + copy.color = color; + return copy; + } @Override - public String toString(){ - String text = "DPoint["; - if( label != null ) { - text += label+", "; - } - text += "x: "+x+", y: "+y+", color: "+color+"]"; - return text; - } + public String toString() { + String text = "DPoint["; + if (label != null) { + text += label + ", "; + } + text += "x: " + x + ", y: " + y + ", color: " + color + "]"; + return text; + } } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/DPointIcon.java b/src/eva2/tools/chart2d/DPointIcon.java index 67f533d0..f1b826a5 100644 --- a/src/eva2/tools/chart2d/DPointIcon.java +++ b/src/eva2/tools/chart2d/DPointIcon.java @@ -11,6 +11,7 @@ package eva2.tools.chart2d; */ import java.awt.Graphics; + /** * A simple interface which can be used to paint certain icons at DPoints * ( @see chart2d.DPoint.setIcon or chart2d.DPointSet.setIcon ). @@ -21,18 +22,18 @@ import java.awt.Graphics; public interface DPointIcon { - /** - * this method has to be overridden to paint the icon. The point itself lies - * at coordinates (0, 0) - */ - void paint( Graphics g ); + /** + * this method has to be overridden to paint the icon. The point itself lies + * at coordinates (0, 0) + */ + void paint(Graphics g); - /** - * the border which is necessary to be paint around the DPoint that the whole - * icon is visible - * - * @return the border - */ - DBorder getDBorder(); + /** + * the border which is necessary to be paint around the DPoint that the whole + * icon is visible + * + * @return the border + */ + DBorder getDBorder(); } diff --git a/src/eva2/tools/chart2d/DPointSet.java b/src/eva2/tools/chart2d/DPointSet.java index 27aa018d..e2c38a69 100644 --- a/src/eva2/tools/chart2d/DPointSet.java +++ b/src/eva2/tools/chart2d/DPointSet.java @@ -9,292 +9,294 @@ package eva2.tools.chart2d; * ==========================================================================* IMPORTS *========================================================================== */ + import eva2.tools.math.Mathematics; + import java.awt.*; import java.util.ArrayList; public class DPointSet extends DComponent { - protected DPointIcon icon = null; + protected DPointIcon icon = null; - /* - * -------------------------------------------------------------------------* private member - * variables + /* + * -------------------------------------------------------------------------* private member + * variables *------------------------------------------------------------------------- - */ - protected DIntDoubleMap x, y; - protected boolean connected; - protected Stroke stroke = new BasicStroke(); - protected JumpManager jumper = new JumpManager(); + */ + protected DIntDoubleMap x, y; + protected boolean connected; + protected Stroke stroke = new BasicStroke(); + protected JumpManager jumper = new JumpManager(); - /* - * -------------------------------------------------------------------------* constructor + /* + * -------------------------------------------------------------------------* constructor *------------------------------------------------------------------------- - */ - public DPointSet() { - this(10, 2); - } + */ + public DPointSet() { + this(10, 2); + } - public DPointSet(int initial_capacity) { - this(initial_capacity, 2); - } + public DPointSet(int initial_capacity) { + this(initial_capacity, 2); + } - public DPointSet(int initial_capacity, int length_multiplier) { - this(new DArray(initial_capacity, length_multiplier), - new DArray(initial_capacity, length_multiplier)); - } + public DPointSet(int initial_capacity, int length_multiplier) { + this(new DArray(initial_capacity, length_multiplier), + new DArray(initial_capacity, length_multiplier)); + } - public DPointSet(DIntDoubleMap x_values, DIntDoubleMap y_values) { - if (x_values.getSize() != y_values.getSize()) { - throw new IllegalArgumentException( - "The number of x-values has to be the same than the number of y-values"); - } - x = x_values; - y = y_values; - restore(); - setDBorder(new DBorder(1, 1, 1, 1)); - } + public DPointSet(DIntDoubleMap x_values, DIntDoubleMap y_values) { + if (x_values.getSize() != y_values.getSize()) { + throw new IllegalArgumentException( + "The number of x-values has to be the same than the number of y-values"); + } + x = x_values; + y = y_values; + restore(); + setDBorder(new DBorder(1, 1, 1, 1)); + } - /* - * -------------------------------------------------------------------------* public methods + /* + * -------------------------------------------------------------------------* public methods *------------------------------------------------------------------------- - */ + */ @Override - public void paint(DMeasures m) { - Graphics2D g = (Graphics2D) m.getGraphics(); - g.setStroke(stroke); - if (color != null) { - g.setColor(color); - } - int size = getSize(); - if (connected && size > 1) { - jumper.restore(); - while (jumper.hasMoreIntervals()) { - int[] interval = jumper.nextInterval(); - Point p1 = null, p2; - for (int i = interval[0]; i < interval[1]; i++) { - p2 = m.getPoint(x.getImage(i), y.getImage(i)); - if (p1 != null) { - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - if (icon != null) { - g.setStroke(new BasicStroke()); - g.translate(p2.x, p2.y); - icon.paint(g); - g.translate(-p2.x, -p2.y); - g.setStroke(stroke); - } - p1 = p2; - } - } - } else { - Point p; - for (int i = 0; i < size; i++) { - p = m.getPoint(x.getImage(i), y.getImage(i)); - if (icon == null) { - g.drawLine(p.x - 1, p.y - 1, p.x + 1, p.y + 1); - g.drawLine(p.x + 1, p.y - 1, p.x - 1, p.y + 1); - } else { - g.setStroke(new BasicStroke()); - g.translate(p.x, p.y); - icon.paint(g); - g.translate(-p.x, -p.y); - } - } - } - g.setStroke(new BasicStroke()); - } + public void paint(DMeasures m) { + Graphics2D g = (Graphics2D) m.getGraphics(); + g.setStroke(stroke); + if (color != null) { + g.setColor(color); + } + int size = getSize(); + if (connected && size > 1) { + jumper.restore(); + while (jumper.hasMoreIntervals()) { + int[] interval = jumper.nextInterval(); + Point p1 = null, p2; + for (int i = interval[0]; i < interval[1]; i++) { + p2 = m.getPoint(x.getImage(i), y.getImage(i)); + if (p1 != null) { + g.drawLine(p1.x, p1.y, p2.x, p2.y); + } + if (icon != null) { + g.setStroke(new BasicStroke()); + g.translate(p2.x, p2.y); + icon.paint(g); + g.translate(-p2.x, -p2.y); + g.setStroke(stroke); + } + p1 = p2; + } + } + } else { + Point p; + for (int i = 0; i < size; i++) { + p = m.getPoint(x.getImage(i), y.getImage(i)); + if (icon == null) { + g.drawLine(p.x - 1, p.y - 1, p.x + 1, p.y + 1); + g.drawLine(p.x + 1, p.y - 1, p.x - 1, p.y + 1); + } else { + g.setStroke(new BasicStroke()); + g.translate(p.x, p.y); + icon.paint(g); + g.translate(-p.x, -p.y); + } + } + } + g.setStroke(new BasicStroke()); + } - public void addDPoint(DPoint p) { - x.addImage(p.x); - y.addImage(p.y); - rectangle.insert(p); - repaint(); - } + public void addDPoint(DPoint p) { + x.addImage(p.x); + y.addImage(p.y); + rectangle.insert(p); + repaint(); + } - public void addDPoint(double x, double y) { - addDPoint(new DPoint(x, y)); - } + public void addDPoint(double x, double y) { + addDPoint(new DPoint(x, y)); + } - /** - * method causes the DPointSet to interupt the connected painting at the current position - */ - public void jump() { - jumper.addJump(); - } + /** + * method causes the DPointSet to interupt the connected painting at the current position + */ + public void jump() { + jumper.addJump(); + } - /** - * method removes all jump positions if the DPointSet is connected, all points will be painted - * connected to their following point - */ - public void removeJumps() { - jumper.reset(); - } + /** + * method removes all jump positions if the DPointSet is connected, all points will be painted + * connected to their following point + */ + public void removeJumps() { + jumper.reset(); + } - /** - * method returns the DPoint at the given index - * - * @param index the index of the DPoint - * @return the DPoint at the given index - */ - public DPoint getDPoint(int index) { - if (index >= x.getSize()) { - System.out.println("getDPoint() index" + index); - System.out.println("x.getSize() " + x.getSize()); - throw new ArrayIndexOutOfBoundsException(index); - } - DPoint p = new DPoint(x.getImage(index), y.getImage(index)); - p.setIcon(icon); - p.setColor(color); - return p; - } + /** + * method returns the DPoint at the given index + * + * @param index the index of the DPoint + * @return the DPoint at the given index + */ + public DPoint getDPoint(int index) { + if (index >= x.getSize()) { + System.out.println("getDPoint() index" + index); + System.out.println("x.getSize() " + x.getSize()); + throw new ArrayIndexOutOfBoundsException(index); + } + DPoint p = new DPoint(x.getImage(index), y.getImage(index)); + p.setIcon(icon); + p.setColor(color); + return p; + } - /** - * method puts the given DPoint at the given position in the set - * - * @param index the index of the point - * @param p the point to insert - */ - public void setDPoint(int index, DPoint p) { - if (index >= x.getSize()) { - throw new ArrayIndexOutOfBoundsException(index); - } - rectangle.insert(p); - x.setImage(index, p.x); - y.setImage(index, p.y); - restore(); - repaint(); - } + /** + * method puts the given DPoint at the given position in the set + * + * @param index the index of the point + * @param p the point to insert + */ + public void setDPoint(int index, DPoint p) { + if (index >= x.getSize()) { + throw new ArrayIndexOutOfBoundsException(index); + } + rectangle.insert(p); + x.setImage(index, p.x); + y.setImage(index, p.y); + restore(); + repaint(); + } - /** - * method sets an icon for a better displaying of the point set - * - * @param icon the DPointIcon - */ - public void setIcon(DPointIcon icon) { - this.icon = icon; - if (icon == null) { - setDBorder(new DBorder(1, 1, 1, 1)); - } else { - setDBorder(icon.getDBorder()); - } - } + /** + * method sets an icon for a better displaying of the point set + * + * @param icon the DPointIcon + */ + public void setIcon(DPointIcon icon) { + this.icon = icon; + if (icon == null) { + setDBorder(new DBorder(1, 1, 1, 1)); + } else { + setDBorder(icon.getDBorder()); + } + } - /** - * method returns the current icon of the point set - * - * @return the DPointIcon - */ - public DPointIcon getIcon() { - return icon; - } + /** + * method returns the current icon of the point set + * + * @return the DPointIcon + */ + public DPointIcon getIcon() { + return icon; + } - /** - * method sets the stroke of the line if the points were not connected, they now will be - * connected - * - * @param s the new stroke - */ - public void setStroke(Stroke s) { - if (s == null) { - s = new BasicStroke(); - } - stroke = s; - repaint(); - } + /** + * method sets the stroke of the line if the points were not connected, they now will be + * connected + * + * @param s the new stroke + */ + public void setStroke(Stroke s) { + if (s == null) { + s = new BasicStroke(); + } + stroke = s; + repaint(); + } - /** - * method returns the current stroke of the line - * - * @return the stroke - */ - public Stroke getStroke() { - return stroke; - } + /** + * method returns the current stroke of the line + * + * @return the stroke + */ + public Stroke getStroke() { + return stroke; + } - /** - * Return the minimum y value in the point set. - * - * @return the minimum y value in the point set - */ - public double getMinYVal() { - return y.getMinImageValue(); - } + /** + * Return the minimum y value in the point set. + * + * @return the minimum y value in the point set + */ + public double getMinYVal() { + return y.getMinImageValue(); + } - public double getMinPositiveYValue() { - return y.getMinPositiveImageValue(); - } + public double getMinPositiveYValue() { + return y.getMinPositiveImageValue(); + } - public void setConnected(boolean aFlag) { - boolean changed = !(aFlag == connected); - connected = aFlag; - if (changed) { - repaint(); - } - } + public void setConnected(boolean aFlag) { + boolean changed = !(aFlag == connected); + connected = aFlag; + if (changed) { + repaint(); + } + } - public void removeAllPoints() { - if (x.getSize() == 0) { - return; - } - x.reset(); - y.reset(); - jumper.reset(); - repaint(); - rectangle = DRectangle.getEmpty(); - } + public void removeAllPoints() { + if (x.getSize() == 0) { + return; + } + x.reset(); + y.reset(); + jumper.reset(); + repaint(); + rectangle = DRectangle.getEmpty(); + } @Override - public String toString() { - String text = "eva2.tools.chart2d.DPointSet[size:" + getSize(); - for (int i = 0; i < x.getSize(); i++) { - text += ",(" + x.getImage(i) + "," + y.getImage(i) + ")"; - } - text += "]"; - return text; - } + public String toString() { + String text = "eva2.tools.chart2d.DPointSet[size:" + getSize(); + for (int i = 0; i < x.getSize(); i++) { + text += ",(" + x.getImage(i) + "," + y.getImage(i) + ")"; + } + text += "]"; + return text; + } - /** - * method returns the index to the nearest - * DPoint in this - * DPointSet. - * - * @return the index to the nearest - * DPoint. -1 if no nearest - * DPoint was found. - */ - public int getNearestDPointIndex(DPoint point) { - double minValue = Double.MAX_VALUE; - int minIndex = -1; - for (int i = 0; i < x.getSize(); i++) { - double dx = point.x - x.getImage(i); - double dy = point.y - y.getImage(i); - double dummy = dx * dx + dy * dy; - if (dummy < minValue) { - minValue = dummy; - minIndex = i; - } - } - return minIndex; - } + /** + * method returns the index to the nearest + * DPoint in this + * DPointSet. + * + * @return the index to the nearest + * DPoint. -1 if no nearest + * DPoint was found. + */ + public int getNearestDPointIndex(DPoint point) { + double minValue = Double.MAX_VALUE; + int minIndex = -1; + for (int i = 0; i < x.getSize(); i++) { + double dx = point.x - x.getImage(i); + double dy = point.y - y.getImage(i); + double dummy = dx * dx + dy * dy; + if (dummy < minValue) { + minValue = dummy; + minIndex = i; + } + } + return minIndex; + } - /** - * method returns the nearest - * DPoint in this - * DPointSet. - * - * @return the nearest - * DPoint - */ - public DPoint getNearestDPoint(DPoint point) { - int minIndex = getNearestDPointIndex(point); + /** + * method returns the nearest + * DPoint in this + * DPointSet. + * + * @return the nearest + * DPoint + */ + public DPoint getNearestDPoint(DPoint point) { + int minIndex = getNearestDPointIndex(point); - if (minIndex == -1) { - return null; - } else { - return new DPoint(x.getImage(minIndex), y.getImage(minIndex)); - } - } + if (minIndex == -1) { + return null; + } else { + return new DPoint(x.getImage(minIndex), y.getImage(minIndex)); + } + } // public int getSize(){ // int size = x.getSize(); @@ -305,79 +307,80 @@ public class DPointSet extends DComponent { // ); // return size; // } - /** - * - */ - public int getSize() { // testhu - int size = x.getSize(); - if (size <= y.getSize()) { - return size; - } - return x.getSize(); - } - protected void restore() { - if (getSize() == 0) { - rectangle = DRectangle.getEmpty(); - return; - } - double min_x = x.getMinImageValue(), - max_x = x.getMaxImageValue(), - min_y = y.getMinImageValue(), - max_y = y.getMaxImageValue(); - if (Mathematics.areFinite(min_x, max_x, min_y, max_y) == -1) { - rectangle = new DRectangle(min_x, min_y, max_x - min_x, max_y - min_y); - } - } + /** + * + */ + public int getSize() { // testhu + int size = x.getSize(); + if (size <= y.getSize()) { + return size; + } + return x.getSize(); + } - /** - * this class stores the jump positions (see this.jump) - */ - class JumpManager { + protected void restore() { + if (getSize() == 0) { + rectangle = DRectangle.getEmpty(); + return; + } + double min_x = x.getMinImageValue(), + max_x = x.getMaxImageValue(), + min_y = y.getMinImageValue(), + max_y = y.getMaxImageValue(); + if (Mathematics.areFinite(min_x, max_x, min_y, max_y) == -1) { + rectangle = new DRectangle(min_x, min_y, max_x - min_x, max_y - min_y); + } + } - protected ArrayList jumps = new ArrayList(); - protected int index = -1; + /** + * this class stores the jump positions (see this.jump) + */ + class JumpManager { - public void addJump() { - jumps.add(getSize()); - } + protected ArrayList jumps = new ArrayList(); + protected int index = -1; - public int[] nextInterval() { - int noJumps = jumps.size(); - if (index >= noJumps) { - throw new ArrayIndexOutOfBoundsException("No more intervals in JumpManager"); - } + public void addJump() { + jumps.add(getSize()); + } - int[] inter = new int[2]; + public int[] nextInterval() { + int noJumps = jumps.size(); + if (index >= noJumps) { + throw new ArrayIndexOutOfBoundsException("No more intervals in JumpManager"); + } - if (index == -1) { - inter[0] = 0; - } else { - inter[0] = jumps.get(index); - } + int[] inter = new int[2]; - index++; + if (index == -1) { + inter[0] = 0; + } else { + inter[0] = jumps.get(index); + } - if (index < noJumps) { - inter[1] = jumps.get(index); - } else { - inter[1] = getSize(); - } + index++; - return inter; - } + if (index < noJumps) { + inter[1] = jumps.get(index); + } else { + inter[1] = getSize(); + } - public boolean hasMoreIntervals() { - return index < jumps.size(); - } + return inter; + } - public void restore() { - index = -1; - } + public boolean hasMoreIntervals() { + return index < jumps.size(); + } - public void reset() { - index = -1; - jumps.clear(); - } - } + public void restore() { + index = -1; + } + + public void reset() { + index = -1; + jumps.clear(); + } + } } diff --git a/src/eva2/tools/chart2d/DRectangle.java b/src/eva2/tools/chart2d/DRectangle.java index e1527cb8..8058cbc5 100644 --- a/src/eva2/tools/chart2d/DRectangle.java +++ b/src/eva2/tools/chart2d/DRectangle.java @@ -17,325 +17,361 @@ package eva2.tools.chart2d; *==========================================================================*/ import eva2.tools.EVAERROR; + import java.awt.*; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ -public class DRectangle extends DComponent -{ - private double x, y; - private double width, height; - public static final int PART = 0, ALL = 1, EMPTY = 2; - protected int status; - protected Color fillColor; +public class DRectangle extends DComponent { + private double x, y; + private double width, height; + public static final int PART = 0, ALL = 1, EMPTY = 2; + protected int status; + protected Color fillColor; - private DRectangle( int status ){ - super(true); - this.status = status; - } - - public DRectangle( double x, double y, double width, double height ){ - super(true); - this.x = x; - this.y = y; - if( width < 0 || Double.isInfinite(width) || Double.isNaN(width)) { - throw -new IllegalArgumentException("Width of a DRectangle is invalid (" + width + ")"); - } - this.width = width; - if( height < 0 || Double.isInfinite(height) || Double.isNaN(height)) { - throw -new IllegalArgumentException("Height of a DRectangle is invalid (" + height + ")"); - } - this.height = height; - status = PART; - } - - @Override - public DRectangle getRectangle(){ return this; } - - @Override - public void paint( DMeasures m ){ - if( isEmpty() ) { - return; - } - Graphics g = m.getGraphics(); - Color old_color = g.getColor(); - SlimRect rect = m.getSlimRectangle().getIntersection(this); - Point p1 = m.getPoint( rect.x, rect.y ), - p2 = m.getPoint( rect.x + rect.width, rect.y + rect.height ); - if( fillColor != null ){ - g.setColor( fillColor ); - g.fillRect( p1.x, p2.y, p2.x - p1.x, p1.y - p2.y ); + private DRectangle(int status) { + super(true); + this.status = status; } - if( !isAll() ){ - if( color != null ) { - g.setColor( color ); + + public DRectangle(double x, double y, double width, double height) { + super(true); + this.x = x; + this.y = y; + if (width < 0 || Double.isInfinite(width) || Double.isNaN(width)) { + throw + new IllegalArgumentException("Width of a DRectangle is invalid (" + width + ")"); } - else { - g.setColor( DEFAULT_COLOR ); + this.width = width; + if (height < 0 || Double.isInfinite(height) || Double.isNaN(height)) { + throw + new IllegalArgumentException("Height of a DRectangle is invalid (" + height + ")"); } - g.drawRect( p1.x, p2.y, p2.x - p1.x, p1.y - p2.y ); + this.height = height; + status = PART; } - g.setColor( old_color ); - } - - public boolean contains( DPoint p ){ - if( status == ALL ) { - return true; - } - if( status == EMPTY ) { - return false; - } - if( p.x < x ) { - return false; - } - if( p.y < y ) { - return false; - } - if( p.x > x + width ) { - return false; - } - if( p.y > y + height ) { - return false; - } - return true; - } - - public double getHeight() { return height; } - public double getWidth() { return width; } - public void setHeight(double h) { - if (Double.isInfinite(h) || Double.isNaN(h)) { - System.err.println("Warning, infinite vaule for height!"); - } else { - height = h; - } - } - public void setWidth(double w) { - if (Double.isInfinite(w) || Double.isNaN(w)) { - System.err.println("Warning, infinite vaule for width!"); - } else { - width = w; - } - } - public double getX() { return x; } - public double getY() { return y; } - public void setX(double v) { - if (Double.isInfinite(v) || Double.isNaN(v)) { - System.err.println("Warning, infinite vaule for x!"); - } else { - x = v; - } - } - public void setY(double v) { - if (Double.isInfinite(v) || Double.isNaN(v)) { - System.err.println("Warning, infinite vaule for y!"); - } else { - y = v; - } - } - - /** - * Faster contains withouth checking for ALL or EMPTY status. - * - * @param ox - * @param oy - * @return - */ - private boolean contains( double ox, double oy ){ - if (( ox < x ) || ( oy < y ) || ( ox > x + width ) || ( oy > y + height )) { - return false; - } - else { - return true; - } - } - - public boolean contains( DRectangle rect ){ - if( status == ALL || rect.isEmpty() ) { - return true; - } - if( status == EMPTY || rect.isAll() ) { - return false; - } - if( !contains(rect.x, rect.y ) ) { - return false; - } - if( !contains(rect.x + rect.width, rect.y + rect.height ) ) { - return false; - } - return true; - } - - public boolean contains( double ox, double oy, double width, double heigth){ - if( status == ALL) { - return true; - } - if( status == EMPTY) { - return false; - } - if( !contains(ox, oy ) ) { - return false; - } - if( !contains(ox + width, oy + height ) ) { - return false; - } - return true; - } - - public DRectangle getIntersection( DRectangle r ){ - if( status == EMPTY || (r.status == EMPTY) ) { - return DRectangle.getEmpty(); - } - if( status == ALL ) { - return (DRectangle)r.clone(); - } - if( r.status == ALL ) { - return (DRectangle)clone(); - } - DRectangle s = (DRectangle)this.clone(); - if( s.x < r.x ){ - s.x = r.x; - s.width -= r.x - s.x; - } - if( s.y < r.y ){ - s.y = r.y; - s.height -= r.y - s.y; - } - if( s.x + s.width > r.x + r.width ) { - s.width = r.x + r.width - s.x; - } - if( s.y + s.height > r.y + r.height ) { - s.height = r.y + r.height - s.y; - } - if( s.width < 0 || s.height < 0 ) { - return DRectangle.getEmpty(); - } - else { - return s; - } - } - - /** - * method resizes the rectangle to insert p - * - * @param the dPoint p to insert - * @return true when the size of the rectangle changed - */ - public boolean insert( DPoint p ){ - if( p.x == Double.NaN || p.y == Double.NaN || Double.isInfinite(p.x) || Double.isInfinite(p.y)) { - EVAERROR.errorMsgOnce("Warning, inserted invalid point (NaN/infinity) in " + this.getClass().getSimpleName()); - return false; - } - if( isAll() ) { - return false; - } - if( contains( p ) ) { - return false; - } - if( isEmpty() ){ - x = p.x; y = p.y; width = height = 0; - status = PART; - return true; - } - if( p.x < x ) { - width += x - p.x; - x = p.x; - } - else if( p.x > x + width ) { - width = p.x - x; - } - if( p.y < y ) { - height += y - p.y; - y = p.y; - } - else if( p.y > y + height ) { - height = p.y - y; - } - return true; - } - - /** - * method inserts the given rectangle to this instance of it - * and returns true when the size changed - * - * @param rect the rectangle to inserts - * @return true if the size changed - */ - public boolean insert( DRectangle rect ){ - if( isAll() || rect.isEmpty() ) { - return false; - } - if( rect.isAll() ){ status = ALL; return true; } - if( isEmpty() ){ - x = rect.x; y = rect.y; width = rect.width; height = rect.height; - status = PART; - return true; - } - boolean changed = false; - changed = insert( new DPoint( rect.x, rect.y ) ); - changed = insert( new DPoint( rect.x + rect.width, rect.y + rect.height ) )? true : changed; - return changed; - } @Override - public Object clone(){ - DRectangle copy = new DRectangle( x, y, width, height ); - copy.status = status; - if( color != null ) { - copy.color = new Color( color.getRGB() ); - } - return copy; - } + public DRectangle getRectangle() { + return this; + } @Override - public String toString(){ - String text = "DRectangle[ "; - switch( status ){ - case ALL : text += "all"; break; - case EMPTY : text += "empty"; break; - case PART : text += x+", "+y+", "+width+", "+height; + public void paint(DMeasures m) { + if (isEmpty()) { + return; + } + Graphics g = m.getGraphics(); + Color old_color = g.getColor(); + SlimRect rect = m.getSlimRectangle().getIntersection(this); + Point p1 = m.getPoint(rect.x, rect.y), + p2 = m.getPoint(rect.x + rect.width, rect.y + rect.height); + if (fillColor != null) { + g.setColor(fillColor); + g.fillRect(p1.x, p2.y, p2.x - p1.x, p1.y - p2.y); + } + if (!isAll()) { + if (color != null) { + g.setColor(color); + } else { + g.setColor(DEFAULT_COLOR); + } + g.drawRect(p1.x, p2.y, p2.x - p1.x, p1.y - p2.y); + } + g.setColor(old_color); } - text += " ]"; - return text; - } - public boolean equals( DRectangle r ){ - if( r.status != status ) { - return false; - } - if( r.x != x ) { - return false; - } - if( r.y != y ) { - return false; - } - if( r.width != width ) { - return false; - } - if( r.height != height ) { - return false; - } - return true; - } - - public void setFillColor( Color fill_color ){ - if( fillColor == null || !fillColor.equals( fill_color ) ){ - fillColor = fill_color; - repaint(); + public boolean contains(DPoint p) { + if (status == ALL) { + return true; + } + if (status == EMPTY) { + return false; + } + if (p.x < x) { + return false; + } + if (p.y < y) { + return false; + } + if (p.x > x + width) { + return false; + } + if (p.y > y + height) { + return false; + } + return true; } - } - public Color getFillColor(){ - return fillColor; - } + public double getHeight() { + return height; + } - public static DRectangle getAll(){ return new DRectangle( ALL ); } - public boolean isAll(){ return status == ALL; } - public static DRectangle getEmpty(){ return new DRectangle( EMPTY ); } - public boolean isEmpty(){ return status == EMPTY; } + public double getWidth() { + return width; + } + + public void setHeight(double h) { + if (Double.isInfinite(h) || Double.isNaN(h)) { + System.err.println("Warning, infinite vaule for height!"); + } else { + height = h; + } + } + + public void setWidth(double w) { + if (Double.isInfinite(w) || Double.isNaN(w)) { + System.err.println("Warning, infinite vaule for width!"); + } else { + width = w; + } + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public void setX(double v) { + if (Double.isInfinite(v) || Double.isNaN(v)) { + System.err.println("Warning, infinite vaule for x!"); + } else { + x = v; + } + } + + public void setY(double v) { + if (Double.isInfinite(v) || Double.isNaN(v)) { + System.err.println("Warning, infinite vaule for y!"); + } else { + y = v; + } + } + + /** + * Faster contains withouth checking for ALL or EMPTY status. + * + * @param ox + * @param oy + * @return + */ + private boolean contains(double ox, double oy) { + if ((ox < x) || (oy < y) || (ox > x + width) || (oy > y + height)) { + return false; + } else { + return true; + } + } + + public boolean contains(DRectangle rect) { + if (status == ALL || rect.isEmpty()) { + return true; + } + if (status == EMPTY || rect.isAll()) { + return false; + } + if (!contains(rect.x, rect.y)) { + return false; + } + if (!contains(rect.x + rect.width, rect.y + rect.height)) { + return false; + } + return true; + } + + public boolean contains(double ox, double oy, double width, double heigth) { + if (status == ALL) { + return true; + } + if (status == EMPTY) { + return false; + } + if (!contains(ox, oy)) { + return false; + } + if (!contains(ox + width, oy + height)) { + return false; + } + return true; + } + + public DRectangle getIntersection(DRectangle r) { + if (status == EMPTY || (r.status == EMPTY)) { + return DRectangle.getEmpty(); + } + if (status == ALL) { + return (DRectangle) r.clone(); + } + if (r.status == ALL) { + return (DRectangle) clone(); + } + DRectangle s = (DRectangle) this.clone(); + if (s.x < r.x) { + s.x = r.x; + s.width -= r.x - s.x; + } + if (s.y < r.y) { + s.y = r.y; + s.height -= r.y - s.y; + } + if (s.x + s.width > r.x + r.width) { + s.width = r.x + r.width - s.x; + } + if (s.y + s.height > r.y + r.height) { + s.height = r.y + r.height - s.y; + } + if (s.width < 0 || s.height < 0) { + return DRectangle.getEmpty(); + } else { + return s; + } + } + + /** + * method resizes the rectangle to insert p + * + * @param the dPoint p to insert + * @return true when the size of the rectangle changed + */ + public boolean insert(DPoint p) { + if (p.x == Double.NaN || p.y == Double.NaN || Double.isInfinite(p.x) || Double.isInfinite(p.y)) { + EVAERROR.errorMsgOnce("Warning, inserted invalid point (NaN/infinity) in " + this.getClass().getSimpleName()); + return false; + } + if (isAll()) { + return false; + } + if (contains(p)) { + return false; + } + if (isEmpty()) { + x = p.x; + y = p.y; + width = height = 0; + status = PART; + return true; + } + if (p.x < x) { + width += x - p.x; + x = p.x; + } else if (p.x > x + width) { + width = p.x - x; + } + if (p.y < y) { + height += y - p.y; + y = p.y; + } else if (p.y > y + height) { + height = p.y - y; + } + return true; + } + + /** + * method inserts the given rectangle to this instance of it + * and returns true when the size changed + * + * @param rect the rectangle to inserts + * @return true if the size changed + */ + public boolean insert(DRectangle rect) { + if (isAll() || rect.isEmpty()) { + return false; + } + if (rect.isAll()) { + status = ALL; + return true; + } + if (isEmpty()) { + x = rect.x; + y = rect.y; + width = rect.width; + height = rect.height; + status = PART; + return true; + } + boolean changed = false; + changed = insert(new DPoint(rect.x, rect.y)); + changed = insert(new DPoint(rect.x + rect.width, rect.y + rect.height)) ? true : changed; + return changed; + } + + @Override + public Object clone() { + DRectangle copy = new DRectangle(x, y, width, height); + copy.status = status; + if (color != null) { + copy.color = new Color(color.getRGB()); + } + return copy; + } + + @Override + public String toString() { + String text = "DRectangle[ "; + switch (status) { + case ALL: + text += "all"; + break; + case EMPTY: + text += "empty"; + break; + case PART: + text += x + ", " + y + ", " + width + ", " + height; + } + text += " ]"; + return text; + } + + public boolean equals(DRectangle r) { + if (r.status != status) { + return false; + } + if (r.x != x) { + return false; + } + if (r.y != y) { + return false; + } + if (r.width != width) { + return false; + } + if (r.height != height) { + return false; + } + return true; + } + + public void setFillColor(Color fill_color) { + if (fillColor == null || !fillColor.equals(fill_color)) { + fillColor = fill_color; + repaint(); + } + } + + public Color getFillColor() { + return fillColor; + } + + public static DRectangle getAll() { + return new DRectangle(ALL); + } + + public boolean isAll() { + return status == ALL; + } + + public static DRectangle getEmpty() { + return new DRectangle(EMPTY); + } + + public boolean isEmpty() { + return status == EMPTY; + } } /**************************************************************************** diff --git a/src/eva2/tools/chart2d/ScaledBorder.java b/src/eva2/tools/chart2d/ScaledBorder.java index 21fb9051..c957706c 100644 --- a/src/eva2/tools/chart2d/ScaledBorder.java +++ b/src/eva2/tools/chart2d/ScaledBorder.java @@ -1,6 +1,7 @@ package eva2.tools.chart2d; import eva2.tools.math.Mathematics; + import java.awt.Color; import java.awt.Component; import java.awt.Dimension; @@ -18,687 +19,690 @@ import javax.swing.border.Border; /** * ScaledBorder puts a border around Components - * ( especially around DrawingAreas ) with scaled and labeled axes. + * ( especially around DrawingAreas ) with scaled and labeled axes. */ -public class ScaledBorder implements Border -{ - private boolean under_construction = false; +public class ScaledBorder implements Border { + private boolean under_construction = false; - /** - * length of the distance markers on the axes in pixels - */ - int marker_length = 2; + /** + * length of the distance markers on the axes in pixels + */ + int marker_length = 2; - /** - * length in pixels of the arrows at the ends of the axes - */ - int arrow_length = 10; + /** + * length in pixels of the arrows at the ends of the axes + */ + int arrow_length = 10; - /** - * a flag if the arrows should be visible - */ - public boolean show_arrows = true; + /** + * a flag if the arrows should be visible + */ + public boolean show_arrows = true; - /** - * distance between the x-values in digits - */ - int x_value2value = 2; + /** + * distance between the x-values in digits + */ + int x_value2value = 2; - /** - * distance between y-label and y-values in digit width - */ - int y_label2values = 1; + /** + * distance between y-label and y-values in digit width + */ + int y_label2values = 1; - /** - * distance between y-values and y-axis markers in parts of the digit width - */ - int y_values2marker = 2; + /** + * distance between y-values and y-axis markers in parts of the digit width + */ + int y_values2marker = 2; - /** - * distance between values and arrows in pixels - */ - int x_values2arrow = 10, - y_values2arrow = 10; + /** + * distance between values and arrows in pixels + */ + int x_values2arrow = 10, + y_values2arrow = 10; - /** - * distance between arrows and outer border - */ - int axis2border = 4; + /** + * distance between arrows and outer border + */ + int axis2border = 4; - /** - * distance between labels and the border in pixels - */ - public int x_label2border = 6, - y_label2border = 6; + /** + * distance between labels and the border in pixels + */ + public int x_label2border = 6, + y_label2border = 6; - /** - * the size of the source rectangle - * that means before the values are mdified by scale functions - */ - SlimRect src_rect = null; + /** + * the size of the source rectangle + * that means before the values are mdified by scale functions + */ + SlimRect src_rect = null; - /** - * the minimal increment of the scales - */ - public double minimal_increment; + /** + * the minimal increment of the scales + */ + public double minimal_increment; - /** - * the displayed labels - */ - public String x_label, y_label; + /** + * the displayed labels + */ + public String x_label, y_label; - /** - * foreground and background colors - */ - public Color foreground, background; + /** + * foreground and background colors + */ + public Color foreground, background; - /** - * the border which is shown around the scaled border - */ - Border outer_border; + /** + * the border which is shown around the scaled border + */ + Border outer_border; - /** - * flag if the outer border should be displayed - */ - boolean show_outer_border = true; + /** + * flag if the outer border should be displayed + */ + boolean show_outer_border = true; - /** - * scale functions if, for example, an logarithmic function is needed instead - * of a linear. - */ - public DFunction x_scale, y_scale; + /** + * scale functions if, for example, an logarithmic function is needed instead + * of a linear. + */ + public DFunction x_scale, y_scale; - /** - * formatters of the x- and y-axis numbers - * @see java.text.NumberFormat - */ - private NumberFormat format_x = new DecimalFormat(), - format_y = new DecimalFormat(); + /** + * formatters of the x- and y-axis numbers + * + * @see java.text.NumberFormat + */ + private NumberFormat format_x = new DecimalFormat(), + format_y = new DecimalFormat(); - /** - * Possible patterns for the number formats used by a border. - */ - private String[] decPatterns = {"#,##0.###", "0.###E0"}; // standard decimal or scientific exponential - - /** - * Internal states of which decPatterns to switch to next. - */ - private int nextYPattern = 1; - private int nextXPattern = 1; + /** + * Possible patterns for the number formats used by a border. + */ + private String[] decPatterns = {"#,##0.###", "0.###E0"}; // standard decimal or scientific exponential - private double src_dX = -1, src_dY = -1; + /** + * Internal states of which decPatterns to switch to next. + */ + private int nextYPattern = 1; + private int nextXPattern = 1; - private boolean do_refresh, - auto_scale_x = true, - auto_scale_y = true; + private double src_dX = -1, src_dY = -1; - private Insets old_insets; + private boolean do_refresh, + auto_scale_x = true, + auto_scale_y = true; - private DMeasures m; + private Insets old_insets; - /** - * constructor creates a default ScaledBorder inside of a lowered BevelBorder - */ - public ScaledBorder(){ - this( - BorderFactory.createBevelBorder( - BevelBorder.LOWERED, - Color.white, - Color.lightGray, - Color.black, - Color.lightGray - ) - ); - } - /** - * constructor creates a new ScaledBorder - * surrounded by the specified Border - */ - public ScaledBorder( Border outer ){ - outer_border = outer; - m = new DMeasures( this ); - } + private DMeasures m; - /** - * method tells the border to calculate the differences between displayed - * x-values by itself - */ - public void setAutoScaleX(){ auto_scale_x = true; } + /** + * constructor creates a default ScaledBorder inside of a lowered BevelBorder + */ + public ScaledBorder() { + this( + BorderFactory.createBevelBorder( + BevelBorder.LOWERED, + Color.white, + Color.lightGray, + Color.black, + Color.lightGray + ) + ); + } - /** - * method tells the border to calculate the differences between displayed - * y-values by itself - */ - public void setAutoScaleY(){ auto_scale_y = true; } + /** + * constructor creates a new ScaledBorder + * surrounded by the specified Border + */ + public ScaledBorder(Border outer) { + outer_border = outer; + m = new DMeasures(this); + } - /** - * method sets the differences between source x-values of the displayed values - * @see setAutoScaleX(). - * If scale functions are used there might be a difference between the shown values - * and the source values - */ - public void setSrcdX(double dX){ - auto_scale_x = false; - src_dX = dX; - } + /** + * method tells the border to calculate the differences between displayed + * x-values by itself + */ + public void setAutoScaleX() { + auto_scale_x = true; + } - /** - * method sets the differences between source y-values of the displayed values - * @see setAutoScaleY(). - * If scale functions are used there might be a difference between the shown values - * and the source values - */ - public void setSrcdY(double dY){ - auto_scale_y = false; - src_dY = dY; - } + /** + * method tells the border to calculate the differences between displayed + * y-values by itself + */ + public void setAutoScaleY() { + auto_scale_y = true; + } - /** - * Returns the inner rectangle in pixel coordinates. - * - * @param c - * @return - */ - public SlimRect getInnerRect(Component c) { - Insets inner_insets = getBorderInsets(c); - Dimension d = c.getSize(); - int width = d.width - inner_insets.left - inner_insets.right; - int height = d.height - inner_insets.top - inner_insets.bottom; + /** + * method sets the differences between source x-values of the displayed values + * + * @see setAutoScaleX(). + * If scale functions are used there might be a difference between the shown values + * and the source values + */ + public void setSrcdX(double dX) { + auto_scale_x = false; + src_dX = dX; + } + + /** + * method sets the differences between source y-values of the displayed values + * + * @see setAutoScaleY(). + * If scale functions are used there might be a difference between the shown values + * and the source values + */ + public void setSrcdY(double dY) { + auto_scale_y = false; + src_dY = dY; + } + + /** + * Returns the inner rectangle in pixel coordinates. + * + * @param c + * @return + */ + public SlimRect getInnerRect(Component c) { + Insets inner_insets = getBorderInsets(c); + Dimension d = c.getSize(); + int width = d.width - inner_insets.left - inner_insets.right; + int height = d.height - inner_insets.top - inner_insets.bottom; + + SlimRect rect = new SlimRect(inner_insets.left, inner_insets.top, width, height); + return rect; + } - SlimRect rect=new SlimRect(inner_insets.left, inner_insets.top, width, height); - return rect; - } - @Override - public void paintBorder(Component c, Graphics g, int x, int y, int width, int height){ - if( under_construction ) { - System.out.println("ScaledBorder.paintBorder()"); - } + public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { + if (under_construction) { + System.out.println("ScaledBorder.paintBorder()"); + } // Here one might know how much of the graph is taken by the border only and possibly switch to exponential numbering? - - if( foreground == null ) { - foreground = c.getForeground(); - } - if( background == null ) { - background = c.getBackground(); - } - Color old_color = g.getColor(); - g.setColor( background ); - g.fillRect( x, y, width, height ); - g.setColor( old_color ); - Insets outer_insets = new Insets( 0, 0, 0, 0);// insets of the outer border - if( show_outer_border ) { - outer_border.paintBorder( c, g, x, y, width, height ); - outer_insets = outer_border.getBorderInsets( c ); + if (foreground == null) { + foreground = c.getForeground(); + } + if (background == null) { + background = c.getBackground(); + } + Color old_color = g.getColor(); + g.setColor(background); + g.fillRect(x, y, width, height); + g.setColor(old_color); + + Insets outer_insets = new Insets(0, 0, 0, 0);// insets of the outer border + if (show_outer_border) { + outer_border.paintBorder(c, g, x, y, width, height); + outer_insets = outer_border.getBorderInsets(c); + } + + do_refresh = true; + Insets inner_insets = getBorderInsets(c); + + Dimension d = c.getSize(), + cd = new Dimension(d.width - inner_insets.left - inner_insets.right, + d.height - inner_insets.top - inner_insets.bottom); + + FontMetrics fm = g.getFontMetrics(); + int fontAsc = fm.getAscent(); + do_refresh = false; + + m.update(c, inner_insets); + + // axes + g.setColor(foreground); + g.drawLine(inner_insets.left, inner_insets.top, + inner_insets.left, inner_insets.top + cd.height); + g.drawLine(inner_insets.left, inner_insets.top + cd.height, + inner_insets.left + cd.width, inner_insets.top + cd.height); + + if (show_arrows) { + g.drawLine(inner_insets.left, inner_insets.top, + inner_insets.left, inner_insets.top - y_values2arrow); + g.drawLine(inner_insets.left - marker_length, inner_insets.top - y_values2arrow, + inner_insets.left, inner_insets.top - y_values2arrow - arrow_length); + g.drawLine(inner_insets.left + marker_length, inner_insets.top - y_values2arrow, + inner_insets.left, inner_insets.top - y_values2arrow - arrow_length); + g.drawLine(inner_insets.left - marker_length, inner_insets.top - y_values2arrow, + inner_insets.left + marker_length, inner_insets.top - y_values2arrow); + + g.drawLine(inner_insets.left + cd.width, inner_insets.top + cd.height, + inner_insets.left + cd.width + x_values2arrow, inner_insets.top + cd.height); + g.drawLine(inner_insets.left + cd.width + x_values2arrow, + inner_insets.top + cd.height - marker_length, + inner_insets.left + cd.width + x_values2arrow + arrow_length, + inner_insets.top + cd.height); + g.drawLine(inner_insets.left + cd.width + x_values2arrow, + inner_insets.top + cd.height + marker_length, + inner_insets.left + cd.width + x_values2arrow + arrow_length, + inner_insets.top + cd.height); + g.drawLine(inner_insets.left + cd.width + x_values2arrow, + inner_insets.top + cd.height - marker_length, + inner_insets.left + cd.width + x_values2arrow, + inner_insets.top + cd.height + marker_length); + } + + if (y_label != null) { + Dimension yld = new Dimension(fm.getAscent() + fm.getDescent(), fm.stringWidth(y_label)); + AffineTransform T = new AffineTransform(0, -1, 1, 0, 0, 0); + Font old = g.getFont(), f = old.deriveFont(T); + g.setFont(f); + g.drawString(y_label, y_label2border + fm.getAscent(), inner_insets.top + (cd.height + yld.height) / 2); + g.setFont(old); + } + + if (x_label != null) { + g.drawString( + x_label, inner_insets.left + (cd.width - fm.stringWidth(x_label)) / 2, + d.height - outer_insets.bottom - x_label2border - fm.getDescent()); + } + + if (src_rect.x == 0 && src_rect.y == 0) { + int v2m = fm.stringWidth("0") / y_values2marker; + g.drawString("0", inner_insets.left - fm.stringWidth("0") - v2m - marker_length, + inner_insets.top + cd.height + fontAsc); + g.drawLine(inner_insets.left, inner_insets.top + cd.height + fm.getAscent(), + inner_insets.left, inner_insets.top + cd.height); + g.drawLine(inner_insets.left, inner_insets.top + cd.height, + inner_insets.left - fm.stringWidth("0") - v2m - marker_length, + inner_insets.top + cd.height); + } + + drawYValues(g, inner_insets); + drawXValues(g, inner_insets, cd); + + g.setColor(old_color); } - do_refresh = true; - Insets inner_insets = getBorderInsets(c); + /** + * The scaling of the y-axis is defined here. + * + * @param g + * @param insets + */ + private void drawYValues(Graphics g, Insets insets) { + if (under_construction) { + System.out.println("ScaledBorder.drawYValues()"); + } - Dimension d = c.getSize(), - cd = new Dimension( d.width - inner_insets.left - inner_insets.right, - d.height - inner_insets.top - inner_insets.bottom ); + FontMetrics fm = g.getFontMetrics(); + int fontAsc = fm.getAscent(), v2m = fm.stringWidth("0") / y_values2marker; - FontMetrics fm = g.getFontMetrics(); - int fontAsc = fm.getAscent(); - do_refresh = false; - - m.update(c, inner_insets); - - // axes - g.setColor( foreground ); - g.drawLine( inner_insets.left, inner_insets.top, - inner_insets.left, inner_insets.top + cd.height ); - g.drawLine( inner_insets.left, inner_insets.top + cd.height, - inner_insets.left + cd.width, inner_insets.top + cd.height ); - - if( show_arrows ){ - g.drawLine( inner_insets.left, inner_insets.top, - inner_insets.left, inner_insets.top - y_values2arrow ); - g.drawLine( inner_insets.left - marker_length, inner_insets.top - y_values2arrow, - inner_insets.left, inner_insets.top - y_values2arrow - arrow_length ); - g.drawLine( inner_insets.left + marker_length, inner_insets.top - y_values2arrow, - inner_insets.left, inner_insets.top - y_values2arrow - arrow_length); - g.drawLine( inner_insets.left - marker_length, inner_insets.top - y_values2arrow, - inner_insets.left + marker_length, inner_insets.top - y_values2arrow ); - - g.drawLine( inner_insets.left + cd.width , inner_insets.top + cd.height, - inner_insets.left + cd.width + x_values2arrow, inner_insets.top + cd.height ); - g.drawLine( inner_insets.left + cd.width + x_values2arrow, - inner_insets.top + cd.height - marker_length, - inner_insets.left + cd.width + x_values2arrow + arrow_length, - inner_insets.top + cd.height ); - g.drawLine( inner_insets.left + cd.width + x_values2arrow, - inner_insets.top + cd.height + marker_length, - inner_insets.left + cd.width + x_values2arrow + arrow_length, - inner_insets.top + cd.height ); - g.drawLine( inner_insets.left + cd.width + x_values2arrow, - inner_insets.top + cd.height - marker_length, - inner_insets.left + cd.width + x_values2arrow, - inner_insets.top + cd.height + marker_length ); - } - - if( y_label != null ) { - Dimension yld = new Dimension(fm.getAscent()+fm.getDescent(), fm.stringWidth(y_label)); - AffineTransform T = new AffineTransform(0, -1, 1, 0, 0, 0); - Font old = g.getFont(), f = old.deriveFont( T ); - g.setFont( f ); - g.drawString( y_label, y_label2border + fm.getAscent(), inner_insets.top + ( cd.height + yld.height )/ 2 ); - g.setFont( old ); - } - - if( x_label != null ) { - g.drawString( - x_label, inner_insets.left + ( cd.width - fm.stringWidth( x_label ) ) / 2, - d.height - outer_insets.bottom - x_label2border - fm.getDescent() ); - } - - if( src_rect.x == 0 && src_rect.y == 0 ){ - int v2m = fm.stringWidth("0") / y_values2marker; - g.drawString( "0", inner_insets.left - fm.stringWidth( "0" ) - v2m - marker_length, - inner_insets.top + cd.height + fontAsc ); - g.drawLine( inner_insets.left, inner_insets.top + cd.height + fm.getAscent(), - inner_insets.left, inner_insets.top + cd.height); - g.drawLine( inner_insets.left, inner_insets.top + cd.height, - inner_insets.left - fm.stringWidth( "0" ) - v2m - marker_length, - inner_insets.top + cd.height ); - } - - drawYValues( g, inner_insets); - drawXValues( g, inner_insets, cd ); - - g.setColor( old_color ); - } - - /** - * The scaling of the y-axis is defined here. - * - * @param g - * @param insets - */ - private void drawYValues( Graphics g, Insets insets){ - if( under_construction ) { - System.out.println("ScaledBorder.drawYValues()"); - } - - FontMetrics fm = g.getFontMetrics(); - int fontAsc = fm.getAscent(), v2m = fm.stringWidth("0") / y_values2marker; - // double startVal,dn = (src_rect.y / src_dY ); // startVal = Math.round(dn-0.5)*src_dY; // // if( startVal < src_rect.y || ( src_rect.x == 0 && src_rect.y == 0 ) ) { // startVal+=src_dY; // } - - double startVal = Mathematics.firstMultipleAbove(src_rect.y, src_dY); - - double v, scaledV, minx = src_rect.x; - if( x_scale != null ) { - minx = x_scale.getImageOf( minx ); - } - v = startVal; - while (v <= src_rect.y + src_rect.height){ - if( y_scale != null ) { - scaledV = y_scale.getImageOf( v ); - } - else { - scaledV=v; - } - String text = format_y.format(scaledV); - try{ scaledV = format_y.parse(text).doubleValue(); } - catch( java.text.ParseException ex ){ } - Point p = m.getPoint( minx, scaledV ); - if( p != null ){ - g.drawString( text, - insets.left - fm.stringWidth( text ) - v2m - marker_length, - p.y + fontAsc / 2 ); - g.drawLine( insets.left - marker_length, p.y, insets.left, p.y ); - } - if (v+src_dY<= v) { -// System.err.println("Overflow error B in ScaledBorder! v,src_dY:" + v + ", " + src_dY); - v*=1.01; - } - v += src_dY; - } - } - - public double getSrcdY( FontMetrics fm, Dimension cd ){ - return getSrcdY(fm.getHeight(), cd.height); - } - public double getSrcdY( int fontMetricsHeight, int componentHeight ){ - if( under_construction ) { - System.out.println("ScaledBorder.getSrcdY()"); - } - if( (!do_refresh && src_dY != -1) || !auto_scale_y ) { - return src_dY; - } - int max = componentHeight / fontMetricsHeight; - if (Double.isInfinite(src_rect.height) || Double.isInfinite(src_rect.width)) { - System.err.println("Error, infinite value in ScaledBorder:getSrcdY !!"); - } - double minsrc_dY = 2 * src_rect.height / (double)max; // die 2 einfach mal so eingesetzt <-------------------------- - src_dY = aBitBigger( minsrc_dY ); - if( src_dY < minimal_increment ) { - src_dY = minimal_increment; - } - if( under_construction ) { - System.out.println("Setting src_dY to " + src_dY + " for " + src_rect); - } - return src_dY; - } - - private void drawXValues( Graphics g, Insets insets, Dimension cd ){ - if( under_construction ) { - System.out.println("ScaledBorder.drawXValues()"); - } + double startVal = Mathematics.firstMultipleAbove(src_rect.y, src_dY); - FontMetrics fm = g.getFontMetrics(); - double mx = cd.width / src_rect.width; - int n, labelX, - xnull = insets.left + (int)( - src_rect.x * mx ); - - n = (int)( src_rect.x / src_dX ); - if( n * src_dX < src_rect.x || ( src_rect.x == 0 && src_rect.y == 0 ) ) { - n++; - } - - int fontAsc = fm.getAscent(), xLineY = insets.top + cd.height; - labelX = xnull + (int)(n * src_dX * mx); - while( n * src_dX <= src_rect.x + src_rect.width ){ - double v = n * src_dX; - if( x_scale != null ) { - v = x_scale.getImageOf(v); + double v, scaledV, minx = src_rect.x; + if (x_scale != null) { + minx = x_scale.getImageOf(minx); + } + v = startVal; + while (v <= src_rect.y + src_rect.height) { + if (y_scale != null) { + scaledV = y_scale.getImageOf(v); + } else { + scaledV = v; + } + String text = format_y.format(scaledV); + try { + scaledV = format_y.parse(text).doubleValue(); + } catch (java.text.ParseException ex) { + } + Point p = m.getPoint(minx, scaledV); + if (p != null) { + g.drawString(text, + insets.left - fm.stringWidth(text) - v2m - marker_length, + p.y + fontAsc / 2); + g.drawLine(insets.left - marker_length, p.y, insets.left, p.y); + } + if (v + src_dY <= v) { +// System.err.println("Overflow error B in ScaledBorder! v,src_dY:" + v + ", " + src_dY); + v *= 1.01; + } + v += src_dY; } - String text = format_x.format(v); - try{ v = format_x.parse(text).doubleValue(); } - catch( java.text.ParseException ex ){ } - int strW = fm.stringWidth( text ); - g.drawString( text, labelX - strW / 2, xLineY + fontAsc ); - g.drawLine( labelX, xLineY, labelX, xLineY + marker_length ); - n++; - labelX = xnull + (int)( n * src_dX * mx); } - } - public double getSrcdX( FontMetrics fm, Dimension cd ){ - if( under_construction ) { - System.out.println("ScaledBorder.getSrcdX()"); - } - if( (!do_refresh && src_dX != - 1) || !auto_scale_x ) { - return src_dX; - } - int digit_width = fm.stringWidth("0"), - max = cd.width / ( digit_width * ( x_value2value + 1 ) ); - src_dX = src_rect.width / (double)max; - int n, labelX, olsrc_dX; + public double getSrcdY(FontMetrics fm, Dimension cd) { + return getSrcdY(fm.getHeight(), cd.height); + } - boolean ok = false; - while( !ok ){ - src_dX = aBitBigger( src_dX ); + public double getSrcdY(int fontMetricsHeight, int componentHeight) { + if (under_construction) { + System.out.println("ScaledBorder.getSrcdY()"); + } + if ((!do_refresh && src_dY != -1) || !auto_scale_y) { + return src_dY; + } + int max = componentHeight / fontMetricsHeight; + if (Double.isInfinite(src_rect.height) || Double.isInfinite(src_rect.width)) { + System.err.println("Error, infinite value in ScaledBorder:getSrcdY !!"); + } + double minsrc_dY = 2 * src_rect.height / (double) max; // die 2 einfach mal so eingesetzt <-------------------------- + src_dY = aBitBigger(minsrc_dY); + if (src_dY < minimal_increment) { + src_dY = minimal_increment; + } + if (under_construction) { + System.out.println("Setting src_dY to " + src_dY + " for " + src_rect); + } + return src_dY; + } - n = (int)( src_rect.x / src_dX ); - if( n * src_dX < src_rect.x ) { + private void drawXValues(Graphics g, Insets insets, Dimension cd) { + if (under_construction) { + System.out.println("ScaledBorder.drawXValues()"); + } + + FontMetrics fm = g.getFontMetrics(); + double mx = cd.width / src_rect.width; + int n, labelX, + xnull = insets.left + (int) (-src_rect.x * mx); + + n = (int) (src_rect.x / src_dX); + if (n * src_dX < src_rect.x || (src_rect.x == 0 && src_rect.y == 0)) { n++; } - olsrc_dX = 0; + int fontAsc = fm.getAscent(), xLineY = insets.top + cd.height; + labelX = xnull + (int) (n * src_dX * mx); + while (n * src_dX <= src_rect.x + src_rect.width) { + double v = n * src_dX; + if (x_scale != null) { + v = x_scale.getImageOf(v); + } + String text = format_x.format(v); + try { + v = format_x.parse(text).doubleValue(); + } catch (java.text.ParseException ex) { + } + int strW = fm.stringWidth(text); + g.drawString(text, labelX - strW / 2, xLineY + fontAsc); + g.drawLine(labelX, xLineY, labelX, xLineY + marker_length); + n++; + labelX = xnull + (int) (n * src_dX * mx); + } + } - boolean suits = true, first = true; - while( suits && n * src_dX <= src_rect.x + src_rect.width ){ - double v = n * src_dX; - if( x_scale != null ) { - v = x_scale.getImageOf( v ); - } - String text = format_x.format(v); - int strW = fm.stringWidth( text ); - labelX = (int)((( n * src_dX - src_rect.x ) / src_rect.width ) * cd.width ) - strW / 2; - if( !first && labelX <= olsrc_dX + digit_width * x_value2value ) { - suits = false; - } - else{ - olsrc_dX = labelX + strW; - n++; + public double getSrcdX(FontMetrics fm, Dimension cd) { + if (under_construction) { + System.out.println("ScaledBorder.getSrcdX()"); } - first = false; - } - if( !suits ) { - ok = false; + if ((!do_refresh && src_dX != -1) || !auto_scale_x) { + return src_dX; } - else { - ok = true; - } - } - if( src_dX < minimal_increment ) { - src_dX = minimal_increment; - } - return src_dX; - } + int digit_width = fm.stringWidth("0"), + max = cd.width / (digit_width * (x_value2value + 1)); + src_dX = src_rect.width / (double) max; + int n, labelX, olsrc_dX; - /** - * method returns to a certain minimal value the next higher value which can be - * displayed, which looks a bit nicer - * it returns values like ... 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, ... - * - * @param the double value next to which the displayable value should be found - * @return the displayable value - */ - public static double aBitBigger( double min ){ - if( min <= 0 || Double.isInfinite(min) || Double.isNaN(min)) { - return 1; - } - double d = 1; - if( min < d ){ - while( d * .5 > min ) { - d *= .5; - if( d * .4 > min ) { - d *= .4; - } - if( d * .5 > min ) { - d *= .5; - } - } + boolean ok = false; + while (!ok) { + src_dX = aBitBigger(src_dX); + + n = (int) (src_rect.x / src_dX); + if (n * src_dX < src_rect.x) { + n++; + } + + olsrc_dX = 0; + + boolean suits = true, first = true; + while (suits && n * src_dX <= src_rect.x + src_rect.width) { + double v = n * src_dX; + if (x_scale != null) { + v = x_scale.getImageOf(v); + } + String text = format_x.format(v); + int strW = fm.stringWidth(text); + labelX = (int) (((n * src_dX - src_rect.x) / src_rect.width) * cd.width) - strW / 2; + if (!first && labelX <= olsrc_dX + digit_width * x_value2value) { + suits = false; + } else { + olsrc_dX = labelX + strW; + n++; + } + first = false; + } + if (!suits) { + ok = false; + } else { + ok = true; + } + } + if (src_dX < minimal_increment) { + src_dX = minimal_increment; + } + return src_dX; } - else{ - while( d <= min ) { - d *= 2; - if( d <= min ) { - d *= 2.5; - } - if( d <= min ) { - d *= 2; - } - } + + /** + * method returns to a certain minimal value the next higher value which can be + * displayed, which looks a bit nicer + * it returns values like ... 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, ... + * + * @param the double value next to which the displayable value should be found + * @return the displayable value + */ + public static double aBitBigger(double min) { + if (min <= 0 || Double.isInfinite(min) || Double.isNaN(min)) { + return 1; + } + double d = 1; + if (min < d) { + while (d * .5 > min) { + d *= .5; + if (d * .4 > min) { + d *= .4; + } + if (d * .5 > min) { + d *= .5; + } + } + } else { + while (d <= min) { + d *= 2; + if (d <= min) { + d *= 2.5; + } + if (d <= min) { + d *= 2; + } + } + } + return d; } - return d; - } @Override - public boolean isBorderOpaque(){ - return outer_border.isBorderOpaque(); - } + public boolean isBorderOpaque() { + return outer_border.isBorderOpaque(); + } - /** - * Toggle between different decimal patterns on the axes. Basically shifts - * to the next pattern specified for this border type. - * - * @param xOrY if true toggle for the x axis otherwise for the y axis - */ - public void toggleDecPattern(boolean xOrY) { + /** + * Toggle between different decimal patterns on the axes. Basically shifts + * to the next pattern specified for this border type. + * + * @param xOrY if true toggle for the x axis otherwise for the y axis + */ + public void toggleDecPattern(boolean xOrY) { // System.out.println("Next pattern: " + nextYPattern); - int current; - if (xOrY) { - current = nextXPattern; - nextXPattern = (nextXPattern+1) % decPatterns.length; - } else { - current = nextYPattern; - nextYPattern = (nextYPattern+1) % decPatterns.length; - } - applyPattern(xOrY, decPatterns[current]); - } - - /** - * Switch between different decimal patterns on the axes. - * The next index gives the index within the pattern list of this border type - * to switch to. - * - * @param xOrY if true toggle for the x axis otherwise for the y axis - * @param next index of the pattern to switch to - */ - protected void setNextPattern(boolean xOrY, int next) { - if (xOrY) { - nextXPattern=next; - } - else { - nextYPattern=next; - } - toggleDecPattern(xOrY); - } - - /** - * Set the standard decimal number pattern for the x or y axis. - * - * @param xOrY if true, toggle for the x axis otherwise for the y axis - */ - public void setStandardPattern(boolean xOrY) { - setNextPattern(xOrY, 0); - } - - /** - * Set the exponential number pattern for the x or y axis. - * - * @param xOrY if true, toggle for the x axis otherwise for the y axis - */ - public void setScientificPattern(boolean xOrY) { - setNextPattern(xOrY, 1); - } - - /** - * Apply a decimal format pattern to x (bXorY true) or y (bXorY false) axis. - * - * @see #java.text.DecimalFormat.applyPattern - * - * @param bXorY - * @param pattern - */ - public void applyPattern(boolean bXorY, String pattern) { - if (bXorY) { - ((java.text.DecimalFormat)format_x).applyPattern(pattern); - } - else { - ((java.text.DecimalFormat)format_y).applyPattern(pattern); - } - } + int current; + if (xOrY) { + current = nextXPattern; + nextXPattern = (nextXPattern + 1) % decPatterns.length; + } else { + current = nextYPattern; + nextYPattern = (nextYPattern + 1) % decPatterns.length; + } + applyPattern(xOrY, decPatterns[current]); + } - /** - * This measures the space required for numberings on x and y axis and returns - * it. Depends on the decimal format applied and the FontMetrics of the - * current Graphics instance. - */ + /** + * Switch between different decimal patterns on the axes. + * The next index gives the index within the pattern list of this border type + * to switch to. + * + * @param xOrY if true toggle for the x axis otherwise for the y axis + * @param next index of the pattern to switch to + */ + protected void setNextPattern(boolean xOrY, int next) { + if (xOrY) { + nextXPattern = next; + } else { + nextYPattern = next; + } + toggleDecPattern(xOrY); + } + + /** + * Set the standard decimal number pattern for the x or y axis. + * + * @param xOrY if true, toggle for the x axis otherwise for the y axis + */ + public void setStandardPattern(boolean xOrY) { + setNextPattern(xOrY, 0); + } + + /** + * Set the exponential number pattern for the x or y axis. + * + * @param xOrY if true, toggle for the x axis otherwise for the y axis + */ + public void setScientificPattern(boolean xOrY) { + setNextPattern(xOrY, 1); + } + + /** + * Apply a decimal format pattern to x (bXorY true) or y (bXorY false) axis. + * + * @param bXorY + * @param pattern + * @see #java.text.DecimalFormat.applyPattern + */ + public void applyPattern(boolean bXorY, String pattern) { + if (bXorY) { + ((java.text.DecimalFormat) format_x).applyPattern(pattern); + } else { + ((java.text.DecimalFormat) format_y).applyPattern(pattern); + } + } + + /** + * This measures the space required for numberings on x and y axis and returns + * it. Depends on the decimal format applied and the FontMetrics of the + * current Graphics instance. + */ @Override - public Insets getBorderInsets(Component c){ - if( under_construction ) { - System.out.println("ScaledBorder.getBorderInsets()"); - } - if( !do_refresh && old_insets != null ) { - return old_insets; - } + public Insets getBorderInsets(Component c) { + if (under_construction) { + System.out.println("ScaledBorder.getBorderInsets()"); + } + if (!do_refresh && old_insets != null) { + return old_insets; + } - Graphics g = c.getGraphics(); + Graphics g = c.getGraphics(); - Insets insets = new Insets(0, 0, 0, 0); - if( show_outer_border ) { - insets = outer_border.getBorderInsets( c ); - } + Insets insets = new Insets(0, 0, 0, 0); + if (show_outer_border) { + insets = outer_border.getBorderInsets(c); + } - if( g == null ) { - return insets; - } + if (g == null) { + return insets; + } - FontMetrics fm = g.getFontMetrics(); + FontMetrics fm = g.getFontMetrics(); // int fontAsc = fm.getAscent(); - int fontHeight = fm.getHeight(), - digit_width = fm.stringWidth("0"); + int fontHeight = fm.getHeight(), + digit_width = fm.stringWidth("0"); - if( c instanceof DArea ){ - DArea area = (DArea)c; - DMeasures m = area.getDMeasures(); - src_rect = m.getSourceOf(area.getSlimRectangle()); - x_scale = area.getDMeasures().x_scale; - y_scale = area.getDMeasures().y_scale; - } + if (c instanceof DArea) { + DArea area = (DArea) c; + DMeasures m = area.getDMeasures(); + src_rect = m.getSourceOf(area.getSlimRectangle()); + x_scale = area.getDMeasures().x_scale; + y_scale = area.getDMeasures().y_scale; + } + + // left: + if (y_label != null) { + insets.left += fm.getAscent() + fm.getDescent(); + } + insets.left += y_label2values * digit_width; + getSrcdY(fm, c.getSize()); + double start, n, inc; + int maxWidth = 0; + start = src_dY * (int) (src_rect.y / src_dY); + n = start; + if (n < src_rect.y) { + n += src_dY; + } - // left: - if( y_label != null ) { - insets.left += fm.getAscent() + fm.getDescent(); - } - insets.left += y_label2values * digit_width; - getSrcdY( fm, c.getSize() ); - double start, n, inc; - int maxWidth = 0; - start = src_dY*(int)( src_rect.y / src_dY ); - n=start; - if ( n < src_rect.y ) { - n+=src_dY; - } - // System.out.println("Steps approx: " + ((src_rect.y + src_rect.height)-start)/src_dY); - if (((src_rect.y + src_rect.height)-start)/src_dY>20) { - inc = ((src_rect.y + src_rect.height)- start)/20.; - } - else { - inc = src_dY; - } - if ((n+inc)==n) { - System.err.println("Warning, too small increase step size!"); - } - for (; n <= src_rect.y + src_rect.height; n+=inc ){ + if (((src_rect.y + src_rect.height) - start) / src_dY > 20) { + inc = ((src_rect.y + src_rect.height) - start) / 20.; + } else { + inc = src_dY; + } + if ((n + inc) == n) { + System.err.println("Warning, too small increase step size!"); + } + for (; n <= src_rect.y + src_rect.height; n += inc) { // System.out.println(n); - // TODO here might be a bug for mean values - double v = n; - if( y_scale != null ) { - v = y_scale.getImageOf( v ); + // TODO here might be a bug for mean values + double v = n; + if (y_scale != null) { + v = y_scale.getImageOf(v); + } + int w = fm.stringWidth(format_y.format(v)); + if (w > maxWidth) { + maxWidth = w; + } + // avoid nearly endless loop for large src_rect.y value and small src_dY } - int w = fm.stringWidth( format_y.format(v) ); - if( w > maxWidth ) { - maxWidth = w; + + insets.left += 1 + y_label2border + maxWidth + digit_width / y_values2marker + marker_length; + + // bottom: + insets.bottom += 1 + fontHeight + x_label2border; + if (x_label != null) { + insets.bottom += fontHeight; } - // avoid nearly endless loop for large src_rect.y value and small src_dY + + // top: + if (show_arrows) { + insets.top += y_values2arrow + arrow_length; + } + insets.top += axis2border; + + // right: + if (show_arrows) { + insets.right += x_values2arrow + arrow_length; + } + insets.right += axis2border; + getSrcdX(fm, c.getSize()); + int k = (int) (src_rect.x + src_rect.width / src_dX); + if (k < 0) { + k++; + } + int w = fm.stringWidth(format_x.format(k * src_dX)); + if (w / 2 > insets.right) { + insets.right = w / 2; + } + + old_insets = insets; + return insets; } - - insets.left += 1 + y_label2border + maxWidth + digit_width / y_values2marker + marker_length; - - // bottom: - insets.bottom += 1 + fontHeight + x_label2border; - if( x_label != null ) { - insets.bottom += fontHeight; - } - - // top: - if( show_arrows ) { - insets.top += y_values2arrow + arrow_length; - } - insets.top += axis2border; - - // right: - if( show_arrows ) { - insets.right += x_values2arrow + arrow_length; - } - insets.right += axis2border; - getSrcdX( fm, c.getSize() ); - int k = (int)( src_rect.x + src_rect.width / src_dX ); - if( k < 0 ) { - k ++; - } - int w = fm.stringWidth( format_x.format(k * src_dX) ); - if( w / 2 > insets.right ) { - insets.right = w / 2; - } - - old_insets = insets; - return insets; - } } diff --git a/src/eva2/tools/chart2d/SlimRect.java b/src/eva2/tools/chart2d/SlimRect.java index b8c8b55f..ede181d2 100644 --- a/src/eva2/tools/chart2d/SlimRect.java +++ b/src/eva2/tools/chart2d/SlimRect.java @@ -3,143 +3,144 @@ package eva2.tools.chart2d; /** * Encapsulates a slim rectangle structure with x, y, width and height and * nothing else. Makes some painting calculations quite a bit faster. - * - * @author mkron * + * @author mkron */ public class SlimRect { - double x, y, width, height; + double x, y, width, height; - public SlimRect(double xpos, double ypos, double wd, double ht) { - x=xpos; - y=ypos; - width = wd; - height = ht; - } + public SlimRect(double xpos, double ypos, double wd, double ht) { + x = xpos; + y = ypos; + width = wd; + height = ht; + } - public SlimRect(SlimRect o) { - x=o.x; - y=o.y; - width = o.width; - height = o.height; - } - /** - * Check whether a given point lies within the rectangle. - * - * @param ox - * @param oy - * @return true if the given point lies within the rectangle, else false - */ - public boolean contains( double ox, double oy ){ - if (( ox < x ) || ( oy < y ) || ( ox > x + width ) || ( oy > y + height )) { - return false; - } - else { - return true; - } - } + public SlimRect(SlimRect o) { + x = o.x; + y = o.y; + width = o.width; + height = o.height; + } + + /** + * Check whether a given point lies within the rectangle. + * + * @param ox + * @param oy + * @return true if the given point lies within the rectangle, else false + */ + public boolean contains(double ox, double oy) { + if ((ox < x) || (oy < y) || (ox > x + width) || (oy > y + height)) { + return false; + } else { + return true; + } + } + + /** + * Check whether a given rectangle lies within this rectangle. + * + * @param xpos + * @param ypos + * @param wd + * @param ht + * @return true if the given rectangle lies within the rectangle, else false + */ + public boolean contains(double xpos, double ypos, double wd, double ht) { + return (contains(xpos, ypos) && contains(xpos + wd, ypos + ht)); + } - /** - * Check whether a given rectangle lies within this rectangle. - * - * @param xpos - * @param ypos - * @param wd - * @param ht - * @return true if the given rectangle lies within the rectangle, else false - */ - public boolean contains(double xpos, double ypos, double wd, double ht) { - return (contains(xpos,ypos) && contains(xpos+wd, ypos+ht)); - } - @Override - public String toString() { - return "SlimRect["+x+","+y+"/"+width+","+height+"]"; - } + public String toString() { + return "SlimRect[" + x + "," + y + "/" + width + "," + height + "]"; + } - /** - * Intersect two rectangles. If the intersection is empty, null is returned. - * - * @param r - * @return A rectangle representing the intersection or null - */ - public SlimRect getIntersection( SlimRect r ){ - return getIntersection(r.x, r.y, r.width, r.height); - } - - /** - * Intersect two rectangles. If the intersection is empty, null is returned. - * - * @param r - * @return A rectangle representing the intersection or null - */ - public SlimRect getIntersection( DRectangle r ){ - return getIntersection(r.getX(), r.getY(), r.getWidth(), r.getHeight()); - } - - /** - * Intersect two rectangles. If the intersection is empty, null is returned. - * - * @param rx - * @param ry - * @param rwidth - * @param rheight - * @return A rectangle representing the intersection or null - */ - public SlimRect getIntersection(double rx, double ry, double rwidth, double rheight){ - SlimRect s = new SlimRect(this); - if( s.x < rx ){ - s.x = rx; - s.width -= rx - s.x; - } - if( s.y < ry ){ - s.y = ry; - s.height -= ry - s.y; - } - if( s.x + s.width > rx + rwidth ) { - s.width = rx + rwidth - s.x; - } - if( s.y + s.height > ry + rheight ) { - s.height = ry + rheight - s.y; - } - if( s.width < 0 || s.height < 0 ) { - return null; - } - else { - return s; - } - } - - /** - * Check for empty intersection. - * @param r - * @return true if the two rectangles do not intersect, else false - */ - public boolean hasEmptyIntersection(DRectangle r){ - return (getIntersection(r.getX(), r.getY(), r.getWidth(), r.getHeight())==null); - } - - /** - * Check for empty intersection. - * @param r - * @return true if the two rectangles do not intersect, else false - */ - public boolean hasEmptyIntersection(SlimRect r){ - return (getIntersection(r)==null); - } + /** + * Intersect two rectangles. If the intersection is empty, null is returned. + * + * @param r + * @return A rectangle representing the intersection or null + */ + public SlimRect getIntersection(SlimRect r) { + return getIntersection(r.x, r.y, r.width, r.height); + } - public double getX() { - return x; - } + /** + * Intersect two rectangles. If the intersection is empty, null is returned. + * + * @param r + * @return A rectangle representing the intersection or null + */ + public SlimRect getIntersection(DRectangle r) { + return getIntersection(r.getX(), r.getY(), r.getWidth(), r.getHeight()); + } - public double getY() { - return y; - } + /** + * Intersect two rectangles. If the intersection is empty, null is returned. + * + * @param rx + * @param ry + * @param rwidth + * @param rheight + * @return A rectangle representing the intersection or null + */ + public SlimRect getIntersection(double rx, double ry, double rwidth, double rheight) { + SlimRect s = new SlimRect(this); + if (s.x < rx) { + s.x = rx; + s.width -= rx - s.x; + } + if (s.y < ry) { + s.y = ry; + s.height -= ry - s.y; + } + if (s.x + s.width > rx + rwidth) { + s.width = rx + rwidth - s.x; + } + if (s.y + s.height > ry + rheight) { + s.height = ry + rheight - s.y; + } + if (s.width < 0 || s.height < 0) { + return null; + } else { + return s; + } + } - public double getWidth() { - return width; - } - public double getHeight() { - return height; - } + /** + * Check for empty intersection. + * + * @param r + * @return true if the two rectangles do not intersect, else false + */ + public boolean hasEmptyIntersection(DRectangle r) { + return (getIntersection(r.getX(), r.getY(), r.getWidth(), r.getHeight()) == null); + } + + /** + * Check for empty intersection. + * + * @param r + * @return true if the two rectangles do not intersect, else false + */ + public boolean hasEmptyIntersection(SlimRect r) { + return (getIntersection(r) == null); + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getWidth() { + return width; + } + + public double getHeight() { + return height; + } } diff --git a/src/eva2/tools/diagram/ColorBarCalculator.java b/src/eva2/tools/diagram/ColorBarCalculator.java index 8232dc1c..1485c0e9 100644 --- a/src/eva2/tools/diagram/ColorBarCalculator.java +++ b/src/eva2/tools/diagram/ColorBarCalculator.java @@ -26,124 +26,121 @@ import java.awt.*; /** * Calculates the color values for a legend-style color bar. */ -public class ColorBarCalculator -{ +public class ColorBarCalculator { /*-------------------------------------------------------------------------- * static public final member variables *--------------------------------------------------------------------------*/ - static public final int BLUE_TO_RED = 0; - static public final int GREY_SCALE = 1; - static public final int BLUE_SCALE = 2; - static public final int ALL_COLORS = 3; - // GREY_SCALE returns luminance values in [0.1;0.9], GREY_EXTENDED_SCALE in [0.0;1.0] - static public final int GREY_EXTENDED_SCALE = 4; + static public final int BLUE_TO_RED = 0; + static public final int GREY_SCALE = 1; + static public final int BLUE_SCALE = 2; + static public final int ALL_COLORS = 3; + // GREY_SCALE returns luminance values in [0.1;0.9], GREY_EXTENDED_SCALE in [0.0;1.0] + static public final int GREY_EXTENDED_SCALE = 4; /*-------------------------------------------------------------------------- * private member variables *--------------------------------------------------------------------------*/ - private int color_scale = BLUE_TO_RED; - private boolean inverseScale = false; + private int color_scale = BLUE_TO_RED; + private boolean inverseScale = false; /*-------------------------------------------------------------------------- * constructor *--------------------------------------------------------------------------*/ - public ColorBarCalculator(int color_scale) - { - this.color_scale = color_scale; - } + public ColorBarCalculator(int color_scale) { + this.color_scale = color_scale; + } /*-------------------------------------------------------------------------- * public methods *--------------------------------------------------------------------------*/ - public void setColorScale(int color_scale) { this.color_scale = color_scale; } - - /** - * Returns color for the given float-value, which must be in the range from 0 to 1. - * Warning: Creates new color object, better use the method 'getRGB' if possible. - */ - public Color getColor(float value) - { - return new Color( getRGB(value) ); - } - - /** - * Returns color RGB-value for the given float-value, which must be in the range from 0 to 1. - */ - public int getRGB(float value) - { - int rgbValue = 0; - if(inverseScale) { - value = 1 - value; + public void setColorScale(int color_scale) { + this.color_scale = color_scale; } - switch (color_scale) - { - case BLUE_TO_RED: - float hue = value * (value + value * 0.8F) / 2.65F - 1F; - rgbValue = Color.HSBtoRGB(hue, 0.6F, 1F); - break; - case GREY_SCALE: - rgbValue = Color.HSBtoRGB(0F, 0F, (value * 0.8F) + 0.1F); - break; - - case BLUE_SCALE: - int rg = (int) (value * 0.95F * 256); - int b = (int) ((value/2.0F + 0.45F) * 256); - rgbValue = rg * 0x10000 + rg * 0x100 + b; - break; - - case ALL_COLORS: - rgbValue = Color.HSBtoRGB(value, 0.6F, 1F); - break; - - case GREY_EXTENDED_SCALE: - rgbValue = Color.HSBtoRGB(0F, 0F, value ); - break; + /** + * Returns color for the given float-value, which must be in the range from 0 to 1. + * Warning: Creates new color object, better use the method 'getRGB' if possible. + */ + public Color getColor(float value) { + return new Color(getRGB(value)); } - return rgbValue; - } - /** - * Reverts color scale (e.g. black will be white and vice versa). - * @param isInverse Color scale is inverted, if isInverse is set to true. - */ - public void setInverseScale(boolean isInverse) { - inverseScale = isInverse; - } + /** + * Returns color RGB-value for the given float-value, which must be in the range from 0 to 1. + */ + public int getRGB(float value) { + int rgbValue = 0; + if (inverseScale) { + value = 1 - value; + } + switch (color_scale) { + case BLUE_TO_RED: + float hue = value * (value + value * 0.8F) / 2.65F - 1F; + rgbValue = Color.HSBtoRGB(hue, 0.6F, 1F); + break; - /** - * Returns current scale mode. - * @return true if scale is inverted, else false. - */ - public boolean isInverseScale() { - return inverseScale; - } + case GREY_SCALE: + rgbValue = Color.HSBtoRGB(0F, 0F, (value * 0.8F) + 0.1F); + break; + + case BLUE_SCALE: + int rg = (int) (value * 0.95F * 256); + int b = (int) ((value / 2.0F + 0.45F) * 256); + rgbValue = rg * 0x10000 + rg * 0x100 + b; + break; + + case ALL_COLORS: + rgbValue = Color.HSBtoRGB(value, 0.6F, 1F); + break; + + case GREY_EXTENDED_SCALE: + rgbValue = Color.HSBtoRGB(0F, 0F, value); + break; + } + return rgbValue; + } + + /** + * Reverts color scale (e.g. black will be white and vice versa). + * + * @param isInverse Color scale is inverted, if isInverse is set to true. + */ + public void setInverseScale(boolean isInverse) { + inverseScale = isInverse; + } + + /** + * Returns current scale mode. + * + * @return true if scale is inverted, else false. + */ + public boolean isInverseScale() { + return inverseScale; + } /*-------------------------------------------------------------------------- * static public methods *--------------------------------------------------------------------------*/ - /** - * Returns color for the given float-value, which must be in the range from 0 to 1. - * Warning: Creates new color object, better use the method 'getRGB' if possible. - */ - static public Color getDefaultColor(float value) - { - return new Color( getDefaultRGB(value) ); - } + /** + * Returns color for the given float-value, which must be in the range from 0 to 1. + * Warning: Creates new color object, better use the method 'getRGB' if possible. + */ + static public Color getDefaultColor(float value) { + return new Color(getDefaultRGB(value)); + } - /** - * Returns color RGB-value for the given float-value, which must be in the range from 0 to 1. - */ - static public int getDefaultRGB(float value) - { - float hue = value * (value + value * 0.8F) / 2.65F - 1F; - return Color.HSBtoRGB(hue, 0.6F, 1F); - } + /** + * Returns color RGB-value for the given float-value, which must be in the range from 0 to 1. + */ + static public int getDefaultRGB(float value) { + float hue = value * (value + value * 0.8F) / 2.65F - 1F; + return Color.HSBtoRGB(hue, 0.6F, 1F); + } } /**************************************************************************** diff --git a/src/eva2/tools/math/BayNet.java b/src/eva2/tools/math/BayNet.java index f09c7504..fd2368e4 100644 --- a/src/eva2/tools/math/BayNet.java +++ b/src/eva2/tools/math/BayNet.java @@ -7,6 +7,7 @@ import eva2.optimization.individuals.InterfaceDataTypeBinary; import eva2.optimization.individuals.InterfaceGAIndividual; import eva2.optimization.population.Population; import eva2.tools.Pair; + import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; @@ -16,86 +17,83 @@ import java.util.List; public class BayNet { - private boolean[][] network = null; - private int dimension = 3; - private BayNode[] nodes = null; - private List rootNodes = new LinkedList(); - private double upperProbLimit = 0.9; - private double lowerProbLimit = 0.1; - private BOAScoringMethods scoringMethod = BOAScoringMethods.BDM; - private double[] scoreArray = null; + private boolean[][] network = null; + private int dimension = 3; + private BayNode[] nodes = null; + private List rootNodes = new LinkedList(); + private double upperProbLimit = 0.9; + private double lowerProbLimit = 0.1; + private BOAScoringMethods scoringMethod = BOAScoringMethods.BDM; + private double[] scoreArray = null; // private String tables = ""; - public BayNet(int dimension, double upperLimit, double lowerLimit){ - this.dimension = dimension; - this.upperProbLimit = upperLimit; - this.lowerProbLimit = lowerLimit; - init(); - } + public BayNet(int dimension, double upperLimit, double lowerLimit) { + this.dimension = dimension; + this.upperProbLimit = upperLimit; + this.lowerProbLimit = lowerLimit; + init(); + } - public BayNet(BayNet b){ - this.network = cloneNetwork(b.network); - this.dimension = b.dimension; - this.nodes = new BayNode[b.dimension]; - for(int i=0; i(); - for(Integer node: b.rootNodes){ - this.rootNodes.add(node); - } - this.upperProbLimit = b.upperProbLimit; - this.lowerProbLimit = b.lowerProbLimit; - } + public BayNet(BayNet b) { + this.network = cloneNetwork(b.network); + this.dimension = b.dimension; + this.nodes = new BayNode[b.dimension]; + for (int i = 0; i < this.nodes.length; i++) { + this.nodes[i] = (BayNode) b.nodes[i].clone(); + } + this.rootNodes = new LinkedList(); + for (Integer node : b.rootNodes) { + this.rootNodes.add(node); + } + this.upperProbLimit = b.upperProbLimit; + this.lowerProbLimit = b.lowerProbLimit; + } @Override - public Object clone(){ - return new BayNet(this); - } - - private boolean[][] cloneNetwork(boolean[][] b){ - boolean[][] result = new boolean[b.length][b.length]; - for(int i=0; i getRootNodes(){ + /** + * initialize the Network + */ + public void init() { + this.network = new boolean[this.dimension][this.dimension]; + this.nodes = new BayNode[this.dimension]; + for (int i = 0; i < this.dimension; i++) { + this.nodes[i] = new BayNode(i); + this.rootNodes.add(i); + } + this.scoreArray = new double[this.dimension]; + Arrays.fill(scoreArray, -1.0); + } + + private static BitSet getBinaryData(AbstractEAIndividual indy) { + if (indy instanceof InterfaceGAIndividual) { + return ((InterfaceGAIndividual) indy).getBGenotype(); + } else if (indy instanceof InterfaceDataTypeBinary) { + return ((InterfaceDataTypeBinary) indy).getBinaryData(); + } else { + throw new RuntimeException("Unable to get binary representation for " + indy.getClass()); + } + } + + /** + * @return a list of the root nodes + */ + public List getRootNodes() { // ArrayList result = new ArrayList(); // for (int i=0; i result = new LinkedList(); - for(Integer i: this.rootNodes){ - result.add(this.nodes[i]); - } - return result; - } + LinkedList result = new LinkedList(); + for (Integer i : this.rootNodes) { + result.add(this.nodes[i]); + } + return result; + } - /** - * get the i-th node - * @param i the node to be returned - * @return the requested node - */ - public BayNode getNode(int i){ - return this.nodes[i]; - } + /** + * get the i-th node + * + * @param i the node to be returned + * @return the requested node + */ + public BayNode getNode(int i) { + return this.nodes[i]; + } - /** - * return the children for a given node - * @param n the node - * @return the children of the node - */ - public List getChildren(BayNode n){ + /** + * return the children for a given node + * + * @param n the node + * @return the children of the node + */ + public List getChildren(BayNode n) { // ArrayList result = new ArrayList(); // int i = n.getId(); // for(int j=0; j ids = n.getChildren(); - List result = new ArrayList(); - for(int i: ids){ - result.add(this.nodes[i]); - } - return result; - } + List ids = n.getChildren(); + List result = new ArrayList(); + for (int i : ids) { + result.add(this.nodes[i]); + } + return result; + } - /** - * return the parents for a given node - * @param n the node - * @return the parents of the node - */ - public List getParents(BayNode n){ + /** + * return the parents for a given node + * + * @param n the node + * @return the parents of the node + */ + public List getParents(BayNode n) { // ArrayList result = new ArrayList(); // int i = n.getId(); // for(int j=0; j ids = n.getParents(); - List result = new LinkedList(); - for(int i: ids){ - result.add(this.nodes[i]); - } - return result; - } + List ids = n.getParents(); + List result = new LinkedList(); + for (int i : ids) { + result.add(this.nodes[i]); + } + return result; + } - /** - * return the children of a list of nodes - * @param n the list of nodes - * @return the children of the nodes - */ - public List getChildren(List n){ - ArrayList result = new ArrayList(); - for(BayNode node: n){ - List children = getChildren(node); - for(BayNode nod: children){ - if(!result.contains(nod)){ - result.add(nod); - } - } - } - return result; - } - - /** - * remove the edge from node i to node j - * @param i the node from which the edge comes - * @param j the node to which the edge points - */ - public void removeEdge(Integer i, Integer j){ - if(this.network[i][j]){ - this.network[i][j] = false; - this.nodes[j].decrNumberOfParents(); - this.nodes[i].removeChild(j); - this.nodes[j].removeParent(i); - this.nodes[j].generateNewPTable(); - if(this.nodes[j].getNumberOfParents() == 0){ - this.rootNodes.add(j); - } - } - } + /** + * return the children of a list of nodes + * + * @param n the list of nodes + * @return the children of the nodes + */ + public List getChildren(List n) { + ArrayList result = new ArrayList(); + for (BayNode node : n) { + List children = getChildren(node); + for (BayNode nod : children) { + if (!result.contains(nod)) { + result.add(nod); + } + } + } + return result; + } - /** - * add an edge from the node i to the node j - * @param i edge from this node - * @param j edge to this node - */ - public void addEdge(Integer i, Integer j){ - if(i!=j){ - if(!this.network[i][j]){ - this.network[i][j] = true; - this.rootNodes.remove(j); - this.nodes[j].incrNumberOfParents(); - this.nodes[j].generateNewPTable(); - this.nodes[i].addChild(j); - this.nodes[j].addParent(i); - } - } - } - - private int findNext(double[] probabilities){ - int result = -1; - for(int i=0; i parents = getParents(currentNode); - boolean possible = true; - for(BayNode node: parents){ - if(probabilities[node.getId()]==-1){ - possible = false; - } - } - if(!possible){ - continue; - } - result = i; - break; - } - return result; - } + /** + * remove the edge from node i to node j + * + * @param i the node from which the edge comes + * @param j the node to which the edge points + */ + public void removeEdge(Integer i, Integer j) { + if (this.network[i][j]) { + this.network[i][j] = false; + this.nodes[j].decrNumberOfParents(); + this.nodes[i].removeChild(j); + this.nodes[j].removeParent(i); + this.nodes[j].generateNewPTable(); + if (this.nodes[j].getNumberOfParents() == 0) { + this.rootNodes.add(j); + } + } + } - /** - * find the next value where all the parents are already set - * @param data - * @return - */ - private int findNext(double[] probabilities, List nodes){ - nodes = removeDuplicate(nodes); - for(BayNode node: nodes){ - if(node.getCalculated()){ - continue; - } - node.setCalculated(true); - List parents = getParents(node); - boolean possible = false; - for(BayNode p: parents){ - if(probabilities[p.getId()] != -1){ - possible = true; - }else{ - possible = false; - break; - } - } - if(possible){ - resetCalculated(); - return node.getId(); - } - } - resetCalculated(); - return -1; - } + /** + * add an edge from the node i to the node j + * + * @param i edge from this node + * @param j edge to this node + */ + public void addEdge(Integer i, Integer j) { + if (i != j) { + if (!this.network[i][j]) { + this.network[i][j] = true; + this.rootNodes.remove(j); + this.nodes[j].incrNumberOfParents(); + this.nodes[j].generateNewPTable(); + this.nodes[i].addChild(j); + this.nodes[j].addParent(i); + } + } + } - private List removeDuplicate(List nodes) { - //Create a HashSet which allows no duplicates - HashSet hashSet = new HashSet(nodes); + private int findNext(double[] probabilities) { + int result = -1; + for (int i = 0; i < probabilities.length; i++) { + if (probabilities[i] != -1) { + continue; + } + BayNode currentNode = nodes[i]; + List parents = getParents(currentNode); + boolean possible = true; + for (BayNode node : parents) { + if (probabilities[node.getId()] == -1) { + possible = false; + } + } + if (!possible) { + continue; + } + result = i; + break; + } + return result; + } - //Assign the HashSet to a new ArrayList - ArrayList arrayList2 = new ArrayList(hashSet) ; - return arrayList2; - } + /** + * find the next value where all the parents are already set + * + * @param data + * @return + */ + private int findNext(double[] probabilities, List nodes) { + nodes = removeDuplicate(nodes); + for (BayNode node : nodes) { + if (node.getCalculated()) { + continue; + } + node.setCalculated(true); + List parents = getParents(node); + boolean possible = false; + for (BayNode p : parents) { + if (probabilities[p.getId()] != -1) { + possible = true; + } else { + possible = false; + break; + } + } + if (possible) { + resetCalculated(); + return node.getId(); + } + } + resetCalculated(); + return -1; + } - /** - * calculate a new BitSet according to the network - * @param data the BitSet that will be calculated - * @return the new BitSet - */ - public BitSet sample(BitSet data){ - // generate a new probabilities-vector - double[] probabilities = new double[this.network.length]; - for(int i=0; i nodes = getRootNodes(); - // calculate the BitSet-Value for these nodes - for(BayNode node: nodes){ - int id = node.getId(); - probabilities[id] = node.getProbability(0); - data.set(id, RNG.flipCoin(probabilities[id])); - node.setCalculated(true); - } - // find the next node that can be evaluated + private List removeDuplicate(List nodes) { + //Create a HashSet which allows no duplicates + HashSet hashSet = new HashSet(nodes); + + //Assign the HashSet to a new ArrayList + ArrayList arrayList2 = new ArrayList(hashSet); + return arrayList2; + } + + /** + * calculate a new BitSet according to the network + * + * @param data the BitSet that will be calculated + * @return the new BitSet + */ + public BitSet sample(BitSet data) { + // generate a new probabilities-vector + double[] probabilities = new double[this.network.length]; + for (int i = 0; i < probabilities.length; i++) { + probabilities[i] = -1; + } + // get the root-nodes (the non dependent nodes) + List nodes = getRootNodes(); + // calculate the BitSet-Value for these nodes + for (BayNode node : nodes) { + int id = node.getId(); + probabilities[id] = node.getProbability(0); + data.set(id, RNG.flipCoin(probabilities[id])); + node.setCalculated(true); + } + // find the next node that can be evaluated // List toCalculate = getChildren(nodes); // int next = findNext(probabilities, toCalculate); - int next = findNext(probabilities); - while(next != -1){ + int next = findNext(probabilities); + while (next != -1) { // toCalculate.remove(this.nodes[next]); - this.nodes[next].setCalculated(true); + this.nodes[next].setCalculated(true); // toCalculate = addToToCalculate(toCalculate, this.nodes[next]); // toCalculate.addAll(getChildren(this.nodes[next])); // probabilities[next] = calculateNextProbability(data, toCalculate, next); - probabilities[next] = calculateNextProbability(data, next); - data.set(next, RNG.flipCoin(probabilities[next])); + probabilities[next] = calculateNextProbability(data, next); + data.set(next, RNG.flipCoin(probabilities[next])); // next = findNext(probabilities, toCalculate); - next = findNext(probabilities); - } - resetCalculated(); - return data; - } + next = findNext(probabilities); + } + resetCalculated(); + return data; + } - private List addToToCalculate(List toCalculate, - BayNode next) { - List toAdd = getChildren(next); - for(int i=0; i=0; i--){ - if(data.get(parId[i])){ - par += Math.pow(2, i); - } - } - return this.nodes[next].getProbability(par); - } + private List addToToCalculate(List toCalculate, + BayNode next) { + List toAdd = getChildren(next); + for (int i = 0; i < toAdd.size(); i++) { + BayNode node = toAdd.get(i); + if (!toCalculate.contains(node) && !node.getCalculated()) { + toCalculate.add(node); + } + } + return toCalculate; + } - /** - * calculate the next probability - * @param data the already calculated data - * @param probabilities the already calculated probabilities - * @param toCalculate the Nodes that have yet to be calculated - * @param next the node for which to calculate the probability - * @return the new probabilities array - */ - private double calculateNextProbability(BitSet data, List toCalculate, int next) { - toCalculate.addAll(getChildren(this.nodes[next])); - int[] parId = calculateSortedParentIds(next); - int prob = 0; - int cnt = 0; - for(int j=parId.length-1; j>=0; j--){ - if(data.get(parId[j])){ - prob += (int) Math.pow(2, j); - } - cnt++; - } - return this.nodes[next].getProbability(prob); - } + private double calculateNextProbability(BitSet data, int next) { + int[] parId = calculateSortedParentIds(next); + int par = 0; + for (int i = parId.length - 1; i >= 0; i--) { + if (data.get(parId[i])) { + par += Math.pow(2, i); + } + } + return this.nodes[next].getProbability(par); + } - /** - * generate an array of the parents, sorted by there id - * @param id the id of the node - * @return the sorted parent-ids - */ - private int[] calculateSortedParentIds(int id) { - List parents = getParents(this.nodes[id]); - int[] parId = new int[parents.size()]; - int i=0; - for(BayNode nod: parents){ - parId[i] = nod.getId(); - i++; - } - Arrays.sort(parId); - return parId; - } + /** + * calculate the next probability + * + * @param data the already calculated data + * @param probabilities the already calculated probabilities + * @param toCalculate the Nodes that have yet to be calculated + * @param next the node for which to calculate the probability + * @return the new probabilities array + */ + private double calculateNextProbability(BitSet data, List toCalculate, int next) { + toCalculate.addAll(getChildren(this.nodes[next])); + int[] parId = calculateSortedParentIds(next); + int prob = 0; + int cnt = 0; + for (int j = parId.length - 1; j >= 0; j--) { + if (data.get(parId[j])) { + prob += (int) Math.pow(2, j); + } + cnt++; + } + return this.nodes[next].getProbability(prob); + } + + /** + * generate an array of the parents, sorted by there id + * + * @param id the id of the node + * @return the sorted parent-ids + */ + private int[] calculateSortedParentIds(int id) { + List parents = getParents(this.nodes[id]); + int[] parId = new int[parents.size()]; + int i = 0; + for (BayNode nod : parents) { + parId[i] = nod.getId(); + i++; + } + Arrays.sort(parId); + return parId; + } // /** // * generate an array of the parents plus the given node, sorted by there id @@ -409,363 +417,432 @@ public class BayNet { // Arrays.sort(sortedIds); // return sortedIds; // } - - private void resetCalculated(){ - for(int i=0; i toCalculate = getChildren(this.nodes[to]); - while(!toCalculate.isEmpty()){ - BayNode node = toCalculate.get(0); - toCalculate.remove(node); - if(!node.getCalculated()){ - node.setCalculated(true); - if(from == node.getId()){ - resetCalculated(); - return false; - } - List children = getChildren(node); - toCalculate.addAll(children); - } - } - resetCalculated(); - return true; - } - /** - * check if the given Network is acyclic - * @param net the Network - * @return is the net acyclic - */ - public boolean isACyclic(){ - List> deletedEdges = new LinkedList>(); - List nodes = getRootNodes(); - boolean res=false; - for(int i=0; i<=this.dimension; i++){ - for(BayNode node: nodes){ - int id = node.getId(); - for(int j=0; j(id,j)); - } - } - } - nodes = getRootNodes(); - // if we only have root nodes, we have an acyclic graph - if(nodes.size() == this.nodes.length){ - res = true; - break; - } - } - for (Pair edge : deletedEdges) { - this.network[edge.head][edge.tail] = true; - } - return res; - } + private void resetCalculated() { + for (int i = 0; i < this.dimension; i++) { + this.nodes[i].setCalculated(false); + } + } - private double getPrior(List parents, Population pop){ - double result = 1.0; - switch(this.scoringMethod){ - case BDM: result = ((double) pop.size()) / Math.pow(2.0, (double) parents.size()); break; - case K2: result = 2.0; - } - return result; - } + /** + * see if the network is still acyclic after inserting the edge + * + * @param from the node from which the edge comes from + * @param to the node to which the edgte points + * @return is the network still acyclic + */ + public boolean isACyclic(int from, int to) { + int cnt1 = 0; + int cnt2 = 0; + for (int i = 0; i < this.dimension; i++) { + if (this.network[i][from]) { + cnt1++; + } + if (this.network[to][i]) { + cnt2++; + } + } + // if the from node has no incoming edges or the to node has no outgoing edges the network is still acyclic + if (cnt1 == 0 || cnt2 == 0) { + return true; + } + // look at all the children and see if we can get to the from-node from the to-node + List toCalculate = getChildren(this.nodes[to]); + while (!toCalculate.isEmpty()) { + BayNode node = toCalculate.get(0); + toCalculate.remove(node); + if (!node.getCalculated()) { + node.setCalculated(true); + if (from == node.getId()) { + resetCalculated(); + return false; + } + List children = getChildren(node); + toCalculate.addAll(children); + } + } + resetCalculated(); + return true; + } - private double getPrior(List parents, BayNode current, Population pop){ - double result = 1.0; - switch(this.scoringMethod){ - case BDM: result = getPrior(parents, pop) / 2.0; break; - case K2: result = 1.0; - } - return result; - } + /** + * check if the given Network is acyclic + * + * @param net the Network + * @return is the net acyclic + */ + public boolean isACyclic() { + List> deletedEdges = new LinkedList>(); + List nodes = getRootNodes(); + boolean res = false; + for (int i = 0; i <= this.dimension; i++) { + for (BayNode node : nodes) { + int id = node.getId(); + for (int j = 0; j < this.dimension; j++) { + if (this.network[id][j]) { + this.network[id][j] = false; + deletedEdges.add(new Pair(id, j)); + } + } + } + nodes = getRootNodes(); + // if we only have root nodes, we have an acyclic graph + if (nodes.size() == this.nodes.length) { + res = true; + break; + } + } + for (Pair edge : deletedEdges) { + this.network[edge.head][edge.tail] = true; + } + return res; + } - public void setUpperProbLimit(double upperProbLimit) { - this.upperProbLimit = upperProbLimit; - } + private double getPrior(List parents, Population pop) { + double result = 1.0; + switch (this.scoringMethod) { + case BDM: + result = ((double) pop.size()) / Math.pow(2.0, (double) parents.size()); + break; + case K2: + result = 2.0; + } + return result; + } - public void setLowerProbLimit(double lowerProbLimit) { - this.lowerProbLimit = lowerProbLimit; - } - - - private double gamma(double x){ - double result = 1.0; - result = SpecialFunction.gamma(x); - return result; - } + private double getPrior(List parents, BayNode current, Population pop) { + double result = 1.0; + switch (this.scoringMethod) { + case BDM: + result = getPrior(parents, pop) / 2.0; + break; + case K2: + result = 1.0; + } + return result; + } - /** - * calculate the score, either BDM, K2 or BIC - * @param pop the population on which the metric is based on - * @return the metric - */ - public double getScore(Population pop){ - double result = 0.0; - //for every node - for(int i=0; i parents = getParents(currentNode); - // get the parentIds sorted (for the lookup) - int[] parId = new int[0]; - if(!parents.isEmpty()){ - parId = calculateSortedParentIds(i); - } - double[] pTable = currentNode.getPTable(); - switch(this.scoringMethod){ - case BIC: result -= (Math.log(pop.size()) * pTable.length * 2)/2;break; - default: break; - } - for(int j=0; j parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if (!parents.isEmpty()) { + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch (this.scoringMethod) { + case BIC: + result -= (Math.log(pop.size()) * pTable.length * 2) / 2; + break; + default: + break; + } + for (int j = 0; j < pTable.length; j++) { + Population pop2 = numberSetCorrectly(pop, j, parId); // double firstFraction = 0.0; - switch(this.scoringMethod){ - case BDM: result += Math.log(firstFractionBDM(pop, parents, pop2)); break; - case K2: result += Math.log(firstFractionBDM(pop, parents, pop2)); break; - case BIC: result -= firstFractionBIC(pop2); break; - } + switch (this.scoringMethod) { + case BDM: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case K2: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case BIC: + result -= firstFractionBIC(pop2); + break; + } // result = result + Math.log(firstFraction); - if(pop2.size() > 0){ - for(int k=0; k<2; k++){ + if (pop2.size() > 0) { + for (int k = 0; k < 2; k++) { // double secondFraction = 0.0; - switch(this.scoringMethod){ - case BDM: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case K2: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case BIC: result += secondFractionBIC(pop2, currentNode, k, j); break; - } + switch (this.scoringMethod) { + case BDM: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case K2: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case BIC: + result += secondFractionBIC(pop2, currentNode, k, j); + break; + } // result = result + Math.log(secondFraction); - } - } - } - } - return result; - } - - public void initScoreArray(Population pop){ - //for every node - for(int i=0; i parents = getParents(currentNode); - // get the parentIds sorted (for the lookup) - int[] parId = new int[0]; - if(!parents.isEmpty()){ - parId = calculateSortedParentIds(i); - } - double[] pTable = currentNode.getPTable(); - switch(this.scoringMethod){ - case BIC: result -= (Math.log(pop.size()) * pTable.length * 2)/2;break; - default: break; - } - for(int j=0; j parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if (!parents.isEmpty()) { + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch (this.scoringMethod) { + case BIC: + result -= (Math.log(pop.size()) * pTable.length * 2) / 2; + break; + default: + break; + } + for (int j = 0; j < pTable.length; j++) { + Population pop2 = numberSetCorrectly(pop, j, parId); // double firstFraction = 0.0; - switch(this.scoringMethod){ - case BDM: result += Math.log(firstFractionBDM(pop, parents, pop2)); break; - case K2: result += Math.log(firstFractionBDM(pop, parents, pop2)); break; - case BIC: result -= firstFractionBIC(pop2); break; - } + switch (this.scoringMethod) { + case BDM: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case K2: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case BIC: + result -= firstFractionBIC(pop2); + break; + } // result = result + Math.log(firstFraction); - if(pop2.size() > 0){ - for(int k=0; k<2; k++){ + if (pop2.size() > 0) { + for (int k = 0; k < 2; k++) { // double secondFraction = 0.0; - switch(this.scoringMethod){ - case BDM: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case K2: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case BIC: result += secondFractionBIC(pop2, currentNode, k, j); break; - } + switch (this.scoringMethod) { + case BDM: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case K2: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case BIC: + result += secondFractionBIC(pop2, currentNode, k, j); + break; + } // result = result + Math.log(secondFraction); - } - } - } - scoreArray[i] = result; - } - } - - public void updateScoreArray(Population pop, int i){ - //for every node - double result = 0.0; - BayNode currentNode = this.nodes[i]; - //get the parents - List parents = getParents(currentNode); - // get the parentIds sorted (for the lookup) - int[] parId = new int[0]; - if(!parents.isEmpty()){ - parId = calculateSortedParentIds(i); - } - double[] pTable = currentNode.getPTable(); - switch(this.scoringMethod){ - case BIC: result -= (Math.log(pop.size()) * pTable.length * 2)/2;break; - default: break; - } - for(int j=0; j 0){ - for(int k=0; k<2; k++){ - switch(this.scoringMethod){ - case BDM: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case K2: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case BIC: result += secondFractionBIC(pop2, currentNode, k, j); break; - } - } - } - } - scoreArray[i] = result; - } - - public double getNewScore(Population pop, int i){ - double result = 0; - for(int j=0; j parents = getParents(currentNode); - // get the parentIds sorted (for the lookup) - int[] parId = new int[0]; - if(!parents.isEmpty()){ - parId = calculateSortedParentIds(i); - } - double[] pTable = currentNode.getPTable(); - switch(this.scoringMethod){ - case BIC: result -= (Math.log(pop.size()) * pTable.length * 2)/2;break; - default: break; - } - for(int j=0; j 0){ - for(int k=0; k<2; k++){ - switch(this.scoringMethod){ - case BDM: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case K2: result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; - case BIC: result += secondFractionBIC(pop2, currentNode, k, j); break; - } - } - } - } - return result; - } - - private double secondFractionBIC(Population pop2, BayNode currentNode, int k, int j){ - double result = 0.0; - double Nijk = numberSetCorrectly(pop2, k, currentNode.getId()); - if(Nijk>0){ - result = (double)Nijk * Math.log((double) Nijk); - } - if(k==1){ - double prob = Nijk / (double) pop2.size(); - setProbability(currentNode, j, prob); - } - return result; - } - - private double firstFractionBIC(Population pop2){ - double result = 0.0; - if(pop2.size()>0){ - result = ((double) pop2.size()) * Math.log((double) pop2.size()); - } - return result; - } + } + } + } + scoreArray[i] = result; + } + } - private double secondFractionBDM(Population pop, BayNode currentNode, - List parents, int j, Population pop2, int k) { - double mXiPiXi = numberSetCorrectly(pop2, k, currentNode.getId()); - double mDashXiPiXi = getPrior(parents, currentNode, pop); - double numeratorSecondFraction = gamma(mDashXiPiXi + mXiPiXi); - double denumeratorSecondFraction = gamma(mDashXiPiXi); - double secondFraction = numeratorSecondFraction / denumeratorSecondFraction; - if(k==1){ - double prob = mXiPiXi / (double) pop2.size(); - setProbability(currentNode, j, prob); - } - return secondFraction; - } + public void updateScoreArray(Population pop, int i) { + //for every node + double result = 0.0; + BayNode currentNode = this.nodes[i]; + //get the parents + List parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if (!parents.isEmpty()) { + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch (this.scoringMethod) { + case BIC: + result -= (Math.log(pop.size()) * pTable.length * 2) / 2; + break; + default: + break; + } + for (int j = 0; j < pTable.length; j++) { + Population pop2 = numberSetCorrectly(pop, j, parId); + switch (this.scoringMethod) { + case BDM: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case K2: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case BIC: + result -= firstFractionBIC(pop2); + break; + } + if (pop2.size() > 0) { + for (int k = 0; k < 2; k++) { + switch (this.scoringMethod) { + case BDM: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case K2: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case BIC: + result += secondFractionBIC(pop2, currentNode, k, j); + break; + } + } + } + } + scoreArray[i] = result; + } + + public double getNewScore(Population pop, int i) { + double result = 0; + for (int j = 0; j < this.dimension; j++) { + if (j == i) { + result += getSingleScore(pop, i); + } else { + result += scoreArray[j]; + } + } + return result; + } + + private double getSingleScore(Population pop, int i) { + //for every node + double result = 0.0; + BayNode currentNode = this.nodes[i]; + //get the parents + List parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if (!parents.isEmpty()) { + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch (this.scoringMethod) { + case BIC: + result -= (Math.log(pop.size()) * pTable.length * 2) / 2; + break; + default: + break; + } + for (int j = 0; j < pTable.length; j++) { + Population pop2 = numberSetCorrectly(pop, j, parId); + switch (this.scoringMethod) { + case BDM: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case K2: + result += Math.log(firstFractionBDM(pop, parents, pop2)); + break; + case BIC: + result -= firstFractionBIC(pop2); + break; + } + if (pop2.size() > 0) { + for (int k = 0; k < 2; k++) { + switch (this.scoringMethod) { + case BDM: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case K2: + result += Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); + break; + case BIC: + result += secondFractionBIC(pop2, currentNode, k, j); + break; + } + } + } + } + return result; + } + + private double secondFractionBIC(Population pop2, BayNode currentNode, int k, int j) { + double result = 0.0; + double Nijk = numberSetCorrectly(pop2, k, currentNode.getId()); + if (Nijk > 0) { + result = (double) Nijk * Math.log((double) Nijk); + } + if (k == 1) { + double prob = Nijk / (double) pop2.size(); + setProbability(currentNode, j, prob); + } + return result; + } + + private double firstFractionBIC(Population pop2) { + double result = 0.0; + if (pop2.size() > 0) { + result = ((double) pop2.size()) * Math.log((double) pop2.size()); + } + return result; + } + + private double secondFractionBDM(Population pop, BayNode currentNode, + List parents, int j, Population pop2, int k) { + double mXiPiXi = numberSetCorrectly(pop2, k, currentNode.getId()); + double mDashXiPiXi = getPrior(parents, currentNode, pop); + double numeratorSecondFraction = gamma(mDashXiPiXi + mXiPiXi); + double denumeratorSecondFraction = gamma(mDashXiPiXi); + double secondFraction = numeratorSecondFraction / denumeratorSecondFraction; + if (k == 1) { + double prob = mXiPiXi / (double) pop2.size(); + setProbability(currentNode, j, prob); + } + return secondFraction; + } + + private double firstFractionBDM(Population pop, List parents, + Population pop2) { + double mPiXi = (double) pop2.size(); + double mDashPiXi = getPrior(parents, pop); + double numeratorFirstFraction = gamma(mDashPiXi); + double denominatorFirstFraction = gamma(mDashPiXi + mPiXi); + double firstFraction = numeratorFirstFraction / denominatorFirstFraction; + return firstFraction; + } - private double firstFractionBDM(Population pop, List parents, - Population pop2) { - double mPiXi = (double) pop2.size(); - double mDashPiXi = getPrior(parents, pop); - double numeratorFirstFraction = gamma(mDashPiXi); - double denominatorFirstFraction = gamma(mDashPiXi + mPiXi); - double firstFraction = numeratorFirstFraction / denominatorFirstFraction; - return firstFraction; - } - // public String getTables(){ // return this.tables; // } - + // public void setTables(String s){ // this.tables = ""; // this.tables = s; // } - - private void setProbability(BayNode n, int j, double prob){ - n.setPTable(j, Math.min(upperProbLimit, Math.max(lowerProbLimit, prob))); - } - private double numberSetCorrectly(Population pop, int k, int Id){ - double result = 0.0; - for(int i=0; iBitSet from the position offset by the - * given amount of bits. - * - * @param bitSet the BitSet to operate on - * @param offset the offset in the bit set - * @param length the length of the bit string that should represent the given value - * @param value the value to encode in the bit set - * @return the modified bit set - * @throws RuntimeException if length is greater than the amount of bits in an - * integer value - * @throws RuntimeException if value is greather than the value encodeable by the - * given amount of bits or if value == Integer.MIN_VALUE (no absolute value awailable as - * int) - */ - public static BitSet intToBitSet(BitSet bitSet, int offset, int length, int value) - { - // checking the bit length - if (length > Integer.SIZE) { - throw new RuntimeException("You can not set a higher length than " + Integer.SIZE - + " bits."); - } - length += 1; - // checking whether the value fits into the bit string of length - 1 - int absValue = Math.abs(value); - if (absValue > Math.pow(2.0, length - 1 - 1) * 2 - 1 || value == Integer.MIN_VALUE) { - throw new RuntimeException("The value of " + value - + " does not fit into a bit string of " + (length - 1) + " bits."); + result.add(indy); } + } + return result; + } - // setting all bits to zero - bitSet.clear(offset, offset + length - 1); - - // setting up the number in reverse order - int mask = 1; - for (int i = 0; i < length; ++i, mask <<= 1) { - if ((mask & absValue) > 0) { - bitSet.set(offset + i); - } + /** + * Encodes the given integer value in the BitSet from the position offset by the + * given amount of bits. + * + * @param bitSet the BitSet to operate on + * @param offset the offset in the bit set + * @param length the length of the bit string that should represent the given value + * @param value the value to encode in the bit set + * @return the modified bit set + * @throws RuntimeException if length is greater than the amount of bits in an + * integer value + * @throws RuntimeException if value is greather than the value encodeable by the + * given amount of bits or if value == Integer.MIN_VALUE (no absolute value awailable as + * int) + */ + public static BitSet intToBitSet(BitSet bitSet, int offset, int length, int value) { + // checking the bit length + if (length > Integer.SIZE) { + throw new RuntimeException("You can not set a higher length than " + Integer.SIZE + + " bits."); + } + length += 1; + // checking whether the value fits into the bit string of length - 1 + int absValue = Math.abs(value); + if (absValue > Math.pow(2.0, length - 1 - 1) * 2 - 1 || value == Integer.MIN_VALUE) { + throw new RuntimeException("The value of " + value + + " does not fit into a bit string of " + (length - 1) + " bits."); } - // setting up the sign - if (value < 0) { - bitSet.set(offset + length - 1); + // setting all bits to zero + bitSet.clear(offset, offset + length - 1); + + // setting up the number in reverse order + int mask = 1; + for (int i = 0; i < length; ++i, mask <<= 1) { + if ((mask & absValue) > 0) { + bitSet.set(offset + i); } + } - return bitSet; - } + // setting up the sign + if (value < 0) { + bitSet.set(offset + length - 1); + } - /** - * is the BitSet of the individual set correctly corresponding to the binary String and the parId - * @param ids the Ids of the parents sorted - * @param data the data of the individual to be checked - * @param j how the Bits have to be set (as Integer) - * @return is the data set correctly - */ - private boolean isSetCorrectly(int[] ids, BitSet data, int j) { - int value = 0; + return bitSet; + } + + /** + * is the BitSet of the individual set correctly corresponding to the binary String and the parId + * + * @param ids the Ids of the parents sorted + * @param data the data of the individual to be checked + * @param j how the Bits have to be set (as Integer) + * @return is the data set correctly + */ + private boolean isSetCorrectly(int[] ids, BitSet data, int j) { + int value = 0; // BitSet toTest = new BitSet(length); - for(int i=0; i\n"; - result += "\n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - for(int i=0; i pair = generateTable(i); - Integer length = pair.getHead(); - String table = pair.getTail(); - int x = 40+100*(i % 20); - int y = (int) (40+100*Math.floor(((double)i) / 20)); - Double height = 40+11*Math.pow(2, length-1); - Double width = (double) (40+10*length); - result = result + " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result = result + " \n"; - result += " \n"; - result += " \n"; - result = result + " " + i + table + "\n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - } - int cnt = 0; - for(int i=0; i\n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - cnt++; - } - } - } - result += " \n"; - result += " \n"; - result += " \n"; - result += " \n"; - result += "\n"; - return result; - } + for (int i = 0; i < ids.length; i++) { + if (data.get(ids[i])) { + value += Math.pow(2, ids.length - i - 1); + } + } + return value == j; + } - private Pair generateTable(int i) { - String result = ""; - double [] pTable = nodes[i].getPTable(); - int length = Integer.toBinaryString(pTable.length).length(); - for(int j=0; j p = new Pair(); - p.setHead(length); - p.setTail(result); - return p; - } + public void print() { + for (int i = 0; i < this.dimension; i++) { + for (int j = 0; j < this.dimension; j++) { + if (this.network[i][j]) { + System.out.print("1"); + } else { + System.out.print("0"); + } + } + System.out.println(); + } + for (int i = 0; i < this.dimension; i++) { + System.out.println(BeanInspector.toString(nodes[i].getPTable())); + } + } - /** - * has the network already an edge from node i to node j - * @param i the node from which the edge originates - * @param j the node to which the edge points - * @return is the edge already there - */ - public boolean hasEdge(int i, int j){ - return this.network[i][j]; - } + public String generateYFilesCode() { + String result = "\n"; + result += "\n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + for (int i = 0; i < this.nodes.length; i++) { + Pair pair = generateTable(i); + Integer length = pair.getHead(); + String table = pair.getTail(); + int x = 40 + 100 * (i % 20); + int y = (int) (40 + 100 * Math.floor(((double) i) / 20)); + Double height = 40 + 11 * Math.pow(2, length - 1); + Double width = (double) (40 + 10 * length); + result = result + " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result = result + " \n"; + result += " \n"; + result += " \n"; + result = result + " " + i + table + "\n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + } + int cnt = 0; + for (int i = 0; i < this.network.length; i++) { + for (int j = 0; j < this.network[i].length; j++) { + if (this.network[i][j]) { + result = result + " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + cnt++; + } + } + } + result += " \n"; + result += " \n"; + result += " \n"; + result += " \n"; + result += "\n"; + return result; + } - public static void main(String[] args){ + private Pair generateTable(int i) { + String result = ""; + double[] pTable = nodes[i].getPTable(); + int length = Integer.toBinaryString(pTable.length).length(); + for (int j = 0; j < pTable.length; j++) { + result += "\n"; + String line = Integer.toBinaryString(j); + while (line.length() < length - 1) { + line = "0" + line; + } + line = line + ": " + pTable[j]; + result += line; + } + Pair p = new Pair(); + p.setHead(length); + p.setTail(result); + return p; + } + + /** + * has the network already an edge from node i to node j + * + * @param i the node from which the edge originates + * @param j the node to which the edge points + * @return is the edge already there + */ + public boolean hasEdge(int i, int j) { + return this.network[i][j]; + } + + public static void main(String[] args) { // BayNet b = new BayNet(3, 0.9, 0.1); //// b.addEdge(0, 2); // b.addEdge(1, 2); @@ -1048,32 +1126,32 @@ public class BayNet { // System.out.println("-----"); // System.out.println(b.bayesianDirichletMetric(pop)); // b.print(); - double val = SpecialFunction.gamma(26); - double val2 = SpecialFunction.gamma(51); - double val3 = (SpecialFunction.gamma(12+12.5))/SpecialFunction.gamma(12.5); - double val4 = (SpecialFunction.gamma(13+12.5))/SpecialFunction.gamma(12.5); - double erg = val/val2; - erg = erg * val3 * val4; - System.out.println(erg); - } - - public void setScoringMethod(BOAScoringMethods method){ - this.scoringMethod = method; - } - - public BOAScoringMethods getScoringMethod(){ - return this.scoringMethod; - } + double val = SpecialFunction.gamma(26); + double val2 = SpecialFunction.gamma(51); + double val3 = (SpecialFunction.gamma(12 + 12.5)) / SpecialFunction.gamma(12.5); + double val4 = (SpecialFunction.gamma(13 + 12.5)) / SpecialFunction.gamma(12.5); + double erg = val / val2; + erg = erg * val3 * val4; + System.out.println(erg); + } - public int[][] adaptEdgeRate(int[][] edgeRate) { - for(int i=0; i parents = new LinkedList(); - private List children = new LinkedList(); - - public BayNode(int id){ - this.id = id; - } - - public BayNode(BayNode b){ - this.id = b.id; - this.numberOfParents = b.numberOfParents; - this.pTable = b.pTable.clone(); - this.parents = new LinkedList(); - this.children = new LinkedList(); - for(int i: b.parents){ - this.parents.add(i); - } - for(int i: b.children){ - this.children.add(i); - } - this.calculated = b.calculated; - } - + private int id; + private int numberOfParents = 0; + private double[] pTable = {0.5}; + private boolean calculated = false; + private List parents = new LinkedList(); + private List children = new LinkedList(); + + public BayNode(int id) { + this.id = id; + } + + public BayNode(BayNode b) { + this.id = b.id; + this.numberOfParents = b.numberOfParents; + this.pTable = b.pTable.clone(); + this.parents = new LinkedList(); + this.children = new LinkedList(); + for (int i : b.parents) { + this.parents.add(i); + } + for (int i : b.children) { + this.children.add(i); + } + this.calculated = b.calculated; + } + @Override - public Object clone(){ - return new BayNode(this); - } - - public double getProbability(int i){ - return pTable[i]; - } - - public void generateNewPTable(){ - this.pTable = new double[(int) Math.pow(2, this.numberOfParents)]; - for(int i=0; i getParents(){ - return this.parents; - } - - public void addParent(Integer b){ - if(!this.parents.contains(b)){ - this.parents.add(b); - } - } - - public void removeParent(Integer b){ - this.parents.remove(b); - } - - public List getChildren(){ - return this.children; - } - - public void addChild(Integer b){ - if(!this.children.contains(b)){ - this.children.add(b); - } - } - public void removeChild(Integer b){ - this.children.remove(b); - } - - public void setPTable(double[] table){ - this.pTable = table; - } - - public void setPTable(int i, double v){ - this.pTable[i] = v; - } - - public void incrNumberOfParents(){ - this.numberOfParents++; - } - - public void decrNumberOfParents(){ - this.numberOfParents--; - } - - public int getNumberOfParents(){ - return this.numberOfParents; - } - - public int getId(){ - return this.id; - } - - public double[] getPTable(){ - return this.pTable; - } - - public boolean getCalculated(){ - return this.calculated; - } - - public void setCalculated(boolean b){ - this.calculated = b; - } + public Object clone() { + return new BayNode(this); + } + + public double getProbability(int i) { + return pTable[i]; + } + + public void generateNewPTable() { + this.pTable = new double[(int) Math.pow(2, this.numberOfParents)]; + for (int i = 0; i < this.pTable.length; i++) { + this.pTable[i] = 0.50001; + } + } + + public List getParents() { + return this.parents; + } + + public void addParent(Integer b) { + if (!this.parents.contains(b)) { + this.parents.add(b); + } + } + + public void removeParent(Integer b) { + this.parents.remove(b); + } + + public List getChildren() { + return this.children; + } + + public void addChild(Integer b) { + if (!this.children.contains(b)) { + this.children.add(b); + } + } + + public void removeChild(Integer b) { + this.children.remove(b); + } + + public void setPTable(double[] table) { + this.pTable = table; + } + + public void setPTable(int i, double v) { + this.pTable[i] = v; + } + + public void incrNumberOfParents() { + this.numberOfParents++; + } + + public void decrNumberOfParents() { + this.numberOfParents--; + } + + public int getNumberOfParents() { + return this.numberOfParents; + } + + public int getId() { + return this.id; + } + + public double[] getPTable() { + return this.pTable; + } + + public boolean getCalculated() { + return this.calculated; + } + + public void setCalculated(boolean b) { + this.calculated = b; + } } \ No newline at end of file diff --git a/src/eva2/tools/math/Jama/CholeskyDecomposition.java b/src/eva2/tools/math/Jama/CholeskyDecomposition.java index b2171a1a..fd0b2db6 100644 --- a/src/eva2/tools/math/Jama/CholeskyDecomposition.java +++ b/src/eva2/tools/math/Jama/CholeskyDecomposition.java @@ -1,14 +1,15 @@ package eva2.tools.math.Jama; - /** Cholesky Decomposition. -

- For a symmetric, positive definite matrix A, the Cholesky decomposition - is an lower triangular matrix L so that A = L*L'. -

- If the matrix is not symmetric or positive definite, the constructor - returns a partial decomposition and sets an internal flag that may - be queried by the isSPD() method. - */ +/** + * Cholesky Decomposition. + *

+ * For a symmetric, positive definite matrix A, the Cholesky decomposition + * is an lower triangular matrix L so that A = L*L'. + *

+ * If the matrix is not symmetric or positive definite, the constructor + * returns a partial decomposition and sets an internal flag that may + * be queried by the isSPD() method. + */ public class CholeskyDecomposition implements java.io.Serializable { @@ -16,59 +17,66 @@ public class CholeskyDecomposition implements java.io.Serializable { Class variables * ------------------------ */ - /** Array for internal storage of decomposition. - @serial internal array storage. - */ - private double[][] L; + /** + * Array for internal storage of decomposition. + * + * @serial internal array storage. + */ + private double[][] L; - /** Row and column dimension (square matrix). - @serial matrix dimension. - */ - private int n; + /** + * Row and column dimension (square matrix). + * + * @serial matrix dimension. + */ + private int n; - /** Symmetric and positive definite flag. - @serial is symmetric and positive definite flag. - */ - private boolean isspd; + /** + * Symmetric and positive definite flag. + * + * @serial is symmetric and positive definite flag. + */ + private boolean isspd; /* ------------------------ Constructor * ------------------------ */ - /** Cholesky algorithm for symmetric and positive definite matrix. - @param A Square, symmetric matrix. - @return Structure to access L and isspd flag. - */ + /** + * Cholesky algorithm for symmetric and positive definite matrix. + * + * @param A Square, symmetric matrix. + * @return Structure to access L and isspd flag. + */ - public CholeskyDecomposition (Matrix Arg) { - // Initialize. - double[][] A = Arg.getArray(); - n = Arg.getRowDimension(); - L = new double[n][n]; - isspd = (Arg.getColumnDimension() == n); - // Main loop. - for (int j = 0; j < n; j++) { - double[] Lrowj = L[j]; - double d = 0.0; - for (int k = 0; k < j; k++) { - double[] Lrowk = L[k]; - double s = 0.0; - for (int i = 0; i < k; i++) { - s += Lrowk[i]*Lrowj[i]; - } - Lrowj[k] = s = (A[j][k] - s)/L[k][k]; - d += s*s; + public CholeskyDecomposition(Matrix Arg) { + // Initialize. + double[][] A = Arg.getArray(); + n = Arg.getRowDimension(); + L = new double[n][n]; + isspd = (Arg.getColumnDimension() == n); + // Main loop. + for (int j = 0; j < n; j++) { + double[] Lrowj = L[j]; + double d = 0.0; + for (int k = 0; k < j; k++) { + double[] Lrowk = L[k]; + double s = 0.0; + for (int i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; + } + Lrowj[k] = s = (A[j][k] - s) / L[k][k]; + d += s * s; isspd &= (A[k][j] == A[j][k]); - } - d = A[j][j] - d; + } + d = A[j][j] - d; isspd &= (d > 0.0); - L[j][j] = Math.sqrt(Math.max(d,0.0)); - for (int k = j+1; k < n; k++) { - L[j][k] = 0.0; - } - } - } - + L[j][j] = Math.sqrt(Math.max(d, 0.0)); + for (int k = j + 1; k < n; k++) { + L[j][k] = 0.0; + } + } + } // \** Right Triangular Cholesky Decomposition. @@ -82,101 +90,106 @@ public class CholeskyDecomposition implements java.io.Serializable { // *\ - private transient double[][] R; + private transient double[][] R; - - public CholeskyDecomposition (Matrix Arg, int rightflag) { - // Initialize. - double[][] A = Arg.getArray(); - n = Arg.getColumnDimension(); - R = new double[n][n]; - isspd = (Arg.getColumnDimension() == n); - // Main loop. - for (int j = 0; j < n; j++) { - double d = 0.0; - for (int k = 0; k < j; k++) { - double s = A[k][j]; - for (int i = 0; i < k; i++) { - s -= R[i][k]*R[i][j]; - } - R[k][j] = s /= R[k][k]; - d += s*s; + public CholeskyDecomposition(Matrix Arg, int rightflag) { + // Initialize. + double[][] A = Arg.getArray(); + n = Arg.getColumnDimension(); + R = new double[n][n]; + isspd = (Arg.getColumnDimension() == n); + // Main loop. + for (int j = 0; j < n; j++) { + double d = 0.0; + for (int k = 0; k < j; k++) { + double s = A[k][j]; + for (int i = 0; i < k; i++) { + s -= R[i][k] * R[i][j]; + } + R[k][j] = s /= R[k][k]; + d += s * s; isspd &= (A[k][j] == A[j][k]); - } - d = A[j][j] - d; + } + d = A[j][j] - d; isspd &= (d > 0.0); - R[j][j] = Math.sqrt(Math.max(d,0.0)); - for (int k = j+1; k < n; k++) { - R[k][j] = 0.0; - } - } - } - - - public Matrix getR () { - return new Matrix(R,n,n); - } - - - /** Is the matrix symmetric and positive definite? - @return true if A is symmetric and positive definite. - */ - - public boolean isSPD () { - return isspd; - } - - /** Return triangular factor. - @return L - */ - - public Matrix getL () { - return new Matrix(L,n,n); - } - - /** Solve A*X = B - @param B A Matrix with as many rows as A and any number of columns. - @return X so that L*L'*X = B - @exception IllegalArgumentException Matrix row dimensions must agree. - @exception RuntimeException Matrix is not symmetric positive definite. - */ - - public Matrix solve (Matrix B) { - if (B.getRowDimension() != n) { - throw new IllegalArgumentException("Matrix row dimensions must agree."); - } - if (!isspd) { - throw new RuntimeException("Matrix is not symmetric positive definite."); - } - - // Copy right hand side. - double[][] X = B.getArrayCopy(); - int nx = B.getColumnDimension(); - - // Solve L*Y = B; - for (int k = 0; k < n; k++) { - for (int i = k+1; i < n; i++) { - for (int j = 0; j < nx; j++) { - X[i][j] -= X[k][j]*L[i][k]; + R[j][j] = Math.sqrt(Math.max(d, 0.0)); + for (int k = j + 1; k < n; k++) { + R[k][j] = 0.0; } - } - for (int j = 0; j < nx; j++) { - X[k][j] /= L[k][k]; - } - } + } + } - // Solve L'*X = Y; - for (int k = n-1; k >= 0; k--) { - for (int j = 0; j < nx; j++) { - X[k][j] /= L[k][k]; - } - for (int i = 0; i < k; i++) { - for (int j = 0; j < nx; j++) { - X[i][j] -= X[k][j]*L[k][i]; + + public Matrix getR() { + return new Matrix(R, n, n); + } + + + /** + * Is the matrix symmetric and positive definite? + * + * @return true if A is symmetric and positive definite. + */ + + public boolean isSPD() { + return isspd; + } + + /** + * Return triangular factor. + * + * @return L + */ + + public Matrix getL() { + return new Matrix(L, n, n); + } + + /** + * Solve A*X = B + * + * @param B A Matrix with as many rows as A and any number of columns. + * @return X so that L*L'*X = B + * @throws IllegalArgumentException Matrix row dimensions must agree. + * @throws RuntimeException Matrix is not symmetric positive definite. + */ + + public Matrix solve(Matrix B) { + if (B.getRowDimension() != n) { + throw new IllegalArgumentException("Matrix row dimensions must agree."); + } + if (!isspd) { + throw new RuntimeException("Matrix is not symmetric positive definite."); + } + + // Copy right hand side. + double[][] X = B.getArrayCopy(); + int nx = B.getColumnDimension(); + + // Solve L*Y = B; + for (int k = 0; k < n; k++) { + for (int i = k + 1; i < n; i++) { + for (int j = 0; j < nx; j++) { + X[i][j] -= X[k][j] * L[i][k]; + } } - } - } - return new Matrix(X,n,nx); - } + for (int j = 0; j < nx; j++) { + X[k][j] /= L[k][k]; + } + } + + // Solve L'*X = Y; + for (int k = n - 1; k >= 0; k--) { + for (int j = 0; j < nx; j++) { + X[k][j] /= L[k][k]; + } + for (int i = 0; i < k; i++) { + for (int j = 0; j < nx; j++) { + X[i][j] -= X[k][j] * L[k][i]; + } + } + } + return new Matrix(X, n, nx); + } } diff --git a/src/eva2/tools/math/Jama/EigenvalueDecomposition.java b/src/eva2/tools/math/Jama/EigenvalueDecomposition.java index c150c787..0c7b31f4 100644 --- a/src/eva2/tools/math/Jama/EigenvalueDecomposition.java +++ b/src/eva2/tools/math/Jama/EigenvalueDecomposition.java @@ -1,22 +1,24 @@ package eva2.tools.math.Jama; + import eva2.tools.math.Jama.util.Maths; -/** Eigenvalues and eigenvectors of a real matrix. -

- If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is - diagonal and the eigenvector matrix V is orthogonal. - I.e. A = V.times(D.times(V.transpose())) and - V.times(V.transpose()) equals the identiCty matrix. -

- If A is not symmetric, then the eigenvalue matrix D is block diagonal - with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, - lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The - columns of V represent the eigenvectors in the sense that A*V = V*D, - i.e. A.times(V) equals V.times(D). The matrix V may be badly - conditioned, or even singular, so the validity of the equation - A = V*D*inverse(V) depends upon V.cond(). -**/ +/** + * Eigenvalues and eigenvectors of a real matrix. + *

+ * If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is + * diagonal and the eigenvector matrix V is orthogonal. + * I.e. A = V.times(D.times(V.transpose())) and + * V.times(V.transpose()) equals the identiCty matrix. + *

+ * If A is not symmetric, then the eigenvalue matrix D is block diagonal + * with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, + * lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The + * columns of V represent the eigenvectors in the sense that A*V = V*D, + * i.e. A.times(V) equals V.times(D). The matrix V may be badly + * conditioned, or even singular, so the validity of the equation + * A = V*D*inverse(V) depends upon V.cond(). + */ public class EigenvalueDecomposition implements java.io.Serializable { @@ -24,933 +26,956 @@ public class EigenvalueDecomposition implements java.io.Serializable { Class variables * ------------------------ */ - /** Row and column dimension (square matrix). - @serial matrix dimension. - */ - private int n; + /** + * Row and column dimension (square matrix). + * + * @serial matrix dimension. + */ + private int n; - /** Symmetry flag. - @serial internal symmetry flag. - */ - private boolean issymmetric; + /** + * Symmetry flag. + * + * @serial internal symmetry flag. + */ + private boolean issymmetric; - /** Arrays for internal storage of eigenvalues. - @serial internal storage of eigenvalues. - */ - private double[] d, e; + /** + * Arrays for internal storage of eigenvalues. + * + * @serial internal storage of eigenvalues. + */ + private double[] d, e; - /** Array for internal storage of eigenvectors. - @serial internal storage of eigenvectors. - */ - private double[][] V; + /** + * Array for internal storage of eigenvectors. + * + * @serial internal storage of eigenvectors. + */ + private double[][] V; - /** Array for internal storage of nonsymmetric Hessenberg form. - @serial internal storage of nonsymmetric Hessenberg form. - */ - private double[][] H; + /** + * Array for internal storage of nonsymmetric Hessenberg form. + * + * @serial internal storage of nonsymmetric Hessenberg form. + */ + private double[][] H; - /** Working storage for nonsymmetric algorithm. - @serial working storage for nonsymmetric algorithm. - */ - private double[] ort; + /** + * Working storage for nonsymmetric algorithm. + * + * @serial working storage for nonsymmetric algorithm. + */ + private double[] ort; /* ------------------------ Private Methods * ------------------------ */ - // Symmetric Householder reduction to tridiagonal form. + // Symmetric Householder reduction to tridiagonal form. - private void tred2 () { + private void tred2() { - // This is derived from the Algol procedures tred2 by - // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for - // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutine in EISPACK. + // This is derived from the Algol procedures tred2 by + // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for + // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding + // Fortran subroutine in EISPACK. - for (int j = 0; j < n; j++) { - d[j] = V[n-1][j]; - } + for (int j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + } - // Householder reduction to tridiagonal form. + // Householder reduction to tridiagonal form. - for (int i = n-1; i > 0; i--) { + for (int i = n - 1; i > 0; i--) { - // Scale to avoid under/overflow. - - double scale = 0.0; - double h = 0.0; - for (int k = 0; k < i; k++) { - scale += Math.abs(d[k]); - } - if (scale == 0.0) { - e[i] = d[i-1]; - for (int j = 0; j < i; j++) { - d[j] = V[i-1][j]; - V[i][j] = 0.0; - V[j][i] = 0.0; - } - } else { - - // Generate Householder vector. + // Scale to avoid under/overflow. + double scale = 0.0; + double h = 0.0; for (int k = 0; k < i; k++) { - d[k] /= scale; - h += d[k] * d[k]; + scale += Math.abs(d[k]); } - double f = d[i-1]; - double g = Math.sqrt(h); - if (f > 0) { - g = -g; - } - e[i] = scale * g; + if (scale == 0.0) { + e[i] = d[i - 1]; + for (int j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0.0; + V[j][i] = 0.0; + } + } else { + + // Generate Householder vector. + + for (int k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } + double f = d[i - 1]; + double g = Math.sqrt(h); + if (f > 0) { + g = -g; + } + e[i] = scale * g; h -= f * g; - d[i-1] = f - g; - for (int j = 0; j < i; j++) { - e[j] = 0.0; - } + d[i - 1] = f - g; + for (int j = 0; j < i; j++) { + e[j] = 0.0; + } - // Apply similarity transformation to remaining columns. + // Apply similarity transformation to remaining columns. - for (int j = 0; j < i; j++) { - f = d[j]; - V[j][i] = f; - g = e[j] + V[j][j] * f; - for (int k = j+1; k <= i-1; k++) { - g += V[k][j] * d[k]; - e[k] += V[k][j] * f; - } - e[j] = g; + for (int j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (int k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + e[j] = g; + } + f = 0.0; + for (int j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } + double hh = f / (h + h); + for (int j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } + for (int j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (int k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0.0; + } } - f = 0.0; - for (int j = 0; j < i; j++) { - e[j] /= h; - f += e[j] * d[j]; - } - double hh = f / (h + h); - for (int j = 0; j < i; j++) { - e[j] -= hh * d[j]; - } - for (int j = 0; j < i; j++) { - f = d[j]; - g = e[j]; - for (int k = j; k <= i-1; k++) { - V[k][j] -= (f * e[k] + g * d[k]); - } - d[j] = V[i-1][j]; - V[i][j] = 0.0; - } - } - d[i] = h; - } + d[i] = h; + } - // Accumulate transformations. + // Accumulate transformations. - for (int i = 0; i < n-1; i++) { - V[n-1][i] = V[i][i]; - V[i][i] = 1.0; - double h = d[i+1]; - if (h != 0.0) { + for (int i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1.0; + double h = d[i + 1]; + if (h != 0.0) { + for (int k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; + } + for (int j = 0; j <= i; j++) { + double g = 0.0; + for (int k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + for (int k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } + } + } for (int k = 0; k <= i; k++) { - d[k] = V[k][i+1] / h; + V[k][i + 1] = 0.0; } - for (int j = 0; j <= i; j++) { - double g = 0.0; - for (int k = 0; k <= i; k++) { - g += V[k][i+1] * V[k][j]; - } - for (int k = 0; k <= i; k++) { - V[k][j] -= g * d[k]; - } + } + for (int j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0.0; + } + V[n - 1][n - 1] = 1.0; + e[0] = 0.0; + } + + // Symmetric tridiagonal QL algorithm. + + private void tql2() { + + // This is derived from the Algol procedures tql2, by + // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for + // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding + // Fortran subroutine in EISPACK. + + for (int i = 1; i < n; i++) { + e[i - 1] = e[i]; + } + e[n - 1] = 0.0; + + double f = 0.0; + double tst1 = 0.0; + double eps = Math.pow(2.0, -52.0); + for (int l = 0; l < n; l++) { + + // Find small subdiagonal element + + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + int m = l; + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; + } + m++; } - } - for (int k = 0; k <= i; k++) { - V[k][i+1] = 0.0; - } - } - for (int j = 0; j < n; j++) { - d[j] = V[n-1][j]; - V[n-1][j] = 0.0; - } - V[n-1][n-1] = 1.0; - e[0] = 0.0; - } - // Symmetric tridiagonal QL algorithm. + // If m == l, d[l] is an eigenvalue, + // otherwise, iterate. - private void tql2 () { - - // This is derived from the Algol procedures tql2, by - // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for - // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutine in EISPACK. - - for (int i = 1; i < n; i++) { - e[i-1] = e[i]; - } - e[n-1] = 0.0; - - double f = 0.0; - double tst1 = 0.0; - double eps = Math.pow(2.0,-52.0); - for (int l = 0; l < n; l++) { - - // Find small subdiagonal element - - tst1 = Math.max(tst1,Math.abs(d[l]) + Math.abs(e[l])); - int m = l; - while (m < n) { - if (Math.abs(e[m]) <= eps*tst1) { - break; - } - m++; - } - - // If m == l, d[l] is an eigenvalue, - // otherwise, iterate. - - if (m > l) { - int iter = 0; - do { + if (m > l) { + int iter = 0; + do { iter += 1; // (Could check iteration count here.) - // Compute implicit shift + // Compute implicit shift - double g = d[l]; - double p = (d[l+1] - g) / (2.0 * e[l]); - double r = Maths.hypot(p,1.0); - if (p < 0) { - r = -r; - } - d[l] = e[l] / (p + r); - d[l+1] = e[l] * (p + r); - double dl1 = d[l+1]; - double h = g - d[l]; - for (int i = l+2; i < n; i++) { - d[i] -= h; - } + double g = d[l]; + double p = (d[l + 1] - g) / (2.0 * e[l]); + double r = Maths.hypot(p, 1.0); + if (p < 0) { + r = -r; + } + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + double dl1 = d[l + 1]; + double h = g - d[l]; + for (int i = l + 2; i < n; i++) { + d[i] -= h; + } f += h; - // Implicit QL transformation. + // Implicit QL transformation. - p = d[m]; - double c = 1.0; - double c2 = c; - double c3 = c; - double el1 = e[l+1]; - double s = 0.0; - double s2 = 0.0; - for (int i = m-1; i >= l; i--) { - c3 = c2; - c2 = c; - s2 = s; - g = c * e[i]; - h = c * p; - r = Maths.hypot(p,e[i]); - e[i+1] = s * r; - s = e[i] / r; - c = p / r; - p = c * d[i] - s * g; - d[i+1] = h + s * (c * g + s * d[i]); + p = d[m]; + double c = 1.0; + double c2 = c; + double c3 = c; + double el1 = e[l + 1]; + double s = 0.0; + double s2 = 0.0; + for (int i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = Maths.hypot(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); - // Accumulate transformation. + // Accumulate transformation. - for (int k = 0; k < n; k++) { - h = V[k][i+1]; - V[k][i+1] = s * V[k][i] + c * h; - V[k][i] = c * V[k][i] - s * h; - } - } - p = -s * s2 * c3 * el1 * e[l] / dl1; - e[l] = s * p; - d[l] = c * p; + for (int k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; + } + } + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; - // Check for convergence. + // Check for convergence. - } while (Math.abs(e[l]) > eps*tst1); - } + } while (Math.abs(e[l]) > eps * tst1); + } d[l] += f; - e[l] = 0.0; - } + e[l] = 0.0; + } - // Sort eigenvalues and corresponding vectors. + // Sort eigenvalues and corresponding vectors. - for (int i = 0; i < n-1; i++) { - int k = i; - double p = d[i]; - for (int j = i+1; j < n; j++) { - if (d[j] < p) { - k = j; - p = d[j]; + for (int i = 0; i < n - 1; i++) { + int k = i; + double p = d[i]; + for (int j = i + 1; j < n; j++) { + if (d[j] < p) { + k = j; + p = d[j]; + } } - } - if (k != i) { - d[k] = d[i]; - d[i] = p; - for (int j = 0; j < n; j++) { - p = V[j][i]; - V[j][i] = V[j][k]; - V[j][k] = p; + if (k != i) { + d[k] = d[i]; + d[i] = p; + for (int j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } } - } - } - } + } + } - // Nonsymmetric reduction to Hessenberg form. + // Nonsymmetric reduction to Hessenberg form. - private void orthes () { + private void orthes() { - // This is derived from the Algol procedures orthes and ortran, - // by Martin and Wilkinson, Handbook for Auto. Comp., - // Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutines in EISPACK. + // This is derived from the Algol procedures orthes and ortran, + // by Martin and Wilkinson, Handbook for Auto. Comp., + // Vol.ii-Linear Algebra, and the corresponding + // Fortran subroutines in EISPACK. - int low = 0; - int high = n-1; + int low = 0; + int high = n - 1; - for (int m = low+1; m <= high-1; m++) { + for (int m = low + 1; m <= high - 1; m++) { - // Scale column. + // Scale column. - double scale = 0.0; - for (int i = m; i <= high; i++) { - scale += Math.abs(H[i][m-1]); - } - if (scale != 0.0) { - - // Compute Householder transformation. - - double h = 0.0; - for (int i = high; i >= m; i--) { - ort[i] = H[i][m-1]/scale; - h += ort[i] * ort[i]; - } - double g = Math.sqrt(h); - if (ort[m] > 0) { - g = -g; + double scale = 0.0; + for (int i = m; i <= high; i++) { + scale += Math.abs(H[i][m - 1]); } + if (scale != 0.0) { + + // Compute Householder transformation. + + double h = 0.0; + for (int i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } + double g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } h -= ort[m] * g; ort[m] -= g; - // Apply Householder similarity transformation - // H = (I-u*u'/h)*H*(I-u*u')/h) + // Apply Householder similarity transformation + // H = (I-u*u'/h)*H*(I-u*u')/h) - for (int j = m; j < n; j++) { - double f = 0.0; - for (int i = high; i >= m; i--) { - f += ort[i]*H[i][j]; - } + for (int j = m; j < n; j++) { + double f = 0.0; + for (int i = high; i >= m; i--) { + f += ort[i] * H[i][j]; + } f /= h; - for (int i = m; i <= high; i++) { - H[i][j] -= f*ort[i]; - } - } + for (int i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; + } + } - for (int i = 0; i <= high; i++) { - double f = 0.0; - for (int j = high; j >= m; j--) { - f += ort[j]*H[i][j]; - } + for (int i = 0; i <= high; i++) { + double f = 0.0; + for (int j = high; j >= m; j--) { + f += ort[j] * H[i][j]; + } f /= h; - for (int j = m; j <= high; j++) { - H[i][j] -= f*ort[j]; - } + for (int j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; + } + } + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; } - ort[m] = scale*ort[m]; - H[m][m-1] = scale*g; - } - } + } - // Accumulate transformations (Algol's ortran). + // Accumulate transformations (Algol's ortran). - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - V[i][j] = (i == j ? 1.0 : 0.0); - } - } - - for (int m = high-1; m >= low+1; m--) { - if (H[m][m-1] != 0.0) { - for (int i = m+1; i <= high; i++) { - ort[i] = H[i][m-1]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + V[i][j] = (i == j ? 1.0 : 0.0); } - for (int j = m; j <= high; j++) { - double g = 0.0; - for (int i = m; i <= high; i++) { - g += ort[i] * V[i][j]; - } - // Double division avoids possible underflow - g = (g / ort[m]) / H[m][m-1]; - for (int i = m; i <= high; i++) { - V[i][j] += g * ort[i]; - } + } + + for (int m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] != 0.0) { + for (int i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; + } + for (int j = m; j <= high; j++) { + double g = 0.0; + for (int i = m; i <= high; i++) { + g += ort[i] * V[i][j]; + } + // Double division avoids possible underflow + g = (g / ort[m]) / H[m][m - 1]; + for (int i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } + } } - } - } - } + } + } - // Complex scalar division. + // Complex scalar division. - private transient double cdivr, cdivi; - private void cdiv(double xr, double xi, double yr, double yi) { - double r,d; - if (Math.abs(yr) > Math.abs(yi)) { - r = yi/yr; - d = yr + r*yi; - cdivr = (xr + r*xi)/d; - cdivi = (xi - r*xr)/d; - } else { - r = yr/yi; - d = yi + r*yr; - cdivr = (r*xr + xi)/d; - cdivi = (r*xi - xr)/d; - } - } + private transient double cdivr, cdivi; + + private void cdiv(double xr, double xi, double yr, double yi) { + double r, d; + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + cdivr = (xr + r * xi) / d; + cdivi = (xi - r * xr) / d; + } else { + r = yr / yi; + d = yi + r * yr; + cdivr = (r * xr + xi) / d; + cdivi = (r * xi - xr) / d; + } + } - // Nonsymmetric reduction from Hessenberg to real Schur form. + // Nonsymmetric reduction from Hessenberg to real Schur form. - private void hqr2 () { + private void hqr2() { - // This is derived from the Algol procedure hqr2, - // by Martin and Wilkinson, Handbook for Auto. Comp., - // Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutine in EISPACK. + // This is derived from the Algol procedure hqr2, + // by Martin and Wilkinson, Handbook for Auto. Comp., + // Vol.ii-Linear Algebra, and the corresponding + // Fortran subroutine in EISPACK. - // Initialize + // Initialize - int nn = this.n; - int n = nn-1; - int low = 0; - int high = nn-1; - double eps = Math.pow(2.0,-52.0); - double exshift = 0.0; - double p=0,q=0,r=0,s=0,z=0,t,w,x,y; + int nn = this.n; + int n = nn - 1; + int low = 0; + int high = nn - 1; + double eps = Math.pow(2.0, -52.0); + double exshift = 0.0; + double p = 0, q = 0, r = 0, s = 0, z = 0, t, w, x, y; - // Store roots isolated by balanc and compute matrix norm + // Store roots isolated by balanc and compute matrix norm - double norm = 0.0; - for (int i = 0; i < nn; i++) { - if (i < low | i > high) { - d[i] = H[i][i]; - e[i] = 0.0; - } - for (int j = Math.max(i-1,0); j < nn; j++) { + double norm = 0.0; + for (int i = 0; i < nn; i++) { + if (i < low | i > high) { + d[i] = H[i][i]; + e[i] = 0.0; + } + for (int j = Math.max(i - 1, 0); j < nn; j++) { norm += Math.abs(H[i][j]); - } - } - - // Outer loop over eigenvalue index - - int iter = 0; - while (n >= low) { - - // Look for single small sub-diagonal element - - int l = n; - while (l > low) { - s = Math.abs(H[l-1][l-1]) + Math.abs(H[l][l]); - if (s == 0.0) { - s = norm; } - if (Math.abs(H[l][l-1]) < eps * s) { - break; + } + + // Outer loop over eigenvalue index + + int iter = 0; + while (n >= low) { + + // Look for single small sub-diagonal element + + int l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s == 0.0) { + s = norm; + } + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; } - l--; - } - // Check for convergence - // One root found + // Check for convergence + // One root found - if (l == n) { + if (l == n) { H[n][n] += exshift; - d[n] = H[n][n]; - e[n] = 0.0; - n--; - iter = 0; + d[n] = H[n][n]; + e[n] = 0.0; + n--; + iter = 0; - // Two roots found + // Two roots found - } else if (l == n-1) { - w = H[n][n-1] * H[n-1][n]; - p = (H[n-1][n-1] - H[n][n]) / 2.0; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); + } else if (l == n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2.0; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); H[n][n] += exshift; - H[n-1][n-1] += exshift; - x = H[n][n]; + H[n - 1][n - 1] += exshift; + x = H[n][n]; - // Real pair + // Real pair - if (q >= 0) { - if (p >= 0) { - z = p + z; - } else { - z = p - z; - } - d[n-1] = x + z; - d[n] = d[n-1]; - if (z != 0.0) { - d[n] = x - w / z; - } - e[n-1] = 0.0; - e[n] = 0.0; - x = H[n][n-1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p+q * q); + if (q >= 0) { + if (p >= 0) { + z = p + z; + } else { + z = p - z; + } + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z != 0.0) { + d[n] = x - w / z; + } + e[n - 1] = 0.0; + e[n] = 0.0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); p /= r; q /= r; - // Row modification + // Row modification - for (int j = n-1; j < nn; j++) { - z = H[n-1][j]; - H[n-1][j] = q * z + p * H[n][j]; - H[n][j] = q * H[n][j] - p * z; - } + for (int j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } - // Column modification + // Column modification - for (int i = 0; i <= n; i++) { - z = H[i][n-1]; - H[i][n-1] = q * z + p * H[i][n]; - H[i][n] = q * H[i][n] - p * z; - } + for (int i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; + } - // Accumulate transformations + // Accumulate transformations - for (int i = low; i <= high; i++) { - z = V[i][n-1]; - V[i][n-1] = q * z + p * V[i][n]; - V[i][n] = q * V[i][n] - p * z; - } + for (int i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } - // Complex pair + // Complex pair + + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } + n -= 2; + iter = 0; + + // No convergence yet } else { - d[n-1] = x + p; - d[n] = x + p; - e[n-1] = z; - e[n] = -z; - } - n -= 2; - iter = 0; - // No convergence yet + // Form shift - } else { - - // Form shift - - x = H[n][n]; - y = 0.0; - w = 0.0; - if (l < n) { - y = H[n-1][n-1]; - w = H[n][n-1] * H[n-1][n]; - } - - // Wilkinson's original ad hoc shift - - if (iter == 10) { - exshift += x; - for (int i = low; i <= n; i++) { - H[i][i] -= x; - } - s = Math.abs(H[n][n-1]) + Math.abs(H[n-1][n-2]); - x = y = 0.75 * s; - w = -0.4375 * s * s; - } - - // MATLAB's new ad hoc shift - - if (iter == 30) { - s = (y - x) / 2.0; - s = s * s + w; - if (s > 0) { - s = Math.sqrt(s); - if (y < x) { - s = -s; - } - s = x - w / ((y - x) / 2.0 + s); - for (int i = low; i <= n; i++) { - H[i][i] -= s; - } - exshift += s; - x = y = w = 0.964; + x = H[n][n]; + y = 0.0; + w = 0.0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } + + // Wilkinson's original ad hoc shift + + if (iter == 10) { + exshift += x; + for (int i = low; i <= n; i++) { + H[i][i] -= x; + } + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; + } + + // MATLAB's new ad hoc shift + + if (iter == 30) { + s = (y - x) / 2.0; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; + } + s = x - w / ((y - x) / 2.0 + s); + for (int i = low; i <= n; i++) { + H[i][i] -= s; + } + exshift += s; + x = y = w = 0.964; + } } - } iter += 1; // (Could check iteration count here.) - // Look for two consecutive small sub-diagonal elements + // Look for two consecutive small sub-diagonal elements - int m = n-2; - while (m >= l) { - z = H[m][m]; - r = x - z; - s = y - z; - p = (r * s - w) / H[m+1][m] + H[m][m+1]; - q = H[m+1][m+1] - z - r - s; - r = H[m+2][m+1]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); + int m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); p /= s; q /= s; r /= s; - if (m == l) { - break; - } - if (Math.abs(H[m][m-1]) * (Math.abs(q) + Math.abs(r)) < - eps * (Math.abs(p) * (Math.abs(H[m-1][m-1]) + Math.abs(z) + - Math.abs(H[m+1][m+1])))) { - break; - } - m--; - } + if (m == l) { + break; + } + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < + eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + + Math.abs(H[m + 1][m + 1])))) { + break; + } + m--; + } - for (int i = m+2; i <= n; i++) { - H[i][i-2] = 0.0; - if (i > m+2) { - H[i][i-3] = 0.0; - } - } + for (int i = m + 2; i <= n; i++) { + H[i][i - 2] = 0.0; + if (i > m + 2) { + H[i][i - 3] = 0.0; + } + } - // Double QR step involving rows l:n and columns m:n + // Double QR step involving rows l:n and columns m:n - for (int k = m; k <= n-1; k++) { - boolean notlast = (k != n-1); - if (k != m) { - p = H[k][k-1]; - q = H[k+1][k-1]; - r = (notlast ? H[k+2][k-1] : 0.0); - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x != 0.0) { + for (int k = m; k <= n - 1; k++) { + boolean notlast = (k != n - 1); + if (k != m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0.0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x != 0.0) { p /= x; q /= x; r /= x; - } - } - if (x == 0.0) { - break; - } - s = Math.sqrt(p * p + q * q + r * r); - if (p < 0) { - s = -s; - } - if (s != 0) { - if (k != m) { - H[k][k-1] = -s * x; - } else if (l != m) { - H[k][k-1] = -H[k][k-1]; - } + } + } + if (x == 0.0) { + break; + } + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; + } + if (s != 0) { + if (k != m) { + H[k][k - 1] = -s * x; + } else if (l != m) { + H[k][k - 1] = -H[k][k - 1]; + } p += s; - x = p / s; - y = q / s; - z = r / s; + x = p / s; + y = q / s; + z = r / s; q /= p; r /= p; - // Row modification + // Row modification - for (int j = k; j < nn; j++) { - p = H[k][j] + q * H[k+1][j]; - if (notlast) { - p += r * H[k+2][j]; - H[k+2][j] -= p * z; - } + for (int j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p += r * H[k + 2][j]; + H[k + 2][j] -= p * z; + } H[k][j] -= p * x; - H[k+1][j] -= p * y; - } + H[k + 1][j] -= p * y; + } - // Column modification + // Column modification - for (int i = 0; i <= Math.min(n,k+3); i++) { - p = x * H[i][k] + y * H[i][k+1]; - if (notlast) { - p += z * H[i][k+2]; - H[i][k+2] -= p * r; - } + for (int i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p += z * H[i][k + 2]; + H[i][k + 2] -= p * r; + } H[i][k] -= p; - H[i][k+1] -= p * q; - } + H[i][k + 1] -= p * q; + } - // Accumulate transformations + // Accumulate transformations - for (int i = low; i <= high; i++) { - p = x * V[i][k] + y * V[i][k+1]; - if (notlast) { - p += z * V[i][k+2]; - V[i][k+2] -= p * r; - } + for (int i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p += z * V[i][k + 2]; + V[i][k + 2] -= p * r; + } V[i][k] -= p; - V[i][k+1] -= p * q; - } - } // (s != 0) - } // k loop - } // check convergence - } // while (n >= low) + V[i][k + 1] -= p * q; + } + } // (s != 0) + } // k loop + } // check convergence + } // while (n >= low) - // Backsubstitute to find vectors of upper triangular form + // Backsubstitute to find vectors of upper triangular form - if (norm == 0.0) { - return; - } + if (norm == 0.0) { + return; + } - for (n = nn-1; n >= 0; n--) { - p = d[n]; - q = e[n]; + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; - // Real vector + // Real vector - if (q == 0) { - int l = n; - H[n][n] = 1.0; - for (int i = n-1; i >= 0; i--) { - w = H[i][i] - p; - r = 0.0; - for (int j = l; j <= n; j++) { + if (q == 0) { + int l = n; + H[n][n] = 1.0; + for (int i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0.0; + for (int j = l; j <= n; j++) { r += H[i][j] * H[j][n]; - } - if (e[i] < 0.0) { - z = w; - s = r; - } else { - l = i; - if (e[i] == 0.0) { - if (w != 0.0) { - H[i][n] = -r / w; - } else { - H[i][n] = -r / (eps * norm); - } + } + if (e[i] < 0.0) { + z = w; + s = r; + } else { + l = i; + if (e[i] == 0.0) { + if (w != 0.0) { + H[i][n] = -r / w; + } else { + H[i][n] = -r / (eps * norm); + } - // Solve real equations + // Solve real equations - } else { - x = H[i][i+1]; - y = H[i+1][i]; - q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; - t = (x * s - z * r) / q; - H[i][n] = t; - if (Math.abs(x) > Math.abs(z)) { - H[i+1][n] = (-r - w * t) / x; - } else { - H[i+1][n] = (-s - y * t) / z; - } - } + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + if (Math.abs(x) > Math.abs(z)) { + H[i + 1][n] = (-r - w * t) / x; + } else { + H[i + 1][n] = (-s - y * t) / z; + } + } - // Overflow control + // Overflow control - t = Math.abs(H[i][n]); - if ((eps * t) * t > 1) { - for (int j = i; j <= n; j++) { + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (int j = i; j <= n; j++) { H[j][n] /= t; - } - } - } - } + } + } + } + } - // Complex vector + // Complex vector - } else if (q < 0) { - int l = n-1; + } else if (q < 0) { + int l = n - 1; - // Last vector component imaginary so matrix is triangular + // Last vector component imaginary so matrix is triangular - if (Math.abs(H[n][n-1]) > Math.abs(H[n-1][n])) { - H[n-1][n-1] = q / H[n][n-1]; - H[n-1][n] = -(H[n][n] - p) / H[n][n-1]; - } else { - cdiv(0.0,-H[n-1][n],H[n-1][n-1]-p,q); - H[n-1][n-1] = cdivr; - H[n-1][n] = cdivi; - } - H[n][n-1] = 0.0; - H[n][n] = 1.0; - for (int i = n-2; i >= 0; i--) { - double ra,sa,vr,vi; - ra = 0.0; - sa = 0.0; - for (int j = l; j <= n; j++) { - ra += H[i][j] * H[j][n-1]; + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdiv(0.0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivr; + H[n - 1][n] = cdivi; + } + H[n][n - 1] = 0.0; + H[n][n] = 1.0; + for (int i = n - 2; i >= 0; i--) { + double ra, sa, vr, vi; + ra = 0.0; + sa = 0.0; + for (int j = l; j <= n; j++) { + ra += H[i][j] * H[j][n - 1]; sa += H[i][j] * H[j][n]; - } - w = H[i][i] - p; + } + w = H[i][i] - p; - if (e[i] < 0.0) { - z = w; - r = ra; - s = sa; - } else { - l = i; - if (e[i] == 0) { - cdiv(-ra,-sa,w,q); - H[i][n-1] = cdivr; - H[i][n] = cdivi; - } else { + if (e[i] < 0.0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] == 0) { + cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivr; + H[i][n] = cdivi; + } else { - // Solve complex equations + // Solve complex equations - x = H[i][i+1]; - y = H[i+1][i]; - vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; - vi = (d[i] - p) * 2.0 * q; - if (vr == 0.0 & vi == 0.0) { - vr = eps * norm * (Math.abs(w) + Math.abs(q) + - Math.abs(x) + Math.abs(y) + Math.abs(z)); - } - cdiv(x*r-z*ra+q*sa,x*s-z*sa-q*ra,vr,vi); - H[i][n-1] = cdivr; - H[i][n] = cdivi; - if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { - H[i+1][n-1] = (-ra - w * H[i][n-1] + q * H[i][n]) / x; - H[i+1][n] = (-sa - w * H[i][n] - q * H[i][n-1]) / x; - } else { - cdiv(-r-y*H[i][n-1],-s-y*H[i][n],z,q); - H[i+1][n-1] = cdivr; - H[i+1][n] = cdivi; - } - } + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2.0 * q; + if (vr == 0.0 & vi == 0.0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivr; + H[i][n] = cdivi; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivr; + H[i + 1][n] = cdivi; + } + } - // Overflow control + // Overflow control - t = Math.max(Math.abs(H[i][n-1]),Math.abs(H[i][n])); - if ((eps * t) * t > 1) { - for (int j = i; j <= n; j++) { - H[j][n-1] /= t; + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (int j = i; j <= n; j++) { + H[j][n - 1] /= t; H[j][n] /= t; - } - } - } + } + } + } + } } - } - } + } - // Vectors of isolated roots + // Vectors of isolated roots - for (int i = 0; i < nn; i++) { - if (i < low | i > high) { - for (int j = i; j < nn; j++) { - V[i][j] = H[i][j]; + for (int i = 0; i < nn; i++) { + if (i < low | i > high) { + for (int j = i; j < nn; j++) { + V[i][j] = H[i][j]; + } } - } - } + } - // Back transformation to get eigenvectors of original matrix + // Back transformation to get eigenvectors of original matrix - for (int j = nn-1; j >= low; j--) { - for (int i = low; i <= high; i++) { - z = 0.0; - for (int k = low; k <= Math.min(j,high); k++) { + for (int j = nn - 1; j >= low; j--) { + for (int i = low; i <= high; i++) { + z = 0.0; + for (int k = low; k <= Math.min(j, high); k++) { z += V[i][k] * H[k][j]; + } + V[i][j] = z; } - V[i][j] = z; - } - } - } + } + } /* ------------------------ Constructor * ------------------------ */ - /** Check for symmetry, then construct the eigenvalue decomposition - @param A Square matrix - @return Structure to access D and V. - */ + /** + * Check for symmetry, then construct the eigenvalue decomposition + * + * @param A Square matrix + * @return Structure to access D and V. + */ - public EigenvalueDecomposition (Matrix Arg) { - double[][] A = Arg.getArray(); - n = Arg.getColumnDimension(); - V = new double[n][n]; - d = new double[n]; - e = new double[n]; + public EigenvalueDecomposition(Matrix Arg) { + double[][] A = Arg.getArray(); + n = Arg.getColumnDimension(); + V = new double[n][n]; + d = new double[n]; + e = new double[n]; - issymmetric = true; - for (int j = 0; (j < n) & issymmetric; j++) { - for (int i = 0; (i < n) & issymmetric; i++) { - issymmetric = (A[i][j] == A[j][i]); - } - } - - if (issymmetric) { - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - V[i][j] = A[i][j]; + issymmetric = true; + for (int j = 0; (j < n) & issymmetric; j++) { + for (int i = 0; (i < n) & issymmetric; i++) { + issymmetric = (A[i][j] == A[j][i]); } - } + } - // Tridiagonalize. - tred2(); - - // Diagonalize. - tql2(); - - } else { - H = new double[n][n]; - ort = new double[n]; - - for (int j = 0; j < n; j++) { + if (issymmetric) { for (int i = 0; i < n; i++) { - H[i][j] = A[i][j]; + for (int j = 0; j < n; j++) { + V[i][j] = A[i][j]; + } } - } - // Reduce to Hessenberg form. - orthes(); + // Tridiagonalize. + tred2(); - // Reduce Hessenberg to real Schur form. - hqr2(); - } - } + // Diagonalize. + tql2(); + + } else { + H = new double[n][n]; + ort = new double[n]; + + for (int j = 0; j < n; j++) { + for (int i = 0; i < n; i++) { + H[i][j] = A[i][j]; + } + } + + // Reduce to Hessenberg form. + orthes(); + + // Reduce Hessenberg to real Schur form. + hqr2(); + } + } /* ------------------------ Public Methods * ------------------------ */ - /** Return the eigenvector matrix - @return V - */ + /** + * Return the eigenvector matrix + * + * @return V + */ - public Matrix getV () { - return new Matrix(V,n,n); - } + public Matrix getV() { + return new Matrix(V, n, n); + } - /** Return the real parts of the eigenvalues - @return real(diag(D)) - */ + /** + * Return the real parts of the eigenvalues + * + * @return real(diag(D)) + */ - public double[] getRealEigenvalues () { - return d; - } + public double[] getRealEigenvalues() { + return d; + } - /** Return the imaginary parts of the eigenvalues - @return imag(diag(D)) - */ + /** + * Return the imaginary parts of the eigenvalues + * + * @return imag(diag(D)) + */ - public double[] getImagEigenvalues () { - return e; - } + public double[] getImagEigenvalues() { + return e; + } - /** Return the block diagonal eigenvalue matrix - @return D - */ + /** + * Return the block diagonal eigenvalue matrix + * + * @return D + */ - public Matrix getD () { - Matrix X = new Matrix(n,n); - double[][] D = X.getArray(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - D[i][j] = 0.0; - } - D[i][i] = d[i]; - if (e[i] > 0) { - D[i][i+1] = e[i]; - } else if (e[i] < 0) { - D[i][i-1] = e[i]; - } - } - return X; - } + public Matrix getD() { + Matrix X = new Matrix(n, n); + double[][] D = X.getArray(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + D[i][j] = 0.0; + } + D[i][i] = d[i]; + if (e[i] > 0) { + D[i][i + 1] = e[i]; + } else if (e[i] < 0) { + D[i][i - 1] = e[i]; + } + } + return X; + } } diff --git a/src/eva2/tools/math/Jama/LUDecomposition.java b/src/eva2/tools/math/Jama/LUDecomposition.java index 5d0b7d14..1c08531c 100644 --- a/src/eva2/tools/math/Jama/LUDecomposition.java +++ b/src/eva2/tools/math/Jama/LUDecomposition.java @@ -1,18 +1,19 @@ package eva2.tools.math.Jama; - /** LU Decomposition. -

- For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n - unit lower triangular matrix L, an n-by-n upper triangular matrix U, - and a permutation vector piv of length m so that A(piv,:) = L*U. - If m < n, then L is m-by-m and U is m-by-n. -

- The LU decompostion with pivoting always exists, even if the matrix is - singular, so the constructor will never fail. The primary use of the - LU decomposition is in the solution of square systems of simultaneous - linear equations. This will fail if isNonsingular() returns false. - */ +/** + * LU Decomposition. + *

+ * For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n + * unit lower triangular matrix L, an n-by-n upper triangular matrix U, + * and a permutation vector piv of length m so that A(piv,:) = L*U. + * If m < n, then L is m-by-m and U is m-by-n. + *

+ * The LU decompostion with pivoting always exists, even if the matrix is + * singular, so the constructor will never fail. The primary use of the + * LU decomposition is in the solution of square systems of simultaneous + * linear equations. This will fail if isNonsingular() returns false. + */ public class LUDecomposition implements java.io.Serializable { @@ -20,100 +21,112 @@ public class LUDecomposition implements java.io.Serializable { Class variables * ------------------------ */ - /** Array for internal storage of decomposition. - @serial internal array storage. - */ - private double[][] LU; + /** + * Array for internal storage of decomposition. + * + * @serial internal array storage. + */ + private double[][] LU; - /** Row and column dimensions, and pivot sign. - @serial column dimension. - @serial row dimension. - @serial pivot sign. - */ - private int m, n, pivsign; + /** + * Row and column dimensions, and pivot sign. + * + * @serial column dimension. + * @serial row dimension. + * @serial pivot sign. + */ + private int m, n, pivsign; - /** Internal storage of pivot vector. - @serial pivot vector. - */ - private int[] piv; + /** + * Internal storage of pivot vector. + * + * @serial pivot vector. + */ + private int[] piv; /* ------------------------ Constructor * ------------------------ */ - /** LU Decomposition - @param A Rectangular matrix - @return Structure to access L, U and piv. - */ + /** + * LU Decomposition + * + * @param A Rectangular matrix + * @return Structure to access L, U and piv. + */ - public LUDecomposition (Matrix A) { + public LUDecomposition(Matrix A) { - // Use a "left-looking", dot-product, Crout/Doolittle algorithm. + // Use a "left-looking", dot-product, Crout/Doolittle algorithm. // System.out.println("A="); // A.print(A.getRowDimension(),A.getColumnDimension()); - LU = A.getArrayCopy(); - m = A.getRowDimension(); - n = A.getColumnDimension(); - piv = new int[m]; - for (int i = 0; i < m; i++) { - piv[i] = i; - } - pivsign = 1; - double[] LUrowi; - double[] LUcolj = new double[m]; + LU = A.getArrayCopy(); + m = A.getRowDimension(); + n = A.getColumnDimension(); + piv = new int[m]; + for (int i = 0; i < m; i++) { + piv[i] = i; + } + pivsign = 1; + double[] LUrowi; + double[] LUcolj = new double[m]; - // Outer loop. + // Outer loop. - for (int j = 0; j < n; j++) { + for (int j = 0; j < n; j++) { - // Make a copy of the j-th column to localize references. + // Make a copy of the j-th column to localize references. - for (int i = 0; i < m; i++) { - LUcolj[i] = LU[i][j]; - } - - // Apply previous transformations. - - for (int i = 0; i < m; i++) { - LUrowi = LU[i]; - - // Most of the time is spent in the following dot product. - - int kmax = Math.min(i,j); - double s = 0.0; - for (int k = 0; k < kmax; k++) { - s += LUrowi[k]*LUcolj[k]; + for (int i = 0; i < m; i++) { + LUcolj[i] = LU[i][j]; } - LUrowi[j] = LUcolj[i] -= s; - } + // Apply previous transformations. - // Find pivot and exchange if necessary. + for (int i = 0; i < m; i++) { + LUrowi = LU[i]; - int p = j; - for (int i = j+1; i < m; i++) { - if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { - p = i; + // Most of the time is spent in the following dot product. + + int kmax = Math.min(i, j); + double s = 0.0; + for (int k = 0; k < kmax; k++) { + s += LUrowi[k] * LUcolj[k]; + } + + LUrowi[j] = LUcolj[i] -= s; } - } - if (p != j) { - for (int k = 0; k < n; k++) { - double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; - } - int k = piv[p]; piv[p] = piv[j]; piv[j] = k; - pivsign = -pivsign; - } - // Compute multipliers. + // Find pivot and exchange if necessary. - if (j < m & LU[j][j] != 0.0) { - for (int i = j+1; i < m; i++) { - LU[i][j] /= LU[j][j]; + int p = j; + for (int i = j + 1; i < m; i++) { + if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { + p = i; + } } - } - } - } + if (p != j) { + for (int k = 0; k < n; k++) { + double t = LU[p][k]; + LU[p][k] = LU[j][k]; + LU[j][k] = t; + } + int k = piv[p]; + piv[p] = piv[j]; + piv[j] = k; + pivsign = -pivsign; + } + + // Compute multipliers. + + if (j < m & LU[j][j] != 0.0) { + for (int i = j + 1; i < m; i++) { + LU[i][j] /= LU[j][j]; + } + } + } + } /* ------------------------ Temporary, experimental code. @@ -178,142 +191,156 @@ public class LUDecomposition implements java.io.Serializable { Public Methods * ------------------------ */ - /** Is the matrix nonsingular? - @return true if U, and hence A, is nonsingular. - */ + /** + * Is the matrix nonsingular? + * + * @return true if U, and hence A, is nonsingular. + */ - public boolean isNonsingular () { - for (int j = 0; j < n; j++) { - //System.out.println("LU[j][j]"+LU[j][j]); - if (LU[j][j] == 0) { - return false; - } - - } - return true; - } - - /** Return lower triangular factor - @return L - */ - - public Matrix getL () { - Matrix X = new Matrix(m,n); - double[][] L = X.getArray(); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (i > j) { - L[i][j] = LU[i][j]; - } else if (i == j) { - L[i][j] = 1.0; - } else { - L[i][j] = 0.0; + public boolean isNonsingular() { + for (int j = 0; j < n; j++) { + //System.out.println("LU[j][j]"+LU[j][j]); + if (LU[j][j] == 0) { + return false; } - } - } - return X; - } - /** Return upper triangular factor - @return U - */ + } + return true; + } - public Matrix getU () { - Matrix X = new Matrix(n,n); - double[][] U = X.getArray(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - if (i <= j) { - U[i][j] = LU[i][j]; - } else { - U[i][j] = 0.0; + /** + * Return lower triangular factor + * + * @return L + */ + + public Matrix getL() { + Matrix X = new Matrix(m, n); + double[][] L = X.getArray(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (i > j) { + L[i][j] = LU[i][j]; + } else if (i == j) { + L[i][j] = 1.0; + } else { + L[i][j] = 0.0; + } } - } - } - return X; - } + } + return X; + } - /** Return pivot permutation vector - @return piv - */ + /** + * Return upper triangular factor + * + * @return U + */ - public int[] getPivot () { - int[] p = new int[m]; - for (int i = 0; i < m; i++) { - p[i] = piv[i]; - } - return p; - } + public Matrix getU() { + Matrix X = new Matrix(n, n); + double[][] U = X.getArray(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i <= j) { + U[i][j] = LU[i][j]; + } else { + U[i][j] = 0.0; + } + } + } + return X; + } - /** Return pivot permutation vector as a one-dimensional double array - @return (double) piv - */ + /** + * Return pivot permutation vector + * + * @return piv + */ - public double[] getDoublePivot () { - double[] vals = new double[m]; - for (int i = 0; i < m; i++) { - vals[i] = (double) piv[i]; - } - return vals; - } + public int[] getPivot() { + int[] p = new int[m]; + for (int i = 0; i < m; i++) { + p[i] = piv[i]; + } + return p; + } - /** Determinant - @return det(A) - @exception IllegalArgumentException Matrix must be square - */ + /** + * Return pivot permutation vector as a one-dimensional double array + * + * @return (double) piv + */ - public double det () { - if (m != n) { - throw new IllegalArgumentException("Matrix must be square."); - } - double d = (double) pivsign; - for (int j = 0; j < n; j++) { - d *= LU[j][j]; - } - return d; - } + public double[] getDoublePivot() { + double[] vals = new double[m]; + for (int i = 0; i < m; i++) { + vals[i] = (double) piv[i]; + } + return vals; + } - /** Solve A*X = B - @param B A Matrix with as many rows as A and any number of columns. - @return X so that L*U*X = B(piv,:) - @exception IllegalArgumentException Matrix row dimensions must agree. - @exception RuntimeException Matrix is singular. - */ + /** + * Determinant + * + * @return det(A) + * @throws IllegalArgumentException Matrix must be square + */ - public Matrix solve (Matrix B) { - if (B.getRowDimension() != m) { - throw new IllegalArgumentException("Matrix row dimensions must agree."); - } - if (!this.isNonsingular()) { - //System.out.println("B="); - //B.print(B.getRowDimension(),B.getColumnDimension()); - throw new RuntimeException("Matrix is singular."); - } + public double det() { + if (m != n) { + throw new IllegalArgumentException("Matrix must be square."); + } + double d = (double) pivsign; + for (int j = 0; j < n; j++) { + d *= LU[j][j]; + } + return d; + } - // Copy right hand side with pivoting - int nx = B.getColumnDimension(); - Matrix Xmat = B.getMatrix(piv,0,nx-1); - double[][] X = Xmat.getArray(); + /** + * Solve A*X = B + * + * @param B A Matrix with as many rows as A and any number of columns. + * @return X so that L*U*X = B(piv,:) + * @throws IllegalArgumentException Matrix row dimensions must agree. + * @throws RuntimeException Matrix is singular. + */ - // Solve L*Y = B(piv,:) - for (int k = 0; k < n; k++) { - for (int i = k+1; i < n; i++) { + public Matrix solve(Matrix B) { + if (B.getRowDimension() != m) { + throw new IllegalArgumentException("Matrix row dimensions must agree."); + } + if (!this.isNonsingular()) { + //System.out.println("B="); + //B.print(B.getRowDimension(),B.getColumnDimension()); + throw new RuntimeException("Matrix is singular."); + } + + // Copy right hand side with pivoting + int nx = B.getColumnDimension(); + Matrix Xmat = B.getMatrix(piv, 0, nx - 1); + double[][] X = Xmat.getArray(); + + // Solve L*Y = B(piv,:) + for (int k = 0; k < n; k++) { + for (int i = k + 1; i < n; i++) { + for (int j = 0; j < nx; j++) { + X[i][j] -= X[k][j] * LU[i][k]; + } + } + } + // Solve U*X = Y; + for (int k = n - 1; k >= 0; k--) { for (int j = 0; j < nx; j++) { - X[i][j] -= X[k][j]*LU[i][k]; + X[k][j] /= LU[k][k]; } - } - } - // Solve U*X = Y; - for (int k = n-1; k >= 0; k--) { - for (int j = 0; j < nx; j++) { - X[k][j] /= LU[k][k]; - } - for (int i = 0; i < k; i++) { - for (int j = 0; j < nx; j++) { - X[i][j] -= X[k][j]*LU[i][k]; + for (int i = 0; i < k; i++) { + for (int j = 0; j < nx; j++) { + X[i][j] -= X[k][j] * LU[i][k]; + } } - } - } - return Xmat; - } + } + return Xmat; + } } diff --git a/src/eva2/tools/math/Jama/Matrix.java b/src/eva2/tools/math/Jama/Matrix.java index df477d12..6ec2c52f 100644 --- a/src/eva2/tools/math/Jama/Matrix.java +++ b/src/eva2/tools/math/Jama/Matrix.java @@ -5,6 +5,7 @@ import eva2.gui.BeanInspector; import eva2.tools.Pair; import eva2.tools.math.Jama.util.Maths; import eva2.tools.math.Mathematics; + import java.io.BufferedReader; import java.io.PrintWriter; import java.io.Serializable; @@ -18,1391 +19,1537 @@ import java.util.Vector; /** - Jama = Java Matrix class. -

- The Java Matrix Class provides the fundamental operations of numerical - linear algebra. Various constructors create Matrices from two dimensional - arrays of double precision floating point numbers. Various "gets" and - "sets" provide access to submatrices and matrix elements. Several methods - implement basic matrix arithmetic, including matrix addition and - multiplication, matrix norms, and element-by-element array operations. - Methods for reading and printing matrices are also included. All the - operations in this version of the Matrix Class involve real matrices. - Complex matrices may be handled in a future version. -

- Five fundamental matrix decompositions, which consist of pairs or triples - of matrices, permutation vectors, and the like, produce results in five - decomposition classes. These decompositions are accessed by the Matrix - class to compute solutions of simultaneous linear equations, determinants, - inverses and other matrix functions. The five decompositions are: -

    -
  • Cholesky Decomposition of symmetric, positive definite matrices. -
  • LU Decomposition of rectangular matrices. -
  • QR Decomposition of rectangular matrices. -
  • Singular Value Decomposition of rectangular matrices. -
  • Eigenvalue Decomposition of both symmetric and nonsymmetric square matrices. -
-
-
Example of use:
-

-

Solve a linear system A x = b and compute the residual norm, ||b - A x||. -

-      double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
-      Matrix A = new Matrix(vals);
-      Matrix b = Matrix.random(3,1);
-      Matrix x = A.solve(b);
-      Matrix r = A.times(x).minus(b);
-      double rnorm = r.normInf();
-
-
- -@author The MathWorks, Inc. and the National Institute of Standards and Technology. -@version 5 August 1998 -*/ + * Jama = Java Matrix class. + *

+ * The Java Matrix Class provides the fundamental operations of numerical + * linear algebra. Various constructors create Matrices from two dimensional + * arrays of double precision floating point numbers. Various "gets" and + * "sets" provide access to submatrices and matrix elements. Several methods + * implement basic matrix arithmetic, including matrix addition and + * multiplication, matrix norms, and element-by-element array operations. + * Methods for reading and printing matrices are also included. All the + * operations in this version of the Matrix Class involve real matrices. + * Complex matrices may be handled in a future version. + *

+ * Five fundamental matrix decompositions, which consist of pairs or triples + * of matrices, permutation vectors, and the like, produce results in five + * decomposition classes. These decompositions are accessed by the Matrix + * class to compute solutions of simultaneous linear equations, determinants, + * inverses and other matrix functions. The five decompositions are: + *

    + *
  • Cholesky Decomposition of symmetric, positive definite matrices. + *
  • LU Decomposition of rectangular matrices. + *
  • QR Decomposition of rectangular matrices. + *
  • Singular Value Decomposition of rectangular matrices. + *
  • Eigenvalue Decomposition of both symmetric and nonsymmetric square matrices. + *
+ *
+ *
Example of use:
+ *

+ *

Solve a linear system A x = b and compute the residual norm, ||b - A x||. + *

+ * double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
+ * Matrix A = new Matrix(vals);
+ * Matrix b = Matrix.random(3,1);
+ * Matrix x = A.solve(b);
+ * Matrix r = A.times(x).minus(b);
+ * double rnorm = r.normInf();
+ * 
+ *
+ * + * @author The MathWorks, Inc. and the National Institute of Standards and Technology. + * @version 5 August 1998 + */ public class Matrix implements Cloneable, Serializable { - /** - * Generated serial version identifier. - */ - private static final long serialVersionUID = 3672826349694248499L; + /** + * Generated serial version identifier. + */ + private static final long serialVersionUID = 3672826349694248499L; /* ------------------------ Class variables * ------------------------ */ - - /** Array for internal storage of elements. - @serial internal array storage. - */ - private double[][] A; - /** Row and column dimensions. - @serial row dimension. - @serial column dimension. - */ - private int m, n; + /** + * Array for internal storage of elements. + * + * @serial internal array storage. + */ + private double[][] A; + + /** + * Row and column dimensions. + * + * @serial row dimension. + * @serial column dimension. + */ + private int m, n; /* ------------------------ Constructors * ------------------------ */ - /** Construct an m-by-n matrix of zeros. - @param m Number of rows. - @param n Number of colums. - */ + /** + * Construct an m-by-n matrix of zeros. + * + * @param m Number of rows. + * @param n Number of colums. + */ - public Matrix (int m, int n) { - this.m = m; - this.n = n; - A = new double[m][n]; - } - - /** Construct an m-by-n constant matrix. - @param m Number of rows. - @param n Number of colums. - @param s Fill the matrix with this scalar value. - */ - - public Matrix (int m, int n, double s) { - this.m = m; - this.n = n; - A = new double[m][n]; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - A[i][j] = s; - } - } - } - - /** Construct a matrix from a 2-D array. - @param A Two-dimensional array of doubles. - @exception IllegalArgumentException All rows must have the same length - @see #constructWithCopy - */ - - public Matrix(double[][] A) { - this(A, true); - } - - /** - * - * @param A - * @param checkDims - */ - public Matrix(double[][] A, boolean checkDims) { - m = A.length; - n = m == 0 ? 0 : A[0].length; - if (checkDims) { - for (int i = 0; i < m; i++) { - if (A[i].length != n) { - throw new IllegalArgumentException("All rows must have the same length."); - } - } - } - this.A = A; - } - - /** Construct a matrix quickly without checking arguments. - @param A Two-dimensional array of doubles. - @param m Number of rows. - @param n Number of colums. - */ - - public Matrix (double[][] A, int m, int n) { - this.A = A; - this.m = m; - this.n = n; - } - - /** Construct a matrix from a one-dimensional packed array - @param vals One-dimensional array of doubles, packed by columns (ala Fortran). - @param m Number of rows. - @exception IllegalArgumentException Array length must be a multiple of m. - */ - - public Matrix (double vals[], int m) { - this.m = m; - n = (m != 0 ? vals.length/m : 0); - if (m*n != vals.length) { - throw new IllegalArgumentException("Array length must be a multiple of m."); - } - A = new double[m][n]; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - A[i][j] = vals[i+j*m]; - } - } - } - - /** - * - */ - public static Matrix repMat (Matrix A, int m, int n) { - int An = A.getColumnDimension(); - int Am = A.getRowDimension(); - Matrix Ret = new Matrix (m*Am,n*An); - int nn = 0; - int mm = 0; - for ( int im=0;im getMinMaxDiag() { - if (m<1 || n<1) { - return null; - } - - double v = get(0,0); - Pair ret = new Pair(v,v); - for (int i=1; i getMinMaxDiag() { + if (m < 1 || n < 1) { + return null; + } + + double v = get(0, 0); + Pair ret = new Pair(v, v); + for (int i = 1; i < Math.min(m, n); i++) { + v = get(i, i); + ret.head = Math.min(ret.head, v); + ret.tail = Math.max(ret.tail, v); + } + return ret; + } - /** Print the matrix to stdout. Line the elements up in columns + /** + * Print the matrix to stdout. Line the elements up in columns * with a Fortran-like 'Fw.d' style format. - @param w Column width. - @param d Number of digits after the decimal. - */ + * + * @param w Column width. + * @param d Number of digits after the decimal. + */ - public void print (int w, int d) { - print(new PrintWriter(System.out,true),w,d); } + public void print(int w, int d) { + print(new PrintWriter(System.out, true), w, d); + } - /** Print the matrix to the output stream. Line the elements up in + /** + * Print the matrix to the output stream. Line the elements up in * columns with a Fortran-like 'Fw.d' style format. - @param output Output stream. - @param w Column width. - @param d Number of digits after the decimal. - */ + * + * @param output Output stream. + * @param w Column width. + * @param d Number of digits after the decimal. + */ - public void print (PrintWriter output, int w, int d) { - DecimalFormat format = new DecimalFormat(); - format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); - format.setMinimumIntegerDigits(1); - format.setMaximumFractionDigits(d); - format.setMinimumFractionDigits(d); - format.setGroupingUsed(false); - print(output,format,w+2); - } + public void print(PrintWriter output, int w, int d) { + DecimalFormat format = new DecimalFormat(); + format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); + format.setMinimumIntegerDigits(1); + format.setMaximumFractionDigits(d); + format.setMinimumFractionDigits(d); + format.setGroupingUsed(false); + print(output, format, w + 2); + } - /** Print the matrix to stdout. Line the elements up in columns. + /** + * Print the matrix to stdout. Line the elements up in columns. * Use the format object, and right justify within columns of width * characters. * Note that is the matrix is to be read back in, you probably will want * to use a NumberFormat that is set to US Locale. - @param format A Formatting object for individual elements. - @param width Field width for each column. - @see java.text.DecimalFormat#setDecimalFormatSymbols - */ + * + * @param format A Formatting object for individual elements. + * @param width Field width for each column. + * @see java.text.DecimalFormat#setDecimalFormatSymbols + */ - public void print (NumberFormat format, int width) { - print(new PrintWriter(System.out,true),format,width); } + public void print(NumberFormat format, int width) { + print(new PrintWriter(System.out, true), format, width); + } - // DecimalFormat is a little disappointing coming from Fortran or C's printf. - // Since it doesn't pad on the left, the elements will come out different - // widths. Consequently, we'll pass the desired column width in as an - // argument and do the extra padding ourselves. + // DecimalFormat is a little disappointing coming from Fortran or C's printf. + // Since it doesn't pad on the left, the elements will come out different + // widths. Consequently, we'll pass the desired column width in as an + // argument and do the extra padding ourselves. - /** Print the matrix to the output stream. Line the elements up in columns. + /** + * Print the matrix to the output stream. Line the elements up in columns. * Use the format object, and right justify within columns of width * characters. * Note that is the matrix is to be read back in, you probably will want * to use a NumberFormat that is set to US Locale. - @param output the output stream. - @param format A formatting object to format the matrix elements - @param width Column width. - @see java.text.DecimalFormat#setDecimalFormatSymbols - */ + * + * @param output the output stream. + * @param format A formatting object to format the matrix elements + * @param width Column width. + * @see java.text.DecimalFormat#setDecimalFormatSymbols + */ - public void print (PrintWriter output, NumberFormat format, int width) { - output.println(); // start on new line. - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - String s = format.format(A[i][j]); // format the number - int padding = Math.max(1,width-s.length()); // At _least_ 1 space - for (int k = 0; k < padding; k++) { + public void print(PrintWriter output, NumberFormat format, int width) { + output.println(); // start on new line. + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + String s = format.format(A[i][j]); // format the number + int padding = Math.max(1, width - s.length()); // At _least_ 1 space + for (int k = 0; k < padding; k++) { output.print(' '); } - output.print(s); - } - output.println(); - } - output.println(); // end with blank line. - } + output.print(s); + } + output.println(); + } + output.println(); // end with blank line. + } - /** Read a matrix from a stream. The format is the same the print method, + /** + * Read a matrix from a stream. The format is the same the print method, * so printed matrices can be read back in (provided they were printed using * US Locale). Elements are separated by * whitespace, all the elements for each row appear on a single line, * the last row is followed by a blank line. - @param input the input stream. - */ + * + * @param input the input stream. + */ - public static Matrix read (BufferedReader input) throws java.io.IOException { - StreamTokenizer tokenizer= new StreamTokenizer(input); + public static Matrix read(BufferedReader input) throws java.io.IOException { + StreamTokenizer tokenizer = new StreamTokenizer(input); - // Although StreamTokenizer will parse numbers, it doesn't recognize - // scientific notation (E or D); however, Double.valueOf does. - // The strategy here is to disable StreamTokenizer's number parsing. - // We'll only get whitespace delimited words, EOL's and EOF's. - // These words should all be numbers, for Double.valueOf to parse. + // Although StreamTokenizer will parse numbers, it doesn't recognize + // scientific notation (E or D); however, Double.valueOf does. + // The strategy here is to disable StreamTokenizer's number parsing. + // We'll only get whitespace delimited words, EOL's and EOF's. + // These words should all be numbers, for Double.valueOf to parse. - tokenizer.resetSyntax(); - tokenizer.wordChars(0,255); - tokenizer.whitespaceChars(0, ' '); - tokenizer.eolIsSignificant(true); - Vector v = new Vector(); + tokenizer.resetSyntax(); + tokenizer.wordChars(0, 255); + tokenizer.whitespaceChars(0, ' '); + tokenizer.eolIsSignificant(true); + Vector v = new Vector(); - // Ignore initial empty lines - while (tokenizer.nextToken() == StreamTokenizer.TT_EOL); - if (tokenizer.ttype == StreamTokenizer.TT_EOF) { - throw new java.io.IOException("Unexpected EOF on matrix read."); - } - do { - v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st row. - } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD); - - int n = v.size(); // Now we've got the number of columns! - double row[] = new double[n]; - for (int j=0; j= n) { - throw new java.io.IOException - ("Row " + v.size() + " is too long."); - } - row[j++] = Double.valueOf(tokenizer.sval).doubleValue(); - } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD); - if (j < n) { - throw new java.io.IOException - ("Row " + v.size() + " is too short."); - } - } - int m = v.size(); // Now we've got the number of rows. - double[][] A = new double[m][]; - v.copyInto(A); // copy the rows out of the vector - return new Matrix(A); - } + do { + v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st row. + } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD); + + int n = v.size(); // Now we've got the number of columns! + double row[] = new double[n]; + for (int j = 0; j < n; j++) { + row[j] = ((Double) v.elementAt(j)).doubleValue(); + } + v.removeAllElements(); + v.addElement(row); // Start storing rows instead of columns. + while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) { + // While non-empty lines + v.addElement(row = new double[n]); + int j = 0; + do { + if (j >= n) { + throw new java.io.IOException + ("Row " + v.size() + " is too long."); + } + row[j++] = Double.valueOf(tokenizer.sval).doubleValue(); + } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD); + if (j < n) { + throw new java.io.IOException + ("Row " + v.size() + " is too short."); + } + } + int m = v.size(); // Now we've got the number of rows. + double[][] A = new double[m][]; + v.copyInto(A); // copy the rows out of the vector + return new Matrix(A); + } /* ------------------------ Private Methods * ------------------------ */ - /** Check if size(A) == size(B) **/ + /** + * Check if size(A) == size(B) * + */ - private void checkMatrixDimensions (Matrix B) { - if (B.m != m || B.n != n) { - System.out.println("B.m"+B.m); - System.out.println("m"+m); - System.out.println("B.n"+B.n); - System.out.println("n"+n); - throw new IllegalArgumentException("Matrix dimensions must agree."); - } - } + private void checkMatrixDimensions(Matrix B) { + if (B.m != m || B.n != n) { + System.out.println("B.m" + B.m); + System.out.println("m" + m); + System.out.println("B.n" + B.n); + System.out.println("n" + n); + throw new IllegalArgumentException("Matrix dimensions must agree."); + } + } - /** - * Subtract a line from the indicated line of this matrix in place. - * - * @param rowIndex - * @param B - */ - public void rowSubtract(int rowIndex, double[] v) { - if ((v.length != n) || (rowIndex<0) || (rowIndex>=m)) { - throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); - } - rowSubtract(rowIndex, rowIndex, v); - } - - /** - * Subtract a line from each line of this matrix in place. - * - * @param rowIndex - * @param B - */ - public void rowSubtract(double[] v) { - if ((v.length != n)) { - throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); - } - rowSubtract(0, m-1, v); - } - - private void rowSubtract(int start, int end, double[] v) { - for (int i=start; i<=end; i++) { + /** + * Subtract a line from the indicated line of this matrix in place. + * + * @param rowIndex + * @param B + */ + public void rowSubtract(int rowIndex, double[] v) { + if ((v.length != n) || (rowIndex < 0) || (rowIndex >= m)) { + throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); + } + rowSubtract(rowIndex, rowIndex, v); + } + + /** + * Subtract a line from each line of this matrix in place. + * + * @param rowIndex + * @param B + */ + public void rowSubtract(double[] v) { + if ((v.length != n)) { + throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); + } + rowSubtract(0, m - 1, v); + } + + private void rowSubtract(int start, int end, double[] v) { + for (int i = start; i <= end; i++) { Mathematics.vvSub(A[i], v, A[i]); } - } + } - /** - * Given two vectors, ``[a0, a1, ..., aM]`` and ``[b0, b1, ..., bN]``, - * the outer product becomes:: - * - * [[a0*b0 a0*b1 ... a0*bN ] - * [a1*b0 . - * [ ... . - * [aM*b0 aM*bN ]] - */ - public static Matrix outer(double[] a, double[] b) { - double[][] M = new double[a.length][b.length]; - for (int i=0; i + * [[a0*b0 a0*b1 ... a0*bN ] + * [a1*b0 . + * [ ... . + * [aM*b0 aM*bN ]] + */ + public static Matrix outer(double[] a, double[] b) { + double[][] M = new double[a.length][b.length]; + for (int i = 0; i < a.length; i++) { + for (int j = 0; j < b.length; j++) { + M[i][j] = a[i] * b[j]; + } + } + return new Matrix(M); + } - /** - * Multiply the j-th row of the matrix by s, in place. - * @param j - * @param s - */ - public void multRow(int j, double s) { - Mathematics.svMult(s, getRowShallow(j), getRowShallow(j)); - } + /** + * Create a full copy with each entry set to its absolute value. + * + * @param M + * @return + */ + public Matrix abs(Matrix M) { + double[][] A = M.getArrayCopy(); + for (int i = 0; i < A.length; i++) { + for (int j = 0; j < A[0].length; j++) { + A[i][j] = Math.abs(A[i][j]); + } + } + return new Matrix(A); + } - /** - * Multiply the j-th column of the matrix by s, in place. - * @param j - * @param s - */ - public void multCol(int j, double s) { - for (int i=0; i - For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n - orthogonal matrix Q and an n-by-n upper triangular matrix R so that - A = Q*R. -

- The QR decompostion always exists, even if the matrix does not have - full rank, so the constructor will never fail. The primary use of the - QR decomposition is in the least squares solution of nonsquare systems - of simultaneous linear equations. This will fail if isFullRank() - returns false. -*/ +/** + * QR Decomposition. + *

+ * For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n + * orthogonal matrix Q and an n-by-n upper triangular matrix R so that + * A = Q*R. + *

+ * The QR decompostion always exists, even if the matrix does not have + * full rank, so the constructor will never fail. The primary use of the + * QR decomposition is in the least squares solution of nonsquare systems + * of simultaneous linear equations. This will fail if isFullRank() + * returns false. + */ public class QRDecomposition implements java.io.Serializable { @@ -20,200 +22,218 @@ public class QRDecomposition implements java.io.Serializable { Class variables * ------------------------ */ - /** Array for internal storage of decomposition. - @serial internal array storage. - */ - private double[][] QR; + /** + * Array for internal storage of decomposition. + * + * @serial internal array storage. + */ + private double[][] QR; - /** Row and column dimensions. - @serial column dimension. - @serial row dimension. - */ - private int m, n; + /** + * Row and column dimensions. + * + * @serial column dimension. + * @serial row dimension. + */ + private int m, n; - /** Array for internal storage of diagonal of R. - @serial diagonal of R. - */ - private double[] Rdiag; + /** + * Array for internal storage of diagonal of R. + * + * @serial diagonal of R. + */ + private double[] Rdiag; /* ------------------------ Constructor * ------------------------ */ - /** QR Decomposition, computed by Householder reflections. - @param A Rectangular matrix - @return Structure to access R and the Householder vectors and compute Q. - */ + /** + * QR Decomposition, computed by Householder reflections. + * + * @param A Rectangular matrix + * @return Structure to access R and the Householder vectors and compute Q. + */ - public QRDecomposition (Matrix A) { - // Initialize. - QR = A.getArrayCopy(); - m = A.getRowDimension(); - n = A.getColumnDimension(); - Rdiag = new double[n]; + public QRDecomposition(Matrix A) { + // Initialize. + QR = A.getArrayCopy(); + m = A.getRowDimension(); + n = A.getColumnDimension(); + Rdiag = new double[n]; - // Main loop. - for (int k = 0; k < n; k++) { - // Compute 2-norm of k-th column without under/overflow. - double nrm = 0; - for (int i = k; i < m; i++) { - nrm = Maths.hypot(nrm,QR[i][k]); - } - - if (nrm != 0.0) { - // Form k-th Householder vector. - if (QR[k][k] < 0) { - nrm = -nrm; - } + // Main loop. + for (int k = 0; k < n; k++) { + // Compute 2-norm of k-th column without under/overflow. + double nrm = 0; for (int i = k; i < m; i++) { - QR[i][k] /= nrm; + nrm = Maths.hypot(nrm, QR[i][k]); } - QR[k][k] += 1.0; - // Apply transformation to remaining columns. - for (int j = k+1; j < n; j++) { - double s = 0.0; - for (int i = k; i < m; i++) { - s += QR[i][k]*QR[i][j]; - } - s = -s/QR[k][k]; - for (int i = k; i < m; i++) { - QR[i][j] += s*QR[i][k]; - } + if (nrm != 0.0) { + // Form k-th Householder vector. + if (QR[k][k] < 0) { + nrm = -nrm; + } + for (int i = k; i < m; i++) { + QR[i][k] /= nrm; + } + QR[k][k] += 1.0; + + // Apply transformation to remaining columns. + for (int j = k + 1; j < n; j++) { + double s = 0.0; + for (int i = k; i < m; i++) { + s += QR[i][k] * QR[i][j]; + } + s = -s / QR[k][k]; + for (int i = k; i < m; i++) { + QR[i][j] += s * QR[i][k]; + } + } } - } - Rdiag[k] = -nrm; - } - } + Rdiag[k] = -nrm; + } + } /* ------------------------ Public Methods * ------------------------ */ - /** Is the matrix full rank? - @return true if R, and hence A, has full rank. - */ + /** + * Is the matrix full rank? + * + * @return true if R, and hence A, has full rank. + */ - public boolean isFullRank () { - for (int j = 0; j < n; j++) { - if (Rdiag[j] == 0) { - return false; - } - } - return true; - } - - /** Return the Householder vectors - @return Lower trapezoidal matrix whose columns define the reflections - */ - - public Matrix getH () { - Matrix X = new Matrix(m,n); - double[][] H = X.getArray(); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (i >= j) { - H[i][j] = QR[i][j]; - } else { - H[i][j] = 0.0; + public boolean isFullRank() { + for (int j = 0; j < n; j++) { + if (Rdiag[j] == 0) { + return false; } - } - } - return X; - } + } + return true; + } - /** Return the upper triangular factor - @return R - */ + /** + * Return the Householder vectors + * + * @return Lower trapezoidal matrix whose columns define the reflections + */ - public Matrix getR () { - Matrix X = new Matrix(n,n); - double[][] R = X.getArray(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - if (i < j) { - R[i][j] = QR[i][j]; - } else if (i == j) { - R[i][j] = Rdiag[i]; - } else { - R[i][j] = 0.0; + public Matrix getH() { + Matrix X = new Matrix(m, n); + double[][] H = X.getArray(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (i >= j) { + H[i][j] = QR[i][j]; + } else { + H[i][j] = 0.0; + } } - } - } - return X; - } + } + return X; + } - /** Generate and return the (economy-sized) orthogonal factor - @return Q - */ + /** + * Return the upper triangular factor + * + * @return R + */ - public Matrix getQ () { - Matrix X = new Matrix(m,n); - double[][] Q = X.getArray(); - for (int k = n-1; k >= 0; k--) { - for (int i = 0; i < m; i++) { - Q[i][k] = 0.0; - } - Q[k][k] = 1.0; - for (int j = k; j < n; j++) { - if (QR[k][k] != 0) { - double s = 0.0; - for (int i = k; i < m; i++) { - s += QR[i][k]*Q[i][j]; - } - s = -s/QR[k][k]; - for (int i = k; i < m; i++) { - Q[i][j] += s*QR[i][k]; - } + public Matrix getR() { + Matrix X = new Matrix(n, n); + double[][] R = X.getArray(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i < j) { + R[i][j] = QR[i][j]; + } else if (i == j) { + R[i][j] = Rdiag[i]; + } else { + R[i][j] = 0.0; + } } - } - } - return X; - } + } + return X; + } - /** Least squares solution of A*X = B - @param B A Matrix with as many rows as A and any number of columns. - @return X that minimizes the two norm of Q*R*X-B. - @exception IllegalArgumentException Matrix row dimensions must agree. - @exception RuntimeException Matrix is rank deficient. - */ + /** + * Generate and return the (economy-sized) orthogonal factor + * + * @return Q + */ - public Matrix solve (Matrix B) { - if (B.getRowDimension() != m) { - throw new IllegalArgumentException("Matrix row dimensions must agree."); - } - if (!this.isFullRank()) { - throw new RuntimeException("Matrix is rank deficient."); - } - - // Copy right hand side - int nx = B.getColumnDimension(); - double[][] X = B.getArrayCopy(); - - // Compute Y = transpose(Q)*B - for (int k = 0; k < n; k++) { - for (int j = 0; j < nx; j++) { - double s = 0.0; - for (int i = k; i < m; i++) { - s += QR[i][k]*X[i][j]; + public Matrix getQ() { + Matrix X = new Matrix(m, n); + double[][] Q = X.getArray(); + for (int k = n - 1; k >= 0; k--) { + for (int i = 0; i < m; i++) { + Q[i][k] = 0.0; } - s = -s/QR[k][k]; - for (int i = k; i < m; i++) { - X[i][j] += s*QR[i][k]; + Q[k][k] = 1.0; + for (int j = k; j < n; j++) { + if (QR[k][k] != 0) { + double s = 0.0; + for (int i = k; i < m; i++) { + s += QR[i][k] * Q[i][j]; + } + s = -s / QR[k][k]; + for (int i = k; i < m; i++) { + Q[i][j] += s * QR[i][k]; + } + } } - } - } - // Solve R*X = Y; - for (int k = n-1; k >= 0; k--) { - for (int j = 0; j < nx; j++) { - X[k][j] /= Rdiag[k]; - } - for (int i = 0; i < k; i++) { + } + return X; + } + + /** + * Least squares solution of A*X = B + * + * @param B A Matrix with as many rows as A and any number of columns. + * @return X that minimizes the two norm of Q*R*X-B. + * @throws IllegalArgumentException Matrix row dimensions must agree. + * @throws RuntimeException Matrix is rank deficient. + */ + + public Matrix solve(Matrix B) { + if (B.getRowDimension() != m) { + throw new IllegalArgumentException("Matrix row dimensions must agree."); + } + if (!this.isFullRank()) { + throw new RuntimeException("Matrix is rank deficient."); + } + + // Copy right hand side + int nx = B.getColumnDimension(); + double[][] X = B.getArrayCopy(); + + // Compute Y = transpose(Q)*B + for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { - X[i][j] -= X[k][j]*QR[i][k]; + double s = 0.0; + for (int i = k; i < m; i++) { + s += QR[i][k] * X[i][j]; + } + s = -s / QR[k][k]; + for (int i = k; i < m; i++) { + X[i][j] += s * QR[i][k]; + } } - } - } - return (new Matrix(X,n,nx).getMatrix(0,n-1,0,nx-1)); - } + } + // Solve R*X = Y; + for (int k = n - 1; k >= 0; k--) { + for (int j = 0; j < nx; j++) { + X[k][j] /= Rdiag[k]; + } + for (int i = 0; i < k; i++) { + for (int j = 0; j < nx; j++) { + X[i][j] -= X[k][j] * QR[i][k]; + } + } + } + return (new Matrix(X, n, nx).getMatrix(0, n - 1, 0, nx - 1)); + } } diff --git a/src/eva2/tools/math/Jama/SingularValueDecomposition.java b/src/eva2/tools/math/Jama/SingularValueDecomposition.java index a5339c9d..282c4bba 100644 --- a/src/eva2/tools/math/Jama/SingularValueDecomposition.java +++ b/src/eva2/tools/math/Jama/SingularValueDecomposition.java @@ -1,20 +1,22 @@ package eva2.tools.math.Jama; + import eva2.tools.math.Jama.util.*; - /** Singular Value Decomposition. -

- For an m-by-n matrix A with m >= n, the singular value decomposition is - an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and - an n-by-n orthogonal matrix V so that A = U*S*V'. -

- The singular values, sigma[k] = S[k][k], are ordered so that - sigma[0] >= sigma[1] >= ... >= sigma[n-1]. -

- The singular value decompostion always exists, so the constructor will - never fail. The matrix condition number and the effective numerical - rank can be computed from this decomposition. - */ +/** + * Singular Value Decomposition. + *

+ * For an m-by-n matrix A with m >= n, the singular value decomposition is + * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and + * an n-by-n orthogonal matrix V so that A = U*S*V'. + *

+ * The singular values, sigma[k] = S[k][k], are ordered so that + * sigma[0] >= sigma[1] >= ... >= sigma[n-1]. + *

+ * The singular value decompostion always exists, so the constructor will + * never fail. The matrix condition number and the effective numerical + * rank can be computed from this decomposition. + */ public class SingularValueDecomposition implements java.io.Serializable { @@ -22,519 +24,545 @@ public class SingularValueDecomposition implements java.io.Serializable { Class variables * ------------------------ */ - /** Arrays for internal storage of U and V. - @serial internal storage of U. - @serial internal storage of V. - */ - private double[][] U, V; + /** + * Arrays for internal storage of U and V. + * + * @serial internal storage of U. + * @serial internal storage of V. + */ + private double[][] U, V; - /** Array for internal storage of singular values. - @serial internal storage of singular values. - */ - private double[] s; + /** + * Array for internal storage of singular values. + * + * @serial internal storage of singular values. + */ + private double[] s; - /** Row and column dimensions. - @serial row dimension. - @serial column dimension. - */ - private int m, n; + /** + * Row and column dimensions. + * + * @serial row dimension. + * @serial column dimension. + */ + private int m, n; /* ------------------------ Constructor * ------------------------ */ - /** Construct the singular value decomposition - @param A Rectangular matrix - @return Structure to access U, S and V. - */ + /** + * Construct the singular value decomposition + * + * @param A Rectangular matrix + * @return Structure to access U, S and V. + */ - public SingularValueDecomposition (Matrix Arg) { + public SingularValueDecomposition(Matrix Arg) { - // Derived from LINPACK code. - // Initialize. - double[][] A = Arg.getArrayCopy(); - m = Arg.getRowDimension(); - n = Arg.getColumnDimension(); - int nu = Math.min(m,n); - s = new double [Math.min(m+1,n)]; - U = new double [m][nu]; - V = new double [n][n]; - double[] e = new double [n]; - double[] work = new double [m]; - boolean wantu = true; - boolean wantv = true; + // Derived from LINPACK code. + // Initialize. + double[][] A = Arg.getArrayCopy(); + m = Arg.getRowDimension(); + n = Arg.getColumnDimension(); + int nu = Math.min(m, n); + s = new double[Math.min(m + 1, n)]; + U = new double[m][nu]; + V = new double[n][n]; + double[] e = new double[n]; + double[] work = new double[m]; + boolean wantu = true; + boolean wantv = true; - // Reduce A to bidiagonal form, storing the diagonal elements - // in s and the super-diagonal elements in e. + // Reduce A to bidiagonal form, storing the diagonal elements + // in s and the super-diagonal elements in e. - int nct = Math.min(m-1,n); - int nrt = Math.max(0,Math.min(n-2,m)); - for (int k = 0; k < Math.max(nct,nrt); k++) { - if (k < nct) { + int nct = Math.min(m - 1, n); + int nrt = Math.max(0, Math.min(n - 2, m)); + for (int k = 0; k < Math.max(nct, nrt); k++) { + if (k < nct) { - // Compute the transformation for the k-th column and - // place the k-th diagonal in s[k]. - // Compute 2-norm of k-th column without under/overflow. - s[k] = 0; - for (int i = k; i < m; i++) { - s[k] = Maths.hypot(s[k],A[i][k]); + // Compute the transformation for the k-th column and + // place the k-th diagonal in s[k]. + // Compute 2-norm of k-th column without under/overflow. + s[k] = 0; + for (int i = k; i < m; i++) { + s[k] = Maths.hypot(s[k], A[i][k]); + } + if (s[k] != 0.0) { + if (A[k][k] < 0.0) { + s[k] = -s[k]; + } + for (int i = k; i < m; i++) { + A[i][k] /= s[k]; + } + A[k][k] += 1.0; + } + s[k] = -s[k]; } - if (s[k] != 0.0) { - if (A[k][k] < 0.0) { - s[k] = -s[k]; - } - for (int i = k; i < m; i++) { - A[i][k] /= s[k]; - } - A[k][k] += 1.0; + for (int j = k + 1; j < n; j++) { + if ((k < nct) & (s[k] != 0.0)) { + + // Apply the transformation. + + double t = 0; + for (int i = k; i < m; i++) { + t += A[i][k] * A[i][j]; + } + t = -t / A[k][k]; + for (int i = k; i < m; i++) { + A[i][j] += t * A[i][k]; + } + } + + // Place the k-th row of A into e for the + // subsequent calculation of the row transformation. + + e[j] = A[k][j]; } - s[k] = -s[k]; - } - for (int j = k+1; j < n; j++) { - if ((k < nct) & (s[k] != 0.0)) { + if (wantu & (k < nct)) { - // Apply the transformation. + // Place the transformation in U for subsequent back + // multiplication. - double t = 0; - for (int i = k; i < m; i++) { - t += A[i][k]*A[i][j]; - } - t = -t/A[k][k]; - for (int i = k; i < m; i++) { - A[i][j] += t*A[i][k]; - } + for (int i = k; i < m; i++) { + U[i][k] = A[i][k]; + } } + if (k < nrt) { - // Place the k-th row of A into e for the - // subsequent calculation of the row transformation. + // Compute the k-th row transformation and place the + // k-th super-diagonal in e[k]. + // Compute 2-norm without under/overflow. + e[k] = 0; + for (int i = k + 1; i < n; i++) { + e[k] = Maths.hypot(e[k], e[i]); + } + if (e[k] != 0.0) { + if (e[k + 1] < 0.0) { + e[k] = -e[k]; + } + for (int i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1.0; + } + e[k] = -e[k]; + if ((k + 1 < m) & (e[k] != 0.0)) { - e[j] = A[k][j]; - } - if (wantu & (k < nct)) { + // Apply the transformation. - // Place the transformation in U for subsequent back - // multiplication. + for (int i = k + 1; i < m; i++) { + work[i] = 0.0; + } + for (int j = k + 1; j < n; j++) { + for (int i = k + 1; i < m; i++) { + work[i] += e[j] * A[i][j]; + } + } + for (int j = k + 1; j < n; j++) { + double t = -e[j] / e[k + 1]; + for (int i = k + 1; i < m; i++) { + A[i][j] += t * work[i]; + } + } + } + if (wantv) { - for (int i = k; i < m; i++) { - U[i][k] = A[i][k]; + // Place the transformation in V for subsequent + // back multiplication. + + for (int i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } } - } - if (k < nrt) { + } - // Compute the k-th row transformation and place the - // k-th super-diagonal in e[k]. - // Compute 2-norm without under/overflow. - e[k] = 0; - for (int i = k+1; i < n; i++) { - e[k] = Maths.hypot(e[k],e[i]); + // Set up the final bidiagonal matrix or order p. + + int p = Math.min(n, m + 1); + if (nct < n) { + s[nct] = A[nct][nct]; + } + if (m < p) { + s[p - 1] = 0.0; + } + if (nrt + 1 < p) { + e[nrt] = A[nrt][p - 1]; + } + e[p - 1] = 0.0; + + // If required, generate U. + + if (wantu) { + for (int j = nct; j < nu; j++) { + for (int i = 0; i < m; i++) { + U[i][j] = 0.0; + } + U[j][j] = 1.0; } - if (e[k] != 0.0) { - if (e[k+1] < 0.0) { - e[k] = -e[k]; - } - for (int i = k+1; i < n; i++) { - e[i] /= e[k]; - } - e[k+1] += 1.0; + for (int k = nct - 1; k >= 0; k--) { + if (s[k] != 0.0) { + for (int j = k + 1; j < nu; j++) { + double t = 0; + for (int i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } + t = -t / U[k][k]; + for (int i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } + for (int i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } + U[k][k] = 1.0 + U[k][k]; + for (int i = 0; i < k - 1; i++) { + U[i][k] = 0.0; + } + } else { + for (int i = 0; i < m; i++) { + U[i][k] = 0.0; + } + U[k][k] = 1.0; + } } - e[k] = -e[k]; - if ((k+1 < m) & (e[k] != 0.0)) { + } - // Apply the transformation. + // If required, generate V. - for (int i = k+1; i < m; i++) { - work[i] = 0.0; - } - for (int j = k+1; j < n; j++) { - for (int i = k+1; i < m; i++) { - work[i] += e[j]*A[i][j]; - } - } - for (int j = k+1; j < n; j++) { - double t = -e[j]/e[k+1]; - for (int i = k+1; i < m; i++) { - A[i][j] += t*work[i]; - } - } + if (wantv) { + for (int k = n - 1; k >= 0; k--) { + if ((k < nrt) & (e[k] != 0.0)) { + for (int j = k + 1; j < nu; j++) { + double t = 0; + for (int i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } + t = -t / V[k + 1][k]; + for (int i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } + for (int i = 0; i < n; i++) { + V[i][k] = 0.0; + } + V[k][k] = 1.0; } - if (wantv) { + } - // Place the transformation in V for subsequent - // back multiplication. + // Main iteration loop for the singular values. - for (int i = k+1; i < n; i++) { - V[i][k] = e[i]; - } + int pp = p - 1; + int iter = 0; + double eps = Math.pow(2.0, -52.0); + while (p > 0) { + int k, kase; + + // Here is where a test for too many iterations would go. + + // This section of the program inspects for + // negligible elements in the s and e arrays. On + // completion the variables kase and k are set as follows. + + // kase = 1 if s(p) and e[k-1] are negligible and k

= -1; k--) { + if (k == -1) { + break; + } + if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { + e[k] = 0.0; + break; + } } - } - } - - // Set up the final bidiagonal matrix or order p. - - int p = Math.min(n,m+1); - if (nct < n) { - s[nct] = A[nct][nct]; - } - if (m < p) { - s[p-1] = 0.0; - } - if (nrt+1 < p) { - e[nrt] = A[nrt][p-1]; - } - e[p-1] = 0.0; - - // If required, generate U. - - if (wantu) { - for (int j = nct; j < nu; j++) { - for (int i = 0; i < m; i++) { - U[i][j] = 0.0; - } - U[j][j] = 1.0; - } - for (int k = nct-1; k >= 0; k--) { - if (s[k] != 0.0) { - for (int j = k+1; j < nu; j++) { - double t = 0; - for (int i = k; i < m; i++) { - t += U[i][k]*U[i][j]; - } - t = -t/U[k][k]; - for (int i = k; i < m; i++) { - U[i][j] += t*U[i][k]; - } - } - for (int i = k; i < m; i++ ) { - U[i][k] = -U[i][k]; - } - U[k][k] = 1.0 + U[k][k]; - for (int i = 0; i < k-1; i++) { - U[i][k] = 0.0; - } + if (k == p - 2) { + kase = 4; } else { - for (int i = 0; i < m; i++) { - U[i][k] = 0.0; - } - U[k][k] = 1.0; + int ks; + for (ks = p - 1; ks >= k; ks--) { + if (ks == k) { + break; + } + double t = (ks != p ? Math.abs(e[ks]) : 0.) + + (ks != k + 1 ? Math.abs(e[ks - 1]) : 0.); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0.0; + break; + } + } + if (ks == k) { + kase = 3; + } else if (ks == p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } } - } - } + k++; - // If required, generate V. + // Perform the task indicated by kase. - if (wantv) { - for (int k = n-1; k >= 0; k--) { - if ((k < nrt) & (e[k] != 0.0)) { - for (int j = k+1; j < nu; j++) { - double t = 0; - for (int i = k+1; i < n; i++) { - t += V[i][k]*V[i][j]; - } - t = -t/V[k+1][k]; - for (int i = k+1; i < n; i++) { - V[i][j] += t*V[i][k]; - } - } + switch (kase) { + + // Deflate negligible s(p). + + case 1: { + double f = e[p - 2]; + e[p - 2] = 0.0; + for (int j = p - 2; j >= k; j--) { + double t = Maths.hypot(s[j], f); + double cs = s[j] / t; + double sn = f / t; + s[j] = t; + if (j != k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (int i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } + } + break; + + // Split at negligible s(k). + + case 2: { + double f = e[k - 1]; + e[k - 1] = 0.0; + for (int j = k; j < p; j++) { + double t = Maths.hypot(s[j], f); + double cs = s[j] / t; + double sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (int i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } + } + break; + + // Perform one qr step. + + case 3: { + + // Calculate the shift. + + double scale = Math.max(Math.max(Math.max(Math.max( + Math.abs(s[p - 1]), Math.abs(s[p - 2])), Math.abs(e[p - 2])), + Math.abs(s[k])), Math.abs(e[k])); + double sp = s[p - 1] / scale; + double spm1 = s[p - 2] / scale; + double epm1 = e[p - 2] / scale; + double sk = s[k] / scale; + double ek = e[k] / scale; + double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; + double c = (sp * epm1) * (sp * epm1); + double shift = 0.0; + if ((b != 0.0) | (c != 0.0)) { + shift = Math.sqrt(b * b + c); + if (b < 0.0) { + shift = -shift; + } + shift = c / (b + shift); + } + double f = (sk + sp) * (sk - sp) + shift; + double g = sk * ek; + + // Chase zeros. + + for (int j = k; j < p - 1; j++) { + double t = Maths.hypot(f, g); + double cs = f / t; + double sn = g / t; + if (j != k) { + e[j - 1] = t; + } + f = cs * s[j] + sn * e[j]; + e[j] = cs * e[j] - sn * s[j]; + g = sn * s[j + 1]; + s[j + 1] = cs * s[j + 1]; + if (wantv) { + for (int i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } + t = Maths.hypot(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (int i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } + e[p - 2] = f; + iter += 1; + } + break; + + // Convergence. + + case 4: { + + // Make the singular values positive. + + if (s[k] <= 0.0) { + s[k] = (s[k] < 0.0 ? -s[k] : 0.0); + if (wantv) { + for (int i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } + + // Order the singular values. + + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + double t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (int i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } + if (wantu && (k < m - 1)) { + for (int i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } + k++; + } + iter = 0; + p--; + } + break; } - for (int i = 0; i < n; i++) { - V[i][k] = 0.0; - } - V[k][k] = 1.0; - } - } - - // Main iteration loop for the singular values. - - int pp = p-1; - int iter = 0; - double eps = Math.pow(2.0,-52.0); - while (p > 0) { - int k,kase; - - // Here is where a test for too many iterations would go. - - // This section of the program inspects for - // negligible elements in the s and e arrays. On - // completion the variables kase and k are set as follows. - - // kase = 1 if s(p) and e[k-1] are negligible and k

= -1; k--) { - if (k == -1) { - break; - } - if (Math.abs(e[k]) <= eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) { - e[k] = 0.0; - break; - } - } - if (k == p-2) { - kase = 4; - } else { - int ks; - for (ks = p-1; ks >= k; ks--) { - if (ks == k) { - break; - } - double t = (ks != p ? Math.abs(e[ks]) : 0.) + - (ks != k+1 ? Math.abs(e[ks-1]) : 0.); - if (Math.abs(s[ks]) <= eps*t) { - s[ks] = 0.0; - break; - } - } - if (ks == k) { - kase = 3; - } else if (ks == p-1) { - kase = 1; - } else { - kase = 2; - k = ks; - } - } - k++; - - // Perform the task indicated by kase. - - switch (kase) { - - // Deflate negligible s(p). - - case 1: { - double f = e[p-2]; - e[p-2] = 0.0; - for (int j = p-2; j >= k; j--) { - double t = Maths.hypot(s[j],f); - double cs = s[j]/t; - double sn = f/t; - s[j] = t; - if (j != k) { - f = -sn*e[j-1]; - e[j-1] = cs*e[j-1]; - } - if (wantv) { - for (int i = 0; i < n; i++) { - t = cs*V[i][j] + sn*V[i][p-1]; - V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1]; - V[i][j] = t; - } - } - } - } - break; - - // Split at negligible s(k). - - case 2: { - double f = e[k-1]; - e[k-1] = 0.0; - for (int j = k; j < p; j++) { - double t = Maths.hypot(s[j],f); - double cs = s[j]/t; - double sn = f/t; - s[j] = t; - f = -sn*e[j]; - e[j] = cs*e[j]; - if (wantu) { - for (int i = 0; i < m; i++) { - t = cs*U[i][j] + sn*U[i][k-1]; - U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1]; - U[i][j] = t; - } - } - } - } - break; - - // Perform one qr step. - - case 3: { - - // Calculate the shift. - - double scale = Math.max(Math.max(Math.max(Math.max( - Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])), - Math.abs(s[k])),Math.abs(e[k])); - double sp = s[p-1]/scale; - double spm1 = s[p-2]/scale; - double epm1 = e[p-2]/scale; - double sk = s[k]/scale; - double ek = e[k]/scale; - double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; - double c = (sp*epm1)*(sp*epm1); - double shift = 0.0; - if ((b != 0.0) | (c != 0.0)) { - shift = Math.sqrt(b*b + c); - if (b < 0.0) { - shift = -shift; - } - shift = c/(b + shift); - } - double f = (sk + sp)*(sk - sp) + shift; - double g = sk*ek; - - // Chase zeros. - - for (int j = k; j < p-1; j++) { - double t = Maths.hypot(f,g); - double cs = f/t; - double sn = g/t; - if (j != k) { - e[j-1] = t; - } - f = cs*s[j] + sn*e[j]; - e[j] = cs*e[j] - sn*s[j]; - g = sn*s[j+1]; - s[j+1] = cs*s[j+1]; - if (wantv) { - for (int i = 0; i < n; i++) { - t = cs*V[i][j] + sn*V[i][j+1]; - V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1]; - V[i][j] = t; - } - } - t = Maths.hypot(f,g); - cs = f/t; - sn = g/t; - s[j] = t; - f = cs*e[j] + sn*s[j+1]; - s[j+1] = -sn*e[j] + cs*s[j+1]; - g = sn*e[j+1]; - e[j+1] = cs*e[j+1]; - if (wantu && (j < m-1)) { - for (int i = 0; i < m; i++) { - t = cs*U[i][j] + sn*U[i][j+1]; - U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1]; - U[i][j] = t; - } - } - } - e[p-2] = f; - iter += 1; - } - break; - - // Convergence. - - case 4: { - - // Make the singular values positive. - - if (s[k] <= 0.0) { - s[k] = (s[k] < 0.0 ? -s[k] : 0.0); - if (wantv) { - for (int i = 0; i <= pp; i++) { - V[i][k] = -V[i][k]; - } - } - } - - // Order the singular values. - - while (k < pp) { - if (s[k] >= s[k+1]) { - break; - } - double t = s[k]; - s[k] = s[k+1]; - s[k+1] = t; - if (wantv && (k < n-1)) { - for (int i = 0; i < n; i++) { - t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t; - } - } - if (wantu && (k < m-1)) { - for (int i = 0; i < m; i++) { - t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t; - } - } - k++; - } - iter = 0; - p--; - } - break; - } - } - } + } + } /* ------------------------ Public Methods * ------------------------ */ - /** Return the left singular vectors - @return U - */ + /** + * Return the left singular vectors + * + * @return U + */ - public Matrix getU () { - return new Matrix(U,m,Math.min(m+1,n)); - } + public Matrix getU() { + return new Matrix(U, m, Math.min(m + 1, n)); + } - /** Return the right singular vectors - @return V - */ + /** + * Return the right singular vectors + * + * @return V + */ - public Matrix getV () { - return new Matrix(V,n,n); - } + public Matrix getV() { + return new Matrix(V, n, n); + } - /** Return the one-dimensional array of singular values - @return diagonal of S. - */ + /** + * Return the one-dimensional array of singular values + * + * @return diagonal of S. + */ - public double[] getSingularValues () { - return s; - } + public double[] getSingularValues() { + return s; + } - /** Return the diagonal matrix of singular values - @return S - */ + /** + * Return the diagonal matrix of singular values + * + * @return S + */ - public Matrix getS () { - Matrix X = new Matrix(n,n); - double[][] S = X.getArray(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - S[i][j] = 0.0; - } - S[i][i] = this.s[i]; - } - return X; - } + public Matrix getS() { + Matrix X = new Matrix(n, n); + double[][] S = X.getArray(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + S[i][j] = 0.0; + } + S[i][i] = this.s[i]; + } + return X; + } - /** Two norm - @return max(S) - */ + /** + * Two norm + * + * @return max(S) + */ - public double norm2 () { - return s[0]; - } + public double norm2() { + return s[0]; + } - /** Two norm condition number - @return max(S)/min(S) - */ + /** + * Two norm condition number + * + * @return max(S)/min(S) + */ - public double cond () { - return s[0]/s[Math.min(m,n)-1]; - } + public double cond() { + return s[0] / s[Math.min(m, n) - 1]; + } - /** Effective numerical matrix rank - @return Number of nonnegligible singular values. - */ + /** + * Effective numerical matrix rank + * + * @return Number of nonnegligible singular values. + */ - public int rank () { - double eps = Math.pow(2.0,-52.0); - double tol = Math.max(m,n)*s[0]*eps; - int r = 0; - for (int i = 0; i < s.length; i++) { - if (s[i] > tol) { - r++; - } - } - return r; - } + public int rank() { + double eps = Math.pow(2.0, -52.0); + double tol = Math.max(m, n) * s[0] * eps; + int r = 0; + for (int i = 0; i < s.length; i++) { + if (s[i] > tol) { + r++; + } + } + return r; + } } diff --git a/src/eva2/tools/math/Jama/util/Maths.java b/src/eva2/tools/math/Jama/util/Maths.java index 1484af67..f585f5cf 100644 --- a/src/eva2/tools/math/Jama/util/Maths.java +++ b/src/eva2/tools/math/Jama/util/Maths.java @@ -2,21 +2,23 @@ package eva2.tools.math.Jama.util; public class Maths { - /** sqrt(a^2 + b^2) without under/overflow. **/ + /** + * sqrt(a^2 + b^2) without under/overflow. * + */ - public static double hypot(double a, double b) { - double r; - double aa = Math.abs(a); - double bb = Math.abs(b); - if (aa > bb) { - r = b/a; - r = aa*Math.sqrt(1+r*r); - } else if (b != 0) { - r = a/b; - r = bb*Math.sqrt(1+r*r); - } else { - r = 0.0; - } - return r; - } + public static double hypot(double a, double b) { + double r; + double aa = Math.abs(a); + double bb = Math.abs(b); + if (aa > bb) { + r = b / a; + r = aa * Math.sqrt(1 + r * r); + } else if (b != 0) { + r = a / b; + r = bb * Math.sqrt(1 + r * r); + } else { + r = 0.0; + } + return r; + } } diff --git a/src/eva2/tools/math/Mathematics.java b/src/eva2/tools/math/Mathematics.java index 01665196..5cf22740 100644 --- a/src/eva2/tools/math/Mathematics.java +++ b/src/eva2/tools/math/Mathematics.java @@ -6,6 +6,7 @@ import eva2.tools.math.Jama.Matrix; import eva2.tools.math.interpolation.BasicDataSet; import eva2.tools.math.interpolation.InterpolationException; import eva2.tools.math.interpolation.SplineInterpolation; + import java.util.Arrays; import java.util.List; @@ -15,1466 +16,1425 @@ import java.util.List; * @author Andreas Dräger */ public class Mathematics { - /** - * Computes the full adjoint matrix. - * - * @param a - * @return - */ - public static double[][] adjoint(double[][] a) { - if (a == null) { - return null; - } - if (a.length != a[0].length) { - return null; - } - double[][] b = new double[a.length][a.length]; - for (int i = 0; i < a.length; i++) { + /** + * Computes the full adjoint matrix. + * + * @param a + * @return + */ + public static double[][] adjoint(double[][] a) { + if (a == null) { + return null; + } + if (a.length != a[0].length) { + return null; + } + double[][] b = new double[a.length][a.length]; + for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { b[i][j] = adjoint(a, i, j); } } - return b; - } + return b; + } - /** - * Computes the adjoint of the matrix element at the position (k, l). - * - * @param a - * @param k - * @param l - * @return - */ - public static double adjoint(double[][] a, int k, int l) { - return Math.pow(-1, k + l + 2) * determinant(submatrix(a, k, l)); - } + /** + * Computes the adjoint of the matrix element at the position (k, l). + * + * @param a + * @param k + * @param l + * @return + */ + public static double adjoint(double[][] a, int k, int l) { + return Math.pow(-1, k + l + 2) * determinant(submatrix(a, k, l)); + } - /** - * This computes the determinant of the given matrix - * - * @param matrix - * @return The determinant or null if there is no determinant (if the matrix - * is not square). - */ - public static double determinant(double[][] matrix) { - if (matrix == null) { - return 0; - } - if (matrix.length != matrix[0].length) { - return 0; - } - if (matrix.length == 1) { - return matrix[0][0]; - } - if (matrix.length == 2) { - return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; - } - if (matrix.length == 3) { - return matrix[0][0] * matrix[1][1] * matrix[2][2] + matrix[0][1] - * matrix[1][2] * matrix[2][0] + matrix[0][2] * matrix[1][0] - * matrix[2][1] - matrix[2][0] * matrix[1][1] * matrix[0][2] - - matrix[2][1] * matrix[1][2] * matrix[0][0] - matrix[2][2] - * matrix[1][0] * matrix[0][1]; - } + /** + * This computes the determinant of the given matrix + * + * @param matrix + * @return The determinant or null if there is no determinant (if the matrix + * is not square). + */ + public static double determinant(double[][] matrix) { + if (matrix == null) { + return 0; + } + if (matrix.length != matrix[0].length) { + return 0; + } + if (matrix.length == 1) { + return matrix[0][0]; + } + if (matrix.length == 2) { + return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + } + if (matrix.length == 3) { + return matrix[0][0] * matrix[1][1] * matrix[2][2] + matrix[0][1] + * matrix[1][2] * matrix[2][0] + matrix[0][2] * matrix[1][0] + * matrix[2][1] - matrix[2][0] * matrix[1][1] * matrix[0][2] + - matrix[2][1] * matrix[1][2] * matrix[0][0] - matrix[2][2] + * matrix[1][0] * matrix[0][1]; + } - double det = 0; - for (int k = 0; k < matrix.length; k++) { - if (matrix[0][k] != 0) { - det += matrix[0][k] * adjoint(matrix, 0, k); - } - } - return det; - } + double det = 0; + for (int k = 0; k < matrix.length; k++) { + if (matrix[0][k] != 0) { + det += matrix[0][k] * adjoint(matrix, 0, k); + } + } + return det; + } - /** - * Computes the root-Distance function. For example root = 2 gives the - * Euclidian Distance. - * - * @param x - * a vector - * @param y - * another vector - * @param root - * what kind of distance funktion - * @return the distance of x and y - * @throws Exception - * if x and y have different dimensions an exception is thrown. - */ - public static double dist(double[] x, double[] y, int root) { - if (x.length != y.length) { - throw new RuntimeException( - "The vectors x and y must have the same dimension"); - } - if (root == 0) { - throw new RuntimeException("There is no 0-root!"); - } - double d = 0; - for (int i = 0; i < x.length; i++) { + /** + * Computes the root-Distance function. For example root = 2 gives the + * Euclidian Distance. + * + * @param x a vector + * @param y another vector + * @param root what kind of distance funktion + * @return the distance of x and y + * @throws Exception if x and y have different dimensions an exception is thrown. + */ + public static double dist(double[] x, double[] y, int root) { + if (x.length != y.length) { + throw new RuntimeException( + "The vectors x and y must have the same dimension"); + } + if (root == 0) { + throw new RuntimeException("There is no 0-root!"); + } + double d = 0; + for (int i = 0; i < x.length; i++) { d += Math.pow(Math.abs(x[i] - y[i]), root); } - return Math.pow(d, (double) 1 / root); - } + return Math.pow(d, (double) 1 / root); + } - /** - * Computes the euclidian distance function. - * - * @param x - * a vector - * @param y - * another vector - * @param root - * what kind of distance funktion - * @return the distance of x and y - * @throws Exception - * if x and y have different dimensions an exception is thrown. - */ - public static double euclidianDist(double[] x, double[] y) { - if (x.length != y.length) { - throw new RuntimeException( - "The vectors x and y must have the same dimension"); - } - double d = 0; - for (int i = 0; i < x.length; i++) { + /** + * Computes the euclidian distance function. + * + * @param x a vector + * @param y another vector + * @param root what kind of distance funktion + * @return the distance of x and y + * @throws Exception if x and y have different dimensions an exception is thrown. + */ + public static double euclidianDist(double[] x, double[] y) { + if (x.length != y.length) { + throw new RuntimeException( + "The vectors x and y must have the same dimension"); + } + double d = 0; + for (int i = 0; i < x.length; i++) { d += Math.pow(Math.abs(x[i] - y[i]), 2); } - return Math.sqrt(d); - } + return Math.sqrt(d); + } - /** - * Expand a vector to a higher dimension (len) by filling it up with a - * constant value. - * - * @param x - * @param len - * @param v - * @return - */ - public static double[] expandVector(double[] x, int len, double v) { - if (len <= x.length) {// not really an error, just perform identity - // System.err.println("Error, invalid length in expandVector, expecting l>" - // + x.length); - return x; - } else { - double[] expanded = new double[len]; - System.arraycopy(x, 0, expanded, 0, x.length); - for (int i = x.length; i < expanded.length; i++) { + /** + * Expand a vector to a higher dimension (len) by filling it up with a + * constant value. + * + * @param x + * @param len + * @param v + * @return + */ + public static double[] expandVector(double[] x, int len, double v) { + if (len <= x.length) {// not really an error, just perform identity + // System.err.println("Error, invalid length in expandVector, expecting l>" + // + x.length); + return x; + } else { + double[] expanded = new double[len]; + System.arraycopy(x, 0, expanded, 0, x.length); + for (int i = x.length; i < expanded.length; i++) { expanded[i] = v; } - return expanded; - } - } + return expanded; + } + } - /** - * Fill the front of an array with data from a given source array. - * - * @param dest - * @param src - */ - public static void fillFront(double[] dest, double[] src) { - System.arraycopy(src, 0, dest, 0, Math.min(dest.length, src.length)); - } + /** + * Fill the front of an array with data from a given source array. + * + * @param dest + * @param src + */ + public static void fillFront(double[] dest, double[] src) { + System.arraycopy(src, 0, dest, 0, Math.min(dest.length, src.length)); + } - /** - * Return first multiple of interval which is larger than len. - * - * @param len - * @param interval - * @return - */ - public static double firstMultipleAbove(double len, double interval) { - double startVal, dn = (len / interval); - startVal = Math.round(dn - 0.5) * interval; + /** + * Return first multiple of interval which is larger than len. + * + * @param len + * @param interval + * @return + */ + public static double firstMultipleAbove(double len, double interval) { + double startVal, dn = (len / interval); + startVal = Math.round(dn - 0.5) * interval; - if (startVal < len || (len == 0)) { - startVal += interval; - } - return startVal; - } + if (startVal < len || (len == 0)) { + startVal += interval; + } + return startVal; + } - /** - * Return the vector of interval length values in any dimension. - * ret[i]=range[i][1]-range[i][0]; - * - * @param range - * @return - */ - public static double[] getAbsRange(double[][] range) { - double[] ret = new double[range.length]; - for (int i = 0; i < ret.length; i++) { - ret[i] = range[i][1] - range[i][0]; - } - return ret; - } + /** + * Return the vector of interval length values in any dimension. + * ret[i]=range[i][1]-range[i][0]; + * + * @param range + * @return + */ + public static double[] getAbsRange(double[][] range) { + double[] ret = new double[range.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = range[i][1] - range[i][0]; + } + return ret; + } - /** - * Calculate the average length of the range intervals over all dimensions. - * - * @param range - * @return the average length of the range intervals - */ - public static double getAvgRange(double[][] range) { - double sum = 0.; - for (int i = 0; i < range.length; i++) { + /** + * Calculate the average length of the range intervals over all dimensions. + * + * @param range + * @return the average length of the range intervals + */ + public static double getAvgRange(double[][] range) { + double sum = 0.; + for (int i = 0; i < range.length; i++) { sum += (range[i][1] - range[i][0]); } - return sum / range.length; - } + return sum / range.length; + } - /** - * Calculates the norm of the given vector relative to the problem range. - * - * @param vector - * a double vector within the range - * @param range - * the range in each dimension - * @return measure of the length relative to the problem range - */ - public static double getRelativeLength(double[] vector, double[][] range) { - double sumV = 0; - double sumR = 0; - for (int i = 0; i < range.length; i++) { - sumV += Math.pow(vector[i], 2); - sumR += Math.pow(range[i][1] - range[i][0], 2); - } - sumV = Math.sqrt(sumV); - sumR = Math.sqrt(sumR); - return sumV / sumR; - } + /** + * Calculates the norm of the given vector relative to the problem range. + * + * @param vector a double vector within the range + * @param range the range in each dimension + * @return measure of the length relative to the problem range + */ + public static double getRelativeLength(double[] vector, double[][] range) { + double sumV = 0; + double sumR = 0; + for (int i = 0; i < range.length; i++) { + sumV += Math.pow(vector[i], 2); + sumR += Math.pow(range[i][1] - range[i][0], 2); + } + sumV = Math.sqrt(sumV); + sumR = Math.sqrt(sumR); + return sumV / sumR; + } - /** - * Set rotation matrix entries along i/j axis. w is expected in radians. - * - * @param tmp - * @param i - * @param j - * @param w - */ - public static void getRotationEntriesSingleAxis(Matrix tmp, int i, int j, - double w) { - double cosw = Math.cos(w); - double sinw = Math.sin(w); - tmp.set(i, i, cosw); - tmp.set(i, j, sinw); - tmp.set(j, i, -sinw); - tmp.set(j, j, cosw); - } + /** + * Set rotation matrix entries along i/j axis. w is expected in radians. + * + * @param tmp + * @param i + * @param j + * @param w + */ + public static void getRotationEntriesSingleAxis(Matrix tmp, int i, int j, + double w) { + double cosw = Math.cos(w); + double sinw = Math.sin(w); + tmp.set(i, i, cosw); + tmp.set(i, j, sinw); + tmp.set(j, i, -sinw); + tmp.set(j, j, cosw); + } - public static Matrix getRotationMatrix(double w, int dim) { - Matrix A = Matrix.identity(dim, dim); - Matrix tmp = Matrix.identity(dim, dim); + public static Matrix getRotationMatrix(double w, int dim) { + Matrix A = Matrix.identity(dim, dim); + Matrix tmp = Matrix.identity(dim, dim); - for (int i = 1; i < dim; i++) { - // System.out.println("deg: "+(w/Math.PI)*180); - // make partial rotation matrix - getRotationEntriesSingleAxis(tmp, i - 1, i, w); - A = tmp.times(A); // add to resulting rotation - // reset tmp matrix to unity - resetRotationEntriesSingleAxis(tmp, i - 1, i); - } - // Matrix vec = new Matrix(dim, 1); - // for (int i=0; i=0) { - return i; - } - } - return -1; - } - - /** - * Check if all numbers are valid (not NaN) and finite. Returns - * -1 if this is the case or the index of the first invalid number. - * - * @param v - * @return - */ - public static int areFinite(double ... v) { - for (int i=0; i upper)) { + /** + * Check if a number is valid (not NaN) and finite. + * + * @param v + * @return + */ + public static boolean isFinite(double v) { + return (!Double.isInfinite(v) && !Double.isNaN(v)); + } + + /** + * Check if all numbers are valid (not NaN) and finite. Returns + * -1 if this is the case or the index of the first row with an invalid number. + * + * @param v + * @return + */ + public static int areFinite(double[][] v) { + for (int i = 0; i < v.length; i++) { + if (areFinite(v[i]) >= 0) { + return i; + } + } + return -1; + } + + /** + * Check if all numbers are valid (not NaN) and finite. Returns + * -1 if this is the case or the index of the first invalid number. + * + * @param v + * @return + */ + public static int areFinite(double... v) { + for (int i = 0; i < v.length; i++) { + if (Double.isInfinite(v[i]) || Double.isNaN(v[i])) { + return i; + } + } + return -1; + } + + /** + * Check whether the given value lies within the interval in every + * dimension. + * + * @param x + * @param range + * @return true if the vector lies within the range, else false + */ + public static boolean isInRange(double v, double lower, double upper) { + if (v < lower || (v > upper)) { + return false; + } + return true; + } + + /** + * Check whether the given vector lies within the range in every dimension. + * + * @param x + * @param range + * @return true if the vector lies within the range, else false + */ + public static boolean isInRange(double[] x, double[][] range) { + for (int i = 0; i < x.length; i++) { + if (x[i] < range[i][0] || (x[i] > range[i][1])) { return false; } - return true; - } + } + return true; + } - /** - * Check whether the given vector lies within the range in every dimension. - * - * @param x - * @param range - * @return true if the vector lies within the range, else false - */ - public static boolean isInRange(double[] x, double[][] range) { - for (int i = 0; i < x.length; i++) { - if (x[i] < range[i][0] || (x[i] > range[i][1])) { - return false; - } - } - return true; - } - - /** - * Returns false if a column vector contains NaN, its squared sum is NaN or the - * absolute sum is smaller than 10^-18. - * - * @param d - * @return - */ - public static boolean isValidVec(double[][] d) { - for (int i=0; i dblArrList, boolean interpolate) { - java.util.Collections.sort(dblArrList, new DoubleArrayComparator()); // by - // default, - // the - // comparator - // uses - // pareto - // dominance - - int len = dblArrList.size(); - if (len % 2 != 0) { - return dblArrList.get((len - 1) / 2); + if (in.length == 1) { + return in[0]; + } else if (in.length == 2) { + return (in[0] + in[1]) / 2.; + } else { + Arrays.sort(in); + if (in.length % 2 != 0) { + return in[(in.length - 1) / 2]; + } else { + return (in[in.length / 2] + in[(in.length / 2) + 1]) / 2.; } - else { - double[] med = dblArrList.get(len / 2).clone(); - if (interpolate) { - vvAdd(med, dblArrList.get((len / 2) + 1), med); - svDiv(2, med, med); - } - return med; - } - } + } + } - - public static double median2(double[] vector, boolean clone){ - double[] in; - if (clone){ - in = (double[]) vector.clone(); - }else{ - in = vector; - } - if(in.length == 0){ - return 0; - } - Arrays.sort(in); - return in[(int) Math.floor(((double) in.length) / 2.0)]; - } - - public static double variance(double[] vector){ - double mean = Mathematics.mean(vector); - double result = 0.0; - for(int i=0; i dblArrList, boolean interpolate) { + java.util.Collections.sort(dblArrList, new DoubleArrayComparator()); // by + // default, + // the + // comparator + // uses + // pareto + // dominance + + int len = dblArrList.size(); + if (len % 2 != 0) { + return dblArrList.get((len - 1) / 2); + } else { + double[] med = dblArrList.get(len / 2).clone(); + if (interpolate) { + vvAdd(med, dblArrList.get((len / 2) + 1), med); + svDiv(2, med, med); + } + return med; + } + } + + + public static double median2(double[] vector, boolean clone) { + double[] in; + if (clone) { + in = (double[]) vector.clone(); + } else { + in = vector; + } + if (in.length == 0) { + return 0; + } + Arrays.sort(in); + return in[(int) Math.floor(((double) in.length) / 2.0)]; + } + + public static double variance(double[] vector) { + double mean = Mathematics.mean(vector); + double result = 0.0; + for (int i = 0; i < vector.length; i++) { + result += Math.pow(vector[i] - mean, 2); + } + return result; + } + + public static double stdDev(double[] vector) { + double result = variance(vector); + result = Math.sqrt(result); + return result; + } + + public static double tTestEqSizeEqVar(double[] vector1, double[] vector2) { + double n = (double) vector1.length; + double mean1 = mean(vector1); + double mean2 = mean(vector2); + double stdDev1 = stdDev(vector1); + double stdDev2 = stdDev(vector2); + double sX1X2 = Math.sqrt((Math.pow(stdDev1, 2) + Math.pow(stdDev2, 2)) / 2); + double result = (mean1 - mean2) / (Math.sqrt(2 / n) * sX1X2); + return result; + } + + public static double tTestUnEqSizeEqVar(double[] vector1, double[] vector2) { + double n1 = (double) vector1.length; + double n2 = (double) vector2.length; + double mean1 = mean(vector1); + double mean2 = mean(vector2); + double stdDev1 = stdDev(vector1); + double stdDev2 = stdDev(vector2); + double sX1X2 = Math.sqrt(((n1 - 1) * Math.pow(stdDev1, 2) + (n2 - 1) * Math.pow(stdDev2, 2)) / (n1 + n2 - 2)); + double result = (mean1 - mean2) / (sX1X2 * Math.sqrt(1 / n1 + 1 / n2)); + return result; + } + + public static double tTestUnEqSizeUnEqVar(double[] vector1, double[] vector2) { + double n1 = (double) vector1.length; + double n2 = (double) vector2.length; + double mean1 = mean(vector1); + double mean2 = mean(vector2); + double stdDev1 = stdDev(vector1); + double stdDev2 = stdDev(vector2); + double sX1X2 = Math.sqrt((Math.pow(stdDev1, 2) / n1) + (Math.pow(stdDev2, 2) / n2)); + double result = (mean1 - mean2) / sX1X2; + return result; + } + + public static double min(double[] vals) { + double minVal = vals[0]; + for (int i = 1; i < vals.length; i++) { minVal = Math.min(minVal, vals[i]); } - return minVal; - } + return minVal; + } - /** - * Computes the 2-norm of an array of doubles. - * - * @param doubles - * the array of double - * @return the 2-norm of the elements - */ - public static double norm(double[] d) { - double sqSum = 0; - for (int i = 0; i < d.length; i++) { - sqSum += d[i] * d[i]; - } - return Math.sqrt(sqSum); - } + /** + * Computes the 2-norm of an array of doubles. + * + * @param doubles the array of double + * @return the 2-norm of the elements + */ + public static double norm(double[] d) { + double sqSum = 0; + for (int i = 0; i < d.length; i++) { + sqSum += d[i] * d[i]; + } + return Math.sqrt(sqSum); + } - /** - * Normalizes the doubles in the array by their sum, so that they add up to - * one. - * - * @param doubles - * the array of double - * @exception IllegalArgumentException - * if sum is Zero or NaN - */ - public static double[] normalizeSum(double[] v) { - double[] res = new double[v.length]; - svMult(1. / sum(v), v, res); - return res; - } + /** + * Normalizes the doubles in the array by their sum, so that they add up to + * one. + * + * @param doubles the array of double + * @throws IllegalArgumentException if sum is Zero or NaN + */ + public static double[] normalizeSum(double[] v) { + double[] res = new double[v.length]; + svMult(1. / sum(v), v, res); + return res; + } - /** - * Normalizes the doubles in the array by their sum, so that they add up to - * one. - * - * @param doubles - * the array of double - * @exception IllegalArgumentException - * if sum is Zero or NaN - */ - public static void normalizeSum(double[] v, double[] res) { - svMult(1. / sum(v), v, res); - } + /** + * Normalizes the doubles in the array by their sum, so that they add up to + * one. + * + * @param doubles the array of double + * @throws IllegalArgumentException if sum is Zero or NaN + */ + public static void normalizeSum(double[] v, double[] res) { + svMult(1. / sum(v), v, res); + } - /** - * Normalize the given vector to an euclidian length of 1. - * - * @param v - * @return - */ - public static double[] normVect(double[] v) { - return svDiv(norm(v), v); - } + /** + * Normalize the given vector to an euclidian length of 1. + * + * @param v + * @return + */ + public static double[] normVect(double[] v) { + return svDiv(norm(v), v); + } - /** - * Normalize the given vector to an euclidian length of 1. - * - * @param v - * @return - */ - public static void normVect(double[] v, double[] res) { - svDiv(norm(v), v, res); - } + /** + * Normalize the given vector to an euclidian length of 1. + * + * @param v + * @return + */ + public static void normVect(double[] v, double[] res) { + svDiv(norm(v), v, res); + } - /** - * Return the product over a double vector. - * - * @param vals - * @return - */ - public static double product(double[] vals) { - double prod = 1.; - for (int i = 0; i < vals.length; i++) { - prod *= vals[i]; - } - return prod; - } + /** + * Return the product over a double vector. + * + * @param vals + * @return + */ + public static double product(double[] vals) { + double prod = 1.; + for (int i = 0; i < vals.length; i++) { + prod *= vals[i]; + } + return prod; + } - // /** - // * Normalizes the doubles in the array using the given value so that they - // sum up to 1. - // * - // * @param doubles the array of double - // * @param sum the value by which the doubles are to be normalized - // * @exception IllegalArgumentException if sum is zero or NaN - // */ - // public static void normalize(double[] v, double sum, double[] res) { - // if (Double.isNaN(sum)) { - // throw new IllegalArgumentException("Can't normalize array. Sum is NaN."); - // } - // if (sum == 0) { - // // Maybe this should just be a return. - // throw new - // IllegalArgumentException("Can't normalize array. Sum is zero."); - // } - // svMult(1/sum, v, res); - // } + // /** + // * Normalizes the doubles in the array using the given value so that they + // sum up to 1. + // * + // * @param doubles the array of double + // * @param sum the value by which the doubles are to be normalized + // * @exception IllegalArgumentException if sum is zero or NaN + // */ + // public static void normalize(double[] v, double sum, double[] res) { + // if (Double.isNaN(sum)) { + // throw new IllegalArgumentException("Can't normalize array. Sum is NaN."); + // } + // if (sum == 0) { + // // Maybe this should just be a return. + // throw new + // IllegalArgumentException("Can't normalize array. Sum is zero."); + // } + // svMult(1/sum, v, res); + // } - /** - * Project the values in x to the range given. The range must be an vector - * of 2d-arrays each of which containing lower and upper bound in the i-th - * dimension. x must not be longer than the available ranges. Values - * exceeding the bounds are set on the bound. The number of bound violations - * is returned. - * - * @param x - * @param range - * @return - */ - public static int projectToRange(double[] x, double[][] range) { - int viols = 0; - if (x.length > range.length) { - System.err - .println("Invalid vector length, x is longer than range! (Mathematics.projectToRange)"); + /** + * Project the values in x to the range given. The range must be an vector + * of 2d-arrays each of which containing lower and upper bound in the i-th + * dimension. x must not be longer than the available ranges. Values + * exceeding the bounds are set on the bound. The number of bound violations + * is returned. + * + * @param x + * @param range + * @return + */ + public static int projectToRange(double[] x, double[][] range) { + int viols = 0; + if (x.length > range.length) { + System.err + .println("Invalid vector length, x is longer than range! (Mathematics.projectToRange)"); + } + for (int i = 0; i < x.length; i++) { + if (x[i] < range[i][0]) { + viols++; + x[i] = range[i][0]; + } else if (x[i] > range[i][1]) { + viols++; + x[i] = range[i][1]; } - for (int i = 0; i < x.length; i++) { - if (x[i] < range[i][0]) { - viols++; - x[i] = range[i][0]; - } else if (x[i] > range[i][1]) { - viols++; - x[i] = range[i][1]; - } - } - return viols; - } + } + return viols; + } - /** - * Project the value to the range given. - * - * @param v - * @param min - * @param max - * @return the closest value to v within [min,max] - */ - public static double projectValue(double v, double min, double max) { - double value; - if (v < min) { - value = min; - } else if (v > max) { - value = max; - } else { - value = v; - } - return value; - } + /** + * Project the value to the range given. + * + * @param v + * @param min + * @param max + * @return the closest value to v within [min,max] + */ + public static double projectValue(double v, double min, double max) { + double value; + if (v < min) { + value = min; + } else if (v > max) { + value = max; + } else { + value = v; + } + return value; + } - /** - * Create a random vector, the components will be set to Gaussian - * distributed values with mean zero and the given standard deviation. - * - * @param dim The desired dimension - * @param stdDev The Gaussian standard deviation - * @return random vector - */ - public static double[] randomVector(final int dim, final double stdDev) { - double[] vect = new double[dim]; - for (int j = 0; j < vect.length; j++) { - vect[j] = RNG.gaussianDouble(stdDev); - } - return vect; - } + /** + * Create a random vector, the components will be set to Gaussian + * distributed values with mean zero and the given standard deviation. + * + * @param dim The desired dimension + * @param stdDev The Gaussian standard deviation + * @return random vector + */ + public static double[] randomVector(final int dim, final double stdDev) { + double[] vect = new double[dim]; + for (int j = 0; j < vect.length; j++) { + vect[j] = RNG.gaussianDouble(stdDev); + } + return vect; + } - /** - * Reflect the entries of x which violate the bounds to within the range. - * Return the number of violating dimensions. - * - * @param x - * @param range - * @return The number of violating dimensions - */ - public static int reflectBounds(double[] x, double[][] range) { - int viols = 0; - double d = 0.; - for (int i = 0; i < x.length; i++) { - double dimLen = range[i][1] - range[i][0]; - if (dimLen <= 0.) { - EVAERROR.errorMsgOnce("Error in reflectBounds: empty range! (possibly multiple errors)"); - } else { - if (x[i] < range[i][0]) { - viols++; - d = range[i][0] - x[i]; - while (d > dimLen) - d -= dimLen; // avoid violating the other bound - // immediately - x[i] = range[i][0] + d; - } else if (x[i] > range[i][1]) { - viols++; - d = x[i] - range[i][1]; - while (d > dimLen) { - d -= dimLen; // avoid violating the other bound - } - // immediately - x[i] = range[i][1] - d; - } - } - } - return viols; - } - - /** - * Simple version of reflection of a value moving by a step and bouncing of - * min and max values like a pool ball. Precondition is min <= val <= max, - * post condition is min <= retVal <= max. - * - * @param val - * @param step - * @param min - * @param max - * @return - */ - public static double reflectValue(double val, double step, double min, - double max) { - while (step > (max - min)) { - step -= (max - min); - } - if ((val + step) > max) { - return (2 * max - val - step); - } - if ((val + step) < min) { - return (2 * min - val - step); - } - return (val += step); - } - - /** - * Computes the relative distance of vector x to vector y. Therefore the - * difference of x[i] and y[i] is divided by y[i] for every i. If y[i] is - * zero, the default value def is used instead. The sum of these differences - * gives the distance function. - * - * @param x - * A vector - * @param y - * The reference vector - * @param def - * The default value to be use to avoid division by zero. - * @return The relative distance of x to y. - * @throws Exception - */ - public static double relDist(double[] x, double[] y, double def) - throws Exception { - if (x.length != y.length) { - throw new Exception("The vectors x and y must have the same dimension"); - } - double d = 0; - for (int i = 0; i < x.length; i++) { - if (y[i] != 0) { - d += Math.pow(((x[i] - y[i]) / y[i]), 2); - } else { - d += def; - } - } - return d; - } - - /** - * Reset single axis rotation matrix to unity. - */ - public static void resetRotationEntriesSingleAxis(Matrix tmp, int i, int j) { - tmp.set(i, i, 1); - tmp.set(i, j, 0); - tmp.set(j, i, 0); - tmp.set(j, j, 1); - } - - public static void revertArray(Object[] src, Object[] dst) { - if (dst.length >= src.length) { - for (int i = 0; i < src.length; i++) { - dst[src.length - i - 1] = src[i]; - } - } else { - System.err.println("Mismatching array lengths!"); - } - } - - /** - * Rotate the vector by angle alpha around axis i/j - * - * @param vect - * @param alpha - * @param i - * @param j - */ - public static void rotate(double[] vect, double alpha, int i, int j) { - double xi = vect[i]; - double xj = vect[j]; - vect[i] = (xi * Math.cos(alpha)) - (xj * Math.sin(alpha)); - vect[j] = (xi * Math.sin(alpha)) + (xj * Math.cos(alpha)); - } - - /** - * Rotate a given double vector using a rotation matrix. If the matrix is - * null, x will be returned unchanged. Matrix dimensions must fit. - * - * @param x - * @param rotMatrix - * @return the rotated vector - */ - public static double[] rotate(double[] x, Matrix rotMatrix) { - if (rotMatrix != null) { - Matrix resVec = rotMatrix.times(new Matrix(x, x.length)); - x = resVec.getColumnPackedCopy(); - return x; - } else { - return x; + /** + * Reflect the entries of x which violate the bounds to within the range. + * Return the number of violating dimensions. + * + * @param x + * @param range + * @return The number of violating dimensions + */ + public static int reflectBounds(double[] x, double[][] range) { + int viols = 0; + double d = 0.; + for (int i = 0; i < x.length; i++) { + double dimLen = range[i][1] - range[i][0]; + if (dimLen <= 0.) { + EVAERROR.errorMsgOnce("Error in reflectBounds: empty range! (possibly multiple errors)"); + } else { + if (x[i] < range[i][0]) { + viols++; + d = range[i][0] - x[i]; + while (d > dimLen) + d -= dimLen; // avoid violating the other bound + // immediately + x[i] = range[i][0] + d; + } else if (x[i] > range[i][1]) { + viols++; + d = x[i] - range[i][1]; + while (d > dimLen) { + d -= dimLen; // avoid violating the other bound + } + // immediately + x[i] = range[i][1] - d; + } } - } + } + return viols; + } - /** - * Rotate the vector along all axes by angle alpha or a uniform random value - * in [-alpha, alpha] if randomize is true. - * - * @param vect - * @param alpha - * @param randomize - */ - public static void rotateAllAxes(double[] vect, double alpha, - boolean randomize) { - for (int i = 0; i < vect.length - 1; i++) { - for (int j = i + 1; j < vect.length; j++) { - if (randomize) { - rotate(vect, RNG.randomDouble(-alpha, alpha), i, j); - } - else { - rotate(vect, alpha, i, j); - } - } - } - } + /** + * Simple version of reflection of a value moving by a step and bouncing of + * min and max values like a pool ball. Precondition is min <= val <= max, + * post condition is min <= retVal <= max. + * + * @param val + * @param step + * @param min + * @param max + * @return + */ + public static double reflectValue(double val, double step, double min, + double max) { + while (step > (max - min)) { + step -= (max - min); + } + if ((val + step) > max) { + return (2 * max - val - step); + } + if ((val + step) < min) { + return (2 * min - val - step); + } + return (val += step); + } - /** - * Rotate the vector along all axes i/j by angle alphas[i][j]. - * - * @param vect - * @param alphas - */ - public static void rotateAllAxes(double[] vect, double[][] alphas) { - for (int i = 0; i < vect.length - 1; i++) { - for (int j = i + 1; j < vect.length; j++) { - rotate(vect, alphas[i][j], i, j); - } - } - } + /** + * Computes the relative distance of vector x to vector y. Therefore the + * difference of x[i] and y[i] is divided by y[i] for every i. If y[i] is + * zero, the default value def is used instead. The sum of these differences + * gives the distance function. + * + * @param x A vector + * @param y The reference vector + * @param def The default value to be use to avoid division by zero. + * @return The relative distance of x to y. + * @throws Exception + */ + public static double relDist(double[] x, double[] y, double def) + throws Exception { + if (x.length != y.length) { + throw new Exception("The vectors x and y must have the same dimension"); + } + double d = 0; + for (int i = 0; i < x.length; i++) { + if (y[i] != 0) { + d += Math.pow(((x[i] - y[i]) / y[i]), 2); + } else { + d += def; + } + } + return d; + } - /** - * Scale a range by the given factor, meaning that the interval in each - * dimension is extended (fact>1) or reduced (fact < 1) by the defined ratio - * around the center. - * - * @param rangeScaleFact - * @param range - */ - public static void scaleRange(double rangeScaleFact, double[][] range) { - double[] intervalLengths = Mathematics.getAbsRange(range); - double[] tmpInts = Mathematics.svMult(rangeScaleFact, intervalLengths); - Mathematics.vvSub(tmpInts, intervalLengths, tmpInts); // this is what - // must be added - // to range - // interval - for (int i = 0; i < range.length; i++) { - range[i][0] -= tmpInts[i] / 2; - range[i][1] += tmpInts[i] / 2; - } - } + /** + * Reset single axis rotation matrix to unity. + */ + public static void resetRotationEntriesSingleAxis(Matrix tmp, int i, int j) { + tmp.set(i, i, 1); + tmp.set(i, j, 0); + tmp.set(j, i, 0); + tmp.set(j, j, 1); + } - /** - * Shift bounds by a constant value in every dimension. - * - * @param range - * @return - */ - public static void shiftRange(double[][] range, double dist) { - for (int i = 0; i < range.length; i++) { - svAdd(dist, range[i]); - } - } + public static void revertArray(Object[] src, Object[] dst) { + if (dst.length >= src.length) { + for (int i = 0; i < src.length; i++) { + dst[src.length - i - 1] = src[i]; + } + } else { + System.err.println("Mismatching array lengths!"); + } + } - /** - * Shift bounds by a constant value in every dimension. The dists must be of - * dimensions as the range. - * - * @param range - * @return - */ - public static void shiftRange(double[][] range, double[] dists) { - for (int i = 0; i < range.length; i++) { - svAdd(dists[i], range[i]); - } - } + /** + * Rotate the vector by angle alpha around axis i/j + * + * @param vect + * @param alpha + * @param i + * @param j + */ + public static void rotate(double[] vect, double alpha, int i, int j) { + double xi = vect[i]; + double xj = vect[j]; + vect[i] = (xi * Math.cos(alpha)) - (xj * Math.sin(alpha)); + vect[j] = (xi * Math.sin(alpha)) + (xj * Math.cos(alpha)); + } - /** - * Computes a spline interpolation of the two point (x0,f0) and (x1,f1). - * - * @param x - * @param x0 - * @param x1 - * @param f0 - * @param f1 - * @return If an error with the spline occurs, a linear interpolation will - * be returned. - */ - public static double splineInterpolation(double x, double x0, double x1, - double f0, double f1) { - try { - double[] t = { x0, x1 }, f = { f0, f1 }; - SplineInterpolation spline = new SplineInterpolation( - new BasicDataSet(t, f, 1)); - return spline.getY(x); - } catch (InterpolationException e) { - e.printStackTrace(); - } - return linearInterpolation(x, x0, x1, f0, f1); - } + /** + * Rotate a given double vector using a rotation matrix. If the matrix is + * null, x will be returned unchanged. Matrix dimensions must fit. + * + * @param x + * @param rotMatrix + * @return the rotated vector + */ + public static double[] rotate(double[] x, Matrix rotMatrix) { + if (rotMatrix != null) { + Matrix resVec = rotMatrix.times(new Matrix(x, x.length)); + x = resVec.getColumnPackedCopy(); + return x; + } else { + return x; + } + } - /** - * This computes the submatrix of the given matrix as a result by scraching - * out the row k and the column l. - * - * @param a - * @param k - * @param l - * @return - */ - public static double[][] submatrix(double[][] a, int k, int l) { - double b[][] = new double[a.length - 1][a[0].length - 1]; - int i, j, m = 0, n = 0; + /** + * Rotate the vector along all axes by angle alpha or a uniform random value + * in [-alpha, alpha] if randomize is true. + * + * @param vect + * @param alpha + * @param randomize + */ + public static void rotateAllAxes(double[] vect, double alpha, + boolean randomize) { + for (int i = 0; i < vect.length - 1; i++) { + for (int j = i + 1; j < vect.length; j++) { + if (randomize) { + rotate(vect, RNG.randomDouble(-alpha, alpha), i, j); + } else { + rotate(vect, alpha, i, j); + } + } + } + } - for (i = 0; i < a.length; i++) { - if (i == k) { - continue; - } - for (j = 0; j < a[0].length; j++) { - if (j == l) { - continue; - } - b[m][n++] = a[i][j]; - } - m++; - n = 0; - } + /** + * Rotate the vector along all axes i/j by angle alphas[i][j]. + * + * @param vect + * @param alphas + */ + public static void rotateAllAxes(double[] vect, double[][] alphas) { + for (int i = 0; i < vect.length - 1; i++) { + for (int j = i + 1; j < vect.length; j++) { + rotate(vect, alphas[i][j], i, j); + } + } + } - return b; - } + /** + * Scale a range by the given factor, meaning that the interval in each + * dimension is extended (fact>1) or reduced (fact < 1) by the defined ratio + * around the center. + * + * @param rangeScaleFact + * @param range + */ + public static void scaleRange(double rangeScaleFact, double[][] range) { + double[] intervalLengths = Mathematics.getAbsRange(range); + double[] tmpInts = Mathematics.svMult(rangeScaleFact, intervalLengths); + Mathematics.vvSub(tmpInts, intervalLengths, tmpInts); // this is what + // must be added + // to range + // interval + for (int i = 0; i < range.length; i++) { + range[i][0] -= tmpInts[i] / 2; + range[i][1] += tmpInts[i] / 2; + } + } - /** - * Computes the sum of the elements of an array of doubles. - * - * @param doubles - * the array of double - * @return the sum of the elements - */ - public static double sum(double[] doubles) { - double sum = 0; - for (int i = 0; i < doubles.length; i++) { - sum += doubles[i]; - } - return sum; - } + /** + * Shift bounds by a constant value in every dimension. + * + * @param range + * @return + */ + public static void shiftRange(double[][] range, double dist) { + for (int i = 0; i < range.length; i++) { + svAdd(dist, range[i]); + } + } - /** - * Computes the sum of the elements of an array of integers. - * - * @param ints - * the array of integers - * @return the sum of the elements - */ - public static int sum(int[] ints) { + /** + * Shift bounds by a constant value in every dimension. The dists must be of + * dimensions as the range. + * + * @param range + * @return + */ + public static void shiftRange(double[][] range, double[] dists) { + for (int i = 0; i < range.length; i++) { + svAdd(dists[i], range[i]); + } + } - int sum = 0; + /** + * Computes a spline interpolation of the two point (x0,f0) and (x1,f1). + * + * @param x + * @param x0 + * @param x1 + * @param f0 + * @param f1 + * @return If an error with the spline occurs, a linear interpolation will + * be returned. + */ + public static double splineInterpolation(double x, double x0, double x1, + double f0, double f1) { + try { + double[] t = {x0, x1}, f = {f0, f1}; + SplineInterpolation spline = new SplineInterpolation( + new BasicDataSet(t, f, 1)); + return spline.getY(x); + } catch (InterpolationException e) { + e.printStackTrace(); + } + return linearInterpolation(x, x0, x1, f0, f1); + } - for (int i = 0; i < ints.length; i++) { - sum += ints[i]; - } - return sum; - } + /** + * This computes the submatrix of the given matrix as a result by scraching + * out the row k and the column l. + * + * @param a + * @param k + * @param l + * @return + */ + public static double[][] submatrix(double[][] a, int k, int l) { + double b[][] = new double[a.length - 1][a[0].length - 1]; + int i, j, m = 0, n = 0; - /** - * Add each entry of a vector with a scalar in a new vector. - * - * @param s - * @param v - * @return - */ - public static double[] svAdd(double s, double[] v) { - double[] res = new double[v.length]; - svAdd(s, v, res); - return res; - } + for (i = 0; i < a.length; i++) { + if (i == k) { + continue; + } + for (j = 0; j < a[0].length; j++) { + if (j == l) { + continue; + } + b[m][n++] = a[i][j]; + } + m++; + n = 0; + } - /** - * Add each entry of a vector with a scalar in a result vector. - * - * @param s - * @param v - * @return - */ - public static void svAdd(double s, double[] v, double[] res) { - for (int i = 0; i < v.length; i++) { - res[i] = v[i] + s; - } - } + return b; + } - /** - * Return a new vector which is c = (v_i/s). - * - * @param s - * @param v - * @return - */ - public static double[] svDiv(double s, double[] v) { - double[] res = new double[v.length]; - for (int i = 0; i < v.length; i++) { - res[i] = v[i] / s; - } - return res; - } + /** + * Computes the sum of the elements of an array of doubles. + * + * @param doubles the array of double + * @return the sum of the elements + */ + public static double sum(double[] doubles) { + double sum = 0; + for (int i = 0; i < doubles.length; i++) { + sum += doubles[i]; + } + return sum; + } - /** - * Divide by scalar in place, res_i = v_i/s. - * - * @param s - * @param v - * @return - */ - public static void svDiv(double s, double[] v, double[] res) { - for (int i = 0; i < v.length; i++) { - res[i] = v[i] / s; - } - } + /** + * Computes the sum of the elements of an array of integers. + * + * @param ints the array of integers + * @return the sum of the elements + */ + public static int sum(int[] ints) { - /** - * Multiplies (scales) every element of the array v with s returning a new - * vector. - * - * @param s - * a scalar - * @param v - * an array to be multiplied with s. - * @return a scaled array. - */ - public static double[] svMult(double s, double[] v) { - double[] res = new double[v.length]; - for (int i = 0; i < v.length; i++) { - res[i] = v[i] * s; - } - return res; - } + int sum = 0; - /** - * Multiplies (scales) every element of the array v with s in place. - * - * @param s - * a scalar - * @param v - * an array to be multiplied with s. - * @return a scaled array. - */ - public static void svMult(double s, double[] v, double[] res) { - for (int i = 0; i < v.length; i++) { - res[i] = v[i] * s; - } - } + for (int i = 0; i < ints.length; i++) { + sum += ints[i]; + } + return sum; + } - /** - * Add vectors scaled: res[i] = s*v[i] + w[i] - * - * @param s - * @param v - * @param w - * @return - */ - public static void svvAddScaled(double s, double[] v, double[] w, - double[] res) { - for (int i = 0; i < v.length; i++) { - res[i] = s * v[i] + w[i]; - } - } - - /** - * Add vectors scaled: res[i] = s*(v[i] + w[i]) - * - * @param s - * @param v - * @param w - * @return - */ - public static void svvAddAndScale(double s, double[] v, double[] w, - double[] res) { - for (int i = 0; i < v.length; i++) { - res[i] = s * (v[i] + w[i]); - } - } + /** + * Add each entry of a vector with a scalar in a new vector. + * + * @param s + * @param v + * @return + */ + public static double[] svAdd(double s, double[] v) { + double[] res = new double[v.length]; + svAdd(s, v, res); + return res; + } - /** - * Add vectors returning a new vector c = a + b; - * - * @param a - * @param b - * @return a new vector c = a + b - */ - public static double[] vvAdd(double[] a, double[] b) { - double[] result = new double[a.length]; - for (int i = 0; i < a.length; i++) { - result[i] = a[i] + b[i]; - } - return result; - } + /** + * Add each entry of a vector with a scalar in a result vector. + * + * @param s + * @param v + * @return + */ + public static void svAdd(double s, double[] v, double[] res) { + for (int i = 0; i < v.length; i++) { + res[i] = v[i] + s; + } + } - /** - * Add vectors in place setting res = v1 + v2. - * - * @param v1 - * @param v2 - * @return vector addition - */ - public static void vvAdd(double[] v1, double[] v2, double[] res) { - vvAddOffs(v1, 0, v2, 0, res, 0, v1.length); - } + /** + * Return a new vector which is c = (v_i/s). + * + * @param s + * @param v + * @return + */ + public static double[] svDiv(double s, double[] v) { + double[] res = new double[v.length]; + for (int i = 0; i < v.length; i++) { + res[i] = v[i] / s; + } + return res; + } - /** - * Calculate r=1/2 * sqrt(sum(sqr(upperBound_i - lowerBound_i))). - * - * @param range - * @return the average length of the range intervals - */ - public static double getAvgRangeL2(double[][] range) { - double sum = 0.; - for (int i = 0; i < range.length; i++) { - double d = (range[i][1] - range[i][0]); - sum += (d * d); - } - return Math.sqrt(sum) / 2.; - } + /** + * Divide by scalar in place, res_i = v_i/s. + * + * @param s + * @param v + * @return + */ + public static void svDiv(double s, double[] v, double[] res) { + for (int i = 0; i < v.length; i++) { + res[i] = v[i] / s; + } + } - /** - * Add vectors in place setting with an offset within the target vector, - * meaning that res[resOffs+i]=v1[v1Offs+i]+v2[v2Offs+i] for i in length. - * - * @param v1 - * @param v2 - * @return vector addition - */ - public static void vvAddOffs(double[] v1, int v1Offs, double[] v2, - int v2Offs, double[] res, int resOffs, int len) { - for (int i = 0; i < len; i++) { - res[resOffs + i] = v1[v1Offs + i] + v2[v2Offs + i]; - } - } + /** + * Multiplies (scales) every element of the array v with s returning a new + * vector. + * + * @param s a scalar + * @param v an array to be multiplied with s. + * @return a scaled array. + */ + public static double[] svMult(double s, double[] v) { + double[] res = new double[v.length]; + for (int i = 0; i < v.length; i++) { + res[i] = v[i] * s; + } + return res; + } - /** - * Scalar product of two vectors returning sum_i (a_i * b_i). - * - * @param a - * @param b - * @return - */ - public static double vvMult(double[] a, double[] b) { - double result = 0; - for (int i = 0; i < a.length; i++) { - result += a[i] * b[i]; - } - return result; - } + /** + * Multiplies (scales) every element of the array v with s in place. + * + * @param s a scalar + * @param v an array to be multiplied with s. + * @return a scaled array. + */ + public static void svMult(double s, double[] v, double[] res) { + for (int i = 0; i < v.length; i++) { + res[i] = v[i] * s; + } + } - /** - * Component wise multiplication of vectors: res[i]=u[i]*v[i] - * - * @param s - * @param v - * @return - */ - public static void vvMultCw(double[] u, double[] v, double[] res) { - for (int i = 0; i < res.length; i++) { - res[i] = u[i] * v[i]; - } - } + /** + * Add vectors scaled: res[i] = s*v[i] + w[i] + * + * @param s + * @param v + * @param w + * @return + */ + public static void svvAddScaled(double s, double[] v, double[] w, + double[] res) { + for (int i = 0; i < v.length; i++) { + res[i] = s * v[i] + w[i]; + } + } - /** - * Subtract vectors returning a new vector c = a - b. - * - * @param a - * @param b - * @return a new vector c = a - b - */ - public static double[] vvSub(double[] a, double[] b) { - double[] result = new double[a.length]; - vvSub(a, b, result); - return result; - } + /** + * Add vectors scaled: res[i] = s*(v[i] + w[i]) + * + * @param s + * @param v + * @param w + * @return + */ + public static void svvAddAndScale(double s, double[] v, double[] w, + double[] res) { + for (int i = 0; i < v.length; i++) { + res[i] = s * (v[i] + w[i]); + } + } - /** - * Subtract vectors returning a new vector c = a - b. - * - * @param a - * @param b - * @return a new vector c = a - b - */ - public static void vvSub(double[] a, double[] b, double[] res) { - for (int i = 0; i < a.length; i++) { - res[i] = a[i] - b[i]; - } - } + /** + * Add vectors returning a new vector c = a + b; + * + * @param a + * @param b + * @return a new vector c = a + b + */ + public static double[] vvAdd(double[] a, double[] b) { + double[] result = new double[a.length]; + for (int i = 0; i < a.length; i++) { + result[i] = a[i] + b[i]; + } + return result; + } - /** - * Return a vector of given length containing zeroes. - * - * @param n - * @return - */ - public static double[] zeroes(int n) { - return makeVector(0, n); - } + /** + * Add vectors in place setting res = v1 + v2. + * + * @param v1 + * @param v2 + * @return vector addition + */ + public static void vvAdd(double[] v1, double[] v2, double[] res) { + vvAddOffs(v1, 0, v2, 0, res, 0, v1.length); + } - /** - * Create a double vector of length dim filled with value d. - * - * @param d - * @param dim - * @return a double vector of length dim filled with value d - */ - public static double[] makeVector(double d, int dim) { - double[] ret = new double[dim]; - Arrays.fill(ret, d); - return ret; - } + /** + * Calculate r=1/2 * sqrt(sum(sqr(upperBound_i - lowerBound_i))). + * + * @param range + * @return the average length of the range intervals + */ + public static double getAvgRangeL2(double[][] range) { + double sum = 0.; + for (int i = 0; i < range.length; i++) { + double d = (range[i][1] - range[i][0]); + sum += (d * d); + } + return Math.sqrt(sum) / 2.; + } - /** - * Scales a vector with the given scalar. - * - * @param scale - * @param vec - */ - public static void scale(double scale, double[] vec) { - for (int i = 0; i < vec.length; i++) { - vec[i] *= scale; - } - } - - /** - * Return true if an integer is contained in an integer list, otherwise false. - * - * @param list - * @param i - * @return - */ - public static boolean contains(int[] list, int i) { - for (int k:list) { - if (k==i) { - return true; - } - } - return false; - } + /** + * Add vectors in place setting with an offset within the target vector, + * meaning that res[resOffs+i]=v1[v1Offs+i]+v2[v2Offs+i] for i in length. + * + * @param v1 + * @param v2 + * @return vector addition + */ + public static void vvAddOffs(double[] v1, int v1Offs, double[] v2, + int v2Offs, double[] res, int resOffs, int len) { + for (int i = 0; i < len; i++) { + res[resOffs + i] = v1[v1Offs + i] + v2[v2Offs + i]; + } + } + + /** + * Scalar product of two vectors returning sum_i (a_i * b_i). + * + * @param a + * @param b + * @return + */ + public static double vvMult(double[] a, double[] b) { + double result = 0; + for (int i = 0; i < a.length; i++) { + result += a[i] * b[i]; + } + return result; + } + + /** + * Component wise multiplication of vectors: res[i]=u[i]*v[i] + * + * @param s + * @param v + * @return + */ + public static void vvMultCw(double[] u, double[] v, double[] res) { + for (int i = 0; i < res.length; i++) { + res[i] = u[i] * v[i]; + } + } + + /** + * Subtract vectors returning a new vector c = a - b. + * + * @param a + * @param b + * @return a new vector c = a - b + */ + public static double[] vvSub(double[] a, double[] b) { + double[] result = new double[a.length]; + vvSub(a, b, result); + return result; + } + + /** + * Subtract vectors returning a new vector c = a - b. + * + * @param a + * @param b + * @return a new vector c = a - b + */ + public static void vvSub(double[] a, double[] b, double[] res) { + for (int i = 0; i < a.length; i++) { + res[i] = a[i] - b[i]; + } + } + + /** + * Return a vector of given length containing zeroes. + * + * @param n + * @return + */ + public static double[] zeroes(int n) { + return makeVector(0, n); + } + + /** + * Create a double vector of length dim filled with value d. + * + * @param d + * @param dim + * @return a double vector of length dim filled with value d + */ + public static double[] makeVector(double d, int dim) { + double[] ret = new double[dim]; + Arrays.fill(ret, d); + return ret; + } + + /** + * Scales a vector with the given scalar. + * + * @param scale + * @param vec + */ + public static void scale(double scale, double[] vec) { + for (int i = 0; i < vec.length; i++) { + vec[i] *= scale; + } + } + + /** + * Return true if an integer is contained in an integer list, otherwise false. + * + * @param list + * @param i + * @return + */ + public static boolean contains(int[] list, int i) { + for (int k : list) { + if (k == i) { + return true; + } + } + return false; + } } diff --git a/src/eva2/tools/math/RNG.java b/src/eva2/tools/math/RNG.java index 6d0edbc8..c72e03ed 100644 --- a/src/eva2/tools/math/RNG.java +++ b/src/eva2/tools/math/RNG.java @@ -1,6 +1,7 @@ package eva2.tools.math; import eva2.tools.EVAERROR; + import java.util.ArrayList; import java.util.BitSet; import java.util.Random; @@ -378,16 +379,12 @@ public class RNG { * deviation (instead of 1/D), the parameter is not further used in the * other two cases. Original code by Maurice Clerc, from the TRIBES package * - - * - * @param center center point of the distribution - * @param radius radius of the distribution + * @param center center point of the distribution + * @param radius radius of the distribution * @param nonUnif kind of distribution - * - * */ public static double[] randHypersphere(double[] center, double radius, - double nonUnif) { + double nonUnif) { double[] x = new double[center.length]; int j; double xLen, r; @@ -422,7 +419,7 @@ public class RNG { /** * Adds Gaussian noise to a double vector * - * @param v the double vector + * @param v the double vector * @param dev the Gaussian deviation */ public static void addNoise(double[] v, double dev) { @@ -452,7 +449,7 @@ public class RNG { * @return */ public static double[] gaussianVector(double dev, double[] result, - boolean normalize) { + boolean normalize) { for (int i = 0; i < result.length; i++) { result[i] = RNG.gaussianDouble(dev); } diff --git a/src/eva2/tools/math/SpecialFunction.java b/src/eva2/tools/math/SpecialFunction.java index 66f8af22..0e3239a9 100644 --- a/src/eva2/tools/math/SpecialFunction.java +++ b/src/eva2/tools/math/SpecialFunction.java @@ -36,27 +36,27 @@ package eva2.tools.math; * Like the java.lang.Math class this class is final and cannot be * subclassed. * All physical constants are in cgs units. - *

+ *

* NOTE: These special functions do not necessarily use the fastest * or most accurate algorithms. * - * @version $Revision: 1.1.1.1 $, $Date: 2003/07/03 14:59:40 $ * @author Leigh Brookshaw + * @version $Revision: 1.1.1.1 $, $Date: 2003/07/03 14:59:40 $ */ public final class SpecialFunction extends Object { - /* - ** machine constants - */ - private static final double MACHEP = 1.11022302462515654042E-16; - private static final double MAXLOG = 7.09782712893383996732E2; + /* + ** machine constants + */ + private static final double MACHEP = 1.11022302462515654042E-16; + private static final double MAXLOG = 7.09782712893383996732E2; private static final double MINLOG = -7.451332191019412076235E2; private static final double MAXGAM = 171.624376956302725; - private static final double SQTPI = 2.50662827463100050242E0; - private static final double SQRTH = 7.07106781186547524401E-1; - private static final double LOGPI = 1.14472988584940017414; + private static final double SQTPI = 2.50662827463100050242E0; + private static final double SQRTH = 7.07106781186547524401E-1; + private static final double LOGPI = 1.14472988584940017414; /* @@ -64,638 +64,631 @@ public final class SpecialFunction extends Object { */ - /** - * Boltzman Constant. Units erg/deg(K) - */ - public static final double BOLTZMAN = 1.3807e-16; - /** - * Elementary Charge. Units statcoulomb - */ - public static final double ECHARGE = 4.8032e-10; - /** - * Electron Mass. Units g - */ - public static final double EMASS = 9.1095e-28; - /** - * Proton Mass. Units g - */ - public static final double PMASS = 1.6726e-24; - /** - * Gravitational Constant. Units dyne-cm^2/g^2 - */ - public static final double GRAV = 6.6720e-08; - /** - * Planck constant. Units erg-sec - */ - public static final double PLANCK = 6.6262e-27; - /** - * Speed of Light in a Vacuum. Units cm/sec - */ - public static final double LIGHTSPEED = 2.9979e10; - /** - * Stefan-Boltzman Constant. Units erg/cm^2-sec-deg^4 - */ - public static final double STEFANBOLTZ = 5.6703e-5; - /** - * Avogadro Number. Units 1/mol - */ - public static final double AVOGADRO = 6.0220e23; - /** - * Gas Constant. Units erg/deg-mol - */ - public static final double GASCONSTANT = 8.3144e07; - /** - * Gravitational Acceleration at the Earths surface. Units cm/sec^2 - */ - public static final double GRAVACC = 980.67; + /** + * Boltzman Constant. Units erg/deg(K) + */ + public static final double BOLTZMAN = 1.3807e-16; + /** + * Elementary Charge. Units statcoulomb + */ + public static final double ECHARGE = 4.8032e-10; + /** + * Electron Mass. Units g + */ + public static final double EMASS = 9.1095e-28; + /** + * Proton Mass. Units g + */ + public static final double PMASS = 1.6726e-24; + /** + * Gravitational Constant. Units dyne-cm^2/g^2 + */ + public static final double GRAV = 6.6720e-08; + /** + * Planck constant. Units erg-sec + */ + public static final double PLANCK = 6.6262e-27; + /** + * Speed of Light in a Vacuum. Units cm/sec + */ + public static final double LIGHTSPEED = 2.9979e10; + /** + * Stefan-Boltzman Constant. Units erg/cm^2-sec-deg^4 + */ + public static final double STEFANBOLTZ = 5.6703e-5; + /** + * Avogadro Number. Units 1/mol + */ + public static final double AVOGADRO = 6.0220e23; + /** + * Gas Constant. Units erg/deg-mol + */ + public static final double GASCONSTANT = 8.3144e07; + /** + * Gravitational Acceleration at the Earths surface. Units cm/sec^2 + */ + public static final double GRAVACC = 980.67; - /** - * Solar Mass. Units g - */ - public static final double SOLARMASS = 1.99e33; - /** - * Solar Radius. Units cm - */ - public static final double SOLARRADIUS = 6.96e10; - /** - * Solar Luminosity. Units erg/sec - */ - public static final double SOLARLUM = 3.90e33; - /** - * Solar Flux. Units erg/cm^2-sec - */ - public static final double SOLARFLUX = 6.41e10; - /** - * Astronomical Unit (radius of the Earth's orbit). Units cm - */ - public static final double AU = 1.50e13; + /** + * Solar Mass. Units g + */ + public static final double SOLARMASS = 1.99e33; + /** + * Solar Radius. Units cm + */ + public static final double SOLARRADIUS = 6.96e10; + /** + * Solar Luminosity. Units erg/sec + */ + public static final double SOLARLUM = 3.90e33; + /** + * Solar Flux. Units erg/cm^2-sec + */ + public static final double SOLARFLUX = 6.41e10; + /** + * Astronomical Unit (radius of the Earth's orbit). Units cm + */ + public static final double AU = 1.50e13; /** * Don't let anyone instantiate this class. */ - private SpecialFunction() {} + private SpecialFunction() { + } /* ** Function Methods */ - /** - * @param x a double value - * @return The log10 - */ + /** + * @param x a double value + * @return The log10 + */ static public double log10(double x) throws ArithmeticException { - if( x <= 0.0 ) { + if (x <= 0.0) { throw new ArithmeticException("range exception"); } - return Math.log(x)/2.30258509299404568401; + return Math.log(x) / 2.30258509299404568401; } - + /** - * * @param b Base of the logarithm * @param x a double value * @return The logb * @throws ArithmeticException */ static public double logb(double b, double x) throws ArithmeticException { - if( x <= 0.0 ) { + if (x <= 0.0) { throw new ArithmeticException("range exception"); } - return Math.log(x)/Math.log(b); + return Math.log(x) / Math.log(b); } - /** - * @param x a double value - * @return the hyperbolic cosine of the argument - */ + /** + * @param x a double value + * @return the hyperbolic cosine of the argument + */ static public double cosh(double x) throws ArithmeticException { - double a; - a = x; - if( a < 0.0 ) { + double a; + a = x; + if (a < 0.0) { a = Math.abs(x); } - a = Math.exp(a); - return 0.5*(a+1/a); + a = Math.exp(a); + return 0.5 * (a + 1 / a); } - /** - * @param x a double value - * @return the hyperbolic sine of the argument - */ + /** + * @param x a double value + * @return the hyperbolic sine of the argument + */ static public double sinh(double x) throws ArithmeticException { - double a; - if(x == 0.0) { + double a; + if (x == 0.0) { return x; } - a = x; - if( a < 0.0 ) { + a = x; + if (a < 0.0) { a = Math.abs(x); } - a = Math.exp(a); - if( x < 0.0 ) { - return -0.5*(a-1/a); - } - else { - return 0.5*(a-1/a); + a = Math.exp(a); + if (x < 0.0) { + return -0.5 * (a - 1 / a); + } else { + return 0.5 * (a - 1 / a); } } - /** - * @param x a double value - * @return the hyperbolic tangent of the argument - */ + /** + * @param x a double value + * @return the hyperbolic tangent of the argument + */ static public double tanh(double x) throws ArithmeticException { - double a; - if( x == 0.0 ) { + double a; + if (x == 0.0) { return x; } - a = x; - if( a < 0.0 ) { + a = x; + if (a < 0.0) { a = Math.abs(x); } - a = Math.exp(2.0*a); - if(x < 0.0 ) { - return -( 1.0-2.0/(a+1.0) ); - } - else { - return ( 1.0-2.0/(a+1.0) ); + a = Math.exp(2.0 * a); + if (x < 0.0) { + return -(1.0 - 2.0 / (a + 1.0)); + } else { + return (1.0 - 2.0 / (a + 1.0)); } } - /** - * @param x a double value - * @return the hyperbolic arc cosine of the argument - */ + /** + * @param x a double value + * @return the hyperbolic arc cosine of the argument + */ static public double acosh(double x) throws ArithmeticException { - if( x < 1.0 ) { + if (x < 1.0) { throw new ArithmeticException("range exception"); } - return Math.log( x + Math.sqrt(x*x-1)); + return Math.log(x + Math.sqrt(x * x - 1)); } - /** - * @param x a double value - * @return the hyperbolic arc sine of the argument - */ + /** + * @param x a double value + * @return the hyperbolic arc sine of the argument + */ static public double asinh(double xx) throws ArithmeticException { - double x; - int sign; - if(xx == 0.0) { + double x; + int sign; + if (xx == 0.0) { return xx; } - if( xx < 0.0 ) { - sign = -1; - x = -xx; - } else { - sign = 1; - x = xx; - } - return sign*Math.log( x + Math.sqrt(x*x+1)); - } - - /** - * @param x a double value - * @return the hyperbolic arc tangent of the argument - */ - static public double atanh(double x) throws ArithmeticException { - if( x > 1.0 || x < -1.0 ) { - throw - new ArithmeticException("range exception"); + if (xx < 0.0) { + sign = -1; + x = -xx; + } else { + sign = 1; + x = xx; } - return 0.5 * Math.log( (1.0+x)/(1.0-x) ); + return sign * Math.log(x + Math.sqrt(x * x + 1)); } - /** - * @param x a double value - * @return the Bessel function of order 0 of the argument. - */ + /** + * @param x a double value + * @return the hyperbolic arc tangent of the argument + */ + static public double atanh(double x) throws ArithmeticException { + if (x > 1.0 || x < -1.0) { + throw + new ArithmeticException("range exception"); + } + return 0.5 * Math.log((1.0 + x) / (1.0 - x)); + } + + /** + * @param x a double value + * @return the Bessel function of order 0 of the argument. + */ static public double j0(double x) throws ArithmeticException { double ax; - if( (ax=Math.abs(x)) < 8.0 ) { - double y=x*x; - double ans1=57568490574.0+y*(-13362590354.0+y*(651619640.7 - +y*(-11214424.18+y*(77392.33017+y*(-184.9052456))))); - double ans2=57568490411.0+y*(1029532985.0+y*(9494680.718 - +y*(59272.64853+y*(267.8532712+y*1.0)))); + if ((ax = Math.abs(x)) < 8.0) { + double y = x * x; + double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7 + + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456))))); + double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718 + + y * (59272.64853 + y * (267.8532712 + y * 1.0)))); - return ans1/ans2; + return ans1 / ans2; } else { - double z=8.0/ax; - double y=z*z; - double xx=ax-0.785398164; - double ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 - +y*(-0.2073370639e-5+y*0.2093887211e-6))); - double ans2 = -0.1562499995e-1+y*(0.1430488765e-3 - +y*(-0.6911147651e-5+y*(0.7621095161e-6 - -y*0.934935152e-7))); + double z = 8.0 / ax; + double y = z * z; + double xx = ax - 0.785398164; + double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4 + + y * (-0.2073370639e-5 + y * 0.2093887211e-6))); + double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3 + + y * (-0.6911147651e-5 + y * (0.7621095161e-6 + - y * 0.934935152e-7))); - return Math.sqrt(0.636619772/ax)* - (Math.cos(xx)*ans1-z*Math.sin(xx)*ans2); - } + return Math.sqrt(0.636619772 / ax) * + (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2); + } } - /** - * @param x a double value - * @return the Bessel function of order 1 of the argument. - */ + + /** + * @param x a double value + * @return the Bessel function of order 1 of the argument. + */ static public double j1(double x) throws ArithmeticException { - double ax; - double y; - double ans1, ans2; + double ax; + double y; + double ans1, ans2; - if ((ax=Math.abs(x)) < 8.0) { - y=x*x; - ans1=x*(72362614232.0+y*(-7895059235.0+y*(242396853.1 - +y*(-2972611.439+y*(15704.48260+y*(-30.16036606)))))); - ans2=144725228442.0+y*(2300535178.0+y*(18583304.74 - +y*(99447.43394+y*(376.9991397+y*1.0)))); - return ans1/ans2; - } else { - double z=8.0/ax; - double xx=ax-2.356194491; - y=z*z; + if ((ax = Math.abs(x)) < 8.0) { + y = x * x; + ans1 = x * (72362614232.0 + y * (-7895059235.0 + y * (242396853.1 + + y * (-2972611.439 + y * (15704.48260 + y * (-30.16036606)))))); + ans2 = 144725228442.0 + y * (2300535178.0 + y * (18583304.74 + + y * (99447.43394 + y * (376.9991397 + y * 1.0)))); + return ans1 / ans2; + } else { + double z = 8.0 / ax; + double xx = ax - 2.356194491; + y = z * z; - ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4 - +y*(0.2457520174e-5+y*(-0.240337019e-6)))); - ans2=0.04687499995+y*(-0.2002690873e-3 - +y*(0.8449199096e-5+y*(-0.88228987e-6 - +y*0.105787412e-6))); - double ans=Math.sqrt(0.636619772/ax)* - (Math.cos(xx)*ans1-z*Math.sin(xx)*ans2); - if (x < 0.0) { - ans = -ans; - } - return ans; - } + ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4 + + y * (0.2457520174e-5 + y * (-0.240337019e-6)))); + ans2 = 0.04687499995 + y * (-0.2002690873e-3 + + y * (0.8449199096e-5 + y * (-0.88228987e-6 + + y * 0.105787412e-6))); + double ans = Math.sqrt(0.636619772 / ax) * + (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2); + if (x < 0.0) { + ans = -ans; + } + return ans; + } } - /** - * @param n integer order - * @param x a double value - * @return the Bessel function of order n of the argument. - */ + /** + * @param n integer order + * @param x a double value + * @return the Bessel function of order n of the argument. + */ static public double jn(int n, double x) throws ArithmeticException { - int j,m; - double ax,bj,bjm,bjp,sum,tox,ans; - boolean jsum; + int j, m; + double ax, bj, bjm, bjp, sum, tox, ans; + boolean jsum; - double ACC = 40.0; - double BIGNO = 1.0e+10; - double BIGNI = 1.0e-10; + double ACC = 40.0; + double BIGNO = 1.0e+10; + double BIGNI = 1.0e-10; - if(n == 0) { + if (n == 0) { return j0(x); } - if(n == 1) { + if (n == 1) { return j1(x); } - ax=Math.abs(x); - if(ax == 0.0) { + ax = Math.abs(x); + if (ax == 0.0) { return 0.0; - } - else - if (ax > (double)n) { - tox=2.0/ax; - bjm=j0(ax); - bj=j1(ax); - for (j=1;j0;j--) { - bjm=j*tox*bj-bjp; - bjp=bj; - bj=bjm; - if (Math.abs(bj) > BIGNO) { - bj *= BIGNI; - bjp *= BIGNI; - ans *= BIGNI; - sum *= BIGNI; + } else if (ax > (double) n) { + tox = 2.0 / ax; + bjm = j0(ax); + bj = j1(ax); + for (j = 1; j < n; j++) { + bjp = j * tox * bj - bjm; + bjm = bj; + bj = bjp; } - if (jsum) { - sum += bj; - } - jsum=!jsum; - if (j == n) { - ans=bjp; - } - } - sum=2.0*sum-bj; - ans /= sum; - } - return x < 0.0 && n%2 == 1 ? -ans : ans; - } - /** - * @param x a double value - * @return the Bessel function of the second kind, - * of order 0 of the argument. - */ + ans = bj; + } else { + tox = 2.0 / ax; + m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2); + jsum = false; + bjp = ans = sum = 0.0; + bj = 1.0; + for (j = m; j > 0; j--) { + bjm = j * tox * bj - bjp; + bjp = bj; + bj = bjm; + if (Math.abs(bj) > BIGNO) { + bj *= BIGNI; + bjp *= BIGNI; + ans *= BIGNI; + sum *= BIGNI; + } + if (jsum) { + sum += bj; + } + jsum = !jsum; + if (j == n) { + ans = bjp; + } + } + sum = 2.0 * sum - bj; + ans /= sum; + } + return x < 0.0 && n % 2 == 1 ? -ans : ans; + } - static public double y0(double x) throws ArithmeticException { + /** + * @param x a double value + * @return the Bessel function of the second kind, + * of order 0 of the argument. + */ - if (x < 8.0) { - double y=x*x; + static public double y0(double x) throws ArithmeticException { - double ans1 = -2957821389.0+y*(7062834065.0+y*(-512359803.6 - +y*(10879881.29+y*(-86327.92757+y*228.4622733)))); - double ans2=40076544269.0+y*(745249964.8+y*(7189466.438 - +y*(47447.26470+y*(226.1030244+y*1.0)))); + if (x < 8.0) { + double y = x * x; - return (ans1/ans2)+0.636619772*j0(x)*Math.log(x); - } else { - double z=8.0/x; - double y=z*z; - double xx=x-0.785398164; + double ans1 = -2957821389.0 + y * (7062834065.0 + y * (-512359803.6 + + y * (10879881.29 + y * (-86327.92757 + y * 228.4622733)))); + double ans2 = 40076544269.0 + y * (745249964.8 + y * (7189466.438 + + y * (47447.26470 + y * (226.1030244 + y * 1.0)))); - double ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 - +y*(-0.2073370639e-5+y*0.2093887211e-6))); - double ans2 = -0.1562499995e-1+y*(0.1430488765e-3 - +y*(-0.6911147651e-5+y*(0.7621095161e-6 - +y*(-0.934945152e-7)))); - return Math.sqrt(0.636619772/x)* - (Math.sin(xx)*ans1+z*Math.cos(xx)*ans2); - } - } + return (ans1 / ans2) + 0.636619772 * j0(x) * Math.log(x); + } else { + double z = 8.0 / x; + double y = z * z; + double xx = x - 0.785398164; - /** - * @param x a double value - * @return the Bessel function of the second kind, - * of order 1 of the argument. - */ - static public double y1(double x) throws ArithmeticException { + double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4 + + y * (-0.2073370639e-5 + y * 0.2093887211e-6))); + double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3 + + y * (-0.6911147651e-5 + y * (0.7621095161e-6 + + y * (-0.934945152e-7)))); + return Math.sqrt(0.636619772 / x) * + (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2); + } + } - if (x < 8.0) { - double y=x*x; - double ans1=x*(-0.4900604943e13+y*(0.1275274390e13 - +y*(-0.5153438139e11+y*(0.7349264551e9 - +y*(-0.4237922726e7+y*0.8511937935e4))))); - double ans2=0.2499580570e14+y*(0.4244419664e12 - +y*(0.3733650367e10+y*(0.2245904002e8 - +y*(0.1020426050e6+y*(0.3549632885e3+y))))); - return (ans1/ans2)+0.636619772*(j1(x)*Math.log(x)-1.0/x); - } else { - double z=8.0/x; - double y=z*z; - double xx=x-2.356194491; - double ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4 - +y*(0.2457520174e-5+y*(-0.240337019e-6)))); - double ans2=0.04687499995+y*(-0.2002690873e-3 - +y*(0.8449199096e-5+y*(-0.88228987e-6 - +y*0.105787412e-6))); - return Math.sqrt(0.636619772/x)* - (Math.sin(xx)*ans1+z*Math.cos(xx)*ans2); - } - } - /** - * @param n integer order - * @param x a double value - * @return the Bessel function of the second kind, - * of order n of the argument. - */ + /** + * @param x a double value + * @return the Bessel function of the second kind, + * of order 1 of the argument. + */ + static public double y1(double x) throws ArithmeticException { + + if (x < 8.0) { + double y = x * x; + double ans1 = x * (-0.4900604943e13 + y * (0.1275274390e13 + + y * (-0.5153438139e11 + y * (0.7349264551e9 + + y * (-0.4237922726e7 + y * 0.8511937935e4))))); + double ans2 = 0.2499580570e14 + y * (0.4244419664e12 + + y * (0.3733650367e10 + y * (0.2245904002e8 + + y * (0.1020426050e6 + y * (0.3549632885e3 + y))))); + return (ans1 / ans2) + 0.636619772 * (j1(x) * Math.log(x) - 1.0 / x); + } else { + double z = 8.0 / x; + double y = z * z; + double xx = x - 2.356194491; + double ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4 + + y * (0.2457520174e-5 + y * (-0.240337019e-6)))); + double ans2 = 0.04687499995 + y * (-0.2002690873e-3 + + y * (0.8449199096e-5 + y * (-0.88228987e-6 + + y * 0.105787412e-6))); + return Math.sqrt(0.636619772 / x) * + (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2); + } + } + + /** + * @param n integer order + * @param x a double value + * @return the Bessel function of the second kind, + * of order n of the argument. + */ static public double yn(int n, double x) throws ArithmeticException { - double by,bym,byp,tox; + double by, bym, byp, tox; - if(n == 0) { + if (n == 0) { return y0(x); } - if(n == 1) { + if (n == 1) { return y1(x); } - tox=2.0/x; - by=y1(x); - bym=y0(x); - for (int j=1;j 1) { d *= i--; } - if(j < 0) { - return -d; - } - else { - return d; - } - } + if (j < 0) { + i = Math.abs(j); + } + while (i > 1) { + d *= i--; + } + if (j < 0) { + return -d; + } else { + return d; + } + } - - - - /** - * @param x a double value - * @return the Gamma function of the value. - *

- * - * Converted to Java from
- * Cephes Math Library Release 2.2: July, 1992
- * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
- **/ + /** + * @param x a double value + * @return the Gamma function of the value. + *

+ * + * Converted to Java from
+ * Cephes Math Library Release 2.2: July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */ static public double gamma(double x) throws ArithmeticException { - double P[] = { - 1.60119522476751861407E-4, - 1.19135147006586384913E-3, - 1.04213797561761569935E-2, - 4.76367800457137231464E-2, - 2.07448227648435975150E-1, - 4.94214826801497100753E-1, - 9.99999999999999996796E-1 - }; - double Q[] = { - -2.31581873324120129819E-5, - 5.39605580493303397842E-4, - -4.45641913851797240494E-3, - 1.18139785222060435552E-2, - 3.58236398605498653373E-2, - -2.34591795718243348568E-1, - 7.14304917030273074085E-2, - 1.00000000000000000320E0 - }; - double MAXGAM = 171.624376956302725; - double LOGPI = 1.14472988584940017414; + double P[] = { + 1.60119522476751861407E-4, + 1.19135147006586384913E-3, + 1.04213797561761569935E-2, + 4.76367800457137231464E-2, + 2.07448227648435975150E-1, + 4.94214826801497100753E-1, + 9.99999999999999996796E-1 + }; + double Q[] = { + -2.31581873324120129819E-5, + 5.39605580493303397842E-4, + -4.45641913851797240494E-3, + 1.18139785222060435552E-2, + 3.58236398605498653373E-2, + -2.34591795718243348568E-1, + 7.14304917030273074085E-2, + 1.00000000000000000320E0 + }; + double MAXGAM = 171.624376956302725; + double LOGPI = 1.14472988584940017414; - double p, z; - int i; + double p, z; + int i; - double q = Math.abs(x); + double q = Math.abs(x); - if( q > 33.0 ) { - if( x < 0.0 ) { - p = Math.floor(q); - if( p == q ) { - throw new ArithmeticException("gamma: overflow"); - } - i = (int)p; - z = q - p; - if( z > 0.5 ) { - p += 1.0; - z = q - p; - } - z = q * Math.sin( Math.PI * z ); - if( z == 0.0 ) { - throw new ArithmeticException("gamma: overflow"); - } - z = Math.abs(z); - z = Math.PI/(z * stirf(q) ); + if (q > 33.0) { + if (x < 0.0) { + p = Math.floor(q); + if (p == q) { + throw new ArithmeticException("gamma: overflow"); + } + i = (int) p; + z = q - p; + if (z > 0.5) { + p += 1.0; + z = q - p; + } + z = q * Math.sin(Math.PI * z); + if (z == 0.0) { + throw new ArithmeticException("gamma: overflow"); + } + z = Math.abs(z); + z = Math.PI / (z * stirf(q)); - return -z; - } else { - return stirf(x); - } - } + return -z; + } else { + return stirf(x); + } + } - z = 1.0; - while( x >= 3.0 ) { - x -= 1.0; - z *= x; - } + z = 1.0; + while (x >= 3.0) { + x -= 1.0; + z *= x; + } - while( x < 0.0 ) { - if( x == 0.0 ) { + while (x < 0.0) { + if (x == 0.0) { throw new ArithmeticException("gamma: singular"); - } else - if( x > -1.E-9 ) { - return( z/((1.0 + 0.5772156649015329 * x) * x) ); - } - z /= x; - x += 1.0; - } + } else if (x > -1.E-9) { + return (z / ((1.0 + 0.5772156649015329 * x) * x)); + } + z /= x; + x += 1.0; + } - while( x < 2.0 ) { - if( x == 0.0 ) { + while (x < 2.0) { + if (x == 0.0) { throw new ArithmeticException("gamma: singular"); - } else - if( x < 1.e-9 ) { - return( z/((1.0 + 0.5772156649015329 * x) * x) ); - } - z /= x; - x += 1.0; - } + } else if (x < 1.e-9) { + return (z / ((1.0 + 0.5772156649015329 * x) * x)); + } + z /= x; + x += 1.0; + } - if( (x == 2.0) || (x == 3.0) ) { + if ((x == 2.0) || (x == 3.0)) { return z; } x -= 2.0; - p = polevl( x, P, 6 ); - q = polevl( x, Q, 7 ); - return z * p / q; + p = polevl(x, P, 6); + q = polevl(x, Q, 7); + return z * p / q; } -/* Gamma function computed by Stirling's formula. - * The polynomial STIR is valid for 33 <= x <= 172. + /* Gamma function computed by Stirling's formula. + * The polynomial STIR is valid for 33 <= x <= 172. -Cephes Math Library Release 2.2: July, 1992 -Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier -Direct inquiries to 30 Frost Street, Cambridge, MA 02140 -*/ - static private double stirf(double x) throws ArithmeticException { + Cephes Math Library Release 2.2: July, 1992 + Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier + Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + static private double stirf(double x) throws ArithmeticException { double STIR[] = { - 7.87311395793093628397E-4, - -2.29549961613378126380E-4, - -2.68132617805781232825E-3, - 3.47222221605458667310E-3, - 8.33333333333482257126E-2, - }; + 7.87311395793093628397E-4, + -2.29549961613378126380E-4, + -2.68132617805781232825E-3, + 3.47222221605458667310E-3, + 8.33333333333482257126E-2, + }; double MAXSTIR = 143.01608; - double w = 1.0/x; - double y = Math.exp(x); + double w = 1.0 / x; + double y = Math.exp(x); - w = 1.0 + w * polevl( w, STIR, 4 ); + w = 1.0 + w * polevl(w, STIR, 4); - if( x > MAXSTIR ) { - /* Avoid overflow in Math.pow() */ - double v = Math.pow( x, 0.5 * x - 0.25 ); - y = v * (v / y); - } else { - y = Math.pow( x, x - 0.5 ) / y; - } + if (x > MAXSTIR) { + /* Avoid overflow in Math.pow() */ + double v = Math.pow(x, 0.5 * x - 0.25); + y = v * (v / y); + } else { + y = Math.pow(x, x - 0.5) / y; + } y = SQTPI * y * w; return y; - } + } - /** - * @param a double value - * @param x double value - * @return the Complemented Incomplete Gamma function. - *

- * - * Converted to Java from
- * Cephes Math Library Release 2.2: July, 1992
- * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
- **/ + /** + * @param a double value + * @param x double value + * @return the Complemented Incomplete Gamma function. + *

+ * + * Converted to Java from
+ * Cephes Math Library Release 2.2: July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */ - static public double igamc( double a, double x ) - throws ArithmeticException { - double big = 4.503599627370496e15; - double biginv = 2.22044604925031308085e-16; + static public double igamc(double a, double x) + throws ArithmeticException { + double big = 4.503599627370496e15; + double biginv = 2.22044604925031308085e-16; double ans, ax, c, yc, r, t, y, z; double pk, pkm1, pkm2, qk, qkm1, qkm2; - if( x <= 0 || a <= 0 ) { - return 1.0; - } + if (x <= 0 || a <= 0) { + return 1.0; + } - if( x < 1.0 || x < a ) { - return 1.0 - igam(a,x); - } + if (x < 1.0 || x < a) { + return 1.0 - igam(a, x); + } ax = a * Math.log(x) - x - lgamma(a); - if( ax < -MAXLOG ) { - return 0.0; - } + if (ax < -MAXLOG) { + return 0.0; + } ax = Math.exp(ax); @@ -707,69 +700,69 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 qkm2 = x; pkm1 = x + 1.0; qkm1 = z * x; - ans = pkm1/qkm1; + ans = pkm1 / qkm1; do { - c += 1.0; - y += 1.0; - z += 2.0; - yc = y * c; - pk = pkm1 * z - pkm2 * yc; - qk = qkm1 * z - qkm2 * yc; - if( qk != 0 ) { - r = pk/qk; - t = Math.abs( (ans - r)/r ); - ans = r; - } else { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk != 0) { + r = pk / qk; + t = Math.abs((ans - r) / r); + ans = r; + } else { t = 1.0; } - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; - if( Math.abs(pk) > big ) { - pkm2 *= biginv; - pkm1 *= biginv; - qkm2 *= biginv; - qkm1 *= biginv; - } - } while( t > MACHEP ); + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (Math.abs(pk) > big) { + pkm2 *= biginv; + pkm1 *= biginv; + qkm2 *= biginv; + qkm1 *= biginv; + } + } while (t > MACHEP); return ans * ax; - } + } - /** - * @param a double value - * @param x double value - * @return the Incomplete Gamma function. - *

- * - * Converted to Java from
- * Cephes Math Library Release 2.2: July, 1992
- * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
- **/ - static public double igam(double a, double x) - throws ArithmeticException { + /** + * @param a double value + * @param x double value + * @return the Incomplete Gamma function. + *

+ * + * Converted to Java from
+ * Cephes Math Library Release 2.2: July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */ + static public double igam(double a, double x) + throws ArithmeticException { double ans, ax, c, r; - if( x <= 0 || a <= 0 ) { - return 0.0; - } + if (x <= 0 || a <= 0) { + return 0.0; + } - if( x > 1.0 && x > a ) { - return 1.0 - igamc(a,x); - } + if (x > 1.0 && x > a) { + return 1.0 - igamc(a, x); + } /* Compute x**a * exp(-x) / gamma(a) */ ax = a * Math.log(x) - x - lgamma(a); - if( ax < -MAXLOG ) { - return( 0.0 ); - } + if (ax < -MAXLOG) { + return (0.0); + } ax = Math.exp(ax); @@ -779,296 +772,294 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 ans = 1.0; do { - r += 1.0; - c *= x/r; - ans += c; - } - while( c/ans > MACHEP ); + r += 1.0; + c *= x / r; + ans += c; + } + while (c / ans > MACHEP); - return( ans * ax/a ); + return (ans * ax / a); - } + } - /** - * Returns the area under the left hand tail (from 0 to x) - * of the Chi square probability density function with - * v degrees of freedom. - * - * @param df degrees of freedom - * @param x double value - * @return the Chi-Square function. - **/ + /** + * Returns the area under the left hand tail (from 0 to x) + * of the Chi square probability density function with + * v degrees of freedom. + * + * @param df degrees of freedom + * @param x double value + * @return the Chi-Square function. + */ - static public double chisq(double df, double x) - throws ArithmeticException { + static public double chisq(double df, double x) + throws ArithmeticException { - if( x < 0.0 || df < 1.0 ) { - return 0.0; - } + if (x < 0.0 || df < 1.0) { + return 0.0; + } - return igam( df/2.0, x/2.0 ); + return igam(df / 2.0, x / 2.0); - } + } - /** - * Returns the area under the right hand tail (from x to - * infinity) of the Chi square probability density function - * with v degrees of freedom: - * - * @param df degrees of freedom - * @param x double value - * @return the Chi-Square function. - *

- **/ + /** + * Returns the area under the right hand tail (from x to + * infinity) of the Chi square probability density function + * with v degrees of freedom: + * + * @param df degrees of freedom + * @param x double value + * @return the Chi-Square function. + *

+ */ - static public double chisqc(double df, double x) - throws ArithmeticException { + static public double chisqc(double df, double x) + throws ArithmeticException { - if( x < 0.0 || df < 1.0 ) { - return 0.0; - } + if (x < 0.0 || df < 1.0) { + return 0.0; + } - return igamc( df/2.0, x/2.0 ); + return igamc(df / 2.0, x / 2.0); - } + } - /** - * Returns the sum of the first k terms of the Poisson - * distribution. - * @param k number of terms - * @param x double value - */ + /** + * Returns the sum of the first k terms of the Poisson + * distribution. + * + * @param k number of terms + * @param x double value + */ - static public double poisson(int k, double x) - throws ArithmeticException { + static public double poisson(int k, double x) + throws ArithmeticException { - if( k < 0 || x < 0 ) { - return 0.0; - } + if (k < 0 || x < 0) { + return 0.0; + } - return igamc((double)(k+1) ,x); - } + return igamc((double) (k + 1), x); + } - /** - * Returns the sum of the terms k+1 to infinity of the Poisson - * distribution. - * @param k start - * @param x double value - */ + /** + * Returns the sum of the terms k+1 to infinity of the Poisson + * distribution. + * + * @param k start + * @param x double value + */ - static public double poissonc(int k, double x) - throws ArithmeticException { + static public double poissonc(int k, double x) + throws ArithmeticException { - if( k < 0 || x < 0 ) { - return 0.0; - } + if (k < 0 || x < 0) { + return 0.0; + } - return igam((double)(k+1),x); - } + return igam((double) (k + 1), x); + } + /** + * @param a double value + * @return The area under the Gaussian probability density + * function, integrated from minus infinity to x: + */ - /** - * @param a double value - * @return The area under the Gaussian probability density - * function, integrated from minus infinity to x: - */ + static public double normal(double a) + throws ArithmeticException { + double x, y, z; - static public double normal( double a) - throws ArithmeticException { - double x, y, z; + x = a * SQRTH; + z = Math.abs(x); - x = a * SQRTH; - z = Math.abs(x); + if (z < SQRTH) { + y = 0.5 + 0.5 * erf(x); + } else { + y = 0.5 * erfc(z); + if (x > 0) { + y = 1.0 - y; + } + } - if( z < SQRTH ) { - y = 0.5 + 0.5 * erf(x); - } - else { - y = 0.5 * erfc(z); - if( x > 0 ) { - y = 1.0 - y; - } - } - - return y; - } + return y; + } - /** - * @param a double value - * @return The complementary Error function - *

- * - * Converted to Java from
- * Cephes Math Library Release 2.2: July, 1992
- * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
- */ + /** + * @param a double value + * @return The complementary Error function + *

+ * + * Converted to Java from
+ * Cephes Math Library Release 2.2: July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */ - static public double erfc(double a) - throws ArithmeticException { - double x,y,z,p,q; + static public double erfc(double a) + throws ArithmeticException { + double x, y, z, p, q; - double P[] = { - 2.46196981473530512524E-10, - 5.64189564831068821977E-1, - 7.46321056442269912687E0, - 4.86371970985681366614E1, - 1.96520832956077098242E2, - 5.26445194995477358631E2, - 9.34528527171957607540E2, - 1.02755188689515710272E3, - 5.57535335369399327526E2 - }; - double Q[] = { - //1.0 - 1.32281951154744992508E1, - 8.67072140885989742329E1, - 3.54937778887819891062E2, - 9.75708501743205489753E2, - 1.82390916687909736289E3, - 2.24633760818710981792E3, - 1.65666309194161350182E3, - 5.57535340817727675546E2 - }; + double P[] = { + 2.46196981473530512524E-10, + 5.64189564831068821977E-1, + 7.46321056442269912687E0, + 4.86371970985681366614E1, + 1.96520832956077098242E2, + 5.26445194995477358631E2, + 9.34528527171957607540E2, + 1.02755188689515710272E3, + 5.57535335369399327526E2 + }; + double Q[] = { + //1.0 + 1.32281951154744992508E1, + 8.67072140885989742329E1, + 3.54937778887819891062E2, + 9.75708501743205489753E2, + 1.82390916687909736289E3, + 2.24633760818710981792E3, + 1.65666309194161350182E3, + 5.57535340817727675546E2 + }; - double R[] = { - 5.64189583547755073984E-1, - 1.27536670759978104416E0, - 5.01905042251180477414E0, - 6.16021097993053585195E0, - 7.40974269950448939160E0, - 2.97886665372100240670E0 - }; - double S[] = { - //1.00000000000000000000E0, - 2.26052863220117276590E0, - 9.39603524938001434673E0, - 1.20489539808096656605E1, - 1.70814450747565897222E1, - 9.60896809063285878198E0, - 3.36907645100081516050E0 - }; + double R[] = { + 5.64189583547755073984E-1, + 1.27536670759978104416E0, + 5.01905042251180477414E0, + 6.16021097993053585195E0, + 7.40974269950448939160E0, + 2.97886665372100240670E0 + }; + double S[] = { + //1.00000000000000000000E0, + 2.26052863220117276590E0, + 9.39603524938001434673E0, + 1.20489539808096656605E1, + 1.70814450747565897222E1, + 9.60896809063285878198E0, + 3.36907645100081516050E0 + }; - if( a < 0.0 ) { - x = -a; - } - else { - x = a; - } + if (a < 0.0) { + x = -a; + } else { + x = a; + } - if( x < 1.0 ) { - return 1.0 - erf(a); - } + if (x < 1.0) { + return 1.0 - erf(a); + } z = -a * a; - if( z < -MAXLOG ) { - if( a < 0 ) { - return( 2.0 ); - } - else { - return( 0.0 ); + if (z < -MAXLOG) { + if (a < 0) { + return (2.0); + } else { + return (0.0); } } z = Math.exp(z); - if( x < 8.0 ) { - p = polevl( x, P, 8 ); - q = p1evl( x, Q, 8 ); + if (x < 8.0) { + p = polevl(x, P, 8); + q = p1evl(x, Q, 8); } else { - p = polevl( x, R, 5 ); - q = p1evl( x, S, 6 ); + p = polevl(x, R, 5); + q = p1evl(x, S, 6); } - y = (z * p)/q; + y = (z * p) / q; - if( a < 0 ) { - y = 2.0 - y; - } + if (a < 0) { + y = 2.0 - y; + } - if( y == 0.0 ) { - if( a < 0 ) { + if (y == 0.0) { + if (a < 0) { return 2.0; + } else { + return (0.0); } - else { - return( 0.0 ); - } - } + } return y; - } + } - /** - * @param a double value - * @return The Error function - *

- * - * Converted to Java from
- * Cephes Math Library Release 2.2: July, 1992
- * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
- */ + /** + * @param a double value + * @return The Error function + *

+ * + * Converted to Java from
+ * Cephes Math Library Release 2.2: July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */ - static public double erf(double x) - throws ArithmeticException { - double y, z; - double T[] = { - 9.60497373987051638749E0, - 9.00260197203842689217E1, - 2.23200534594684319226E3, - 7.00332514112805075473E3, - 5.55923013010394962768E4 - }; - double U[] = { - //1.00000000000000000000E0, - 3.35617141647503099647E1, - 5.21357949780152679795E2, - 4.59432382970980127987E3, - 2.26290000613890934246E4, - 4.92673942608635921086E4 - }; + static public double erf(double x) + throws ArithmeticException { + double y, z; + double T[] = { + 9.60497373987051638749E0, + 9.00260197203842689217E1, + 2.23200534594684319226E3, + 7.00332514112805075473E3, + 5.55923013010394962768E4 + }; + double U[] = { + //1.00000000000000000000E0, + 3.35617141647503099647E1, + 5.21357949780152679795E2, + 4.59432382970980127987E3, + 2.26290000613890934246E4, + 4.92673942608635921086E4 + }; - if( Math.abs(x) > 1.0 ) { - return( 1.0 - erfc(x) ); - } - z = x * x; - y = x * polevl( z, T, 4 ) / p1evl( z, U, 5 ); - return y; -} + if (Math.abs(x) > 1.0) { + return (1.0 - erfc(x)); + } + z = x * x; + y = x * polevl(z, T, 4) / p1evl(z, U, 5); + return y; + } + static private double polevl(double x, double coef[], int N) + throws ArithmeticException { + double ans; + ans = coef[0]; - static private double polevl( double x, double coef[], int N ) - throws ArithmeticException { + for (int i = 1; i <= N; i++) { + ans = ans * x + coef[i]; + } - double ans; + return ans; + } - ans = coef[0]; + static private double p1evl(double x, double coef[], int N) + throws ArithmeticException { - for(int i=1; i<=N; i++) { ans = ans*x+coef[i]; } + double ans; - return ans; - } + ans = x + coef[0]; - static private double p1evl( double x, double coef[], int N ) - throws ArithmeticException { + for (int i = 1; i < N; i++) { + ans = ans * x + coef[i]; + } - double ans; - - ans = x + coef[0]; - - for(int i=1; i 0.5 ) { - p += 1.0; - z = p - q; - } - z = q * Math.sin( Math.PI * z ); - if( z == 0.0 ) { - throw new - ArithmeticException("lgamma: Overflow"); - } - z = LOGPI - Math.log( z ) - w; - return z; - } + if (x < -34.0) { + q = -x; + w = lgamma(q); + p = Math.floor(q); + if (p == q) { + throw new ArithmeticException("lgam: Overflow"); + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = p - q; + } + z = q * Math.sin(Math.PI * z); + if (z == 0.0) { + throw new + ArithmeticException("lgamma: Overflow"); + } + z = LOGPI - Math.log(z) - w; + return z; + } - if( x < 13.0 ) { - z = 1.0; - while( x >= 3.0 ) { - x -= 1.0; - z *= x; - } - while( x < 2.0 ) { - if( x == 0.0 ) { - throw new + if (x < 13.0) { + z = 1.0; + while (x >= 3.0) { + x -= 1.0; + z *= x; + } + while (x < 2.0) { + if (x == 0.0) { + throw new + ArithmeticException("lgamma: Overflow"); + } + z /= x; + x += 1.0; + } + if (z < 0.0) { + z = -z; + } + if (x == 2.0) { + return Math.log(z); + } + x -= 2.0; + p = x * polevl(x, B, 5) / p1evl(x, C, 6); + return (Math.log(z) + p); + } + + if (x > 2.556348e305) { + throw new ArithmeticException("lgamma: Overflow"); - } - z /= x; - x += 1.0; - } - if( z < 0.0 ) { - z = -z; - } - if( x == 2.0 ) { - return Math.log(z); - } - x -= 2.0; - p = x * polevl( x, B, 5 ) / p1evl( x, C, 6); - return( Math.log(z) + p ); - } + } - if( x > 2.556348e305 ) { - throw new - ArithmeticException("lgamma: Overflow"); - } + q = (x - 0.5) * Math.log(x) - x + 0.91893853320467274178; + if (x > 1.0e8) { + return (q); + } - q = ( x - 0.5 ) * Math.log(x) - x + 0.91893853320467274178; - if( x > 1.0e8 ) { - return( q ); - } - - p = 1.0/(x*x); - if( x >= 1000.0 ) { - q += (( 7.9365079365079365079365e-4 * p - - 2.7777777777777777777778e-3) *p - + 0.0833333333333333333333) / x; - } - else { - q += polevl( p, A, 4 ) / x; - } - return q; - } + p = 1.0 / (x * x); + if (x >= 1000.0) { + q += ((7.9365079365079365079365e-4 * p + - 2.7777777777777777777778e-3) * p + + 0.0833333333333333333333) / x; + } else { + q += polevl(p, A, 4) / x; + } + return q; + } + /** + * @param aa double value + * @param bb double value + * @param xx double value + * @return The Incomplete Beta Function evaluated from zero to xx. + *

+ * + * Converted to Java from
+ * Cephes Math Library Release 2.3: July, 1995
+ * Copyright 1984, 1995 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */ - /** - * @param aa double value - * @param bb double value - * @param xx double value - * @return The Incomplete Beta Function evaluated from zero to xx. - *

- * - * Converted to Java from
- * Cephes Math Library Release 2.3: July, 1995
- * Copyright 1984, 1995 by Stephen L. Moshier
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
- */ - - public static double ibeta( double aa, double bb, double xx ) - throws ArithmeticException { + public static double ibeta(double aa, double bb, double xx) + throws ArithmeticException { double a, b, t, x, xc, w, y; boolean flag; - if( aa <= 0.0 || bb <= 0.0 ) { - throw new - ArithmeticException("ibeta: Domain error!"); - } + if (aa <= 0.0 || bb <= 0.0) { + throw new + ArithmeticException("ibeta: Domain error!"); + } - if( (xx <= 0.0) || ( xx >= 1.0) ) { - if( xx == 0.0 ) { + if ((xx <= 0.0) || (xx >= 1.0)) { + if (xx == 0.0) { return 0.0; } - if( xx == 1.0 ) { + if (xx == 1.0) { return 1.0; } - throw new ArithmeticException("ibeta: Domain error!"); - } + throw new ArithmeticException("ibeta: Domain error!"); + } flag = false; - if( (bb * xx) <= 1.0 && xx <= 0.95) { - t = pseries(aa, bb, xx); - return t; - } + if ((bb * xx) <= 1.0 && xx <= 0.95) { + t = pseries(aa, bb, xx); + return t; + } w = 1.0 - xx; /* Reverse a and b if x is greater than the mean. */ - if( xx > (aa/(aa+bb)) ) { - flag = true; - a = bb; - b = aa; - xc = xx; - x = w; - } else { - a = aa; - b = bb; - xc = w; - x = xx; - } + if (xx > (aa / (aa + bb))) { + flag = true; + a = bb; + b = aa; + xc = xx; + x = w; + } else { + a = aa; + b = bb; + xc = w; + x = xx; + } - if( flag && (b * x) <= 1.0 && x <= 0.95) { - t = pseries(a, b, x); - if( t <= MACHEP ) { + if (flag && (b * x) <= 1.0 && x <= 0.95) { + t = pseries(a, b, x); + if (t <= MACHEP) { t = 1.0 - MACHEP; - } - else { + } else { t = 1.0 - t; } - return t; - } + return t; + } /* Choose expansion for better convergence. */ - y = x * (a+b-2.0) - (a-1.0); - if( y < 0.0 ) { - w = incbcf( a, b, x ); - } - else { - w = incbd( a, b, x ) / xc; - } + y = x * (a + b - 2.0) - (a - 1.0); + if (y < 0.0) { + w = incbcf(a, b, x); + } else { + w = incbd(a, b, x) / xc; + } /* Multiply w by the factor a b _ _ _ @@ -1261,221 +1248,218 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 y = a * Math.log(x); t = b * Math.log(xc); - if( (a+b) < MAXGAM && Math.abs(y) < MAXLOG && Math.abs(t) < MAXLOG ) { - t = Math.pow(xc,b); - t *= Math.pow(x,a); - t /= a; - t *= w; - t *= gamma(a+b) / (gamma(a) * gamma(b)); - if( flag ) { - if( t <= MACHEP ) { + if ((a + b) < MAXGAM && Math.abs(y) < MAXLOG && Math.abs(t) < MAXLOG) { + t = Math.pow(xc, b); + t *= Math.pow(x, a); + t /= a; + t *= w; + t *= gamma(a + b) / (gamma(a) * gamma(b)); + if (flag) { + if (t <= MACHEP) { t = 1.0 - MACHEP; - } - else { + } else { t = 1.0 - t; } - } - return t; - } - /* Resort to logarithms. */ - y += t + lgamma(a+b) - lgamma(a) - lgamma(b); - y += Math.log(w/a); - if( y < MINLOG ) { - t = 0.0; - } - else { - t = Math.exp(y); - } - - if( flag ) { - if( t <= MACHEP ) { - t = 1.0 - MACHEP; } - else { + return t; + } + /* Resort to logarithms. */ + y += t + lgamma(a + b) - lgamma(a) - lgamma(b); + y += Math.log(w / a); + if (y < MINLOG) { + t = 0.0; + } else { + t = Math.exp(y); + } + + if (flag) { + if (t <= MACHEP) { + t = 1.0 - MACHEP; + } else { t = 1.0 - t; } - } + } return t; - } + } /* Continued fraction expansion #1 * for incomplete beta integral */ - private static double incbcf( double a, double b, double x ) - throws ArithmeticException { - double xk, pk, pkm1, pkm2, qk, qkm1, qkm2; - double k1, k2, k3, k4, k5, k6, k7, k8; - double r, t, ans, thresh; - int n; - double big = 4.503599627370496e15; - double biginv = 2.22044604925031308085e-16; + private static double incbcf(double a, double b, double x) + throws ArithmeticException { + double xk, pk, pkm1, pkm2, qk, qkm1, qkm2; + double k1, k2, k3, k4, k5, k6, k7, k8; + double r, t, ans, thresh; + int n; + double big = 4.503599627370496e15; + double biginv = 2.22044604925031308085e-16; - k1 = a; - k2 = a + b; - k3 = a; - k4 = a + 1.0; - k5 = 1.0; - k6 = b - 1.0; - k7 = k4; - k8 = a + 2.0; + k1 = a; + k2 = a + b; + k3 = a; + k4 = a + 1.0; + k5 = 1.0; + k6 = b - 1.0; + k7 = k4; + k8 = a + 2.0; - pkm2 = 0.0; - qkm2 = 1.0; - pkm1 = 1.0; - qkm1 = 1.0; - ans = 1.0; - r = 1.0; - n = 0; - thresh = 3.0 * MACHEP; - do { - xk = -( x * k1 * k2 )/( k3 * k4 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + pkm2 = 0.0; + qkm2 = 1.0; + pkm1 = 1.0; + qkm1 = 1.0; + ans = 1.0; + r = 1.0; + n = 0; + thresh = 3.0 * MACHEP; + do { + xk = -(x * k1 * k2) / (k3 * k4); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - xk = ( x * k5 * k6 )/( k7 * k8 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + xk = (x * k5 * k6) / (k7 * k8); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - if( qk != 0 ) { - r = pk/qk; - } - if( r != 0 ) { - t = Math.abs( (ans - r)/r ); - ans = r; - } else { - t = 1.0; - } + if (qk != 0) { + r = pk / qk; + } + if (r != 0) { + t = Math.abs((ans - r) / r); + ans = r; + } else { + t = 1.0; + } - if( t < thresh ) { - return ans; - } + if (t < thresh) { + return ans; + } - k1 += 1.0; - k2 += 1.0; - k3 += 2.0; - k4 += 2.0; - k5 += 1.0; - k6 -= 1.0; - k7 += 2.0; - k8 += 2.0; + k1 += 1.0; + k2 += 1.0; + k3 += 2.0; + k4 += 2.0; + k5 += 1.0; + k6 -= 1.0; + k7 += 2.0; + k8 += 2.0; - if( (Math.abs(qk) + Math.abs(pk)) > big ) { - pkm2 *= biginv; - pkm1 *= biginv; - qkm2 *= biginv; - qkm1 *= biginv; - } - if( (Math.abs(qk) < biginv) || (Math.abs(pk) < biginv) ) { - pkm2 *= big; - pkm1 *= big; - qkm2 *= big; - qkm1 *= big; - } - } while( ++n < 300 ); + if ((Math.abs(qk) + Math.abs(pk)) > big) { + pkm2 *= biginv; + pkm1 *= biginv; + qkm2 *= biginv; + qkm1 *= biginv; + } + if ((Math.abs(qk) < biginv) || (Math.abs(pk) < biginv)) { + pkm2 *= big; + pkm1 *= big; + qkm2 *= big; + qkm1 *= big; + } + } while (++n < 300); - return ans; - } + return ans; + } /* Continued fraction expansion #2 * for incomplete beta integral */ - static private double incbd( double a, double b, double x ) - throws ArithmeticException { - double xk, pk, pkm1, pkm2, qk, qkm1, qkm2; - double k1, k2, k3, k4, k5, k6, k7, k8; - double r, t, ans, z, thresh; - int n; - double big = 4.503599627370496e15; - double biginv = 2.22044604925031308085e-16; + static private double incbd(double a, double b, double x) + throws ArithmeticException { + double xk, pk, pkm1, pkm2, qk, qkm1, qkm2; + double k1, k2, k3, k4, k5, k6, k7, k8; + double r, t, ans, z, thresh; + int n; + double big = 4.503599627370496e15; + double biginv = 2.22044604925031308085e-16; - k1 = a; - k2 = b - 1.0; - k3 = a; - k4 = a + 1.0; - k5 = 1.0; - k6 = a + b; - k7 = a + 1.0; - k8 = a + 2.0; + k1 = a; + k2 = b - 1.0; + k3 = a; + k4 = a + 1.0; + k5 = 1.0; + k6 = a + b; + k7 = a + 1.0; + k8 = a + 2.0; - pkm2 = 0.0; - qkm2 = 1.0; - pkm1 = 1.0; - qkm1 = 1.0; - z = x / (1.0-x); - ans = 1.0; - r = 1.0; - n = 0; - thresh = 3.0 * MACHEP; - do { - xk = -( z * k1 * k2 )/( k3 * k4 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + pkm2 = 0.0; + qkm2 = 1.0; + pkm1 = 1.0; + qkm1 = 1.0; + z = x / (1.0 - x); + ans = 1.0; + r = 1.0; + n = 0; + thresh = 3.0 * MACHEP; + do { + xk = -(z * k1 * k2) / (k3 * k4); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - xk = ( z * k5 * k6 )/( k7 * k8 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + xk = (z * k5 * k6) / (k7 * k8); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - if( qk != 0 ) { - r = pk/qk; - } - if( r != 0 ) { - t = Math.abs( (ans - r)/r ); - ans = r; - } else { - t = 1.0; - } + if (qk != 0) { + r = pk / qk; + } + if (r != 0) { + t = Math.abs((ans - r) / r); + ans = r; + } else { + t = 1.0; + } - if( t < thresh ) { - return ans; - } + if (t < thresh) { + return ans; + } - k1 += 1.0; - k2 -= 1.0; - k3 += 2.0; - k4 += 2.0; - k5 += 1.0; - k6 += 1.0; - k7 += 2.0; - k8 += 2.0; + k1 += 1.0; + k2 -= 1.0; + k3 += 2.0; + k4 += 2.0; + k5 += 1.0; + k6 += 1.0; + k7 += 2.0; + k8 += 2.0; - if( (Math.abs(qk) + Math.abs(pk)) > big ) { - pkm2 *= biginv; - pkm1 *= biginv; - qkm2 *= biginv; - qkm1 *= biginv; - } - if( (Math.abs(qk) < biginv) || (Math.abs(pk) < biginv) ) { - pkm2 *= big; - pkm1 *= big; - qkm2 *= big; - qkm1 *= big; - } - } while( ++n < 300 ); + if ((Math.abs(qk) + Math.abs(pk)) > big) { + pkm2 *= biginv; + pkm1 *= biginv; + qkm2 *= biginv; + qkm1 *= biginv; + } + if ((Math.abs(qk) < biginv) || (Math.abs(pk) < biginv)) { + pkm2 *= big; + pkm1 *= big; + qkm2 *= big; + qkm1 *= big; + } + } while (++n < 300); return ans; - } + } /* Power series for incomplete beta integral. Use when b*x is small and x not too close to 1. */ - static private double pseries( double a, double b, double x ) - throws ArithmeticException { + static private double pseries(double a, double b, double x) + throws ArithmeticException { double s, t, u, v, n, t1, z, ai; ai = 1.0 / a; @@ -1486,44 +1470,45 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 n = 2.0; s = 0.0; z = MACHEP * ai; - while( Math.abs(v) > z ) { - u = (n - b) * x / n; - t *= u; - v = t / (a + n); - s += v; - n += 1.0; - } + while (Math.abs(v) > z) { + u = (n - b) * x / n; + t *= u; + v = t / (a + n); + s += v; + n += 1.0; + } s += t1; s += ai; u = a * Math.log(x); - if( (a+b) < MAXGAM && Math.abs(u) < MAXLOG ) { - t = gamma(a+b)/(gamma(a)*gamma(b)); - s = s * t * Math.pow(x,a); - } else { - t = lgamma(a+b) - lgamma(a) - lgamma(b) + u + Math.log(s); - if( t < MINLOG ) { - s = 0.0; - } - else { - s = Math.exp(t); - } - } + if ((a + b) < MAXGAM && Math.abs(u) < MAXLOG) { + t = gamma(a + b) / (gamma(a) * gamma(b)); + s = s * t * Math.pow(x, a); + } else { + t = lgamma(a + b) - lgamma(a) - lgamma(b) + u + Math.log(s); + if (t < MINLOG) { + s = 0.0; + } else { + s = Math.exp(t); + } + } return s; - } - public static double getnormpdf(double x) { + } + + public static double getnormpdf(double x) { // k = find(sigma > 0); // if any(k) // xn = (x(k) - mu(k)) ./ sigma(k); // y(k) = exp(-0.5 * xn .^2) ./ (sqrt(2*pi) .* sigma(k)); // end - double y = Math.exp(-0.5 *x *x) / Math.sqrt(2.0*Math.PI); - return y; - } - public static double getnormcdf(double x) { - //p = 0.5 * erfc(-(x-mu)./(sqrt(2)*sigma)); - double p = 0.5 * erfc(-x/Math.sqrt(2)); - return p; - } + double y = Math.exp(-0.5 * x * x) / Math.sqrt(2.0 * Math.PI); + return y; + } + + public static double getnormcdf(double x) { + //p = 0.5 * erfc(-(x-mu)./(sqrt(2)*sigma)); + double p = 0.5 * erfc(-x / Math.sqrt(2)); + return p; + } } diff --git a/src/eva2/tools/math/StatisticUtils.java b/src/eva2/tools/math/StatisticUtils.java index c8e2a409..6c77b2b6 100644 --- a/src/eva2/tools/math/StatisticUtils.java +++ b/src/eva2/tools/math/StatisticUtils.java @@ -12,441 +12,444 @@ package eva2.tools.math; // Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany // /////////////////////////////////////////////////////////////////////////////// + import eva2.optimization.problems.AbstractProblemDouble; import eva2.tools.math.Jama.Matrix; + import java.util.ArrayList; import java.util.Collections; /** * Statistic utils. */ -public class StatisticUtils -{ - /** The natural logarithm of 2. */ - public static double log2 = Math.log(2); +public class StatisticUtils { + /** + * The natural logarithm of 2. + */ + public static double log2 = Math.log(2); - /** The small deviation allowed in double comparisons */ - public static double SMALL = 1e-6; + /** + * The small deviation allowed in double comparisons + */ + public static double SMALL = 1e-6; - /** - * Returns the correlation coefficient of two double vectors. - * - * @param y1 double vector 1 - * @param y2 double vector 2 - * @param n the length of two double vectors - * @return the correlation coefficient - */ - public final static double correlation(double y1[],double y2[]) { + /** + * Returns the correlation coefficient of two double vectors. + * + * @param y1 double vector 1 + * @param y2 double vector 2 + * @param n the length of two double vectors + * @return the correlation coefficient + */ + public final static double correlation(double y1[], double y2[]) { - int i; - double av1 = 0.0, av2 = 0.0, y11 = 0.0, y22 = 0.0, y12 = 0.0, c; - int n=y1.length; - if (n!=y2.length) { - throw new RuntimeException("Error, mismatching vectors for correlation calculation in StatisticUtils.correlation(double[], double[])"); + int i; + double av1 = 0.0, av2 = 0.0, y11 = 0.0, y22 = 0.0, y12 = 0.0, c; + int n = y1.length; + if (n != y2.length) { + throw new RuntimeException("Error, mismatching vectors for correlation calculation in StatisticUtils.correlation(double[], double[])"); + } + + if (n <= 1) { + return 1.0; + } + for (i = 0; i < n; i++) { + av1 += y1[i]; + av2 += y2[i]; + } + av1 /= (double) n; + av2 /= (double) n; + for (i = 0; i < n; i++) { + y11 += (y1[i] - av1) * (y1[i] - av1); + y22 += (y2[i] - av2) * (y2[i] - av2); + y12 += (y1[i] - av1) * (y2[i] - av2); + } + if (y11 * y22 == 0.0) { + c = 1.0; + } else { + c = y12 / Math.sqrt(Math.abs(y11 * y22)); + } + + return c; + } + + /** + * Computes differential shannon entropy + * + * @return DSE=SE(AB)-0.5*[SE(A)+SE(B)] + */ + public static double differentialShannon(int counts1[], int counts2[], int n, int countsSum1, int countsSum2) { + double seA = 0.0; + double seB = 0.0; + double seAB = 0.0; + double c = 0.0; + int AB; + int allSum = countsSum1 + countsSum2; + for (int i = 0; i < n; i++) { + AB = counts1[i] + counts2[i]; + seA -= xlogx(((double) counts1[i]) / ((double) countsSum1)); + seB -= xlogx(((double) counts2[i]) / ((double) countsSum2)); + seAB -= xlogx(((double) AB) / ((double) allSum)); + } + + c = seAB - 0.5 * (seA + seB); + + return c; + } + + /** + * Computes entropy for an array of integers. + * + * @param counts array of counts + * @return - a log2 a - b log2 b - c log2 c + (a+b+c) log2 (a+b+c) + * when given array [a b c] + */ + public static double info(int counts[]) { + + int total = 0; + int c; + double x = 0; + for (int j = 0; j < counts.length; j++) { + x -= xlogx(counts[j]); + total += counts[j]; + } + return x + xlogx(total); + } + + /** + * Computes shannon entropy for an array of integers. + * + * @param counts array of counts + * @return - a log2 a - b log2 b - c log2 c + * when given array [a b c] + */ + public static double shannon(int counts[], int countsSum) { + + double x = 0; + for (int j = 0; j < counts.length; j++) { + x -= xlogx(((double) counts[j]) / ((double) countsSum)); + } + return x; + } + + + /** + * Returns the logarithm of a for base 2. + * + * @param a a double + */ + public static final double log2(double a) { + + return Math.log(a) / log2; + } + + /** + * Returns index of maximum element in a given + * array of doubles. First maximum is returned. + * + * @param doubles the array of doubles + * @return the index of the maximum element + */ + public static int maxIndex(double[] doubles) { + + double maximum = 0; + int maxIndex = 0; + + for (int i = 0; i < doubles.length; i++) { + if ((i == 0) || (doubles[i] > maximum)) { + maxIndex = i; + maximum = doubles[i]; } + } - if (n <= 1) { - return 1.0; - } - for (i = 0; i < n; i++) { - av1 += y1[i]; - av2 += y2[i]; - } - av1 /= (double) n; - av2 /= (double) n; - for (i = 0; i < n; i++) { - y11 += (y1[i] - av1) * (y1[i] - av1); - y22 += (y2[i] - av2) * (y2[i] - av2); - y12 += (y1[i] - av1) * (y2[i] - av2); - } - if (y11 * y22 == 0.0) { - c=1.0; - } else { - c = y12 / Math.sqrt(Math.abs(y11 * y22)); - } + return maxIndex; + } - return c; - } + /** + * Returns index of maximum element in a given + * array of integers. First maximum is returned. + * + * @param ints the array of integers + * @return the index of the maximum element + */ + public static int maxIndex(int[] ints) { - /** - * Computes differential shannon entropy - * - * @return DSE=SE(AB)-0.5*[SE(A)+SE(B)] - */ - public static double differentialShannon(int counts1[],int counts2[], int n, int countsSum1, int countsSum2) - { - double seA=0.0; - double seB=0.0; - double seAB=0.0; - double c=0.0; - int AB; - int allSum = countsSum1+countsSum2; - for(int i=0;i maximum)) { - maxIndex = i; - maximum = doubles[i]; - } - } - - return maxIndex; - } - - /** - * Returns index of maximum element in a given - * array of integers. First maximum is returned. - * - * @param ints the array of integers - * @return the index of the maximum element - */ - public static int maxIndex(int [] ints) { - - int maximum = 0; - int maxIndex = 0; - - for (int i = 0; i < ints.length; i++) { - if ((i == 0) || (ints[i] > maximum)) { - maxIndex = i; - maximum = ints[i]; - } - } - - return maxIndex; - } - - /** - * Returns index of minimum element in a given - * array of integers. First minimum is returned. - * - * @param ints the array of integers - * @return the index of the minimum element - */ - public static int minIndex(int [] ints) { - - int minimum = 0; - int minIndex = 0; - - for (int i = 0; i < ints.length; i++) { - if ((i == 0) || (ints[i] < minimum)) { - minIndex = i; - minimum = ints[i]; - } - } - - return minIndex; - } - - /** - * Returns index of minimum element in a given - * array of doubles. First minimum is returned. - * - * @param doubles the array of doubles - * @return the index of the minimum element - */ - public static int minIndex(double [] doubles) { - - double minimum = 0; - int minIndex = 0; - - for (int i = 0; i < doubles.length; i++) { - if ((i == 0) || (doubles[i] < minimum)) { - minIndex = i; - minimum = doubles[i]; - } - } - - return minIndex; - } - - /** - * Computes the variance for an array of doubles. - * - * @param vector the array - * @param finiteSet if true, the vector is interpreted as complete data set, otherwise a set of samples of a larger set. - * @return the variance - */ - public static double variance(double[] vector, boolean finiteSet) { - - double sum = 0, sumSquared = 0; - int n=vector.length; - if (n <= 1) { - return 0; - } - for (int i = 0; i < n; i++) { - sum += vector[i]; - sumSquared += (vector[i] * vector[i]); - } - double denom; - if (finiteSet) { - denom=n; + for (int i = 0; i < ints.length; i++) { + if ((i == 0) || (ints[i] > maximum)) { + maxIndex = i; + maximum = ints[i]; } - else { - denom=(n-1); + } + + return maxIndex; + } + + /** + * Returns index of minimum element in a given + * array of integers. First minimum is returned. + * + * @param ints the array of integers + * @return the index of the minimum element + */ + public static int minIndex(int[] ints) { + + int minimum = 0; + int minIndex = 0; + + for (int i = 0; i < ints.length; i++) { + if ((i == 0) || (ints[i] < minimum)) { + minIndex = i; + minimum = ints[i]; } - double result = (sumSquared - (sum * sum / (double) n)) / denom; + } - // We don't like negative variance - if (result < 0) { - return 0; - } else { - return result; - } - } + return minIndex; + } - /** - * Returns c*log2(c) for a given integer value c. - * - * @param c an integer value - * @return c*log2(c) (but is careful to return 0 if c is 0) - */ - public static final double xlogx(int c) { + /** + * Returns index of minimum element in a given + * array of doubles. First minimum is returned. + * + * @param doubles the array of doubles + * @return the index of the minimum element + */ + public static int minIndex(double[] doubles) { - if (c == 0) { - return 0.0; - } - return c * StatisticUtils.log2((double) c); - } + double minimum = 0; + int minIndex = 0; - /** - * Returns c*log2(c) for a given value c. - * - * @param c an integer value - * @return c*log2(c) (but is careful to return 0 if c is 0) - */ - public static final double xlogx(double c) { + for (int i = 0; i < doubles.length; i++) { + if ((i == 0) || (doubles[i] < minimum)) { + minIndex = i; + minimum = doubles[i]; + } + } - if (c == 0) { - return 0.0; - } - return c * StatisticUtils.log2( c); - } + return minIndex; + } - /** - * Tests if a is equal to b. - * - * @param a a double - * @param b a double - */ - public static final boolean eq(double a, double b){ + /** + * Computes the variance for an array of doubles. + * + * @param vector the array + * @param finiteSet if true, the vector is interpreted as complete data set, otherwise a set of samples of a larger set. + * @return the variance + */ + public static double variance(double[] vector, boolean finiteSet) { - return (a - b < SMALL) && (b - a < SMALL); - } + double sum = 0, sumSquared = 0; + int n = vector.length; + if (n <= 1) { + return 0; + } + for (int i = 0; i < n; i++) { + sum += vector[i]; + sumSquared += (vector[i] * vector[i]); + } + double denom; + if (finiteSet) { + denom = n; + } else { + denom = (n - 1); + } + double result = (sumSquared - (sum * sum / (double) n)) / denom; - /** - * Tests if a is smaller or equal to b. - * - * @param a a double - * @param b a double - */ - public static final boolean smOrEq(double a,double b) { + // We don't like negative variance + if (result < 0) { + return 0; + } else { + return result; + } + } - return (a-b < SMALL); - } + /** + * Returns c*log2(c) for a given integer value c. + * + * @param c an integer value + * @return c*log2(c) (but is careful to return 0 if c is 0) + */ + public static final double xlogx(int c) { - /** - * Tests if a is greater or equal to b. - * - * @param a a double - * @param b a double - */ - public static final boolean grOrEq(double a,double b) { + if (c == 0) { + return 0.0; + } + return c * StatisticUtils.log2((double) c); + } - return (b-a < SMALL); - } + /** + * Returns c*log2(c) for a given value c. + * + * @param c an integer value + * @return c*log2(c) (but is careful to return 0 if c is 0) + */ + public static final double xlogx(double c) { - /** - * Tests if a is smaller than b. - * - * @param a a double - * @param b a double - */ - public static final boolean sm(double a,double b) { + if (c == 0) { + return 0.0; + } + return c * StatisticUtils.log2(c); + } - return (b-a > SMALL); - } + /** + * Tests if a is equal to b. + * + * @param a a double + * @param b a double + */ + public static final boolean eq(double a, double b) { - /** - * Tests if a is greater than b. - * - * @param a a double - * @param b a double - */ - public static final boolean gr(double a,double b) { + return (a - b < SMALL) && (b - a < SMALL); + } - return (a-b > SMALL); - } + /** + * Tests if a is smaller or equal to b. + * + * @param a a double + * @param b a double + */ + public static final boolean smOrEq(double a, double b) { - /** - * returns root mean square error. - */ - public static final double rmsError(double array1[], double array2[]) - { - if ((array1 == null) || (array2 == null)) { return -1.0; } + return (a - b < SMALL); + } - double errorValueRMS = 0; - for (int i=0; i SMALL); + } - for (int i=0; i SMALL); + } - double n = (double) array1.length; - double numerator = sumAB - (sumA*sumB/n); - double denominator = Math.sqrt((sumAA - (sumA*sumA/n)) * (sumBB - (sumB*sumB/n))); - double corrCoefficient = numerator / denominator; - corrCoefficient *= corrCoefficient; + /** + * returns root mean square error. + */ + public static final double rmsError(double array1[], double array2[]) { + if ((array1 == null) || (array2 == null)) { + return -1.0; + } - return corrCoefficient; - } + double errorValueRMS = 0; + for (int i = 0; i < array1.length; i++) { + // add squared error value + errorValueRMS += (array1[i] - array2[i]) * (array1[i] - array2[i]); + } + // calculate mean and root of the sum of the squared error values + errorValueRMS = Math.sqrt(errorValueRMS / (double) array1.length); - /** - * Main method for testing this class. - */ - public static void main(String[] ops) { - double[][] vs = {{ 356.873,-498.563, 130.923,-223.684, 494.296, 380.739, 481.353, 344.571, 501.105,-166.109}, - { 199.116,-423.448, 487.898, 344.579, 140.709, 89.007,-259.310, 512.000, 152.069,-440.778}, - { 439.128, 112.370,-422.820,-43.119,-297.609,-438.940, 488.914,-512.000,-407.847, 386.611}, - { 395.772, 191.634,-511.999,-93.078,-282.853,-444.621, 491.291,-512.000,-407.620, 386.493}}; - - vs[1]=Mathematics.rotate(vs[0], AbstractProblemDouble.initializeDefaultRotationMatrix(10, 10)); - - for (int i=0; i + * Correlation ("Statistik", 7 Aufl., Hartung, 1989, Kapitel 9 und 10, S.546-608): + * a=yMess[i]; + * b=yWahr[i]; + * aa=a*a; + * bb=b*b; + * ab=a*b; + * numerator=sumAB-(sumA*sumB/n); + * denominator=sqrt[(sumAA-(sumA*sumA/n))*(sumBB-(sumB*sumB/n))]; + * R=correlationcoefficient=numerator/denominator; + * + * @author Joerg K. Wegner + */ + public static double getCorrelationCoefficient(double array1[], double array2[]) { + if ((array1 == null) || (array2 == null)) { + return -2.0; + } + + double sumA = 0; + double sumB = 0; + double sumAB = 0; + double sumAA = 0; + double sumBB = 0; + + for (int i = 0; i < array1.length; i++) { + double a = array1[i]; + double b = array2[i]; + + sumA += a; + sumB += b; + sumAA += a * a; + sumBB += b * b; + sumAB += a * b; + } + + double n = (double) array1.length; + double numerator = sumAB - (sumA * sumB / n); + double denominator = Math.sqrt((sumAA - (sumA * sumA / n)) * (sumBB - (sumB * sumB / n))); + double corrCoefficient = numerator / denominator; + corrCoefficient *= corrCoefficient; + + return corrCoefficient; + } + + /** + * Main method for testing this class. + */ + public static void main(String[] ops) { + double[][] vs = {{356.873, -498.563, 130.923, -223.684, 494.296, 380.739, 481.353, 344.571, 501.105, -166.109}, + {199.116, -423.448, 487.898, 344.579, 140.709, 89.007, -259.310, 512.000, 152.069, -440.778}, + {439.128, 112.370, -422.820, -43.119, -297.609, -438.940, 488.914, -512.000, -407.847, 386.611}, + {395.772, 191.634, -511.999, -93.078, -282.853, -444.621, 491.291, -512.000, -407.620, 386.493}}; + + vs[1] = Mathematics.rotate(vs[0], AbstractProblemDouble.initializeDefaultRotationMatrix(10, 10)); + + for (int i = 0; i < vs.length; i++) { + for (int j = 0; j < vs.length; j++) { + System.out.print("\t" + correlation(vs[i], vs[j])); + } + System.out.println(); + } // vs[1]=Mathematics.rotate(vs[0], AbstractProblemDouble.initializeDefaultRotationMatrix(30, 10)); // vs[2]=Mathematics.rotate(vs[0], AbstractProblemDouble.initializeDefaultRotationMatrix(50, 10)); // vs[3]=Mathematics.rotate(vs[0], AbstractProblemDouble.initializeDefaultRotationMatrix(70, 10)); - - vs = new double[][]{{0.1,0.9}, - {0.8,0.2}, + + vs = new double[][]{{0.1, 0.9}, + {0.8, 0.2}, // {0.8,0.2}, - {0.0,1.0}}; - System.out.println("---"); - + {0.0, 1.0}}; + System.out.println("---"); + // for (int i=0; i indices = new ArrayList( samples ); - for( int i=0; i indices = new ArrayList(samples); + for (int i = 0; i < samples; ++i) { + indices.add(i); + } - // X(:,i) = randperm(n)'; - Collections.shuffle( indices ); - for( int j=0; j rlhPoints(int samples, int dim, double lb, double ub, boolean edges) - { - ArrayList samplePoints = new ArrayList(samples); - Matrix p = rlh( samples,dim,lb,ub,edges ); + return X; + } - for( int i=0; i rlhPoints(int samples, int dim, double lb, double ub, boolean edges) { + ArrayList samplePoints = new ArrayList(samples); + Matrix p = rlh(samples, dim, lb, ub, edges); - Matrix x = new Matrix(dim,1); - for( int j=0; j rlhPoints(int samples, double[][] range, boolean edges) - { - ArrayList rlhM = rlhPoints(samples, range.length, 0, 1, edges); - for( int i=0; i rlhPoints(int samples, double[][] range, boolean edges) { + ArrayList rlhM = rlhPoints(samples, range.length, 0, 1, edges); + for (int i = 0; i < rlhM.size(); ++i) { + Matrix p = rlhM.get(i); + for (int j = 0; j < range.length; ++j) { + // carsten hatte nen bug im RLH - zählweise der indices beginnt bei 0, nicht bei 1 + p.set(j, 0, range[j][0] + p.get(j, 0) * (range[j][1] - range[j][0])); + } + } + return rlhM; + } } diff --git a/src/eva2/tools/math/interpolation/AbstractDataModifier.java b/src/eva2/tools/math/interpolation/AbstractDataModifier.java index 126c63c3..6fd43ad2 100644 --- a/src/eva2/tools/math/interpolation/AbstractDataModifier.java +++ b/src/eva2/tools/math/interpolation/AbstractDataModifier.java @@ -26,25 +26,26 @@ package eva2.tools.math.interpolation; * The minimal set of functions which should implemented in a data modifier for * AbstractDataSet. */ -public abstract class AbstractDataModifier -{ +public abstract class AbstractDataModifier { /*-------------------------------------------------------------------------* - * abstract methods + * abstract methods *-------------------------------------------------------------------------*/ - /** - * Modifies the X data. - */ - public abstract void modifyX(double[] setX); - /** - * Modifies the Y data. - */ - public abstract void modifyY(double[] setY); - /** - * Modifies the data. - */ - public abstract void modify(double[] setX, double[] setY); + /** + * Modifies the X data. + */ + public abstract void modifyX(double[] setX); + + /** + * Modifies the Y data. + */ + public abstract void modifyY(double[] setY); + + /** + * Modifies the data. + */ + public abstract void modify(double[] setX, double[] setY); } /**************************************************************************** diff --git a/src/eva2/tools/math/interpolation/AbstractDataSet.java b/src/eva2/tools/math/interpolation/AbstractDataSet.java index 5e4afb54..ae1f9deb 100644 --- a/src/eva2/tools/math/interpolation/AbstractDataSet.java +++ b/src/eva2/tools/math/interpolation/AbstractDataSet.java @@ -22,94 +22,98 @@ package eva2.tools.math.interpolation; * CLASS DECLARATION *==========================================================================*/ -public abstract class AbstractDataSet -{ - /*-------------------------------------------------------------------------* - * public member variables +public abstract class AbstractDataSet { + /*-------------------------------------------------------------------------* + * public member variables *-------------------------------------------------------------------------*/ /*--------------------------------------------------------------o-----------* * protected member variables *-------------------------------------------------------------------------*/ - /** - * double array of X data. - * - * @see #yDoubleData - */ - protected double[] xDoubleData = { -1, 1 }; - /** - * double array of Y data. - * - * @see #xDoubleData - */ - protected double[] yDoubleData = { 1, 1 }; + /** + * double array of X data. + * + * @see #yDoubleData + */ + protected double[] xDoubleData = {-1, 1}; + /** + * double array of Y data. + * + * @see #xDoubleData + */ + protected double[] yDoubleData = {1, 1}; /*-------------------------------------------------------------------------* * abstract methods *-------------------------------------------------------------------------*/ - /** - * Returns the length of the data set - * @return the length of the data set - */ - public int getLength() - { - return xDoubleData.length; - } - /** - * Returns an array of the X data - * @return the array of the X data - */ - public double[] getXData() - { - return xDoubleData; - } - /** - * Returns an array of the Y data - * @return the array of the Y data - */ - public double[] getYData() - { - return yDoubleData; - } - /** - * Returns the X label of the data set - * @return the X label of the data set - */ - public abstract String getXLabel(); - /** - * Returns the Y label of the data set - * @return the Y label of the data set - */ - public abstract String getYLabel(); + /** + * Returns the length of the data set + * + * @return the length of the data set + */ + public int getLength() { + return xDoubleData.length; + } - /** - * Modifies the X data. - * - * @param the data modifier - */ - public void modifyXData(AbstractDataModifier modifier) - { - modifier.modifyX(xDoubleData); - } - /** - * Modifies the Y data. - * - * @param the data modifier - */ - public void modifyYData(AbstractDataModifier modifier) - { - modifier.modifyY(yDoubleData); - } - /** - * Modifies the data. - * - * @param the data modifier - */ - public void modifyData(AbstractDataModifier modifier) - { - modifier.modify(xDoubleData, yDoubleData); - } + /** + * Returns an array of the X data + * + * @return the array of the X data + */ + public double[] getXData() { + return xDoubleData; + } + + /** + * Returns an array of the Y data + * + * @return the array of the Y data + */ + public double[] getYData() { + return yDoubleData; + } + + /** + * Returns the X label of the data set + * + * @return the X label of the data set + */ + public abstract String getXLabel(); + + /** + * Returns the Y label of the data set + * + * @return the Y label of the data set + */ + public abstract String getYLabel(); + + /** + * Modifies the X data. + * + * @param the data modifier + */ + public void modifyXData(AbstractDataModifier modifier) { + modifier.modifyX(xDoubleData); + } + + /** + * Modifies the Y data. + * + * @param the data modifier + */ + public void modifyYData(AbstractDataModifier modifier) { + modifier.modifyY(yDoubleData); + } + + /** + * Modifies the data. + * + * @param the data modifier + */ + public void modifyData(AbstractDataModifier modifier) { + modifier.modify(xDoubleData, yDoubleData); + } } /**************************************************************************** * END OF FILE diff --git a/src/eva2/tools/math/interpolation/BasicDataSet.java b/src/eva2/tools/math/interpolation/BasicDataSet.java index d8d5c8a8..2512d8d2 100644 --- a/src/eva2/tools/math/interpolation/BasicDataSet.java +++ b/src/eva2/tools/math/interpolation/BasicDataSet.java @@ -18,52 +18,47 @@ package eva2.tools.math.interpolation; * The minimum wrapper class for an AbstractDataSet. */ public class BasicDataSet extends AbstractDataSet { - protected int dataType = -1; - protected String xLabel = null; - protected String yLabel = null; + protected int dataType = -1; + protected String xLabel = null; + protected String yLabel = null; - public BasicDataSet() - { - this(null, null, null, null); - } + public BasicDataSet() { + this(null, null, null, null); + } - public BasicDataSet( - double[] xDoubleData, - double[] yDoubleData, - int dataType) { - this(xDoubleData, yDoubleData, null, null); - } + public BasicDataSet( + double[] xDoubleData, + double[] yDoubleData, + int dataType) { + this(xDoubleData, yDoubleData, null, null); + } - public BasicDataSet( - double[] xDoubleData, - double[] yDoubleData, - String xLabel, - String yLabel) { - this.xDoubleData = xDoubleData; - this.yDoubleData = yDoubleData; - this.xLabel = xLabel; - this.yLabel = yLabel; - } + public BasicDataSet( + double[] xDoubleData, + double[] yDoubleData, + String xLabel, + String yLabel) { + this.xDoubleData = xDoubleData; + this.yDoubleData = yDoubleData; + this.xLabel = xLabel; + this.yLabel = yLabel; + } - public int getDataType() - { - return dataType; - } + public int getDataType() { + return dataType; + } @Override - public String getXLabel() - { - return xLabel; - } + public String getXLabel() { + return xLabel; + } @Override - public String getYLabel() - { - return yLabel; - } + public String getYLabel() { + return yLabel; + } - public String getAdditionalInformation(String parm1) - { - return new String(); - } + public String getAdditionalInformation(String parm1) { + return new String(); + } } diff --git a/src/eva2/tools/math/interpolation/InterpolationException.java b/src/eva2/tools/math/interpolation/InterpolationException.java index 6fd68713..6eb40d8d 100644 --- a/src/eva2/tools/math/interpolation/InterpolationException.java +++ b/src/eva2/tools/math/interpolation/InterpolationException.java @@ -26,17 +26,15 @@ package eva2.tools.math.interpolation; /** * Exception for interpolation error. */ -public class InterpolationException extends Exception -{ +public class InterpolationException extends Exception { - public InterpolationException() - { - super(); - } - public InterpolationException(String s) - { - super(s); - } + public InterpolationException() { + super(); + } + + public InterpolationException(String s) { + super(s); + } } /**************************************************************************** diff --git a/src/eva2/tools/math/interpolation/LinearInterpolation.java b/src/eva2/tools/math/interpolation/LinearInterpolation.java index 0066b043..0b6af8e6 100644 --- a/src/eva2/tools/math/interpolation/LinearInterpolation.java +++ b/src/eva2/tools/math/interpolation/LinearInterpolation.java @@ -24,550 +24,504 @@ package eva2.tools.math.interpolation; /** * Defines the routines for the spline interpolation of data. */ -public class LinearInterpolation -{ - AbstractDataSet abstractDataSet = null; - private double[] x, y; - //vectors of x,y - private double sumX = 0; - private double sumY = 0; - private double sumXY = 0; - private double sumXsquared = 0; - private double sumYsquared = 0; - private double Sxx, Sxy, Syy, n; - private double a = 0, b = 0; - //coefficients of regression - private int dataLength; - private double[][] residual; - // residual[0][i] = x[i], residual[1][i]= residual - private double maxAbsoluteResidual = 0.0; - private double SSR = 0.0; - //regression sum of squares - private double SSE = 0.0; - //error sum of squares - private double minX = Double.POSITIVE_INFINITY; - private double maxX = Double.NEGATIVE_INFINITY; - private double minY = Double.POSITIVE_INFINITY; - private double maxY = Double.NEGATIVE_INFINITY; +public class LinearInterpolation { + AbstractDataSet abstractDataSet = null; + private double[] x, y; + //vectors of x,y + private double sumX = 0; + private double sumY = 0; + private double sumXY = 0; + private double sumXsquared = 0; + private double sumYsquared = 0; + private double Sxx, Sxy, Syy, n; + private double a = 0, b = 0; + //coefficients of regression + private int dataLength; + private double[][] residual; + // residual[0][i] = x[i], residual[1][i]= residual + private double maxAbsoluteResidual = 0.0; + private double SSR = 0.0; + //regression sum of squares + private double SSE = 0.0; + //error sum of squares + private double minX = Double.POSITIVE_INFINITY; + private double maxX = Double.NEGATIVE_INFINITY; + private double minY = Double.POSITIVE_INFINITY; + private double maxY = Double.NEGATIVE_INFINITY; - //MISC - String xName, yName; - double aCILower, aCIUpper, bCILower, bCIUpper; //confidence interval - double t, bSE, aSE; - double MSE, F; - static double[] t025 = - { - Double.NaN, - 12.706, - 4.303, - 3.182, - 2.776, - 2.571, - 2.447, - 2.365, - 2.306, - 2.262, - 2.228, - 2.201, - 2.179, - 2.160, - 2.145, - 2.131, - 2.120, - 2.110, - 2.101, - 2.093, - 2.086, - 2.080, - 2.075, - 2.069, - 2.064, - 2.060, - 2.056, - 2.052, - 2.048, - 2.045, - 1.960 }; + //MISC + String xName, yName; + double aCILower, aCIUpper, bCILower, bCIUpper; //confidence interval + double t, bSE, aSE; + double MSE, F; + static double[] t025 = + { + Double.NaN, + 12.706, + 4.303, + 3.182, + 2.776, + 2.571, + 2.447, + 2.365, + 2.306, + 2.262, + 2.228, + 2.201, + 2.179, + 2.160, + 2.145, + 2.131, + 2.120, + 2.110, + 2.101, + 2.093, + 2.086, + 2.080, + 2.075, + 2.069, + 2.064, + 2.060, + 2.056, + 2.052, + 2.048, + 2.045, + 1.960}; /*------------------------------------------------------------------------* - * constructor + * constructor *------------------------------------------------------------------------*/ - /** - * Initializes this class. - */ - public LinearInterpolation() throws InterpolationException - { - this.abstractDataSet = null; - } - /** - * Constructor for regression calculator. - * - * @param x is the array of x data - * @param y is the array of y data - */ - public LinearInterpolation(double[] x, double[] y) - { - this.x = x; - this.y = y; - if (x.length != y.length) - { - System.out.println("x, y vectors must be of same length"); - } - else - { - dataLength = x.length; - doStatistics(); - } + /** + * Initializes this class. + */ + public LinearInterpolation() throws InterpolationException { + this.abstractDataSet = null; + } - } + /** + * Constructor for regression calculator. + * + * @param x is the array of x data + * @param y is the array of y data + */ + public LinearInterpolation(double[] x, double[] y) { + this.x = x; + this.y = y; + if (x.length != y.length) { + System.out.println("x, y vectors must be of same length"); + } else { + dataLength = x.length; + doStatistics(); + } - /** - * Initializes this class and calculates the second derivative of the spline. - * - * @param abstractDataSet the AbstractDataSet - */ - public LinearInterpolation(AbstractDataSet abstractDataSet) - throws InterpolationException - { - this.setAbstractDataSet(abstractDataSet); - } + } - public void setAbstractDataSet(AbstractDataSet abstractDataSet) - throws InterpolationException - { - this.abstractDataSet = abstractDataSet; - x = abstractDataSet.getXData(); - y = abstractDataSet.getYData(); - if (x.length != y.length) - { - System.out.println("x, y vectors must be of same length"); - } - else - { - dataLength = x.length; - doStatistics(); - } - } + /** + * Initializes this class and calculates the second derivative of the spline. + * + * @param abstractDataSet the AbstractDataSet + */ + public LinearInterpolation(AbstractDataSet abstractDataSet) + throws InterpolationException { + this.setAbstractDataSet(abstractDataSet); + } - /** - * Find the p value for a given value of F. - * Requires the COLT high performance library: - * http://hoschek.home.cern.ch/hoschek/colt/ - * - * @param fValue the value for the CDF - * @return The P value - */ - // public double getP(double fValue) { - // double answer; - // double y1; - // double y2; - // //nu1 = 1; - // //x2 =1 - // double nu2 = n - 2; - // y1 = nu2 / (nu2 + fValue); - // y2 = 0.0; - // answer = Gamma.incompleteBeta(nu2 / 2.0, 1 / 2.0, y1) - // - Gamma.incompleteBeta(nu2 / 2.0, 1 / 2.0, y2); - // return answer; - // } + public void setAbstractDataSet(AbstractDataSet abstractDataSet) + throws InterpolationException { + this.abstractDataSet = abstractDataSet; + x = abstractDataSet.getXData(); + y = abstractDataSet.getYData(); + if (x.length != y.length) { + System.out.println("x, y vectors must be of same length"); + } else { + dataLength = x.length; + doStatistics(); + } + } + + /** + * Find the p value for a given value of F. + * Requires the COLT high performance library: + * http://hoschek.home.cern.ch/hoschek/colt/ + * + * @param fValue the value for the CDF + * @return The P value + */ + // public double getP(double fValue) { + // double answer; + // double y1; + // double y2; + // //nu1 = 1; + // //x2 =1 + // double nu2 = n - 2; + // y1 = nu2 / (nu2 + fValue); + // y2 = 0.0; + // answer = Gamma.incompleteBeta(nu2 / 2.0, 1 / 2.0, y1) + // - Gamma.incompleteBeta(nu2 / 2.0, 1 / 2.0, y2); + // return answer; + // } /* - * Here are the accessor methods + * Here are the accessor methods * */ - /** - * Gets the intercept of the regression line. - * - * @return The intercept. - */ - public double getIntercept() - { - return a; - } - /** - * Gets the Slope of the regression line. - * - * @return The slope. - */ - public double getSlope() - { - return b; - } + /** + * Gets the intercept of the regression line. + * + * @return The intercept. + */ + public double getIntercept() { + return a; + } - /** - * Gets the residuals of the regression. - * - * @return The residuals. - */ - public double[][] getResiduals() - { - return residual; - } + /** + * Gets the Slope of the regression line. + * + * @return The slope. + */ + public double getSlope() { + return b; + } - /** - * Gets the x data for the regression. - * - * @return The array of x values. - */ - public double[] getDataX() - { - return x; - } + /** + * Gets the residuals of the regression. + * + * @return The residuals. + */ + public double[][] getResiduals() { + return residual; + } - /** - * Gets the y data for the regression. - * - * @return The array of y values. - */ - public double[] getDataY() - { - return y; - } + /** + * Gets the x data for the regression. + * + * @return The array of x values. + */ + public double[] getDataX() { + return x; + } - /** - * Gets the minimum of the x values. - * - * @return The minimum. - */ - public double getMinX() - { - return minX; - } + /** + * Gets the y data for the regression. + * + * @return The array of y values. + */ + public double[] getDataY() { + return y; + } - /** - * Gets the maximum of the x values. - * - * @return The maximum. - */ - public double getMaxX() - { - return maxX; - } + /** + * Gets the minimum of the x values. + * + * @return The minimum. + */ + public double getMinX() { + return minX; + } - /** - * Gets the minimum of the y values. - * - * @return The minumum. - */ - public double getMinY() - { - return minY; - } + /** + * Gets the maximum of the x values. + * + * @return The maximum. + */ + public double getMaxX() { + return maxX; + } - /** - * Gets the maximum of the y values. - * - * @return The maximum. - */ - public double getMaxY() - { - return maxY; - } + /** + * Gets the minimum of the y values. + * + * @return The minumum. + */ + public double getMinY() { + return minY; + } - /** - * Gets the maximum absolute residual. - * - * @return The maximum. - */ - public double getMaxAbsoluteResidual() - { - return maxAbsoluteResidual; - } + /** + * Gets the maximum of the y values. + * + * @return The maximum. + */ + public double getMaxY() { + return maxY; + } - /** - * Gets the sum of the square x deviations from mean of x. - * - * @return The Sxx value - */ - public double getSxx() - { - return Sxx; - } + /** + * Gets the maximum absolute residual. + * + * @return The maximum. + */ + public double getMaxAbsoluteResidual() { + return maxAbsoluteResidual; + } - /** - * Gets the sum of the square y deviations from mean of y. - * - * @return The Syy value - */ - public double getSyy() - { - return Syy; - } + /** + * Gets the sum of the square x deviations from mean of x. + * + * @return The Sxx value + */ + public double getSxx() { + return Sxx; + } - /** - * Gets SSR = Sxy * Sxy / Sxx; - * - * @return The SSR value - */ - public double getSSR() - { - return SSR; - } + /** + * Gets the sum of the square y deviations from mean of y. + * + * @return The Syy value + */ + public double getSyy() { + return Syy; + } - /** - * Gets SSE = Syy - SSR. - * - * @return The SSE value - */ - public double getSSE() - { - return SSE; - } + /** + * Gets SSR = Sxy * Sxy / Sxx; + * + * @return The SSR value + */ + public double getSSR() { + return SSR; + } - /** - * Gets the mean square error MSE. - * - * @return The MSE value - */ - public double getMSE() - { - return SSE / (n - 2); - } + /** + * Gets SSE = Syy - SSR. + * + * @return The SSE value + */ + public double getSSE() { + return SSE; + } - /** - * Gets the mean XBar of x. - * - * @return The XBar value - */ - public double getXBar() - { - return sumX / n; - } + /** + * Gets the mean square error MSE. + * + * @return The MSE value + */ + public double getMSE() { + return SSE / (n - 2); + } - /** - * Gets the mean YBar of y. - * - * @return The YBar value - */ - public double getYBar() - { - return sumY / n; - } + /** + * Gets the mean XBar of x. + * + * @return The XBar value + */ + public double getXBar() { + return sumX / n; + } - /** - * Gets the sample size. - * - * @return The sample size. - */ - public int getDataLength() - { - return x.length; - } + /** + * Gets the mean YBar of y. + * + * @return The YBar value + */ + public double getYBar() { + return sumY / n; + } - /** - * Gets the Pearson R statistic of the regression. - * - * @return The PearsonR value - */ - public double getPearsonR() - { - return Sxy / Math.sqrt(Sxx * Syy); - } + /** + * Gets the sample size. + * + * @return The sample size. + */ + public int getDataLength() { + return x.length; + } - /** - * Gets the sum of the x squared values. - * - * @return The sum of the x squared values. - */ - public double getSumXSquared() - { - return sumXsquared; - } + /** + * Gets the Pearson R statistic of the regression. + * + * @return The PearsonR value + */ + public double getPearsonR() { + return Sxy / Math.sqrt(Sxx * Syy); + } - /** - * reset data to 0 - */ - public void reset() - { - x = new double[0]; - y = new double[0]; - dataLength = 0; - n = 0.0; - residual = new double[0][0]; + /** + * Gets the sum of the x squared values. + * + * @return The sum of the x squared values. + */ + public double getSumXSquared() { + return sumXsquared; + } - sumX = 0; - sumXsquared = 0; - sumY = 0; - sumYsquared = 0; - sumXY = 0; + /** + * reset data to 0 + */ + public void reset() { + x = new double[0]; + y = new double[0]; + dataLength = 0; + n = 0.0; + residual = new double[0][0]; - } + sumX = 0; + sumXsquared = 0; + sumY = 0; + sumYsquared = 0; + sumXY = 0; - /** - * Adds a new point to the regression (for interactive use). - * - * @param xValue The new x value - * @param yValue The new y value - */ - public void addPoint(double xValue, double yValue) - { - dataLength++; - double[] xNew = new double[dataLength]; - double[] yNew = new double[dataLength]; - System.arraycopy(x, 0, xNew, 0, dataLength - 1); - System.arraycopy(y, 0, yNew, 0, dataLength - 1); - xNew[dataLength - 1] = xValue; - yNew[dataLength - 1] = yValue; - x = xNew; - y = yNew; - updateStatistics(xValue, yValue); - } + } - private void doStatistics() - { - //Find sum of squares for x,y and sum of xy - for (int i = 0; i < dataLength; i++) - { - minX = Math.min(minX, x[i]); - maxX = Math.max(maxX, x[i]); - minY = Math.min(minY, y[i]); - maxY = Math.max(maxY, y[i]); - sumX += x[i]; - sumY += y[i]; - sumXsquared += x[i] * x[i]; - sumYsquared += y[i] * y[i]; - sumXY += x[i] * y[i]; - } - //Caculate regression coefficients - n = (double) dataLength; - Sxx = sumXsquared - sumX * sumX / n; - Syy = sumYsquared - sumY * sumY / n; - Sxy = sumXY - sumX * sumY / n; - b = Sxy / Sxx; - a = (sumY - b * sumX) / n; - SSR = Sxy * Sxy / Sxx; - SSE = Syy - SSR; - calculateResiduals(); - } + /** + * Adds a new point to the regression (for interactive use). + * + * @param xValue The new x value + * @param yValue The new y value + */ + public void addPoint(double xValue, double yValue) { + dataLength++; + double[] xNew = new double[dataLength]; + double[] yNew = new double[dataLength]; + System.arraycopy(x, 0, xNew, 0, dataLength - 1); + System.arraycopy(y, 0, yNew, 0, dataLength - 1); + xNew[dataLength - 1] = xValue; + yNew[dataLength - 1] = yValue; + x = xNew; + y = yNew; + updateStatistics(xValue, yValue); + } - private void calculateResiduals() - { - residual = new double[2][dataLength]; - maxAbsoluteResidual = 0.0; - for (int i = 0; i < dataLength; i++) - { - residual[0][i] = x[i]; - residual[1][i] = y[i] - (a + b * x[i]); - maxAbsoluteResidual = - Math.max(maxAbsoluteResidual, Math.abs(y[i] - (a + b * x[i]))); - } - } + private void doStatistics() { + //Find sum of squares for x,y and sum of xy + for (int i = 0; i < dataLength; i++) { + minX = Math.min(minX, x[i]); + maxX = Math.max(maxX, x[i]); + minY = Math.min(minY, y[i]); + maxY = Math.max(maxY, y[i]); + sumX += x[i]; + sumY += y[i]; + sumXsquared += x[i] * x[i]; + sumYsquared += y[i] * y[i]; + sumXY += x[i] * y[i]; + } + //Caculate regression coefficients + n = (double) dataLength; + Sxx = sumXsquared - sumX * sumX / n; + Syy = sumYsquared - sumY * sumY / n; + Sxy = sumXY - sumX * sumY / n; + b = Sxy / Sxx; + a = (sumY - b * sumX) / n; + SSR = Sxy * Sxy / Sxx; + SSE = Syy - SSR; + calculateResiduals(); + } - //update statistics for a single additional data point - private void updateStatistics(double xValue, double yValue) - { - //Find sum of squares for x,y and sum of xy - n++; - sumX += xValue; - sumY += yValue; - sumXsquared += xValue * xValue; - sumYsquared += yValue * yValue; - sumXY += xValue * yValue; - //Caculate regression coefficients - n = (double) dataLength; - Sxx = sumXsquared - sumX * sumX / n; - Syy = sumYsquared - sumY * sumY / n; - Sxy = sumXY - sumX * sumY / n; - b = Sxy / Sxx; - a = (sumY - b * sumX) / n; - SSR = Sxy * Sxy / Sxx; - SSE = Syy - SSR; - calculateResiduals(); - } + private void calculateResiduals() { + residual = new double[2][dataLength]; + maxAbsoluteResidual = 0.0; + for (int i = 0; i < dataLength; i++) { + residual[0][i] = x[i]; + residual[1][i] = y[i] - (a + b * x[i]); + maxAbsoluteResidual = + Math.max(maxAbsoluteResidual, Math.abs(y[i] - (a + b * x[i]))); + } + } - /** - * regression line y = a + bx. - * - * @param x - * @return double - * @throws InterpolationException - */ - public double getY(double x) throws InterpolationException - { - return a + b * x; - } + //update statistics for a single additional data point + private void updateStatistics(double xValue, double yValue) { + //Find sum of squares for x,y and sum of xy + n++; + sumX += xValue; + sumY += yValue; + sumXsquared += xValue * xValue; + sumYsquared += yValue * yValue; + sumXY += xValue * yValue; + //Caculate regression coefficients + n = (double) dataLength; + Sxx = sumXsquared - sumX * sumX / n; + Syy = sumYsquared - sumY * sumY / n; + Sxy = sumXY - sumX * sumY / n; + b = Sxy / Sxx; + a = (sumY - b * sumX) / n; + SSR = Sxy * Sxy / Sxx; + SSE = Syy - SSR; + calculateResiduals(); + } + + /** + * regression line y = a + bx. + * + * @param x + * @return double + * @throws InterpolationException + */ + public double getY(double x) throws InterpolationException { + return a + b * x; + } @Override - public String toString() - { - StringBuffer sb = new StringBuffer(1000); + public String toString() { + StringBuffer sb = new StringBuffer(1000); - sb.append("Regression Statistics for " + yName + " = a + b*" + xName); - sb.append(""); - sb.append("Sample Statistics"); - int n = this.getDataLength(); - sb.append("Sample size n = " + n); - sb.append("Mean of " + yName + " Y bar = " + this.getYBar()); - sb.append("s_Y"); - sb.append("= " + Math.sqrt(this.getSyy() / ((float) (n - 1)))); - sb.append("Pearson correlation R = " + this.getPearsonR()); - sb.append(""); - sb.append("Coefficient Estimates"); - a = this.getIntercept(); - b = this.getSlope(); - sb.append("a = " + a); - sb.append("b = " + b); - sb.append(""); + sb.append("Regression Statistics for " + yName + " = a + b*" + xName); + sb.append(""); + sb.append("Sample Statistics"); + int n = this.getDataLength(); + sb.append("Sample size n = " + n); + sb.append("Mean of " + yName + " Y bar = " + this.getYBar()); + sb.append("s_Y"); + sb.append("= " + Math.sqrt(this.getSyy() / ((float) (n - 1)))); + sb.append("Pearson correlation R = " + this.getPearsonR()); + sb.append(""); + sb.append("Coefficient Estimates"); + a = this.getIntercept(); + b = this.getSlope(); + sb.append("a = " + a); + sb.append("b = " + b); + sb.append(""); - sb.append("95% Confidence Intervals"); + sb.append("95% Confidence Intervals"); - if (n > 32) - { - t = t025[30]; - } - else if (n > 2) - { - t = t025[n - 2]; - } - else - { - t = Double.NaN; - } - MSE = this.getMSE(); - if (n > 2) - { - bSE = Math.sqrt(MSE / this.getSxx()); - } - else - { - bSE = Double.NaN; - } - aSE = bSE * Math.sqrt(this.getSumXSquared() / n); - aCILower = a - t * aSE; - aCIUpper = a + t * aSE; - sb.append("a : (" + aCILower + ", " + aCIUpper + ")"); - bCILower = b - t * bSE; - bCIUpper = b + t * bSE; - sb.append("b : (" + bCILower + ", " + bCIUpper + ")"); - sb.append(""); - sb.append("Analysis of Variance"); - sb.append("Source Degrees Freedom Sum of Squares"); - sb.append(""); - SSR = this.getSSR(); - //allow one degree of freedom for mean - sb.append( - "model 1 " - + SSR); - sb.append( - "error " - + (n - 2) - + " " - + this.getSSE()); - sb.append( - "total(corrected) " - + (n - 1) - + " " - + this.getSyy()); - sb.append(""); - sb.append("MSE =" + MSE); - F = SSR / MSE; - sb.append("F = " + F + " "); - //sb.append("p = " + this.getP(F)); + if (n > 32) { + t = t025[30]; + } else if (n > 2) { + t = t025[n - 2]; + } else { + t = Double.NaN; + } + MSE = this.getMSE(); + if (n > 2) { + bSE = Math.sqrt(MSE / this.getSxx()); + } else { + bSE = Double.NaN; + } + aSE = bSE * Math.sqrt(this.getSumXSquared() / n); + aCILower = a - t * aSE; + aCIUpper = a + t * aSE; + sb.append("a : (" + aCILower + ", " + aCIUpper + ")"); + bCILower = b - t * bSE; + bCIUpper = b + t * bSE; + sb.append("b : (" + bCILower + ", " + bCIUpper + ")"); + sb.append(""); + sb.append("Analysis of Variance"); + sb.append("Source Degrees Freedom Sum of Squares"); + sb.append(""); + SSR = this.getSSR(); + //allow one degree of freedom for mean + sb.append( + "model 1 " + + SSR); + sb.append( + "error " + + (n - 2) + + " " + + this.getSSE()); + sb.append( + "total(corrected) " + + (n - 1) + + " " + + this.getSyy()); + sb.append(""); + sb.append("MSE =" + MSE); + F = SSR / MSE; + sb.append("F = " + F + " "); + //sb.append("p = " + this.getP(F)); - return sb.toString(); - } + return sb.toString(); + } } /**************************************************************************** * END OF FILE diff --git a/src/eva2/tools/math/interpolation/PolyInterpolation.java b/src/eva2/tools/math/interpolation/PolyInterpolation.java index 41c82aa6..94087a46 100644 --- a/src/eva2/tools/math/interpolation/PolyInterpolation.java +++ b/src/eva2/tools/math/interpolation/PolyInterpolation.java @@ -21,441 +21,412 @@ package eva2.tools.math.interpolation; /** * Defines the routines for the interpolation of data. */ -public class PolyInterpolation -{ - AbstractDataSet abstractDataSet = null; - boolean sloppy = true; - double[] polynomialCoefficients = null; +public class PolyInterpolation { + AbstractDataSet abstractDataSet = null; + boolean sloppy = true; + double[] polynomialCoefficients = null; /*------------------------------------------------------------------------* - * constructor + * constructor *------------------------------------------------------------------------*/ - /** - * Initializes this class. - */ - public PolyInterpolation() throws InterpolationException - { - this.abstractDataSet = null; - sloppy = true; - polynomialCoefficients = null; - } - /** - * Initializes this class and calculates the coefficients of the polynom. - * - * @param abstractDataSet the AbstractDataSet - */ - public PolyInterpolation(AbstractDataSet abstractDataSet) - throws InterpolationException - { - this.abstractDataSet = abstractDataSet; - sloppy = true; - this.polynomialCoefficients = calculatePolynomialCoefficients(); - } + /** + * Initializes this class. + */ + public PolyInterpolation() throws InterpolationException { + this.abstractDataSet = null; + sloppy = true; + polynomialCoefficients = null; + } - /** - * Initializes this class and calculates the coefficients of the polynom. - * - * @param abstractDataSet the AbstractDataSet - * @param sloppy if true Neville's algorithm which is used in the - * polynomialInterpolation-routines does only print a - * warning message on the screen and does not throw an - * Exception if two x values are identical. - */ - public PolyInterpolation(AbstractDataSet abstractDataSet, boolean sloppy) - throws InterpolationException - { - this.abstractDataSet = abstractDataSet; - this.sloppy = sloppy; - this.polynomialCoefficients = calculatePolynomialCoefficients(); - } + /** + * Initializes this class and calculates the coefficients of the polynom. + * + * @param abstractDataSet the AbstractDataSet + */ + public PolyInterpolation(AbstractDataSet abstractDataSet) + throws InterpolationException { + this.abstractDataSet = abstractDataSet; + sloppy = true; + this.polynomialCoefficients = calculatePolynomialCoefficients(); + } - /** - * Sets the new AbstractDataSet and calculates the coefficients - * of the polynom. - * - * @param abstractDataSet the AbstractDataSet - */ - public void setAbstractDataSet(AbstractDataSet abstractDataSet) - throws InterpolationException - { - this.abstractDataSet = abstractDataSet; - this.polynomialCoefficients = calculatePolynomialCoefficients(); - } + /** + * Initializes this class and calculates the coefficients of the polynom. + * + * @param abstractDataSet the AbstractDataSet + * @param sloppy if true Neville's algorithm which is used in the + * polynomialInterpolation-routines does only print a + * warning message on the screen and does not throw an + * Exception if two x values are identical. + */ + public PolyInterpolation(AbstractDataSet abstractDataSet, boolean sloppy) + throws InterpolationException { + this.abstractDataSet = abstractDataSet; + this.sloppy = sloppy; + this.polynomialCoefficients = calculatePolynomialCoefficients(); + } - /** - * Uses the polynom with the calculated coefficients to calculate the - * y value. This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 5, pages 173-176.
- * The Neville's algorithm which is used in the polynomialInterpolation- - * routines returns also the error of this interpolated point. - * - * @param x the x value - * @return the interpolated y value - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #getYandDerivatives(double, int) - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #calculatePolynomialCoefficients(double[], double[]) - */ + /** + * Sets the new AbstractDataSet and calculates the coefficients + * of the polynom. + * + * @param abstractDataSet the AbstractDataSet + */ + public void setAbstractDataSet(AbstractDataSet abstractDataSet) + throws InterpolationException { + this.abstractDataSet = abstractDataSet; + this.polynomialCoefficients = calculatePolynomialCoefficients(); + } - public double getY(double x) - { - int n = polynomialCoefficients.length - 1; - double y = polynomialCoefficients[n]; - for (int j = n - 1; j >= 0; j--) { + /** + * Uses the polynom with the calculated coefficients to calculate the + * y value. This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 5, pages 173-176.
+ * The Neville's algorithm which is used in the polynomialInterpolation- + * routines returns also the error of this interpolated point. + * + * @param x the x value + * @return the interpolated y value + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #getYandDerivatives(double, int) + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #calculatePolynomialCoefficients(double[], double[]) + */ + + public double getY(double x) { + int n = polynomialCoefficients.length - 1; + double y = polynomialCoefficients[n]; + for (int j = n - 1; j >= 0; j--) { y = y * x + polynomialCoefficients[j]; } - return y; - } + return y; + } - /** - * Uses the polynom with the calculated coefficients to calculate the - * y value and the derivatives at the point x, - * y. This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 5, pages 173-176.
- * The Neville's algorithm which is used in the polynomialInterpolation- - * routines returns also the error of this interpolated point. - * - * @param x the x value - * @param ndDerivateNumber the number of the calculated derivatives - * @return the interpolated y value at ...[0], the 1st derivativ value at - * ...[1], the 2nd derivativ at ...[2] and so on ... - * @see #getY(double) - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #calculatePolynomialCoefficients(double[], double[]) - */ - public double[] getYandDerivatives(double x, int ndDerivateNumber) - throws InterpolationException - { - if (ndDerivateNumber < 0) { - throw new InterpolationException("Negative derivative numbers make no sense."); - } - else if (ndDerivateNumber == 0) - { - double[] pd = new double[1]; - pd[0] = getY(x); - return pd; - } + /** + * Uses the polynom with the calculated coefficients to calculate the + * y value and the derivatives at the point x, + * y. This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 5, pages 173-176.
+ * The Neville's algorithm which is used in the polynomialInterpolation- + * routines returns also the error of this interpolated point. + * + * @param x the x value + * @param ndDerivateNumber the number of the calculated derivatives + * @return the interpolated y value at ...[0], the 1st derivativ value at + * ...[1], the 2nd derivativ at ...[2] and so on ... + * @see #getY(double) + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #calculatePolynomialCoefficients(double[], double[]) + */ + public double[] getYandDerivatives(double x, int ndDerivateNumber) + throws InterpolationException { + if (ndDerivateNumber < 0) { + throw new InterpolationException("Negative derivative numbers make no sense."); + } else if (ndDerivateNumber == 0) { + double[] pd = new double[1]; + pd[0] = getY(x); + return pd; + } - int nnd, j, i; - int nc = polynomialCoefficients.length - 1; - double[] pd = new double[ndDerivateNumber + 1]; - double cnst = 1.0; + int nnd, j, i; + int nc = polynomialCoefficients.length - 1; + double[] pd = new double[ndDerivateNumber + 1]; + double cnst = 1.0; - pd[0] = polynomialCoefficients[nc]; - for (j = 1; j <= ndDerivateNumber; j++) { + pd[0] = polynomialCoefficients[nc]; + for (j = 1; j <= ndDerivateNumber; j++) { pd[j] = 0.0; } - for (i = nc - 1; i >= 0; i--) - { - nnd = (ndDerivateNumber < (nc - i) ? ndDerivateNumber : nc - i); - for (j = nnd; j >= 1; j--) { + for (i = nc - 1; i >= 0; i--) { + nnd = (ndDerivateNumber < (nc - i) ? ndDerivateNumber : nc - i); + for (j = nnd; j >= 1; j--) { pd[j] = pd[j] * x + pd[j - 1]; } - pd[0] = pd[0] * x + polynomialCoefficients[i]; - } - for (i = 2; i <= ndDerivateNumber; i++) - { - cnst *= i; - pd[i] *= cnst; - } + pd[0] = pd[0] * x + polynomialCoefficients[i]; + } + for (i = 2; i <= ndDerivateNumber; i++) { + cnst *= i; + pd[i] *= cnst; + } - return pd; - } + return pd; + } - /** - * Neville's interpolation algorithm. This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 108-122.
- * - * @param x the x value - * @return the interpolated y value and the interpolation error - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #getY(double) - * @see #getYandDerivatives(double, int) - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #calculatePolynomialCoefficients(double[], double[]) - */ - public PolynomialInterpolationResult polynomialInterpolation(double x) - throws InterpolationException - { - if (abstractDataSet == null) { - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + /** + * Neville's interpolation algorithm. This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 108-122.
+ * + * @param x the x value + * @return the interpolated y value and the interpolation error + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #getY(double) + * @see #getYandDerivatives(double, int) + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #calculatePolynomialCoefficients(double[], double[]) + */ + public PolynomialInterpolationResult polynomialInterpolation(double x) + throws InterpolationException { + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } + return polynomialInterpolation( + abstractDataSet.getXData(), + abstractDataSet.getYData(), + x); + } + + /** + * Neville's interpolation algorithm. This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 108-122.
+ * + * @param abstractDataSet the AbstractDataSet + * @param x the x value + * @return the interpolated y value and the interpolation error + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #getY(double) + * @see #getYandDerivatives(double, int) + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #calculatePolynomialCoefficients(double[], double[]) + */ + public PolynomialInterpolationResult polynomialInterpolation( + AbstractDataSet abstractDataSet, + double x) + throws InterpolationException { + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } + return polynomialInterpolation( + abstractDataSet.getXData(), + abstractDataSet.getYData(), + x); + } + + /** + * Neville's interpolation algorithm. This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 108-122.
+ * + * @param xa the array of x values + * @param ya the array of y values + * @param x the x value + * @return the interpolated y value and the interpolation error + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #getY(double) + * @see #getYandDerivatives(double, int) + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #calculatePolynomialCoefficients(double[], double[]) + */ + public PolynomialInterpolationResult polynomialInterpolation( + double[] xa, + double[] ya, + double x) + throws InterpolationException { + if (xa == null || ya == null) { + throw new InterpolationException("No data."); + } + int i, m, ns = 1; + double den, dif, dift, ho, hp, w; + double[] c = new double[xa.length + 1]; + double[] d = new double[xa.length + 1]; + PolynomialInterpolationResult result = + new PolynomialInterpolationResult(); + + dif = Math.abs(x - xa[1 - 1]); + for (i = 1; i <= xa.length; i++) { + if ((dift = Math.abs(x - xa[i - 1])) < dif) { + ns = i; + dif = dift; } - return polynomialInterpolation( - abstractDataSet.getXData(), - abstractDataSet.getYData(), - x); - } - - /** - * Neville's interpolation algorithm. This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 108-122.
- * - * @param abstractDataSet the AbstractDataSet - * @param x the x value - * @return the interpolated y value and the interpolation error - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #getY(double) - * @see #getYandDerivatives(double, int) - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #calculatePolynomialCoefficients(double[], double[]) - */ - public PolynomialInterpolationResult polynomialInterpolation( - AbstractDataSet abstractDataSet, - double x) - throws InterpolationException - { - if (abstractDataSet == null) { - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + c[i] = ya[i - 1]; + d[i] = ya[i - 1]; + //System.out.println("x"+xa[i-1]+" y"+ya[i-1]); + } + result.y = ya[ns - 1]; + //System.out.println("y="+result.y+" ns="+ns); + ns--; + for (m = 1; m < xa.length; m++) { + for (i = 1; i <= xa.length - m; i++) { + ho = xa[i - 1] - x; + hp = xa[i + m - 1] - x; + w = c[i + 1] - d[i]; + if ((den = ho - hp) == 0.0) { + if (sloppy) { + System.out.println( + "Two identical x values. The values must be distinct."); + den = 1.0; + } else { + throw new InterpolationException("Two identical x values."); + } + } + den = w / den; + d[i] = hp * den; + c[i] = ho * den; } - return polynomialInterpolation( - abstractDataSet.getXData(), - abstractDataSet.getYData(), - x); - } + result.y + += (result.yError = + (2 * ns < (xa.length - m) ? c[ns + 1] : d[ns--])); + } + return result; + } - /** - * Neville's interpolation algorithm. This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 108-122.
- * - * @param xa the array of x values - * @param ya the array of y values - * @param x the x value - * @return the interpolated y value and the interpolation error - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #getY(double) - * @see #getYandDerivatives(double, int) - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #calculatePolynomialCoefficients(double[], double[]) - */ - public PolynomialInterpolationResult polynomialInterpolation( - double[] xa, - double[] ya, - double x) - throws InterpolationException - { - if (xa == null || ya == null) { - throw new InterpolationException("No data."); + /** + * Calculates the coefficients of a polynom of the grade N-1. This + * interpolation algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 108-122.
+ * + * @return the array with the polynomial coefficients y = ...[0] + + * ...[1]*x2 + ...[2]*x3 + ... + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #calculatePolynomialCoefficients(double[], double[]) + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #getY(double) + * @see #getYandDerivatives(double, int) + */ + public double[] calculatePolynomialCoefficients() + throws InterpolationException { + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } + return calculatePolynomialCoefficients( + abstractDataSet.getXData(), + abstractDataSet.getYData()); + } + + /** + * Calculates the coefficients of a polynom of the grade N-1. This + * interpolation algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 108-122.
+ * + * @param abstractDataSet the AbstractDataSet + * @return the array with the polynomial coefficients y = ...[0] + + * ...[1]*x2 + ...[2]*x3 + ... + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(double[], double[]) + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #getY(double) + * @see #getYandDerivatives(double, int) + */ + public double[] calculatePolynomialCoefficients(AbstractDataSet abstractDataSet) + throws InterpolationException { + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } + return calculatePolynomialCoefficients( + abstractDataSet.getXData(), + abstractDataSet.getYData()); + } + + /** + * Calculates the coefficients of a polynom of the grade N-1. This + * interpolation algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 108-122.
+ * + * @param x the array of x values + * @param y the array of y values + * @return the array with the polynomial coefficients y = ...[0] + + * ...[1]*x2 + ...[2]*x3 + ... + * @see #calculatePolynomialCoefficients() + * @see #calculatePolynomialCoefficients(AbstractDataSet) + * @see #polynomialInterpolation(double) + * @see #polynomialInterpolation(AbstractDataSet, double) + * @see #polynomialInterpolation(double[], double[], double) + * @see #getY(double) + * @see #getYandDerivatives(double, int) + */ + public double[] calculatePolynomialCoefficients(double x[], double y[]) { + int k, j, i, n = x.length - 1; + double phi, ff, b; + double[] s = new double[n + 1]; + double[] cof = new double[n + 1]; + + for (i = 0; i <= n; i++) { + s[i] = cof[i] = 0.0; + } + s[n] = -x[0]; + + for (i = 1; i <= n; i++) { + for (j = n - i; j <= n - 1; j++) { + s[j] -= x[i] * s[j + 1]; } - int i, m, ns = 1; - double den, dif, dift, ho, hp, w; - double[] c = new double[xa.length + 1]; - double[] d = new double[xa.length + 1]; - PolynomialInterpolationResult result = - new PolynomialInterpolationResult(); + s[n] -= x[i]; + } - dif = Math.abs(x - xa[1 - 1]); - for (i = 1; i <= xa.length; i++) - { - if ((dift = Math.abs(x - xa[i - 1])) < dif) - { - ns = i; - dif = dift; - } - c[i] = ya[i - 1]; - d[i] = ya[i - 1]; - //System.out.println("x"+xa[i-1]+" y"+ya[i-1]); - } - result.y = ya[ns - 1]; - //System.out.println("y="+result.y+" ns="+ns); - ns--; - for (m = 1; m < xa.length; m++) - { - for (i = 1; i <= xa.length - m; i++) - { - ho = xa[i - 1] - x; - hp = xa[i + m - 1] - x; - w = c[i + 1] - d[i]; - if ((den = ho - hp) == 0.0) - { - if (sloppy) - { - System.out.println( - "Two identical x values. The values must be distinct."); - den = 1.0; - } - else { - throw new InterpolationException("Two identical x values."); - } - } - den = w / den; - d[i] = hp * den; - c[i] = ho * den; - } - result.y - += (result.yError = - (2 * ns < (xa.length - m) ? c[ns + 1] : d[ns--])); - } - return result; - } - - /** - * Calculates the coefficients of a polynom of the grade N-1. This - * interpolation algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 108-122.
- * - * @return the array with the polynomial coefficients y = ...[0] + - * ...[1]*x2 + ...[2]*x3 + ... - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #calculatePolynomialCoefficients(double[], double[]) - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #getY(double) - * @see #getYandDerivatives(double, int) - */ - public double[] calculatePolynomialCoefficients() - throws InterpolationException - { - if (abstractDataSet == null) { - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + for (j = 0; j < n; j++) { + phi = n + 1; + for (k = n; k >= 1; k--) { + phi = k * s[k] + x[j] * phi; } - return calculatePolynomialCoefficients( - abstractDataSet.getXData(), - abstractDataSet.getYData()); - } - - /** - * Calculates the coefficients of a polynom of the grade N-1. This - * interpolation algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 108-122.
- * - * @param abstractDataSet the AbstractDataSet - * @return the array with the polynomial coefficients y = ...[0] + - * ...[1]*x2 + ...[2]*x3 + ... - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(double[], double[]) - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #getY(double) - * @see #getYandDerivatives(double, int) - */ - public double[] calculatePolynomialCoefficients(AbstractDataSet abstractDataSet) - throws InterpolationException - { - if (abstractDataSet == null) { - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + ff = y[j] / phi; + b = 1.0; + for (k = n; k >= 0; k--) { + cof[k] += b * ff; + b = s[k] + x[j] * b; } - return calculatePolynomialCoefficients( - abstractDataSet.getXData(), - abstractDataSet.getYData()); - } - - /** - * Calculates the coefficients of a polynom of the grade N-1. This - * interpolation algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 108-122.
- * - * @param x the array of x values - * @param y the array of y values - * @return the array with the polynomial coefficients y = ...[0] + - * ...[1]*x2 + ...[2]*x3 + ... - * @see #calculatePolynomialCoefficients() - * @see #calculatePolynomialCoefficients(AbstractDataSet) - * @see #polynomialInterpolation(double) - * @see #polynomialInterpolation(AbstractDataSet, double) - * @see #polynomialInterpolation(double[], double[], double) - * @see #getY(double) - * @see #getYandDerivatives(double, int) - */ - public double[] calculatePolynomialCoefficients(double x[], double y[]) - { - int k, j, i, n = x.length - 1; - double phi, ff, b; - double[] s = new double[n + 1]; - double[] cof = new double[n + 1]; - - for (i = 0; i <= n; i++) - { - s[i] = cof[i] = 0.0; - } - s[n] = -x[0]; - - for (i = 1; i <= n; i++) - { - for (j = n - i; j <= n - 1; j++) - { - s[j] -= x[i] * s[j + 1]; - } - s[n] -= x[i]; - } - - for (j = 0; j < n; j++) - { - phi = n + 1; - for (k = n; k >= 1; k--) - { - phi = k * s[k] + x[j] * phi; - } - ff = y[j] / phi; - b = 1.0; - for (k = n; k >= 0; k--) - { - cof[k] += b * ff; - b = s[k] + x[j] * b; - } - } - return cof; - } + } + return cof; + } } /**************************************************************************** diff --git a/src/eva2/tools/math/interpolation/PolynomialInterpolationResult.java b/src/eva2/tools/math/interpolation/PolynomialInterpolationResult.java index 19e6ed76..eb23dedd 100644 --- a/src/eva2/tools/math/interpolation/PolynomialInterpolationResult.java +++ b/src/eva2/tools/math/interpolation/PolynomialInterpolationResult.java @@ -25,30 +25,27 @@ package eva2.tools.math.interpolation; /** * The result data for a polynomial interpolation. */ -public class PolynomialInterpolationResult -{ - /*-------------------------------------------------------------------------* - * public member variables +public class PolynomialInterpolationResult { + /*-------------------------------------------------------------------------* + * public member variables *-------------------------------------------------------------------------*/ - public double y = Double.NaN; - public double yError = Double.NaN; + public double y = Double.NaN; + public double yError = Double.NaN; /*------------------------------------------------------------------------* * constructor *------------------------------------------------------------------------*/ - public PolynomialInterpolationResult() - { - y = Double.NaN; - yError = Double.NaN; - } + public PolynomialInterpolationResult() { + y = Double.NaN; + yError = Double.NaN; + } - public PolynomialInterpolationResult(double y, double yError) - { - this.y = y; - this.yError = yError; - } + public PolynomialInterpolationResult(double y, double yError) { + this.y = y; + this.yError = yError; + } } /**************************************************************************** diff --git a/src/eva2/tools/math/interpolation/SplineInterpolation.java b/src/eva2/tools/math/interpolation/SplineInterpolation.java index 3caa3ffe..0bd42019 100644 --- a/src/eva2/tools/math/interpolation/SplineInterpolation.java +++ b/src/eva2/tools/math/interpolation/SplineInterpolation.java @@ -21,285 +21,259 @@ package eva2.tools.math.interpolation; /** * Defines the routines for the spline interpolation of data. */ -public class SplineInterpolation -{ - AbstractDataSet abstractDataSet = null; - double[] secondDerivative = null; - double[] xArray = null; - double[] yArray = null; - boolean ascendingData = true; +public class SplineInterpolation { + AbstractDataSet abstractDataSet = null; + double[] secondDerivative = null; + double[] xArray = null; + double[] yArray = null; + boolean ascendingData = true; /*------------------------------------------------------------------------* - * constructor + * constructor *------------------------------------------------------------------------*/ - /** - * Initializes this class. - */ - public SplineInterpolation() throws InterpolationException - { - this.abstractDataSet = null; - this.secondDerivative = null; - } - /** - * Initializes this class and calculates the second derivative of the spline. - * - * @param abstractDataSet the AbstractDataSet - */ - public SplineInterpolation(AbstractDataSet abstractDataSet) - throws InterpolationException - { - this.setAbstractDataSet(abstractDataSet); - } + /** + * Initializes this class. + */ + public SplineInterpolation() throws InterpolationException { + this.abstractDataSet = null; + this.secondDerivative = null; + } - /** - * Sets the new AbstractDataSet and calculates the second - * derivative of the spline. - * - * @param abstractDataSet the AbstractDataSet - */ - public void setAbstractDataSet(AbstractDataSet abstractDataSet) - throws InterpolationException - { - this.abstractDataSet = abstractDataSet; - double[] x = abstractDataSet.getXData(); - double[] y = abstractDataSet.getYData(); - boolean ascending = false; - boolean descending = false; - int n = x.length; + /** + * Initializes this class and calculates the second derivative of the spline. + * + * @param abstractDataSet the AbstractDataSet + */ + public SplineInterpolation(AbstractDataSet abstractDataSet) + throws InterpolationException { + this.setAbstractDataSet(abstractDataSet); + } - xArray = new double[n]; - yArray = new double[n]; - xArray[n - 1] = x[0]; - yArray[n - 1] = y[0]; - for (int i = 0; i < n - 1; i++) - { - xArray[i] = x[n - i - 1]; - yArray[i] = y[n - i - 1]; - if (x[i] < x[i + 1]) - { - //if(descending)throw new InterpolationException("The x values must be"+ - // " in continous ascending/descending order."); - ascending = true; - } - else - { - //if(ascending)throw new InterpolationException("The x values must be"+ - // " in continous ascending/descending order."); - descending = true; - } - } - ascendingData = ascending; + /** + * Sets the new AbstractDataSet and calculates the second + * derivative of the spline. + * + * @param abstractDataSet the AbstractDataSet + */ + public void setAbstractDataSet(AbstractDataSet abstractDataSet) + throws InterpolationException { + this.abstractDataSet = abstractDataSet; + double[] x = abstractDataSet.getXData(); + double[] y = abstractDataSet.getYData(); + boolean ascending = false; + boolean descending = false; + int n = x.length; - if (ascendingData) - { - xArray = null; - yArray = null; - xArray = abstractDataSet.getXData(); - yArray = abstractDataSet.getYData(); - } - this.secondDerivative = - spline( - xArray, - yArray, - (yArray[1] - yArray[0]) / (xArray[1] - xArray[0]), - (yArray[n - 1] - yArray[n - 2]) / (xArray[1] - xArray[n - 2])); - } - - /** - * Uses the spline with the calculated second derivative values to calculate - * the y value. This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 5, pages 173-176.
- */ - public double getY(double x) throws InterpolationException - { - return splineInterpolation(xArray, yArray, secondDerivative, x); - } - - public double getDerivative(double x) throws InterpolationException - { - return splineInterpolatedDerivative( - xArray, - yArray, - secondDerivative, - x); - } - - /** - * Calculates the second derivative of the data. It's important that the - * xi values of the function yi=f(xi) are - * in ascending order, as x0<x1<x2<... . - * This algorithm was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 113-116.
- */ - public double[] spline(double[] x, double[] y, double yp0, double ypn) - throws InterpolationException - { - if (x[0] > x[1]) { - throw new InterpolationException( - "The x values must be" + " in ascending order."); + xArray = new double[n]; + yArray = new double[n]; + xArray[n - 1] = x[0]; + yArray[n - 1] = y[0]; + for (int i = 0; i < n - 1; i++) { + xArray[i] = x[n - i - 1]; + yArray[i] = y[n - i - 1]; + if (x[i] < x[i + 1]) { + //if(descending)throw new InterpolationException("The x values must be"+ + // " in continous ascending/descending order."); + ascending = true; + } else { + //if(ascending)throw new InterpolationException("The x values must be"+ + // " in continous ascending/descending order."); + descending = true; } - int n = x.length; - double[] y2 = new double[n]; - double[] u = new double[n - 1]; - int i, k; - double p, qn, sig, un; + } + ascendingData = ascending; - if (yp0 > 0.99e30) { - y2[0] = u[0] = 0.0; + if (ascendingData) { + xArray = null; + yArray = null; + xArray = abstractDataSet.getXData(); + yArray = abstractDataSet.getYData(); + } + this.secondDerivative = + spline( + xArray, + yArray, + (yArray[1] - yArray[0]) / (xArray[1] - xArray[0]), + (yArray[n - 1] - yArray[n - 2]) / (xArray[1] - xArray[n - 2])); + } + + /** + * Uses the spline with the calculated second derivative values to calculate + * the y value. This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 5, pages 173-176.
+ */ + public double getY(double x) throws InterpolationException { + return splineInterpolation(xArray, yArray, secondDerivative, x); + } + + public double getDerivative(double x) throws InterpolationException { + return splineInterpolatedDerivative( + xArray, + yArray, + secondDerivative, + x); + } + + /** + * Calculates the second derivative of the data. It's important that the + * xi values of the function yi=f(xi) are + * in ascending order, as x0<x1<x2<... . + * This algorithm was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 113-116.
+ */ + public double[] spline(double[] x, double[] y, double yp0, double ypn) + throws InterpolationException { + if (x[0] > x[1]) { + throw new InterpolationException( + "The x values must be" + " in ascending order."); + } + int n = x.length; + double[] y2 = new double[n]; + double[] u = new double[n - 1]; + int i, k; + double p, qn, sig, un; + + if (yp0 > 0.99e30) { + y2[0] = u[0] = 0.0; + } else { + y2[0] = -0.5; + u[0] = + (3.0 / (x[1] - x[0])) * ((y[1] - y[0]) / (x[1] - x[0]) - yp0); + } + for (i = 2; i <= n - 1; i++) { + sig = (x[i - 1] - x[i - 2]) / (x[i] - x[i - 2]); + p = sig * y2[i - 2] + 2.0; + y2[i - 1] = (sig - 1.0) / p; + u[i - 1] = + (y[i] - y[i - 1]) / (x[i] - x[i - 1]) + - (y[i - 1] - y[i - 2]) / (x[i - 1] - x[i - 2]); + u[i - 1] = + (6.0 * u[i - 1] / (x[i] - x[i - 2]) - sig * u[i - 2]) / p; + } + if (ypn > 0.99e30) { + qn = un = 0.0; + } else { + qn = 0.5; + un = + (3.0 / (x[n - 1] - x[n - 2])) + * (ypn - (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2])); + } + y2[n - 1] = (un - qn * u[n - 2]) / (qn * y2[n - 2] + 1.0); + for (k = n - 1; k >= 1; k--) { + y2[k - 1] = y2[k - 1] * y2[k] + u[k - 1]; + } + + return y2; + } + + /** + * Calculates the second derivative of the data. This algorithm + * was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 113-116.
+ */ + public double splineInterpolation( + double[] xa, + double[] ya, + double[] y2a, + double x) + throws InterpolationException { + int n = xa.length; + if (n != ya.length || n != y2a.length) { + throw new InterpolationException("Arrays have different lengths."); + } + double y; + int klo, khi, k; + double h, b, a; + + klo = 0; + khi = n - 1; + while (khi - klo > 1) { + k = (khi + klo) >> 1; + if (xa[k] > x) { + khi = k; + } else { + klo = k; } - else - { - y2[0] = -0.5; - u[0] = - (3.0 / (x[1] - x[0])) * ((y[1] - y[0]) / (x[1] - x[0]) - yp0); - } - for (i = 2; i <= n - 1; i++) - { - sig = (x[i - 1] - x[i - 2]) / (x[i] - x[i - 2]); - p = sig * y2[i - 2] + 2.0; - y2[i - 1] = (sig - 1.0) / p; - u[i - 1] = - (y[i] - y[i - 1]) / (x[i] - x[i - 1]) - - (y[i - 1] - y[i - 2]) / (x[i - 1] - x[i - 2]); - u[i - 1] = - (6.0 * u[i - 1] / (x[i] - x[i - 2]) - sig * u[i - 2]) / p; - } - if (ypn > 0.99e30) - { - qn = un = 0.0; - } - else - { - qn = 0.5; - un = - (3.0 / (x[n - 1] - x[n - 2])) - * (ypn - (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2])); - } - y2[n - 1] = (un - qn * u[n - 2]) / (qn * y2[n - 2] + 1.0); - for (k = n - 1; k >= 1; k--) - { - y2[k - 1] = y2[k - 1] * y2[k] + u[k - 1]; - } + } + h = xa[khi] - xa[klo]; + //System.out.println(""+x+" between "+xa[khi]+" "+xa[klo]); + if (h == 0.0) { + throw new InterpolationException("Two identical x values. The values must be distinct."); + } + a = (xa[khi] - x) / h; + b = (x - xa[klo]) / h; + y = + a * ya[klo] + + b * ya[khi] + + ((a * a * a - a) * y2a[klo] + (b * b * b - b) * y2a[khi]) + * (h * h) + / 6.0; + return y; + } - return y2; - } + /** + * Calculates the second derivative of the data. This algorithm + * was taken from:
+ * + * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, + * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, + * Cambridge University Press, + * ISBN 0-521-43108-5, + * chapter 3, pages 113-116.
+ */ + public double splineInterpolatedDerivative( + double[] xa, + double[] ya, + double[] y2a, + double x) + throws InterpolationException { + int n = xa.length; + if (n != ya.length || n != y2a.length) { + throw new InterpolationException("Arrays have different lengths."); + } + double dydx; + int klo, khi, k; + double h, b, a; - /** - * Calculates the second derivative of the data. This algorithm - * was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 113-116.
- */ - public double splineInterpolation( - double[] xa, - double[] ya, - double[] y2a, - double x) - throws InterpolationException - { - int n = xa.length; - if (n != ya.length || n != y2a.length) - { - throw new InterpolationException("Arrays have different lengths."); - } - double y; - int klo, khi, k; - double h, b, a; - - klo = 0; - khi = n - 1; - while (khi - klo > 1) - { - k = (khi + klo) >> 1; - if (xa[k] > x) { - khi = k; - } - else { - klo = k; - } - } - h = xa[khi] - xa[klo]; - //System.out.println(""+x+" between "+xa[khi]+" "+xa[klo]); - if (h == 0.0) { - throw new InterpolationException("Two identical x values. The values must be distinct."); + klo = 0; + khi = n - 1; + while (khi - klo > 1) { + k = (khi + klo) >> 1; + if (xa[k] > x) { + khi = k; + } else { + klo = k; } - a = (xa[khi] - x) / h; - b = (x - xa[klo]) / h; - y = - a * ya[klo] - + b * ya[khi] - + ((a * a * a - a) * y2a[klo] + (b * b * b - b) * y2a[khi]) - * (h * h) - / 6.0; - return y; - } - - /** - * Calculates the second derivative of the data. This algorithm - * was taken from:
- * - * William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery, - * "Numerical Recipes in C - The Art of Scientific Computing", Second Edition, - * Cambridge University Press, - * ISBN 0-521-43108-5, - * chapter 3, pages 113-116.
- */ - public double splineInterpolatedDerivative( - double[] xa, - double[] ya, - double[] y2a, - double x) - throws InterpolationException - { - int n = xa.length; - if (n != ya.length || n != y2a.length) - { - throw new InterpolationException("Arrays have different lengths."); - } - double dydx; - int klo, khi, k; - double h, b, a; - - klo = 0; - khi = n - 1; - while (khi - klo > 1) - { - k = (khi + klo) >> 1; - if (xa[k] > x) { - khi = k; - } - else { - klo = k; - } - } - h = xa[khi] - xa[klo]; - //System.out.println(""+x+" between "+xa[khi]+" "+xa[klo]); - if (h == 0.0) { - throw new InterpolationException("Two identical x values. The values must be distinct."); - } - a = (xa[khi] - x) / h; - b = (x - xa[klo]) / h; - dydx = - (ya[khi] - ya[klo]) / h - - ((3 * (a * a) - 1) * h * y2a[klo]) / 6.0 - + ((3 * (b * b) - 1) * h * y2a[khi]) / 6.0; - return dydx; - } + } + h = xa[khi] - xa[klo]; + //System.out.println(""+x+" between "+xa[khi]+" "+xa[klo]); + if (h == 0.0) { + throw new InterpolationException("Two identical x values. The values must be distinct."); + } + a = (xa[khi] - x) / h; + b = (x - xa[klo]) / h; + dydx = + (ya[khi] - ya[klo]) / h + - ((3 * (a * a) - 1) * h * y2a[klo]) / 6.0 + + ((3 * (b * b) - 1) * h * y2a[khi]) / 6.0; + return dydx; + } } /**************************************************************************** diff --git a/src/eva2/tools/matlab/JMatLink.java b/src/eva2/tools/matlab/JMatLink.java index a54f8654..4cb1180a 100644 --- a/src/eva2/tools/matlab/JMatLink.java +++ b/src/eva2/tools/matlab/JMatLink.java @@ -123,1334 +123,1359 @@ package eva2.tools.matlab; // The problem is ActiveX: one only can make calls to the engine library // (especially engEvalString) from ONE single thread. + import java.io.UnsupportedEncodingException; public class JMatLink extends Thread { - private static JMatLink m_Instance = null; + private static JMatLink m_Instance = null; - /** - * - */ - public static JMatLink getInstance() { - // System.out.println("JMatLink getInstance () {"); - if (m_Instance == null) { - m_Instance = new JMatLink(); - } - return m_Instance; - } + /** + * + */ + public static JMatLink getInstance() { + // System.out.println("JMatLink getInstance () {"); + if (m_Instance == null) { + m_Instance = new JMatLink(); + } + return m_Instance; + } - // static declarations - // the variable "status" is used to tell the main - // thread what to do. - private final static int idleI = 0; - private final static int engOpenI = 1; - private final static int engCloseI = 2; - private final static int engEvalStringI = 3; - private final static int engGetScalarI = 4; - private final static int engGetVectorI = 5; - private final static int engGetArrayI = 6; - private final static int engPutArray2dI = 9; - private final static int engOutputBufferI = 10; - private final static int engGetCharArrayI = 11; - private final static int destroyJMatLinkI = 12; - private final static int engOpenSingleUseI = 13; - // All variables are global to allow all methods + // static declarations + // the variable "status" is used to tell the main + // thread what to do. + private final static int idleI = 0; + private final static int engOpenI = 1; + private final static int engCloseI = 2; + private final static int engEvalStringI = 3; + private final static int engGetScalarI = 4; + private final static int engGetVectorI = 5; + private final static int engGetArrayI = 6; + private final static int engPutArray2dI = 9; + private final static int engOutputBufferI = 10; + private final static int engGetCharArrayI = 11; + private final static int destroyJMatLinkI = 12; + private final static int engOpenSingleUseI = 13; + // All variables are global to allow all methods - // and the main thread to share all data + // and the main thread to share all data - private int status = idleI; + private int status = idleI; - private String arrayS; + private String arrayS; - private String engEvalStringS; + private String engEvalStringS; - private String engOutputBufferS; + private String engOutputBufferS; - private double engGetScalarD; + private double engGetScalarD; - private double[] engGetVectorD; + private double[] engGetVectorD; - private double[][] engGetArrayD; + private double[][] engGetArrayD; - private double engPutArrayD; + private double engPutArrayD; - private double[] engPutArray1dD; + private double[] engPutArray1dD; - private double[][] engPutArray2dD; + private double[][] engPutArray2dD; - private String[] engGetCharArrayS; + private String[] engGetCharArrayS; - private int epI; /* Engine pointer */ + private int epI; /* Engine pointer */ - private int retValI; /* return Value of eng-methods */ + private int retValI; /* return Value of eng-methods */ - private String startCmdS; /* start command for engOpen... */ + private String startCmdS; /* start command for engOpen... */ - private int buflenI; /* output buffer length */ + private int buflenI; /* output buffer length */ - private boolean debugB = false; + private boolean debugB = false; - // Locks + // Locks - private boolean lockEngineB = false; + private boolean lockEngineB = false; - private boolean lockThreadB = false; + private boolean lockThreadB = false; - private boolean lockWaitForValueB = false; + private boolean lockWaitForValueB = false; - private boolean destroyJMatLinkB = false; + private boolean destroyJMatLinkB = false; - private Thread runner; + private Thread runner; - // *********************** native declarations **************************** + // *********************** native declarations **************************** - // NEVER call native methods directly, like + // NEVER call native methods directly, like - // JMatLink.engEvalStringNATIVE("a=1"). Matlab's engine has quite some + // JMatLink.engEvalStringNATIVE("a=1"). Matlab's engine has quite some - // thread problems. + // thread problems. - private native void displayHelloWorld(); + private native void displayHelloWorld(); - private native void engTestNATIVE(); + private native void engTestNATIVE(); - private native int engOpenNATIVE(String startCmdS); + private native int engOpenNATIVE(String startCmdS); - private native int engOpenSingleUseNATIVE(String startCmdS); + private native int engOpenSingleUseNATIVE(String startCmdS); - private native int engCloseNATIVE(int epI); + private native int engCloseNATIVE(int epI); - private native int engEvalStringNATIVE(int epI, String evalS); + private native int engEvalStringNATIVE(int epI, String evalS); - private native double engGetScalarNATIVE(int epI, String nameS); + private native double engGetScalarNATIVE(int epI, String nameS); - private native double[] engGetVectorNATIVE(int epI, String nameS); + private native double[] engGetVectorNATIVE(int epI, String nameS); - private native double[][] engGetArrayNATIVE(int epI, String nameS); + private native double[][] engGetArrayNATIVE(int epI, String nameS); - private native String[] engGetCharArrayNATIVE(int epI, String nameS); + private native String[] engGetCharArrayNATIVE(int epI, String nameS); - private native void engPutArrayNATIVE(int epI, String matrixS, - double[][] valuesDD); + private native void engPutArrayNATIVE(int epI, String matrixS, + double[][] valuesDD); - private native String engOutputBufferNATIVE(int epI, int buflenI); + private native String engOutputBufferNATIVE(int epI, int buflenI); - private native void setDebugNATIVE(boolean debugB); + private native void setDebugNATIVE(boolean debugB); - // ******************************************************************************* + // ******************************************************************************* - // ************** load JMatLink library into memory ********************** + // ************** load JMatLink library into memory ********************** - static { - // System.out.println("loading !!"); - try { // System.out.println("loading"); + static { + // System.out.println("loading !!"); + try { // System.out.println("loading"); - System.loadLibrary("JMatLink"); + System.loadLibrary("JMatLink"); - // String - // path="../lib/"+SystemHelper.getOperationSystemName()+"/JMatLink.dll"; + // String + // path="../lib/"+SystemHelper.getOperationSystemName()+"/JMatLink.dll"; - // System.out.println("load: "+path); + // System.out.println("load: "+path); - // System.loadLibrary(path); + // System.loadLibrary(path); - // String libPath = "." + System.getProperty("file.separator", "/"); + // String libPath = "." + System.getProperty("file.separator", "/"); - // //libPath += SystemHelper.getOperationSystemName() + - // System.getProperty("file.separator", "/"); + // //libPath += SystemHelper.getOperationSystemName() + + // System.getProperty("file.separator", "/"); - // libPath += System.mapLibraryName("JMatLink"); + // libPath += System.mapLibraryName("JMatLink"); - // + // - // // make sure that we have the absolute path + // // make sure that we have the absolute path - // libPath = new File(libPath).getAbsolutePath(); + // libPath = new File(libPath).getAbsolutePath(); - // + // - // System.out.println("load: "+"d:/workingAt/JCompChem/lib/windows/JMatLink.dll"); + // System.out.println("load: "+"d:/workingAt/JCompChem/lib/windows/JMatLink.dll"); - // System.loadLibrary("../lib/windows/JMatLink_old.dll"); + // System.loadLibrary("../lib/windows/JMatLink_old.dll"); - // System.out.println("loaded"); + // System.out.println("loaded"); - } + } catch (UnsatisfiedLinkError e) { - catch (UnsatisfiedLinkError e) { + System.err.println("ERROR: Could not load the JMatLink library"); - System.err.println("ERROR: Could not load the JMatLink library"); + e.printStackTrace(); - e.printStackTrace(); + } + // System.out.println("loading !! end"); - } - // System.out.println("loading !! end"); + } - } + // ************************ JMatLink constructor *************************** - // ************************ JMatLink constructor *************************** + /** + * This is the constructor for the JMatLink library. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ - /** - * This is the constructor for the JMatLink library. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ + private JMatLink() { - private JMatLink() { + if (debugB) { + System.out.println("JMatLink constructor"); + } - if (debugB) { - System.out.println("JMatLink constructor"); - } + runner = new Thread(this); - runner = new Thread(this); + runner.start(); - runner.start(); + } - } - - // **** terminate running thread **** + // **** terminate running thread **** @Override - public void destroy() { + public void destroy() { - destroyJMatLinkB = true; + destroyJMatLinkB = true; - notifyAll(); + notifyAll(); - } + } - public void kill() { + public void kill() { - destroyJMatLinkB = true; + destroyJMatLinkB = true; - callThread(destroyJMatLinkI); + callThread(destroyJMatLinkI); - } - - // //////////////////////////////////////////////////////////////////////////// - - // ***************************** engOpen ***************************** - - /** - * Open engine. This command is used to open a single connection - * - * to matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized int engOpen() - - { - return engOpen(""); // return value is pointer to engine - - } - - // ***************************** engOpen ******************************* - - /** - * Open engine. This command is used to open a single connection - * - * to matlab. - *

- * This command is only useful on unix systems. On windows - * - * the optional parameter must be NULL. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen("commands to start matlab");
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized int engOpen(String startCmdS) - - { - - // startup MATLAB and set up connection - - lockEngineLock(); - - lockWaitForValue(); - - this.startCmdS = startCmdS; - - callThread(engOpenI); - - WaitForValue(); - - releaseEngineLock(); - - return this.epI; - - } - - // ************************** engOpenSingleUse ***************************** - - /** - * Open engine for single use. This command is used to open - * - * multiple connections to matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int a,b;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   a = engine.engOpenSingleUse();   // start first matlab session
-	 * 
-	 *   b = engine.engOpenSingleUse();   // start second matlab session
-	 * 
-	 *   engine.engEvalString(a, "surf(peaks)");
-	 * 
-	 *   engine.engEvalString(b, "foo=ones(10,0)");
-	 * 
-	 *   engine.engClose(a);
-	 * 
-	 *   engine.engClose(b);
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized int engOpenSingleUse() - - { - - return engOpenSingleUse(""); - - } - - // ************************** engOpenSingleUse ***************************** - - /** - * Open engine for single use. This command is used to open - * - * multiple connections to matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int a,b;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   a = engine.engOpenSingleUse("start matlab");   // start first matlab session
-	 * 
-	 *   b = engine.engOpenSingleUse("start matlab");   // start second matlab session
-	 * 
-	 *   engine.engEvalString(a, "surf(peaks)");
-	 * 
-	 *   engine.engEvalString(b, "foo=ones(10,0)");
-	 * 
-	 *   engine.engClose(a);
-	 * 
-	 *   engine.engClose(b);
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized int engOpenSingleUse(String startCmdS) - - { - - lockEngineLock(); - - lockWaitForValue(); - - this.startCmdS = startCmdS; - - callThread(engOpenSingleUseI); - - WaitForValue(); - - releaseEngineLock(); - - return this.epI; - - } - - // ***************************** engClose ***************************** - - /** - * Close the connection to matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *  JMatLink engine = new JMatLink();
-	 * 
-	 *  engine.engOpen();
-	 * 
-	 *  engine.engEvalString("surf(peaks)");
-	 * 
-	 *  engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engClose() - - { - - engClose(this.epI); - - } - - // ***************************** engClose ***************************** - - /** - * Close a specified connection to an instance of matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *  int a,b;
-	 * 
-	 *  JMatLink engine = new JMatLink();
-	 * 
-	 *  a = engine.engOpenSingleUse();       // start first  matlab session
-	 * 
-	 *  b = engine.engOpenSingleUse();       // start second matlab session
-	 * 
-	 *  engine.engEvalString(b, "surf(peaks)");
-	 * 
-	 *  engine.engEvalString(a, "array = randn(23)");
-	 * 
-	 *  engine.engClose(a);      // Close the first  connection to matlab
-	 * 
-	 *  engine.engClose(b);      // Close the second connection to matlab
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engClose(int epI) - - { - - // close connection and terminate MATLAB + } + + // //////////////////////////////////////////////////////////////////////////// + + // ***************************** engOpen ***************************** + + /** + * Open engine. This command is used to open a single connection + *

+ * to matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized int engOpen() + + { + return engOpen(""); // return value is pointer to engine + + } + + // ***************************** engOpen ******************************* + + /** + * Open engine. This command is used to open a single connection + *

+ * to matlab. + *

+ * This command is only useful on unix systems. On windows + *

+ * the optional parameter must be NULL. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen("commands to start matlab");
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized int engOpen(String startCmdS) + + { + + // startup MATLAB and set up connection + + lockEngineLock(); + + lockWaitForValue(); + + this.startCmdS = startCmdS; + + callThread(engOpenI); + + WaitForValue(); + + releaseEngineLock(); + + return this.epI; + + } + + // ************************** engOpenSingleUse ***************************** + + /** + * Open engine for single use. This command is used to open + *

+ * multiple connections to matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int a,b;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   a = engine.engOpenSingleUse();   // start first matlab session
+     *
+     *   b = engine.engOpenSingleUse();   // start second matlab session
+     *
+     *   engine.engEvalString(a, "surf(peaks)");
+     *
+     *   engine.engEvalString(b, "foo=ones(10,0)");
+     *
+     *   engine.engClose(a);
+     *
+     *   engine.engClose(b);
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized int engOpenSingleUse() + + { + + return engOpenSingleUse(""); + + } + + // ************************** engOpenSingleUse ***************************** + + /** + * Open engine for single use. This command is used to open + *

+ * multiple connections to matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int a,b;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   a = engine.engOpenSingleUse("start matlab");   // start first matlab session
+     *
+     *   b = engine.engOpenSingleUse("start matlab");   // start second matlab session
+     *
+     *   engine.engEvalString(a, "surf(peaks)");
+     *
+     *   engine.engEvalString(b, "foo=ones(10,0)");
+     *
+     *   engine.engClose(a);
+     *
+     *   engine.engClose(b);
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized int engOpenSingleUse(String startCmdS) + + { + + lockEngineLock(); + + lockWaitForValue(); + + this.startCmdS = startCmdS; + + callThread(engOpenSingleUseI); + + WaitForValue(); + + releaseEngineLock(); + + return this.epI; + + } + + // ***************************** engClose ***************************** + + /** + * Close the connection to matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *  JMatLink engine = new JMatLink();
+     *
+     *  engine.engOpen();
+     *
+     *  engine.engEvalString("surf(peaks)");
+     *
+     *  engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engClose() + + { + + engClose(this.epI); + + } + + // ***************************** engClose ***************************** + + /** + * Close a specified connection to an instance of matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *  int a,b;
+     *
+     *  JMatLink engine = new JMatLink();
+     *
+     *  a = engine.engOpenSingleUse();       // start first  matlab session
+     *
+     *  b = engine.engOpenSingleUse();       // start second matlab session
+     *
+     *  engine.engEvalString(b, "surf(peaks)");
+     *
+     *  engine.engEvalString(a, "array = randn(23)");
+     *
+     *  engine.engClose(a);      // Close the first  connection to matlab
+     *
+     *  engine.engClose(b);      // Close the second connection to matlab
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engClose(int epI) + + { + + // close connection and terminate MATLAB + + lockEngineLock(); - lockEngineLock(); + lockWaitForValue(); - lockWaitForValue(); + this.epI = epI; - this.epI = epI; + callThread(engCloseI); - callThread(engCloseI); + WaitForValue(); - WaitForValue(); + releaseEngineLock(); - releaseEngineLock(); + // return retValI; Return value indicates success - // return retValI; Return value indicates success + } - } + // ***************************** engEvalString ***************************** + + /** + * Evaluate an expression in matlab's workspace. + *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engEvalString(String evalS) + + { + + engEvalString(this.epI, evalS); + + } + + // ***************************** engEvalString ************************* + + /** + * Evaluate an expression in a specified workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *  int a,b;
+     *
+     *  JMatLink engine = new JMatLink();
+     *
+     *  a = engine.engOpenSingleUse();
+     *
+     *  engine.engEvalString(a, "surf(peaks)");
+     *
+     *  engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engEvalString(int epI, String evalS) + + { + + // evaluate expression "evalS" in specified engine Ep + + if (debugB) { + System.out.println("eval(ep,String) in " + epI + " " + evalS); + } + + lockEngineLock(); + + lockWaitForValue(); + + this.epI = epI; + + engEvalStringS = evalS; - // ***************************** engEvalString ***************************** + callThread(engEvalStringI); - /** - * Evaluate an expression in matlab's workspace. - * - * - * - * E.g.:
- * - *
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engEvalString(String evalS) - - { - - engEvalString(this.epI, evalS); - - } - - // ***************************** engEvalString ************************* - - /** - * Evaluate an expression in a specified workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *  int a,b;
-	 * 
-	 *  JMatLink engine = new JMatLink();
-	 * 
-	 *  a = engine.engOpenSingleUse();
-	 * 
-	 *  engine.engEvalString(a, "surf(peaks)");
-	 * 
-	 *  engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engEvalString(int epI, String evalS) - - { - - // evaluate expression "evalS" in specified engine Ep - - if (debugB) { - System.out.println("eval(ep,String) in " + epI + " " + evalS); - } - - lockEngineLock(); - - lockWaitForValue(); - - this.epI = epI; + WaitForValue(); - engEvalStringS = evalS; + releaseEngineLock(); + + if (debugB) { + System.out.println("eval(ep,String) out " + epI + " " + evalS); + } + + // return retValI; Return value indicates success + + } + + // ***************************** engGetScalar ************************** + + /** + * Get a scalar value from matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *  double a;
+     *
+     *  JMatLink engine = new JMatLink();
+     *
+     *  engine.engOpen();
+     *
+     *  engine.engEvalString("foo = sin( 3 )");
+     *
+     *  a = engine.engGetScalarValue("foo");
+     *
+     *  engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized double engGetScalar(String arrayS) + + { + + return engGetScalar(this.epI, arrayS); + + } + + // ***************************** engGetScalar ************************** + + /** + * Get a scalar value from a specified workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   double a;
+     *
+     *   int b;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   b = engine.engOpenSigleUse();
+     *
+     *   engine.engEvalString(b, "foo = sin( 3 )");
+     *
+     *   a = engine.engGetScalarValue(b, "foo");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ - callThread(engEvalStringI); + public synchronized double engGetScalar(int epI, String arrayS) - WaitForValue(); + { - releaseEngineLock(); + // Get scalar value or element (1,1) of an array from - if (debugB) { - System.out.println("eval(ep,String) out " + epI + " " + evalS); - } + // MATLAB's workspace - // return retValI; Return value indicates success - - } - - // ***************************** engGetScalar ************************** - - /** - * Get a scalar value from matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *  double a;
-	 * 
-	 *  JMatLink engine = new JMatLink();
-	 * 
-	 *  engine.engOpen();
-	 * 
-	 *  engine.engEvalString("foo = sin( 3 )");
-	 * 
-	 *  a = engine.engGetScalarValue("foo");
-	 * 
-	 *  engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized double engGetScalar(String arrayS) - - { - - return engGetScalar(this.epI, arrayS); - - } + // Only real values are supported right now + + lockEngineLock(); - // ***************************** engGetScalar ************************** - - /** - * Get a scalar value from a specified workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   double a;
-	 * 
-	 *   int b;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   b = engine.engOpenSigleUse();
-	 * 
-	 *   engine.engEvalString(b, "foo = sin( 3 )");
-	 * 
-	 *   a = engine.engGetScalarValue(b, "foo");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized double engGetScalar(int epI, String arrayS) - - { - - // Get scalar value or element (1,1) of an array from - - // MATLAB's workspace - - // Only real values are supported right now - - lockEngineLock(); - - lockWaitForValue(); + lockWaitForValue(); /* copy parameters to global variables */ - this.epI = epI; + this.epI = epI; - this.arrayS = arrayS; + this.arrayS = arrayS; - callThread(engGetScalarI); + callThread(engGetScalarI); - WaitForValue(); + WaitForValue(); - releaseEngineLock(); + releaseEngineLock(); - return engGetScalarD; + return engGetScalarD; - } + } - // ***************************** engGetVector ************************** - - /** - * Get an array (1 * n) from matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   double[] array;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("array = randn(10,1);");
-	 * 
-	 *   array = engine.engGetVector("array");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized double[] engGetVector(String arrayS) - - { - - return engGetVector(this.epI, arrayS); - - } - - // ***************************** engGetVector ************************** - - /** - * Get an array (1 * n) from a specified workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int b;
-	 * 
-	 *   double[] array;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   b = engine.engOpenSingleUse();
-	 * 
-	 *   engine.engEvalString(b, "array = randn(10,1);");
-	 * 
-	 *   array = engine.engGetVector(b, "array");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized double[] engGetVector(int epI, String arrayS) - - { - - // only real values are supported so far - - lockEngineLock(); - - lockWaitForValue(); - - this.epI = epI; - - this.arrayS = arrayS; - - callThread(engGetVectorI); + // ***************************** engGetVector ************************** + + /** + * Get an array (1 * n) from matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   double[] array;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("array = randn(10,1);");
+     *
+     *   array = engine.engGetVector("array");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized double[] engGetVector(String arrayS) + + { + + return engGetVector(this.epI, arrayS); + + } + + // ***************************** engGetVector ************************** + + /** + * Get an array (1 * n) from a specified workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int b;
+     *
+     *   double[] array;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   b = engine.engOpenSingleUse();
+     *
+     *   engine.engEvalString(b, "array = randn(10,1);");
+     *
+     *   array = engine.engGetVector(b, "array");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized double[] engGetVector(int epI, String arrayS) + + { + + // only real values are supported so far + + lockEngineLock(); + + lockWaitForValue(); + + this.epI = epI; + + this.arrayS = arrayS; + + callThread(engGetVectorI); + + WaitForValue(); + + releaseEngineLock(); + + return engGetVectorD; + + } + + // ***************************** engGetArray *************************** + + /** + * Get an array from matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int b;
+     *
+     *   double[][] array;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("array = randn(10);");
+     *
+     *   array = engine.engGetArray("array");
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized double[][] engGetArray(String arrayS) + + { + + return engGetArray(this.epI, arrayS); + + } + + // ***************************** engGetArray *************************** + + /** + * Get an array from a specified instance/workspace of matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int b;
+     *
+     *   double[][] array;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   b = engine.engOpenSingleUse();
+     *
+     *   engine.engEvalString(b, "array = randn(10);");
+     *
+     *   array = engine.engGetArray(b, "array");
+     *
+     *   engine.engClose(b);
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized double[][] engGetArray(int epI, String arrayS) + + { + + // only real values are supported so far - WaitForValue(); - - releaseEngineLock(); - - return engGetVectorD; - - } - - // ***************************** engGetArray *************************** - - /** - * Get an array from matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int b;
-	 * 
-	 *   double[][] array;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("array = randn(10);");
-	 * 
-	 *   array = engine.engGetArray("array");
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized double[][] engGetArray(String arrayS) - - { - - return engGetArray(this.epI, arrayS); - - } + lockEngineLock(); - // ***************************** engGetArray *************************** + lockWaitForValue(); - /** - * Get an array from a specified instance/workspace of matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int b;
-	 * 
-	 *   double[][] array;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   b = engine.engOpenSingleUse();
-	 * 
-	 *   engine.engEvalString(b, "array = randn(10);");
-	 * 
-	 *   array = engine.engGetArray(b, "array");
-	 * 
-	 *   engine.engClose(b);
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized double[][] engGetArray(int epI, String arrayS) - - { + this.epI = epI; - // only real values are supported so far + this.arrayS = arrayS; - lockEngineLock(); + callThread(engGetArrayI); - lockWaitForValue(); + WaitForValue(); - this.epI = epI; + releaseEngineLock(); - this.arrayS = arrayS; + return engGetArrayD; - callThread(engGetArrayI); + } - WaitForValue(); + // ************************** engGetCharArray ***************************** + + /** + * Get an 'char' array (string) from matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   String array;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("array = 'hello world';");
+     *
+     *   array = engine.engCharArray("array");
+     *
+     *   System.out.println("output = "+ array);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized String[] engGetCharArray(String arrayS) - releaseEngineLock(); + { - return engGetArrayD; + // convert to double array - } + engEvalString("engGetCharArrayD=double(" + arrayS + ")"); - // ************************** engGetCharArray ***************************** + // get double array + + double[][] arrayD = engGetArray("engGetCharArrayD"); + + // delete temporary double array + + engEvalString("clear engGetCharArrayD"); + + // convert double back to char + + return double2String(arrayD); + + } + + // ***************************** engPutArray *************************** + + /** + * Put an array into a specified workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int array = 1;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engPutArray("array", array);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ - /** - * Get an 'char' array (string) from matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   String array;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("array = 'hello world';");
-	 * 
-	 *   array = engine.engCharArray("array");
-	 * 
-	 *   System.out.println("output = "+ array);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ + public synchronized void engPutArray(String arrayS, int valueI) - public synchronized String[] engGetCharArray(String arrayS) - - { - - // convert to double array - - engEvalString("engGetCharArrayD=double(" + arrayS + ")"); - - // get double array - - double[][] arrayD = engGetArray("engGetCharArrayD"); - - // delete temporary double array - - engEvalString("clear engGetCharArrayD"); - - // convert double back to char - - return double2String(arrayD); - - } - - // ***************************** engPutArray *************************** - - /** - * Put an array into a specified workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int array = 1;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engPutArray("array", array);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(String arrayS, int valueI) - - { - - engPutArray(this.epI, arrayS, new Integer(valueI).doubleValue()); - - } - - // ***************************** engPutArray *************************** - - // public synchronized void engPutArray( String arrayS, int[] valuesI ) - - // { - - // engPutArray( this.epI, arrayS, (double[])valuesI ); - - // } - - // ***************************** engPutArray *************************** - - /** - * Put an array into matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   double array = 1;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engPutArray("array", array);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(String arrayS, double valueD) - - { - - engPutArray(this.epI, arrayS, valueD); - - } - - // ***************************** engPutArray ***************************** - - /** - * Put an array into a specified instance/workspace of matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int b;
-	 * 
-	 *   double array = 1;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   b = engine.engOpenSingleUse();
-	 * 
-	 *   engine.engPutArray(b, "array", array);
-	 * 
-	 *   engine.engClose(b);
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(int epI, String arrayS, double valueD) - - { - - double vDD[][] = { { 0.0 } }; - - vDD[0][0] = valueD; - - engPutArray(epI, arrayS, vDD); // nxn dimensional - - } - - // ***************************** engPutArray *************************** - - /** - * Put an array (1 dimensional) into a specified instance/workspace of - * - * matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   double[] array = {1.0 , 2.0 , 3.0};
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engPutArray("array", array);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(String arrayS, double[] valuesD) - - { - - engPutArray(this.epI, arrayS, valuesD); - - } - - // ***************************** engPutArray ***************************** - - /** - * Put an array (1 dimensional) into a specified instance/workspace of - * - * matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   int b;
-	 * 
-	 *   double[] array = {1.0 , 2.0 , 3.0};
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   b = engine.engOpenSingleUse();
-	 * 
-	 *   engine.engPutArray(b, "array", array);
-	 * 
-	 *   engine.engClose(b);
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(int epI, String arrayS, - double[] valuesD) - - { - - double[][] vDD = new double[1][valuesD.length]; // 1xn array - - if (debugB) { - System.out.println("length = " + valuesD.length); - } - - vDD[0] = valuesD; // copy row - - engPutArray(epI, arrayS, vDD); - - } - - // ***************************** engPutArray *************************** - - /** - * Put an array (2 dimensional) into matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   double[][] array={{1.0 , 2.0 , 3.0},
-	 * 
-	 *                     {4.0 , 5.0 , 6.0}};
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpenSingleUse();
-	 * 
-	 *   engine.engPutArray("array", array);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(String arrayS, double[][] valuesDD) - - { - - engPutArray(this.epI, arrayS, valuesDD); - - } - - // ***************************** engPutArray *************************** - - /** - * Put an array (2 dimensional) into a specified instance/workspace of - * - * matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 * int b;
-	 * 
-	 * double[][] array = { { 1.0, 2.0, 3.0 },
-	 * 
-	 * { 4.0, 5.0, 6.0 } };
-	 * 
-	 * JMatLink engine = new JMatLink();
-	 * 
-	 * b = engine.engOpenSingleUse();
-	 * 
-	 * engine.engPutArray(b, "array", array);
-	 * 
-	 * engine.engClose(b);
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized void engPutArray(int epI, String arrayS, - double[][] valuesDD) - - { - - // send an array to MATLAB - - // only real values are supported so far - - lockEngineLock(); - - lockWaitForValue(); - - this.epI = epI; - - this.arrayS = arrayS; - - this.engPutArray2dD = valuesDD; - - callThread(engPutArray2dI); - - WaitForValue(); - - releaseEngineLock(); - - } - - // ***************************** engOutputBuffer *********************** - - /** - * Return the outputs of previous commands from matlab's workspace. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   String buffer;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   buffer = engine.engOutputBuffer();
-	 * 
-	 *   System.out.println("workspace " + buffer);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized String engOutputBuffer() - - { - - return engOutputBuffer(this.epI, this.buflenI); - - } - - // ***************************** engOutputBuffer *********************** - - /** - * Return the outputs of previous commands from a specified instance/ - * - * workspace form matlab. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   String buffer;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   buffer = engine.engOutputBuffer();
-	 * 
-	 *   System.out.println("workspace " + buffer);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized String engOutputBuffer(int epI) - - { - - return engOutputBuffer(epI, this.buflenI); - - } - - // ***************************** engOutputBuffer *********************** - - /** - * Return the ouputs of previous commands in matlab's workspace. - * - * - * - * Right now the parameter buflen is not supported. - * - * - * - *

- * E.g.:
- * - *

-	 * 
-	 *   String buffer;
-	 * 
-	 *   JMatLink engine = new JMatLink();
-	 * 
-	 *   engine.engOpen();
-	 * 
-	 *   engine.engEvalString("surf(peaks)");
-	 * 
-	 *   buffer = engine.engOutputBuffer();
-	 * 
-	 *   System.out.println("workspace " + buffer);
-	 * 
-	 *   engine.engClose();
-	 * 
-	 * 
- ***************************************************************************/ - - public synchronized String engOutputBuffer(int epI, int buflenI) - - { - - // get the output buffer from MATLAB - - if (debugB) { - System.out - .println("Thread in: " + Thread.currentThread().getName()); - } - - lockEngineLock(); - - lockWaitForValue(); - - this.epI = epI; - - this.buflenI = buflenI; - - callThread(engOutputBufferI); - - WaitForValue(); - - releaseEngineLock(); - - if (debugB) { - System.out.println("Thread out: " - + Thread.currentThread().getName()); - } - - return engOutputBufferS; - - } - - // ***************************** setDebug ******************************* + { + + engPutArray(this.epI, arrayS, new Integer(valueI).doubleValue()); + + } + + // ***************************** engPutArray *************************** + + // public synchronized void engPutArray( String arrayS, int[] valuesI ) + + // { + + // engPutArray( this.epI, arrayS, (double[])valuesI ); + + // } + + // ***************************** engPutArray *************************** + + /** + * Put an array into matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   double array = 1;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engPutArray("array", array);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engPutArray(String arrayS, double valueD) + + { + + engPutArray(this.epI, arrayS, valueD); + + } + + // ***************************** engPutArray ***************************** + + /** + * Put an array into a specified instance/workspace of matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int b;
+     *
+     *   double array = 1;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   b = engine.engOpenSingleUse();
+     *
+     *   engine.engPutArray(b, "array", array);
+     *
+     *   engine.engClose(b);
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engPutArray(int epI, String arrayS, double valueD) + + { + + double vDD[][] = {{0.0}}; + + vDD[0][0] = valueD; + + engPutArray(epI, arrayS, vDD); // nxn dimensional + + } + + // ***************************** engPutArray *************************** + + /** + * Put an array (1 dimensional) into a specified instance/workspace of + *

+ * matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   double[] array = {1.0 , 2.0 , 3.0};
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engPutArray("array", array);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engPutArray(String arrayS, double[] valuesD) + + { + + engPutArray(this.epI, arrayS, valuesD); + + } + + // ***************************** engPutArray ***************************** + + /** + * Put an array (1 dimensional) into a specified instance/workspace of + *

+ * matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   int b;
+     *
+     *   double[] array = {1.0 , 2.0 , 3.0};
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   b = engine.engOpenSingleUse();
+     *
+     *   engine.engPutArray(b, "array", array);
+     *
+     *   engine.engClose(b);
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engPutArray(int epI, String arrayS, + double[] valuesD) + + { + + double[][] vDD = new double[1][valuesD.length]; // 1xn array + + if (debugB) { + System.out.println("length = " + valuesD.length); + } + + vDD[0] = valuesD; // copy row + + engPutArray(epI, arrayS, vDD); + + } + + // ***************************** engPutArray *************************** + + /** + * Put an array (2 dimensional) into matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   double[][] array={{1.0 , 2.0 , 3.0},
+     *
+     *                     {4.0 , 5.0 , 6.0}};
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpenSingleUse();
+     *
+     *   engine.engPutArray("array", array);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engPutArray(String arrayS, double[][] valuesDD) + + { + + engPutArray(this.epI, arrayS, valuesDD); + + } + + // ***************************** engPutArray *************************** + + /** + * Put an array (2 dimensional) into a specified instance/workspace of + *

+ * matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     * int b;
+     *
+     * double[][] array = { { 1.0, 2.0, 3.0 },
+     *
+     * { 4.0, 5.0, 6.0 } };
+     *
+     * JMatLink engine = new JMatLink();
+     *
+     * b = engine.engOpenSingleUse();
+     *
+     * engine.engPutArray(b, "array", array);
+     *
+     * engine.engClose(b);
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized void engPutArray(int epI, String arrayS, + double[][] valuesDD) + + { + + // send an array to MATLAB + + // only real values are supported so far + + lockEngineLock(); + + lockWaitForValue(); + + this.epI = epI; + + this.arrayS = arrayS; + + this.engPutArray2dD = valuesDD; + + callThread(engPutArray2dI); + + WaitForValue(); + + releaseEngineLock(); + + } + + // ***************************** engOutputBuffer *********************** + + /** + * Return the outputs of previous commands from matlab's workspace. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   String buffer;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   buffer = engine.engOutputBuffer();
+     *
+     *   System.out.println("workspace " + buffer);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized String engOutputBuffer() + + { + + return engOutputBuffer(this.epI, this.buflenI); + + } + + // ***************************** engOutputBuffer *********************** + + /** + * Return the outputs of previous commands from a specified instance/ + *

+ * workspace form matlab. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   String buffer;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   buffer = engine.engOutputBuffer();
+     *
+     *   System.out.println("workspace " + buffer);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized String engOutputBuffer(int epI) + + { + + return engOutputBuffer(epI, this.buflenI); + + } + + // ***************************** engOutputBuffer *********************** + + /** + * Return the ouputs of previous commands in matlab's workspace. + *

+ *

+ *

+ * Right now the parameter buflen is not supported. + *

+ *

+ *

+ *

+ * E.g.:
+ *

+ *

+     *
+     *   String buffer;
+     *
+     *   JMatLink engine = new JMatLink();
+     *
+     *   engine.engOpen();
+     *
+     *   engine.engEvalString("surf(peaks)");
+     *
+     *   buffer = engine.engOutputBuffer();
+     *
+     *   System.out.println("workspace " + buffer);
+     *
+     *   engine.engClose();
+     *
+     * 
+ * ************************************************************************* + */ + + public synchronized String engOutputBuffer(int epI, int buflenI) + + { + + // get the output buffer from MATLAB + + if (debugB) { + System.out + .println("Thread in: " + Thread.currentThread().getName()); + } + + lockEngineLock(); + + lockWaitForValue(); + + this.epI = epI; + + this.buflenI = buflenI; + + callThread(engOutputBufferI); + + WaitForValue(); + + releaseEngineLock(); + + if (debugB) { + System.out.println("Thread out: " + + Thread.currentThread().getName()); + } + + return engOutputBufferS; + + } + + // ***************************** setDebug ******************************* /* - * Switch on or disable debug information printed to standard output. + * Switch on or disable debug information printed to standard output. * * * @@ -1475,325 +1500,323 @@ public class JMatLink extends Thread { * ************************************************************************* */ - public void setDebug(boolean debugB) + public void setDebug(boolean debugB) - { + { - this.debugB = debugB; + this.debugB = debugB; - setDebugNATIVE(debugB); + setDebugNATIVE(debugB); - } + } - // ////////////////////////////////////////////////////////////////////////////// + // ////////////////////////////////////////////////////////////////////////////// - // This method notifys the main thread to call matlab's engine + // This method notifys the main thread to call matlab's engine - // Since threads don't have methods, we set a variable which + // Since threads don't have methods, we set a variable which - // contains the necessary information about what to do. + // contains the necessary information about what to do. - private synchronized void callThread(int status) + private synchronized void callThread(int status) - { + { - this.status = status; + this.status = status; - lockThreadB = false; + lockThreadB = false; - notifyAll(); + notifyAll(); - } + } - // ////////////////////////////////////////////////////////////////////////////// + // ////////////////////////////////////////////////////////////////////////////// - // The run methods does ALL calls to the native methods + // The run methods does ALL calls to the native methods - // The keyword "synchronized" is neccessary to block the run() + // The keyword "synchronized" is neccessary to block the run() - // method as long as one command needs to get executed. + // method as long as one command needs to get executed. @Override - public synchronized void run() + public synchronized void run() - { + { - int tempRetVal; + int tempRetVal; + + if (debugB) { + System.out.println("JMatLink: thread is running"); + } + + while (true) { + + // System.out.println("Number of Java-Threads: "+Thread.activeCount()+""); + + // Thread thread = Thread.currentThread(); + + // System.out.println("Name of active Java-Threads: "+thread.getName()+""); + + // System.out.println("active Java-Thread is Daemon: "+thread.isDaemon();+""); + + switch (status) { + + case engOpenI: + epI = engOpenNATIVE(startCmdS); + + releaseWaitForValue(); + + break; + + case engOpenSingleUseI: + epI = engOpenSingleUseNATIVE(startCmdS); + + releaseWaitForValue(); + + break; + + case engCloseI: + retValI = engCloseNATIVE(epI); + + releaseWaitForValue(); + + break; + + case engEvalStringI: + retValI = engEvalStringNATIVE(epI, engEvalStringS); + + releaseWaitForValue(); + + break; + + case engGetScalarI: + engGetScalarD = engGetScalarNATIVE(epI, arrayS); + + releaseWaitForValue(); + + break; + + case engGetVectorI: + engGetVectorD = engGetVectorNATIVE(epI, arrayS); + + releaseWaitForValue(); + + break; + + case engGetArrayI: + engGetArrayD = engGetArrayNATIVE(epI, arrayS); + + releaseWaitForValue(); + + break; + + case engGetCharArrayI: + engGetCharArrayS = engGetCharArrayNATIVE(epI, arrayS); + + releaseWaitForValue(); + + break; + + case engPutArray2dI: + engPutArrayNATIVE(epI, arrayS, engPutArray2dD); + + releaseWaitForValue(); + + break; + + case engOutputBufferI: + engOutputBufferS = engOutputBufferNATIVE(epI, buflenI); + + releaseWaitForValue(); + + break; + + default: // System.out.println("thread default switch statem."); - if (debugB) { - System.out.println("JMatLink: thread is running"); } - while (true) { + status = 0; - // System.out.println("Number of Java-Threads: "+Thread.activeCount()+""); + lockThreadB = true; - // Thread thread = Thread.currentThread(); + while (lockThreadB == true) { - // System.out.println("Name of active Java-Threads: "+thread.getName()+""); + synchronized (this) { - // System.out.println("active Java-Thread is Daemon: "+thread.isDaemon();+""); + try { + wait(); + } // wait until next command is available - switch (status) { - - case engOpenI: - epI = engOpenNATIVE(startCmdS); - - releaseWaitForValue(); - - break; - - case engOpenSingleUseI: - epI = engOpenSingleUseNATIVE(startCmdS); - - releaseWaitForValue(); - - break; - - case engCloseI: - retValI = engCloseNATIVE(epI); - - releaseWaitForValue(); - - break; - - case engEvalStringI: - retValI = engEvalStringNATIVE(epI, engEvalStringS); - - releaseWaitForValue(); - - break; - - case engGetScalarI: - engGetScalarD = engGetScalarNATIVE(epI, arrayS); - - releaseWaitForValue(); - - break; - - case engGetVectorI: - engGetVectorD = engGetVectorNATIVE(epI, arrayS); - - releaseWaitForValue(); - - break; - - case engGetArrayI: - engGetArrayD = engGetArrayNATIVE(epI, arrayS); - - releaseWaitForValue(); - - break; - - case engGetCharArrayI: - engGetCharArrayS = engGetCharArrayNATIVE(epI, arrayS); - - releaseWaitForValue(); - - break; - - case engPutArray2dI: - engPutArrayNATIVE(epI, arrayS, engPutArray2dD); - - releaseWaitForValue(); - - break; - - case engOutputBufferI: - engOutputBufferS = engOutputBufferNATIVE(epI, buflenI); - - releaseWaitForValue(); - - break; - - default: // System.out.println("thread default switch statem."); - - } - - status = 0; - - lockThreadB = true; - - while (lockThreadB == true) { - - synchronized (this) { - - try { - wait(); - } // wait until next command is available - - catch (InterruptedException e) { - } - - } - - } - - // System.out.println("JMatLink: thread awoke and passed lock"); - - if (destroyJMatLinkB == true) { - break; + catch (InterruptedException e) { } - } // end while + } - if (debugB) { - System.out.println("JMatLink: thread terminated"); } - } // end run + // System.out.println("JMatLink: thread awoke and passed lock"); - // ////////////////////////////////////////////////////////////////////////////// + if (destroyJMatLinkB == true) { + break; + } - // The MATLAB engine is served by a thread. Threads don't have methods + } // end while - // which can be called. So we need to send messages to that thread + if (debugB) { + System.out.println("JMatLink: thread terminated"); + } - // by using notifyAll. In the meantime NO OTHER methods is allowed to + } // end run - // access our thread (engine) so we lock everything up. + // ////////////////////////////////////////////////////////////////////////////// - private void lockEngineLock() { + // The MATLAB engine is served by a thread. Threads don't have methods - synchronized (this) { + // which can be called. So we need to send messages to that thread - while (lockEngineB == true) { + // by using notifyAll. In the meantime NO OTHER methods is allowed to - try { // System.out.println("lockEngineLock locked"); + // access our thread (engine) so we lock everything up. - wait(); - } // wait until last command is finished + private void lockEngineLock() { - catch (InterruptedException e) { - } + synchronized (this) { - } + while (lockEngineB == true) { - // now lockEngineB is false + try { // System.out.println("lockEngineLock locked"); - lockEngineB = true; + wait(); + } // wait until last command is finished - } + catch (InterruptedException e) { + } - } // end lockEngine + } - private synchronized void releaseEngineLock() { + // now lockEngineB is false - lockEngineB = false; + lockEngineB = true; - notifyAll(); + } - } + } // end lockEngine - // ////////////////////////////////////////////////////////////////////////////// + private synchronized void releaseEngineLock() { - // The MATLAB engine is served by a thread. Threads don't have methods + lockEngineB = false; - // which can be called directly. If we send a command that returns data + notifyAll(); - // back to the calling function e.g. engGetArray("array"), we'll notify + } - // the main thread to get the data from matlab. Since the data is collected + // ////////////////////////////////////////////////////////////////////////////// - // in another thread, we don't know exactly when the data is available, - // since + // The MATLAB engine is served by a thread. Threads don't have methods - // this is a concurrent situation. + // which can be called directly. If we send a command that returns data - // The solution is simple: I always use a locking-mechanism to wait for the + // back to the calling function e.g. engGetArray("array"), we'll notify - // data. The main thread will release the lock and the calling method can + // the main thread to get the data from matlab. Since the data is collected - // return the data. + // in another thread, we don't know exactly when the data is available, + // since - // + // this is a concurrent situation. - // Steps: + // The solution is simple: I always use a locking-mechanism to wait for the - // 1. a method that returns data calls the locking method + // data. The main thread will release the lock and the calling method can - // 2. notify the thread to call matlab + // return the data. - // 3. wait for the returned data + // - // 4. after the thread itself got the data it releases the locks method + // Steps: - // 5. return data + // 1. a method that returns data calls the locking method - private synchronized void lockWaitForValue() { + // 2. notify the thread to call matlab - lockWaitForValueB = true; + // 3. wait for the returned data - } + // 4. after the thread itself got the data it releases the locks method - private void WaitForValue() { + // 5. return data - synchronized (this) { + private synchronized void lockWaitForValue() { - while (lockWaitForValueB == true) { + lockWaitForValueB = true; - try { // System.out.println("lockWaitForValue locked"); + } - wait(); - } // wait for return value + private void WaitForValue() { - catch (InterruptedException e) { - } + synchronized (this) { - } + while (lockWaitForValueB == true) { - } + try { // System.out.println("lockWaitForValue locked"); - // System.out.println("WaitForValue released"); + wait(); + } // wait for return value - } // end waitForValue + catch (InterruptedException e) { + } - private synchronized void releaseWaitForValue() { + } - lockWaitForValueB = false; + } - notifyAll(); + // System.out.println("WaitForValue released"); - } + } // end waitForValue - // ////////////////////////////////////////////////////////////////////////////// + private synchronized void releaseWaitForValue() { - // // Utility methods //// + lockWaitForValueB = false; - // Convert an n*n double array to n*1 String vector + notifyAll(); - private String[] double2String(double[][] d) + } - { + // ////////////////////////////////////////////////////////////////////////////// - String encodeS[] = new String[d.length]; // String vector + // // Utility methods //// - // for all rows + // Convert an n*n double array to n*1 String vector - for (int n = 0; n < d.length; n++) { + private String[] double2String(double[][] d) - byte b[] = new byte[d[n].length]; + { - // convert row from double to byte + String encodeS[] = new String[d.length]; // String vector - for (int i = 0; i < d[n].length; i++) { - b[i] = (byte) d[n][i]; - } + // for all rows - // convert byte to String + for (int n = 0; n < d.length; n++) { - try { - encodeS[n] = new String(b, "UTF8"); - } + byte b[] = new byte[d[n].length]; - catch (UnsupportedEncodingException e) { - } + // convert row from double to byte - } + for (int i = 0; i < d[n].length; i++) { + b[i] = (byte) d[n][i]; + } - return encodeS; + // convert byte to String - } // end double2String + try { + encodeS[n] = new String(b, "UTF8"); + } catch (UnsupportedEncodingException e) { + } + + } + + return encodeS; + + } // end double2String } // end class JMatLink diff --git a/src/eva2/tools/print/PagePrinter.java b/src/eva2/tools/print/PagePrinter.java index e8c3c0b8..e957d081 100644 --- a/src/eva2/tools/print/PagePrinter.java +++ b/src/eva2/tools/print/PagePrinter.java @@ -25,139 +25,130 @@ import javax.swing.*; * CLASS DECLARATION *==========================================================================*/ -public class PagePrinter -{ - Component c; - Graphics g; - PageFormat pf; - public boolean fit_in_possible = true; +public class PagePrinter { + Component c; + Graphics g; + PageFormat pf; + public boolean fit_in_possible = true; - public PagePrinter( Component c, Graphics g, PageFormat pf ) { - this.c = c; - this.g = g; - this.pf = pf; - } - - public int print(){ - Dimension old = c.getSize(); - - int x = (int)pf.getImageableX(), - y = (int)pf.getImageableY(); - - g.translate( x, y ); - - double w = (int)pf.getImageableWidth(), - h = (int)pf.getImageableHeight(); - - if( old.width > w || old.height > h ){ - boolean rec_turn = false, rec_fit_in = false; - if( ( old.width > old.height && h > w ) || - ( old.width < old.height && h < w ) ) { - rec_turn = true; - if( old.width > h || old.height > w ) { - rec_fit_in = true; - } - } - else { - rec_fit_in = true; - } - - JLabel[] text = new JLabel[4]; - text[0] = new JLabel("The component which should be printed"); - text[1] = new JLabel("is too large."); - text[2] = new JLabel("You can choose if the component should be"); - JCheckBox cbFitIn = new JCheckBox("fitted-in", rec_fit_in), - cbTurn = new JCheckBox("turned", rec_turn ); - text[3] = new JLabel("(Recommended choice is pre-selected)"); - - if( !fit_in_possible ){ - cbFitIn.setEnabled( false ); - cbFitIn.setSelected( false ); - } - - GridBagLayout gbl = new GridBagLayout(); - JPanel panel = new JPanel( gbl ); - GridBagConstraints gbc = new GridBagConstraints(); - gbc.gridx = gbc.gridy = 0; - gbc.weightx = gbc.weighty = .5; - - gbc.gridwidth = 2; - gbl.setConstraints( text[0], gbc ); - panel.add( text[0] ); - - gbc.gridy++; - gbl.setConstraints( text[1], gbc ); - panel.add( text[1] ); - - gbc.gridy++; - gbl.setConstraints( text[2], gbc ); - panel.add( text[2] ); - - gbc.gridy++; - gbc.gridwidth = 1; - gbl.setConstraints( cbFitIn, gbc ); - panel.add( cbFitIn ); - - gbc.gridx++; - gbl.setConstraints( cbTurn, gbc ); - panel.add( cbTurn ); - gbc.gridx = 0; - gbc.gridwidth = 2; - gbc.gridy++; - gbl.setConstraints( text[3], gbc); - panel.add( text[3] ); - - int choice = JOptionPane.showOptionDialog( c, panel, "Fit-in", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, null, null ); - - if( choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.CLOSED_OPTION ) { - return Printable.NO_SUCH_PAGE; - } - - else if( choice == JOptionPane.OK_OPTION ){ - - if( cbTurn.isSelected() ){ - BufferedImage img; - if( cbFitIn.isSelected() ){ - double m = Math.min( h / (double)old.width, w / (double)old.height ); - img = (BufferedImage)c.createImage( (int)( old.height * m ), (int)( old.width * m ) ); - Graphics2D g2 = img.createGraphics(); - g2.rotate( Math.toRadians( 90 ) ); - g2.translate( 0, - old.height * m ); - c.setSize( (int)( old.width * m ), (int)( old.height * m ) ); - c.paint( g2 ); - c.setSize( old ); - } - else{ - img = (BufferedImage)c.createImage( old.height, old.width ); - Graphics2D g2 = img.createGraphics(); - g2.rotate( Math.toRadians( 90 ) ); - g2.translate( 0, - old.height ); - c.paint( g2 ); - } - g.drawImage( img, 0, 0, c.getBackground(), c ); - } - - else{ - if( cbFitIn.isSelected() ){ - double m = Math.min( w / (double)old.width, h / (double)old.height ); - c.setSize( (int)( old.width * m ), (int)( old.height * m ) ); - c.paint( g ); - c.setSize( old ); - } - else { - c.paint( g ); - } - } - } + public PagePrinter(Component c, Graphics g, PageFormat pf) { + this.c = c; + this.g = g; + this.pf = pf; + } + + public int print() { + Dimension old = c.getSize(); + + int x = (int) pf.getImageableX(), + y = (int) pf.getImageableY(); + + g.translate(x, y); + + double w = (int) pf.getImageableWidth(), + h = (int) pf.getImageableHeight(); + + if (old.width > w || old.height > h) { + boolean rec_turn = false, rec_fit_in = false; + if ((old.width > old.height && h > w) || + (old.width < old.height && h < w)) { + rec_turn = true; + if (old.width > h || old.height > w) { + rec_fit_in = true; + } + } else { + rec_fit_in = true; + } + + JLabel[] text = new JLabel[4]; + text[0] = new JLabel("The component which should be printed"); + text[1] = new JLabel("is too large."); + text[2] = new JLabel("You can choose if the component should be"); + JCheckBox cbFitIn = new JCheckBox("fitted-in", rec_fit_in), + cbTurn = new JCheckBox("turned", rec_turn); + text[3] = new JLabel("(Recommended choice is pre-selected)"); + + if (!fit_in_possible) { + cbFitIn.setEnabled(false); + cbFitIn.setSelected(false); + } + + GridBagLayout gbl = new GridBagLayout(); + JPanel panel = new JPanel(gbl); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridx = gbc.gridy = 0; + gbc.weightx = gbc.weighty = .5; + + gbc.gridwidth = 2; + gbl.setConstraints(text[0], gbc); + panel.add(text[0]); + + gbc.gridy++; + gbl.setConstraints(text[1], gbc); + panel.add(text[1]); + + gbc.gridy++; + gbl.setConstraints(text[2], gbc); + panel.add(text[2]); + + gbc.gridy++; + gbc.gridwidth = 1; + gbl.setConstraints(cbFitIn, gbc); + panel.add(cbFitIn); + + gbc.gridx++; + gbl.setConstraints(cbTurn, gbc); + panel.add(cbTurn); + gbc.gridx = 0; + gbc.gridwidth = 2; + gbc.gridy++; + gbl.setConstraints(text[3], gbc); + panel.add(text[3]); + + int choice = JOptionPane.showOptionDialog(c, panel, "Fit-in", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, null, null); + + if (choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.CLOSED_OPTION) { + return Printable.NO_SUCH_PAGE; + } else if (choice == JOptionPane.OK_OPTION) { + + if (cbTurn.isSelected()) { + BufferedImage img; + if (cbFitIn.isSelected()) { + double m = Math.min(h / (double) old.width, w / (double) old.height); + img = (BufferedImage) c.createImage((int) (old.height * m), (int) (old.width * m)); + Graphics2D g2 = img.createGraphics(); + g2.rotate(Math.toRadians(90)); + g2.translate(0, -old.height * m); + c.setSize((int) (old.width * m), (int) (old.height * m)); + c.paint(g2); + c.setSize(old); + } else { + img = (BufferedImage) c.createImage(old.height, old.width); + Graphics2D g2 = img.createGraphics(); + g2.rotate(Math.toRadians(90)); + g2.translate(0, -old.height); + c.paint(g2); + } + g.drawImage(img, 0, 0, c.getBackground(), c); + } else { + if (cbFitIn.isSelected()) { + double m = Math.min(w / (double) old.width, h / (double) old.height); + c.setSize((int) (old.width * m), (int) (old.height * m)); + c.paint(g); + c.setSize(old); + } else { + c.paint(g); + } + } + } + } else { + c.paint(g); + } + return Printable.PAGE_EXISTS; } - else { - c.paint( g ); - } - return Printable.PAGE_EXISTS; - } } /****************************************************************************