From bcf7a9a8a2e45f3c027f494b8133cc8162b138e8 Mon Sep 17 00:00:00 2001 From: Fabian Becker Date: Tue, 29 Jan 2013 14:02:48 +0000 Subject: [PATCH] refs #25, #24 Should be the last of the huge commits. --- src/eva2/EvAInfo.java | 4 +- src/eva2/OptimizerRunnable.java | 48 ++- src/eva2/client/RMIConnectionEvA.java | 4 +- src/eva2/gui/AbstractListSelectionEditor.java | 20 +- src/eva2/gui/BeanInspector.java | 345 ++++++++++++----- src/eva2/gui/BigStringEditor.java | 8 +- src/eva2/gui/DPointSetMultiIcon.java | 4 +- src/eva2/gui/DataViewer.java | 34 +- src/eva2/gui/EnumEditor.java | 4 +- src/eva2/gui/EvATreeNode.java | 17 +- src/eva2/gui/EvATreeSelectionListener.java | 27 +- src/eva2/gui/Exp.java | 12 +- src/eva2/gui/ExtAction.java | 10 +- src/eva2/gui/GenericAreaEditor.java | 4 +- src/eva2/gui/GenericDoubleArrayEditor.java | 12 +- .../gui/GenericEpsilonConstraintEditor.java | 12 +- .../gui/GenericEpsilonThresholdEditor.java | 12 +- src/eva2/gui/GenericFilePathEditor.java | 12 +- src/eva2/gui/GenericIntArrayEditor.java | 12 +- .../gui/GenericObjectListSelectionEditor.java | 4 +- .../GenericOptimizationObjectivesEditor.java | 49 ++- ...OptimizationObjectivesWithParamEditor.java | 49 ++- src/eva2/gui/GenericRemoteServersEditor.java | 40 +- .../GenericWeigthedLPTchebycheffEditor.java | 12 +- src/eva2/gui/GraphPointSet.java | 28 +- src/eva2/gui/GraphPointSetLegend.java | 8 +- src/eva2/gui/JDocFrame.java | 16 +- src/eva2/gui/JExtFileChooser.java | 7 +- src/eva2/gui/JExtMenu.java | 36 +- src/eva2/gui/JExtToolBar.java | 4 +- src/eva2/gui/JTextEditorInternalFrame.java | 52 ++- src/eva2/gui/MultiLineStringEditor.java | 8 +- src/eva2/gui/PropertyBoolSelector.java | 10 +- src/eva2/gui/PropertyDoubleArray.java | 61 ++- src/eva2/gui/PropertyEditorProvider.java | 92 +++-- src/eva2/gui/PropertyFilePath.java | 28 +- .../gui/PropertyOptimizationObjectives.java | 4 +- ...opertyOptimizationObjectivesWithParam.java | 8 +- src/eva2/gui/PropertyRemoteServers.java | 26 +- src/eva2/gui/PropertySelectableList.java | 24 +- src/eva2/gui/StringSelectionEditor.java | 8 +- src/eva2/gui/TopoPlot.java | 22 +- src/eva2/server/go/GOStandaloneVersion.java | 61 ++- src/eva2/server/go/MOCCOStandalone.java | 72 ++-- .../AbstractEAIndividualComparator.java | 36 +- .../individuals/ESIndividualBinaryData.java | 55 ++- .../individuals/ESIndividualDoubleData.java | 72 +++- .../individuals/ESIndividualIntegerData.java | 52 ++- .../ESIndividualPermutationData.java | 52 ++- .../GAESIndividualBinaryDoubleData.java | 16 +- .../individuals/GAIndividualBinaryData.java | 50 ++- .../individuals/GAIndividualDoubleData.java | 48 ++- .../individuals/GAIndividualIntegerData.java | 48 ++- .../individuals/GAPIndividualProgramData.java | 16 +- .../individuals/GEIndividualProgramData.java | 114 ++++-- .../individuals/GIIndividualIntegerData.java | 28 +- ...IOBGAIndividualIntegerPermutationData.java | 16 +- .../individuals/GPIndividualProgramData.java | 43 ++- .../IndividualDistanceComparator.java | 12 +- .../IndividualWeightedFitnessComparator.java | 40 +- .../OBGAIndividualPermutationData.java | 19 +- .../codings/ga/GAGrayCodingDouble.java | 32 +- .../codings/ga/GAGrayCodingInteger.java | 32 +- .../codings/ga/GAStandardCodingDouble.java | 28 +- .../codings/ga/GAStandardCodingInteger.java | 32 +- .../codings/gp/AbstractGPNode.java | 120 ++++-- .../go/individuals/codings/gp/GPArea.java | 49 ++- .../go/individuals/codings/gp/GPNodeAbs.java | 12 +- .../go/individuals/codings/gp/GPNodeAdd.java | 4 +- .../individuals/codings/gp/GPNodeConst.java | 4 +- .../go/individuals/codings/gp/GPNodeCos.java | 4 +- .../go/individuals/codings/gp/GPNodeDiv.java | 15 +- .../go/individuals/codings/gp/GPNodeExp.java | 4 +- .../individuals/codings/gp/GPNodeInput.java | 12 +- .../go/individuals/codings/gp/GPNodeMult.java | 8 +- .../go/individuals/codings/gp/GPNodeNeg.java | 8 +- .../individuals/codings/gp/GPNodeOutput.java | 4 +- .../go/individuals/codings/gp/GPNodePow2.java | 4 +- .../go/individuals/codings/gp/GPNodePow3.java | 4 +- .../go/individuals/codings/gp/GPNodeProd.java | 8 +- .../go/individuals/codings/gp/GPNodeSin.java | 4 +- .../go/individuals/codings/gp/GPNodeSqrt.java | 4 +- .../go/individuals/codings/gp/GPNodeSub.java | 8 +- .../go/individuals/codings/gp/GPNodeSum.java | 8 +- .../mocco/MOCCOChooseReferenceSolution.java | 8 +- .../server/go/mocco/MOCCOParameterizeGDF.java | 38 +- .../server/go/mocco/MOCCOParameterizeMO.java | 30 +- .../go/mocco/MOCCOParameterizeRefPoint.java | 41 +- .../server/go/mocco/MOCCOParameterizeSO.java | 22 +- .../go/mocco/MOCCOParameterizeSTEP.java | 42 ++- .../mocco/MOCCOParameterizeTchebycheff.java | 46 ++- src/eva2/server/go/mocco/MOCCOState.java | 20 +- .../mocco/paretofrontviewer/MOCCOViewer.java | 32 +- .../paretofrontviewer/ParetoFrontView2D.java | 76 +++- .../ParetoFrontViewScatterPlot.java | 44 ++- .../archiving/AbstractArchiving.java | 20 +- .../archiving/ArchivingAllDominating.java | 4 +- .../operators/archiving/ArchivingMaxiMin.java | 4 +- .../go/operators/archiving/ArchivingNSGA.java | 4 +- .../operators/archiving/ArchivingNSGAII.java | 4 +- .../archiving/ArchivingNSGAIISMeasure.java | 21 +- .../operators/archiving/ArchivingPESAII.java | 36 +- .../operators/archiving/ArchivingSPEAII.java | 36 +- .../InformationRetrievalInserting.java | 4 +- .../InformationRetrievalReplacing.java | 4 +- ...oveSurplusIndividualsDynamicHyperCube.java | 12 +- .../RemoveSurplusIndividualsSMetric.java | 7 +- .../ClassificationSelfOrganizingMaps.java | 28 +- .../go/operators/cluster/ClusterAll.java | 12 +- .../cluster/ClusteringDensityBased.java | 48 ++- .../cluster/ClusteringDynPeakIdent.java | 24 +- .../operators/cluster/ClusteringKMeans.java | 71 +++- .../cluster/ClusteringNearestBetter.java | 114 ++++-- .../operators/cluster/ClusteringXMeans.java | 19 +- .../constraint/AbstractConstraint.java | 24 +- .../ConstBelongsToDifferentClass.java | 4 +- ...tObjectivesInEqualityBiggerThanLinear.java | 12 +- ...ObjectivesInEqualityBiggerThanSurface.java | 8 +- ...tObjectivesInEqualityLesserThanLinear.java | 12 +- ...bjectivesInEqualitySmallerThanSurface.java | 8 +- .../constraint/ConstraintCollection.java | 8 +- .../constraint/GenericConstraint.java | 24 +- .../constraint/ImplicitConstraint.java | 8 +- .../constraint/IntervalConstraint.java | 28 +- .../operators/crossover/CrossoverEAMixer.java | 24 +- .../crossover/CrossoverESArithmetical.java | 8 +- .../crossover/CrossoverESBLXAlpha.java | 12 +- .../crossover/CrossoverESDefault.java | 8 +- .../operators/crossover/CrossoverESFlat.java | 8 +- .../crossover/CrossoverESIntermediate.java | 8 +- .../crossover/CrossoverESNPointDiscrete.java | 16 +- .../CrossoverESNPointDiscreteDislocation.java | 20 +- .../operators/crossover/CrossoverESPCX.java | 36 +- .../operators/crossover/CrossoverESSBX.java | 12 +- .../operators/crossover/CrossoverESSPX.java | 16 +- .../operators/crossover/CrossoverESUNDX.java | 24 +- .../crossover/CrossoverESUniformDiscrete.java | 8 +- .../crossover/CrossoverGABitSimulated.java | 24 +- .../crossover/CrossoverGADefault.java | 40 +- .../crossover/CrossoverGAGINPoint.java | 32 +- .../CrossoverGAGINPointSegmentwise.java | 4 +- .../crossover/CrossoverGAUniform.java | 20 +- .../crossover/CrossoverGIDefault.java | 20 +- .../crossover/CrossoverGINPoint.java | 20 +- .../crossover/CrossoverGINPointVL.java | 16 +- .../crossover/CrossoverGIUniform.java | 12 +- .../crossover/CrossoverGPDefault.java | 52 ++- .../operators/crossover/CrossoverOBGAPMX.java | 8 +- .../crossover/CrossoverOBGAPMXUniform.java | 8 +- .../go/operators/crossover/NoCrossover.java | 8 +- .../crossover/PropertyCrossoverMixer.java | 8 +- .../PropertyCrossoverMixerEditor.java | 45 ++- .../distancemetric/DoubleIntegralMetric.java | 4 +- .../distancemetric/GenotypeMetricBitSet.java | 12 +- .../distancemetric/IndividualDataMetric.java | 4 +- .../distancemetric/PhenotypeMetric.java | 24 +- .../SigmaSingleMetricGlobalMutation.java | 8 +- .../FitnessAdaptiveClustering.java | 4 +- .../fitnessmodifier/FitnessSharing.java | 4 +- .../GAGIInitializeSegmentwise.java | 40 +- .../operators/migration/MOBestMigration.java | 4 +- .../migration/MOClusteringSeparation.java | 20 +- .../operators/migration/MOConeSeparation.java | 36 +- .../migration/MOXMeansSeparation.java | 16 +- .../operators/migration/SOBestMigration.java | 4 +- .../operators/moso/MOSOEpsilonConstraint.java | 7 +- .../operators/moso/MOSOEpsilonThreshold.java | 23 +- .../go/operators/moso/MOSOLpMetric.java | 4 +- .../operators/moso/MOSOWeightedFitness.java | 4 +- .../moso/MOSOWeightedLPTchebycheff.java | 15 +- .../go/operators/mutation/CMAParamSet.java | 12 +- .../go/operators/mutation/MutateDefault.java | 12 +- .../go/operators/mutation/MutateEAMixer.java | 28 +- .../mutation/MutateESCorrVector.java | 52 ++- .../mutation/MutateESCorrolated.java | 72 +++- .../MutateESCovarianceMatrixAdaption.java | 64 +++- .../MutateESCovarianceMatrixAdaptionPlus.java | 43 ++- .../mutation/MutateESFixedStepSize.java | 20 +- .../go/operators/mutation/MutateESGlobal.java | 52 ++- .../go/operators/mutation/MutateESLocal.java | 60 ++- .../mutation/MutateESMainVectorAdaption.java | 52 ++- .../MutateESMutativeStepSizeControl.java | 50 ++- .../mutation/MutateESPathLengthAdaption.java | 64 +++- .../mutation/MutateESPolynomial.java | 20 +- .../operators/mutation/MutateESRankMuCMA.java | 148 ++++++-- .../mutation/MutateESSuccessRule.java | 49 ++- .../operators/mutation/MutateGAAdaptive.java | 32 +- .../mutation/MutateGAGISwapBits.java | 44 ++- .../mutation/MutateGAShiftSubstring.java | 20 +- .../mutation/MutateGASwapBitsSegmentwise.java | 20 +- .../operators/mutation/MutateGAUniform.java | 16 +- .../mutation/MutateGIInsertDelete.java | 24 +- .../go/operators/mutation/MutateGIInvert.java | 12 +- .../operators/mutation/MutateGINominal.java | 8 +- .../operators/mutation/MutateGIOrdinal.java | 28 +- .../go/operators/mutation/MutateGISubset.java | 8 +- .../mutation/MutateGITranslocate.java | 20 +- .../operators/mutation/MutateGPAdaptive.java | 48 ++- .../mutation/MutateGPSingleNode.java | 8 +- .../go/operators/mutation/MutateOBGAFlip.java | 8 +- .../mutation/MutateOBGAInversion.java | 8 +- .../mutation/PropertyMutationMixer.java | 16 +- .../mutation/PropertyMutationMixerEditor.java | 37 +- .../ConsiderPBestAbsorptionStrategy.java | 4 +- .../EuclideanDiversityAbsorptionStrategy.java | 4 +- .../StandardAbsorptionStrategy.java | 4 +- .../ImprovementDeactivationStrategy.java | 8 +- .../StandardDeactivationStrategy.java | 4 +- .../merging/StandardMergingStrategy.java | 20 +- .../AbstractParameterControl.java | 4 +- .../CbpsoFitnessThresholdBasedAdaption.java | 8 +- .../paramcontrol/ConstraintBasedAdaption.java | 40 +- .../paramcontrol/LinearParamAdaption.java | 8 +- .../PSOActivityFeedbackControl.java | 24 +- .../paramcontrol/ParameterControlManager.java | 36 +- .../paramcontrol/SuccessBasedAdaption.java | 8 +- .../MetricD1ApproxParetoFront.java | 8 +- .../MetricD1TrueParetoFront.java | 8 +- .../paretofrontmetrics/MetricErrorRatio.java | 12 +- .../MetricMaximumParetoFrontError.java | 8 +- .../MetricOverallNonDominatedVectors.java | 4 +- .../operators/paretofrontmetrics/MetricS.java | 20 +- .../MetricSWithReference.java | 12 +- .../go/operators/postprocess/PostProcess.java | 275 ++++++++++---- .../postprocess/SolutionHistogram.java | 16 +- .../go/operators/selection/MOSolution.java | 6 +- .../selection/SelectBestIndividuals.java | 20 +- .../operators/selection/SelectBestSingle.java | 8 +- .../selection/SelectEPTournaments.java | 16 +- .../selection/SelectHomologousMate.java | 8 +- .../SelectMOMAIIDominanceCounter.java | 4 +- .../SelectMONSGAIICrowedTournament.java | 20 +- .../selection/SelectMONonDominated.java | 12 +- .../go/operators/selection/SelectMOPESA.java | 4 +- .../selection/SelectParticleWheel.java | 8 +- .../go/operators/selection/SelectRandom.java | 11 +- .../operators/selection/SelectTournament.java | 4 +- .../selection/SelectXProbRouletteWheel.java | 24 +- .../probability/AbstractSelProb.java | 16 +- .../probability/SelProbBoltzman.java | 86 +++-- .../probability/SelProbFitnessSharing.java | 4 +- .../probability/SelProbInvertByMax.java | 12 +- .../probability/SelProbLinearRanking.java | 28 +- .../probability/SelProbNonLinearRanking.java | 28 +- .../selection/probability/SelProbRanking.java | 16 +- .../probability/SelProbStandard.java | 6 +- .../probability/SelProbStandardScaling.java | 62 ++- ...ntNondominatedSortingDistanceCrowding.java | 4 +- .../terminators/CombinedTerminator.java | 24 +- .../terminators/EvaluationTerminator.java | 4 +- .../terminators/FitnessValueTerminator.java | 4 +- .../HistoryConvergenceTerminator.java | 4 +- .../KnownOptimaFoundTerminator.java | 12 +- .../terminators/ParetoMetricTerminator.java | 24 +- .../PopulationArchiveTerminator.java | 16 +- .../PopulationMeasureTerminator.java | 24 +- .../server/go/populations/PBILPopulation.java | 28 +- .../go/problems/AbstractDynTransProblem.java | 18 +- .../AbstractDynamicOptimizationProblem.java | 35 +- .../AbstractMultiModalProblemKnown.java | 47 ++- ...ractMultiObjectiveOptimizationProblem.java | 77 +++- .../problems/AbstractOptimizationProblem.java | 65 +++- .../AbstractParallelOptimizationProblem.java | 4 +- .../go/problems/AbstractProblemBinary.java | 8 +- .../go/problems/AbstractProblemDouble.java | 88 +++-- .../go/problems/AbstractProblemInteger.java | 12 +- ...bstractSynchronousOptimizationProblem.java | 8 +- src/eva2/server/go/problems/B1Problem.java | 4 +- .../server/go/problems/BKnapsackProblem.java | 40 +- .../go/problems/ConstrHimmelblauProblem.java | 4 +- .../server/go/problems/DynJumpProblem.java | 14 +- src/eva2/server/go/problems/ERPStarter.java | 12 +- .../go/problems/ExternalRuntimeProblem.java | 74 +++- src/eva2/server/go/problems/F10Problem.java | 16 +- src/eva2/server/go/problems/F13Problem.java | 12 +- src/eva2/server/go/problems/F15Problem.java | 12 +- src/eva2/server/go/problems/F17Problem.java | 8 +- src/eva2/server/go/problems/F19Problem.java | 8 +- src/eva2/server/go/problems/F1Problem.java | 4 +- src/eva2/server/go/problems/F20Problem.java | 28 +- src/eva2/server/go/problems/F2Problem.java | 4 +- src/eva2/server/go/problems/F6Problem.java | 12 +- src/eva2/server/go/problems/F7Problem.java | 4 +- src/eva2/server/go/problems/F8Problem.java | 65 ++-- src/eva2/server/go/problems/FLensProblem.java | 74 +++- src/eva2/server/go/problems/FM0Problem.java | 8 +- .../server/go/problems/GPFunctionProblem.java | 8 +- .../go/problems/MatlabEvalMediator.java | 36 +- .../server/go/problems/MatlabProblem.java | 76 +++- .../go/problems/PSymbolicRegression.java | 83 ++-- .../go/problems/SimpleProblemWrapper.java | 20 +- src/eva2/server/go/problems/TF1Problem.java | 32 +- .../go/problems/WaitForEvARunnable.java | 4 +- .../inference/metabolic/TimeSeries.java | 37 +- src/eva2/server/go/strategies/ANPSO.java | 72 +++- src/eva2/server/go/strategies/BOA.java | 25 +- .../go/strategies/BinaryScatterSearch.java | 32 +- src/eva2/server/go/strategies/CBNPSO.java | 75 +++- .../CHCAdaptiveSearchAlgorithm.java | 36 +- .../go/strategies/ClusterBasedNichingEA.java | 241 +++++++++--- .../go/strategies/ClusteringHillClimbing.java | 44 ++- .../go/strategies/DifferentialEvolution.java | 182 ++++++--- .../DynamicParticleSwarmOptimization.java | 92 +++-- .../go/strategies/EvolutionStrategyIPOP.java | 52 ++- .../strategies/EvolutionaryProgramming.java | 8 +- .../server/go/strategies/FloodAlgorithm.java | 28 +- .../strategies/GradientDescentAlgorithm.java | 44 ++- .../server/go/strategies/HillClimbing.java | 24 +- .../go/strategies/InterfaceOptimizer.java | 1 - .../server/go/strategies/IslandModelEA.java | 64 +++- .../go/strategies/MemeticAlgorithm.java | 36 +- .../go/strategies/MonteCarloSearch.java | 16 +- .../go/strategies/MultiObjectiveCMAES.java | 5 +- .../go/strategies/MultiObjectiveEA.java | 20 +- .../go/strategies/NelderMeadSimplex.java | 48 ++- src/eva2/server/go/strategies/NicheGraph.java | 16 +- src/eva2/server/go/strategies/NichePSO.java | 154 ++++++-- .../ParticleFilterOptimization.java | 76 +++- .../ParticleSubSwarmOptimization.java | 48 ++- .../ParticleSwarmOptimizationGCPSO.java | 12 +- .../PopulationBasedIncrementalLearning.java | 32 +- .../server/go/strategies/ScatterSearch.java | 104 +++-- .../go/strategies/SimulatedAnnealing.java | 28 +- .../server/go/strategies/SteadyStateGA.java | 12 +- .../go/strategies/ThresholdAlgorithm.java | 28 +- src/eva2/server/go/strategies/Tribes.java | 32 +- .../go/strategies/WingedMultiObjectiveEA.java | 8 +- .../go/strategies/tribes/TribesExplorer.java | 4 +- .../go/strategies/tribes/TribesPosition.java | 12 +- .../go/strategies/tribes/TribesSwarm.java | 28 +- .../server/go/tools/AbstractObjectEditor.java | 27 +- src/eva2/server/go/tools/DeNovofilter.java | 4 +- .../go/tools/DoubleArrayComparator.java | 16 +- src/eva2/server/go/tools/FileTools.java | 36 +- src/eva2/server/go/tools/GeneralGEOFaker.java | 8 +- .../GeneralGenericObjectEditorPanel.java | 20 +- .../go/tools/ImpactOfDimensionOnMOEAs.java | 12 +- .../go/tools/ParetoFrontLocalTester.java | 4 +- .../server/go/tools/PortfolioFrontTester.java | 16 +- .../server/modules/AbstractGOParameters.java | 47 ++- src/eva2/server/modules/GAParameters.java | 4 +- src/eva2/server/modules/PBILParameters.java | 20 +- src/eva2/server/modules/SAParameters.java | 4 +- src/eva2/server/stat/AbstractStatistics.java | 356 +++++++++++++----- src/eva2/server/stat/EvAJob.java | 64 +++- .../server/stat/EvAStatisticalEvaluation.java | 149 ++++---- src/eva2/server/stat/GraphSelectionEnum.java | 4 +- src/eva2/server/stat/MovingAverage.java | 5 +- src/eva2/server/stat/StatisticsDummy.java | 24 +- .../server/stat/StatisticsStandalone.java | 12 +- src/eva2/tools/BasicResourceLoader.java | 48 ++- src/eva2/tools/CubicSpline.java | 12 +- src/eva2/tools/KMEANSJAVA.java | 18 +- src/eva2/tools/MultirunRefiner.java | 20 +- src/eva2/tools/PairComparator.java | 12 +- src/eva2/tools/ReflectPackage.java | 123 ++++-- src/eva2/tools/SelectedTag.java | 24 +- src/eva2/tools/SerializedObject.java | 5 +- src/eva2/tools/StringTools.java | 52 ++- src/eva2/tools/TXTFileFilter.java | 12 +- src/eva2/tools/ToolBox.java | 8 +- .../Chart2DDPointContentSelectable.java | 12 +- .../chart2d/Chart2DDPointIconCircle.java | 4 +- .../tools/chart2d/Chart2DDPointIconPoint.java | 4 +- src/eva2/tools/chart2d/DArea.java | 254 ++++++++----- src/eva2/tools/chart2d/DArray.java | 115 ++++-- src/eva2/tools/chart2d/DBorder.java | 5 +- src/eva2/tools/chart2d/DComponent.java | 12 +- src/eva2/tools/chart2d/DContainer.java | 41 +- src/eva2/tools/chart2d/DFunction.java | 16 +- src/eva2/tools/chart2d/DGrid.java | 8 +- src/eva2/tools/chart2d/DLine.java | 4 +- src/eva2/tools/chart2d/DMeasures.java | 36 +- src/eva2/tools/chart2d/DPoint.java | 21 +- src/eva2/tools/chart2d/DRectangle.java | 178 ++++++--- src/eva2/tools/chart2d/ScaledBorder.java | 193 +++++++--- src/eva2/tools/chart2d/SlimRect.java | 26 +- src/eva2/tools/jproxy/ComAdapter.java | 60 ++- src/eva2/tools/jproxy/JProxyRemoteThread.java | 10 +- .../tools/jproxy/MainAdapterClientImpl.java | 8 +- .../jproxy/RMIInvocationHandlerImpl.java | 32 +- src/eva2/tools/jproxy/RMIProxyLocal.java | 24 +- .../tools/jproxy/RMIProxyLocalThread.java | 8 +- src/eva2/tools/jproxy/RMIProxyRemote.java | 16 +- .../tools/jproxy/RMIProxyRemoteThread.java | 5 +- .../RMIThreadInvocationHandlerImpl.java | 20 +- src/eva2/tools/jproxy/ThreadProxy.java | 5 +- src/eva2/tools/jproxy/ThreadWrapper.java | 5 +- src/eva2/tools/jproxy/XThread.java | 33 +- src/eva2/tools/math/BayNet.java | 32 +- src/eva2/tools/math/Jama/LUDecomposition.java | 5 +- src/eva2/tools/math/Jama/Matrix.java | 37 +- src/eva2/tools/math/Jama/QRDecomposition.java | 5 +- src/eva2/tools/math/Jama/util/Maths.java | 5 +- src/eva2/tools/math/Mathematics.java | 205 ++++++---- src/eva2/tools/math/SpecialFunction.java | 351 ++++++++++++----- src/eva2/tools/math/StatisticUtils.java | 12 +- .../math/interpolation/PolyInterpolation.java | 43 ++- .../interpolation/SplineInterpolation.java | 42 ++- src/eva2/tools/matlab/JMatLink.java | 54 +-- src/eva2/tools/print/PagePrinter.java | 21 +- src/simpleprobs/SimpleB1.java | 4 +- 402 files changed, 8970 insertions(+), 3416 deletions(-) diff --git a/src/eva2/EvAInfo.java b/src/eva2/EvAInfo.java index f7b02831..8231ccf6 100644 --- a/src/eva2/EvAInfo.java +++ b/src/eva2/EvAInfo.java @@ -91,7 +91,9 @@ public class EvAInfo { public static String getVersion() { String version = getProperty("EvA2Version"); - if (version==null) System.err.println("ERROR, missing property EvA2Version!"); + if (version==null) { + System.err.println("ERROR, missing property EvA2Version!"); + } return version; } diff --git a/src/eva2/OptimizerRunnable.java b/src/eva2/OptimizerRunnable.java index 276c0e42..c19b0f98 100644 --- a/src/eva2/OptimizerRunnable.java +++ b/src/eva2/OptimizerRunnable.java @@ -83,7 +83,9 @@ public class OptimizerRunnable implements Runnable { cntID++; proc = new Processor(stats, null, params); - if (proc.getStatistics() instanceof AbstractStatistics) ((AbstractStatistics)proc.getStatistics()).setSaveParams(false); + if (proc.getStatistics() instanceof AbstractStatistics) { + ((AbstractStatistics)proc.getStatistics()).setSaveParams(false); + } doRestart = restart; } @@ -112,20 +114,28 @@ public class OptimizerRunnable implements Runnable { } public void setStats(InterfaceStatistics stats) { - if (proc.isOptRunning()) throw new RuntimeException("Error - cannot change statistics instance during optimization."); + if (proc.isOptRunning()) { + throw new RuntimeException("Error - cannot change statistics instance during optimization."); + } InterfaceGOParameters params = proc.getGOParams(); proc = new Processor(stats, null, params); - if (proc.getStatistics() instanceof AbstractStatistics) ((AbstractStatistics)proc.getStatistics()).setSaveParams(false); + if (proc.getStatistics() instanceof AbstractStatistics) { + ((AbstractStatistics)proc.getStatistics()).setSaveParams(false); + } } public void setTextListener(InterfaceTextListener lsnr) { proc.getStatistics().removeTextListener(listener); this.listener = lsnr; - if (listener != null) proc.getStatistics().addTextListener(listener); + if (listener != null) { + proc.getStatistics().addTextListener(listener); + } } public void addRemoteStateListener(RemoteStateListener rsl) { - if (proc != null) proc.addListener(rsl); + if (proc != null) { + proc.addListener(rsl); + } } public void setDoRestart(boolean restart) { @@ -140,8 +150,12 @@ public class OptimizerRunnable implements Runnable { if (postProcessOnly) { proc.performPostProcessing((PostProcessParams)proc.getGOParams().getPostProcessParams(), listener); } else { - if (doRestart) proc.restartOpt(); - else proc.startOpt(); + if (doRestart) { + proc.restartOpt(); + } + else { + proc.startOpt(); + } proc.runOptOnce(); } } catch(Exception e) { @@ -204,28 +218,36 @@ public class OptimizerRunnable implements Runnable { InterfaceTerminator term = proc.getGOParams().getTerminator(); return term.lastTerminationMessage(); } - } else return "Not yet terminated"; + } else { + return "Not yet terminated"; + } } public double[] getDoubleSolution() { IndividualInterface indy = getResult(); if (indy instanceof InterfaceDataTypeDouble) { return ((InterfaceDataTypeDouble)indy).getDoubleData(); - } else return null; + } else { + return null; + } } public BitSet getBinarySolution() { IndividualInterface indy = getResult(); if (indy instanceof InterfaceDataTypeBinary) { return ((InterfaceDataTypeBinary)indy).getBinaryData(); - } else return null; + } else { + return null; + } } public int[] getIntegerSolution() { IndividualInterface indy = getResult(); if (indy instanceof InterfaceDataTypeInteger) { return ((InterfaceDataTypeInteger)indy).getIntegerData(); - } else return null; + } else { + return null; + } } /** @@ -237,7 +259,9 @@ public class OptimizerRunnable implements Runnable { public void setVerbosityLevel(int vLev) { if (vLev >= 0 && vLev < proc.getStatistics().getStatisticsParameter().getOutputVerbosity().getTags().length) { proc.getStatistics().getStatisticsParameter().getOutputVerbosity().setSelectedTag(vLev); - } else System.err.println("Invalid verbosity leveln in OptimizerRunnable.setVerbosityLevel!"); + } else { + System.err.println("Invalid verbosity leveln in OptimizerRunnable.setVerbosityLevel!"); + } } /** diff --git a/src/eva2/client/RMIConnectionEvA.java b/src/eva2/client/RMIConnectionEvA.java index d7b53e66..3964e001 100644 --- a/src/eva2/client/RMIConnectionEvA.java +++ b/src/eva2/client/RMIConnectionEvA.java @@ -27,7 +27,9 @@ class RMIConnectionEvA extends RMIConnection { if (m_MainAdapter instanceof EvAMainAdapter) { EvAMainAdapter evaAdapter = (EvAMainAdapter)m_MainAdapter; ModuleAdapter ret = null; - if (TRACE) System.out.println("ComAdapter.getModuleAdapter(" + Modul + ")"); + if (TRACE) { + System.out.println("ComAdapter.getModuleAdapter(" + Modul + ")"); + } String hostAdd = ""; try { hostAdd = InetAddress.getLocalHost().getHostAddress(); diff --git a/src/eva2/gui/AbstractListSelectionEditor.java b/src/eva2/gui/AbstractListSelectionEditor.java index c55ed3a2..347e7ed7 100644 --- a/src/eva2/gui/AbstractListSelectionEditor.java +++ b/src/eva2/gui/AbstractListSelectionEditor.java @@ -98,7 +98,9 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop this.m_BlackCheck[i].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { - if (actionOnSelect()) m_Support.firePropertyChange("AbstractListSelectionEditor", null, this); + if (actionOnSelect()) { + m_Support.firePropertyChange("AbstractListSelectionEditor", null, this); + } } }); this.m_NodePanel.add(this.m_BlackCheck[i]); @@ -125,7 +127,9 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop */ @Override public void setValue(Object o) { - if (setObject(o)) updateEditor(); + if (setObject(o)) { + updateEditor(); + } } /** @@ -157,13 +161,17 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -202,7 +210,9 @@ public abstract class AbstractListSelectionEditor extends JPanel implements Prop */ @Override public Component getCustomEditor() { - if (this.m_CustomEditor == null) this.initCustomEditor(); + if (this.m_CustomEditor == null) { + this.initCustomEditor(); + } return m_CustomEditor; } diff --git a/src/eva2/gui/BeanInspector.java b/src/eva2/gui/BeanInspector.java index 1fafc143..4d0533fe 100644 --- a/src/eva2/gui/BeanInspector.java +++ b/src/eva2/gui/BeanInspector.java @@ -146,26 +146,38 @@ public class BeanInspector { * @return Description of the Return Value */ private static String toString(Object obj, char delim, boolean tight, String indentStr, int indentDepth, boolean withNewlines) { - if (obj == null) return "null"; + if (obj == null) { + return "null"; + } // try the object itself - if (obj instanceof String) return (String)obj; // directly return a string object + if (obj instanceof String) { + return (String)obj; + } // directly return a string object Class type = obj.getClass(); if (type.isArray()) { // handle the array case StringBuffer sbuf = new StringBuffer(); sbuf.append("["); - if (!tight) sbuf.append(" "); + if (!tight) { + sbuf.append(" "); + } int len = Array.getLength(obj); for (int i=0; i lst = (List)obj; for (Object o : lst) { sbuf.append(o.toString()); sbuf.append(delim); - if (!tight) sbuf.append(" "); + if (!tight) { + sbuf.append(" "); + } } - if (!tight && (sbuf.charAt(sbuf.length()-2) == delim)) sbuf.setCharAt(sbuf.length()-2, ' '); // delete the delim + if (!tight && (sbuf.charAt(sbuf.length()-2) == delim)) { + sbuf.setCharAt(sbuf.length()-2, ' '); + } // delete the delim sbuf.setCharAt(sbuf.length()-1, ']'); return sbuf.toString(); } @@ -198,7 +218,9 @@ public class BeanInspector { //args[0] = obj; try { String ret = (String) methods[ii].invoke(obj, args); - if (TRACE) System.out.println("toString on "+ obj.getClass() + " gave me " + ret); + if (TRACE) { + System.out.println("toString on "+ obj.getClass() + " gave me " + ret); + } return makeIndent(indentStr, indentDepth) + ret; } catch (Exception e) { System.err.println(" ERROR +"+ e.getMessage()); @@ -211,19 +233,25 @@ public class BeanInspector { Pair nameVals = getPublicPropertiesOf(obj, true, true); StringBuffer sbuf = new StringBuffer(); - if (withNewlines) sbuf.append('\n'); + if (withNewlines) { + sbuf.append('\n'); + } addIndent(sbuf, indentStr, indentDepth); sbuf.append(type.getName()); sbuf.append("{"); for (int i=0; i memberInfoList = new ArrayList(); for (int i = 0; i < m_Properties.length; i++) { - if (m_Properties[i].isExpert()) continue; + if (m_Properties[i].isExpert()) { + continue; + } String name = m_Properties[i].getDisplayName(); - if (TRACE) System.out.println("PSP looking at "+ name); + if (TRACE) { + System.out.println("PSP looking at "+ name); + } Method getter = m_Properties[i].getReadMethod(); Method setter = m_Properties[i].getWriteMethod(); // Only display read/write properties. - if (getter == null || setter == null) continue; + if (getter == null || setter == null) { + continue; + } try { Object args[] = { }; @@ -612,7 +702,9 @@ public class BeanInspector { if (value == null) { // If it's a user-defined property we give a warning. String getterClass = m_Properties[i].getReadMethod().getDeclaringClass().getName(); - if (getterClass.indexOf("java.") != 0) System.err.println("Warning: Property \"" + name+ "\" has null initial value. Skipping."); + if (getterClass.indexOf("java.") != 0) { + System.err.println("Warning: Property \"" + name+ "\" has null initial value. Skipping."); + } continue; } @@ -633,10 +725,14 @@ public class BeanInspector { memberInfoBf.append("String in {"); for (int k=0; k destType) throws NumberFormatException { - if ((destType == Integer.class) || (destType == int.class)) return Integer.valueOf(str); - else if ((destType == Double.class) || (destType == double.class)) return Double.valueOf(str); - else if ((destType == Boolean.class) || (destType == boolean.class)) return Boolean.valueOf(str); - else if ((destType == Byte.class) || (destType == byte.class)) return Byte.valueOf(str); - else if ((destType == Short.class) || (destType == short.class)) return Short.valueOf(str); - else if ((destType == Long.class) || (destType == long.class)) return Long.valueOf(str); - else if ((destType == Float.class) || (destType == float.class)) return Float.valueOf(str); - else if ((destType == Character.class) || (destType == char.class)) return str.charAt(0); + if ((destType == Integer.class) || (destType == int.class)) { + return Integer.valueOf(str); + } + else if ((destType == Double.class) || (destType == double.class)) { + return Double.valueOf(str); + } + else if ((destType == Boolean.class) || (destType == boolean.class)) { + return Boolean.valueOf(str); + } + else if ((destType == Byte.class) || (destType == byte.class)) { + return Byte.valueOf(str); + } + else if ((destType == Short.class) || (destType == short.class)) { + return Short.valueOf(str); + } + else if ((destType == Long.class) || (destType == long.class)) { + return Long.valueOf(str); + } + else if ((destType == Float.class) || (destType == float.class)) { + return Float.valueOf(str); + } + else if ((destType == Character.class) || (destType == char.class)) { + return str.charAt(0); + } else { // if (destType == Void.class) System.err.println("warning, value interpreted as void type"); @@ -714,18 +844,35 @@ public class BeanInspector { * @return */ public static Object doubleToPrimitive(Double d, Class destType) { - if ((destType == Double.class) || (destType == double.class)) return d; - if ((destType == Integer.class) || (destType == int.class)) return new Integer(d.intValue()); - else if ((destType == Boolean.class) || (destType == boolean.class)) return (d!=0) ? Boolean.TRUE : Boolean.FALSE; - else if ((destType == Byte.class) || (destType == byte.class)) return new Byte(d.byteValue()); - else if ((destType == Short.class) || (destType == short.class)) return new Short(d.shortValue()); - else if ((destType == Long.class) || (destType == long.class)) return new Long(d.longValue()); - else if ((destType == Float.class) || (destType == float.class)) return new Float(d.floatValue()); + if ((destType == Double.class) || (destType == double.class)) { + return d; + } + if ((destType == Integer.class) || (destType == int.class)) { + return new Integer(d.intValue()); + } + else if ((destType == Boolean.class) || (destType == boolean.class)) { + return (d!=0) ? Boolean.TRUE : Boolean.FALSE; + } + else if ((destType == Byte.class) || (destType == byte.class)) { + return new Byte(d.byteValue()); + } + else if ((destType == Short.class) || (destType == short.class)) { + return new Short(d.shortValue()); + } + else if ((destType == Long.class) || (destType == long.class)) { + return new Long(d.longValue()); + } + else if ((destType == Float.class) || (destType == float.class)) { + return new Float(d.floatValue()); + } else { // this makes hardly sense... System.err.println("warning: converting from double to character or void..."); - if ((destType == Character.class) || (destType == char.class)) return new Character(d.toString().charAt(0)); - else //if (destType == Void.class) return 0; - return 0; + if ((destType == Character.class) || (destType == char.class)) { + return new Character(d.toString().charAt(0)); + } + else { + return 0; + } } } @@ -737,9 +884,13 @@ public class BeanInspector { * @return */ public static boolean isJavaPrimitive(Class cls) { - if (cls.isPrimitive()) return true; + if (cls.isPrimitive()) { + return true; + } if ((cls == Double.class) || (cls == Integer.class) || (cls == Boolean.class) || (cls == Character.class) || (cls == Void.class) - || (cls == Byte.class) || (cls == Short.class) || (cls == Long.class) || (cls == Float.class)) return true; + || (cls == Byte.class) || (cls == Short.class) || (cls == Long.class) || (cls == Float.class)) { + return true; + } return false; } @@ -751,14 +902,30 @@ public class BeanInspector { * @return */ public static Class getJavaPrimitive(Class cls) { - if (cls.isPrimitive()) return cls; - if (cls == Double.class) return double.class; - else if (cls == Integer.class) return int.class; - else if (cls == Boolean.class) return Boolean.class; - else if (cls == Byte.class) return byte.class; - else if (cls == Short.class) return short.class; - else if (cls == Long.class) return long.class; - else if (cls == Float.class) return float.class; + if (cls.isPrimitive()) { + return cls; + } + if (cls == Double.class) { + return double.class; + } + else if (cls == Integer.class) { + return int.class; + } + else if (cls == Boolean.class) { + return Boolean.class; + } + else if (cls == Byte.class) { + return byte.class; + } + else if (cls == Short.class) { + return short.class; + } + else if (cls == Long.class) { + return long.class; + } + else if (cls == Float.class) { + return float.class; + } return null; } /** @@ -776,8 +943,12 @@ public class BeanInspector { return value; } if (destType == String.class || destType == SelectedTag.class) { - if (value.getClass() == String.class) return value; - else return value.toString(); + if (value.getClass() == String.class) { + return value; + } + else { + return value.toString(); + } } else if (isJavaPrimitive(destType)) { try { if (value.getClass() == String.class) { diff --git a/src/eva2/gui/BigStringEditor.java b/src/eva2/gui/BigStringEditor.java index 098ced4b..2a004351 100644 --- a/src/eva2/gui/BigStringEditor.java +++ b/src/eva2/gui/BigStringEditor.java @@ -214,13 +214,17 @@ public class BigStringEditor implements PropertyEditor { @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } } diff --git a/src/eva2/gui/DPointSetMultiIcon.java b/src/eva2/gui/DPointSetMultiIcon.java index d2a08521..a66a0449 100644 --- a/src/eva2/gui/DPointSetMultiIcon.java +++ b/src/eva2/gui/DPointSetMultiIcon.java @@ -339,7 +339,9 @@ public class DPointSetMultiIcon extends DComponent { p = m.getPoint(xMI.getImage(i), yMI.getImage(i)); - if (p==null) continue; + if (p==null) { + continue; + } if (this.m_IconsMI.get(i) != null) { g.setStroke(new BasicStroke()); diff --git a/src/eva2/gui/DataViewer.java b/src/eva2/gui/DataViewer.java index 898fe22b..1e9a9ad0 100644 --- a/src/eva2/gui/DataViewer.java +++ b/src/eva2/gui/DataViewer.java @@ -37,8 +37,9 @@ public class DataViewer implements DataViewerInterface { * */ public static DataViewerInterface getInstance (MainAdapterClient client,String GraphWindowName) { - if (m_ViewContainer == null) - m_ViewContainer = new ViewContainer(); + if (m_ViewContainer == null) { + m_ViewContainer = new ViewContainer(); + } DataViewerInterface ret =null; try { if (!m_ViewContainer.containsName(GraphWindowName)) { @@ -50,13 +51,17 @@ public class DataViewer implements DataViewerInterface { e.printStackTrace(); } if (client != null && client.getHostName().equals(m_MyHostName)== true) { - if (TRACE) System.out.println("no RMI"); + if (TRACE) { + System.out.println("no RMI"); + } ret = new DataViewer(GraphWindowName,true); } else { ret = (DataViewerInterface) RMIProxyRemote.newInstance(new DataViewer(GraphWindowName,false), client); ret.init(); - if (TRACE) System.out.println("with RMI"); + if (TRACE) { + System.out.println("with RMI"); + } } @@ -76,10 +81,13 @@ public class DataViewer implements DataViewerInterface { * */ private DataViewer(String PlotName,boolean initflag){ - if (TRACE) System.out.println("Constructor DataViewer"); + if (TRACE) { + System.out.println("Constructor DataViewer"); + } m_Name = PlotName; - if(initflag) - this.init(); + if(initflag) { + this.init(); + } } /** * @@ -93,7 +101,9 @@ public class DataViewer implements DataViewerInterface { @Override public Graph getNewGraph(String InfoString) { m_GraphCounter++; - if (TRACE) System.out.println("Graph.getNewGraph No:"+m_GraphCounter); + if (TRACE) { + System.out.println("Graph.getNewGraph No:"+m_GraphCounter); + } return new Graph (InfoString,m_Plot,m_GraphCounter); } /** @@ -131,9 +141,11 @@ class ViewContainer extends ArrayList { * */ public DataViewer getPlot (String name) { - if (m_actualPlot!=null) - if (m_actualPlot.getName().equals(name)) - return m_actualPlot; + if (m_actualPlot!=null) { + if (m_actualPlot.getName().equals(name)) { + return m_actualPlot; + } + } DataViewer temp = null; for (int i=0;i=0; i--) { - System.out.println("* " + i + " " + tp.getPathComponent(i)); - } + if (TRACE) { + for (int i=tp.getPathCount()-1; i>=0; i--) { + System.out.println("* " + i + " " + tp.getPathComponent(i)); + } } EvATreeNode leafNode = (EvATreeNode)tp.getLastPathComponent(); // goe.setValue(leafNode.getUserObject()); Component editComp = goe.getCustomEditor(); @@ -61,8 +68,12 @@ public class EvATreeSelectionListener implements TreeSelectionListener, Property @Override public void propertyChange(PropertyChangeEvent evt) { - if (TRACE) System.out.println("EvATreeNode received change event " + 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! + 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 8a6e962d..c9787979 100644 --- a/src/eva2/gui/Exp.java +++ b/src/eva2/gui/Exp.java @@ -12,8 +12,12 @@ 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!"); + if (v>0) { + minValue = v; + } + else { + System.err.println("Error, minimal value for Exp must be positive!"); + } } /* * (non-Javadoc) @@ -58,6 +62,8 @@ public class Exp extends DFunction { } public void updateMinValue(double y) { - if (y0)) minValue=y; + if (y0)) { + minValue=y; + } } } diff --git a/src/eva2/gui/ExtAction.java b/src/eva2/gui/ExtAction.java index 726d16d2..db1696df 100644 --- a/src/eva2/gui/ExtAction.java +++ b/src/eva2/gui/ExtAction.java @@ -38,8 +38,9 @@ public abstract class ExtAction extends AbstractAction { */ public ExtAction(String s, Icon i, String toolTip, KeyStroke key){ this(s, i, toolTip); - if (i==null) - System.out.println("Icon == null"); + if (i==null) { + System.out.println("Icon == null"); + } putValue(KEYSTROKE, key); } /** @@ -47,8 +48,9 @@ public abstract class ExtAction extends AbstractAction { */ public ExtAction(String s, Icon i, String toolTip){ super(null, i); - if (i==null) - System.out.println("Icon == null"); + if (i==null) { + System.out.println("Icon == null"); + } setValues(s, toolTip); } /** diff --git a/src/eva2/gui/GenericAreaEditor.java b/src/eva2/gui/GenericAreaEditor.java index 9c94b387..3e54389e 100644 --- a/src/eva2/gui/GenericAreaEditor.java +++ b/src/eva2/gui/GenericAreaEditor.java @@ -52,7 +52,9 @@ public class GenericAreaEditor extends AbstractListSelectionEditor { this.m_AreaObject = (GPArea) o; m_AreaObject.addPropertyChangeListener(this); return true; - } else return false; + } else { + return false; + } } @Override diff --git a/src/eva2/gui/GenericDoubleArrayEditor.java b/src/eva2/gui/GenericDoubleArrayEditor.java index e3d4f7e9..389ba558 100644 --- a/src/eva2/gui/GenericDoubleArrayEditor.java +++ b/src/eva2/gui/GenericDoubleArrayEditor.java @@ -290,13 +290,17 @@ public class GenericDoubleArrayEditor extends JPanel implements PropertyEditor { @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -348,7 +352,9 @@ public class GenericDoubleArrayEditor extends JPanel implements PropertyEditor { */ @Override public Component getCustomEditor() { - if (this.m_CustomEditor == null) this.initCustomEditor(); + if (this.m_CustomEditor == null) { + this.initCustomEditor(); + } return m_CustomEditor; } } \ No newline at end of file diff --git a/src/eva2/gui/GenericEpsilonConstraintEditor.java b/src/eva2/gui/GenericEpsilonConstraintEditor.java index 97a003c2..279a3de5 100644 --- a/src/eva2/gui/GenericEpsilonConstraintEditor.java +++ b/src/eva2/gui/GenericEpsilonConstraintEditor.java @@ -197,13 +197,17 @@ public class GenericEpsilonConstraintEditor extends JPanel implements PropertyEd @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -255,7 +259,9 @@ public class GenericEpsilonConstraintEditor extends JPanel implements PropertyEd */ @Override public Component getCustomEditor() { - if (this.m_CustomEditor == null) this.initCustomEditor(); + if (this.m_CustomEditor == null) { + this.initCustomEditor(); + } return m_CustomEditor; } } \ No newline at end of file diff --git a/src/eva2/gui/GenericEpsilonThresholdEditor.java b/src/eva2/gui/GenericEpsilonThresholdEditor.java index 35c01cd2..fa116d01 100644 --- a/src/eva2/gui/GenericEpsilonThresholdEditor.java +++ b/src/eva2/gui/GenericEpsilonThresholdEditor.java @@ -214,13 +214,17 @@ public class GenericEpsilonThresholdEditor extends JPanel implements PropertyEdi @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -272,7 +276,9 @@ public class GenericEpsilonThresholdEditor extends JPanel implements PropertyEdi */ @Override public Component getCustomEditor() { - if (this.m_CustomEditor == null) this.initCustomEditor(); + if (this.m_CustomEditor == null) { + this.initCustomEditor(); + } return m_CustomEditor; } } \ No newline at end of file diff --git a/src/eva2/gui/GenericFilePathEditor.java b/src/eva2/gui/GenericFilePathEditor.java index d68e8631..7d649820 100644 --- a/src/eva2/gui/GenericFilePathEditor.java +++ b/src/eva2/gui/GenericFilePathEditor.java @@ -85,13 +85,17 @@ public class GenericFilePathEditor extends JPanel implements PropertyEditor { @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -156,7 +160,9 @@ public class GenericFilePathEditor extends JPanel implements PropertyEditor { m_FilePath.setCompleteFilePath(m_FileChooser.getSelectedFile().getAbsolutePath()); m_Support.firePropertyChange("", m_FilePath, null); Window w = (Window) m_FileChooser.getTopLevelAncestor(); - if (w != null) w.dispose(); + if (w != null) { + w.dispose(); + } m_Panel = null; } } diff --git a/src/eva2/gui/GenericIntArrayEditor.java b/src/eva2/gui/GenericIntArrayEditor.java index 31e9b5fa..6d66b403 100644 --- a/src/eva2/gui/GenericIntArrayEditor.java +++ b/src/eva2/gui/GenericIntArrayEditor.java @@ -173,13 +173,17 @@ public class GenericIntArrayEditor extends JPanel implements PropertyEditor { @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -231,7 +235,9 @@ public class GenericIntArrayEditor extends JPanel implements PropertyEditor { */ @Override public Component getCustomEditor() { - if (this.m_CustomEditor == null) this.initCustomEditor(); + if (this.m_CustomEditor == null) { + this.initCustomEditor(); + } return m_CustomEditor; } } \ No newline at end of file diff --git a/src/eva2/gui/GenericObjectListSelectionEditor.java b/src/eva2/gui/GenericObjectListSelectionEditor.java index 6852ef2a..a6f7c9db 100644 --- a/src/eva2/gui/GenericObjectListSelectionEditor.java +++ b/src/eva2/gui/GenericObjectListSelectionEditor.java @@ -42,7 +42,9 @@ public class GenericObjectListSelectionEditor extends AbstractListSelectionEdito this.objList = (PropertySelectableList) o; objList.addPropertyChangeListener(this); return true; - } else return false; + } else { + return false; + } } /** Retruns the current object. diff --git a/src/eva2/gui/GenericOptimizationObjectivesEditor.java b/src/eva2/gui/GenericOptimizationObjectivesEditor.java index 8e7047b6..42292462 100644 --- a/src/eva2/gui/GenericOptimizationObjectivesEditor.java +++ b/src/eva2/gui/GenericOptimizationObjectivesEditor.java @@ -80,13 +80,18 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceOptimizationTarget.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -217,13 +222,18 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope try { 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); - if (newEdit[l].m_Editor instanceof GenericObjectEditor) + if (newEdit[l].m_Editor == null) { + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); + } + if (newEdit[l].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) newEdit[l].m_Editor).setClassType(InterfaceOptimizationTarget.class); + } newEdit[l].m_Editor.setValue(newEdit[l].m_Value); newEdit[l].m_Editor.addPropertyChangeListener(m_self); AbstractObjectEditor.findViewFor(newEdit[l]); - if (newEdit[l].m_View != null) newEdit[l].m_View.repaint(); + if (newEdit[l].m_View != null) { + newEdit[l].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -240,7 +250,9 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope int l = m_OptimizationObjectives.getSelectedTargets().length, j = 0; 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); + if (event.getSource().equals(m_Delete[i])) { + m_OptimizationObjectives.removeTarget(i); + } else { newEdit[j] = m_Editors[i]; j++; @@ -361,7 +373,9 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope */ @Override public Component getCustomEditor() { - if (this.m_Editor == null) this.initCustomEditor(); + if (this.m_Editor == null) { + this.initCustomEditor(); + } return m_Editor; } @@ -377,13 +391,17 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } /** This will wait for the GenericObjectEditor to finish @@ -402,13 +420,18 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceOptimizationTarget.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } diff --git a/src/eva2/gui/GenericOptimizationObjectivesWithParamEditor.java b/src/eva2/gui/GenericOptimizationObjectivesWithParamEditor.java index 87020609..d98806ff 100644 --- a/src/eva2/gui/GenericOptimizationObjectivesWithParamEditor.java +++ b/src/eva2/gui/GenericOptimizationObjectivesWithParamEditor.java @@ -83,13 +83,18 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceOptimizationObjective.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -242,13 +247,18 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme try { 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); - if (newEdit[l].m_Editor instanceof GenericObjectEditor) + if (newEdit[l].m_Editor == null) { + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); + } + if (newEdit[l].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) newEdit[l].m_Editor).setClassType(InterfaceOptimizationObjective.class); + } newEdit[l].m_Editor.setValue(newEdit[l].m_Value); newEdit[l].m_Editor.addPropertyChangeListener(m_self); AbstractObjectEditor.findViewFor(newEdit[l]); - if (newEdit[l].m_View != null) newEdit[l].m_View.repaint(); + if (newEdit[l].m_View != null) { + newEdit[l].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -265,7 +275,9 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme int l = m_OptimizationObjectivesWithWeights.getSelectedTargets().length, j = 0; 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); + if (event.getSource().equals(m_Delete[i])) { + m_OptimizationObjectivesWithWeights.removeTarget(i); + } else { newEdit[j] = m_Editors[i]; j++; @@ -432,7 +444,9 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme */ @Override public Component getCustomEditor() { - if (this.m_Editor == null) this.initCustomEditor(); + if (this.m_Editor == null) { + this.initCustomEditor(); + } return m_Editor; } @@ -448,13 +462,17 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } /** This will wait for the GenericObjectEditor to finish @@ -473,13 +491,18 @@ public class GenericOptimizationObjectivesWithParamEditor extends JPanel impleme try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizationObjective.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceOptimizationObjective.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } diff --git a/src/eva2/gui/GenericRemoteServersEditor.java b/src/eva2/gui/GenericRemoteServersEditor.java index c53ba707..599573b0 100644 --- a/src/eva2/gui/GenericRemoteServersEditor.java +++ b/src/eva2/gui/GenericRemoteServersEditor.java @@ -107,8 +107,12 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor JButton tmpB; byte[] bytes; bytes = BasicResourceLoader.instance().getBytesFromResourceLocation(iconSrc, false); - if (bytes!=null) tmpB = new JButton(title, new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); - else tmpB = new JButton(title); + if (bytes!=null) { + tmpB = new JButton(title, new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); + } + else { + tmpB = new JButton(title); + } return tmpB; } @@ -148,8 +152,12 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor setGBC(gbc, GridBagConstraints.WEST, GridBagConstraints.BOTH, 0, 1); this.m_Status[i] = new JButton(" "); this.m_Status[i].setEnabled(false); - if (this.m_RemoteServers.isServerOnline(t.m_ServerName)) this.m_Status[i].setBackground(Color.GREEN); - else this.m_Status[i].setBackground(Color.RED); + if (this.m_RemoteServers.isServerOnline(t.m_ServerName)) { + this.m_Status[i].setBackground(Color.GREEN); + } + else { + this.m_Status[i].setBackground(Color.RED); + } this.m_ServerList.add(this.m_Status[i], gbc); // the server name gbc = new GridBagConstraints(); @@ -263,7 +271,9 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor @Override public void actionPerformed(ActionEvent event) { for (int i = 0; i < m_Delete.length; i++) { - if (event.getSource().equals(m_Delete[i])) m_RemoteServers.removeServerNode(m_RemoteServers.get(i).m_ServerName); + if (event.getSource().equals(m_Delete[i])) { + m_RemoteServers.removeServerNode(m_RemoteServers.get(i).m_ServerName); + } } updateServerList(); updateEditor(); @@ -343,7 +353,9 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor @Override public void keyReleased(KeyEvent event) { for (int i = 0; i < m_Names.length; i++) { - if (event.getSource().equals(m_Names[i])) m_RemoteServers.setNameFor(i, m_Names[i].getText()); + if (event.getSource().equals(m_Names[i])) { + m_RemoteServers.setNameFor(i, m_Names[i].getText()); + } } } }; @@ -354,7 +366,9 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor @Override public void itemStateChanged(ItemEvent event) { for (int i = 0; i < m_CPUs.length; i++) { - if (event.getSource().equals(m_CPUs[i])) m_RemoteServers.setCPUsFor(i, m_CPUs[i].getSelectedIndex()+1); + if (event.getSource().equals(m_CPUs[i])) { + m_RemoteServers.setCPUsFor(i, m_CPUs[i].getSelectedIndex()+1); + } } } }; @@ -419,13 +433,17 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -477,7 +495,9 @@ public class GenericRemoteServersEditor extends JPanel implements PropertyEditor */ @Override public Component getCustomEditor() { - if (this.m_Editor == null) this.initCustomEditor(); + if (this.m_Editor == null) { + this.initCustomEditor(); + } return m_Editor; } } \ No newline at end of file diff --git a/src/eva2/gui/GenericWeigthedLPTchebycheffEditor.java b/src/eva2/gui/GenericWeigthedLPTchebycheffEditor.java index 0a249caf..c129cfe7 100644 --- a/src/eva2/gui/GenericWeigthedLPTchebycheffEditor.java +++ b/src/eva2/gui/GenericWeigthedLPTchebycheffEditor.java @@ -221,13 +221,17 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } @@ -279,7 +283,9 @@ public class GenericWeigthedLPTchebycheffEditor extends JPanel implements Proper */ @Override public Component getCustomEditor() { - if (this.m_CustomEditor == null) this.initCustomEditor(); + if (this.m_CustomEditor == null) { + this.initCustomEditor(); + } return m_CustomEditor; } } \ No newline at end of file diff --git a/src/eva2/gui/GraphPointSet.java b/src/eva2/gui/GraphPointSet.java index bd53afde..2d9d513f 100644 --- a/src/eva2/gui/GraphPointSet.java +++ b/src/eva2/gui/GraphPointSet.java @@ -264,10 +264,11 @@ public class GraphPointSet { 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 (GraphSize[i] <= 0) { + System.err.println("Warning: invalid graph size of " + + GraphSize[i] + " at " + i + + "! (GraphPointSet.addGraph)"); + } } if (Mathematics.sum(GraphSize) == 0) { System.err @@ -309,8 +310,9 @@ public class GraphPointSet { y[i] = m_PointSetContainer.get(i).m_Y[index[i]]; index[i]++; numberofpoints++; - } else - y[i] = 0; + } else { + y[i] = 0; + } } double ymean = Mathematics.sum(y) / numberofpoints; // compute median double median = getMedian(y); @@ -499,10 +501,12 @@ public class GraphPointSet { } 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]); + if (buf[i].x == x.x && buf[i].y == x.y) { + System.out.println("point found"); + } + else { + m_ConnectedPointSet.addDPoint(buf[i]); + } } } @@ -563,7 +567,9 @@ public class GraphPointSet { * @return the median point of this point set or null if it is empty */ public DPoint getMedPoint() { - if (m_ConnectedPointSet==null) return null; + if (m_ConnectedPointSet==null) { + return null; + } int medX = m_ConnectedPointSet.getSize()/2; return m_ConnectedPointSet.getDPoint(medX); } diff --git a/src/eva2/gui/GraphPointSetLegend.java b/src/eva2/gui/GraphPointSetLegend.java index b1e6cc92..9893870a 100644 --- a/src/eva2/gui/GraphPointSetLegend.java +++ b/src/eva2/gui/GraphPointSetLegend.java @@ -65,8 +65,12 @@ public class GraphPointSetLegend { 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(); + if (appendIndex) { + entryStr = StringTools.expandPrefixZeros(i, pointSetContainer.size()-1) + ": " + pointset.getInfoString(); + } + else { + entryStr = pointset.getInfoString(); + } legendEntries.add(new Pair(entryStr,pointset.getColor())); } } diff --git a/src/eva2/gui/JDocFrame.java b/src/eva2/gui/JDocFrame.java index 0f6474eb..dd26e779 100644 --- a/src/eva2/gui/JDocFrame.java +++ b/src/eva2/gui/JDocFrame.java @@ -50,7 +50,9 @@ public abstract class JDocFrame extends JInternalFrame{ * */ public void save(){ - if(m_file != null) save(m_file); + if(m_file != null) { + save(m_file); + } } /** * @@ -67,14 +69,20 @@ public abstract class JDocFrame extends JInternalFrame{ */ private void setChangedImpl(boolean value){ changed = value; - if(changed) setTitle(titleStr + " *"); - else setTitle(titleStr); + if(changed) { + setTitle(titleStr + " *"); + } + else { + setTitle(titleStr); + } } /** * */ protected void setChanged(boolean value){ - if(changed != value) setChangedImpl(value); + if(changed != value) { + setChangedImpl(value); + } } /** * diff --git a/src/eva2/gui/JExtFileChooser.java b/src/eva2/gui/JExtFileChooser.java index 245f2353..1c2956ae 100644 --- a/src/eva2/gui/JExtFileChooser.java +++ b/src/eva2/gui/JExtFileChooser.java @@ -31,8 +31,11 @@ public class JExtFileChooser extends JFileChooser{ 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; + 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/JExtMenu.java b/src/eva2/gui/JExtMenu.java index 105c7ec2..ed5a638b 100644 --- a/src/eva2/gui/JExtMenu.java +++ b/src/eva2/gui/JExtMenu.java @@ -49,11 +49,17 @@ public class JExtMenu extends JMenu{ JMenuItem item = super.add(a); Object o; o = a.getValue(ExtAction.MNEMONIC); - if(o != null) item.setMnemonic(((Character)o).charValue()); + if(o != null) { + item.setMnemonic(((Character)o).charValue()); + } o = a.getValue(ExtAction.TOOLTIP); - if(o != null) item.setToolTipText((String)o); + if(o != null) { + item.setToolTipText((String)o); + } o = a.getValue(ExtAction.KEYSTROKE); - if(o != null) item.setAccelerator((KeyStroke)o); + if(o != null) { + item.setAccelerator((KeyStroke)o); + } return item; } /** @@ -65,19 +71,31 @@ public class JExtMenu extends JMenu{ @Override public void propertyChange(PropertyChangeEvent e) { JMenuItem menuItem = (JMenuItem)component; - if(menuItem == null) return; + if(menuItem == null) { + return; + } String propertyName = e.getPropertyName(); - if(propertyName.equals(Action.NAME)) menuItem.setText((String)e.getNewValue()); - else if(propertyName.equals("enabled")) menuItem.setEnabled(((Boolean)e.getNewValue()).booleanValue()); + if(propertyName.equals(Action.NAME)) { + menuItem.setText((String)e.getNewValue()); + } + else if(propertyName.equals("enabled")) { + menuItem.setEnabled(((Boolean)e.getNewValue()).booleanValue()); + } else if(propertyName.equals(Action.SMALL_ICON)){ Icon icon = (Icon)e.getNewValue(); menuItem.setIcon(icon); menuItem.invalidate(); menuItem.repaint(); } - else if(propertyName.equals(ExtAction.MNEMONIC)) menuItem.setMnemonic(((Character)e.getNewValue()).charValue()); - else if(propertyName.equals(ExtAction.TOOLTIP)) menuItem.setToolTipText((String)e.getNewValue()); - else if(propertyName.equals(ExtAction.KEYSTROKE)) menuItem.setAccelerator((KeyStroke)e.getNewValue()); + else if(propertyName.equals(ExtAction.MNEMONIC)) { + menuItem.setMnemonic(((Character)e.getNewValue()).charValue()); + } + else if(propertyName.equals(ExtAction.TOOLTIP)) { + menuItem.setToolTipText((String)e.getNewValue()); + } + else if(propertyName.equals(ExtAction.KEYSTROKE)) { + menuItem.setAccelerator((KeyStroke)e.getNewValue()); + } } }; } diff --git a/src/eva2/gui/JExtToolBar.java b/src/eva2/gui/JExtToolBar.java index 33a0b8de..2dfe246c 100644 --- a/src/eva2/gui/JExtToolBar.java +++ b/src/eva2/gui/JExtToolBar.java @@ -39,7 +39,9 @@ public class JExtToolBar extends JToolBar{ if(k != null){ int modifiers = k.getModifiers(); - if(modifiers > 0) result.append(KeyEvent.getKeyModifiersText(modifiers) + "+"); + if(modifiers > 0) { + result.append(KeyEvent.getKeyModifiersText(modifiers) + "+"); + } result.append(KeyEvent.getKeyText(k.getKeyCode())); } if(result.length() > 0){ diff --git a/src/eva2/gui/JTextEditorInternalFrame.java b/src/eva2/gui/JTextEditorInternalFrame.java index e7f189f0..2657e81c 100644 --- a/src/eva2/gui/JTextEditorInternalFrame.java +++ b/src/eva2/gui/JTextEditorInternalFrame.java @@ -104,12 +104,18 @@ public class JTextEditorInternalFrame extends JDocFrame{ private JToolBar barEdit; @Override public JMenu getMenu(String group){ - if(GROUP_EDIT.equals(group)) return mnuEdit; - else return null; + if(GROUP_EDIT.equals(group)) { + return mnuEdit; + } + else { + return null; + } } @Override public JToolBar getToolBar(String group){ - if(GROUP_EDIT.equals(group)) return barEdit; + if(GROUP_EDIT.equals(group)) { + return barEdit; + } return null; } @@ -156,7 +162,9 @@ public class JTextEditorInternalFrame extends JDocFrame{ a = (Action)hashActions.get(DefaultEditorKit.cutAction); keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + 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')); @@ -166,7 +174,9 @@ public class JTextEditorInternalFrame extends JDocFrame{ a = (Action)hashActions.get(DefaultEditorKit.copyAction); keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + 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')); @@ -176,7 +186,9 @@ public class JTextEditorInternalFrame extends JDocFrame{ a = (Action)hashActions.get(DefaultEditorKit.pasteAction); keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + 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')); @@ -188,7 +200,9 @@ public class JTextEditorInternalFrame extends JDocFrame{ a = (Action)hashActions.get(DefaultEditorKit.selectAllAction); keyActions = keys.getKeyStrokesForAction(a); - if(keyActions != null && keyActions.length > 0) a.putValue(ExtAction.KEYSTROKE, keyActions[0]); + 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"); @@ -259,10 +273,12 @@ public class JTextEditorInternalFrame extends JDocFrame{ } catch(IOException exc){} finally{ - if(in != null) try{ - in.close(); - } - catch(IOException exc){} + if(in != null) { + try{ + in.close(); +} +catch(IOException exc){} + } } } @@ -279,10 +295,12 @@ public class JTextEditorInternalFrame extends JDocFrame{ } catch(IOException exc){} finally{ - if(out != null) try{ - out.close(); - } - catch(IOException exc){} + if(out != null) { + try{ +out.close(); +} +catch(IOException exc){} + } } super.save(f); @@ -292,6 +310,8 @@ public class JTextEditorInternalFrame extends JDocFrame{ public void setSelected(boolean value) throws java.beans.PropertyVetoException{ super.setSelected(value); - if(value) textArea.requestFocus(); + if(value) { + textArea.requestFocus(); + } } } diff --git a/src/eva2/gui/MultiLineStringEditor.java b/src/eva2/gui/MultiLineStringEditor.java index a4d72b55..23299e7b 100644 --- a/src/eva2/gui/MultiLineStringEditor.java +++ b/src/eva2/gui/MultiLineStringEditor.java @@ -73,13 +73,17 @@ public class MultiLineStringEditor implements PropertyEditor { @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (listeners == null) listeners = new PropertyChangeSupport(this); + if (listeners == null) { + listeners = new PropertyChangeSupport(this); + } listeners.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { - if (listeners == null) listeners = new PropertyChangeSupport(this); + if (listeners == null) { + listeners = new PropertyChangeSupport(this); + } listeners.removePropertyChangeListener(l); } } diff --git a/src/eva2/gui/PropertyBoolSelector.java b/src/eva2/gui/PropertyBoolSelector.java index 6abf159b..08560aca 100644 --- a/src/eva2/gui/PropertyBoolSelector.java +++ b/src/eva2/gui/PropertyBoolSelector.java @@ -15,10 +15,12 @@ public class PropertyBoolSelector extends JCheckBox { public PropertyBoolSelector(PropertyEditor pe) { super(); m_Editor = pe; - if (m_Editor.getAsText().equals("True")) - setSelected(true); - else - setSelected(false); + if (m_Editor.getAsText().equals("True")) { + setSelected(true); + } + else { + setSelected(false); + } addItemListener(new ItemListener () { @Override diff --git a/src/eva2/gui/PropertyDoubleArray.java b/src/eva2/gui/PropertyDoubleArray.java index 3a5c2c62..8b4efcb5 100644 --- a/src/eva2/gui/PropertyDoubleArray.java +++ b/src/eva2/gui/PropertyDoubleArray.java @@ -29,15 +29,21 @@ public class PropertyDoubleArray implements java.io.Serializable { * @param d */ 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; + if (rows>0 && cols>0) { + this.m_DoubleArray = new double[rows][cols]; + } + else { + this.m_DoubleArray=null; + } this.m_numCols=cols; int index=0; for (int i=0; i=d.length) index=0; + if (index>=d.length) { + index=0; + } } } } @@ -63,8 +69,12 @@ public class PropertyDoubleArray implements java.io.Serializable { */ public void setDoubleArray(double[][] d) { this.m_DoubleArray = d; - if (d.length>0) m_numCols=d[0].length; - else m_numCols=1; + if (d.length>0) { + m_numCols=d[0].length; + } + else { + m_numCols=1; + } } /** @@ -109,8 +119,12 @@ public class PropertyDoubleArray implements java.io.Serializable { 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."); + if (k<0 || k>=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; + if (i==k) { + inc=1; + } for (int j=0; j= getNumRows()) k=getNumRows()-1; + if (k<0 || k>= getNumRows()) { + k=getNumRows()-1; + } double[][] newDD = new double[getNumRows()+1][getNumCols()]; for (int i = 0; i < getNumRows(); i++) { @@ -145,12 +165,14 @@ public class PropertyDoubleArray implements java.io.Serializable { newDD[i][j] = m_DoubleArray[i][j]; } } - if (k>=0) for (int j=0; j=0) { + for (int j=0; j prim = BeanInspector.getBoxedType(value.getClass()); - if (TRACE) System.out.println("B1 PropertySheetPanel.makeEditor(): checking " + prim); - if (prim!=null) editor = PropertyEditorManager.findEditor(prim); + if (TRACE) { + System.out.println("B1 PropertySheetPanel.makeEditor(): checking " + prim); + } + if (prim!=null) { + editor = PropertyEditorManager.findEditor(prim); + } if (editor ==null) { - if (TRACE) System.out.println((editor == null ) ? "No editor from PEM by boxed type " : ("Found " + editor.getClass())); + if (TRACE) { + System.out.println((editor == null ) ? "No editor from PEM by boxed type " : ("Found " + editor.getClass())); + } prim = BeanInspector.getUnboxedType(value.getClass()); - if (TRACE) System.out.println("B2 PropertySheetPanel.makeEditor(): checking " + prim); - if (prim!=null) editor = PropertyEditorManager.findEditor(prim); - if (TRACE) System.out.println((editor == null ) ? "No editor from PEM by unboxed type " : ("Found " + editor.getClass())); + if (TRACE) { + System.out.println("B2 PropertySheetPanel.makeEditor(): checking " + prim); + } + if (prim!=null) { + editor = PropertyEditorManager.findEditor(prim); + } + if (TRACE) { + System.out.println((editor == null ) ? "No editor from PEM by unboxed type " : ("Found " + editor.getClass())); + } } } if (editor == null) { - if (TRACE) System.out.println("C PropertySheetPanel.makeEditor(): checking " + type); + if (TRACE) { + System.out.println("C PropertySheetPanel.makeEditor(): checking " + type); + } editor = PropertyEditorManager.findEditor(type); - if (TRACE) System.out.println((editor == null ) ? "No editor from PEM by type" : ("Found " + editor.getClass())); + if (TRACE) { + System.out.println((editor == null ) ? "No editor from PEM by type" : ("Found " + editor.getClass())); + } } if ((editor == null) && useDefaultGOE ) { - if (type.isArray()) editor = new GenericArrayEditor(); - else if (type.isEnum()) editor = new EnumEditor(); - else editor = new GenericObjectEditor(); - if (TRACE) System.out.println("using GOE/GAE"); + if (type.isArray()) { + editor = new GenericArrayEditor(); + } + else if (type.isEnum()) { + editor = new EnumEditor(); + } + else { + editor = new GenericObjectEditor(); + } + if (TRACE) { + System.out.println("using GOE/GAE"); + } } } if (editor == null) { @@ -145,7 +189,9 @@ public class PropertyEditorProvider { // ((GenericObjectEditor) editor).getCustomEditor(); ((GenericObjectEditor) editor).setClassType(type); } - if (TRACE) System.out.println("+ using "+ editor.getClass().getName() + " for " + value.getClass().getName()); + if (TRACE) { + System.out.println("+ using "+ editor.getClass().getName() + " for " + value.getClass().getName()); + } return editor; } diff --git a/src/eva2/gui/PropertyFilePath.java b/src/eva2/gui/PropertyFilePath.java index ba3c5a1d..b1c06244 100644 --- a/src/eva2/gui/PropertyFilePath.java +++ b/src/eva2/gui/PropertyFilePath.java @@ -48,8 +48,12 @@ public class PropertyFilePath implements java.io.Serializable { */ public static PropertyFilePath getFilePathFromResource(String relPath) { String fName = ReflectPackage.getResourcePathFromCP(relPath); - if (fName == null) return null; - else return new PropertyFilePath(fName); + if (fName == null) { + return null; + } + else { + return new PropertyFilePath(fName); + } } @Override @@ -67,16 +71,26 @@ public class PropertyFilePath implements java.io.Serializable { String old = this.getCompleteFilePath(); try { - if (trace) System.out.println("Complete Filename: " +s); + if (trace) { + System.out.println("Complete Filename: " +s); + } filesep = System.getProperty("file.separator"); - if (trace) System.out.println("File.Separator: " +filesep); + if (trace) { + System.out.println("File.Separator: " +filesep); + } this.FileName = s.substring(s.lastIndexOf(filesep)+1); this.FileExtension = this.FileName.substring(this.FileName.lastIndexOf(".")); this.FilePath = s.substring(0, s.lastIndexOf(filesep)+1); - if (trace) System.out.println("FilePath: " +this.FilePath); - if (trace) System.out.println("Filename: " + this.FileName); - if (trace) System.out.println("Fileext.: " + this.FileExtension); + if (trace) { + System.out.println("FilePath: " +this.FilePath); + } + if (trace) { + System.out.println("Filename: " + this.FileName); + } + if (trace) { + System.out.println("Fileext.: " + this.FileExtension); + } } catch (Exception e) { this.setCompleteFilePath(old); } diff --git a/src/eva2/gui/PropertyOptimizationObjectives.java b/src/eva2/gui/PropertyOptimizationObjectives.java index 09759e0c..c95a8c78 100644 --- a/src/eva2/gui/PropertyOptimizationObjectives.java +++ b/src/eva2/gui/PropertyOptimizationObjectives.java @@ -58,7 +58,9 @@ public class PropertyOptimizationObjectives implements java.io.Serializable { * @param index The index of the target to be removed. */ public void removeTarget(int index) { - if ((index < 0) || (index >= this.m_SelectedObjectives.length)) return; + if ((index < 0) || (index >= this.m_SelectedObjectives.length)) { + return; + } InterfaceOptimizationObjective[] newList = new InterfaceOptimizationObjective[this.m_SelectedObjectives.length-1]; int j = 0; diff --git a/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java b/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java index b7158cab..779b3c9a 100644 --- a/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java +++ b/src/eva2/gui/PropertyOptimizationObjectivesWithParam.java @@ -59,7 +59,9 @@ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializ return; } - if (d.length == this.m_Weights.length) return; + if (d.length == this.m_Weights.length) { + return; + } if (d.length > this.m_Weights.length) { double[] newWeights = new double[d.length]; @@ -134,7 +136,9 @@ public class PropertyOptimizationObjectivesWithParam implements java.io.Serializ * @param index The index of the target to be removed. */ public void removeTarget(int index) { - if ((index < 0) || (index >= this.m_SelectedObjectives.length)) return; + 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]; diff --git a/src/eva2/gui/PropertyRemoteServers.java b/src/eva2/gui/PropertyRemoteServers.java index cd5a22fc..58c8d5be 100644 --- a/src/eva2/gui/PropertyRemoteServers.java +++ b/src/eva2/gui/PropertyRemoteServers.java @@ -73,7 +73,9 @@ public class PropertyRemoteServers implements java.io.Serializable { // first check for double instances for (int i = 0; i < this.m_AvailableNodes.length; i++) { if (this.m_AvailableNodes[i].m_ServerName.equalsIgnoreCase(name)) { - if (cpus > this.m_AvailableNodes[i].m_CPUs) this.m_AvailableNodes[i].m_CPUs = cpus; + if (cpus > this.m_AvailableNodes[i].m_CPUs) { + this.m_AvailableNodes[i].m_CPUs = cpus; + } return; } } @@ -165,8 +167,12 @@ public class PropertyRemoteServers implements java.io.Serializable { public boolean isServerOnline(String name) { try { String[] list = Naming.list("rmi://" + name + ":" + 1099); - if (list == null) return false; - else return true; + if (list == null) { + return false; + } + else { + return true; + } } catch (Exception et) { return false; } @@ -231,10 +237,12 @@ public class PropertyRemoteServers implements java.io.Serializable { } public ServerNode get(int i) { - if ((i >= 0) && (i < this.m_AvailableNodes.length)) + if ((i >= 0) && (i < this.m_AvailableNodes.length)) { return this.m_AvailableNodes[i]; - else + } + else { return null; + } } public String writeToText() { @@ -246,11 +254,15 @@ public class PropertyRemoteServers implements java.io.Serializable { } public void setNameFor(int i, String name) { - if ((i >= 0) && (i < this.m_AvailableNodes.length)) this.m_AvailableNodes[i].m_ServerName = name; + if ((i >= 0) && (i < this.m_AvailableNodes.length)) { + this.m_AvailableNodes[i].m_ServerName = name; + } } public void setCPUsFor(int i, int c) { - if ((i >= 0) && (i < this.m_AvailableNodes.length)) this.m_AvailableNodes[i].m_CPUs = c; + if ((i >= 0) && (i < this.m_AvailableNodes.length)) { + this.m_AvailableNodes[i].m_CPUs = c; + } } public void readFromText(String text) { diff --git a/src/eva2/gui/PropertySelectableList.java b/src/eva2/gui/PropertySelectableList.java index 47ab61f4..f92e88b3 100644 --- a/src/eva2/gui/PropertySelectableList.java +++ b/src/eva2/gui/PropertySelectableList.java @@ -48,7 +48,9 @@ public class PropertySelectableList implements java.io.Serializable { public void setObjects(T[] o, boolean[] selection) { this.m_Objects = o; this.m_Selection = selection; - if (o.length != selection.length) throw new RuntimeException("Error, mismatching length of arrays in " + this.getClass()); + if (o.length != selection.length) { + throw new RuntimeException("Error, mismatching length of arrays in " + this.getClass()); + } m_Support.firePropertyChange("PropertySelectableList", null, this); } @@ -63,7 +65,9 @@ public class PropertySelectableList implements java.io.Serializable { public T[] getSelectedObjects() { T[] selObjects = getObjects().clone(); for (int i=0; i implements java.io.Serializable { } public int size() { - if (m_Objects == null) return 0; - else return m_Objects.length; + if (m_Objects == null) { + return 0; + } + else { + return m_Objects.length; + } } public T get(int i) { @@ -138,12 +146,16 @@ public class PropertySelectableList implements java.io.Serializable { // } public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } } diff --git a/src/eva2/gui/StringSelectionEditor.java b/src/eva2/gui/StringSelectionEditor.java index b13553f6..70b535a6 100644 --- a/src/eva2/gui/StringSelectionEditor.java +++ b/src/eva2/gui/StringSelectionEditor.java @@ -48,7 +48,9 @@ public class StringSelectionEditor extends AbstractListSelectionEditor { strs = (StringSelection) o; // m_AreaObject.addPropertyChangeListener(this); return true; - } else return false; + } else { + return false; + } } @Override @@ -62,7 +64,9 @@ public class StringSelectionEditor extends AbstractListSelectionEditor { boolean first = true; for (int i=0; im_Frame.getWidth()) - gridX = m_Frame.getWidth(); - if (gridY>m_Frame.getHeight()) - gridY = m_Frame.getHeight(); + 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; @@ -114,9 +116,15 @@ public class TopoPlot extends Plot { pos[0] = border[0][0]+x*deltaX; pos[1] = border[1][0]+y*deltaY; tmp = (float)(problem.functionValue(pos)); - if (TRACEMETH) System.out.println(pos[0] + " " + pos[1] + " " + tmp); - if (tmp < min) min = tmp; - if (tmp > max) max = tmp; + if (TRACEMETH) { + System.out.println(pos[0] + " " + pos[1] + " " + tmp); + } + if (tmp < min) { + min = tmp; + } + if (tmp > max) { + max = tmp; + } if (withGradientsIfAvailable && (problem instanceof InterfaceFirstOrderDerivableProblem)) { double[] deriv = ((InterfaceFirstOrderDerivableProblem)problem).getFirstOrderGradients(problem.project2DPoint(pos)); for (int i=0; i<2;i++) { diff --git a/src/eva2/server/go/GOStandaloneVersion.java b/src/eva2/server/go/GOStandaloneVersion.java index fa9e7aba..8b3776fb 100644 --- a/src/eva2/server/go/GOStandaloneVersion.java +++ b/src/eva2/server/go/GOStandaloneVersion.java @@ -166,7 +166,9 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu } catch(java.lang.ClassNotFoundException e) { System.out.println("No Class found for " + tmp); } - if ((object != null) && (editor != null)) paraPanel.registerEditor(object, editor); + if ((object != null) && (editor != null)) { + paraPanel.registerEditor(object, editor); + } this.m_O1 = (paraPanel.makePanel()); // TODO this is defunct anyways... (MK, 2010-03) // EvAClient.setProperty("eva2.server.oa.go.Tools.InterfaceTest", "eva2.server.oa.go.Tools.Test1,eva2.server.oa.go.Tools.Test2"); @@ -367,7 +369,9 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu public Object doWork() { try { this.m_GO.saveInstance(); - if (this.show) this.m_StatusField.setText("Optimizing..."); + if (this.show) { + this.m_StatusField.setText("Optimizing..."); + } RNG.setRandomSeed(m_GO.getSeed()); // opening output file... @@ -403,10 +407,12 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu this.m_GO.getProblem().initProblem(); // in the loop as well, dynamic probs may need that (MK) this.m_TmpData = new ArrayList(); this.currentRun = j; - if (this.show) + if (this.show) { this.m_StatusField.setText("Optimizing Run " + (j+1) + " of " + this.m_MultiRuns + " Multi Runs..."); - if (Thread.interrupted()) + } + if (Thread.interrupted()) { throw new InterruptedException(); + } // write header to file this.writeToFile(" FitnessCalls\t Best\t Mean\t Worst \t" + BeanInspector.toString(this.m_GO.getProblem().getAdditionalDataHeader(), '\t', false, "")); if ((this.m_ContinueFlag) && (this.m_Backup != null)) { @@ -426,7 +432,9 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu //while (this.m_GO.getOptimizer().getPopulation().getFunctionCalls() < this.m_FunctionCalls) { while (!this.m_GO.getTerminator().isTerminated(this.m_GO.getOptimizer().getPopulation())) { //System.out.println("Simulated Function calls "+ this.m_Optimizer.getPopulation().getFunctionCalls()); - if (Thread.interrupted()) throw new InterruptedException(); + if (Thread.interrupted()) { + throw new InterruptedException(); + } m_GO.getOptimizer().optimize(); } System.gc(); @@ -434,13 +442,19 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu //this.writeToFile(this.m_GO.getProblem().getStringRepresentationForProblem(this.m_GO.getOptimizer())); tmpMultiRun.add(this.m_TmpData); } - if (this.show) this.m_Plot.setInfoString(this.currentExperiment, this.m_ExperimentName, 0.5f); - if (this.show) this.draw(); + if (this.show) { + this.m_Plot.setInfoString(this.currentExperiment, this.m_ExperimentName, 0.5f); + } + if (this.show) { + this.draw(); + } this.m_ExperimentName = this.m_GO.getOptimizer().getName()+"-"+this.m_PerformedRuns.size(); } catch (InterruptedException e) { updateStatus(0); - if (this.show) this.m_StatusField.setText("Interrupted..."); + if (this.show) { + this.m_StatusField.setText("Interrupted..."); + } return "Interrupted"; } if (this.m_OutputFile != null) { @@ -450,11 +464,14 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu System.out.println("Failed to close output file!"); } } - if (this.show) for (int i = 0; i < this.m_MultiRuns; i++) { - this.m_Plot.clearGraph(1000 +i); - } + if (this.show) { + for (int i = 0; i < this.m_MultiRuns; i++) { + this.m_Plot.clearGraph(1000 +i); +} } updateStatus(0); - if (this.show) this.m_StatusField.setText("Finished..."); + if (this.show) { + this.m_StatusField.setText("Finished..."); + } return "All Done"; } @@ -506,8 +523,12 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu // if (this.m_GO.getOptimizer().getName().equalsIgnoreCase("CBN-EA")) tmpColor = Color.black; for (int j = 0; j < data.length; j++) { - if (this.m_ContinueFlag) this.m_Plot.setConnectedPoint(data[j][0]+this.m_RecentFC, data[j][1], this.currentExperiment); - else this.m_Plot.setConnectedPoint(data[j][0], data[j][1], this.currentExperiment); + if (this.m_ContinueFlag) { + this.m_Plot.setConnectedPoint(data[j][0]+this.m_RecentFC, data[j][1], this.currentExperiment); + } + else { + this.m_Plot.setConnectedPoint(data[j][0], data[j][1], this.currentExperiment); + } } this.currentExperiment++; } @@ -593,8 +614,12 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu // instead of adding simply the best fitness value i'll ask the problem what to show tmpData[1] = this.m_GO.getProblem().getDoublePlotValue(population); if (this.m_Plot != null) { - if (this.m_ContinueFlag) this.m_Plot.setConnectedPoint(tmpData[0].doubleValue()+this.m_RecentFC, tmpData[1].doubleValue(), 1000+this.currentRun); - else this.m_Plot.setConnectedPoint(tmpData[0].doubleValue(), tmpData[1].doubleValue(), 1000+this.currentRun); + if (this.m_ContinueFlag) { + this.m_Plot.setConnectedPoint(tmpData[0].doubleValue()+this.m_RecentFC, tmpData[1].doubleValue(), 1000+this.currentRun); + } + else { + this.m_Plot.setConnectedPoint(tmpData[0].doubleValue(), tmpData[1].doubleValue(), 1000+this.currentRun); + } } this.m_TmpData.add(tmpData); } @@ -605,7 +630,9 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu */ private void writeToFile(String line) { String write = line + "\n"; - if (this.m_OutputFile == null) return; + if (this.m_OutputFile == null) { + return; + } try { this.m_OutputFile.write(write, 0, write.length()); this.m_OutputFile.flush(); diff --git a/src/eva2/server/go/MOCCOStandalone.java b/src/eva2/server/go/MOCCOStandalone.java index 72c60802..47496fbc 100644 --- a/src/eva2/server/go/MOCCOStandalone.java +++ b/src/eva2/server/go/MOCCOStandalone.java @@ -212,15 +212,27 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati private void checkForObjectives(String 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 System.out.println("single-objective."); + if (this.m_State.m_OriginalProblem.isMultiObjective()) { + System.out.println("multi-objective."); + } + 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 System.out.println("single-objective."); + if (this.m_State.m_CurrentProblem.isMultiObjective()) { + System.out.println("multi-objective."); + } + 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 System.out.println("single-objective."); + if (this.m_State.m_BackupProblem.isMultiObjective()) { + System.out.println("multi-objective."); + } + else { + System.out.println("single-objective."); + } } else { System.out.println("No Backup Problem"); } @@ -235,7 +247,9 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati s = "Objectives: {"; for (int i = 0; i < obj.length; i++) { s += obj[i].getIdentName(); - if (i < (obj.length-1)) s += "; "; + if (i < (obj.length-1)) { + s += "; "; + } } s += "}"; System.out.println(""+s); @@ -244,7 +258,9 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati s = "Weights : {"; for (int i = 0; i < prop.getNumRows(); i++) { s += prop.getValue(i,0); - if (i < (prop.getNumRows()-1)) s += "; "; + if (i < (prop.getNumRows()-1)) { + s += "; "; + } } s += "}"; System.out.println(""+s); @@ -328,10 +344,12 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati throw new Exception("Object not of type MOCCOState"); } 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()); + 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()); + } } return null; } @@ -346,10 +364,12 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati oo.writeObject(this.m_State); oo.close(); } 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()); + 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()); + } } } @@ -365,10 +385,14 @@ 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()); + if (this.m_Debug) { + 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); - if (this.m_State.m_Optimizer.getPopulation().size() == 0) this.m_State.m_Optimizer.init(); + if (this.m_State.m_Optimizer.getPopulation().size() == 0) { + this.m_State.m_Optimizer.init(); + } this.m_State.m_Optimizer.addPopulationChangedEventListener(this); worker = new SwingWorker() { @Override @@ -394,7 +418,9 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati m_State.addPopulation2History(pop[i]); } } - if (m_View != null) m_View.problemChanged(true); + if (m_View != null) { + m_View.problemChanged(true); + } m_StillWorking = false; } }; @@ -427,9 +453,13 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati */ Object doWork() { try { - if (Thread.interrupted()) throw new InterruptedException(); + if (Thread.interrupted()) { + throw new InterruptedException(); + } while (!this.m_State.m_Terminator.isTerminated(this.m_State.m_Optimizer.getPopulation())) { - if (Thread.interrupted()) throw new InterruptedException(); + if (Thread.interrupted()) { + throw new InterruptedException(); + } this.m_State.m_Optimizer.optimize(); } System.gc(); diff --git a/src/eva2/server/go/individuals/AbstractEAIndividualComparator.java b/src/eva2/server/go/individuals/AbstractEAIndividualComparator.java index c7508b87..2628bf45 100644 --- a/src/eva2/server/go/individuals/AbstractEAIndividualComparator.java +++ b/src/eva2/server/go/individuals/AbstractEAIndividualComparator.java @@ -76,7 +76,9 @@ public class AbstractEAIndividualComparator implements Comparator, Seria 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; + if ((fitCriterion == o.fitCriterion) && (preferFeasible == o.preferFeasible)) { + return true; + } } } return false; @@ -127,32 +129,48 @@ public class AbstractEAIndividualComparator implements Comparator, Seria if (preferFeasible) { // check constraint violation first? int constrViolComp = ((AbstractEAIndividual) o1).compareConstraintViolation((AbstractEAIndividual) o2); - if (constrViolComp>0) return -1; - else if (constrViolComp < 0) return 1; + 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 ((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; + 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; + 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 + if (o1domO2 ^ o2domO1) { + return (o1domO2 ? -1 : 1); + } // they are comparable + else { + return 0; + } // they are not comparable } public String getIndyDataKey() { diff --git a/src/eva2/server/go/individuals/ESIndividualBinaryData.java b/src/eva2/server/go/individuals/ESIndividualBinaryData.java index abdc5733..2f8f538d 100644 --- a/src/eva2/server/go/individuals/ESIndividualBinaryData.java +++ b/src/eva2/server/go/individuals/ESIndividualBinaryData.java @@ -36,8 +36,9 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte } public ESIndividualBinaryData(ESIndividualBinaryData individual) { - if (individual.m_Phenotype != null) + if (individual.m_Phenotype != null) { 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]; for (int i = 0; i < this.m_Genotype.length; i++) { @@ -77,12 +78,22 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof ESIndividualBinaryData) { ESIndividualBinaryData indy = (ESIndividualBinaryData) 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_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if ((this.m_Range == null) || (indy.m_Range == null)) { + 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; + 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 { @@ -166,11 +177,19 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte this.SetBinaryPhenotype(binaryData); 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); + 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); + } } else { - if (binaryData.get(i)) this.m_Genotype[i] = 0.9; - else this.m_Genotype[i] = 0.1; + if (binaryData.get(i)) { + this.m_Genotype[i] = 0.9; + } + else { + this.m_Genotype[i] = 0.1; + } } } } @@ -240,8 +259,12 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte public void SetDGenotype(double[] b) { this.m_Genotype = b; 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[1][0]; - if (this.m_Genotype[i] > this.m_Range[i][1]) this.m_Genotype[i] = this.m_Range[1][1]; + if (this.m_Genotype[i] < this.m_Range[i][0]) { + this.m_Genotype[i] = this.m_Range[1][0]; + } + if (this.m_Genotype[i] > this.m_Range[i][1]) { + this.m_Genotype[i] = this.m_Range[1][1]; + } } } @@ -271,8 +294,12 @@ public class ESIndividualBinaryData extends AbstractEAIndividual implements Inte @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 ESIndividualDoubleData.defaultInit(m_Genotype, m_Range); + 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 diff --git a/src/eva2/server/go/individuals/ESIndividualDoubleData.java b/src/eva2/server/go/individuals/ESIndividualDoubleData.java index 831bcd76..89766316 100644 --- a/src/eva2/server/go/individuals/ESIndividualDoubleData.java +++ b/src/eva2/server/go/individuals/ESIndividualDoubleData.java @@ -79,14 +79,28 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof ESIndividualDoubleData) { ESIndividualDoubleData indy = (ESIndividualDoubleData) 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_Genotype.length != indy.m_Genotype.length) return false; - if (this.m_Range.length != indy.m_Range.length) return false; + 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_Genotype.length != indy.m_Genotype.length) { + return false; + } + if (this.m_Range.length != indy.m_Range.length) { + return false; + } for (int i = 0; i < this.m_Genotype.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; + 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 { @@ -172,7 +186,9 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte 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) return m_Phenotype; + if (this.m_Phenotype!=null) { + return m_Phenotype; + } else { this.m_Phenotype = new double[this.m_Genotype.length]; System.arraycopy(this.m_Genotype, 0, this.m_Phenotype, 0, this.m_Genotype.length); @@ -187,8 +203,12 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte */ @Override public double[] getDoubleDataWithoutUpdate() { - if (m_Phenotype==null) return getDoubleData(); - else return this.m_Phenotype; + if (m_Phenotype==null) { + return getDoubleData(); + } + else { + return this.m_Phenotype; + } } /** This method allows you to set the phenotype double data. To change the genotype, @@ -222,7 +242,9 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte public void init(InterfaceOptimizationProblem opt) { super.init(opt); // evil operators may not respect the range, so at least give some hint - if (!Mathematics.isInRange(m_Genotype, m_Range)) EVAERROR.errorMsgOnce("Warning: Individual out of range after initialization (and potential initial crossover/mutation)!"); + if (!Mathematics.isInRange(m_Genotype, m_Range)) { + EVAERROR.errorMsgOnce("Warning: Individual out of range after initialization (and potential initial crossover/mutation)!"); + } } /** This method will init the individual with a given value for the @@ -234,7 +256,9 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof double[]) { double[] bs = (double[]) obj; - if (bs.length != this.m_Genotype.length) System.out.println("Init value and requested length doesn't match!"); + if (bs.length != this.m_Genotype.length) { + System.out.println("Init value and requested length doesn't match!"); + } this.SetDoubleGenotype(bs); } else { this.defaultInit(opt); @@ -290,8 +314,12 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte this.m_Genotype = b; 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]; - if (this.m_Genotype[i] > this.m_Range[i][1]) this.m_Genotype[i] = this.m_Range[i][1]; + if (this.m_Genotype[i] < this.m_Range[i][0]) { + this.m_Genotype[i] = this.m_Range[i][0]; + } + if (this.m_Genotype[i] > this.m_Range[i][1]) { + this.m_Genotype[i] = this.m_Range[i][1]; + } } } @@ -322,14 +350,22 @@ public class ESIndividualDoubleData extends AbstractEAIndividual implements Inte 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); - if (genotype[mutationIndex] < range[mutationIndex][0]) genotype[mutationIndex] = range[mutationIndex][0]; - if (genotype[mutationIndex] > range[mutationIndex][1]) genotype[mutationIndex] = range[mutationIndex][1]; + if (genotype[mutationIndex] < range[mutationIndex][0]) { + genotype[mutationIndex] = range[mutationIndex][0]; + } + if (genotype[mutationIndex] > range[mutationIndex][1]) { + 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 ESIndividualDoubleData.defaultInit(m_Genotype, m_Range); + 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 } diff --git a/src/eva2/server/go/individuals/ESIndividualIntegerData.java b/src/eva2/server/go/individuals/ESIndividualIntegerData.java index ca5ad9cc..298ee302 100644 --- a/src/eva2/server/go/individuals/ESIndividualIntegerData.java +++ b/src/eva2/server/go/individuals/ESIndividualIntegerData.java @@ -74,12 +74,22 @@ public class ESIndividualIntegerData extends AbstractEAIndividual implements Int public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof ESIndividualIntegerData) { ESIndividualIntegerData indy = (ESIndividualIntegerData) 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_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if ((this.m_Range == null) || (indy.m_Range == null)) { + 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; + 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 { @@ -156,8 +166,12 @@ public class ESIndividualIntegerData extends AbstractEAIndividual implements Int this.m_Phenotype = new int[this.m_Genotype.length]; for (int i = 0; i < this.m_Phenotype.length; i++) { this.m_Phenotype[i] = (int) this.m_Genotype[i]; - if (this.m_Phenotype[i] < this.m_Range[i][0]) this.m_Phenotype[i] = this.m_Range[i][0]; - if (this.m_Phenotype[i] > this.m_Range[i][1]) this.m_Phenotype[i] = this.m_Range[i][1]; + if (this.m_Phenotype[i] < this.m_Range[i][0]) { + this.m_Phenotype[i] = this.m_Range[i][0]; + } + if (this.m_Phenotype[i] > this.m_Range[i][1]) { + this.m_Phenotype[i] = this.m_Range[i][1]; + } } return this.m_Phenotype; } @@ -204,7 +218,9 @@ public class ESIndividualIntegerData extends AbstractEAIndividual implements Int 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!"); + if (bs.length != this.m_Genotype.length) { + System.out.println("Init value and requested length doesn't match!"); + } this.SetIntGenotype(bs); } else { this.defaultInit(opt); @@ -257,8 +273,12 @@ public class ESIndividualIntegerData extends AbstractEAIndividual implements Int public void SetDGenotype(double[] b) { this.m_Genotype = b; 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]; - if (this.m_Genotype[i] > this.m_Range[i][1]) this.m_Genotype[i] = this.m_Range[i][1]; + if (this.m_Genotype[i] < this.m_Range[i][0]) { + this.m_Genotype[i] = this.m_Range[i][0]; + } + if (this.m_Genotype[i] > this.m_Range[i][1]) { + this.m_Genotype[i] = this.m_Range[i][1]; + } } } @@ -268,8 +288,12 @@ public class ESIndividualIntegerData extends AbstractEAIndividual implements Int public void defaultMutate() { int mutationIndex = RNG.randomInt(0, this.m_Genotype.length-1); this.m_Genotype[mutationIndex] += ((this.m_Range[mutationIndex][1] - this.m_Range[mutationIndex][0])/2)*RNG.gaussianDouble(0.05f); - if (this.m_Genotype[mutationIndex] < this.m_Range[mutationIndex][0]) this.m_Genotype[mutationIndex] = this.m_Range[mutationIndex][0]; - if (this.m_Genotype[mutationIndex] > this.m_Range[mutationIndex][1]) this.m_Genotype[mutationIndex] = this.m_Range[mutationIndex][1]; + if (this.m_Genotype[mutationIndex] < this.m_Range[mutationIndex][0]) { + this.m_Genotype[mutationIndex] = this.m_Range[mutationIndex][0]; + } + if (this.m_Genotype[mutationIndex] > this.m_Range[mutationIndex][1]) { + this.m_Genotype[mutationIndex] = this.m_Range[mutationIndex][1]; + } } /** This method will return the range for all double attributes. @@ -288,7 +312,9 @@ public class ESIndividualIntegerData extends AbstractEAIndividual implements Int @Override public void defaultInit(InterfaceOptimizationProblem prob) { int[][] range = m_Range; - if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange)prob).getInitRange()!=null)) range = (int[][])((InterfaceHasInitRange)prob).getInitRange(); + if ((prob != null) && (prob instanceof InterfaceHasInitRange) && (((InterfaceHasInitRange)prob).getInitRange()!=null)) { + range = (int[][])((InterfaceHasInitRange)prob).getInitRange(); + } for (int i = 0; i < this.m_Genotype.length; i++) { this.m_Genotype[i] = RNG.randomInt(range[i][0], range[i][1]); } diff --git a/src/eva2/server/go/individuals/ESIndividualPermutationData.java b/src/eva2/server/go/individuals/ESIndividualPermutationData.java index b45909a8..1816b95b 100644 --- a/src/eva2/server/go/individuals/ESIndividualPermutationData.java +++ b/src/eva2/server/go/individuals/ESIndividualPermutationData.java @@ -92,13 +92,25 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements 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; + 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; + 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 { @@ -163,8 +175,12 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements 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]; + 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; } @@ -196,7 +212,9 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements } 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]++; + if (this.m_Genotype[p][i] > this.m_Genotype[p][j]) { + this.m_Phenotype[p][i]++; + } } } } @@ -233,7 +251,9 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements 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!"); + 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); @@ -318,8 +338,12 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements 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]; + 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]; + } } } @@ -338,7 +362,9 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements @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(); + 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]); diff --git a/src/eva2/server/go/individuals/GAESIndividualBinaryDoubleData.java b/src/eva2/server/go/individuals/GAESIndividualBinaryDoubleData.java index c1d2aa4a..f7149982 100644 --- a/src/eva2/server/go/individuals/GAESIndividualBinaryDoubleData.java +++ b/src/eva2/server/go/individuals/GAESIndividualBinaryDoubleData.java @@ -60,8 +60,12 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GAESIndividualBinaryDoubleData) { 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)) return false; + if (!((AbstractEAIndividual)this.m_Numbers).equalGenotypes((AbstractEAIndividual)indy.m_Numbers)) { + return false; + } + if (!((AbstractEAIndividual)this.m_BitSet).equalGenotypes((AbstractEAIndividual)indy.m_BitSet)) { + return false; + } return true; } else { return false; @@ -109,8 +113,12 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme */ @Override public void mutate() { - if (RNG.flipCoin(this.m_MutationProbability))((AbstractEAIndividual)this.m_Numbers).mutate(); - if (RNG.flipCoin(this.m_MutationProbability))((AbstractEAIndividual)this.m_BitSet).mutate(); + if (RNG.flipCoin(this.m_MutationProbability)) { + ((AbstractEAIndividual)this.m_Numbers).mutate(); + } + if (RNG.flipCoin(this.m_MutationProbability)) { + ((AbstractEAIndividual)this.m_BitSet).mutate(); + } } @Override diff --git a/src/eva2/server/go/individuals/GAIndividualBinaryData.java b/src/eva2/server/go/individuals/GAIndividualBinaryData.java index 4120d857..7c263015 100644 --- a/src/eva2/server/go/individuals/GAIndividualBinaryData.java +++ b/src/eva2/server/go/individuals/GAIndividualBinaryData.java @@ -37,11 +37,13 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte } public GAIndividualBinaryData(GAIndividualBinaryData individual) { - if (individual.m_Phenotype != null) + if (individual.m_Phenotype != null) { this.m_Phenotype = (BitSet) individual.m_Phenotype.clone(); + } this.m_GenotypeLength = individual.m_GenotypeLength; - if (individual.m_Genotype != null) + if (individual.m_Genotype != null) { this.m_Genotype = (BitSet)individual.m_Genotype.clone(); + } // cloning the members of AbstractEAIndividual this.m_Age = individual.m_Age; @@ -73,9 +75,15 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GAIndividualBinaryData) { GAIndividualBinaryData indy = (GAIndividualBinaryData) individual; - if (this.m_GenotypeLength != indy.m_GenotypeLength) return false; - if ((this.m_Genotype == null) || (indy.m_Genotype == null)) return false; - if (!this.m_Genotype.equals(indy.m_Genotype)) return false; + if (this.m_GenotypeLength != indy.m_GenotypeLength) { + return false; + } + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if (!this.m_Genotype.equals(indy.m_Genotype)) { + return false; + } return true; } else { return false; @@ -89,7 +97,9 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte public double defaultEvaulateAsMiniBits() { double result = 0; for (int i = 0; i < this.m_GenotypeLength; i++) { - if (this.m_Genotype.get(i)) result++; + if (this.m_Genotype.get(i)) { + result++; + } } return result; } @@ -146,9 +156,15 @@ 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 (this.m_Genotype.get(i)) result += "1"; - else result += "0"; + if (i%8==0) { + result+="|"; + } + if (this.m_Genotype.get(i)) { + result += "1"; + } + else { + result += "0"; + } } result += "}"; result += "\n Mutation ("+this.m_MutationProbability+"):" + this.m_MutationOperator.getStringRepresentation(); @@ -187,8 +203,12 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte @Override public void defaultInit(InterfaceOptimizationProblem prob) { for (int i = 0; i < this.m_GenotypeLength; i++) { - if (RNG.flipCoin(0.5)) this.m_Genotype.set(i); - else this.m_Genotype.clear(i); + if (RNG.flipCoin(0.5)) { + this.m_Genotype.set(i); + } + else { + this.m_Genotype.clear(i); + } } } @@ -198,8 +218,12 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte public void defaultMutate() { int mutationIndex = RNG.randomInt(0, this.m_GenotypeLength); //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 (this.m_Genotype.get(mutationIndex)) { + this.m_Genotype.clear(mutationIndex); + } + else { + this.m_Genotype.set(mutationIndex); + } //if (mutationIndex > 28) System.out.println(this.getSolutionRepresentationFor()); } diff --git a/src/eva2/server/go/individuals/GAIndividualDoubleData.java b/src/eva2/server/go/individuals/GAIndividualDoubleData.java index b6abf815..1f7e74df 100644 --- a/src/eva2/server/go/individuals/GAIndividualDoubleData.java +++ b/src/eva2/server/go/individuals/GAIndividualDoubleData.java @@ -86,12 +86,22 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte if (individual instanceof GAIndividualDoubleData) { GAIndividualDoubleData indy = (GAIndividualDoubleData) individual; //@todo Eigendlich k�nnte ich noch das Koding vergleichen - if (this.m_GenotypeLength != indy.m_GenotypeLength) return false; - if ((this.m_Genotype == null) || (indy.m_Genotype == null)) return false; - if (!this.m_Genotype.equals(indy.m_Genotype)) return false; + if (this.m_GenotypeLength != indy.m_GenotypeLength) { + return false; + } + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if (!this.m_Genotype.equals(indy.m_Genotype)) { + return false; + } for (int i = 0; i < this.m_Range.length; i++) { - 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; + 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 { @@ -227,7 +237,9 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof double[]) { double[] bs = (double[]) obj; - if (bs.length != this.m_Range.length) System.out.println("Init value and requested length doesn't match!"); + if (bs.length != this.m_Range.length) { + System.out.println("Init value and requested length doesn't match!"); + } this.SetDoubleGenotype(bs); } else { this.defaultInit(opt); @@ -262,8 +274,12 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte result += "]\n"; result += "{"; for (int i = 0; i < this.m_GenotypeLength; i++) { - if (this.m_Genotype.get(i)) result += "1"; - else result += "0"; + if (this.m_Genotype.get(i)) { + result += "1"; + } + else { + result += "0"; + } } result += "}"; return result; @@ -303,8 +319,12 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte @Override public void defaultInit(InterfaceOptimizationProblem prob) { for (int i = 0; i < this.m_GenotypeLength; i++) { - if (RNG.flipCoin(0.5)) this.m_Genotype.set(i); - else this.m_Genotype.clear(i); + if (RNG.flipCoin(0.5)) { + this.m_Genotype.set(i); + } + else { + this.m_Genotype.clear(i); + } } } @@ -313,8 +333,12 @@ public class GAIndividualDoubleData extends AbstractEAIndividual implements Inte @Override public void defaultMutate() { int mutationIndex = RNG.randomInt(0, this.m_GenotypeLength); - if (this.m_Genotype.get(mutationIndex)) this.m_Genotype.clear(mutationIndex); - else this.m_Genotype.set(mutationIndex); + if (this.m_Genotype.get(mutationIndex)) { + this.m_Genotype.clear(mutationIndex); + } + else { + this.m_Genotype.set(mutationIndex); + } } /********************************************************************************************************************** * These are for GUI diff --git a/src/eva2/server/go/individuals/GAIndividualIntegerData.java b/src/eva2/server/go/individuals/GAIndividualIntegerData.java index 39e7eb57..e1ad76db 100644 --- a/src/eva2/server/go/individuals/GAIndividualIntegerData.java +++ b/src/eva2/server/go/individuals/GAIndividualIntegerData.java @@ -86,12 +86,22 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int if (individual instanceof GAIndividualIntegerData) { GAIndividualIntegerData indy = (GAIndividualIntegerData) individual; //@todo Eigendlich k�nnte ich noch das Koding vergleichen - if ((this.m_Genotype == null) || (indy.m_Genotype == null)) return false; - if (!this.m_Genotype.equals(indy.m_Genotype)) return false; - if (this.m_Range.length != indy.m_Range.length) return false; + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if (!this.m_Genotype.equals(indy.m_Genotype)) { + 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_Range[i][0] != indy.m_Range[i][0]) return false; - if (this.m_Range[i][1] != indy.m_Range[i][1]) 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 { @@ -253,7 +263,9 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof int[]) { int[] bs = (int[]) obj; - if (bs.length != this.m_Range.length) System.out.println("Init value and requested length doesn't match!"); + if (bs.length != this.m_Range.length) { + System.out.println("Init value and requested length doesn't match!"); + } this.SetIntGenotype(bs); } else { this.defaultInit(opt); @@ -302,8 +314,12 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int overallLength += this.m_CodingLenghts[i]; } for (int i = 0; i < overallLength; i++) { - if (this.m_Genotype.get(i)) result += "1"; - else result += "0"; + if (this.m_Genotype.get(i)) { + result += "1"; + } + else { + result += "0"; + } } result += "}"; return result; @@ -351,8 +367,12 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int overallLength += this.m_CodingLenghts[i]; } for (int i = 0; i < overallLength; i++) { - if (RNG.flipCoin(0.5)) this.m_Genotype.set(i); - else this.m_Genotype.clear(i); + if (RNG.flipCoin(0.5)) { + this.m_Genotype.set(i); + } + else { + this.m_Genotype.clear(i); + } } } @@ -365,8 +385,12 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int overallLength += this.m_CodingLenghts[i]; } int mutationIndex = RNG.randomInt(0, overallLength); - if (this.m_Genotype.get(mutationIndex)) this.m_Genotype.clear(mutationIndex); - else this.m_Genotype.set(mutationIndex); + if (this.m_Genotype.get(mutationIndex)) { + this.m_Genotype.clear(mutationIndex); + } + else { + this.m_Genotype.set(mutationIndex); + } } public static void main(String[] args) { diff --git a/src/eva2/server/go/individuals/GAPIndividualProgramData.java b/src/eva2/server/go/individuals/GAPIndividualProgramData.java index 97c9a983..796c9172 100644 --- a/src/eva2/server/go/individuals/GAPIndividualProgramData.java +++ b/src/eva2/server/go/individuals/GAPIndividualProgramData.java @@ -60,8 +60,12 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GAPIndividualProgramData) { GAPIndividualProgramData indy = (GAPIndividualProgramData)individual; - if (!((AbstractEAIndividual)this.m_Numbers).equalGenotypes((AbstractEAIndividual)indy.m_Numbers)) return false; - if (!((AbstractEAIndividual)this.m_Program).equalGenotypes((AbstractEAIndividual)indy.m_Program)) return false; + if (!((AbstractEAIndividual)this.m_Numbers).equalGenotypes((AbstractEAIndividual)indy.m_Numbers)) { + return false; + } + if (!((AbstractEAIndividual)this.m_Program).equalGenotypes((AbstractEAIndividual)indy.m_Program)) { + return false; + } return true; } else { return false; @@ -109,8 +113,12 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In */ @Override public void mutate() { - if (RNG.flipCoin(this.m_MutationProbability))((AbstractEAIndividual)this.m_Numbers).mutate(); - if (RNG.flipCoin(this.m_MutationProbability))((AbstractEAIndividual)this.m_Program).mutate(); + if (RNG.flipCoin(this.m_MutationProbability)) { + ((AbstractEAIndividual)this.m_Numbers).mutate(); + } + if (RNG.flipCoin(this.m_MutationProbability)) { + ((AbstractEAIndividual)this.m_Program).mutate(); + } } @Override diff --git a/src/eva2/server/go/individuals/GEIndividualProgramData.java b/src/eva2/server/go/individuals/GEIndividualProgramData.java index b051c11d..54a1b8eb 100644 --- a/src/eva2/server/go/individuals/GEIndividualProgramData.java +++ b/src/eva2/server/go/individuals/GEIndividualProgramData.java @@ -58,8 +58,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int this.m_MaxNumberOfNodes = individual.m_MaxNumberOfNodes; this.m_NumberOfBitPerInt= individual.m_NumberOfBitPerInt; this.m_CurrentIndex = individual.m_CurrentIndex; - if (individual.m_Genotype != null) + if (individual.m_Genotype != null) { this.m_Genotype = (BitSet)individual.m_Genotype.clone(); + } if (individual.m_Area != null) { this.m_Area = new GPArea[individual.m_Area.length]; for (int i = 0; i < this.m_Area.length; i++) { @@ -120,11 +121,21 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GEIndividualProgramData) { GEIndividualProgramData indy = (GEIndividualProgramData) individual; - if (this.m_GenotypeLengthPerProgram != indy.m_GenotypeLengthPerProgram) return false; - if (this.m_MaxNumberOfNodes != indy.m_MaxNumberOfNodes) return false; - if (this.m_NumberOfBitPerInt != indy.m_NumberOfBitPerInt) return false; - if ((this.m_Genotype == null) || (indy.m_Genotype == null)) return false; - if (!this.m_Genotype.equals(indy.m_Genotype)) return false; + if (this.m_GenotypeLengthPerProgram != indy.m_GenotypeLengthPerProgram) { + return false; + } + if (this.m_MaxNumberOfNodes != indy.m_MaxNumberOfNodes) { + return false; + } + if (this.m_NumberOfBitPerInt != indy.m_NumberOfBitPerInt) { + return false; + } + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if (!this.m_Genotype.equals(indy.m_Genotype)) { + return false; + } return true; } else { return false; @@ -148,7 +159,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int ArrayList area = this.m_Area[t].getReducedList(); for (int i = 0; i < area.size(); i++) { arity = ((AbstractGPNode) area.get(i)).getArity(); - if (arity > maxArity) maxArity = arity; + if (arity > maxArity) { + maxArity = arity; + } } // Now i get a sorted list @@ -182,7 +195,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int } } tmpExpr[i] = tmpRule; - if (tmpRule != null) numberOfRules++; + if (tmpRule != null) { + numberOfRules++; + } } // Now get rid of the null rules int[][] trueExpr = new int[numberOfRules][]; @@ -218,11 +233,17 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int // first the Non-Terminals result += "N \t := \t{"; for (int i = 0; i < this.m_Rules[t].length; i++) { - if (i == 0) result += "expr, "; + if (i == 0) { + result += "expr, "; + } else { - if (i == 1) result += "var, "; + if (i == 1) { + result += "var, "; + } else { - if (((AbstractGPNode[])this.m_Rules[t][i]).length > 0) result += "op"+(i-1)+", "; + if (((AbstractGPNode[])this.m_Rules[t][i]).length > 0) { + result += "op"+(i-1)+", "; + } } } } @@ -247,7 +268,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int 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) result += "\t \t \t \t \t \t"; + if ((j+1) < rulz.length) { + result += "\t \t \t \t \t \t"; + } } } else { // now the rules for the terminals @@ -285,9 +308,15 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int String result = ""; result += "{"; 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 result += "0"; + if (i % this.m_NumberOfBitPerInt == 0) { + result += " "; + } + if (this.m_Genotype.get(i)) { + result += "1"; + } + else { + result += "0"; + } } result += "}"; return result; @@ -300,9 +329,15 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int private String getRuleString(int[] rule) { String result =""; for (int k = 0; k < rule.length; k++) { - if (rule[k] == 0) result += " "; - if (rule[k] == 1) result += " "; - if (rule[k] > 1) result += " "; + if (rule[k] == 0) { + result += " "; + } + if (rule[k] == 1) { + result += " "; + } + if (rule[k] > 1) { + result += " "; + } } return result; } @@ -326,7 +361,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int this.m_Area[t] = oldArea[oldArea.length-1]; } this.m_Rules = new Object[length][]; - if (oldRulz == null) return; + 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]; @@ -382,10 +419,13 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int 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; } @@ -445,7 +485,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int // lets decode the stuff! if (this.m_Rules == null) { this.compileArea(); - if (this.m_Rules == null) return null; + if (this.m_Rules == null) { + return null; + } } this.m_CurrentIndex = 0; this.m_CurrentNumberOfNodes = 0; @@ -491,7 +533,9 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int @Override public void SetProgramGenotype(InterfaceProgram[] program) { this.SetProgramPhenotype(program); - if (program instanceof AbstractGPNode[]) System.err.println("Warning setProgram() for GEIndividualProgramData not implemented!"); + if (program instanceof AbstractGPNode[]) { + System.err.println("Warning setProgram() for GEIndividualProgramData not implemented!"); + } } /** This method allows you to set the function area @@ -546,8 +590,12 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int result += "GEIndividual coding program:\n"; result += "{"; for (int i = 0; i < this.m_GenotypeLengthPerProgram*this.m_Area.length; i++) { - if (this.m_Genotype.get(i)) result += "1"; - else result += "0"; + if (this.m_Genotype.get(i)) { + result += "1"; + } + else { + result += "0"; + } } result += "}\n"; InterfaceProgram[] data = this.getProgramData(); @@ -591,8 +639,12 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int @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); + if (RNG.flipCoin(0.5)) { + this.m_Genotype.set(i); + } + else { + this.m_Genotype.clear(i); + } } } @@ -602,8 +654,12 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int 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 (this.m_Genotype.get(mutationIndex)) { + this.m_Genotype.clear(mutationIndex); + } + else { + this.m_Genotype.set(mutationIndex); + } //if (mutationIndex > 28) System.out.println(this.getSolutionRepresentationFor()); } diff --git a/src/eva2/server/go/individuals/GIIndividualIntegerData.java b/src/eva2/server/go/individuals/GIIndividualIntegerData.java index 492413be..8cfb7d1d 100644 --- a/src/eva2/server/go/individuals/GIIndividualIntegerData.java +++ b/src/eva2/server/go/individuals/GIIndividualIntegerData.java @@ -85,12 +85,22 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GIIndividualIntegerData) { GIIndividualIntegerData indy = (GIIndividualIntegerData) individual; - if ((this.m_Genotype == null) || (indy.m_Genotype == null)) return false; - if (this.m_Genotype.length != indy.m_Genotype.length) return false; + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { + return false; + } + if (this.m_Genotype.length != indy.m_Genotype.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; + 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 { @@ -212,7 +222,9 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof int[]) { int[] bs = (int[]) obj; - if (bs.length != this.m_Range.length) System.out.println("Init value and requested length doesn't match!"); + if (bs.length != this.m_Range.length) { + System.out.println("Init value and requested length doesn't match!"); + } this.SetIntGenotype(bs); } else { this.defaultInit(opt); @@ -309,7 +321,9 @@ public class GIIndividualIntegerData extends AbstractEAIndividual implements Int } } else if (rng instanceof int[][]){ range = (int[][])rng; - } else System.err.println("Error, invalid initial range provided by " + prob + ", expecting int[][] or double[][], disregarding initialization range"); + } else { + System.err.println("Error, invalid initial range provided by " + prob + ", expecting int[][] or double[][], disregarding initialization range"); + } } for (int i = 0; i < this.m_Genotype.length; i++) { diff --git a/src/eva2/server/go/individuals/GIOBGAIndividualIntegerPermutationData.java b/src/eva2/server/go/individuals/GIOBGAIndividualIntegerPermutationData.java index cbdd4453..2a835308 100644 --- a/src/eva2/server/go/individuals/GIOBGAIndividualIntegerPermutationData.java +++ b/src/eva2/server/go/individuals/GIOBGAIndividualIntegerPermutationData.java @@ -58,8 +58,12 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual public boolean equalGenotypes(AbstractEAIndividual individual) { if (individual instanceof GIOBGAIndividualIntegerPermutationData) { GIOBGAIndividualIntegerPermutationData indy = (GIOBGAIndividualIntegerPermutationData)individual; - if (!((AbstractEAIndividual)this.m_Integer).equalGenotypes((AbstractEAIndividual)indy.m_Integer)) return false; - if (!((AbstractEAIndividual)this.m_Permutation).equalGenotypes((AbstractEAIndividual)indy.m_Permutation)) return false; + if (!((AbstractEAIndividual)this.m_Integer).equalGenotypes((AbstractEAIndividual)indy.m_Integer)) { + return false; + } + if (!((AbstractEAIndividual)this.m_Permutation).equalGenotypes((AbstractEAIndividual)indy.m_Permutation)) { + return false; + } return true; } else { return false; @@ -107,8 +111,12 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual */ @Override public void mutate() { - if (RNG.flipCoin(this.m_MutationProbability))((AbstractEAIndividual)this.m_Integer).mutate(); - if (RNG.flipCoin(this.m_MutationProbability))((AbstractEAIndividual)this.m_Permutation).mutate(); + if (RNG.flipCoin(this.m_MutationProbability)) { + ((AbstractEAIndividual)this.m_Integer).mutate(); + } + if (RNG.flipCoin(this.m_MutationProbability)) { + ((AbstractEAIndividual)this.m_Permutation).mutate(); + } } @Override diff --git a/src/eva2/server/go/individuals/GPIndividualProgramData.java b/src/eva2/server/go/individuals/GPIndividualProgramData.java index a421ad97..45d5824e 100644 --- a/src/eva2/server/go/individuals/GPIndividualProgramData.java +++ b/src/eva2/server/go/individuals/GPIndividualProgramData.java @@ -41,7 +41,9 @@ public class GPIndividualProgramData 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++) { - if (individual.m_Phenotype[i] != null) this.m_Phenotype[i] = (AbstractGPNode)individual.m_Phenotype[i].clone(); + if (individual.m_Phenotype[i] != null) { + this.m_Phenotype[i] = (AbstractGPNode)individual.m_Phenotype[i].clone(); + } } } if (individual.m_Genotype != null) { @@ -52,7 +54,9 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int 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(); + if (individual.m_Area[i] != null) { + this.m_Area[i] = (GPArea)individual.m_Area[i].clone(); + } } } this.m_InitFullGrowRatio = individual.m_InitFullGrowRatio; @@ -91,14 +95,17 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int if (individual instanceof GPIndividualProgramData) { GPIndividualProgramData indy = (GPIndividualProgramData) individual; //@todo Eigendlich k�nnte ich noch die Areas vergleichen - if (this.m_maxAllowedDepth != indy.m_maxAllowedDepth) + if (this.m_maxAllowedDepth != indy.m_maxAllowedDepth) { return false; - if ((this.m_Genotype == null) || (indy.m_Genotype == null)) + } + if ((this.m_Genotype == null) || (indy.m_Genotype == null)) { return false; + } 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]))) + if ((this.m_Genotype[i] == null) || (indy.m_Genotype[i] == null) || (!this.m_Genotype[i].equals(indy.m_Genotype[i]))) { return false; + } } } return true; @@ -156,8 +163,12 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int */ @Override public InterfaceProgram[] getProgramDataWithoutUpdate() { - if (this.m_Phenotype==null) return getProgramData(); - else return this.m_Phenotype; + if (this.m_Phenotype==null) { + return getProgramData(); + } + else { + return this.m_Phenotype; + } } /** This method allows you to set the program phenotype. @@ -243,7 +254,9 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int } result += "})\n Value: "; for (int i = 0; i < this.m_Genotype.length; i++) { - if (this.m_Genotype[i] != null) result += this.m_Genotype[i].getStringRepresentation(); + if (this.m_Genotype[i] != null) { + result += this.m_Genotype[i].getStringRepresentation(); + } result += "\nUsing " + this.m_Genotype[i].getNumberOfNodes() + " nodes."; } return result; @@ -321,10 +334,12 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int 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)) + 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); + } } } } @@ -365,8 +380,12 @@ public class GPIndividualProgramData extends AbstractEAIndividual implements Int * @param b The new init Full Grow Ratio of the GP Tree. */ public void setInitFullGrowRatio(double b) { - if (b < 0) b = 0; - if (b > 1) b = 1; + if (b < 0) { + b = 0; + } + if (b > 1) { + b = 1; + } this.m_InitFullGrowRatio = b; } public double getInitFullGrowRatio() { diff --git a/src/eva2/server/go/individuals/IndividualDistanceComparator.java b/src/eva2/server/go/individuals/IndividualDistanceComparator.java index 0b28355e..3cec24a5 100644 --- a/src/eva2/server/go/individuals/IndividualDistanceComparator.java +++ b/src/eva2/server/go/individuals/IndividualDistanceComparator.java @@ -33,9 +33,15 @@ public class IndividualDistanceComparator implements Comparator, Seriali double d1 = distMetric.distance((AbstractEAIndividual)o1, refIndy); double d2 = distMetric.distance((AbstractEAIndividual)o2, refIndy); - if (d1==d2) return 0; - if (closerMeansLess) return ((d1, 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; + 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, */ @Override public int hashCode() { - if (fitWeights==null) return super.hashCode(); + if (fitWeights==null) { + return super.hashCode(); + } int code=0; for (int i=0; i, double score1 = calcScore(f1); double score2 = calcScore(f2); - if (score1 < score2) return -1; - else if (score1 > score2) return 1; - else return 0; + if (score1 < score2) { + return -1; + } + else if (score1 > score2) { + return 1; + } + else { + return 0; + } } /** @@ -86,10 +100,16 @@ public class IndividualWeightedFitnessComparator implements Comparator, * @return */ private double calcScore(double[] f) { - if (f==null || fitWeights==null) throw new RuntimeException("Error, missing information in " + this.getClass()); + if (f==null || fitWeights==null) { + throw new RuntimeException("Error, missing information in " + this.getClass()); + } if (f.length!=fitWeights.length) { - if (f.length m_max) tmpV = m_max; - if (tmpV < m_min) tmpV = m_min; + if (tmpV > m_max) { + tmpV = m_max; + } + if (tmpV < m_min) { + tmpV = m_min; + } tmpBitSet = new BitSet(m_length); while (tmpV >= 1) { //System.out.println(tmpV); @@ -111,12 +115,20 @@ public class GAStandardCodingInteger implements InterfaceGAIntegerCoding, java.i //System.out.println("tmpV " + tmpOut + " Range("+m_min+";"+m_max+") "+m_length+" "+this.printBitSet(tmpBitSet,m_length)); // Das sieht bis hierher richtig toll aus, nur jetzt wirds scheisse m_Length war im Arsch for (int i = 0; i < m_length; i++) { - if (tmpBitSet.get(i)) refBitSet.set(m_start + m_length - 1 - i); - else refBitSet.clear(m_start + m_length - 1 - i); + if (tmpBitSet.get(i)) { + refBitSet.set(m_start + m_length - 1 - i); + } + 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 tmpBitSet.clear(m_start + m_length - 1 - i); + if (refBitSet.get(m_start + m_length - 1 - i)) { + tmpBitSet.set(m_length - 1 - i); + } + else { + tmpBitSet.clear(m_start + m_length - 1 - i); + } } //System.out.println("INT Value coded : " + value + " " + this.printBitSet(tmpBitSet, m_length)); } @@ -150,8 +162,12 @@ public class GAStandardCodingInteger implements InterfaceGAIntegerCoding, java.i String output = "{"; for (int i = 0; i < length; i++) { - if (b.get(i)) output += "1"; - else output += "0"; + if (b.get(i)) { + output += "1"; + } + else { + output += "0"; + } } output += "}\n"; return output; diff --git a/src/eva2/server/go/individuals/codings/gp/AbstractGPNode.java b/src/eva2/server/go/individuals/codings/gp/AbstractGPNode.java index fc105106..12e4f385 100644 --- a/src/eva2/server/go/individuals/codings/gp/AbstractGPNode.java +++ b/src/eva2/server/go/individuals/codings/gp/AbstractGPNode.java @@ -80,7 +80,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial sbuf.append("("); for (int i = 0; i < node.m_Nodes.length; i++) { sbuf.append(node.m_Nodes[i].getStringRepresentation()); - if (i1) System.err.println("String has ambiguous prefix: " + str + " -- " + BeanInspector.toString(matchSet)); + 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()); + if (TRACE) { + System.out.println("Found match: " + currentNode.getOpIdentifier() + "/" + currentNode.getArity()); + } int cutFront=currentNode.getOpIdentifier().length(); String restStr; if (currentNode.getArity()==0) { @@ -151,7 +157,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial e.printStackTrace(); } } - if (TRACE) System.out.println("read " + currentNode.getName() + ", rest: " + restStr); + if (TRACE) { + System.out.println("read " + currentNode.getName() + ", rest: " + restStr); + } return new Pair(currentNode, restStr); } } @@ -182,18 +190,28 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial private static Pair readDouble(String str, boolean expect) { String firstArg; int argLen = str.indexOf(','); - if (argLen<0) argLen = str.indexOf(')'); + if (argLen<0) { + argLen = str.indexOf(')'); + } else { int firstBrace = str.indexOf(')'); - if ((firstBrace >= 0) && (firstBrace= 0) && (firstBrace0) firstArg=str.substring(0,argLen); - else firstArg=str.trim(); + 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); + if (expect) { + System.err.println("String has unknown prefix: " + str); + } return null; } } @@ -203,8 +221,12 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial * @return string */ public static String makeStringRepresentation(AbstractGPNode[] nodes, String op) { - if (nodes.length==0) return op; - else if (nodes.length==1) return op+"(" + nodes[0].getStringRepresentation()+")"; + 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++) { @@ -229,9 +251,15 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial 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 (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(); @@ -244,7 +272,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial maxLen = longest.getOpIdentifier().length(); longestList.clear(); longestList.add(longest); - } else if (matching.get(i).getOpIdentifier().length()==maxLen) longestList.add(matching.get(i)); + } else if (matching.get(i).getOpIdentifier().length()==maxLen) { + longestList.add(matching.get(i)); + } } matching.clear(); matching.addAll(longestList); @@ -316,7 +346,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial 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; + if (Modifier.isAbstract(c.getModifiers()) || c.isInterface()) { + continue; + } AbstractGPNode node; try { node = (AbstractGPNode)c.newInstance(); @@ -412,7 +444,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial if (m_Nodes.length>0) { int k=RNG.randomInt(m_Nodes.length); return m_Nodes[k].getRandomLeaf(); - } else return this; + } else { + return this; + } } /** This method allows you to set the parent of the node @@ -433,8 +467,12 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial */ public void connect(AbstractGPNode parent) { this.m_Parent = parent; - if (parent != null) this.m_Depth = this.m_Parent.getDepth()+1; - else this.m_Depth = 0; + if (parent != null) { + this.m_Depth = this.m_Parent.getDepth()+1; + } + else { + this.m_Depth = 0; + } for (int i = 0; i < this.m_Nodes.length; i++) { this.m_Nodes[i].connect(this); } @@ -453,8 +491,12 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial 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(); - else this.m_Nodes[i] = (AbstractGPNode)area.getRandomNonTerminal().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(); + } this.m_Nodes[i].setDepth(this.m_Depth+1); this.m_Nodes[i].setParent(this); this.m_Nodes[i].initFull(area, depth); @@ -468,8 +510,12 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial 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(); - else this.m_Nodes[i] = (AbstractGPNode)area.getRandomNode().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(); + } this.m_Nodes[i].setDepth(this.m_Depth+1); this.m_Nodes[i].setParent(this); this.m_Nodes[i].initGrow(area, depth); @@ -494,7 +540,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial public int getMaxDepth() { int result = this.m_Depth; for (int i = 0; i < this.m_Nodes.length; i++) { - if (this.m_Nodes[i] != null) result = Math.max(result, this.m_Nodes[i].getMaxDepth()); + if (this.m_Nodes[i] != null) { + result = Math.max(result, this.m_Nodes[i].getMaxDepth()); + } } return result; } @@ -514,8 +562,12 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial * @return True if MaxDepth is violated */ public boolean isMaxDepthViolated(int maxDepth) { - if (maxDepth < this.getMaxDepth()) return true; - else return false; + if (maxDepth < this.getMaxDepth()) { + return true; + } + else { + return false; + } // if (depth > this.m_Depth) return false; // else { // boolean result = true; @@ -559,10 +611,16 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial public boolean equals(Object obj) { if (obj.getClass().equals(this.getClass())) { AbstractGPNode node = (AbstractGPNode)obj; - if (this.getArity()!=node.getArity()) return false; - if (this.m_Nodes.length != node.m_Nodes.length) return false; + if (this.getArity()!=node.getArity()) { + return false; + } + if (this.m_Nodes.length != node.m_Nodes.length) { + return false; + } for (int i = 0; i < this.m_Nodes.length; i++) { - if (!this.m_Nodes[i].equals(node.m_Nodes[i])) return false; + if (!this.m_Nodes[i].equals(node.m_Nodes[i])) { + return false; + } } return true; } else { @@ -593,7 +651,9 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial return false; } for (int i=0; i)g.m_BlackList.clone(); - if (g.m_ReducedList != null) + } + if (g.m_ReducedList != null) { this.m_ReducedList = (ArrayList)g.m_ReducedList.clone(); - if (g.m_CompleteList != null) + } + if (g.m_CompleteList != null) { this.m_CompleteList = (ArrayList)g.m_CompleteList.clone(); + } } @Override @@ -118,17 +121,27 @@ public class GPArea implements java.io.Serializable { public AbstractGPNode getRandomNodeWithArity(int targetarity) { ArrayList tmpArray = new ArrayList(); for (int i = 0; i < this.m_ReducedList.size(); i++) { - if (((AbstractGPNode)this.m_ReducedList.get(i)).getArity() == targetarity) tmpArray.add(this.m_ReducedList.get(i)); + 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)); } - if (tmpArray.size() == 0) return null; - else return (AbstractGPNode)tmpArray.get(RNG.randomInt(0, tmpArray.size()-1)); } /** 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)); + if (this.m_ReducedList.size() == 0) { + return null; + } + else { + return (AbstractGPNode)this.m_ReducedList.get(RNG.randomInt(0, this.m_ReducedList.size()-1)); + } } /** This method will return a non terminal @@ -136,10 +149,16 @@ public class GPArea implements java.io.Serializable { public AbstractGPNode getRandomNonTerminal() { ArrayList tmpArray = new ArrayList(); for (int i = 0; i < this.m_ReducedList.size(); i++) { - if (((AbstractGPNode)this.m_ReducedList.get(i)).getArity() > 0) tmpArray.add(this.m_ReducedList.get(i)); + 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)); } - if (tmpArray.size() == 0) return null; - else return (AbstractGPNode)tmpArray.get(RNG.randomInt(0, tmpArray.size()-1)); } public boolean isEmpty() { @@ -154,14 +173,18 @@ public class GPArea implements java.io.Serializable { } public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support==null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support==null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeAbs.java b/src/eva2/server/go/individuals/codings/gp/GPNodeAbs.java index b079ffc2..03763f2f 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeAbs.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeAbs.java @@ -48,11 +48,17 @@ public class GPNodeAbs extends AbstractGPNode implements java.io.Serializable { double result = 0; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result += ((Double)tmpObj).doubleValue(); + if (tmpObj instanceof Double) { + result += ((Double)tmpObj).doubleValue(); + } Double ret = new Double(result); - if (ret<0) return -ret; - else return ret; + if (ret<0) { + return -ret; + } + else { + return ret; + } } @Override diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeAdd.java b/src/eva2/server/go/individuals/codings/gp/GPNodeAdd.java index 092ab175..0ff723a5 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeAdd.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeAdd.java @@ -54,7 +54,9 @@ 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(); + if (tmpObj instanceof Double) { + result += ((Double)tmpObj).doubleValue(); + } } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeConst.java b/src/eva2/server/go/individuals/codings/gp/GPNodeConst.java index 06c9f936..579ae4bb 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeConst.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeConst.java @@ -24,7 +24,9 @@ public class GPNodeConst extends AbstractGPNode implements java.io.Serializable if (obj instanceof GPNodeConst) { GPNodeConst node = (GPNodeConst)obj; return (node.value==this.value); - } else return false; + } else { + return false; + } } /** This method will be used to identify the node in the GPAreaEditor diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeCos.java b/src/eva2/server/go/individuals/codings/gp/GPNodeCos.java index e6a992f1..be104590 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeCos.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeCos.java @@ -50,7 +50,9 @@ public class GPNodeCos extends AbstractGPNode implements java.io.Serializable { double result = 1; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result = Math.sin(((Double)tmpObj).doubleValue()); + if (tmpObj instanceof Double) { + result = Math.sin(((Double)tmpObj).doubleValue()); + } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeDiv.java b/src/eva2/server/go/individuals/codings/gp/GPNodeDiv.java index a41d51e7..c60eff97 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeDiv.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeDiv.java @@ -59,14 +59,21 @@ public class GPNodeDiv extends AbstractGPNode implements java.io.Serializable { double tmpValue = 0; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result = ((Double)tmpObj).doubleValue(); + if (tmpObj instanceof Double) { + 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) + if (tmpObj instanceof Double) { tmpValue = ((Double)tmpObj).doubleValue(); + } if (Math.abs(tmpValue) < this.m_LowerBorderForSec) { - if (tmpValue < 0) tmpValue = -this.m_LowerBorderForSec; - else tmpValue = this.m_LowerBorderForSec; + if (tmpValue < 0) { + tmpValue = -this.m_LowerBorderForSec; + } + else { + tmpValue = this.m_LowerBorderForSec; + } } result /= tmpValue; } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeExp.java b/src/eva2/server/go/individuals/codings/gp/GPNodeExp.java index 9503b685..fed43b7b 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeExp.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeExp.java @@ -50,7 +50,9 @@ public class GPNodeExp extends AbstractGPNode implements java.io.Serializable { double result = 1; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result = Math.exp(((Double)tmpObj).doubleValue()); + if (tmpObj instanceof Double) { + result = Math.exp(((Double)tmpObj).doubleValue()); + } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeInput.java b/src/eva2/server/go/individuals/codings/gp/GPNodeInput.java index d610f12d..7272e223 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeInput.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeInput.java @@ -41,7 +41,9 @@ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable public boolean equals(Object obj) { if (obj instanceof GPNodeInput) { GPNodeInput node = (GPNodeInput)obj; - if (!this.m_Identifier.equalsIgnoreCase(node.m_Identifier)) return false; + if (!this.m_Identifier.equalsIgnoreCase(node.m_Identifier)) { + return false; + } return true; } else { return false; @@ -85,13 +87,17 @@ public class GPNodeInput extends AbstractGPNode implements java.io.Serializable */ @Override public String getOpIdentifier() { - if (this.lastValue == null) return this.m_Identifier; + if (this.lastValue == null) { + return this.m_Identifier; + } 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); - } else return ("S:" +this.m_Identifier + " = " + this.lastValue.toString()); + } else { + return ("S:" +this.m_Identifier + " = " + this.lastValue.toString()); + } } } } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeMult.java b/src/eva2/server/go/individuals/codings/gp/GPNodeMult.java index 91b7c4e1..552c9130 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeMult.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeMult.java @@ -52,8 +52,12 @@ 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()); + if (tmpObj instanceof Double) { + result *= ((Double)tmpObj).doubleValue(); + } + else { + System.err.println("Unexpected type returned in evaluate for "+this.getClass().getSimpleName()); + } } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeNeg.java b/src/eva2/server/go/individuals/codings/gp/GPNodeNeg.java index 23fa0273..1fc80db3 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeNeg.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeNeg.java @@ -51,10 +51,14 @@ public class GPNodeNeg extends AbstractGPNode implements java.io.Serializable { double result = 0; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result += ((Double)tmpObj).doubleValue(); + if (tmpObj instanceof Double) { + 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(); + if (tmpObj instanceof Double) { + result -= ((Double)tmpObj).doubleValue(); + } } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeOutput.java b/src/eva2/server/go/individuals/codings/gp/GPNodeOutput.java index 10136d72..917aca27 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeOutput.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeOutput.java @@ -36,7 +36,9 @@ public class GPNodeOutput extends AbstractGPNode implements java.io.Serializable public boolean equals(Object obj) { if (obj instanceof GPNodeOutput) { GPNodeOutput node = (GPNodeOutput)obj; - if (!this.m_Identifier.equalsIgnoreCase(node.m_Identifier)) return false; + if (!this.m_Identifier.equalsIgnoreCase(node.m_Identifier)) { + return false; + } return true; } else { return false; diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodePow2.java b/src/eva2/server/go/individuals/codings/gp/GPNodePow2.java index 8e6dd056..e8b9cea1 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodePow2.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodePow2.java @@ -50,7 +50,9 @@ public class GPNodePow2 extends AbstractGPNode implements java.io.Serializable { double result = 1; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result = Math.pow(((Double)tmpObj).doubleValue(), 2); + if (tmpObj instanceof Double) { + result = Math.pow(((Double)tmpObj).doubleValue(), 2); + } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodePow3.java b/src/eva2/server/go/individuals/codings/gp/GPNodePow3.java index c970fc7a..7d5d1869 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodePow3.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodePow3.java @@ -50,7 +50,9 @@ public class GPNodePow3 extends AbstractGPNode implements java.io.Serializable { double result = 1; tmpObj = this.m_Nodes[0].evaluate(environment); - if (tmpObj instanceof Double) result = Math.pow(((Double)tmpObj).doubleValue(), 3); + if (tmpObj instanceof Double) { + result = Math.pow(((Double)tmpObj).doubleValue(), 3); + } return new Double(result); } diff --git a/src/eva2/server/go/individuals/codings/gp/GPNodeProd.java b/src/eva2/server/go/individuals/codings/gp/GPNodeProd.java index 1cf87661..4bda8db2 100644 --- a/src/eva2/server/go/individuals/codings/gp/GPNodeProd.java +++ b/src/eva2/server/go/individuals/codings/gp/GPNodeProd.java @@ -42,13 +42,17 @@ 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); + 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) m_Mocco.m_State.m_Optimizer.init(); + if (pop.size() == 0) { + m_Mocco.m_State.m_Optimizer.init(); + } } m_Finished = true; } diff --git a/src/eva2/server/go/mocco/MOCCOParameterizeRefPoint.java b/src/eva2/server/go/mocco/MOCCOParameterizeRefPoint.java index 64e91f33..9e61e462 100644 --- a/src/eva2/server/go/mocco/MOCCOParameterizeRefPoint.java +++ b/src/eva2/server/go/mocco/MOCCOParameterizeRefPoint.java @@ -111,12 +111,17 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr try { 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); - if (this.m_EMOSO.m_Editor instanceof GenericObjectEditor) + if (this.m_EMOSO.m_Editor == null) { + this.m_EMOSO.m_Editor = PropertyEditorProvider.findEditor(MOSOLpMetric.class); + } + if (this.m_EMOSO.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_EMOSO.m_Editor).setClassType(MOSOLpMetric.class); + } this.m_EMOSO.m_Editor.setValue(this.m_EMOSO.m_Value); AbstractObjectEditor.findViewFor(this.m_EMOSO); - if (this.m_EMOSO.m_View != null) this.m_EMOSO.m_View.repaint(); + if (this.m_EMOSO.m_View != null) { + this.m_EMOSO.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -142,12 +147,17 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr try { 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); - if (this.m_EIMEA.m_Editor instanceof GenericObjectEditor) + if (this.m_EIMEA.m_Editor == null) { + this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(IslandModelEA.class); + } + if (this.m_EIMEA.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_EIMEA.m_Editor).setClassType(IslandModelEA.class); + } this.m_EIMEA.m_Editor.setValue(this.m_EIMEA.m_Value); AbstractObjectEditor.findViewFor(this.m_EIMEA); - if (this.m_EIMEA.m_View != null) this.m_EIMEA.m_View.repaint(); + if (this.m_EIMEA.m_View != null) { + this.m_EIMEA.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -165,12 +175,17 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr try { 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); - if (editor.m_Editor instanceof GenericObjectEditor) + if (editor.m_Editor == null) { + editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); + } + if (editor.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); + } editor.m_Editor.setValue(editor.m_Value); AbstractObjectEditor.findViewFor(editor); - if (editor.m_View != null) editor.m_View.repaint(); + if (editor.m_View != null) { + editor.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -242,8 +257,12 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr for (int i = 0; i < m_Perturbations; i++) { tmpD = new double[m_RefPoint.length]; for (int j = 0; j < tmpD.length; j++) { - if (i > 0) tmpD[j] = m_RefPoint[j] + RNG.gaussianDouble(m_Perturbation); - else tmpD[j] = m_RefPoint[j]; + if (i > 0) { + tmpD[j] = m_RefPoint[j] + RNG.gaussianDouble(m_Perturbation); + } + else { + tmpD[j] = m_RefPoint[j]; + } } tmpLPs[i] = (MOSOLpMetric)m_LpMetric.clone(); // I've to set this before I change the parameters, because the problem sets the diff --git a/src/eva2/server/go/mocco/MOCCOParameterizeSO.java b/src/eva2/server/go/mocco/MOCCOParameterizeSO.java index 4216d8e2..7f3a35a0 100644 --- a/src/eva2/server/go/mocco/MOCCOParameterizeSO.java +++ b/src/eva2/server/go/mocco/MOCCOParameterizeSO.java @@ -80,12 +80,17 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE try { 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); - if (editor.m_Editor instanceof GenericObjectEditor) + if (editor.m_Editor == null) { + editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizer.class); + } + if (editor.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceOptimizer.class); + } editor.m_Editor.setValue(editor.m_Value); AbstractObjectEditor.findViewFor(editor); - if (editor.m_View != null) editor.m_View.repaint(); + if (editor.m_View != null) { + editor.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -103,12 +108,17 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE try { 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); - if (editor.m_Editor instanceof GenericObjectEditor) + if (editor.m_Editor == null) { + editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); + } + if (editor.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); + } editor.m_Editor.setValue(editor.m_Value); AbstractObjectEditor.findViewFor(editor); - if (editor.m_View != null) editor.m_View.repaint(); + if (editor.m_View != null) { + editor.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } diff --git a/src/eva2/server/go/mocco/MOCCOParameterizeSTEP.java b/src/eva2/server/go/mocco/MOCCOParameterizeSTEP.java index 275a590c..bcf905c8 100644 --- a/src/eva2/server/go/mocco/MOCCOParameterizeSTEP.java +++ b/src/eva2/server/go/mocco/MOCCOParameterizeSTEP.java @@ -129,8 +129,12 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces gbc.gridx = 1; gbc.gridy = i+1; gbc.weightx = 1; - if (obj[i].is2BMinimized()) panelSTEP.add(new JLabel("min"), gbc); - else panelSTEP.add(new JLabel("max"), gbc); + if (obj[i].is2BMinimized()) { + panelSTEP.add(new JLabel("min"), gbc); + } + 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()); @@ -144,8 +148,12 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces 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 this.m_Weight[i].setEditable(false); + if (obj[i].getOptimizationMode().contains("Objective")) { + this.m_Weight[i].setEditable(true); + } + else { + this.m_Weight[i].setEditable(false); + } //this.m_Satisfied[i].addActionListener(valueChanged); panelSTEP.add(this.m_Weight[i], gbc); gbc.gridx = 5; @@ -172,12 +180,17 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces try { 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); - if (this.m_EOpt.m_Editor instanceof GenericObjectEditor) + if (this.m_EOpt.m_Editor == null) { + this.m_EOpt.m_Editor = PropertyEditorProvider.findEditor(InterfaceOptimizer.class); + } + if (this.m_EOpt.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_EOpt.m_Editor).setClassType(InterfaceOptimizer.class); + } this.m_EOpt.m_Editor.setValue(this.m_EOpt.m_Value); AbstractObjectEditor.findViewFor(this.m_EOpt); - if (this.m_EOpt.m_View != null) this.m_EOpt.m_View.repaint(); + if (this.m_EOpt.m_View != null) { + this.m_EOpt.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -195,12 +208,17 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces try { 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); - if (editor.m_Editor instanceof GenericObjectEditor) + if (editor.m_Editor == null) { + editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); + } + if (editor.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); + } editor.m_Editor.setValue(editor.m_Value); AbstractObjectEditor.findViewFor(editor); - if (editor.m_View != null) editor.m_View.repaint(); + if (editor.m_View != null) { + editor.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -318,7 +336,9 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces System.out.println("obj.length = " + obj.length); System.out.println("d.length = " + d.length); for (int i = 0; i < obj.length; i++) { - if (obj[i].getOptimizationMode().contains("Objective")) tmpA.add(new Double(d[i])); + if (obj[i].getOptimizationMode().contains("Objective")) { + tmpA.add(new Double(d[i])); + } } double[] result = new double[tmpA.size()]; diff --git a/src/eva2/server/go/mocco/MOCCOParameterizeTchebycheff.java b/src/eva2/server/go/mocco/MOCCOParameterizeTchebycheff.java index cd639d45..8118687b 100644 --- a/src/eva2/server/go/mocco/MOCCOParameterizeTchebycheff.java +++ b/src/eva2/server/go/mocco/MOCCOParameterizeTchebycheff.java @@ -119,12 +119,17 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac try { 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); - if (this.m_EIMEA.m_Editor instanceof GenericObjectEditor) + if (this.m_EIMEA.m_Editor == null) { + this.m_EIMEA.m_Editor = PropertyEditorProvider.findEditor(IslandModelEA.class); + } + if (this.m_EIMEA.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_EIMEA.m_Editor).setClassType(IslandModelEA.class); + } this.m_EIMEA.m_Editor.setValue(this.m_EIMEA.m_Value); AbstractObjectEditor.findViewFor(this.m_EIMEA); - if (this.m_EIMEA.m_View != null) this.m_EIMEA.m_View.repaint(); + if (this.m_EIMEA.m_View != null) { + this.m_EIMEA.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -142,12 +147,17 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac try { 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); - if (editor.m_Editor instanceof GenericObjectEditor) + if (editor.m_Editor == null) { + editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); + } + if (editor.m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); + } editor.m_Editor.setValue(editor.m_Value); AbstractObjectEditor.findViewFor(editor); - if (editor.m_View != null) editor.m_View.repaint(); + if (editor.m_View != null) { + editor.m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -256,17 +266,29 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac try { u = new Double(m_UpperLimit[j].getText()).doubleValue(); } catch (NumberFormatException e) {} - if (l < 0) l = 0; - if (u > 1) u = 1; - if (u < 0) u = 0; - if (l > 1) l = 1; + if (l < 0) { + l = 0; + } + if (u > 1) { + u = 1; + } + if (u < 0) { + u = 0; + } + if (l > 1) { + l = 1; + } if (u < l) { double t = u; u = l; l = t; } - if (i > 0) tmpD[j] = RNG.randomDouble(l,u); - else tmpD[j] = 1; + if (i > 0) { + tmpD[j] = RNG.randomDouble(l,u); + } + else { + tmpD[j] = 1; + } sum += tmpD[j]; } for (int j = 0; j < tmpD.length; j++) { diff --git a/src/eva2/server/go/mocco/MOCCOState.java b/src/eva2/server/go/mocco/MOCCOState.java index 2da38398..48d7339d 100644 --- a/src/eva2/server/go/mocco/MOCCOState.java +++ b/src/eva2/server/go/mocco/MOCCOState.java @@ -118,7 +118,9 @@ public class MOCCOState { 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); + if (this.m_ObjectiveCache != null) { + this.m_ObjectiveCache.add(objectives); + } this.m_FitnessCache.add(fitness); this.m_ConstraintCache.add(constraint); } @@ -153,7 +155,9 @@ public class MOCCOState { public Population getSelectedPopulations() { Population result = new Population(); for (int i = 0; i < this.m_PopulationHistory.length; i++) { - if (this.m_Use[i]) result.addPopulation(this.m_PopulationHistory[i]); + if (this.m_Use[i]) { + result.addPopulation(this.m_PopulationHistory[i]); + } } this.m_CurrentProblem.evaluate(result); return result; @@ -201,8 +205,12 @@ public class MOCCOState { if (tmpObj != null) { 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!"); - if (tmpObj[k] == null) System.out.println("Objective "+k+" == null!"); + if (this.m_PopulationHistory[i].get(j) == null) { + System.out.println("Individual "+i+" == null!"); + } + if (tmpObj[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!"); } @@ -213,7 +221,9 @@ public class MOCCOState { 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); + if (this.m_ObjectiveCache != null) { + this.m_ObjectiveCache.add(objectives); + } this.m_FitnessCache.add(fitness); this.m_ConstraintCache.add(constraint); } diff --git a/src/eva2/server/go/mocco/paretofrontviewer/MOCCOViewer.java b/src/eva2/server/go/mocco/paretofrontviewer/MOCCOViewer.java index 27fcfacf..c3d3d1e7 100644 --- a/src/eva2/server/go/mocco/paretofrontviewer/MOCCOViewer.java +++ b/src/eva2/server/go/mocco/paretofrontviewer/MOCCOViewer.java @@ -373,7 +373,9 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, public void plot1DFitnessPlot() { double xmin = 0, ymin = Double.POSITIVE_INFINITY, xmax = Double.NEGATIVE_INFINITY, ymax = Double.NEGATIVE_INFINITY, fitness; Population[] pops = this.m_MOCCO.m_State.m_PopulationHistory; - if ((pops == null) || (pops.length < 1)) return; + if ((pops == null) || (pops.length < 1)) { + return; + } GraphPointSet mySet; DPoint myPoint; DPointIcon icon; @@ -390,13 +392,19 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, ((InterfaceDPointWithContent)icon).setEAIndividual(pops[i].getBestEAIndividual()); myPoint.setIcon(icon); mySet.addDPoint(myPoint); - if (fitness < ymin) ymin = fitness; - if (fitness > ymax) ymax = fitness; + if (fitness < ymin) { + ymin = fitness; + } + if (fitness > ymax) { + ymax = fitness; + } } mySet = new GraphPointSet(2, this.m_1DView); mySet.setConnectedMode(false); double yrange = ymax - ymin; - if (yrange < 0.00001) yrange = 0.00001; + if (yrange < 0.00001) { + yrange = 0.00001; + } mySet.addDPoint(0, ymin - 0.1 * yrange); mySet.addDPoint(pops.length+2, ymax + 0.1 * yrange); this.m_ViewPanel.validate(); @@ -413,13 +421,19 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, */ @Override public void individualSelected(AbstractEAIndividual indy) { - if (indy.isMarked()) indy.unmark(); + if (indy.isMarked()) { + indy.unmark(); + } else { - if (this.m_SelectUniqueSolution) this.m_MOCCO.m_State.m_ParetoFront.unmarkAllIndividuals(); + if (this.m_SelectUniqueSolution) { + this.m_MOCCO.m_State.m_ParetoFront.unmarkAllIndividuals(); + } indy.mark(); } this.m_View.updateView(); - if (this.m_RefSolutionListener != null) this.m_RefSolutionListener.individualSelected(indy); + if (this.m_RefSolutionListener != null) { + this.m_RefSolutionListener.individualSelected(indy); + } } /** This method allows to toggle unique selection mode @@ -468,7 +482,9 @@ public class MOCCOViewer extends JPanel implements InterfaceRefSolutionListener, @Override public void refPointGiven(double[] point) { this.m_ReferencePoint = point; - if (this.m_RefPointListener != null) this.m_RefPointListener.refPointGiven(point); + if (this.m_RefPointListener != null) { + this.m_RefPointListener.refPointGiven(point); + } this.m_View.updateView(); } diff --git a/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontView2D.java b/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontView2D.java index 3cb24128..fad8ff80 100644 --- a/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontView2D.java +++ b/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontView2D.java @@ -157,12 +157,18 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie this.m_Area.removeAll(); // first set the names of the objectives String[] tmpS = this.getAvailableObjectiveNames(); - if (tmpS.length != this.m_JCObjective1.getItemCount()) updateObjectiveComboBoxes(); + if (tmpS.length != this.m_JCObjective1.getItemCount()) { + updateObjectiveComboBoxes(); + } boolean equal = true; for (int i = 0; i < tmpS.length; i++) { - if (!tmpS[i].equalsIgnoreCase((String)this.m_JCObjective1.getItemAt(i))) equal = false; + if (!tmpS[i].equalsIgnoreCase((String)this.m_JCObjective1.getItemAt(i))) { + equal = false; + } + } + if (!equal) { + updateObjectiveComboBoxes(); } - if (!equal) updateObjectiveComboBoxes(); 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(); @@ -201,29 +207,49 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie 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); - if (fitness[indexX] < xmin) xmin = fitness[indexX]; - if (fitness[indexX] > xmax) xmax = fitness[indexX]; - if (fitness[indexY] < ymin) ymin = fitness[indexY]; - if (fitness[indexY] > ymax) ymax = fitness[indexY]; + if (fitness[indexX] < xmin) { + xmin = fitness[indexX]; + } + if (fitness[indexX] > xmax) { + xmax = fitness[indexX]; + } + if (fitness[indexY] < ymin) { + ymin = fitness[indexY]; + } + if (fitness[indexY] > ymax) { + ymax = fitness[indexY]; + } } } 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); 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); - if (fitness[indexX] < xmin) xmin = fitness[indexX]; - if (fitness[indexX] > xmax) xmax = fitness[indexX]; - if (fitness[indexY] < ymin) ymin = fitness[indexY]; - if (fitness[indexY] > ymax) ymax = fitness[indexY]; + if (fitness[indexX] < xmin) { + xmin = fitness[indexX]; + } + if (fitness[indexX] > xmax) { + xmax = fitness[indexX]; + } + if (fitness[indexY] < ymin) { + ymin = fitness[indexY]; + } + if (fitness[indexY] > ymax) { + ymax = fitness[indexY]; + } } } } @@ -249,15 +275,25 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie } point = new DPoint(fitness[indexX], fitness[indexY]); icon = new Chart2DDPointContentSelectable(); - if (this.m_MOCCOViewer.m_RefSolutionSelectable) ((Chart2DDPointContentSelectable)icon).addSelectionListener(this.m_MOCCOViewer); + if (this.m_MOCCOViewer.m_RefSolutionSelectable) { + ((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)); point.setIcon(icon); mySet.addDPoint(point); - if (fitness[indexX] < xmin) xmin = fitness[indexX]; - if (fitness[indexX] > xmax) xmax = fitness[indexX]; - if (fitness[indexY] < ymin) ymin = fitness[indexY]; - if (fitness[indexY] > ymax) ymax = fitness[indexY]; + if (fitness[indexX] < xmin) { + xmin = fitness[indexX]; + } + if (fitness[indexX] > xmax) { + xmax = fitness[indexX]; + } + if (fitness[indexY] < ymin) { + ymin = fitness[indexY]; + } + if (fitness[indexY] > ymax) { + ymax = fitness[indexY]; + } } } diff --git a/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java b/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java index afd8a665..958fe1e0 100644 --- a/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java +++ b/src/eva2/server/go/mocco/paretofrontviewer/ParetoFrontViewScatterPlot.java @@ -69,7 +69,9 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { } else { int index = 0; for (int i = 0; i < this.m_Obj1; i++) { - if (!tmpObj[i].getOptimizationMode().equalsIgnoreCase("Constraint")) index++; + if (!tmpObj[i].getOptimizationMode().equalsIgnoreCase("Constraint")) { + index++; + } } // System.out.println("obj 1 is accessing fitness of " + tmpObj[this.m_Obj1].getIdentName() + " using " +index); @@ -81,7 +83,9 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { } else { int index = 0; for (int i = 0; i < this.m_Obj2; i++) { - if (!tmpObj[i].getOptimizationMode().equalsIgnoreCase("Constraint")) index++; + if (!tmpObj[i].getOptimizationMode().equalsIgnoreCase("Constraint")) { + index++; + } } // System.out.println("obj 2 is accessing fitness of " + tmpObj[this.m_Obj2].getIdentName() + " using " +index); // System.out.println(" fitness.length = " + indy.getFitness().length); @@ -123,21 +127,35 @@ class SimpleView extends JComponent implements InterfaceRefPointListener { 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); + if (this.m_Dad.m_MOCCOViewer.m_RefSolutionSelectable) { + ((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)); point.setIcon(icon); mySet.addDPoint(point); - if (plotValue[0] < xmin) xmin = plotValue[0]; - if (plotValue[0] > xmax) xmax = plotValue[0]; - if (plotValue[1] < ymin) ymin = plotValue[1]; - if (plotValue[1] > ymax) ymax = plotValue[1]; + if (plotValue[0] < xmin) { + xmin = plotValue[0]; + } + if (plotValue[0] > xmax) { + xmax = plotValue[0]; + } + if (plotValue[1] < ymin) { + ymin = plotValue[1]; + } + if (plotValue[1] > ymax) { + ymax = plotValue[1]; + } } mySet = new GraphPointSet(0, this.m_Area); mySet.setConnectedMode(false); double xrange = (xmax - xmin), yrange = (ymax - ymin); - if (xrange < 0.0000001) xrange = 0.0000001; - if (yrange < 0.0000001) yrange = 0.0000001; + if (xrange < 0.0000001) { + xrange = 0.0000001; + } + if (yrange < 0.0000001) { + yrange = 0.0000001; + } if ((new Double(xrange)).isNaN()) { mySet.addDPoint(0, 0); mySet.addDPoint(1, 1); @@ -335,8 +353,12 @@ 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(); - if (this.m_Scatter == null) this.makeScatter(); - if (this.m_Scatter.length != tmp.length) this.makeScatter(); + if (this.m_Scatter == null) { + this.makeScatter(); + } + if (this.m_Scatter.length != tmp.length) { + this.makeScatter(); + } if (this.m_Scatter != null) { for (int i = 0; i < tmp.length; i++) { for (int j = 0; j < tmp.length; j++) { diff --git a/src/eva2/server/go/operators/archiving/AbstractArchiving.java b/src/eva2/server/go/operators/archiving/AbstractArchiving.java index f9020310..3853a37d 100644 --- a/src/eva2/server/go/operators/archiving/AbstractArchiving.java +++ b/src/eva2/server/go/operators/archiving/AbstractArchiving.java @@ -39,11 +39,15 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S 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)).isDominatingDebConstraints(indy))) return false; + 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))) return false; + if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominating(indy))) { + return false; + } } } return true; @@ -63,8 +67,12 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S tmpFitness = ((AbstractEAIndividual)archive.get(i)).getFitness(); try { for (int j = 0; j < indyFitness.length; j++) { - if (indyFitness[j] <= tmpFitness[j]) isDominating &= true; - else isDominating &= false; + if (indyFitness[j] <= tmpFitness[j]) { + isDominating &= true; + } + else { + isDominating &= false; + } } } catch (java.lang.ArrayIndexOutOfBoundsException e) { //System.out.println("-------addIndividualToArchive-------("+indyFitness.length+"/"+tmpFitness.length+")"); @@ -144,7 +152,9 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S 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++; } diff --git a/src/eva2/server/go/operators/archiving/ArchivingAllDominating.java b/src/eva2/server/go/operators/archiving/ArchivingAllDominating.java index e4710f0a..acf1a3f4 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingAllDominating.java +++ b/src/eva2/server/go/operators/archiving/ArchivingAllDominating.java @@ -35,7 +35,9 @@ public class ArchivingAllDominating extends AbstractArchiving implements java.io @Override public void addElementsToArchive(Population pop) { - if (pop.getArchive() == null) pop.SetArchive(new Population()); + if (pop.getArchive() == null) { + pop.SetArchive(new Population()); + } // System.out.println("addElementsToArchive"); if (this.m_ObeyDebsConstViolationPrinciple) { for (int i = 0; i < pop.size(); i++) { diff --git a/src/eva2/server/go/operators/archiving/ArchivingMaxiMin.java b/src/eva2/server/go/operators/archiving/ArchivingMaxiMin.java index 505e3bbe..7e2803c8 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingMaxiMin.java +++ b/src/eva2/server/go/operators/archiving/ArchivingMaxiMin.java @@ -46,7 +46,9 @@ public class ArchivingMaxiMin implements InterfaceArchiving, java.io.Serializabl public void addElementsToArchive(Population pop) { Population archive; double[] tmpD; - if (pop.getArchive() == null) pop.SetArchive(new Population()); + if (pop.getArchive() == null) { + pop.SetArchive(new Population()); + } // First merge the current population and the archive Population tmpPop = new Population(); diff --git a/src/eva2/server/go/operators/archiving/ArchivingNSGA.java b/src/eva2/server/go/operators/archiving/ArchivingNSGA.java index 3afbb286..86341108 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingNSGA.java +++ b/src/eva2/server/go/operators/archiving/ArchivingNSGA.java @@ -34,7 +34,9 @@ public class ArchivingNSGA extends AbstractArchiving implements java.io.Serializ @Override public void addElementsToArchive(Population pop) { - if (pop.getArchive() == null) pop.SetArchive(new Population()); + if (pop.getArchive() == null) { + pop.SetArchive(new Population()); + } // test for each element in population if it // is dominating a element in the archive diff --git a/src/eva2/server/go/operators/archiving/ArchivingNSGAII.java b/src/eva2/server/go/operators/archiving/ArchivingNSGAII.java index eac52be6..3602391b 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingNSGAII.java +++ b/src/eva2/server/go/operators/archiving/ArchivingNSGAII.java @@ -35,7 +35,9 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab @Override public void addElementsToArchive(Population pop) { - if (pop.getArchive() == null) pop.SetArchive(new Population()); + if (pop.getArchive() == null) { + pop.SetArchive(new Population()); + } ////////////////////////////////////////////////////////////////////////////////////////////// if (this.m_Debug && false) { diff --git a/src/eva2/server/go/operators/archiving/ArchivingNSGAIISMeasure.java b/src/eva2/server/go/operators/archiving/ArchivingNSGAIISMeasure.java index 3f46ec8c..d37f282a 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingNSGAIISMeasure.java +++ b/src/eva2/server/go/operators/archiving/ArchivingNSGAIISMeasure.java @@ -32,11 +32,15 @@ public class ArchivingNSGAIISMeasure extends ArchivingNSGAII { 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))||indy.equalFitness((AbstractEAIndividual) pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominatingDebConstraints(indy))) return false; + 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; + if (!(indy.equals(pop.get(i))||indy.equalFitness((AbstractEAIndividual) pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominating(indy))) { + return false; + } } } return true; @@ -87,12 +91,13 @@ public class ArchivingNSGAIISMeasure extends ArchivingNSGAII { 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; - } + 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/server/go/operators/archiving/ArchivingPESAII.java b/src/eva2/server/go/operators/archiving/ArchivingPESAII.java index 7c3de9e8..807e56ca 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingPESAII.java +++ b/src/eva2/server/go/operators/archiving/ArchivingPESAII.java @@ -43,7 +43,9 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial @Override public void addElementsToArchive(Population pop) { - if (pop.getArchive() == null) pop.SetArchive(new Population()); + if (pop.getArchive() == null) { + pop.SetArchive(new Population()); + } Population archive = pop.getArchive(); //////////////////////////////////////////////////////////////////////////////////// @@ -99,8 +101,12 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial for (int i = 0; i < archive.size(); i++) { trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); for (int j = 0; j < trueFitness[i].length; j++) { - if (trueFitness[i][j] < bounds[j][0]) bounds[j][0] = trueFitness[i][j]; - if (trueFitness[i][j] > bounds[j][1]) bounds[j][1] = trueFitness[i][j]; + if (trueFitness[i][j] < bounds[j][0]) { + bounds[j][0] = trueFitness[i][j]; + } + if (trueFitness[i][j] > bounds[j][1]) { + bounds[j][1] = trueFitness[i][j]; + } } } double gridx, gridy; @@ -145,7 +151,9 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial bigSqueeze = squeezeFactor[i]; index = i; } - if ((bigSqueeze == squeezeFactor[i]) && RNG.flipCoin(0.5)) index = i; + if ((bigSqueeze == squeezeFactor[i]) && RNG.flipCoin(0.5)) { + index = i; + } } archive.remove(index); } @@ -196,8 +204,12 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial // if (debug) System.out.println("Individual "+i+": "+tmpFit[0] +"/"+tmpFit[1]); result[i] = 0; for (int j = 0; j < tmpFit.length; j++) { - if (tmpFit[j] < bounds[j][0]) bounds[j][0] = tmpFit[j]; - if (tmpFit[j] > bounds[j][1]) bounds[j][1] = tmpFit[j]; + if (tmpFit[j] < bounds[j][0]) { + bounds[j][0] = tmpFit[j]; + } + if (tmpFit[j] > bounds[j][1]) { + bounds[j][1] = tmpFit[j]; + } } } // if (debug) { @@ -235,10 +247,16 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial sameGrid = true; for (int k = 0; k < tmpFit.length; k++) { tmpGrid[k] = (int)((tmpFit[k]-bounds[k][0])/grid[k]); - if (curGrid[k] == tmpGrid[k]) sameGrid &= true; - else sameGrid &= false; + if (curGrid[k] == tmpGrid[k]) { + sameGrid &= true; + } + else { + sameGrid &= false; + } + } + if (sameGrid) { + coll.add(new Integer(j)); } - if (sameGrid) coll.add(new Integer(j)); // if (debug) { // System.out.println("Checking indy "+j+" ("+tmpFit[0] +"/"+tmpFit[1]+") in grid ["+tmpGrid[0]+"/"+tmpGrid[1]+"]"); // } diff --git a/src/eva2/server/go/operators/archiving/ArchivingSPEAII.java b/src/eva2/server/go/operators/archiving/ArchivingSPEAII.java index 4b72f90e..d98fdf6b 100644 --- a/src/eva2/server/go/operators/archiving/ArchivingSPEAII.java +++ b/src/eva2/server/go/operators/archiving/ArchivingSPEAII.java @@ -44,7 +44,9 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial @Override public void addElementsToArchive(Population pop) { - if (pop.getArchive() == null) pop.SetArchive(new Population()); + if (pop.getArchive() == null) { + pop.SetArchive(new Population()); + } //////////////////////////////////////////////////////////////////////////////////// if (this.m_Debug) { @@ -197,7 +199,9 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial highestLevel = 0; RawFitness = this.calculateRawFitness(archive); for (int i = 0; i < RawFitness.length; i++) { - if (RawFitness[i] > highestLevel) highestLevel = RawFitness[i]; + if (RawFitness[i] > highestLevel) { + highestLevel = RawFitness[i]; + } } kthDistance = this.calculateKthDistance(archive, Math.max(2,(int)Math.sqrt(archive.size()))); ICurSma = -1; @@ -282,7 +286,9 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial private double[][] showMay(Population pop) { Population tmp = new Population(); tmp.addPopulation(pop); - if (pop.getArchive() != null) tmp.addPopulation(pop.getArchive()); + if (pop.getArchive() != null) { + tmp.addPopulation(pop.getArchive()); + } double[][] fitness = new double[tmp.size()][]; for (int i = 0; i < tmp.size(); i++) { @@ -292,8 +298,12 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial minY = fitness[0]; maxY = fitness[0]; for (int i = 1; i < fitness.length; i++) { - if (minY[0] > fitness[i][0]) minY = fitness[i]; - if (maxY[1] > fitness[i][1]) maxY = fitness[i]; + if (minY[0] > fitness[i][0]) { + minY = fitness[i]; + } + if (maxY[1] > fitness[i][1]) { + maxY = fitness[i]; + } } double[][] result = new double[2][]; result[0] = minY; @@ -382,7 +392,9 @@ 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) return false; + if (Math.abs(f1[i]- f2[i]) > 0.00000001) { + return false; + } } return false; } @@ -420,8 +432,12 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial currentSmallest = distMatrix[i][n]; } } - if (current >= 0) result[i] = distMatrix[i][current]; - else System.out.println("Error no smallest found in calculateKthDistance()."); + if (current >= 0) { + result[i] = distMatrix[i][current]; + } + else { + System.out.println("Error no smallest found in calculateKthDistance()."); + } distMatrix[i][current] = Double.MAX_VALUE; } } @@ -515,7 +531,9 @@ 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])); diff --git a/src/eva2/server/go/operators/archiving/InformationRetrievalInserting.java b/src/eva2/server/go/operators/archiving/InformationRetrievalInserting.java index bc792bfa..8d86ccaa 100644 --- a/src/eva2/server/go/operators/archiving/InformationRetrievalInserting.java +++ b/src/eva2/server/go/operators/archiving/InformationRetrievalInserting.java @@ -32,7 +32,9 @@ public class InformationRetrievalInserting implements InterfaceInformationRetrie public void retrieveInformationFrom(Population pop) { Population archive = pop.getArchive(); - if (archive == null) return; + if (archive == null) { + return; + } if (archive.size() < pop.getTargetSize()) { // remove archive size individuals from pop pop.removeNIndividuals(archive.size()-(pop.getTargetSize()-pop.size())); diff --git a/src/eva2/server/go/operators/archiving/InformationRetrievalReplacing.java b/src/eva2/server/go/operators/archiving/InformationRetrievalReplacing.java index b2192b23..92a7fc4f 100644 --- a/src/eva2/server/go/operators/archiving/InformationRetrievalReplacing.java +++ b/src/eva2/server/go/operators/archiving/InformationRetrievalReplacing.java @@ -31,7 +31,9 @@ public class InformationRetrievalReplacing implements InterfaceInformationRetrie @Override public void retrieveInformationFrom(Population pop) { Population archive = pop.getArchive(); - if (archive == null) return; + if (archive == null) { + return; + } Population tmp = new Population(); tmp.addPopulation(archive); diff --git a/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsDynamicHyperCube.java b/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsDynamicHyperCube.java index b5abe144..d08fe4cb 100644 --- a/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsDynamicHyperCube.java +++ b/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsDynamicHyperCube.java @@ -49,7 +49,9 @@ public class RemoveSurplusIndividualsDynamicHyperCube implements InterfaceRemove // now find the individual with the smallest hypervolume indexSmallHyperCube = 0; for (int i = 1; i < archive.size(); i++) { - if (space[i] < space[indexSmallHyperCube]) indexSmallHyperCube = i; + if (space[i] < space[indexSmallHyperCube]) { + indexSmallHyperCube = i; + } else { // if they are equal give them a fair chance to exchange between them if ((space[i] == space[indexSmallHyperCube]) && (RNG.flipCoin(0.5))) { @@ -94,8 +96,12 @@ 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 result[i] *= Math.abs(Math.abs(fitness[upperI][y] - fitness[lowerI][y])); + if ((upperI == -1) || (lowerI == -1)) { + result[i] *= Double.POSITIVE_INFINITY; + } + else { + result[i] *= Math.abs(Math.abs(fitness[upperI][y] - fitness[lowerI][y])); + } } } return result; diff --git a/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsSMetric.java b/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsSMetric.java index 504b7a05..1d1575ea 100644 --- a/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsSMetric.java +++ b/src/eva2/server/go/operators/archiving/RemoveSurplusIndividualsSMetric.java @@ -49,7 +49,9 @@ public class RemoveSurplusIndividualsSMetric implements InterfaceRemoveSurplusIn // now find the individual with the smallest hypervolume indexSmallHyperCube = 0; for (int i = 1; i < archive.size(); i++) { - if (space[i] < space[indexSmallHyperCube]) indexSmallHyperCube = i; + if (space[i] < space[indexSmallHyperCube]) { + indexSmallHyperCube = i; + } else { // if they are equal give them a fair chance to exchange between them if ((space[i] == space[indexSmallHyperCube]) && (RNG.flipCoin(0.5))) { @@ -167,12 +169,13 @@ public class RemoveSurplusIndividualsSMetric implements InterfaceRemoveSurplusIn double min = result[ global[ sort[ minIndex ] ]]; for (int f = 1; f < counter - 1; f++) { - if (!assigned[ sort[ 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; diff --git a/src/eva2/server/go/operators/classification/ClassificationSelfOrganizingMaps.java b/src/eva2/server/go/operators/classification/ClassificationSelfOrganizingMaps.java index f483704a..203429de 100644 --- a/src/eva2/server/go/operators/classification/ClassificationSelfOrganizingMaps.java +++ b/src/eva2/server/go/operators/classification/ClassificationSelfOrganizingMaps.java @@ -176,7 +176,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I winner = this.findWinningNeuron(space[i]); this.m_SOMClass[winner[0]][winner[1]][type[i]]++; } - if (this.debug) this.drawSOM(space, type); + if (this.debug) { + this.drawSOM(space, type); + } } /** This method updates a given winner neuron and it's neighbours @@ -491,7 +493,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I * @param t The number of neurons in x dimension */ public void setSizeX(int t) { - if (t < 1) t = 1; + if (t < 1) { + t = 1; + } this.m_Dim1 = t; } public int getSizeX() { @@ -505,7 +509,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I * @param t The number of neurons in y dimension */ public void setSizeY(int t) { - if (t < 1) t = 1; + if (t < 1) { + t = 1; + } this.m_Dim2 = t; } public int getSizeY() { @@ -518,7 +524,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I * @param t The number of training cycles */ public void setTrainingCycles(int t) { - if (t < 1) t = 1; + if (t < 1) { + t = 1; + } this.m_TrainingCycles = t; } public int getTrainingCycles() { @@ -531,7 +539,9 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I * @param t The size of the neighborhood */ public void setNeighborhoodSize(int t) { - if (t < 0) t = 0; + if (t < 0) { + t = 0; + } this.m_NeighborhoodSize = t; } public int getNeighborhoodSize() { @@ -544,8 +554,12 @@ public class ClassificationSelfOrganizingMaps implements java.io.Serializable, I * @param t The initial alpha value */ public void setAlpha(double t) { - if (t < 0) t = 0; - if (t > 0.5) t = 0.5; + if (t < 0) { + t = 0; + } + if (t > 0.5) { + t = 0.5; + } this.m_Alpha = t; } public double getAlpha() { diff --git a/src/eva2/server/go/operators/cluster/ClusterAll.java b/src/eva2/server/go/operators/cluster/ClusterAll.java index 078e8886..c700c3b7 100644 --- a/src/eva2/server/go/operators/cluster/ClusterAll.java +++ b/src/eva2/server/go/operators/cluster/ClusterAll.java @@ -40,10 +40,16 @@ public class ClusterAll implements InterfaceClustering, Serializable { 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); + if (assignLoners) { + Arrays.fill(indices, 0); + } + else { + Arrays.fill(indices, -1); + } return indices; - } else return null; + } else { + return null; + } } /* diff --git a/src/eva2/server/go/operators/cluster/ClusteringDensityBased.java b/src/eva2/server/go/operators/cluster/ClusteringDensityBased.java index 1b7abc10..3b5af12b 100644 --- a/src/eva2/server/go/operators/cluster/ClusteringDensityBased.java +++ b/src/eva2/server/go/operators/cluster/ClusteringDensityBased.java @@ -56,23 +56,33 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, } public ClusteringDensityBased(ClusteringDensityBased a) { - if (a.m_Metric != null) this.m_Metric = (InterfaceDistanceMetric)a.m_Metric.clone(); + if (a.m_Metric != null) { + 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; 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 this.Clustered[i] = false; + if (a.Clustered[i]) { + this.Clustered[i] = true; + } + else { + this.Clustered[i] = false; + } } } if (a.ConnectionMatrix != null) { this.ConnectionMatrix = new boolean[a.ConnectionMatrix.length][a.ConnectionMatrix[0].length]; for (int i = 0; i < this.ConnectionMatrix.length; i++) { for (int j = 0; j < this.ConnectionMatrix[i].length; j++) { - if (a.ConnectionMatrix[i][j]) this.ConnectionMatrix[i][j] = true; - else this.ConnectionMatrix[i][j] = false; + if (a.ConnectionMatrix[i][j]) { + this.ConnectionMatrix[i][j] = true; + } + else { + this.ConnectionMatrix[i][j] = false; + } } } } @@ -128,8 +138,12 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, if (!Clustered[i]) { Cluster = (Population)template.clone(); this.addRowToPopulation(i, Cluster, pop); - if (Cluster.size() >= this.m_MinimumGroupSize) ClusteredPopulations.add(Cluster); - else PopulationOfUnclustered.addPopulation(Cluster); + if (Cluster.size() >= this.m_MinimumGroupSize) { + ClusteredPopulations.add(Cluster); + } + else { + PopulationOfUnclustered.addPopulation(Cluster); + } } } @@ -173,8 +187,12 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, Population tmpPop = new Population(species1.size()+species2.size()); tmpPop.addPopulation(species1); tmpPop.addPopulation(species2); - if (this.cluster(tmpPop, referencePop).length <= 2) return true; - else return false; + if (this.cluster(tmpPop, referencePop).length <= 2) { + return true; + } + else { + return false; + } } } @@ -216,7 +234,9 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, 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; + if (minDist<0 || (iDist.tail() < minDist)) { + res[l]=spI; + } } } // end for all species } // end for all loners @@ -261,7 +281,9 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, return this.m_MinimumGroupSize; } public void setMinimumGroupSize(int m){ - if (m < 1) m = 1; + if (m < 1) { + m = 1; + } this.m_MinimumGroupSize = m; } public String minimumGroupSizeTipText() { @@ -279,7 +301,9 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam, } @Override public void setClustDistParam(double m) { - if (m < 0) m = 0; + if (m < 0) { + m = 0; + } this.m_ClusterDistance = m; } public String clustDistTipText() { diff --git a/src/eva2/server/go/operators/cluster/ClusteringDynPeakIdent.java b/src/eva2/server/go/operators/cluster/ClusteringDynPeakIdent.java index c1726578..17e9fe92 100644 --- a/src/eva2/server/go/operators/cluster/ClusteringDynPeakIdent.java +++ b/src/eva2/server/go/operators/cluster/ClusteringDynPeakIdent.java @@ -50,8 +50,12 @@ public class ClusteringDynPeakIdent implements InterfaceClustering, java.io.Seri this.maxNicheCount = numIndiesPerPeak; this.nicheRadius = nicheRad; this.strictNicheRadius = strictRad; - if (metric==null && (alternativeMetric==null)) metric=new PhenotypeMetric(); - else if (alternativeMetric!=null) metric=alternativeMetric; + if (metric==null && (alternativeMetric==null)) { + metric=new PhenotypeMetric(); + } + else if (alternativeMetric!=null) { + metric=alternativeMetric; + } } public ClusteringDynPeakIdent(ClusteringDynPeakIdent o) { @@ -91,7 +95,9 @@ public class ClusteringDynPeakIdent implements InterfaceClustering, java.io.Seri // 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()0) clusters[i].add(peaks.getEAIndividual(i-1)); // add peaks to clusters! + 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); @@ -185,11 +193,15 @@ public class ClusteringDynPeakIdent implements InterfaceClustering, java.io.Seri 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: "); + if (TRACE) { + System.out.print("Adding peaks: "); + } while (i this.distance(pop.getEAIndividual(i), this.m_C[j])) -// if (this.distance(this.m_C[assign], data[i]) > this.distance(this.m_C[j], data[i])) + if (this.distance(pop.getEAIndividual(i), this.m_C[assign]) > this.distance(pop.getEAIndividual(i), this.m_C[j])) { assign = j; + } } assignment[i] = assign; } @@ -126,13 +130,19 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab for (int i = 0; i < assignment.length; i++) { numbOfAssigned[assignment[i]]++; for (int j = 0; j < newC[assignment[i]].length; j++) { - if (m_UseSearchSpace) newC[assignment[i]][j] += pop.getEAIndividual(i).getDoublePosition()[j]; - else newC[assignment[i]][j] += pop.getEAIndividual(i).getFitness(j); + if (m_UseSearchSpace) { + newC[assignment[i]][j] += pop.getEAIndividual(i).getDoublePosition()[j]; + } + else { + newC[assignment[i]][j] += pop.getEAIndividual(i).getFitness(j); + } } } for (int i = 0; i < newC.length; i++) { for (int j = 0; j < newC[i].length; j++) { - if (numbOfAssigned[i] > 1) newC[i][j] /= (double)numbOfAssigned[i]; + if (numbOfAssigned[i] > 1) { + newC[i][j] /= (double)numbOfAssigned[i]; + } //else System.out.println("Someone was not assigned any data!? "+ i +" "+numbOfAssigned[i] + ": Data.size()="+data.length); } } @@ -183,7 +193,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab double[] x = pop.getEAIndividual(i).getDoublePosition(); myPoint = new DPoint(x[0], x[1]); tmp = new Chart2DDPointIconText(""+assignment[i]); - if (assignment[i] % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); + if (assignment[i] % 2 == 0) { + tmp.setIcon(new Chart2DDPointIconCircle()); + } myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } @@ -191,7 +203,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab // finally let's check whether or not the C changed and if i can terminate k_Means finished = true; for (int i = 0; i < this.m_C.length; i++) { - if (EuclideanMetric.euclideanDistance(this.m_C[i], newC[i]) > 0.0001) finished = false; + if (EuclideanMetric.euclideanDistance(this.m_C[i], newC[i]) > 0.0001) { + finished = false; + } this.m_C[i] = newC[i]; } } // gosh now i'm done @@ -218,7 +232,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab double[] x = ((InterfaceDataTypeDouble)result[i].get(j)).getDoubleData(); myPoint = new DPoint(x[0], x[1]); tmp = new Chart2DDPointIconText(""+i); - if (i % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); + if (i % 2 == 0) { + tmp.setIcon(new Chart2DDPointIconCircle()); + } myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } @@ -229,7 +245,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab int largeEnough = 0; // count clusters that are large enough for (int i=0; i=getMinClustSize()) largeEnough++; + if (result[i].size()>=getMinClustSize()) { + largeEnough++; + } } Population[] resExpanded = new Population[largeEnough+1]; resExpanded[0]=pop.cloneWithoutInds(); @@ -238,7 +256,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab if (result[i].size()>=getMinClustSize()) { resExpanded[lastIndex]=result[i]; lastIndex++; - } else resExpanded[0].addPopulation(result[i]); + } else { + resExpanded[0].addPopulation(result[i]); + } } tmpIndy=null; return resExpanded; @@ -252,7 +272,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab * @return The clusters as populations */ public Population[] cluster(Population pop, double[][] c) { - if (tmpIndy==null) tmpIndy=(AbstractEAIndividual)pop.getEAIndividual(0).clone(); // nec. only because the method is public... + if (tmpIndy==null) { + tmpIndy=(AbstractEAIndividual)pop.getEAIndividual(0).clone(); + } // nec. only because the method is public... Population[] result = new Population[c.length]; // double[][] data = this.extractClusterDataFrom(pop); int clusterAssigned; @@ -271,8 +293,9 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab // find the closest c clusterAssigned = 0; for (int j = 1; j < c.length; j++) { - if (this.distance(pop.getEAIndividual(i), c[clusterAssigned]) > this.distance(pop.getEAIndividual(i), c[j])) + if (this.distance(pop.getEAIndividual(i), c[clusterAssigned]) > this.distance(pop.getEAIndividual(i), c[j])) { clusterAssigned = j; + } } result[clusterAssigned].add(pop.get(i)); } @@ -285,8 +308,12 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab * @return The scalar distances between d1 and d2 */ private double distance(AbstractEAIndividual indy, double[] p) { - if (m_UseSearchSpace) ((InterfaceDataTypeDouble)tmpIndy).SetDoubleGenotype(p); - else tmpIndy.setFitness(p); + if (m_UseSearchSpace) { + ((InterfaceDataTypeDouble)tmpIndy).SetDoubleGenotype(p); + } + else { + tmpIndy.setFitness(p); + } return metric.distance(indy, tmpIndy); } @@ -322,8 +349,12 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab @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()) 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 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(); + if (children[uplink[i]]==null) { + children[uplink[i]]=new Vector(); + } children[uplink[i]].add(i); edgeLengthSum+=uplinkDist[i]; edgeCnt++; @@ -324,10 +360,14 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl // 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); + if (TRACE) { + System.out.println("Assigned " + current); + } addChildren(children[current].get(i), clustered, sorted, currentClust); } else { - if (TRACE) System.out.println("Not assigned " + current); + if (TRACE) { + System.out.println("Not assigned " + current); + } } } } else { @@ -336,8 +376,12 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl } private double currentDistThreshold() { - if (thresholdMultipleOfMeanDist) return meanDistFactor*currentMeanDistance; - else return absoluteDistThreshold; + if (thresholdMultipleOfMeanDist) { + return meanDistFactor*currentMeanDistance; + } + else { + return absoluteDistThreshold; + } } /** This method allows you to decide if two species converge. @@ -349,14 +393,22 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl public boolean mergingSpecies(Population species1, Population species2, Population referenceSet) { getRefData(referenceSet, species1); if (testConvergingSpeciesOnBestOnly) { - if (this.metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < this.currentDistThreshold()) return true; - else return false; + if (this.metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < this.currentDistThreshold()) { + return true; + } + else { + return false; + } } else { Population tmpPop = new Population(species1.size()+species2.size()); tmpPop.addPopulation(species1); tmpPop.addPopulation(species2); - if (this.cluster(tmpPop, referenceSet).length <= 2) return true; - else return false; + if (this.cluster(tmpPop, referenceSet).length <= 2) { + return true; + } + else { + return false; + } } } diff --git a/src/eva2/server/go/operators/cluster/ClusteringXMeans.java b/src/eva2/server/go/operators/cluster/ClusteringXMeans.java index cfdea4a5..8254e5a4 100644 --- a/src/eva2/server/go/operators/cluster/ClusteringXMeans.java +++ b/src/eva2/server/go/operators/cluster/ClusteringXMeans.java @@ -97,7 +97,9 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab x = ((InterfaceDataTypeDouble)tmpResults[i][k].get(l)).getDoubleData(); myPoint = new DPoint(x[0], x[1]); tmp = new Chart2DDPointIconText(""+k); - if (k % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); + if (k % 2 == 0) { + tmp.setIcon(new Chart2DDPointIconCircle()); + } myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } @@ -107,7 +109,9 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab 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); - if (k % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); + if (k % 2 == 0) { + tmp.setIcon(new Chart2DDPointIconCircle()); + } myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } @@ -172,7 +176,9 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab private double calculateSigma(double[][] data, double[] mean) { double result = 0; - if (data.length == 1) return 1.0; + if (data.length == 1) { + return 1.0; + } for (int i = 0; i < data.length; i++) { result += Math.pow(this.distance(data[i], mean), 2); @@ -275,8 +281,9 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab // find the closest c clusterAssigned = 0; for (int j = 1; j < c.length; j++) { - if (this.distance(data[i], c[clusterAssigned]) > this.distance(data[i], c[j])) + if (this.distance(data[i], c[clusterAssigned]) > this.distance(data[i], c[j])) { clusterAssigned = j; + } } result[clusterAssigned].add(pop.get(i)); } @@ -366,7 +373,9 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab return this.m_MaxK; } public void setMaxK(int m){ - if (m < 1) m = 1; + if (m < 1) { + m = 1; + } this.m_MaxK = m; } public String maxKTipText() { diff --git a/src/eva2/server/go/operators/constraint/AbstractConstraint.java b/src/eva2/server/go/operators/constraint/AbstractConstraint.java index 21227d82..ccaa40f4 100644 --- a/src/eva2/server/go/operators/constraint/AbstractConstraint.java +++ b/src/eva2/server/go/operators/constraint/AbstractConstraint.java @@ -94,7 +94,9 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S } } case specificTag: - if (v>0) indy.addConstraintViolation(v); + if (v>0) { + indy.addConstraintViolation(v); + } break; } currentIndy=null; @@ -120,7 +122,9 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S protected double[] getIndyDblData(String key) { if (currentIndy!=null) { Object dat = currentIndy.getData(key); - if (dat!=null && (dat instanceof double[])) return (double[])dat; + 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; @@ -156,8 +160,12 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S return (val <= 0.) ? 0 : val; case eqZero: val = Math.abs(val); - if (val<=equalityEpsilon) return 0.; - else return val; + if (val<=equalityEpsilon) { + return 0.; + } + else { + return val; + } case greaterEqZero: return (val >= 0.) ? 0. : -val; } @@ -193,7 +201,9 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S 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"); + if (!penaltyPropName.equals(penaltyAdaption.getControlledParam())) { + System.err.println("Warning: penalty factor control may have different target"); + } } } paramCtrl.setSingleAdapters(new ParamAdaption[]{penaltyAdaption}); @@ -210,7 +220,9 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S public void setPenaltyFactor(double penaltyFactor) { if (penaltyFactor<0) { EVAERROR.errorMsgOnce("Error: a negative penalty factor is not allowed!"); - } else this.penaltyFactor = penaltyFactor; + } else { + this.penaltyFactor = penaltyFactor; + } } public String penaltyFactorTipText() { diff --git a/src/eva2/server/go/operators/constraint/ConstBelongsToDifferentClass.java b/src/eva2/server/go/operators/constraint/ConstBelongsToDifferentClass.java index 5ab07881..637ffd73 100644 --- a/src/eva2/server/go/operators/constraint/ConstBelongsToDifferentClass.java +++ b/src/eva2/server/go/operators/constraint/ConstBelongsToDifferentClass.java @@ -60,7 +60,9 @@ public class ConstBelongsToDifferentClass implements InterfaceConstraint, java.i } double distanceToMyClass = this.distance(data, this.m_Class); for (int i = 0; i < this.m_OtherClasses.length; i++) { - if (distanceToMyClass > this.distance(data, this.m_OtherClasses[i])) return false; + if (distanceToMyClass > this.distance(data, this.m_OtherClasses[i])) { + return false; + } } return true; } diff --git a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanLinear.java b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanLinear.java index f2202111..8bc9928e 100644 --- a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanLinear.java +++ b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanLinear.java @@ -39,9 +39,15 @@ public class ConstObjectivesInEqualityBiggerThanLinear implements InterfaceConst @Override public boolean isValid(AbstractEAIndividual indy) { double[] d = indy.getFitness(); - if (d.length != 2) return true; - if ((this.m*d[0] + this.b) < d[1]) return true; - else return false; + if (d.length != 2) { + return true; + } + if ((this.m*d[0] + this.b) < d[1]) { + return true; + } + else { + return false; + } } } diff --git a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanSurface.java b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanSurface.java index 3a8214dd..2c631bcc 100644 --- a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanSurface.java +++ b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityBiggerThanSurface.java @@ -39,8 +39,12 @@ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceCons @Override public boolean isValid(AbstractEAIndividual indy) { double[] d = indy.getFitness(); - if (this.getScalarProduct(norm, this.getSubstraction(d, base)) >= 0) return true; - else return false; + if (this.getScalarProduct(norm, this.getSubstraction(d, base)) >= 0) { + return true; + } + else { + return false; + } } private double[] getSubstraction(double[] a, double[] b) { diff --git a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityLesserThanLinear.java b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityLesserThanLinear.java index 83b28ad7..38848cac 100644 --- a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityLesserThanLinear.java +++ b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualityLesserThanLinear.java @@ -39,8 +39,14 @@ public class ConstObjectivesInEqualityLesserThanLinear implements InterfaceConst @Override public boolean isValid(AbstractEAIndividual indy) { double[] d = indy.getFitness(); - if (d.length != 2) return true; - if ((this.m*d[0] + this.b) > d[1]) return true; - else return false; + if (d.length != 2) { + return true; + } + if ((this.m*d[0] + this.b) > d[1]) { + return true; + } + else { + return false; + } } } \ No newline at end of file diff --git a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualitySmallerThanSurface.java b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualitySmallerThanSurface.java index 8a70e930..749dd92d 100644 --- a/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualitySmallerThanSurface.java +++ b/src/eva2/server/go/operators/constraint/ConstObjectivesInEqualitySmallerThanSurface.java @@ -39,8 +39,12 @@ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceCon @Override public boolean isValid(AbstractEAIndividual indy) { double[] d = indy.getFitness(); - if (this.getScalarProduct(norm, this.getSubstraction(d, base)) < 0) return true; - else return false; + if (this.getScalarProduct(norm, this.getSubstraction(d, base)) < 0) { + return true; + } + else { + return false; + } } private double[] getSubstraction(double[] a, double[] b) { diff --git a/src/eva2/server/go/operators/constraint/ConstraintCollection.java b/src/eva2/server/go/operators/constraint/ConstraintCollection.java index 3c523e68..bc5089e6 100644 --- a/src/eva2/server/go/operators/constraint/ConstraintCollection.java +++ b/src/eva2/server/go/operators/constraint/ConstraintCollection.java @@ -42,11 +42,15 @@ public class ConstraintCollection extends AbstractConstraint { @Override protected double getRawViolationValue(double[] indyX) { double v, sum=0; - if (TRACE) System.out.println("Viol (pen "+getPenaltyFactor()+")"); + if (TRACE) { + System.out.println("Viol (pen "+getPenaltyFactor()+")"); + } for (AbstractConstraint constr : constraintArray) { v=constr.getViolation(indyX); sum += v; - if (TRACE) System.out.println(constr.getClass().getSimpleName() + " " + v); + if (TRACE) { + System.out.println(constr.getClass().getSimpleName() + " " + v); + } } return sum; } diff --git a/src/eva2/server/go/operators/constraint/GenericConstraint.java b/src/eva2/server/go/operators/constraint/GenericConstraint.java index 75409d4c..41aa7bab 100644 --- a/src/eva2/server/go/operators/constraint/GenericConstraint.java +++ b/src/eva2/server/go/operators/constraint/GenericConstraint.java @@ -59,7 +59,9 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo private void compileConstraint() { func=null; constraintProgram = AbstractGPNode.parseFromString(constraintString); - if (constraintProgram==null) System.err.println("Error: invalid expression: " + constraintString); + if (constraintProgram==null) { + System.err.println("Error: invalid expression: " + constraintString); + } if (TRACE) { System.out.println("Compiled constraint " + constraintString); System.out.println("Program: " + constraintProgram.getStringRepresentation()); @@ -71,7 +73,9 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo * @return */ public boolean checkValid() { - if (constraintProgram==null) compileConstraint(); + if (constraintProgram==null) { + compileConstraint(); + } return (constraintProgram!=null); } @@ -81,11 +85,17 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo case eqZero: case greaterEqZero: case lessEqZero: - if (constraintProgram==null) compileConstraint(); + if (constraintProgram==null) { + compileConstraint(); + } if (constraintProgram!=null) { - if (func==null) func = new GPFunctionProblem(constraintProgram, null, indyX.length, 0., 0.); + if (func==null) { + func = new GPFunctionProblem(constraintProgram, null, indyX.length, 0., 0.); + } return func.eval(indyX)[0]; - } else return 0.; + } else { + return 0.; + } // case linearLessEqZero: // return getViolation(evalLinearConstr(indy)); } @@ -100,7 +110,9 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo public void setConstraintString(String constraintString) { this.constraintString = constraintString; constraintProgram = null; - if (TRACE) System.out.println(" NEW CONSTRAINT STRING SET! in " + this); + if (TRACE) { + System.out.println(" NEW CONSTRAINT STRING SET! in " + this); + } } public String getName() { diff --git a/src/eva2/server/go/operators/constraint/ImplicitConstraint.java b/src/eva2/server/go/operators/constraint/ImplicitConstraint.java index c47ff189..1d86d8cd 100644 --- a/src/eva2/server/go/operators/constraint/ImplicitConstraint.java +++ b/src/eva2/server/go/operators/constraint/ImplicitConstraint.java @@ -44,8 +44,12 @@ public class ImplicitConstraint extends AbstractConstraint { } public void setIndex(int index) { - if (index>0) this.index = index; - else System.err.println("Error, invalid index (<=0) in ImplicitConstraint."); + if (index>0) { + this.index = index; + } + else { + System.err.println("Error, invalid index (<=0) in ImplicitConstraint."); + } } public String indexTipText() { diff --git a/src/eva2/server/go/operators/constraint/IntervalConstraint.java b/src/eva2/server/go/operators/constraint/IntervalConstraint.java index abd6c8ed..62a410a8 100644 --- a/src/eva2/server/go/operators/constraint/IntervalConstraint.java +++ b/src/eva2/server/go/operators/constraint/IntervalConstraint.java @@ -74,10 +74,16 @@ public class IntervalConstraint extends AbstractConstraint implements InterfaceD public String getName() { String clsName=this.getClass().getSimpleName(); - if (genericConstr!=null) return clsName+"/"+genericConstr.getConstraintString()+ " in ["+lower+","+upper+"]"; + 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+"]"; + if (index<0) { + return clsName+"/x_i in ["+lower+","+upper+"]"; + } + else { + return clsName+"/x_" + index + " in ["+lower+","+upper+"]"; + } } } @@ -107,13 +113,21 @@ public class IntervalConstraint extends AbstractConstraint implements InterfaceD public void setGenericFunction(String str) { if (str!=null && (str.length()>0)) { genericConstr = new GenericConstraint(str); - if (!genericConstr.checkValid()) genericConstr=null; - } else genericConstr=null; + if (!genericConstr.checkValid()) { + genericConstr=null; + } + } else { + genericConstr=null; + } } public String getGenericFunction() { - if (genericConstr==null) return ""; - else return genericConstr.getConstraintString(); + if (genericConstr==null) { + return ""; + } + else { + return genericConstr.getConstraintString(); + } } public String genericConstrTipText() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverEAMixer.java b/src/eva2/server/go/operators/crossover/CrossoverEAMixer.java index dd7159ad..f7789e8c 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverEAMixer.java +++ b/src/eva2/server/go/operators/crossover/CrossoverEAMixer.java @@ -87,7 +87,9 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating CrossoverEAMixer mut = (CrossoverEAMixer)mutator; return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the crossover operator @@ -114,8 +116,12 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating if (this.m_UseSelfAdaption) { for (int i = 0; i < probs.length; i++) { probs[i] *= Math.exp(this.m_Tau1 * RNG.gaussianDouble(1)); - if (probs[i] <= this.m_LowerLimitChance) probs[i] = this.m_LowerLimitChance; - if (probs[i] >= 1) probs[i] = 1; + if (probs[i] <= this.m_LowerLimitChance) { + probs[i] = this.m_LowerLimitChance; + } + if (probs[i] >= 1) { + probs[i] = 1; + } } this.m_Crossers.normalizeWeights(); } @@ -128,7 +134,9 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating lastOperatorIndex++; dum += probs[lastOperatorIndex]; } - if (lastOperatorIndex == probs.length) lastOperatorIndex = RNG.randomInt(0, probs.length-1); + if (lastOperatorIndex == probs.length) { + 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]); @@ -208,7 +216,9 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating * @param d The mutation operator. */ public void setLowerLimitChance(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitChance = d; } public double getLowerLimitChance() { @@ -222,7 +232,9 @@ public class CrossoverEAMixer implements InterfaceCrossover, InterfaceEvaluating * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESArithmetical.java b/src/eva2/server/go/operators/crossover/CrossoverESArithmetical.java index 9053573e..6f3b7b56 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESArithmetical.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESArithmetical.java @@ -100,8 +100,12 @@ public class CrossoverESArithmetical implements InterfaceCrossover, java.io.Seri */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESArithmetical) return true; - else return false; + if (crossover instanceof CrossoverESArithmetical) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverESBLXAlpha.java b/src/eva2/server/go/operators/crossover/CrossoverESBLXAlpha.java index 7ad7897e..c263c9ac 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESBLXAlpha.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESBLXAlpha.java @@ -97,10 +97,14 @@ public class CrossoverESBLXAlpha implements InterfaceCrossover, java.io.Serializ public boolean equals(Object crossover) { if (crossover instanceof CrossoverESBLXAlpha) { CrossoverESBLXAlpha cross = (CrossoverESBLXAlpha)crossover; - if (this.m_Alpha != cross.m_Alpha) return false; + if (this.m_Alpha != cross.m_Alpha) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -142,7 +146,9 @@ public class CrossoverESBLXAlpha implements InterfaceCrossover, java.io.Serializ * @param a The number of crossovers. */ public void setAlpha(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Alpha = a; } public double getAlpha() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESDefault.java b/src/eva2/server/go/operators/crossover/CrossoverESDefault.java index 9f44ae0c..d56aad50 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESDefault.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESDefault.java @@ -96,8 +96,12 @@ public class CrossoverESDefault implements InterfaceCrossover, java.io.Serializa */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESDefault) return true; - else return false; + if (crossover instanceof CrossoverESDefault) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverESFlat.java b/src/eva2/server/go/operators/crossover/CrossoverESFlat.java index 9a10efec..e92e4e15 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESFlat.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESFlat.java @@ -99,8 +99,12 @@ public class CrossoverESFlat implements InterfaceCrossover, java.io.Serializable */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESFlat) return true; - else return false; + if (crossover instanceof CrossoverESFlat) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverESIntermediate.java b/src/eva2/server/go/operators/crossover/CrossoverESIntermediate.java index 2b208e48..21a93e71 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESIntermediate.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESIntermediate.java @@ -86,8 +86,12 @@ public class CrossoverESIntermediate implements InterfaceCrossover, java.io.Seri */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESIntermediate) return true; - else return false; + if (crossover instanceof CrossoverESIntermediate) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscrete.java b/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscrete.java index 6b77e506..44feadf0 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscrete.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscrete.java @@ -68,7 +68,9 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se } for (int i = 0; i < length; i++) { for (int j = 0; j < this.m_NumberOfCrossovers; j++) { - if (i == crossoverPoints[j]) mixer++; + if (i == crossoverPoints[j]) { + mixer++; + } } for (int j = 0; j < children.length; j++) { children[j][i] = parents[(j + mixer) % parents.length][i]; @@ -96,10 +98,14 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se public boolean equals(Object crossover) { if (crossover instanceof CrossoverESNPointDiscrete) { CrossoverESNPointDiscrete cross = (CrossoverESNPointDiscrete)crossover; - if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) return false; + if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -141,7 +147,9 @@ public class CrossoverESNPointDiscrete implements InterfaceCrossover, java.io.Se * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { - if (crossovers < 0) crossovers = 0; + if (crossovers < 0) { + crossovers = 0; + } this.m_NumberOfCrossovers = crossovers; } public int getNumberOfCrossovers() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscreteDislocation.java b/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscreteDislocation.java index afbb86e3..09433073 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscreteDislocation.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESNPointDiscreteDislocation.java @@ -81,10 +81,14 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, parIndex++; chiIndex++; for (int j = 0; j < crossoverPoints.length; j++) { - if ((parIndex == crossoverPoints[j]) || (parIndex == length) || (chiIndex == length)) bol = true; + if ((parIndex == crossoverPoints[j]) || (parIndex == length) || (chiIndex == length)) { + bol = true; + } } } - if (chiIndex == length) i = crossoverPoints.length; + if (chiIndex == length) { + i = crossoverPoints.length; + } mixer++; } @@ -109,9 +113,13 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, public boolean equals(Object crossover) { if (crossover instanceof CrossoverESNPointDiscreteDislocation) { CrossoverESNPointDiscreteDislocation cross = (CrossoverESNPointDiscreteDislocation)crossover; - if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) return false; + if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -153,7 +161,9 @@ public class CrossoverESNPointDiscreteDislocation implements InterfaceCrossover, * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { - if (crossovers < 0) crossovers = 0; + if (crossovers < 0) { + crossovers = 0; + } this.m_NumberOfCrossovers = crossovers; } public int getNumberOfCrossovers() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESPCX.java b/src/eva2/server/go/operators/crossover/CrossoverESPCX.java index 4da71c4f..074200bf 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESPCX.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESPCX.java @@ -141,7 +141,9 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable toro = Mathematics.svMult(tmpD, toro); tmpVec = Mathematics.vvSub(tmpVec, toro); } - if (this.isValidVec(tmpVec)) result.add(tmpVec); + if (this.isValidVec(tmpVec)) { + result.add(tmpVec); + } } } } @@ -168,11 +170,17 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable private boolean isValidVec(double[] d) { double sum = 0; for (int i = 0; i < d.length; i++) { - if (Double.isNaN(d[i])) return false; + if (Double.isNaN(d[i])) { + return false; + } sum += Math.pow(d[i],2); } - if (Double.isNaN(sum)) return false; - if (Math.abs(sum) < 0.000000000000000001) return false; + if (Double.isNaN(sum)) { + return false; + } + if (Math.abs(sum) < 0.000000000000000001) { + return false; + } return true; } @@ -182,8 +190,12 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESUNDX) return true; - else return false; + if (crossover instanceof CrossoverESUNDX) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -271,7 +283,9 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); - if (plotFlag) plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); + if (plotFlag) { + 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]+"]"); } @@ -300,7 +314,9 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable return "This is the Parent Centric Crossover (PCX)."; } public void setEta(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Eta = a; } public double getEta() { @@ -310,7 +326,9 @@ public class CrossoverESPCX implements InterfaceCrossover, java.io.Serializable return "The Eta of PCX."; } public void setZeta(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Zeta = a; } public double getZeta() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESSBX.java b/src/eva2/server/go/operators/crossover/CrossoverESSBX.java index 591a90f7..73320bbc 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESSBX.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESSBX.java @@ -100,10 +100,14 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable public boolean equals(Object crossover) { if (crossover instanceof CrossoverESSBX) { CrossoverESSBX cross = (CrossoverESSBX)crossover; - if (this.m_Eta != cross.m_Eta) return false; + if (this.m_Eta != cross.m_Eta) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -210,7 +214,9 @@ public class CrossoverESSBX implements InterfaceCrossover, java.io.Serializable * @param a The number of crossovers. */ public void setEta(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Eta = a; } public double getEta() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESSPX.java b/src/eva2/server/go/operators/crossover/CrossoverESSPX.java index fbf972bb..7fcc5dba 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESSPX.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESSPX.java @@ -109,8 +109,12 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESSPX) return true; - else return false; + if (crossover instanceof CrossoverESSPX) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -197,7 +201,9 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); - if (plotFlag) plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); + if (plotFlag) { + 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]+"]"); } @@ -227,7 +233,9 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable } public void setEpsilon(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Epsilon = a; } public double getEpsilon() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESUNDX.java b/src/eva2/server/go/operators/crossover/CrossoverESUNDX.java index 6102c87b..4c6d8a9d 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESUNDX.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESUNDX.java @@ -145,7 +145,9 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable toro = Mathematics.svMult(tmpD, toro); tmpVec = Mathematics.vvSub(tmpVec, toro); } - if (Mathematics.isValidVec(tmpVec)) result.add(tmpVec); + if (Mathematics.isValidVec(tmpVec)) { + result.add(tmpVec); + } } } } @@ -191,8 +193,12 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESUNDX) return true; - else return false; + if (crossover instanceof CrossoverESUNDX) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -280,7 +286,9 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable offsprings = cross.mate(indy1, pop); for (int j = 0; j < offsprings.length; j++) { tmpD = ((ESIndividualDoubleData)offsprings[j]).getDoubleData(); - if (plotFlag) plot.setUnconnectedPoint(tmpD[0], tmpD[1], 1); + if (plotFlag) { + 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]+"]"); } @@ -309,7 +317,9 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable 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; + if (a < 0) { + a = 0; + } this.m_Eta = a; } public double getEta() { @@ -319,7 +329,9 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable return "The Eta of UNDX (=0,35/Math,sqrt(n-l-2))."; } public void setZeta(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Zeta = a; } public double getZeta() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverESUniformDiscrete.java b/src/eva2/server/go/operators/crossover/CrossoverESUniformDiscrete.java index 725cb868..ace5cd7b 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverESUniformDiscrete.java +++ b/src/eva2/server/go/operators/crossover/CrossoverESUniformDiscrete.java @@ -88,8 +88,12 @@ public class CrossoverESUniformDiscrete implements InterfaceCrossover, java.io.S */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESUniformDiscrete) return true; - else return false; + if (crossover instanceof CrossoverESUniformDiscrete) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverGABitSimulated.java b/src/eva2/server/go/operators/crossover/CrossoverGABitSimulated.java index a3843f09..5c9d1976 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGABitSimulated.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGABitSimulated.java @@ -45,7 +45,9 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri for (int i = 0; i < partners.size(); i++) { result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); } - if (partners.size() == 0) return result; + 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(); @@ -63,12 +65,18 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri for (int i = 0; i < length; i++) { current = 0; for (int j = 0; j < tmpBitSet[0].length; j++) { - if (tmpBitSet[0][j].get(i)) current++; + if (tmpBitSet[0][j].get(i)) { + current++; + } } current /= (double)(tmpBitSet[0].length); for (int j = 0; j < tmpBitSet[0].length; j++) { - if (RNG.flipCoin(current)) tmpBitSet[1][j].set(i); - else tmpBitSet[1][j].clear(i); + if (RNG.flipCoin(current)) { + tmpBitSet[1][j].set(i); + } + else { + tmpBitSet[1][j].clear(i); + } } } @@ -90,8 +98,12 @@ public class CrossoverGABitSimulated implements InterfaceCrossover, java.io.Seri */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverGABitSimulated) return true; - else return false; + if (crossover instanceof CrossoverGABitSimulated) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverGADefault.java b/src/eva2/server/go/operators/crossover/CrossoverGADefault.java index e93cce45..0ec14c8d 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGADefault.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGADefault.java @@ -57,7 +57,9 @@ public class CrossoverGADefault implements InterfaceCrossover, } // for (int i = 0; i < result.length; i++) System.out.println("Before // Crossover: " +result[i].getSolutionRepresentationFor()); - if (partners.size() == 0) return result; + if (partners.size() == 0) { + return result; + } if ((indy1 instanceof InterfaceGAIndividual) && (partners.get(0) instanceof InterfaceGAIndividual)) { // Currently we will only handle two parents @@ -69,15 +71,24 @@ public class CrossoverGADefault implements InterfaceCrossover, 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); + 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]); @@ -102,9 +113,12 @@ public class CrossoverGADefault implements InterfaceCrossover, */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverGADefault) - return true; - else return false; + if (crossover instanceof CrossoverGADefault) { + return true; + } + else { + return false; + } } /** diff --git a/src/eva2/server/go/operators/crossover/CrossoverGAGINPoint.java b/src/eva2/server/go/operators/crossover/CrossoverGAGINPoint.java index 59287f17..8555b545 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGAGINPoint.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGAGINPoint.java @@ -64,7 +64,9 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); } - if (partners.size() == 0) return result; + if (partners.size() == 0) { + return result; + } if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { int length = getGenotypeLength(individual); @@ -80,13 +82,19 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ 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)); + 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); - if (TRACE) System.out.println("CO points: " + BeanInspector.toString(crossoverPoints)); + if (TRACE) { + 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]) mixer++; // possibly switch partner to exchange with + if (i == crossoverPoints[j]) { + mixer++; + } // possibly switch partner to exchange with } for (int j = 0; j < origGenotypes.length; j++) { // loop individuals // exchange values at position i between indies @@ -97,7 +105,9 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ for (int i = 0; i < result.length; i++) { writeBack(result[i], newGenotypes[i]); } - if (TRACE) System.out.println("After CO: " + BeanInspector.toString(newGenotypes)); + if (TRACE) { + System.out.println("After CO: " + BeanInspector.toString(newGenotypes)); + } } return result; } @@ -214,9 +224,13 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ public boolean equals(Object crossover) { if (crossover instanceof CrossoverGAGINPoint) { CrossoverGAGINPoint cross = (CrossoverGAGINPoint)crossover; - if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) return false; + if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -258,7 +272,9 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { - if (crossovers < 0) crossovers = 0; + if (crossovers < 0) { + crossovers = 0; + } this.m_NumberOfCrossovers = crossovers; } public int getNumberOfCrossovers() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverGAGINPointSegmentwise.java b/src/eva2/server/go/operators/crossover/CrossoverGAGINPointSegmentwise.java index c127481f..57d9f142 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGAGINPointSegmentwise.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGAGINPointSegmentwise.java @@ -36,7 +36,9 @@ public class CrossoverGAGINPointSegmentwise extends CrossoverGAGINPoint { public boolean equals(Object crossover) { if (super.equals(crossover) && (crossover instanceof CrossoverGAGINPointSegmentwise)) { return ((CrossoverGAGINPointSegmentwise)crossover).segmentLength==this.segmentLength; - } else return false; + } else { + return false; + } } @Override diff --git a/src/eva2/server/go/operators/crossover/CrossoverGAUniform.java b/src/eva2/server/go/operators/crossover/CrossoverGAUniform.java index ef36384b..1809b76a 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGAUniform.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGAUniform.java @@ -45,7 +45,9 @@ public class CrossoverGAUniform implements InterfaceCrossover, java.io.Serializa for (int i = 0; i < partners.size(); i++) { result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); } - if (partners.size() == 0) return result; + 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(); @@ -63,8 +65,12 @@ public class CrossoverGAUniform implements InterfaceCrossover, java.io.Serializa for (int i = 0; i < length; i++) { mixer = RNG.randomInt(0, partners.size()); for (int j = 0; j < tmpBitSet[0].length; j++) { - if (tmpBitSet[0][(j + mixer) % tmpBitSet[0].length].get(i)) tmpBitSet[1][j].set(i); - else tmpBitSet[1][j].clear(i); + if (tmpBitSet[0][(j + mixer) % tmpBitSet[0].length].get(i)) { + tmpBitSet[1][j].set(i); + } + else { + tmpBitSet[1][j].clear(i); + } } } @@ -86,8 +92,12 @@ public class CrossoverGAUniform implements InterfaceCrossover, java.io.Serializa */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverGAUniform) return true; - else return false; + if (crossover instanceof CrossoverGAUniform) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverGIDefault.java b/src/eva2/server/go/operators/crossover/CrossoverGIDefault.java index 8de10f64..823c8313 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGIDefault.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGIDefault.java @@ -51,7 +51,9 @@ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializa //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) return result; + if (((InterfaceGIIndividual)indy1).getIGenotype().length <= 1) { + return result; + } int crossoverpoint = RNG.randomInt(0,((InterfaceGIIndividual)indy1).getIGenotype().length-1); boolean switcher = RNG.randomBoolean(); parents = new int[partners.size()+1][]; @@ -69,11 +71,13 @@ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializa } 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]; + 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)) + if ((i < children[children.length-1].length) && (i < parents[0].length)) { children[children.length-1][i] = parents[0][i]; + } } } // write the result back @@ -95,8 +99,12 @@ public class CrossoverGIDefault implements InterfaceCrossover, java.io.Serializa */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverESDefault) return true; - else return false; + if (crossover instanceof CrossoverESDefault) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverGINPoint.java b/src/eva2/server/go/operators/crossover/CrossoverGINPoint.java index ae0a06aa..b41da251 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGINPoint.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGINPoint.java @@ -46,7 +46,9 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab for (int i = 0; i < partners.size(); i++) { result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); } - if (partners.size() == 0) return result; + 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(); @@ -69,7 +71,9 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab } for (int i = 0; i < length; i++) { for (int j = 0; j < this.m_NumberOfCrossovers; j++) { - if (i == crossoverPoints[j]) mixer++; + if (i == crossoverPoints[j]) { + mixer++; + } } for (int j = 0; j < tmpInts[0].length; j++) { if ((tmpInts[0][(j + mixer) % tmpInts[0].length].length > i) && @@ -99,9 +103,13 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab public boolean equals(Object crossover) { if (crossover instanceof CrossoverGINPoint) { CrossoverGINPoint cross = (CrossoverGINPoint)crossover; - if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) return false; + if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -143,7 +151,9 @@ public class CrossoverGINPoint implements InterfaceCrossover, java.io.Serializab * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { - if (crossovers < 0) crossovers = 0; + if (crossovers < 0) { + crossovers = 0; + } this.m_NumberOfCrossovers = crossovers; } public int getNumberOfCrossovers() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverGINPointVL.java b/src/eva2/server/go/operators/crossover/CrossoverGINPointVL.java index a5238602..f051d3e7 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGINPointVL.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGINPointVL.java @@ -47,7 +47,9 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ for (int i = 0; i < partners.size(); i++) { result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); } - if (partners.size() == 0) return result; + 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]; @@ -153,9 +155,13 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ public boolean equals(Object crossover) { if (crossover instanceof CrossoverGINPointVL) { CrossoverGINPointVL cross = (CrossoverGINPointVL)crossover; - if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) return false; + if (this.m_NumberOfCrossovers != cross.m_NumberOfCrossovers) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the @@ -197,7 +203,9 @@ public class CrossoverGINPointVL implements InterfaceCrossover, java.io.Serializ * @param crossovers The number of crossovers. */ public void setNumberOfCrossovers(int crossovers) { - if (crossovers < 0) crossovers = 0; + if (crossovers < 0) { + crossovers = 0; + } this.m_NumberOfCrossovers = crossovers; } public int getNumberOfCrossovers() { diff --git a/src/eva2/server/go/operators/crossover/CrossoverGIUniform.java b/src/eva2/server/go/operators/crossover/CrossoverGIUniform.java index 7166fa03..4019893c 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGIUniform.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGIUniform.java @@ -46,7 +46,9 @@ public class CrossoverGIUniform implements InterfaceCrossover, java.io.Serializa for (int i = 0; i < partners.size(); i++) { result[i+1] = (AbstractEAIndividual) ((AbstractEAIndividual)partners.get(i)).clone(); } - if (partners.size() == 0) return result; + 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(); @@ -90,8 +92,12 @@ public class CrossoverGIUniform implements InterfaceCrossover, java.io.Serializa */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverGIUniform) return true; - else return false; + if (crossover instanceof CrossoverGIUniform) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverGPDefault.java b/src/eva2/server/go/operators/crossover/CrossoverGPDefault.java index ff6f702e..2172f310 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverGPDefault.java +++ b/src/eva2/server/go/operators/crossover/CrossoverGPDefault.java @@ -48,17 +48,22 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa */ @Override public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners) { - if (partners.size()>1) System.err.println("Warning, crossover may not work on more than one partner! " + this.getClass()); + 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[0] = (AbstractEAIndividual) (indy1).clone(); for (int i = 0; i < partners.size(); i++) { 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()); + if (TRACE) { + for (int i = 0; i < result.length; i++) { + System.out.println("Before Crossover: " +result[i].getStringRepresentation()); + } } + if (partners.size() == 0) { + return result; } - if (partners.size() == 0) return result; if ((indy1 instanceof InterfaceGPIndividual) && (partners.get(0) instanceof InterfaceGPIndividual)) { int allowedDepth = ((InterfaceGPIndividual)indy1).getMaxAllowedDepth(); @@ -72,8 +77,12 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa // 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(); + 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 @@ -92,11 +101,19 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa selNodeOtherParent = selNodeOther.getParent(); // actually switch individuals! - if (selNodeThisParent == null) ((InterfaceGPIndividual)result[0]).SetPGenotype((AbstractGPNode)selNodeOther.clone(), t); - else selNodeThisParent.setNode((AbstractGPNode)selNodeOther.clone(), selNodeThis); + if (selNodeThisParent == null) { + ((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); + if (selNodeOtherParent == null) { + ((InterfaceGPIndividual)result[1]).SetPGenotype((AbstractGPNode)selNodeThis.clone(), t); + } + else { + selNodeOtherParent.setNode((AbstractGPNode)selNodeThis.clone(), selNodeOther); + } } } @@ -105,9 +122,10 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa ((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()); - } + if (TRACE) { + for (int i = 0; i < result.length; i++) { + System.out.println("After Crossover: " +result[i].getStringRepresentation()); + } } return result; } @@ -117,8 +135,12 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverGPDefault) return true; - else return false; + if (crossover instanceof CrossoverGPDefault) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/CrossoverOBGAPMX.java b/src/eva2/server/go/operators/crossover/CrossoverOBGAPMX.java index 30a2fa24..986b011c 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverOBGAPMX.java +++ b/src/eva2/server/go/operators/crossover/CrossoverOBGAPMX.java @@ -87,8 +87,12 @@ public class CrossoverOBGAPMX implements InterfaceCrossover, java.io.Serializabl */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverOBGAPMX) return true; - else return false; + if (crossover instanceof CrossoverOBGAPMX) { + return true; + } + else { + return false; + } } @Override diff --git a/src/eva2/server/go/operators/crossover/CrossoverOBGAPMXUniform.java b/src/eva2/server/go/operators/crossover/CrossoverOBGAPMXUniform.java index 8123c949..07cc99a7 100644 --- a/src/eva2/server/go/operators/crossover/CrossoverOBGAPMXUniform.java +++ b/src/eva2/server/go/operators/crossover/CrossoverOBGAPMXUniform.java @@ -83,8 +83,12 @@ public class CrossoverOBGAPMXUniform implements InterfaceCrossover, java.io.Seri */ @Override public boolean equals(Object crossover) { - if (crossover instanceof CrossoverOBGAPMXUniform) return true; - else return false; + if (crossover instanceof CrossoverOBGAPMXUniform) { + return true; + } + else { + return false; + } } diff --git a/src/eva2/server/go/operators/crossover/NoCrossover.java b/src/eva2/server/go/operators/crossover/NoCrossover.java index 669f57c6..a5e22fdc 100644 --- a/src/eva2/server/go/operators/crossover/NoCrossover.java +++ b/src/eva2/server/go/operators/crossover/NoCrossover.java @@ -57,8 +57,12 @@ public class NoCrossover implements InterfaceCrossover, java.io.Serializable { */ @Override public boolean equals(Object crossover) { - if (crossover instanceof NoCrossover) return true; - else return false; + if (crossover instanceof NoCrossover) { + return true; + } + else { + return false; + } } /** This method will allow the crossover operator to be initialized depending on the diff --git a/src/eva2/server/go/operators/crossover/PropertyCrossoverMixer.java b/src/eva2/server/go/operators/crossover/PropertyCrossoverMixer.java index 9410049d..0a565713 100644 --- a/src/eva2/server/go/operators/crossover/PropertyCrossoverMixer.java +++ b/src/eva2/server/go/operators/crossover/PropertyCrossoverMixer.java @@ -62,7 +62,9 @@ public class PropertyCrossoverMixer implements java.io.Serializable { return; } - if (d.length == this.m_Weights.length) return; + if (d.length == this.m_Weights.length) { + return; + } if (d.length > this.m_Weights.length) { double[] newWeights = new double[d.length]; @@ -142,7 +144,9 @@ public class PropertyCrossoverMixer implements java.io.Serializable { * @param index The index of the target to be removed. */ public void removeCrosser(int index) { - if ((index < 0) || (index >= this.m_SelectedTargets.length)) return; + 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]; diff --git a/src/eva2/server/go/operators/crossover/PropertyCrossoverMixerEditor.java b/src/eva2/server/go/operators/crossover/PropertyCrossoverMixerEditor.java index d5682ca1..8cd1c57c 100644 --- a/src/eva2/server/go/operators/crossover/PropertyCrossoverMixerEditor.java +++ b/src/eva2/server/go/operators/crossover/PropertyCrossoverMixerEditor.java @@ -86,13 +86,18 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceCrossover.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceCrossover.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -245,13 +250,18 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit try { 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); - if (newEdit[l].m_Editor instanceof GenericObjectEditor) + if (newEdit[l].m_Editor == null) { + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceCrossover.class); + } + if (newEdit[l].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) newEdit[l].m_Editor).setClassType(InterfaceCrossover.class); + } newEdit[l].m_Editor.setValue(newEdit[l].m_Value); newEdit[l].m_Editor.addPropertyChangeListener(m_self); AbstractObjectEditor.findViewFor(newEdit[l]); - if (newEdit[l].m_View != null) newEdit[l].m_View.repaint(); + if (newEdit[l].m_View != null) { + newEdit[l].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -268,7 +278,9 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit int l = m_CrossoversWithWeights.getSelectedCrossers().length, j = 0; 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); + if (event.getSource().equals(m_Delete[i])) { + m_CrossoversWithWeights.removeCrosser(i); + } else { newEdit[j] = m_Editors[i]; j++; @@ -444,13 +456,17 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit @Override public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); + 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); + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } m_Support.removePropertyChangeListener(l); } /** This will wait for the GenericObjectEditor to finish @@ -469,13 +485,18 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceCrossover.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceCrossover.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } diff --git a/src/eva2/server/go/operators/distancemetric/DoubleIntegralMetric.java b/src/eva2/server/go/operators/distancemetric/DoubleIntegralMetric.java index 87f0ab0d..ba80b5b6 100644 --- a/src/eva2/server/go/operators/distancemetric/DoubleIntegralMetric.java +++ b/src/eva2/server/go/operators/distancemetric/DoubleIntegralMetric.java @@ -51,7 +51,9 @@ public class DoubleIntegralMetric implements InterfaceDistanceMetric, Serializab 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()); + 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); } diff --git a/src/eva2/server/go/operators/distancemetric/GenotypeMetricBitSet.java b/src/eva2/server/go/operators/distancemetric/GenotypeMetricBitSet.java index 940f96f6..aab62a36 100644 --- a/src/eva2/server/go/operators/distancemetric/GenotypeMetricBitSet.java +++ b/src/eva2/server/go/operators/distancemetric/GenotypeMetricBitSet.java @@ -46,11 +46,17 @@ public class GenotypeMetricBitSet implements InterfaceDistanceMetric, java.io.Se dIndy1 = ((InterfaceGAIndividual) indy1).getBGenotype(); dIndy2 = ((InterfaceGAIndividual) indy2).getBGenotype(); length = Math.min(((InterfaceGAIndividual) indy1).getGenotypeLength(), ((InterfaceGAIndividual) indy2).getGenotypeLength()); - } else return 1.0; + } else { + return 1.0; + } for (int i = 0; i < length; i++) { - if (dIndy1.get(i) == dIndy2.get(i)) result += 0; - else result += 1; + if (dIndy1.get(i) == dIndy2.get(i)) { + result += 0; + } + else { + result += 1; + } } return result/(double)length; } diff --git a/src/eva2/server/go/operators/distancemetric/IndividualDataMetric.java b/src/eva2/server/go/operators/distancemetric/IndividualDataMetric.java index 0cefede5..b673cc26 100644 --- a/src/eva2/server/go/operators/distancemetric/IndividualDataMetric.java +++ b/src/eva2/server/go/operators/distancemetric/IndividualDataMetric.java @@ -46,7 +46,9 @@ public class IndividualDataMetric implements InterfaceDistanceMetric, Serializab @Override public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - if (dataKey==null) throw new RuntimeException("Error, no data key defined in " + this.getClass().getName() + "::distance()"); + 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); diff --git a/src/eva2/server/go/operators/distancemetric/PhenotypeMetric.java b/src/eva2/server/go/operators/distancemetric/PhenotypeMetric.java index 1d576cb2..cd801392 100644 --- a/src/eva2/server/go/operators/distancemetric/PhenotypeMetric.java +++ b/src/eva2/server/go/operators/distancemetric/PhenotypeMetric.java @@ -49,8 +49,12 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali // Step 1 n = s.length (); m = t.length (); - if (n == 0) return m; - if (m == 0) return n; + if (n == 0) { + return m; + } + if (m == 0) { + return n; + } d = new int[n+1][m+1]; // Step 2 @@ -68,7 +72,9 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali for (j = 1; j <= m; j++) { t_j = t.charAt (j - 1); // Step 5 - if (s_i == t_j) cost = 0; + if (s_i == t_j) { + cost = 0; + } else { // @todo cost = 1; @@ -94,7 +100,9 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali double result = 0; // results are added up because individuals can implement several data types! if ((indy1 instanceof InterfaceDataTypeBinary) && (indy2 instanceof InterfaceDataTypeBinary)) { - if (bitMetric == null) bitMetric = new GenotypeMetricBitSet(); + if (bitMetric == null) { + bitMetric = new GenotypeMetricBitSet(); + } result += bitMetric.distance(indy1, indy2); } if ((indy1 instanceof InterfaceDataTypeInteger) && (indy2 instanceof InterfaceDataTypeInteger)) { @@ -162,7 +170,9 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali * @return double */ public static double dist(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - if (pMetric == null) pMetric = new PhenotypeMetric(); + if (pMetric == null) { + pMetric = new PhenotypeMetric(); + } return pMetric.distance(indy1, indy2); } @@ -171,7 +181,9 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali if (indy instanceof InterfaceDataTypeBinary) { BitSet bs = (BitSet)((InterfaceDataTypeBinary)indy).getBinaryData(); for (int i = 0; (i < ((InterfaceDataTypeBinary)indy).size()) ; i++) { - if (bs.get(i)) result += 1; + if (bs.get(i)) { + result += 1; + } } result /= ((InterfaceDataTypeBinary)indy).size(); return result; diff --git a/src/eva2/server/go/operators/distancemetric/SigmaSingleMetricGlobalMutation.java b/src/eva2/server/go/operators/distancemetric/SigmaSingleMetricGlobalMutation.java index 3d7acb44..19ae004e 100644 --- a/src/eva2/server/go/operators/distancemetric/SigmaSingleMetricGlobalMutation.java +++ b/src/eva2/server/go/operators/distancemetric/SigmaSingleMetricGlobalMutation.java @@ -55,9 +55,13 @@ public class SigmaSingleMetricGlobalMutation implements InterfaceDistanceMetric, } // this is the normalized distance result = Math.sqrt(result); - if (result < Math.max(mutator1.getMutationStepSize(),mutator2.getMutationStepSize())) return 0.0; + if (result < Math.max(mutator1.getMutationStepSize(),mutator2.getMutationStepSize())) { + return 0.0; + } return 1.0; - } else return 1.0; + } else { + return 1.0; + } } /********************************************************************************************************************** * These are for GUI diff --git a/src/eva2/server/go/operators/fitnessmodifier/FitnessAdaptiveClustering.java b/src/eva2/server/go/operators/fitnessmodifier/FitnessAdaptiveClustering.java index ce2a397c..47a04b1c 100644 --- a/src/eva2/server/go/operators/fitnessmodifier/FitnessAdaptiveClustering.java +++ b/src/eva2/server/go/operators/fitnessmodifier/FitnessAdaptiveClustering.java @@ -37,7 +37,9 @@ public class FitnessAdaptiveClustering implements java.io.Serializable, Interfac data[i][x] = -data[i][x]; } for (int i = 0; i < data.length; i++) { - if (data[i][x] < min) min = data[i][x] ; + if (data[i][x] < min) { + min = data[i][x] ; + } } for (int i = 0; i < data.length; i++) { diff --git a/src/eva2/server/go/operators/fitnessmodifier/FitnessSharing.java b/src/eva2/server/go/operators/fitnessmodifier/FitnessSharing.java index 14c2728e..68c22c97 100644 --- a/src/eva2/server/go/operators/fitnessmodifier/FitnessSharing.java +++ b/src/eva2/server/go/operators/fitnessmodifier/FitnessSharing.java @@ -39,7 +39,9 @@ public class FitnessSharing implements java.io.Serializable, InterfaceFitnessMod data[i][x] = -data[i][x]; } for (int i = 0; i < data.length; i++) { - if (data[i][x] < min) min = data[i][x]; + if (data[i][x] < min) { + min = data[i][x]; + } } for (int i = 0; i < data.length; i++) { diff --git a/src/eva2/server/go/operators/initialization/GAGIInitializeSegmentwise.java b/src/eva2/server/go/operators/initialization/GAGIInitializeSegmentwise.java index cedfc2a9..7853e1f8 100644 --- a/src/eva2/server/go/operators/initialization/GAGIInitializeSegmentwise.java +++ b/src/eva2/server/go/operators/initialization/GAGIInitializeSegmentwise.java @@ -124,8 +124,12 @@ public class GAGIInitializeSegmentwise implements InterfaceInitialization, java. } } else { // the number of bits to set may vary from segment to segment. - if (bitsPerSegmentArray.length * segmentLength != genotypeLen) EVAERROR.errorMsgOnce("Warning, potential mismatch between segment lengths and genotype length in " + this.getClass()); - if (bitsPerSegmentArray.length * segmentLength < genotypeLen) System.err.println("Warning, " + (genotypeLen - bitsPerSegmentArray.length * segmentLength) + " bits will not be initialized!"); + if (bitsPerSegmentArray.length * segmentLength != genotypeLen) { + EVAERROR.errorMsgOnce("Warning, potential mismatch between segment lengths and genotype length in " + this.getClass()); + } + if (bitsPerSegmentArray.length * segmentLength < genotypeLen) { + System.err.println("Warning, " + (genotypeLen - bitsPerSegmentArray.length * segmentLength) + " bits will not be initialized!"); + } for (int s=0; s0) { // 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]; + 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()); + 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]); } } @@ -208,12 +220,16 @@ public class GAGIInitializeSegmentwise implements InterfaceInitialization, java. 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; + 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 + 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 @@ -227,8 +243,12 @@ public class GAGIInitializeSegmentwise implements InterfaceInitialization, java. // 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); + if (initBit) { + return (targetElement==1); + } + else { + return (targetElement!=1); + } } public int[] getTargetElementsPerSegmentArray() { diff --git a/src/eva2/server/go/operators/migration/MOBestMigration.java b/src/eva2/server/go/operators/migration/MOBestMigration.java index 9288deec..c090f3e5 100644 --- a/src/eva2/server/go/operators/migration/MOBestMigration.java +++ b/src/eva2/server/go/operators/migration/MOBestMigration.java @@ -113,7 +113,9 @@ public class MOBestMigration implements InterfaceMigration, java.io.Serializable return this.m_N; } public void setN(int b){ - if (b < 1) b = 1; + if (b < 1) { + b = 1; + } this.m_N = b; } public String nTipText() { diff --git a/src/eva2/server/go/operators/migration/MOClusteringSeparation.java b/src/eva2/server/go/operators/migration/MOClusteringSeparation.java index 1316a4a3..7f6d3766 100644 --- a/src/eva2/server/go/operators/migration/MOClusteringSeparation.java +++ b/src/eva2/server/go/operators/migration/MOClusteringSeparation.java @@ -68,7 +68,9 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria @Override public void initMigration(InterfaceOptimizer[] islands) { // pff at a later stage i could initialize a topology here - if (this.m_ReuseC) this.m_KMeans.resetC(); + if (this.m_ReuseC) { + this.m_KMeans.resetC(); + } } /** The migrate method can be called asychnronously or @@ -91,7 +93,9 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria // 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()); + if (this.m_Debug) { + System.out.println("Got population from "+i+" of size "+oldIPOP[i].size()); + } collector.addPopulation((Population)oldIPOP[i].clone()); newIPOP[i] = new Population(); } @@ -182,7 +186,9 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria double[][] myOtherClass = new double[c.length -1][]; int index = 0; for (int j = 0; j < myOtherClass.length; j++) { - if (index == i) index++; + if (index == i) { + index++; + } myOtherClass[j] = c[index]; index++; } @@ -217,7 +223,9 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria if (!oldIPOP[i].targetSizeReached()) { 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()); + if (this.m_Debug) { + System.out.println("Setting "+i+" to population size " + oldIPOP[i].size()); + } islands[i].setPopulation(oldIPOP[i]); } } @@ -330,7 +338,9 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria private void writeToFile(BufferedWriter out, String line) { String write = line + "\n"; write.replaceAll(",","."); - if (out == null) return; + if (out == null) { + return; + } try { out.write(write, 0, write.length()); out.flush(); diff --git a/src/eva2/server/go/operators/migration/MOConeSeparation.java b/src/eva2/server/go/operators/migration/MOConeSeparation.java index 207e5f24..817de1e3 100644 --- a/src/eva2/server/go/operators/migration/MOConeSeparation.java +++ b/src/eva2/server/go/operators/migration/MOConeSeparation.java @@ -86,7 +86,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl // 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()); + if (this.m_Debug) { + System.out.println("Got population from "+i+" of size "+oldIPOP[i].size()); + } collector.addPopulation((Population)oldIPOP[i].clone()); newIPOP[i] = new Population(); } @@ -111,7 +113,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl if (!oldIPOP[i].targetSizeReached()) { 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()); + if (this.m_Debug) { + System.out.println("Setting island "+i+" to population size " + oldIPOP[i].size()); + } allDom.addElementsToArchive(oldIPOP[i]); islands[i].setPopulation(oldIPOP[i]); } @@ -159,8 +163,12 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl Population archive = collector.getArchive(); Population ref; - if (this.m_UseAllToDetermineR) ref = collector; - else ref = archive; + if (this.m_UseAllToDetermineR) { + ref = collector; + } + else { + ref = archive; + } for (int i = 1; i < ref.size(); i++) { if (((AbstractEAIndividual)ref.get(i)).getFitness()[0] > ((AbstractEAIndividual)ref.get(y1Big)).getFitness()[0]) { @@ -221,7 +229,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl indy = (AbstractEAIndividual)newIPOP[i].get(j); myPoint = new DPoint(indy.getFitness()[0], indy.getFitness()[1]); tmp = new Chart2DDPointIconText(""+i); - if (i % 2 == 0) tmp.setIcon(new Chart2DDPointIconCircle()); + if (i % 2 == 0) { + tmp.setIcon(new Chart2DDPointIconCircle()); + } myPoint.setIcon(tmp); mySet.addDPoint(myPoint); } @@ -290,8 +300,12 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl Population archive = collector.getArchive(); Population ref; - if (this.m_UseAllToDetermineR) ref = collector; - else ref = archive; + if (this.m_UseAllToDetermineR) { + ref = collector; + } + else { + ref = archive; + } for (int i = 1; i < ref.size(); i++) { if (((AbstractEAIndividual)ref.get(i)).getFitness()[0] > ((AbstractEAIndividual)ref.get(y1Big)).getFitness()[0]) { @@ -379,7 +393,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]; + if (i+1 < normals.length) { + curBoundingPlane[1] = normals[i+1]; + } // else curBoundingPlane[1] = normals[0]; } // System.out.println("collector.size() "+ collector.size()); @@ -699,7 +715,9 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl private void writeToFile(BufferedWriter out, String line) { String write = line + "\n"; write.replaceAll(",","."); - if (out == null) return; + if (out == null) { + return; + } try { out.write(write, 0, write.length()); out.flush(); diff --git a/src/eva2/server/go/operators/migration/MOXMeansSeparation.java b/src/eva2/server/go/operators/migration/MOXMeansSeparation.java index f24d7753..c71cf1a5 100644 --- a/src/eva2/server/go/operators/migration/MOXMeansSeparation.java +++ b/src/eva2/server/go/operators/migration/MOXMeansSeparation.java @@ -88,7 +88,9 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa // 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()); + if (this.m_Debug) { + System.out.println("Got population from "+i+" of size "+oldIPOP[i].size()); + } collector.addPopulation((Population)oldIPOP[i].clone()); //if (oldIPOP[i].getArchive() != null) collector.addPopulation((Population)oldIPOP[i].getArchive().clone()); newIPOP[i] = new Population(); @@ -185,7 +187,9 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa double[][] myOtherClass = new double[c.length -1][]; int index = 0; for (int j = 0; j < myOtherClass.length; j++) { - if (index == i) index++; + if (index == i) { + index++; + } myOtherClass[j] = c[index]; index++; } @@ -221,7 +225,9 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa if (!oldIPOP[i].targetSizeReached()) { 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()); + if (this.m_Debug) { + System.out.println("Setting "+i+" to population size " + oldIPOP[i].size()); + } islands[i].setPopulation(oldIPOP[i]); islands[i].getPopulation().setTargetSize(oldIPOP[i].size()); } @@ -335,7 +341,9 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa private void writeToFile(BufferedWriter out, String line) { String write = line + "\n"; write.replaceAll(",","."); - if (out == null) return; + if (out == null) { + return; + } try { out.write(write, 0, write.length()); out.flush(); diff --git a/src/eva2/server/go/operators/migration/SOBestMigration.java b/src/eva2/server/go/operators/migration/SOBestMigration.java index 8098f5cc..e7f2608e 100644 --- a/src/eva2/server/go/operators/migration/SOBestMigration.java +++ b/src/eva2/server/go/operators/migration/SOBestMigration.java @@ -111,7 +111,9 @@ public class SOBestMigration implements InterfaceMigration, java.io.Serializable return this.m_N; } public void setN(int b){ - if (b < 1) b = 1; + if (b < 1) { + b = 1; + } this.m_N = b; } public String nTipText() { diff --git a/src/eva2/server/go/operators/moso/MOSOEpsilonConstraint.java b/src/eva2/server/go/operators/moso/MOSOEpsilonConstraint.java index b9eb910f..899e8760 100644 --- a/src/eva2/server/go/operators/moso/MOSOEpsilonConstraint.java +++ b/src/eva2/server/go/operators/moso/MOSOEpsilonConstraint.java @@ -26,8 +26,9 @@ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Se } public MOSOEpsilonConstraint(MOSOEpsilonConstraint b) { - if (b.m_EpsilonConstraint != null) + if (b.m_EpsilonConstraint != null) { this.m_EpsilonConstraint = (PropertyEpsilonConstraint)b.m_EpsilonConstraint.clone(); + } } @Override public Object clone() { @@ -82,7 +83,9 @@ public class MOSOEpsilonConstraint implements InterfaceMOSOConverter, java.io.Se for (int i = 0; (i < this.m_EpsilonConstraint.m_TargetValue.length) && (i < newTarget.length); i++) { newTarget[i] = this.m_EpsilonConstraint.m_TargetValue[i]; } - if (this.m_EpsilonConstraint.m_OptimizeObjective >= dim) this.m_EpsilonConstraint.m_OptimizeObjective = dim-1; + if (this.m_EpsilonConstraint.m_OptimizeObjective >= dim) { + this.m_EpsilonConstraint.m_OptimizeObjective = dim-1; + } this.m_EpsilonConstraint.m_TargetValue = newTarget; } diff --git a/src/eva2/server/go/operators/moso/MOSOEpsilonThreshold.java b/src/eva2/server/go/operators/moso/MOSOEpsilonThreshold.java index 6c74af14..0e3363b8 100644 --- a/src/eva2/server/go/operators/moso/MOSOEpsilonThreshold.java +++ b/src/eva2/server/go/operators/moso/MOSOEpsilonThreshold.java @@ -31,8 +31,9 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser } public MOSOEpsilonThreshold(MOSOEpsilonThreshold b) { - if (b.m_EpsilonThreshold != null) + if (b.m_EpsilonThreshold != null) { this.m_EpsilonThreshold = (PropertyEpsilonThreshold)b.m_EpsilonThreshold.clone(); + } } @Override public Object clone() { @@ -64,8 +65,12 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser tmpFit = indy.getFitness(); indy.putData("MOFitness", tmpFit); for (int i = 0; i < tmpFit.length; i++) { - if (new Double(tmpFit[i]).isNaN()) System.out.println("Fitness is NaN"); - if (new Double(tmpFit[i]).isInfinite()) System.out.println("Fitness is Infinite"); + if (new Double(tmpFit[i]).isNaN()) { + System.out.println("Fitness is NaN"); + } + if (new Double(tmpFit[i]).isInfinite()) { + System.out.println("Fitness is Infinite"); + } } resultFit[0] = tmpFit[this.m_EpsilonThreshold.m_OptimizeObjective]; @@ -81,8 +86,12 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser } tmpFit = (double[]) indy.getData("MOFitness"); for (int i = 0; i < tmpFit.length; i++) { - if (new Double(tmpFit[i]).isNaN()) System.out.println("-Fitness is NaN"); - if (new Double(tmpFit[i]).isInfinite()) System.out.println("-Fitness is Infinite"); + if (new Double(tmpFit[i]).isNaN()) { + System.out.println("-Fitness is NaN"); + } + if (new Double(tmpFit[i]).isInfinite()) { + System.out.println("-Fitness is Infinite"); + } } indy.setFitness(resultFit); } @@ -105,7 +114,9 @@ public class MOSOEpsilonThreshold implements InterfaceMOSOConverter, java.io.Ser newPunish[i] = this.m_EpsilonThreshold.m_Punishment[i]; newTarget[i] = this.m_EpsilonThreshold.m_TargetValue[i]; } - if (this.m_EpsilonThreshold.m_OptimizeObjective >= dim) this.m_EpsilonThreshold.m_OptimizeObjective = dim-1; + if (this.m_EpsilonThreshold.m_OptimizeObjective >= dim) { + this.m_EpsilonThreshold.m_OptimizeObjective = dim-1; + } this.m_EpsilonThreshold.m_Punishment = newPunish; this.m_EpsilonThreshold.m_TargetValue = newTarget; diff --git a/src/eva2/server/go/operators/moso/MOSOLpMetric.java b/src/eva2/server/go/operators/moso/MOSOLpMetric.java index ca916dd8..196ff0ca 100644 --- a/src/eva2/server/go/operators/moso/MOSOLpMetric.java +++ b/src/eva2/server/go/operators/moso/MOSOLpMetric.java @@ -105,7 +105,9 @@ public class MOSOLpMetric implements InterfaceMOSOConverter, java.io.Serializabl 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 += "; "; + if (i < (m_Reference.getNumRows()-1)) { + result += "; "; + } } result += ")\n"; return result; diff --git a/src/eva2/server/go/operators/moso/MOSOWeightedFitness.java b/src/eva2/server/go/operators/moso/MOSOWeightedFitness.java index 77b6cb3b..6a758a39 100644 --- a/src/eva2/server/go/operators/moso/MOSOWeightedFitness.java +++ b/src/eva2/server/go/operators/moso/MOSOWeightedFitness.java @@ -76,7 +76,9 @@ public class MOSOWeightedFitness implements InterfaceMOSOConverter, java.io.Seri 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+= "; "; + if (i < this.m_Weights.getNumRows()-1) { + s+= "; "; + } } System.out.println(s+"}"); } diff --git a/src/eva2/server/go/operators/moso/MOSOWeightedLPTchebycheff.java b/src/eva2/server/go/operators/moso/MOSOWeightedLPTchebycheff.java index e84b4127..c36b7386 100644 --- a/src/eva2/server/go/operators/moso/MOSOWeightedLPTchebycheff.java +++ b/src/eva2/server/go/operators/moso/MOSOWeightedLPTchebycheff.java @@ -31,8 +31,9 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i } public MOSOWeightedLPTchebycheff(MOSOWeightedLPTchebycheff b) { - if (b.m_WLPT != null) + if (b.m_WLPT != null) { this.m_WLPT = (PropertyWeightedLPTchebycheff)b.m_WLPT.clone(); + } } @Override public Object clone() { @@ -71,7 +72,9 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i 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)); + if (this.m_WLPT.m_P > 0) { + resultFit[0] = Math.pow(resultFit[0], 1/((double)this.m_WLPT.m_P)); + } indy.setFitness(resultFit); } @@ -108,14 +111,18 @@ public class MOSOWeightedLPTchebycheff implements InterfaceMOSOConverter, java.i double[] p = this.m_WLPT.m_IdealValue; for (int i = 0; i < p.length; i++) { result += p[i]; - if (i < (p.length-1)) result += "; "; + if (i < (p.length-1)) { + result += "; "; + } } result += ")\n"; result += " Weights = ("; p = this.m_WLPT.m_Weights; for (int i = 0; i < p.length; i++) { result += p[i]; - if (i < (p.length-1)) result += "; "; + if (i < (p.length-1)) { + result += "; "; + } } result += ")\n"; return result; diff --git a/src/eva2/server/go/operators/mutation/CMAParamSet.java b/src/eva2/server/go/operators/mutation/CMAParamSet.java index de852590..e752b43b 100644 --- a/src/eva2/server/go/operators/mutation/CMAParamSet.java +++ b/src/eva2/server/go/operators/mutation/CMAParamSet.java @@ -134,7 +134,9 @@ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializab 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!"); + if (initialSigma!=-0.25 && (initialSigma!=-0.5)) { + EVAERROR.errorMsgOnce("Warning, unexpected initial sigma in CMAParamSet!"); + } initialSigma = -initialSigma*Mathematics.getAvgRange(params.range); } if (initialSigma <= 0) { @@ -167,7 +169,9 @@ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializab 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; + if (((String)mutators.get(i)).equals(this.getClass().getName())) { + continue; + } try { tmpList[i] = (InterfaceMutation)Class.forName((String)mutators.get(i)).newInstance(); } catch (java.lang.ClassNotFoundException e) { @@ -90,7 +92,9 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { MutateEAMixer mut = (MutateEAMixer)mutator; return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -116,8 +120,12 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { if (this.m_UseSelfAdaption) { for (int i = 0; i < probs.length; i++) { probs[i] *= Math.exp(this.m_Tau1 * RNG.gaussianDouble(1)); - if (probs[i] <= this.m_LowerLimitChance) probs[i] = this.m_LowerLimitChance; - if (probs[i] >= 1) probs[i] = 1; + if (probs[i] <= this.m_LowerLimitChance) { + probs[i] = this.m_LowerLimitChance; + } + if (probs[i] >= 1) { + probs[i] = 1; + } } this.m_Mutators.normalizeWeights(); } @@ -130,7 +138,9 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { index++; dum += probs[index]; } - if (index == probs.length) index = RNG.randomInt(0, probs.length-1); + if (index == probs.length) { + index = 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]); @@ -207,7 +217,9 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { * @param d The mutation operator. */ public void setLowerLimitChance(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitChance = d; } public double getLowerLimitChance() { @@ -221,7 +233,9 @@ public class MutateEAMixer implements InterfaceMutation, java.io.Serializable { * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { diff --git a/src/eva2/server/go/operators/mutation/MutateESCorrVector.java b/src/eva2/server/go/operators/mutation/MutateESCorrVector.java index 3b3d1fa1..cd709a61 100644 --- a/src/eva2/server/go/operators/mutation/MutateESCorrVector.java +++ b/src/eva2/server/go/operators/mutation/MutateESCorrVector.java @@ -72,11 +72,19 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab public boolean equals(Object mutator) { if (mutator instanceof MutateESCorrVector) { MutateESCorrVector mut = (MutateESCorrVector)mutator; - if (this.m_scalingDev != mut.m_scalingDev) return false; - if (this.m_initialVelocity != m_initialVelocity) return false; - if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) return false; + if (this.m_scalingDev != mut.m_scalingDev) { + return false; + } + if (this.m_initialVelocity != m_initialVelocity) { + return false; + } + if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -133,22 +141,32 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab 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); + 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) System.out.println("-- dir is " + BeanInspector.toString(vel)); + if (TRACE) { + System.out.println("rotated by " + rotateRad + ", scaled by " + rScale); + } + 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); + if (m_checkConstraints) { + Mathematics.projectToRange(genes, range); + } // write genotype back ((InterfaceESIndividual)individual).SetDGenotype(genes); @@ -165,15 +183,21 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab @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)); + if (indy1.getMutationOperator() instanceof MutateESCorrVector) { + 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(); } - if (list.length <= 1) return; + if (list.length <= 1) { + return; + } // discreete mutation for step size this.m_scalingDev = list[RNG.randomInt(0, list.length-1)]; } @@ -221,7 +245,9 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitStepSize = d; } public double getLowerLimitStepSize() { diff --git a/src/eva2/server/go/operators/mutation/MutateESCorrolated.java b/src/eva2/server/go/operators/mutation/MutateESCorrolated.java index 66f2a1d8..0b82043c 100644 --- a/src/eva2/server/go/operators/mutation/MutateESCorrolated.java +++ b/src/eva2/server/go/operators/mutation/MutateESCorrolated.java @@ -63,24 +63,42 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab */ @Override public boolean equals(Object mutator) { - if (mutator==this) return true; + if (mutator==this) { + return true; + } if (mutator instanceof MutateESCorrolated) { MutateESCorrolated mut = (MutateESCorrolated)mutator; - if (this.m_Tau1 != mut.m_Tau1) return false; - if (this.m_Tau2 != mut.m_Tau2) return false; - if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) return false; + if (this.m_Tau1 != mut.m_Tau1) { + return false; + } + if (this.m_Tau2 != mut.m_Tau2) { + return false; + } + if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) { + return false; + } if (this.m_Sigmas != null) { for (int i = 0; i < this.m_Sigmas.length; i++) { - if (this.m_Sigmas[i] != mut.m_Sigmas[i]) return false; + if (this.m_Sigmas[i] != mut.m_Sigmas[i]) { + return false; + } } - } else return false; + } else { + return false; + } if (this.m_Alphas != null) { for (int i = 0; i < this.m_Alphas.length; i++) { - if (this.m_Alphas[i] != mut.m_Alphas[i]) return false; + if (this.m_Alphas[i] != mut.m_Alphas[i]) { + return false; + } } - } else return false; + } else { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -182,14 +200,20 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab //Mutate Sigmas 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; + if (this.m_Sigmas[i] < this.m_LowerLimitStepSize) { + this.m_Sigmas[i] = this.m_LowerLimitStepSize; + } } //Mutate Alphas for (int i = 0; i < this.m_Alphas.length; i++) { this.m_Alphas[i] += RNG.gaussianDouble(0.2); - if (this.m_Alphas[i] < -Math.PI/2) this.m_Alphas[i] = -Math.PI/2; - if (this.m_Alphas[i] > Math.PI/2) this.m_Alphas[i] = Math.PI/2; + if (this.m_Alphas[i] < -Math.PI/2) { + this.m_Alphas[i] = -Math.PI/2; + } + if (this.m_Alphas[i] > Math.PI/2) { + this.m_Alphas[i] = Math.PI/2; + } } //Generate mutationvector in unitspace modified by sigmas @@ -211,8 +235,12 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab //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]; + 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); @@ -277,7 +305,9 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab * @param d The mutation operator. */ public void setTau2(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau2 = d; } public double getTau2() { @@ -291,7 +321,9 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab * @param d The mutation operator. */ public void setMutationStepSize(double d) { - if (d < 0) d = this.m_LowerLimitStepSize; + if (d < 0) { + d = this.m_LowerLimitStepSize; + } this.m_MutationStepSize = d; } public double getMutationStepSize() { @@ -305,7 +337,9 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitStepSize = d; } public double getLowerLimitStepSize() { @@ -319,7 +353,9 @@ public class MutateESCorrolated implements InterfaceMutation, java.io.Serializab * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { diff --git a/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaption.java b/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaption.java index 8a5fe05f..5de63393 100644 --- a/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaption.java +++ b/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaption.java @@ -55,13 +55,27 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java this.cov = mutator.cov; this.Beta = mutator.Beta; this.xi_dach = mutator.xi_dach; - if (mutator.s_N != null) this.s_N = (double[]) mutator.s_N.clone(); - if (mutator.m_PathS != null) this.m_PathS = (double[]) mutator.m_PathS.clone(); - if (mutator.Bz != null) this.Bz = (double[]) mutator.Bz.clone(); - if (mutator.m_C != null) this.m_C = (Matrix) mutator.m_C.clone(); - if (mutator.B != null) this.B = (Matrix) mutator.B.clone(); - if (mutator.m_Z != null) this.m_Z = (double[]) mutator.m_Z.clone(); - if (mutator.m_Eigenvalues != null) this.m_Eigenvalues = (double[]) mutator.m_Eigenvalues.clone(); + if (mutator.s_N != null) { + this.s_N = (double[]) mutator.s_N.clone(); + } + if (mutator.m_PathS != null) { + this.m_PathS = (double[]) mutator.m_PathS.clone(); + } + if (mutator.Bz != null) { + this.Bz = (double[]) mutator.Bz.clone(); + } + if (mutator.m_C != null) { + this.m_C = (Matrix) mutator.m_C.clone(); + } + if (mutator.B != null) { + this.B = (Matrix) mutator.B.clone(); + } + if (mutator.m_Z != null) { + this.m_Z = (double[]) mutator.m_Z.clone(); + } + if (mutator.m_Eigenvalues != null) { + this.m_Eigenvalues = (double[]) mutator.m_Eigenvalues.clone(); + } } /** @@ -87,18 +101,26 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java */ @Override public boolean equals(Object mutator) { - if (mutator==this) return true; + if (mutator==this) { + return true; + } if (mutator instanceof MutateESCovarianceMatrixAdaption) { MutateESCovarianceMatrixAdaption mut = (MutateESCovarianceMatrixAdaption)mutator; // i assume if the C Matrix is equal then the mutation operators are equal try { - if (this.m_C==mut.m_C) return true; + if (this.m_C==mut.m_C) { + return true; + } double[][] c1 = this.m_C.getArray(); double[][] c2 = mut.m_C.getArray(); - if (c1==c2) return true; + if (c1==c2) { + return true; + } for (int i = 0; i < c1.length; i++) { for(int j = 0; j < c1[i].length; j++) { - if (c1[i][j] != c2[i][j]) return false; + if (c1[i][j] != c2[i][j]) { + return false; + } } } } catch (java.lang.NullPointerException e) { @@ -106,7 +128,9 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator @@ -115,12 +139,16 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - if (!(individual instanceof InterfaceESIndividual)) return; + if (!(individual instanceof InterfaceESIndividual)) { + return; + } double[] x = ((InterfaceESIndividual)individual).getDGenotype(); double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); this.m_Counter = this.m_frequency; - if (m_InitSigmaScalar>0) this.m_SigmaGlobal = this.m_InitSigmaScalar; + if (m_InitSigmaScalar>0) { + this.m_SigmaGlobal = this.m_InitSigmaScalar; + } else { double avgRange = Mathematics.getAvgRange(ranges); this.m_SigmaGlobal = 0.25*avgRange; @@ -160,8 +188,12 @@ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java this.adaptStrategy(); this.evaluateNewObjectX(x, 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]; + if (x[i] < ranges[i][0]) { + x[i] = ranges[i][0]; + } + if (x[i] > ranges[i][1]) { + x[i] = ranges[i][1]; + } } ((InterfaceESIndividual)individual).SetDGenotype(x); } diff --git a/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaptionPlus.java b/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaptionPlus.java index 31af4fc6..e28b57ca 100644 --- a/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaptionPlus.java +++ b/src/eva2/server/go/operators/mutation/MutateESCovarianceMatrixAdaptionPlus.java @@ -53,8 +53,9 @@ public class MutateESCovarianceMatrixAdaptionPlus extends public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - if (!(individual instanceof InterfaceESIndividual)) - return; + if (!(individual instanceof InterfaceESIndividual)) { + return; + } super.init(individual, opt); m_psuccesstarget = 1.0 / (5 + Math.sqrt(m_lambda) / 2); m_psuccess = m_psuccesstarget; @@ -162,27 +163,29 @@ public class MutateESCovarianceMatrixAdaptionPlus extends // " , " + // BeanInspector.toString(parentPop.getEAIndividual(i).getFitness())); if (newPop.getEAIndividual(i).getFitness(0) < parentPop - .getEAIndividual(i).getFitness(0)) - rate++; + .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+ ")"); - } + 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(); diff --git a/src/eva2/server/go/operators/mutation/MutateESFixedStepSize.java b/src/eva2/server/go/operators/mutation/MutateESFixedStepSize.java index e3ebf6d9..4a32fdc3 100644 --- a/src/eva2/server/go/operators/mutation/MutateESFixedStepSize.java +++ b/src/eva2/server/go/operators/mutation/MutateESFixedStepSize.java @@ -43,9 +43,13 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali public boolean equals(Object mutator) { if (mutator instanceof MutateESFixedStepSize) { MutateESFixedStepSize mut = (MutateESFixedStepSize)mutator; - if (this.m_Sigma != mut.m_Sigma) return false; + if (this.m_Sigma != mut.m_Sigma) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -69,8 +73,12 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali 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); - if (range[i][0] > x[i]) x[i] = range[i][0]; - if (range[i][1] < x[i]) x[i] = range[i][1]; + 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); @@ -118,7 +126,9 @@ public class MutateESFixedStepSize implements InterfaceMutation, java.io.Seriali * @param d The mutation operator. */ public void setSigma(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Sigma = d; } public double getSigma() { diff --git a/src/eva2/server/go/operators/mutation/MutateESGlobal.java b/src/eva2/server/go/operators/mutation/MutateESGlobal.java index 557e0bc9..6c631051 100644 --- a/src/eva2/server/go/operators/mutation/MutateESGlobal.java +++ b/src/eva2/server/go/operators/mutation/MutateESGlobal.java @@ -69,11 +69,19 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, public boolean equals(Object mutator) { if (mutator instanceof MutateESGlobal) { MutateESGlobal mut = (MutateESGlobal)mutator; - if (this.m_MutationStepSize != mut.m_MutationStepSize) return false; - if (this.m_Tau1 != mut.m_Tau1) return false; - if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) return false; + if (this.m_MutationStepSize != mut.m_MutationStepSize) { + return false; + } + if (this.m_Tau1 != mut.m_Tau1) { + return false; + } + if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -96,11 +104,17 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, 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; + 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); - if (range[i][0] > x[i]) x[i] = range[i][0]; - if (range[i][1] < x[i]) x[i] = range[i][1]; + 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); @@ -117,15 +131,21 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, 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 (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)); + 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(); } - if (list.length <= 1) return; + if (list.length <= 1) { + return; + } switch (this.m_CrossoverType) { case intermediate : @@ -174,7 +194,9 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, * @param d The mutation operator. */ public void setMutationStepSize(double d) { - if (d < 0) d = this.m_LowerLimitStepSize; + if (d < 0) { + d = this.m_LowerLimitStepSize; + } this.m_MutationStepSize = d; } public double getMutationStepSize() { @@ -188,7 +210,9 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitStepSize = d; } public double getLowerLimitStepSize() { @@ -202,7 +226,9 @@ public class MutateESGlobal implements InterfaceMutation, java.io.Serializable, * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { diff --git a/src/eva2/server/go/operators/mutation/MutateESLocal.java b/src/eva2/server/go/operators/mutation/MutateESLocal.java index 24eba6bd..0d270fab 100644 --- a/src/eva2/server/go/operators/mutation/MutateESLocal.java +++ b/src/eva2/server/go/operators/mutation/MutateESLocal.java @@ -65,19 +65,33 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu */ @Override public boolean equals(Object mutator) { - if (mutator==this) return true; + if (mutator==this) { + return true; + } if (mutator instanceof MutateESLocal) { MutateESLocal mut = (MutateESLocal)mutator; - if (this.m_Tau1 != mut.m_Tau1) return false; - if (this.m_Tau2 != mut.m_Tau2) return false; - if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) return false; + if (this.m_Tau1 != mut.m_Tau1) { + return false; + } + if (this.m_Tau2 != mut.m_Tau2) { + return false; + } + if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) { + return false; + } if (this.m_Sigmas != null) { for (int i = 0; i < this.m_Sigmas.length; i++) { - if (this.m_Sigmas[i] != mut.m_Sigmas[i]) return false; + if (this.m_Sigmas[i] != mut.m_Sigmas[i]) { + return false; + } } - } else return false; + } else { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -110,10 +124,16 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu 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; + 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]); - if (range[i][0] > x[i]) x[i] = range[i][0]; - if (range[i][1] < x[i]) x[i] = range[i][1]; + 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); } @@ -145,7 +165,9 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu listA[i] = ((Double)tmpListA.get(i)).doubleValue(); listB[i] = (double[])tmpListB.get(i); } - if (listA.length <= 1) return; + if (listA.length <= 1) { + return; + } switch (this.m_CrossoverType.getSelectedTag().getID()) { case 1 : { this.m_MutationStepSize = 0; @@ -209,7 +231,9 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu * @param d The mutation operator. */ public void setMutationStepSize(double d) { - if (d < 0) d = this.m_LowerLimitStepSize; + if (d < 0) { + d = this.m_LowerLimitStepSize; + } this.m_MutationStepSize = d; } public double getMutationStepSize() { @@ -223,7 +247,9 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitStepSize = d; } public double getLowerLimitStepSize() { @@ -237,7 +263,9 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { @@ -251,7 +279,9 @@ public class MutateESLocal implements InterfaceMutation, InterfaceAdditionalPopu * @param d The mutation operator. */ public void setTau2(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau2 = d; } public double getTau2() { diff --git a/src/eva2/server/go/operators/mutation/MutateESMainVectorAdaption.java b/src/eva2/server/go/operators/mutation/MutateESMainVectorAdaption.java index b1dfae88..d313b9f1 100644 --- a/src/eva2/server/go/operators/mutation/MutateESMainVectorAdaption.java +++ b/src/eva2/server/go/operators/mutation/MutateESMainVectorAdaption.java @@ -45,10 +45,18 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se 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(); - if (mutator.m_Z != null) this.m_Z = (double[]) mutator.m_Z.clone(); - if (mutator.s_N != null) this.s_N = (double[]) mutator.s_N.clone(); - if (mutator.s_d_N != null) this.s_d_N = (double[]) mutator.s_d_N.clone(); + if (mutator.m_main_v != null) { + this.m_main_v = (double[]) mutator.m_main_v.clone(); + } + if (mutator.m_Z != null) { + this.m_Z = (double[]) mutator.m_Z.clone(); + } + if (mutator.s_N != null) { + 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 method will enable you to clone a given mutation operator @@ -65,19 +73,29 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se */ @Override public boolean equals(Object mutator) { - if (this==mutator) return true; + if (this==mutator) { + return true; + } if (mutator instanceof MutateESMainVectorAdaption) { 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) return true; + if (this.m_main_v==mut.m_main_v) { + return true; + } if (this.m_main_v != null) { for (int i = 0; i < this.m_main_v.length; i++) { - if (this.m_main_v[i] != mut.m_main_v[i]) return false; + if (this.m_main_v[i] != mut.m_main_v[i]) { + return false; + } } - } else return false; + } else { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator @@ -86,7 +104,9 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - if (!(individual instanceof InterfaceESIndividual)) return; + if (!(individual instanceof InterfaceESIndividual)) { + return; + } double[] x = ((InterfaceESIndividual)individual).getDGenotype(); double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); this.m_SigmaScalar = this.m_InitSigmaScalar; @@ -155,8 +175,12 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se for (int i = 0; i < this.N; i++) { Product += this.s_N[i] * this.m_main_v[i]; } - if (Product < 0.0) Product = -1.0; - else Product = 1.0; + if (Product < 0.0) { + Product = -1.0; + } + 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]; @@ -164,7 +188,9 @@ public class MutateESMainVectorAdaption implements InterfaceMutation, java.io.Se } private void evaluateNewObjectX(double[] x, double[][] range) { - if (Double.isNaN((x[0]))) System.err.println("treffer in mva "+ x[0]); + if (Double.isNaN((x[0]))) { + System.err.println("treffer in mva "+ x[0]); + } // boolean constraint = false; // int counter = 0; diff --git a/src/eva2/server/go/operators/mutation/MutateESMutativeStepSizeControl.java b/src/eva2/server/go/operators/mutation/MutateESMutativeStepSizeControl.java index 92a4f6f8..3cc4e44f 100644 --- a/src/eva2/server/go/operators/mutation/MutateESMutativeStepSizeControl.java +++ b/src/eva2/server/go/operators/mutation/MutateESMutativeStepSizeControl.java @@ -61,12 +61,22 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. public boolean equals(Object mutator) { if (mutator instanceof MutateESMutativeStepSizeControl) { MutateESMutativeStepSizeControl mut = (MutateESMutativeStepSizeControl)mutator; - if (this.m_MutationStepSize != mut.m_MutationStepSize) return false; - if (this.m_Alpha != mut.m_Alpha) return false; - if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) return false; - if (this.m_UpperLimitStepSize != mut.m_UpperLimitStepSize) return false; + if (this.m_MutationStepSize != mut.m_MutationStepSize) { + return false; + } + if (this.m_Alpha != mut.m_Alpha) { + return false; + } + if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) { + return false; + } + if (this.m_UpperLimitStepSize != mut.m_UpperLimitStepSize) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -88,16 +98,26 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. if (individual instanceof InterfaceESIndividual) { double[] x = ((InterfaceESIndividual)individual).getDGenotype(); double[][] range = ((InterfaceESIndividual)individual).getDoubleRange(); - if (RNG.flipCoin(0.5)) + 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) this.m_MutationStepSize = this.m_LowerLimitStepSize; - if (this.m_MutationStepSize > this.m_UpperLimitStepSize) this.m_MutationStepSize = this.m_UpperLimitStepSize; + } + if (this.m_MutationStepSize < this.m_LowerLimitStepSize) { + this.m_MutationStepSize = this.m_LowerLimitStepSize; + } + if (this.m_MutationStepSize > this.m_UpperLimitStepSize) { + 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); - if (range[i][0] > x[i]) x[i] = range[i][0]; - if (range[i][1] < x[i]) x[i] = range[i][1]; + 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); // System.out.println("new step size: " + m_MutationStepSize); @@ -145,7 +165,9 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. * @param d The mutation operator. */ public void setMutationStepSize(double d) { - if (d < 0) d = this.m_LowerLimitStepSize; + if (d < 0) { + d = this.m_LowerLimitStepSize; + } this.m_MutationStepSize = d; } public double getMutationStepSize() { @@ -185,7 +207,9 @@ public class MutateESMutativeStepSizeControl implements InterfaceMutation, java. * @param d The mutation operator. */ public void setAlpha(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Alpha = d; } public double getAlpha() { diff --git a/src/eva2/server/go/operators/mutation/MutateESPathLengthAdaption.java b/src/eva2/server/go/operators/mutation/MutateESPathLengthAdaption.java index 88809869..a383aff3 100644 --- a/src/eva2/server/go/operators/mutation/MutateESPathLengthAdaption.java +++ b/src/eva2/server/go/operators/mutation/MutateESPathLengthAdaption.java @@ -37,8 +37,12 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se 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(); - if (mutator.m_Path != null) this.m_Path = (double[]) mutator.m_Path.clone(); + if (mutator.m_randZ != null) { + this.m_randZ = (double[]) mutator.m_randZ.clone(); + } + if (mutator.m_Path != null) { + this.m_Path = (double[]) mutator.m_Path.clone(); + } } /** This method will enable you to clone a given mutation operator @@ -58,20 +62,34 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se if (mutator instanceof MutateESPathLengthAdaption) { 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; - if (this.m_SigmaGlobal != mut.m_SigmaGlobal) return false; - if (this.m_c != mut.m_c) return false; - if ((this.m_randZ != null) && (mut.m_randZ != null)) - for (int i = 0; i < this.m_randZ.length; i++) { - if (this.m_randZ[i] != mut.m_randZ[i]) return false; + if (this.m_dim != mut.m_dim) { + return false; } - if ((this.m_Path != null) && (mut.m_Path != null)) + if (this.m_SigmaGlobal != mut.m_SigmaGlobal) { + return false; + } + if (this.m_c != mut.m_c) { + return false; + } + if ((this.m_randZ != null) && (mut.m_randZ != null)) { + for (int i = 0; i < this.m_randZ.length; i++) { + if (this.m_randZ[i] != mut.m_randZ[i]) { + return false; + } + } + } + if ((this.m_Path != null) && (mut.m_Path != null)) { for (int i = 0; i < this.m_Path.length; i++) { - if (this.m_Path[i] != mut.m_Path[i]) return false; + if (this.m_Path[i] != mut.m_Path[i]) { + return false; + } + } } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator @@ -80,7 +98,9 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se */ @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - if (!(individual instanceof InterfaceESIndividual)) return; + if (!(individual instanceof InterfaceESIndividual)) { + return; + } double[] x = ((InterfaceESIndividual)individual).getDGenotype(); double[][] ranges = ((InterfaceESIndividual)individual).getDoubleRange(); this.m_dim = x.length; @@ -93,8 +113,12 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se // this.m_Path[i]=1; } - if (this.m_UsePath) this.m_c = 4./(m_dim+4); - else this.m_c = 1.0; + if (this.m_UsePath) { + 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; @@ -127,8 +151,12 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se 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]; + if (x[i] < ranges[i][0]) { + x[i] = ranges[i][0]; + } + if (x[i] > ranges[i][1]) { + x[i] = ranges[i][1]; + } } } @@ -166,7 +194,9 @@ public class MutateESPathLengthAdaption implements InterfaceMutation, java.io.Se for (int i = 0; i < x.length; i++) { x[i] += m_SigmaGlobal * m_randZ[i]; } - if (checkRange) checkRange(x, range); + if (checkRange) { + checkRange(x, range); + } } /** This method allows you to get a string representation of the mutation diff --git a/src/eva2/server/go/operators/mutation/MutateESPolynomial.java b/src/eva2/server/go/operators/mutation/MutateESPolynomial.java index 445c1336..7baad221 100644 --- a/src/eva2/server/go/operators/mutation/MutateESPolynomial.java +++ b/src/eva2/server/go/operators/mutation/MutateESPolynomial.java @@ -43,9 +43,13 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab public boolean equals(Object mutator) { if (mutator instanceof MutateESPolynomial) { MutateESPolynomial mut = (MutateESPolynomial)mutator; - if (this.m_Eta != mut.m_Eta) return false; + if (this.m_Eta != mut.m_Eta) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -78,8 +82,12 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab } x[i] += delta; - if (range[i][0] > x[i]) x[i] = range[i][0]; - if (range[i][1] < x[i]) x[i] = range[i][1]; + 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); @@ -128,7 +136,9 @@ public class MutateESPolynomial implements InterfaceMutation, java.io.Serializab * @param a The number of crossovers. */ public void setEta(double a) { - if (a < 0) a = 0; + if (a < 0) { + a = 0; + } this.m_Eta = a; } public double getEta() { diff --git a/src/eva2/server/go/operators/mutation/MutateESRankMuCMA.java b/src/eva2/server/go/operators/mutation/MutateESRankMuCMA.java index cb57a456..916655fc 100644 --- a/src/eva2/server/go/operators/mutation/MutateESRankMuCMA.java +++ b/src/eva2/server/go/operators/mutation/MutateESRankMuCMA.java @@ -73,8 +73,12 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In public static double[] getMeanXOfPop(Population pop) { CMAParamSet params = (CMAParamSet)pop.getData(MutateESRankMuCMA.cmaParamsKey); - if (params==null) return null; - else return params.meanX; + if (params==null) { + return null; + } + else { + return params.meanX; + } } /** @@ -117,8 +121,12 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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 (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); @@ -126,13 +134,21 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In } 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)); + 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?"); + 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); + } else { + params = (CMAParamSet)oldGen.getData(cmaParamsKey); + } } if (lambda==1 && (oldGen.size()==1) && (selectedP.size()==1) && (oldGen.getEAIndividual(0).equals(selectedP.getEAIndividual(0)))) { @@ -152,7 +168,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In } double[] newMeanX = calcMeanX(params.weights, selectedSorted); - if (TRACE_1) System.out.println("newMeanX: " + BeanInspector.toString(newMeanX)); + if (TRACE_1) { + System.out.println("newMeanX: " + BeanInspector.toString(newMeanX)); + } int dim=params.meanX.length; double[] BDz = new double[dim]; @@ -219,19 +237,29 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In System.out.println("newPathS: " + BeanInspector.toString(newPathS)); } - if (TRACE_1) System.out.println("Bef: C is \n" + params.mC.toString()); - if (params.meanX == null) params.meanX = newMeanX; + if (TRACE_1) { + System.out.println("Bef: C is \n" + params.mC.toString()); + } + if (params.meanX == null) { + params.meanX = newMeanX; + } updateCov(params, newPathC, newMeanX, hsig, mu, selectedSorted); updateBD(params); - if (TRACE_2) System.out.println("Aft: C is " + params.mC.toString()); + if (TRACE_2) { + System.out.println("Aft: C is " + params.mC.toString()); + } /* update of sigma */ double sigFact = Math.exp(((psNorm / expRandStepLen) - 1) * params.c_sig / params.d_sig); - if (Double.isInfinite(sigFact)) params.sigma *= 10.; // in larger search spaces sigma tends to explode after init. - else params.sigma *= sigFact; + if (Double.isInfinite(sigFact)) { + params.sigma *= 10.; + } // in larger search spaces sigma tends to explode after init. + else { + params.sigma *= sigFact; + } if (!testAndCorrectNumerics(params, generation, selectedSorted)) { // parameter seemingly exploded... @@ -264,8 +292,12 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In Population newPop, boolean updateSelected) { // nothing to do? Oh yes, we can easily transfer the cma-params from the old to the new population. if (!newPop.hasData(cmaParamsKey)) { - if (!oldPop.hasData(cmaParamsKey)) System.err.println("warning: no cma param set found (MutateESRankMuCMA!"); - else newPop.putData(cmaParamsKey, oldPop.getData(cmaParamsKey)); + if (!oldPop.hasData(cmaParamsKey)) { + System.err.println("warning: no cma param set found (MutateESRankMuCMA!"); + } + else { + newPop.putData(cmaParamsKey, oldPop.getData(cmaParamsKey)); + } } //newPop.addData(cmaParamsKey, oldPop.getData(cmaParamsKey)); //newPop.addPopulationChangedEventListener(this); // listen to every population to be informed about reinit events @@ -285,7 +317,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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"); + 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; } @@ -304,10 +338,12 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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 (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.) { // System.err.println("Scaling by " + fac); @@ -317,7 +353,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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)); + if (i!=j) { + params.mC.set(j, i, params.mC.get(i,j)); + } } } } @@ -327,7 +365,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In private boolean nearlySame(double[] bestFitness, double[] worstFitness) { double epsilon = 1e-14; for (int i=0; iepsilon) return false; + if (Math.abs(bestFitness[i]-worstFitness[i])>epsilon) { + return false; + } } return true; } @@ -571,7 +611,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In ((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"); + } else { + System.err.println("Error, expecting InterfaceDataTypeDouble"); + } } private double[] mutate(CMAParamSet params, double[] x, double[][] range, int count) { @@ -585,7 +627,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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; + if (Double.isNaN(sampl[i])) { + sampl[i]=0; + } } // System.out.println("Sampling around " + BeanInspector.toString(meanX)); /* add mutation (sigma * B * (D*z)) */ @@ -609,7 +653,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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] + 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); @@ -627,7 +673,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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)); + if (TRACE_1) { + System.out.println("mutated indy: " + BeanInspector.toString(x)); + } return x; } @@ -647,14 +695,20 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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 + 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; + if (Double.isNaN(sampl[i])) { + sampl[i]=0; + } } // System.out.println("Sampling around " + BeanInspector.toString(meanX)); /* add mutation (sigma * B * (D*z)) */ @@ -676,8 +730,12 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In } } } 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; + 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) { @@ -734,7 +792,11 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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"); + if (TRACE_TEST) { + if (res) { + System.out.println("testAllDistBelow hit"); + } + } return res; } @@ -760,7 +822,11 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In res = res && (params.meanX[i] == (params.meanX[i] + d*getSigma(params, i)*ev_k[i])); i++; } - if (TRACE_TEST) if (res) System.out.println("testNoChangeAddingDevAxis hit"); + if (TRACE_TEST) { + if (res) { + System.out.println("testNoChangeAddingDevAxis hit"); + } + } return res; } @@ -779,7 +845,11 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In ret = ret || (params.meanX[i]==(params.meanX[i] + d*getSigma(params, i)*Math.sqrt(params.mC.get(i, i)))); i++; } - if (TRACE_TEST) if (ret) System.out.println("testNoEffectCoord hit"); + if (TRACE_TEST) { + if (ret) { + System.out.println("testNoEffectCoord hit"); + } + } return ret; } @@ -796,9 +866,13 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In 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"); + if (TRACE_TEST) { + System.out.println("testCCondition hit"); + } return true; - } else return false; + } else { + return false; + } } /** diff --git a/src/eva2/server/go/operators/mutation/MutateESSuccessRule.java b/src/eva2/server/go/operators/mutation/MutateESSuccessRule.java index a45af9a7..4e8eb6af 100644 --- a/src/eva2/server/go/operators/mutation/MutateESSuccessRule.java +++ b/src/eva2/server/go/operators/mutation/MutateESSuccessRule.java @@ -44,11 +44,19 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf public boolean equals(Object mutator) { if (mutator instanceof MutateESSuccessRule) { MutateESSuccessRule mut = (MutateESSuccessRule)mutator; - if (this.m_Sigma != mut.m_Sigma) return false; - if (this.m_SuccessRate != mut.m_SuccessRate) return false; - if (this.m_Alpha != mut.m_Alpha) return false; + if (this.m_Sigma != mut.m_Sigma) { + return false; + } + if (this.m_SuccessRate != mut.m_SuccessRate) { + return false; + } + if (this.m_Alpha != mut.m_Alpha) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to get a string representation of the mutation @@ -97,8 +105,12 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf * @param d The mutation operator. */ public void setSuccessRate(double d) { - if (d < 0) d = 0; - if (d > 1) d = 1; + if (d < 0) { + d = 0; + } + if (d > 1) { + d = 1; + } this.m_SuccessRate = d; } public double getSuccessRate() { @@ -112,7 +124,9 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf * @param d The mutation operator. */ public void setAlpha(double d) { - if (d < 1) d = 1; + if (d < 1) { + d = 1; + } this.m_Alpha = d; } public double getAlpha() { @@ -138,15 +152,18 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf 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++; + 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 - MutateESSuccessRule mutator = (MutateESSuccessRule)((AbstractEAIndividual)selectedPop.get(i)).getMutationOperator(); - updateMutator(rate, mutator); + 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); // 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(); updateMutator(rate, mutator); @@ -155,7 +172,11 @@ public class MutateESSuccessRule extends MutateESFixedStepSize implements Interf } private void updateMutator(double rate, MutateESSuccessRule mutator) { - if (rate < mutator.getSuccessRate()) mutator.decreaseMutationStepSize(); - else mutator.increaseMutationStepSize(); + if (rate < mutator.getSuccessRate()) { + mutator.decreaseMutationStepSize(); + } + else { + mutator.increaseMutationStepSize(); + } } } \ No newline at end of file diff --git a/src/eva2/server/go/operators/mutation/MutateGAAdaptive.java b/src/eva2/server/go/operators/mutation/MutateGAAdaptive.java index 759ae077..97c93719 100644 --- a/src/eva2/server/go/operators/mutation/MutateGAAdaptive.java +++ b/src/eva2/server/go/operators/mutation/MutateGAAdaptive.java @@ -49,11 +49,19 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable public boolean equals(Object mutator) { if (mutator instanceof MutateGAAdaptive) { MutateGAAdaptive mut = (MutateGAAdaptive)mutator; - if (this.m_MutationStep != mut.m_MutationStep) return false; - if (this.m_Tau1 != mut.m_Tau1) return false; - if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) return false; + if (this.m_MutationStep != mut.m_MutationStep) { + return false; + } + if (this.m_Tau1 != mut.m_Tau1) { + return false; + } + if (this.m_LowerLimitStepSize != mut.m_LowerLimitStepSize) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -75,7 +83,9 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable if (individual instanceof InterfaceGAIndividual) { 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; + 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())) { tmpBitSet.flip(i); @@ -126,7 +136,9 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setMutationStep(double d) { - if (d < 0) d = this.m_LowerLimitStepSize; + if (d < 0) { + d = this.m_LowerLimitStepSize; + } this.m_MutationStep = d; } public double getMutationStepSize() { @@ -140,7 +152,9 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitStepSize = d; } public double getLowerLimitStepSize() { @@ -154,7 +168,9 @@ public class MutateGAAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { diff --git a/src/eva2/server/go/operators/mutation/MutateGAGISwapBits.java b/src/eva2/server/go/operators/mutation/MutateGAGISwapBits.java index bf513634..8634e4c0 100644 --- a/src/eva2/server/go/operators/mutation/MutateGAGISwapBits.java +++ b/src/eva2/server/go/operators/mutation/MutateGAGISwapBits.java @@ -56,10 +56,16 @@ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializab 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; + if (this.minNumMutations != mut.minNumMutations) { + return false; + } + if (this.maxNumMutations != mut.maxNumMutations) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -109,8 +115,12 @@ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializab // 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())); } @@ -133,8 +143,12 @@ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializab } 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; + 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) { @@ -170,8 +184,12 @@ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializab // } protected Object valueAt(Object genotype, int k) { - if (genotype instanceof BitSet) return ((BitSet)genotype).get(k); - else return ((int[])genotype)[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 @@ -205,7 +223,9 @@ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializab * @param mutations The number of mutations. */ public void setMinNumberOfMutations(int mutations) { - if (mutations < 0) mutations = 0; + if (mutations < 0) { + mutations = 0; + } this.minNumMutations = mutations; } public int getMinNumberOfMutations() { @@ -216,7 +236,9 @@ public class MutateGAGISwapBits implements InterfaceMutation, java.io.Serializab } public void setMaxNumberOfMutations(int mutations) { - if (mutations < 0) mutations = 0; + if (mutations < 0) { + mutations = 0; + } this.maxNumMutations = mutations; } public int getMaxNumberOfMutations() { diff --git a/src/eva2/server/go/operators/mutation/MutateGAShiftSubstring.java b/src/eva2/server/go/operators/mutation/MutateGAShiftSubstring.java index 10ac1d9d..17c348a4 100644 --- a/src/eva2/server/go/operators/mutation/MutateGAShiftSubstring.java +++ b/src/eva2/server/go/operators/mutation/MutateGAShiftSubstring.java @@ -44,10 +44,16 @@ public class MutateGAShiftSubstring implements InterfaceMutation, java.io.Serial public boolean equals(Object mutator) { if (mutator instanceof MutateGAShiftSubstring) { MutateGAShiftSubstring mut = (MutateGAShiftSubstring)mutator; - if (this.m_subStringLength != mut.m_subStringLength) return false; - if (this.m_shiftDistance != mut.m_shiftDistance) return false; + if (this.m_subStringLength != mut.m_subStringLength) { + return false; + } + if (this.m_shiftDistance != mut.m_shiftDistance) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator @@ -92,8 +98,12 @@ public class MutateGAShiftSubstring implements InterfaceMutation, java.io.Serial } private int selectShiftDist(int len) { - if (m_shiftDistance<=0) return RNG.randomInt(len); - else return m_shiftDistance; + if (m_shiftDistance<=0) { + return RNG.randomInt(len); + } + else { + return m_shiftDistance; + } } private int[] selectSubstring(BitSet tmpBitSet, int len) { diff --git a/src/eva2/server/go/operators/mutation/MutateGASwapBitsSegmentwise.java b/src/eva2/server/go/operators/mutation/MutateGASwapBitsSegmentwise.java index 06e271a3..27065a67 100644 --- a/src/eva2/server/go/operators/mutation/MutateGASwapBitsSegmentwise.java +++ b/src/eva2/server/go/operators/mutation/MutateGASwapBitsSegmentwise.java @@ -71,12 +71,22 @@ public class MutateGASwapBitsSegmentwise implements InterfaceMutation, java.io.S public boolean equals(Object mutator) { if (mutator instanceof MutateGASwapBitsSegmentwise) { MutateGASwapBitsSegmentwise mut = (MutateGASwapBitsSegmentwise)mutator; - if (this.mutationProbPerSegment != mut.mutationProbPerSegment) return false; - if (this.segmentLength != mut.segmentLength) return false; - if (this.multiplesPerSegment != mut.multiplesPerSegment) return false; - if (this.preferPairs != mut.preferPairs) return false; + if (this.mutationProbPerSegment != mut.mutationProbPerSegment) { + return false; + } + if (this.segmentLength != mut.segmentLength) { + return false; + } + if (this.multiplesPerSegment != mut.multiplesPerSegment) { + return false; + } + if (this.preferPairs != mut.preferPairs) { + return false; + } return true; - } else return false; + } else { + return false; + } } /** This method allows you to init the mutation operator diff --git a/src/eva2/server/go/operators/mutation/MutateGAUniform.java b/src/eva2/server/go/operators/mutation/MutateGAUniform.java index c5159d94..5648838b 100644 --- a/src/eva2/server/go/operators/mutation/MutateGAUniform.java +++ b/src/eva2/server/go/operators/mutation/MutateGAUniform.java @@ -54,7 +54,9 @@ public class MutateGAUniform implements InterfaceMutation, Serializable { @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { - if (useInvertedLength && (individual instanceof InterfaceGAIndividual)) setBitwiseProb(1./((double)((InterfaceGAIndividual)individual).getGenotypeLength())); + if (useInvertedLength && (individual instanceof InterfaceGAIndividual)) { + setBitwiseProb(1./((double)((InterfaceGAIndividual)individual).getGenotypeLength())); + } } /** @@ -65,16 +67,22 @@ public class MutateGAUniform implements InterfaceMutation, Serializable { 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); + if (bitwiseProb <0. && (bitwiseProb > 1.)) { + System.err.println("Warning, probability should be within [0,1], given: " + bitwiseProb); + } this.bitwiseProb = bitwiseProb; } public String bitwiseProbTipText() { diff --git a/src/eva2/server/go/operators/mutation/MutateGIInsertDelete.java b/src/eva2/server/go/operators/mutation/MutateGIInsertDelete.java index a138d0a0..d935fd96 100644 --- a/src/eva2/server/go/operators/mutation/MutateGIInsertDelete.java +++ b/src/eva2/server/go/operators/mutation/MutateGIInsertDelete.java @@ -40,10 +40,14 @@ public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializ public boolean equals(Object mutator) { if (mutator instanceof MutateGIInsertDelete) { MutateGIInsertDelete mut = (MutateGIInsertDelete)mutator; - if (this.m_MaxLengthOfInsDel != mut.m_MaxLengthOfInsDel) return false; + if (this.m_MaxLengthOfInsDel != mut.m_MaxLengthOfInsDel) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator @@ -80,7 +84,9 @@ public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializ //this.pintInt("Before ", x); length = RNG.randomInt(1, this.m_MaxLengthOfInsDel); boolean insert = RNG.flipCoin(0.5); - if ((!insert) && (length >= x.length-1)) insert = true; + if ((!insert) && (length >= x.length-1)) { + insert = true; + } if (insert) { // insert position = RNG.randomInt(0, x.length-1); @@ -104,7 +110,9 @@ public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializ 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; + if (newX.length <=1) { + return; + } for (int i = 0; i < position; i++) { newX[i] = x[i]; newRange[i] = range[i]; @@ -114,12 +122,16 @@ public class MutateGIInsertDelete implements InterfaceMutation, java.io.Serializ newRange[i-length] = range[i]; } } - if (newX.length <= 1) System.out.println("newX " + newX.length); + 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(); - if (newX.length <= 1) System.out.println("newX " + newX.length); + if (newX.length <= 1) { + System.out.println("newX " + newX.length); + } } } diff --git a/src/eva2/server/go/operators/mutation/MutateGIInvert.java b/src/eva2/server/go/operators/mutation/MutateGIInvert.java index a4a7c328..eecf8cad 100644 --- a/src/eva2/server/go/operators/mutation/MutateGIInvert.java +++ b/src/eva2/server/go/operators/mutation/MutateGIInvert.java @@ -40,10 +40,14 @@ public class MutateGIInvert implements InterfaceMutation, java.io.Serializable { public boolean equals(Object mutator) { if (mutator instanceof MutateGIInvert) { MutateGIInvert mut = (MutateGIInvert)mutator; - if (this.m_MaxLengthOfInvert != mut.m_MaxLengthOfInvert) return false; + if (this.m_MaxLengthOfInvert != mut.m_MaxLengthOfInvert) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator @@ -66,7 +70,9 @@ public class MutateGIInvert implements InterfaceMutation, java.io.Serializable { int range, center, index = 0; //this.pintInt("Before ", x); range = RNG.randomInt(1, this.m_MaxLengthOfInvert); - if (2*range >= x.length) return; + if (2*range >= x.length) { + return; + } center = RNG.randomInt(0+range, x.length-1-range); //System.out.println("Range: " + range + " Center: " + center); int[] tmp = new int[x.length]; diff --git a/src/eva2/server/go/operators/mutation/MutateGINominal.java b/src/eva2/server/go/operators/mutation/MutateGINominal.java index a7b4cd86..ece11ca6 100644 --- a/src/eva2/server/go/operators/mutation/MutateGINominal.java +++ b/src/eva2/server/go/operators/mutation/MutateGINominal.java @@ -40,10 +40,14 @@ public class MutateGINominal implements InterfaceMutation, java.io.Serializable public boolean equals(Object mutator) { if (mutator instanceof MutateGINominal) { MutateGINominal mut = (MutateGINominal)mutator; - if (this.m_NumberOfMutations != mut.m_NumberOfMutations) return false; + if (this.m_NumberOfMutations != mut.m_NumberOfMutations) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator diff --git a/src/eva2/server/go/operators/mutation/MutateGIOrdinal.java b/src/eva2/server/go/operators/mutation/MutateGIOrdinal.java index 1d0246a7..0dba2d6c 100644 --- a/src/eva2/server/go/operators/mutation/MutateGIOrdinal.java +++ b/src/eva2/server/go/operators/mutation/MutateGIOrdinal.java @@ -42,11 +42,17 @@ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable public boolean equals(Object mutator) { if (mutator instanceof MutateGIOrdinal) { MutateGIOrdinal mut = (MutateGIOrdinal)mutator; - if (this.m_StepSize != mut.m_StepSize) return false; - if (this.m_NumberOfMutations != mut.m_NumberOfMutations) return false; + if (this.m_StepSize != mut.m_StepSize) { + return false; + } + if (this.m_NumberOfMutations != mut.m_NumberOfMutations) { + return false; + } return true; } - else return false; + else { + return false; + } } /** This method allows you to init the mutation operator @@ -75,12 +81,20 @@ public class MutateGIOrdinal implements InterfaceMutation, java.io.Serializable mutate *= (range[mutInd][1] - range[mutInd][1]); mut = (int)Math.round(mutate); if (mut == 0) { - if (RNG.flipCoin(0.5)) mut = -1; - else mut = 1; + if (RNG.flipCoin(0.5)) { + mut = -1; + } + else { + mut = 1; + } } x[mutInd] += mut; - if (x[mutInd] < range[mutInd][0]) x[mutInd] = range[mutInd][0]; - if (x[mutInd] > range[mutInd][1]) x[mutInd] = range[mutInd][1]; + if (x[mutInd] < range[mutInd][0]) { + x[mutInd] = range[mutInd][0]; + } + if (x[mutInd] > range[mutInd][1]) { + x[mutInd] = range[mutInd][1]; + } } ((InterfaceGIIndividual)individual).SetIGenotype(x); } diff --git a/src/eva2/server/go/operators/mutation/MutateGISubset.java b/src/eva2/server/go/operators/mutation/MutateGISubset.java index d4f9220b..145dc7b1 100644 --- a/src/eva2/server/go/operators/mutation/MutateGISubset.java +++ b/src/eva2/server/go/operators/mutation/MutateGISubset.java @@ -99,7 +99,9 @@ public class MutateGISubset implements InterfaceMutation, Serializable { */ 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; + if (v>=range[index][0] && (v<=range[index][1])) { + return v; + } else { EVAERROR.errorMsgOnce("Warning, mutation subset violates range definition!"); return oldVal; @@ -113,7 +115,9 @@ public class MutateGISubset implements InterfaceMutation, Serializable { */ private boolean isMutable(int v) { for (int i=0; i 1) this.m_MutationStep = 1; - if (RNG.flipCoin(this.m_MutationStep)) ((IndividualInterface)individual).defaultMutate(); + if (this.m_MutationStep < this.m_LowerLimitStepSize) { + this.m_MutationStep = this.m_LowerLimitStepSize; + } + if (this.m_MutationStep > 1) { + this.m_MutationStep = 1; + } + if (RNG.flipCoin(this.m_MutationStep)) { + ((IndividualInterface)individual).defaultMutate(); + } } //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); } @@ -120,7 +136,9 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setMutationStep(double d) { - if (d < 0) d = this.m_LowerLimitStepSize; + if (d < 0) { + d = this.m_LowerLimitStepSize; + } this.m_MutationStep = d; } public double getMutationStepSize() { @@ -134,7 +152,9 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setLowerLimitStepSize(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_LowerLimitStepSize = d; } public double getLowerLimitStepSize() { @@ -148,7 +168,9 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setTau1(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau1 = d; } public double getTau1() { @@ -162,7 +184,9 @@ public class MutateGPAdaptive implements InterfaceMutation, java.io.Serializable * @param d The mutation operator. */ public void setTau2(double d) { - if (d < 0) d = 0; + if (d < 0) { + d = 0; + } this.m_Tau2 = d; } public double getTau2() { diff --git a/src/eva2/server/go/operators/mutation/MutateGPSingleNode.java b/src/eva2/server/go/operators/mutation/MutateGPSingleNode.java index b0af3415..200d9140 100644 --- a/src/eva2/server/go/operators/mutation/MutateGPSingleNode.java +++ b/src/eva2/server/go/operators/mutation/MutateGPSingleNode.java @@ -33,8 +33,12 @@ public class MutateGPSingleNode implements InterfaceMutation, java.io.Serializab */ @Override public boolean equals(Object mutator) { - if (mutator instanceof MutateGPSingleNode) return true; - else return false; + if (mutator instanceof MutateGPSingleNode) { + return true; + } + else { + return false; + } } /** This method allows you to init the mutation operator diff --git a/src/eva2/server/go/operators/mutation/MutateOBGAFlip.java b/src/eva2/server/go/operators/mutation/MutateOBGAFlip.java index cb35de42..55fe469f 100644 --- a/src/eva2/server/go/operators/mutation/MutateOBGAFlip.java +++ b/src/eva2/server/go/operators/mutation/MutateOBGAFlip.java @@ -41,8 +41,12 @@ public class MutateOBGAFlip implements InterfaceMutation, java.io.Serializable { */ @Override public boolean equals(Object mutator) { - if (mutator instanceof MutateOBGAFlip) return true; - else return false; + if (mutator instanceof MutateOBGAFlip) { + return true; + } + else { + return false; + } } @Override diff --git a/src/eva2/server/go/operators/mutation/MutateOBGAInversion.java b/src/eva2/server/go/operators/mutation/MutateOBGAInversion.java index c963b710..59ab023a 100644 --- a/src/eva2/server/go/operators/mutation/MutateOBGAInversion.java +++ b/src/eva2/server/go/operators/mutation/MutateOBGAInversion.java @@ -42,8 +42,12 @@ public class MutateOBGAInversion implements java.io.Serializable, InterfaceMutat */ @Override public boolean equals(Object mutator) { - if (mutator instanceof MutateOBGAInversion) return true; - else return false; + if (mutator instanceof MutateOBGAInversion) { + return true; + } + else { + return false; + } } @Override diff --git a/src/eva2/server/go/operators/mutation/PropertyMutationMixer.java b/src/eva2/server/go/operators/mutation/PropertyMutationMixer.java index 29488984..909f0e7b 100644 --- a/src/eva2/server/go/operators/mutation/PropertyMutationMixer.java +++ b/src/eva2/server/go/operators/mutation/PropertyMutationMixer.java @@ -22,8 +22,12 @@ public class PropertyMutationMixer implements java.io.Serializable { this.m_Weights[i] = 1/((double)d.length); } this.m_AvailableTargets = d; - if (selectAllOrNone) this.m_SelectedTargets = d.clone(); - else this.m_SelectedTargets = null; + if (selectAllOrNone) { + this.m_SelectedTargets = d.clone(); + } + else { + this.m_SelectedTargets = null; + } } public PropertyMutationMixer(PropertyMutationMixer d) { this.m_DescriptiveString = d.m_DescriptiveString; @@ -63,7 +67,9 @@ public class PropertyMutationMixer implements java.io.Serializable { return; } - if (d.length == this.m_Weights.length) return; + if (d.length == this.m_Weights.length) { + return; + } if (d.length > this.m_Weights.length) { double[] newWeights = new double[d.length]; @@ -143,7 +149,9 @@ public class PropertyMutationMixer implements java.io.Serializable { * @param index The index of the target to be removed. */ public void removeMutator(int index) { - if ((index < 0) || (index >= this.m_SelectedTargets.length)) return; + 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]; diff --git a/src/eva2/server/go/operators/mutation/PropertyMutationMixerEditor.java b/src/eva2/server/go/operators/mutation/PropertyMutationMixerEditor.java index ea510e93..d5a112ab 100644 --- a/src/eva2/server/go/operators/mutation/PropertyMutationMixerEditor.java +++ b/src/eva2/server/go/operators/mutation/PropertyMutationMixerEditor.java @@ -61,13 +61,18 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceMutation.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceMutation.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -220,13 +225,18 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito try { 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); - if (newEdit[l].m_Editor instanceof GenericObjectEditor) + if (newEdit[l].m_Editor == null) { + newEdit[l].m_Editor = PropertyEditorProvider.findEditor(InterfaceMutation.class); + } + if (newEdit[l].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) newEdit[l].m_Editor).setClassType(InterfaceMutation.class); + } newEdit[l].m_Editor.setValue(newEdit[l].m_Value); newEdit[l].m_Editor.addPropertyChangeListener(m_self); AbstractObjectEditor.findViewFor(newEdit[l]); - if (newEdit[l].m_View != null) newEdit[l].m_View.repaint(); + if (newEdit[l].m_View != null) { + newEdit[l].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } @@ -243,7 +253,9 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito int l = m_MutatorsWithWeights.getSelectedMutators().length, j = 0; 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); + if (event.getSource().equals(m_Delete[i])) { + m_MutatorsWithWeights.removeMutator(i); + } else { newEdit[j] = m_Editors[i]; j++; @@ -442,13 +454,18 @@ public class PropertyMutationMixerEditor extends JPanel implements PropertyEdito try { 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); - if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) + if (this.m_Editors[i].m_Editor == null) { + this.m_Editors[i].m_Editor = PropertyEditorProvider.findEditor(InterfaceMutation.class); + } + if (this.m_Editors[i].m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) this.m_Editors[i].m_Editor).setClassType(InterfaceMutation.class); + } this.m_Editors[i].m_Editor.setValue(this.m_Editors[i].m_Value); this.m_Editors[i].m_Editor.addPropertyChangeListener(this); AbstractObjectEditor.findViewFor(this.m_Editors[i]); - if (this.m_Editors[i].m_View != null) this.m_Editors[i].m_View.repaint(); + if (this.m_Editors[i].m_View != null) { + this.m_Editors[i].m_View.repaint(); + } } catch (Exception e) { System.out.println("Darn can't read the value..."); } diff --git a/src/eva2/server/go/operators/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java b/src/eva2/server/go/operators/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java index 1dd15297..6b4174b4 100644 --- a/src/eva2/server/go/operators/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java +++ b/src/eva2/server/go/operators/nichepso/absorption/ConsiderPBestAbsorptionStrategy.java @@ -37,7 +37,9 @@ public class ConsiderPBestAbsorptionStrategy extends StandardAbsorptionStrategy{ private boolean absorbtionConstraintViolation(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm) { AbstractEAIndividual indysPBest = (AbstractEAIndividual)indy.getData("PersonalBestKey"); AbstractEAIndividual subswarmsGBest = subswarm.getGBestIndividual(); - if (indysPBest.isDominating(subswarmsGBest)) return true; + if (indysPBest.isDominating(subswarmsGBest)) { + return true; + } return false; } } diff --git a/src/eva2/server/go/operators/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java b/src/eva2/server/go/operators/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java index 0aa797b8..2ed39676 100644 --- a/src/eva2/server/go/operators/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java +++ b/src/eva2/server/go/operators/nichepso/absorption/EuclideanDiversityAbsorptionStrategy.java @@ -58,7 +58,9 @@ public class EuclideanDiversityAbsorptionStrategy extends StandardAbsorptionStra double meanDistanceFromGBestPos = subswarm.getEuclideanDiversity(); if (meanDistanceFromGBestPos < getEpsilon()){ return true; - } else return false; + } else { + return false; + } } /********************************************************************************************************************** diff --git a/src/eva2/server/go/operators/nichepso/absorption/StandardAbsorptionStrategy.java b/src/eva2/server/go/operators/nichepso/absorption/StandardAbsorptionStrategy.java index 02c5ccc3..80902ccd 100644 --- a/src/eva2/server/go/operators/nichepso/absorption/StandardAbsorptionStrategy.java +++ b/src/eva2/server/go/operators/nichepso/absorption/StandardAbsorptionStrategy.java @@ -54,7 +54,9 @@ public class StandardAbsorptionStrategy implements InterfaceAbsorptionStrategy, double dist = subswarm.distance(indy,gbest); // euclidean distance if (dist <= R){ return true; - }else return false; + }else { + return false; + } } diff --git a/src/eva2/server/go/operators/nichepso/deactivation/ImprovementDeactivationStrategy.java b/src/eva2/server/go/operators/nichepso/deactivation/ImprovementDeactivationStrategy.java index a8ef73bc..3466c4fc 100644 --- a/src/eva2/server/go/operators/nichepso/deactivation/ImprovementDeactivationStrategy.java +++ b/src/eva2/server/go/operators/nichepso/deactivation/ImprovementDeactivationStrategy.java @@ -67,7 +67,9 @@ public class ImprovementDeactivationStrategy implements InterfaceDeactivationStr 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)=0 && (fitArch.get(archIndex)pop.getGeneration()) return false; - else return true; + if (lastAdaption+adptIntervalGenerations>pop.getGeneration()) { + return false; + } + else { + return true; + } } /* diff --git a/src/eva2/server/go/operators/paramcontrol/ConstraintBasedAdaption.java b/src/eva2/server/go/operators/paramcontrol/ConstraintBasedAdaption.java index 6054976d..a065c852 100644 --- a/src/eva2/server/go/operators/paramcontrol/ConstraintBasedAdaption.java +++ b/src/eva2/server/go/operators/paramcontrol/ConstraintBasedAdaption.java @@ -54,12 +54,20 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { @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() + " ! "); + 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); - if (lastBestSatisfactionState.size()==genGap) lastBestSatisfactionState.poll(); + 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!"); + if (!lastBestSatisfactionState.offer(bestIsFeasible)) { + System.err.println("Error, could not push best indy state!"); + } changed=maybeAdaptFactor((AbstractConstraint)obj); } @@ -71,7 +79,9 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { currentFactor = maxPenalty/initialPenalty; curPen=maxPenalty; } - if (TRACE && changed) System.out.println("NEW penalty: " + curPen); + if (TRACE && changed) { + System.out.println("NEW penalty: " + curPen); + } return curPen; } @@ -81,19 +91,29 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { boolean allValid=true; boolean allInvalid=true; for (Boolean isFeasible : lastBestSatisfactionState) { - if (isFeasible) allInvalid=false; - else allValid=false; + 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); + 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); + 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..."); + } else if (TRACE) { + System.out.println("not yet looking at " + genGap + " individuals..."); + } return changed; } diff --git a/src/eva2/server/go/operators/paramcontrol/LinearParamAdaption.java b/src/eva2/server/go/operators/paramcontrol/LinearParamAdaption.java index de62c339..bf36125f 100644 --- a/src/eva2/server/go/operators/paramcontrol/LinearParamAdaption.java +++ b/src/eva2/server/go/operators/paramcontrol/LinearParamAdaption.java @@ -72,10 +72,14 @@ implements InterfaceHasUpperDoubleBound, GenericParamAdaption, Serializable { setEndV(u); setStartV(u); } else if (getEndV()>getStartV()) { // end value is larger - if (u desiredActivity) { // too high act, so decrease inertness return Math.max(minInert, currentInertness - deltaInertness); - } else return currentInertness; + } 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); + 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) { @@ -122,7 +130,9 @@ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable { } 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!"); + 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."; @@ -154,7 +164,9 @@ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable { 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!"); + if (getFinalActivity()==0) { + System.err.println("Warning: zero final activity will not work with exponential schedule, set it to small epsilon!"); + } } public String exponentialScheduleTipText() { diff --git a/src/eva2/server/go/operators/paramcontrol/ParameterControlManager.java b/src/eva2/server/go/operators/paramcontrol/ParameterControlManager.java index 49b5427d..645ed692 100644 --- a/src/eva2/server/go/operators/paramcontrol/ParameterControlManager.java +++ b/src/eva2/server/go/operators/paramcontrol/ParameterControlManager.java @@ -41,8 +41,12 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria } public ParameterControlManager(ParameterControlManager o) { - if (o.initialValues!=null) initialValues = o.initialValues.clone(); - else initialValues=null; + 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 names = new Vector(singleAdapters.length); for (int i = 0; i < singleAdapters.length; i++) { String prm=singleAdapters[i].getControlledParam(); - if (prm!=null) names.add(prm); + if (prm!=null) { + names.add(prm); + } } return names.toArray(new String[names.size()]); - } else return null; + } else { + return null; + } } /** @@ -157,7 +169,9 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria vals[i]=singleAdapters[i].calcValue(obj, pop, iteration, maxIteration); } return vals; - } else return null; + } else { + return null; + } } public ParamAdaption[] getSingleAdapters() { @@ -174,7 +188,9 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria * @param pa */ public void addSingleAdapter(ParamAdaption pa) { - if (singleAdapters==null) setSingleAdapters(new ParamAdaption[]{pa}); + if (singleAdapters==null) { + setSingleAdapters(new ParamAdaption[]{pa}); + } else { ParamAdaption[] newP = new ParamAdaption[singleAdapters.length+1]; for (int i=0; i 2) smPop = new Population(); + if (dim > 2) { + smPop = new Population(); + } double[][] f = new double[archive.size()][dim]; double[] tmpF, redF; for (int i = 0; i < f.length; i++) { @@ -157,7 +165,9 @@ public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable // 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]); } else { diff --git a/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java b/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java index 00933375..e52167af 100644 --- a/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java +++ b/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java @@ -75,7 +75,9 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io */ private void loadReferenceData() { String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); - if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); + if (lines == null) { + System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); + } lines[0].trim(); this.m_Titles = lines[0].split("\t"); ArrayList tmpA = new ArrayList(); @@ -140,7 +142,9 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io } // Now we have an archive, lets caluculate the s-metric // first extract the fitnesscases from the archive - if (dim > 2) smPop = new Population(); + if (dim > 2) { + smPop = new Population(); + } double[][] f = new double[archive.size()][dim]; double[] tmpF, redF; for (int i = 0; i < f.length; i++) { @@ -189,7 +193,9 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io // 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]); } else { diff --git a/src/eva2/server/go/operators/postprocess/PostProcess.java b/src/eva2/server/go/operators/postprocess/PostProcess.java index 2f695b48..264d1609 100644 --- a/src/eva2/server/go/operators/postprocess/PostProcess.java +++ b/src/eva2/server/go/operators/postprocess/PostProcess.java @@ -133,7 +133,9 @@ public class PostProcess { AbstractEAIndividual[] optsFound = getFoundOptimaArray(pop, optima, epsilon, bTakeFitter); for (int i=0; i= 1) result.addAll((Collection)clusters[j]); // easy case + 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) { @@ -251,8 +261,12 @@ public class PostProcess { Population result = new Population(); for (int i=0; ifitNorm)) result.add(indy); + if (bSmallerEq && (PhenotypeMetric.norm(indy.getFitness())<=fitNorm)) { + result.add(indy); + } + else if (!bSmallerEq && (PhenotypeMetric.norm(indy.getFitness())>fitNorm)) { + result.add(indy); + } } return result; } @@ -276,11 +290,19 @@ public class PostProcess { Population result = new Population(); for (int i=0; i=0) && (crit=0) && (critfitThresh)) result.add(indy); + if (bSmallerEq && (curFit<=fitThresh)) { + result.add(indy); + } + else if (!bSmallerEq && (curFit>fitThresh)) { + result.add(indy); + } } return result; } @@ -573,7 +595,9 @@ public class PostProcess { 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); + if (TRACE) { + System.out.println("perturb " + index + " is " + perturb); + } subPop = NelderMeadSimplex.createNMSPopulation(candidates.getEAIndividual(index), absToRelPerturb(perturb, range), range, false); } // subPop.setSameParams(candidates); @@ -628,7 +652,9 @@ public class PostProcess { return evalsDone; } else { int stepsPerCand = (steps-(candCnt*(dim-1)))/candCnt; - if (TRACE) System.out.println("employing " + stepsPerCand + " steps per cand."); + 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); @@ -679,7 +705,9 @@ public class PostProcess { 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 (TRACE) { + System.out.println("employing " + stepsPerCand + " per candidate."); + } if (stepsPerCand < 1) { System.err.println("Too few steps allowed!"); return 0; @@ -699,7 +727,9 @@ public class PostProcess { break; default: System.err.println("Invalid pp method in processSingleCandidatesNMCMA!"); } - if (stepsAbortedFlag==null) System.err.println("Error 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."); @@ -734,23 +764,41 @@ public class PostProcess { public static double[][] getDoubleRange(AbstractEAIndividual indy) { if (indy instanceof InterfaceDataTypeDouble || (indy instanceof InterfaceESIndividual)) { - if (indy instanceof InterfaceESIndividual) return ((InterfaceESIndividual)indy).getDoubleRange(); - else return ((InterfaceDataTypeDouble)indy).getDoubleRange(); - } else return null; + if (indy instanceof InterfaceESIndividual) { + return ((InterfaceESIndividual)indy).getDoubleRange(); + } + else { + return ((InterfaceDataTypeDouble)indy).getDoubleRange(); + } + } else { + return null; + } } public static double[] getDoubleData(AbstractEAIndividual indy) { if (indy instanceof InterfaceDataTypeDouble || (indy instanceof InterfaceESIndividual)) { - if (indy instanceof InterfaceESIndividual) return ((InterfaceESIndividual)indy).getDGenotype(); - else return ((InterfaceDataTypeDouble)indy).getDoubleData(); - } else return null; + if (indy instanceof InterfaceESIndividual) { + return ((InterfaceESIndividual)indy).getDGenotype(); + } + else { + return ((InterfaceDataTypeDouble)indy).getDoubleData(); + } + } else { + return null; + } } public static void setDoubleData(AbstractEAIndividual indy, double[] data) { if (indy instanceof InterfaceDataTypeDouble || (indy instanceof InterfaceESIndividual)) { - if (indy instanceof InterfaceESIndividual) ((InterfaceESIndividual)indy).SetDGenotype(data); - else ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(data); - } else throw new RuntimeException("Error, unable to set double data to individual instance " + indy.getClass() + " in PostProcess.setDoubleData"); + if (indy instanceof InterfaceESIndividual) { + ((InterfaceESIndividual)indy).SetDGenotype(data); + } + else { + ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(data); + } + } else { + throw new RuntimeException("Error, unable to set double data to individual instance " + indy.getClass() + " in PostProcess.setDoubleData"); + } } /** @@ -796,7 +844,9 @@ public class PostProcess { public static AbstractEAIndividual createRandomDoubleClone(AbstractEAIndividual indy, double[][] range) { AbstractEAIndividual tmpIndy = (AbstractEAIndividual)indy.clone(); double[] data = getDoubleData(tmpIndy); - if (data==null) throw new RuntimeException("Error, given individual must be double compliant in PostProcess.createRandomDoubleClone"); + if (data==null) { + throw new RuntimeException("Error, given individual must be double compliant in PostProcess.createRandomDoubleClone"); + } ESIndividualDoubleData.defaultInit(data, range); setDoubleData(tmpIndy, data); return tmpIndy; @@ -828,7 +878,9 @@ public class PostProcess { private static OptimizerRunnable getRunnable(int rnblID) { synchronized (ppRunnables) { for (int i=0; i(clust, improvement); } @@ -958,17 +1017,20 @@ public class PostProcess { * This may be expensive computationally. */ public static void evaluateMultiModal(Population solutions, AbstractOptimizationProblem prob, InterfaceTextListener listener) { - if (listener == null) return; + 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)); - } + 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 // double epsilonPhenoSpace = 0.01, epsilonFitConv = 1e-10, clusterSigma = 0.; @@ -1025,9 +1087,15 @@ public class PostProcess { // ##### 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; + 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; + } int stepsDone = 0; if (params.getPostProcessSteps() > 0) { @@ -1044,7 +1112,9 @@ public class PostProcess { // #### 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 (listener != null) { + listener.println("Post processing: " + stepsDone + " steps done."); + } if (params.isWithPlot()) { plot = draw("After " + stepsDone + " steps ("+ params.getPPMethod() + ")", null, stateBeforeLS, clusteredPop, problem); } @@ -1054,10 +1124,18 @@ public class PostProcess { // 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("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); @@ -1070,9 +1148,15 @@ public class PostProcess { 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) { + 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); @@ -1087,14 +1171,17 @@ public class PostProcess { 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() + ")"); + 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 0) { - if (listener!=null) listener.print(" measures fit: "); + 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.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 (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); @@ -1210,7 +1327,9 @@ public class PostProcess { 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; + if (postProcessClusterSigma > 0.) { + resolution = postProcessClusterSigma; + } switch (method) { case hillClimber: return resolution/2.; @@ -1251,14 +1370,20 @@ public class PostProcess { } if (!found) { // System.err.println("warning, equal candidates in PostProcess.findNMSPerturb - converged population?!"); - if (maxAbsPerturb>0) return maxAbsPerturb; + 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.); - else return minDistNeighbour/3.; + if (maxAbsPerturb>0) { + return Math.min(maxAbsPerturb, minDistNeighbour/3.); + } + else { + return minDistNeighbour/3.; + } } /** @@ -1322,11 +1447,15 @@ public class PostProcess { public static double getAvgDistToNeighbor(int index, Population pop) { double distSum = 0; int cnt = pop.size()-1; - if (cnt == 0) return 0.; + if (cnt == 0) { + return 0.; + } else { double[] indyPos = AbstractEAIndividual.getDoublePositionShallow(pop.getEAIndividual(index)); for (int i=0; i= 0) return pop.get(index); + if (index >= 0) { + return pop.get(index); + } else { // darn all individuals seem to violate the constraints // so lets select the guy with the least worst constraint violation @@ -123,8 +125,12 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial bestProb = indy.getConstraintViolation(); } } - if (index >= 0) return pop.get(index); - else return pop.get(RNG.randomInt(0, pop.size()-1)); + if (index >= 0) { + return pop.get(index); + } + else { + return pop.get(RNG.randomInt(0, pop.size()-1)); + } } } else { for (int i = 0; i < pop.size(); i++) { @@ -142,8 +148,12 @@ public class SelectBestIndividuals implements InterfaceSelection, java.io.Serial bestProb = indy.getFitness(crit); } } - if (index >= 0) return pop.get(index); - else return pop.get(RNG.randomInt(0, pop.size()-1)); + if (index >= 0) { + return pop.get(index); + } + else { + return pop.get(RNG.randomInt(0, pop.size()-1)); + } } } diff --git a/src/eva2/server/go/operators/selection/SelectBestSingle.java b/src/eva2/server/go/operators/selection/SelectBestSingle.java index 84f8666c..72c0dd83 100644 --- a/src/eva2/server/go/operators/selection/SelectBestSingle.java +++ b/src/eva2/server/go/operators/selection/SelectBestSingle.java @@ -59,7 +59,9 @@ public class SelectBestSingle implements InterfaceSelection, java.io.Serializabl int currentCriteria = 0, critSize; double currentBestValue; - if (population.size()==0) return population; // trivial + if (population.size()==0) { + return population; + } // trivial critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length; result.setTargetSize(size); if (this.m_ObeyDebsConstViolationPrinciple) { @@ -118,7 +120,9 @@ public class SelectBestSingle implements InterfaceSelection, java.io.Serializabl return newPartners; } return this.selectFrom(newPartners, size); - } else return this.selectFrom(availablePartners, size); + } else { + return this.selectFrom(availablePartners, size); + } } /********************************************************************************************************************** * These are for GUI diff --git a/src/eva2/server/go/operators/selection/SelectEPTournaments.java b/src/eva2/server/go/operators/selection/SelectEPTournaments.java index 13bbcb97..0a3ff284 100644 --- a/src/eva2/server/go/operators/selection/SelectEPTournaments.java +++ b/src/eva2/server/go/operators/selection/SelectEPTournaments.java @@ -65,9 +65,13 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ 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))) best[l] = rand; + 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)) best[l] = rand; + if (tmpIndy.getFitness(l) < ((AbstractEAIndividual)population.get(best[l])).getFitness(l)) { + best[l] = rand; + } } } } @@ -140,8 +144,12 @@ public class SelectEPTournaments implements InterfaceSelection, java.io.Serializ mostVictories = this.m_Victories[i][crit]; } } - if (index >= 0) return pop.get(index); - else return pop.get(RNG.randomInt(0, pop.size()-1)); + if (index >= 0) { + return pop.get(index); + } + else { + return pop.get(RNG.randomInt(0, pop.size()-1)); + } } /** This method allows you to select partners for a given Individual diff --git a/src/eva2/server/go/operators/selection/SelectHomologousMate.java b/src/eva2/server/go/operators/selection/SelectHomologousMate.java index e18265be..373ce71d 100644 --- a/src/eva2/server/go/operators/selection/SelectHomologousMate.java +++ b/src/eva2/server/go/operators/selection/SelectHomologousMate.java @@ -60,8 +60,12 @@ public class SelectHomologousMate extends SelectTournament implements java.io.Se } } //System.out.println("Partners Size: " + possibleMates.size()); - if (possibleMates.size() <=1) return this.selectFrom(availablePartners, size); - else return this.selectFrom(possibleMates, size); + if (possibleMates.size() <=1) { + return this.selectFrom(availablePartners, size); + } + else { + return this.selectFrom(possibleMates, size); + } } /********************************************************************************************************************** diff --git a/src/eva2/server/go/operators/selection/SelectMOMAIIDominanceCounter.java b/src/eva2/server/go/operators/selection/SelectMOMAIIDominanceCounter.java index 59ff3ee0..0d50ffa9 100644 --- a/src/eva2/server/go/operators/selection/SelectMOMAIIDominanceCounter.java +++ b/src/eva2/server/go/operators/selection/SelectMOMAIIDominanceCounter.java @@ -73,7 +73,9 @@ public class SelectMOMAIIDominanceCounter implements InterfaceSelection, java.io // lets count the number of dominant solutions int domCount = 0; for (int j = 0; j < malta.size(); j++) { - if (malta.get(i).isDominant) domCount++; + if (malta.get(i).isDominant) { + domCount++; + } } malta.m_SizeDominantSolutions = domCount; double[] fitness = new double[1]; diff --git a/src/eva2/server/go/operators/selection/SelectMONSGAIICrowedTournament.java b/src/eva2/server/go/operators/selection/SelectMONSGAIICrowedTournament.java index 8014e93c..1daf5844 100644 --- a/src/eva2/server/go/operators/selection/SelectMONSGAIICrowedTournament.java +++ b/src/eva2/server/go/operators/selection/SelectMONSGAIICrowedTournament.java @@ -78,9 +78,15 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. 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(); - if (tmpL < smallestLevel) smallestLevel = tmpL; - if (tmpIndy.getConstraintViolation() > 0) infeasiblePop.add(tmpIndy); - else feasiblePop.add(tmpIndy); + if (tmpL < smallestLevel) { + smallestLevel = tmpL; + } + if (tmpIndy.getConstraintViolation() > 0) { + infeasiblePop.add(tmpIndy); + } + else { + feasiblePop.add(tmpIndy); + } } if (feasiblePop.size() == 0) { // choose the least infeasible one @@ -97,7 +103,9 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. for (int i = 0; i < feasiblePop.size(); i++) { tmpIndy = (AbstractEAIndividual) feasiblePop.get(i); tmpL = ((Integer)tmpIndy.getData("ParetoLevel")).intValue(); - if (tmpL < smallestLevel) smallestLevel = tmpL; + if (tmpL < smallestLevel) { + smallestLevel = tmpL; + } } // first remove all individual from tmpPop which are not of smallestLevel for (int i = 0; i < feasiblePop.size(); i++) { @@ -106,7 +114,9 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java. i--; } } - if (feasiblePop.size() == 1) return (AbstractEAIndividual)feasiblePop.get(0); + if (feasiblePop.size() == 1) { + return (AbstractEAIndividual)feasiblePop.get(0); + } else { // now find the one with the biggest crowding distance result = (AbstractEAIndividual)feasiblePop.get(0); diff --git a/src/eva2/server/go/operators/selection/SelectMONonDominated.java b/src/eva2/server/go/operators/selection/SelectMONonDominated.java index 06fb4c16..faf63911 100644 --- a/src/eva2/server/go/operators/selection/SelectMONonDominated.java +++ b/src/eva2/server/go/operators/selection/SelectMONonDominated.java @@ -55,7 +55,9 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali if (this.m_ObeyDebsConstViolationPrinciple) { boolean feasible = false; for (int i = 0; i < population.size(); i++) { - if (((AbstractEAIndividual)population.get(i)).getConstraintViolation() == 0) feasible = true; + if (((AbstractEAIndividual)population.get(i)).getConstraintViolation() == 0) { + feasible = true; + } } if (feasible) { while (result.size() < size) { @@ -111,11 +113,15 @@ public class SelectMONonDominated implements InterfaceSelection, java.io.Seriali 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))) return false; + 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))) return false; + if (!(indy.equals(pop.get(i))) && (((AbstractEAIndividual)pop.get(i)).isDominatingEqual(indy))) { + return false; + } } } return true; diff --git a/src/eva2/server/go/operators/selection/SelectMOPESA.java b/src/eva2/server/go/operators/selection/SelectMOPESA.java index e2b60225..0f3da1a6 100644 --- a/src/eva2/server/go/operators/selection/SelectMOPESA.java +++ b/src/eva2/server/go/operators/selection/SelectMOPESA.java @@ -72,7 +72,9 @@ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable { winner = RNG.randomInt(0, population.size()-1); for (int i = 1; i < this.m_TournamentSize; i++) { tmp = RNG.randomInt(0, population.size()-1); - if (this.m_Squeeze[tmp] < this.m_Squeeze[winner]) winner = tmp; + if (this.m_Squeeze[tmp] < this.m_Squeeze[winner]) { + winner = tmp; + } } resultIndy = (AbstractEAIndividual) population.get(winner); } catch (java.lang.IndexOutOfBoundsException e) { diff --git a/src/eva2/server/go/operators/selection/SelectParticleWheel.java b/src/eva2/server/go/operators/selection/SelectParticleWheel.java index 9e3496c8..8976650f 100644 --- a/src/eva2/server/go/operators/selection/SelectParticleWheel.java +++ b/src/eva2/server/go/operators/selection/SelectParticleWheel.java @@ -67,8 +67,12 @@ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializ Population result = new Population(); result.setTargetSize(size); - if (selectFixedSteps ) selectFixed(population, size, result); - else selectDrawIndependent(population, size, result); + if (selectFixedSteps ) { + selectFixed(population, size, result); + } + else { + selectDrawIndependent(population, size, result); + } //// Unfortunately, this was really problem specific (mk) // diff --git a/src/eva2/server/go/operators/selection/SelectRandom.java b/src/eva2/server/go/operators/selection/SelectRandom.java index 9a1f161d..e41e4acc 100644 --- a/src/eva2/server/go/operators/selection/SelectRandom.java +++ b/src/eva2/server/go/operators/selection/SelectRandom.java @@ -29,7 +29,9 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable { public SelectRandom(boolean withRepl) { withReplacement=withRepl; - if (m_ObeyDebsConstViolationPrinciple) System.err.println("Error, replacement selection not supported for constrained selection (SelectRandom)"); + if (m_ObeyDebsConstViolationPrinciple) { + System.err.println("Error, replacement selection not supported for constrained selection (SelectRandom)"); + } } @Override @@ -63,8 +65,9 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable { int index = 0, rand; while (result.size() < size) { rand = RNG.randomInt(0, population.size()-1); - if (!((AbstractEAIndividual)population.get(rand)).violatesConstraint()) + if (!((AbstractEAIndividual)population.get(rand)).violatesConstraint()) { result.add(population.get(rand)); + } index++; if ((index > 0) && (result.size() == 0 )) { // darn there seems to be no feasible solution @@ -80,7 +83,9 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable { 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."); + 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= 0) return this.m_Index-1; + if (this.m_Index >= 0) { + return this.m_Index-1; + } else { - if (d < this.separator) return this.m_Left.getIndexFor(d); - else return this.m_Right.getIndexFor(d); + if (d < this.separator) { + return this.m_Left.getIndexFor(d); + } + else { + return this.m_Right.getIndexFor(d); + } } } @Override public String toString() { - if (this.m_Index >= 0) return "Ind:"+this.m_Index; + if (this.m_Index >= 0) { + return "Ind:"+this.m_Index; + } else { return "{"+this.m_Left.toString()+"} X<"+this.separator+" {"+this.m_Right.toString()+"}"; } @@ -167,8 +175,12 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser for (int i = 0; i < population.size(); i++) { tmpD = ((AbstractEAIndividual)(population.get(i))).getSelectionProbability(currentCriteria); logger += tmpD + "; "; - if (random < (sum + tmpD)) return ((AbstractEAIndividual)(population.get(i))); - else sum += tmpD; + if (random < (sum + tmpD)) { + return ((AbstractEAIndividual)(population.get(i))); + } + else { + sum += tmpD; + } } } System.out.println("Selection returns null, while computing: " + logger); diff --git a/src/eva2/server/go/operators/selection/probability/AbstractSelProb.java b/src/eva2/server/go/operators/selection/probability/AbstractSelProb.java index f4636a0a..3fd25a25 100644 --- a/src/eva2/server/go/operators/selection/probability/AbstractSelProb.java +++ b/src/eva2/server/go/operators/selection/probability/AbstractSelProb.java @@ -74,7 +74,9 @@ public abstract class AbstractSelProb implements InterfaceSelectionProbability, tmpList = new ArrayList(); for (int j = 0; j < inputs.length; j++) { obj = tmpIndy.getData(inputs[j]); - if (obj==null) EVAERROR.errorMsgOnce("Error: could not get data by key " + inputs[j] + " from individual in AbstractSelProb"); + 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])); @@ -130,10 +132,16 @@ public abstract class AbstractSelProb implements InterfaceSelectionProbability, 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; + if (Double.isInfinite(result[i][j])) { + result[i][j] = Double.NaN; + } if (!Double.isNaN(result[i][j])) { - if (result[i][j] < min) min = result[i][j]; - if (result[i][j] > max) max = result[i][j]; + if (result[i][j] < min) { + min = result[i][j]; + } + if (result[i][j] > max) { + max = result[i][j]; + } } } for (int j = 0; j < result[i].length; j++) { diff --git a/src/eva2/server/go/operators/selection/probability/SelProbBoltzman.java b/src/eva2/server/go/operators/selection/probability/SelProbBoltzman.java index bdfce2fc..6df5f153 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbBoltzman.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbBoltzman.java @@ -47,7 +47,9 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ // 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; + if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + isFeasible = true; + } } if (isFeasible) { // at least one is feasible @@ -59,13 +61,17 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ // first find the worst, to be able to default double worst = Double.NEGATIVE_INFINITY; for (int i = 0; i < data.length; i++) { - if (data[i][x] > worst) worst = data[i][x]; + if (data[i][x] > worst) { + worst = data[i][x]; + } } 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; + } sum += result[i]; } @@ -74,26 +80,34 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ dev += Math.pow((result[i]-mean), 2); } dev = Math.sqrt(dev/(data.length-1)); - if (dev < 0.0000001) dev = 0.0000001; + if (dev < 0.0000001) { + dev = 0.0000001; + } sum = 0; for (int i = 0; i < data.length; i++) { - if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) + if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { result[i] = Math.exp((this.m_Q*-data[i][x])/dev); - else + } + 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 for (int i = 0; i < data.length; i++) { - result[i] /= sum; - } + if (sum == 0) { + for (int i = 0; i < data.length; i++) { + result[i] = 1/result.length; + } } + else { + for (int i = 0; i < data.length; i++) { + result[i] /= sum; + }} boolean check = true; for (int i = 0; i < data.length; i++) { - if (Double.isNaN(result[i])) check = false; + if (Double.isNaN(result[i])) { + check = false; + } } if (!check) { System.out.println("Boltzman Normation created major error (const+feasible)!"); @@ -124,23 +138,29 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ dev += Math.pow((result[i]-mean), 2); } dev = Math.sqrt(dev/(data.length-1)); - if (dev < 0.0000001) dev = 0.0000001; + 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); sum += result[i]; } - if (sum == 0) for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; - } - else for (int i = 0; i < data.length; i++) { - result[i] /= sum; - } + if (sum == 0) { + for (int i = 0; i < data.length; i++) { + result[i] = 1/result.length; + } } + else { + for (int i = 0; i < data.length; i++) { + result[i] /= sum; + }} boolean check = true; for (int i = 0; i < data.length; i++) { - if (Double.isNaN(result[i])) check = false; + if (Double.isNaN(result[i])) { + check = false; + } } if (!check) { System.out.println("Boltzman Normation created major error (const, but no feasible)!"); @@ -167,23 +187,29 @@ public class SelProbBoltzman extends AbstractSelProb implements java.io.Serializ dev += Math.pow((result[i]-mean), 2); } dev = Math.sqrt(dev/(data.length-1)); - if (dev < 0.0000001) dev = 0.0000001; + 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); sum += result[i]; } - if (sum == 0) for (int i = 0; i < data.length; i++) { - result[i] = 1/result.length; - } - else for (int i = 0; i < data.length; i++) { - result[i] /= sum; - } + if (sum == 0) { + for (int i = 0; i < data.length; i++) { + result[i] = 1/result.length; + } } + else { + for (int i = 0; i < data.length; i++) { + result[i] /= sum; + }} boolean check = true; for (int i = 0; i < data.length; i++) { - if (Double.isNaN(result[i])) check = false; + if (Double.isNaN(result[i])) { + check = false; + } } if (!check) { System.out.println("Boltzman Normation created major error (no const)!"); diff --git a/src/eva2/server/go/operators/selection/probability/SelProbFitnessSharing.java b/src/eva2/server/go/operators/selection/probability/SelProbFitnessSharing.java index db88ec40..44173aad 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbFitnessSharing.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbFitnessSharing.java @@ -120,7 +120,9 @@ public class SelProbFitnessSharing extends AbstractSelProb implements java.io.Se return this.m_SharingDistance; } public void setSharingDistance(double b){ - if (b < 0.000001) b = 0.000001; + if (b < 0.000001) { + b = 0.000001; + } this.m_SharingDistance = b; } public String sharingDistanceTipText() { diff --git a/src/eva2/server/go/operators/selection/probability/SelProbInvertByMax.java b/src/eva2/server/go/operators/selection/probability/SelProbInvertByMax.java index c7ed66ba..3f9afc6f 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbInvertByMax.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbInvertByMax.java @@ -49,7 +49,9 @@ public class SelProbInvertByMax extends AbstractSelProb { // first check if anyone holds the constraints int k=0; while ((k < population.size()) && !isFeasible) { - if (!(population.getEAIndividual(k)).violatesConstraint()) isFeasible = true; + if (!(population.getEAIndividual(k)).violatesConstraint()) { + isFeasible = true; + } k++; } } @@ -60,8 +62,12 @@ public class SelProbInvertByMax extends AbstractSelProb { 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]; + if (population.getEAIndividual(i).violatesConstraint()) { + result[i]=0; + } + else { + result[i] = maxFit - data[i][x]; + } sum += result[i]; } diff --git a/src/eva2/server/go/operators/selection/probability/SelProbLinearRanking.java b/src/eva2/server/go/operators/selection/probability/SelProbLinearRanking.java index 8ffefadc..bc3aa848 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbLinearRanking.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbLinearRanking.java @@ -44,7 +44,9 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser // 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; + if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + isFeasible = true; + } } if (isFeasible) { // at least one is feasible @@ -52,7 +54,9 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser // first find the worst, to be able to default double worst = Double.POSITIVE_INFINITY; for (int i = 0; i < data.length; i++) { - if (data[i][x] > worst) worst = data[i][x]; + if (data[i][x] > worst) { + worst = data[i][x]; + } } int[] rank_index = new int[data.length]; double[] fitness = new double[data.length]; @@ -72,7 +76,9 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser for (int index = 0; index < fitness.length; index++) { int min = index; for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) min = i; + if(fitness[min] > fitness[i]) { + min = i; + } } if(fitness[index] != fitness[min]) { temp = fitness[index]; @@ -105,7 +111,9 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser for (int index = 0; index < fitness.length; index++) { int min = index; for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) min = i; + if(fitness[min] > fitness[i]) { + min = i; + } } if(fitness[index] != fitness[min]) { temp = fitness[index]; @@ -139,7 +147,9 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser for (int index = 0; index < fitness.length; index++) { int min = index; for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) min = i; + if(fitness[min] > fitness[i]) { + min = i; + } } if(fitness[index] != fitness[min]) { temp = fitness[index]; @@ -178,8 +188,12 @@ public class SelProbLinearRanking extends AbstractSelProb implements java.io.Ser * @param x Long seed. */ public void setNappa(double x) { - if (x < 1) x = 1; - if (x > 2) x = 2; + if (x < 1) { + x = 1; + } + if (x > 2) { + x = 2; + } nappaPlus = x; this.nappaMinus = 2 - this.nappaPlus; } diff --git a/src/eva2/server/go/operators/selection/probability/SelProbNonLinearRanking.java b/src/eva2/server/go/operators/selection/probability/SelProbNonLinearRanking.java index 978d4580..8f9a4522 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbNonLinearRanking.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbNonLinearRanking.java @@ -47,7 +47,9 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. // 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; + if (!((AbstractEAIndividual)population.get(i)).violatesConstraint()) { + isFeasible = true; + } } if (isFeasible) { // at least one is feasible @@ -55,7 +57,9 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. // first find the worst, to be able to default double worst = Double.POSITIVE_INFINITY; for (int i = 0; i < data.length; i++) { - if (data[i][x] > worst) worst = data[i][x]; + if (data[i][x] > worst) { + worst = data[i][x]; + } } int[] rank_index = new int[data.length]; double[] fitness = new double[data.length]; @@ -75,7 +79,9 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. for (int index = 0; index < fitness.length; index++) { int min = index; for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) min = i; + if(fitness[min] > fitness[i]) { + min = i; + } } if(fitness[index] != fitness[min]) { temp = fitness[index]; @@ -112,7 +118,9 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. for (int index = 0; index < fitness.length; index++) { int min = index; for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) min = i; + if(fitness[min] > fitness[i]) { + min = i; + } } if(fitness[index] != fitness[min]) { temp = fitness[index]; @@ -151,7 +159,9 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. for (int index = 0; index < fitness.length; index++) { int min = index; for(int i = index; i < fitness.length; i++) { - if(fitness[min] > fitness[i]) min = i; + if(fitness[min] > fitness[i]) { + min = i; + } } if(fitness[index] != fitness[min]) { temp = fitness[index]; @@ -194,8 +204,12 @@ public class SelProbNonLinearRanking extends AbstractSelProb implements java.io. * @param x Long seed. */ public void setC(double x) { - if (x < 0) x = 0; - if (x > 1) x = 1; + if (x < 0) { + x = 0; + } + if (x > 1) { + x = 1; + } this.m_C = x; } public double getC() { diff --git a/src/eva2/server/go/operators/selection/probability/SelProbRanking.java b/src/eva2/server/go/operators/selection/probability/SelProbRanking.java index 85f66dd0..006dfb86 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbRanking.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbRanking.java @@ -48,8 +48,12 @@ public class SelProbRanking extends AbstractSelProb implements java.io.Serializa for (int j = i + 1; j < data.length; j++) { 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 result[j]++; + if (data[j][x] < data[i][x]) { + result[i]++; + } + 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()) { @@ -80,8 +84,12 @@ 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 (data[j][x] < data[i][x]) result[i]++; - else result[j]++; + if (data[j][x] < data[i][x]) { + result[i]++; + } + else { + result[j]++; + } } } diff --git a/src/eva2/server/go/operators/selection/probability/SelProbStandard.java b/src/eva2/server/go/operators/selection/probability/SelProbStandard.java index 708738d6..7ecc53db 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbStandard.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbStandard.java @@ -54,10 +54,12 @@ 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++) { diff --git a/src/eva2/server/go/operators/selection/probability/SelProbStandardScaling.java b/src/eva2/server/go/operators/selection/probability/SelProbStandardScaling.java index 77e48d76..ebc5a352 100644 --- a/src/eva2/server/go/operators/selection/probability/SelProbStandardScaling.java +++ b/src/eva2/server/go/operators/selection/probability/SelProbStandardScaling.java @@ -46,7 +46,9 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S boolean isFeasible = false; int k=0; while ((k < population.size()) && !isFeasible) { - if (!((AbstractEAIndividual)population.get(k)).violatesConstraint()) isFeasible = true; + if (!((AbstractEAIndividual)population.get(k)).violatesConstraint()) { + isFeasible = true; + } k++; } if (isFeasible) { @@ -58,20 +60,32 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S // first find the worst, to be able to default double worst = Double.POSITIVE_INFINITY; for (int i = 0; i < data.length; i++) { - if (data[i][x] > worst) worst = data[i][x]; + if (data[i][x] > worst) { + worst = data[i][x]; + } } 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; + } } for (int i = 0; i < data.length; i++) { - if (result[i] < min) min = result[i]; - if (result[i] > max) max = result[i]; + if (result[i] < min) { + min = result[i]; + } + if (result[i] > max) { + max = result[i]; + } + } + if (max != min) { + delta = max -min; + } + else { + delta = 1; } - if (max != min) delta = max -min; - else delta = 1; for (int i = 0; i < data.length; i++) { result[i] = ((result[i] - min)/delta) + this.m_Q; @@ -90,11 +104,19 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S result[i] = -((AbstractEAIndividual)population.get(i)).getConstraintViolation(); } for (int i = 0; i < data.length; i++) { - if (result[i] < min) min = result[i]; - if (result[i] > max) max = result[i]; + if (result[i] < min) { + min = result[i]; + } + if (result[i] > max) { + max = result[i]; + } + } + if (max != min) { + delta = max - min; + } + else { + delta = 1; } - if (max != min) delta = max - min; - else delta = 1; for (int i = 0; i < data.length; i++) { result[i] = ((result[i] - min)/delta) + this.m_Q; @@ -114,11 +136,19 @@ public class SelProbStandardScaling extends AbstractSelProb implements java.io.S result[i] = -data[i][x]; } for (int i = 0; i < data.length; i++) { - if (result[i] < min) min = result[i]; - if (result[i] > max) max = result[i]; + if (result[i] < min) { + min = result[i]; + } + if (result[i] > max) { + max = result[i]; + } + } + if (max != min) { + delta = max -min; + } + else { + delta = 1; } - if (max != min) delta = max -min; - else delta = 1; for (int i = 0; i < data.length; i++) { result[i] = ((result[i] - min)/delta) + this.m_Q; diff --git a/src/eva2/server/go/operators/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java b/src/eva2/server/go/operators/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java index 77f9ec4b..80f671ba 100644 --- a/src/eva2/server/go/operators/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java +++ b/src/eva2/server/go/operators/selection/replacement/ReplacementNondominatedSortingDistanceCrowding.java @@ -25,7 +25,9 @@ public class ReplacementNondominatedSortingDistanceCrowding implements Interface Double a1=(Double) arg1.getData("HyperCube"); if(a0!=null&a1!=null){ return a1.compareTo(a0); - }else return 0; + }else { + return 0; + } } } diff --git a/src/eva2/server/go/operators/terminators/CombinedTerminator.java b/src/eva2/server/go/operators/terminators/CombinedTerminator.java index f590c6ef..9d6244f1 100644 --- a/src/eva2/server/go/operators/terminators/CombinedTerminator.java +++ b/src/eva2/server/go/operators/terminators/CombinedTerminator.java @@ -42,8 +42,12 @@ public class CombinedTerminator implements InterfaceTerminator, Serializable { @Override public void init(InterfaceOptimizationProblem prob) { - if (t1 != null) t1.init(prob); - if (t2 != null) t2.init(prob); + if (t1 != null) { + t1.init(prob); + } + if (t2 != null) { + t2.init(prob); + } msg = "Not terminated."; } @@ -58,8 +62,12 @@ public class CombinedTerminator implements InterfaceTerminator, Serializable { } private boolean getTermState(InterfaceTerminator term, Object curPopOrSols) { - if (curPopOrSols instanceof InterfaceSolutionSet) return term.isTerminated((InterfaceSolutionSet)curPopOrSols); - else return term.isTerminated((PopulationInterface)curPopOrSols); + if (curPopOrSols instanceof InterfaceSolutionSet) { + return term.isTerminated((InterfaceSolutionSet)curPopOrSols); + } + else { + return term.isTerminated((PopulationInterface)curPopOrSols); + } } /** @@ -92,7 +100,9 @@ public class CombinedTerminator implements InterfaceTerminator, Serializable { ret = getTermState(t1, curPopOrSols); boolean ret2 = getTermState(t2, curPopOrSols); ret=ret && ret2; - if (ret) msg = "Terminated because both: " + t1.lastTerminationMessage() + " And " + t2.lastTerminationMessage(); + if (ret) { + msg = "Terminated because both: " + t1.lastTerminationMessage() + " And " + t2.lastTerminationMessage(); + } } else { // OR // make sure that both terminators are triggered on every call, because some judge // time-dependently and store information on the population. @@ -102,7 +112,9 @@ public class CombinedTerminator implements InterfaceTerminator, Serializable { getTermState(t2, curPopOrSols); // just so that the second one is triggered, result is ignored. } else { ret = getTermState(t2, curPopOrSols); // trigger and really look at the result - if (ret) msg = t2.lastTerminationMessage(); + if (ret) { + msg = t2.lastTerminationMessage(); + } } } return ret; diff --git a/src/eva2/server/go/operators/terminators/EvaluationTerminator.java b/src/eva2/server/go/operators/terminators/EvaluationTerminator.java index ef93f9a6..160094ed 100644 --- a/src/eva2/server/go/operators/terminators/EvaluationTerminator.java +++ b/src/eva2/server/go/operators/terminators/EvaluationTerminator.java @@ -60,7 +60,9 @@ Serializable { @Override public boolean isTerminated(PopulationInterface pop) { //System.out.println("m_FitnessCalls="+m_FitnessCalls); - if (m_FitnessCalls>pop.getFunctionCalls()) return false; + if (m_FitnessCalls>pop.getFunctionCalls()) { + return false; + } else { msg = m_FitnessCalls + " fitness calls were reached."; return true; diff --git a/src/eva2/server/go/operators/terminators/FitnessValueTerminator.java b/src/eva2/server/go/operators/terminators/FitnessValueTerminator.java index a3d3720d..c4a2c9f9 100644 --- a/src/eva2/server/go/operators/terminators/FitnessValueTerminator.java +++ b/src/eva2/server/go/operators/terminators/FitnessValueTerminator.java @@ -62,7 +62,9 @@ Serializable { public boolean isTerminated(PopulationInterface Pop) { double[] fit = Pop.getBestFitness(); for (int i = 0; i < fit.length; i++) { - if (m_FitnessValue[i] ((Population)pop).getMaxHistLength()) System.err.println("Warning, population history length not long enough for window length " + haltingWindowLen + " (HistoryConvergenceTerminator)"); + if (haltingWindowLen > ((Population)pop).getMaxHistLength()) { + System.err.println("Warning, population history length not long enough for window length " + haltingWindowLen + " (HistoryConvergenceTerminator)"); + } } return res; } diff --git a/src/eva2/server/go/operators/terminators/KnownOptimaFoundTerminator.java b/src/eva2/server/go/operators/terminators/KnownOptimaFoundTerminator.java index c772115b..a61630e1 100644 --- a/src/eva2/server/go/operators/terminators/KnownOptimaFoundTerminator.java +++ b/src/eva2/server/go/operators/terminators/KnownOptimaFoundTerminator.java @@ -31,8 +31,12 @@ public class KnownOptimaFoundTerminator implements InterfaceTerminator, Serializ 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!"); + } else { + System.err.println("KnownOptimaFoundTerminator only works with InterfaceMultimodalProblemKnown instances!"); + } + } else { + System.err.println("KnownOptimaFoundTerminator wont work with null problem!"); + } msg = "Not terminated."; } @@ -52,7 +56,9 @@ public class KnownOptimaFoundTerminator implements InterfaceTerminator, Serializ if (found >= reqOptima) { msg = "There were " + reqOptima + " optima found."; return true; - } else return false; + } else { + return false; + } } @Override diff --git a/src/eva2/server/go/operators/terminators/ParetoMetricTerminator.java b/src/eva2/server/go/operators/terminators/ParetoMetricTerminator.java index ec5f634f..341f89fa 100644 --- a/src/eva2/server/go/operators/terminators/ParetoMetricTerminator.java +++ b/src/eva2/server/go/operators/terminators/ParetoMetricTerminator.java @@ -45,7 +45,9 @@ public class ParetoMetricTerminator extends PopulationMeasureTerminator implemen @Override public void init(InterfaceOptimizationProblem prob) { super.init(prob); - if (prob instanceof AbstractMultiObjectiveOptimizationProblem) moProb = (AbstractMultiObjectiveOptimizationProblem)prob; + if (prob instanceof AbstractMultiObjectiveOptimizationProblem) { + moProb = (AbstractMultiObjectiveOptimizationProblem)prob; + } else { moProb = null; EVAERROR.errorMsgOnce("Error, " + this.getClass() + " works only with problems inheriting from " + AbstractMultiObjectiveOptimizationProblem.class + "!"); @@ -54,10 +56,16 @@ public class ParetoMetricTerminator extends PopulationMeasureTerminator implemen @Override protected double calcInitialMeasure(PopulationInterface pop) { - if (moProb==null) return Double.MAX_VALUE; + if (moProb==null) { + return Double.MAX_VALUE; + } else { - if (isUseCurrentPop()) return getParetoMetric().calculateMetricOn((Population)pop, moProb); - else return getParetoMetric().calculateMetricOn(moProb.getLocalParetoFront(), moProb); + if (isUseCurrentPop()) { + return getParetoMetric().calculateMetricOn((Population)pop, moProb); + } + else { + return getParetoMetric().calculateMetricOn(moProb.getLocalParetoFront(), moProb); + } } } @@ -73,8 +81,12 @@ public class ParetoMetricTerminator extends PopulationMeasureTerminator implemen 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() { diff --git a/src/eva2/server/go/operators/terminators/PopulationArchiveTerminator.java b/src/eva2/server/go/operators/terminators/PopulationArchiveTerminator.java index 40ffaad0..fc5c721a 100644 --- a/src/eva2/server/go/operators/terminators/PopulationArchiveTerminator.java +++ b/src/eva2/server/go/operators/terminators/PopulationArchiveTerminator.java @@ -21,15 +21,23 @@ public class PopulationArchiveTerminator extends PopulationMeasureTerminator { @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)); + if (archive==null || (archive.size()<1)) { + return Double.MAX_VALUE; + } + else { + return wfComp.calcScore(archive.getBestEAIndividual(wfComp)); + } } @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)); + if (archive==null || (archive.size()<1)) { + return Double.MAX_VALUE; + } + else { + return wfComp.calcScore(archive.getBestEAIndividual(wfComp)); + } } @Override diff --git a/src/eva2/server/go/operators/terminators/PopulationMeasureTerminator.java b/src/eva2/server/go/operators/terminators/PopulationMeasureTerminator.java index cd3c7e99..c138ba78 100644 --- a/src/eva2/server/go/operators/terminators/PopulationMeasureTerminator.java +++ b/src/eva2/server/go/operators/terminators/PopulationMeasureTerminator.java @@ -119,7 +119,9 @@ Serializable { @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 (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(); @@ -170,8 +172,12 @@ Serializable { } sb.append(" for "); sb.append(stagTime); - if (stagnationMeasure == StagnationTypeEnum.generationBased) sb.append(" generations."); - else sb.append(" function calls."); + if (stagnationMeasure == StagnationTypeEnum.generationBased) { + sb.append(" generations."); + } + else { + sb.append(" function calls."); + } return sb.toString(); } @@ -218,7 +224,9 @@ Serializable { switch (changeType) { case absoluteChange: allowedLower=oldMeasure-convThresh; - if (!doCheckImprovement()) allowedUpper=oldMeasure+convThresh; + if (!doCheckImprovement()) { + allowedUpper=oldMeasure+convThresh; + } break; case absoluteValue: allowedUpper=convThresh; @@ -227,7 +235,9 @@ Serializable { case relativeChange: double delta = oldMeasure*convThresh; allowedLower = oldMeasure-delta; - if (!doCheckImprovement()) allowedUpper = oldMeasure+delta; + if (!doCheckImprovement()) { + allowedUpper = oldMeasure+delta; + } break; } ret = (measure <= allowedUpper) && (measure >= allowedLower); @@ -240,7 +250,9 @@ 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 + "]"); + if (TRACE) { + System.out.println("isStillConverged returns " + ret + ", measure " + measure + ", old measure " + BeanInspector.toString(oldMeasure) + ", bounds: [" + allowedLower + " , " + allowedUpper + "]"); + } return ret; } diff --git a/src/eva2/server/go/populations/PBILPopulation.java b/src/eva2/server/go/populations/PBILPopulation.java index b003d355..60329331 100644 --- a/src/eva2/server/go/populations/PBILPopulation.java +++ b/src/eva2/server/go/populations/PBILPopulation.java @@ -73,7 +73,9 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser tmpBitSet = tmpIndy.getBGenotype(); for (int j = 0; j < this.m_ProbabilityVector.length; j++) { this.m_ProbabilityVector[j] *= (1.0 - learnRate); - if (tmpBitSet.get(j)) this.m_ProbabilityVector[j] += learnRate; + if (tmpBitSet.get(j)) { + this.m_ProbabilityVector[j] += learnRate; + } } } } @@ -90,8 +92,12 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser 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 tmpBitSet.clear(j); + if (RNG.flipCoin(this.m_ProbabilityVector[j])) { + tmpBitSet.set(j); + } + else { + tmpBitSet.clear(j); + } } tmpIndy.SetBGenotype(tmpBitSet); super.add(tmpIndy); @@ -104,9 +110,15 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser */ public void mutateProbabilityVector(double mutationRate, double sigma) { for (int j = 0; j < this.m_ProbabilityVector.length; j++) { - if (RNG.flipCoin(mutationRate)) this.m_ProbabilityVector[j] += RNG.gaussianDouble(sigma); - if (this.m_ProbabilityVector[j] > 1) this.m_ProbabilityVector[j] = 1; - if (this.m_ProbabilityVector[j] < 0) this.m_ProbabilityVector[j] = 0; + if (RNG.flipCoin(mutationRate)) { + this.m_ProbabilityVector[j] += RNG.gaussianDouble(sigma); + } + if (this.m_ProbabilityVector[j] > 1) { + this.m_ProbabilityVector[j] = 1; + } + if (this.m_ProbabilityVector[j] < 0) { + this.m_ProbabilityVector[j] = 0; + } } } @@ -125,7 +137,9 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser for (int i = 0; i < this.size(); i++) { tmpSet = ((InterfaceGAIndividual)this.get(i)).getBGenotype(); for (int j = 0; j < dim; j++) { - if (tmpSet.get(j)) this.m_ProbabilityVector[j] += 1; + if (tmpSet.get(j)) { + this.m_ProbabilityVector[j] += 1; + } } } // now normalize diff --git a/src/eva2/server/go/problems/AbstractDynTransProblem.java b/src/eva2/server/go/problems/AbstractDynTransProblem.java index 57accb16..c1bc9a2d 100644 --- a/src/eva2/server/go/problems/AbstractDynTransProblem.java +++ b/src/eva2/server/go/problems/AbstractDynTransProblem.java @@ -63,7 +63,9 @@ public abstract class AbstractDynTransProblem extends AbstractSynchronousOptimiz // myplot.addGraph(0, 1); myplot.jump(); } else { - if (TRACE) System.out.println("creating myplot instance"); + if (TRACE) { + System.out.println("creating myplot instance"); + } double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; @@ -73,8 +75,9 @@ public abstract class AbstractDynTransProblem extends AbstractSynchronousOptimiz myplot.setConnectedPoint(population.getFunctionCalls(), delta, 0); //myplot.setUnconnectedPoint(population.getFunctionCalls(), population.getPopulationMeasures()[2], 2); } - else - myplot = null; + else { + myplot = null; + } } private double transLength(double time) { @@ -122,8 +125,9 @@ public abstract class AbstractDynTransProblem extends AbstractSynchronousOptimiz */ @Override public void resetProblem(double severity) { - if ((prob != null) && (bestIndividual != null)) - this.evaluateAt(bestIndividual, getCurrentProblemTime()); + if ((prob != null) && (bestIndividual != null)) { + this.evaluateAt(bestIndividual, getCurrentProblemTime()); + } } /* inits the population in the problem itself @@ -131,7 +135,9 @@ public abstract class AbstractDynTransProblem extends AbstractSynchronousOptimiz */ @Override public void initPopulationAt(Population population, double time) { - if (TRACE) System.out.println("DynTransProblem at " + this + " initPop, problem is " + getProblem()); + if (TRACE) { + System.out.println("DynTransProblem at " + this + " initPop, problem is " + getProblem()); + } getProblem().initPopulation(population); for (int i = 0; i < population.size(); i++) { ((AbstractEAIndividual)population.get(i)).SetAge(0); diff --git a/src/eva2/server/go/problems/AbstractDynamicOptimizationProblem.java b/src/eva2/server/go/problems/AbstractDynamicOptimizationProblem.java index ccc5a7c1..91044e4d 100644 --- a/src/eva2/server/go/problems/AbstractDynamicOptimizationProblem.java +++ b/src/eva2/server/go/problems/AbstractDynamicOptimizationProblem.java @@ -78,17 +78,20 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz setSeverity(sev); setFrequency(freq); - if (bExtraPlot) makePlot(); + if (bExtraPlot) { + makePlot(); + } } @Override public void initProblem() { setCurrentProblemTime(getStartTime()); - if (myplot != null) try { - myplot.jump(); - } catch(NullPointerException e) { - makePlot(); - } + if (myplot != null) { + try { +myplot.jump(); +} catch(NullPointerException e) { +makePlot(); +} } } /** @@ -140,7 +143,9 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz protected void setCurrentProblemTime(double newTime) { double sev = newTime - currentProblemTime; currentProblemTime = newTime; - if (sev != 0.) resetProblem(sev); + if (sev != 0.) { + resetProblem(sev); + } } /** @@ -161,7 +166,9 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz */ public void setSeverity(double sev) { severity = sev; - if (TRACE) System.out.println("severity to " + sev); + if (TRACE) { + System.out.println("severity to " + sev); + } } /** @@ -218,7 +225,9 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz protected void incProblemTime(double dt) { currentProblemTime += dt; resetProblem(dt); - if (TRACE) System.out.println("new problem time is " + currentProblemTime); + if (TRACE) { + System.out.println("new problem time is " + currentProblemTime); + } } /** @@ -315,7 +324,9 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz } else if (!bExtraPlot && doPlot) { if (myplot != null) { myplot.jump(); - } else makePlot(); + } else { + makePlot(); + } } bExtraPlot = doPlot; } @@ -325,7 +336,9 @@ public abstract class AbstractDynamicOptimizationProblem extends AbstractOptimiz } private void makePlot() { - if (TRACE) System.out.println("creating myplot instance"); + if (TRACE) { + System.out.println("creating myplot instance"); + } double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; diff --git a/src/eva2/server/go/problems/AbstractMultiModalProblemKnown.java b/src/eva2/server/go/problems/AbstractMultiModalProblemKnown.java index 35b51a01..0fc03c16 100644 --- a/src/eva2/server/go/problems/AbstractMultiModalProblemKnown.java +++ b/src/eva2/server/go/problems/AbstractMultiModalProblemKnown.java @@ -36,8 +36,9 @@ implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { protected void cloneObjects(AbstractMultiModalProblemKnown b) { super.cloneObjects(b); - if (b.m_ListOfOptima != null) - this.m_ListOfOptima = (Population)((Population)b.m_ListOfOptima).clone(); + if (b.m_ListOfOptima != null) { + this.m_ListOfOptima = (Population)((Population)b.m_ListOfOptima).clone(); + } // if (b.m_Range != null) { // this.m_Range = new double[b.m_Range.length][b.m_Range[0].length]; // for (int i = 0; i < this.m_Range.length; i++) { @@ -101,7 +102,9 @@ implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { this.m_GlobalOpt = Double.NEGATIVE_INFINITY; m_ListOfOptima = new Population(); this.initListOfOptima(); - if (!fullListAvailable() && (Double.isInfinite(m_GlobalOpt))) m_GlobalOpt=0; + if (!fullListAvailable() && (Double.isInfinite(m_GlobalOpt))) { + m_GlobalOpt=0; + } } /** Ths method allows you to evaluate a simple bit string to determine the fitness @@ -258,8 +261,12 @@ implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { */ @Override public double getMaximumPeakRatio(Population pop) { - if (!this.fullListAvailable()) return -1; - else return getMaximumPeakRatio(this.getRealOptima(), pop, m_Epsilon); + if (!this.fullListAvailable()) { + return -1; + } + else { + return getMaximumPeakRatio(this.getRealOptima(), pop, m_Epsilon); + } } /** @@ -277,7 +284,9 @@ implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { */ public static double getMaximumPeakRatio(Population realOpts, Population pop, double epsilon) { double foundInvertedSum = 0, sumRealMaxima = 0; - if (realOpts==null || (realOpts.size()==0)) return -1; + if (realOpts==null || (realOpts.size()==0)) { + return -1; + } // if (!mmProb.fullListAvailable()) return -1; // Population realOpts = mmProb.getRealOptima(); double tmp, maxOpt = realOpts.getEAIndividual(0).getFitness(0); @@ -287,14 +296,18 @@ implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { // 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!"); + if (realOpts.getEAIndividual(i).getFitness(0)<0) { + EVAERROR.errorMsgOnce("Warning: avoid negative maxima in AbstractMultiModalProblemKnown!"); + } } AbstractEAIndividual[] optsFound = PostProcess.getFoundOptimaArray(pop, realOpts, epsilon, true); 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]; + if (realFits[i]>fitThreshold) { + 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)); @@ -382,7 +401,9 @@ implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown { // 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)"); + 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); diff --git a/src/eva2/server/go/problems/AbstractMultiObjectiveOptimizationProblem.java b/src/eva2/server/go/problems/AbstractMultiObjectiveOptimizationProblem.java index d8218b54..4f585b2d 100644 --- a/src/eva2/server/go/problems/AbstractMultiObjectiveOptimizationProblem.java +++ b/src/eva2/server/go/problems/AbstractMultiObjectiveOptimizationProblem.java @@ -67,8 +67,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract fitness = ind.getFitness(); // check and update border if necessary - if (m_Border == null) - prob.m_Border = new double[fitness.length][2]; + 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!"); @@ -107,7 +108,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract m_defaultBorderHigh=borderHigh; this.m_Template = new ESIndividualDoubleData(); makeBorder(); - if (this.m_Show) this.initProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } } public AbstractMultiObjectiveOptimizationProblem() { @@ -119,7 +122,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract */ public void setShowParetoFront(boolean b) { this.m_Show = b; - if (this.m_Show) this.initProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } else if (this.m_Plot != null) { this.m_Plot.dispose(); this.m_Plot = null; @@ -149,11 +154,15 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract public void initProblem() { makeBorder(); this.m_ParetoFront = new Population(); - if (this.m_Show) this.initProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } } protected void makeBorder() { - if (this.m_Border == null) this.m_Border = new double[m_OutputDimension][2]; + if (this.m_Border == null) { + this.m_Border = new double[m_OutputDimension][2]; + } for (int i = 0; i < this.m_Border.length; i++) { this.m_Border[i][0] = getLowerBorder(i); this.m_Border[i][1] = getUpperBorder(i); @@ -173,8 +182,12 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract * @return true if all individuals are multiobjective */ public static boolean isPopulationMultiObjective(Population pop) { - if (pop == null) return false; - if (pop.size() == 0) return false; + if (pop == null) { + return false; + } + if (pop.size() == 0) { + return false; + } int bestFitLen = pop.getBestFitness().length, tmpFitLen; for (int i = 0; i < pop.size(); i++) { tmpFitLen = ((AbstractEAIndividual)pop.get(i)).getFitness().length; @@ -200,7 +213,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract @Override public void evaluatePopulationStart(Population population) { super.evaluatePopulationStart(population); - if (this.m_Show && (this.m_Plot==null)) this.initProblemFrame(); + if (this.m_Show && (this.m_Plot==null)) { + this.initProblemFrame(); + } } @Override @@ -213,7 +228,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract 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]; + if (m_Border == null) { + this.m_Border = new double[fitness.length][2]; + } 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!"); @@ -247,7 +264,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract this.m_MOSOConverter.convertMultiObjective2SingleObjective(population); if (this.m_Show) { - if (m_Plot.isValid()) AbstractMultiObjectiveOptimizationProblem.drawProblem(population, m_Plot, this); + if (m_Plot.isValid()) { + AbstractMultiObjectiveOptimizationProblem.drawProblem(population, m_Plot, this); + } } } @@ -260,7 +279,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract 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 == null) { + System.err.println("Error, give at least an empty population as initial pareto front"); + } if (pFront.getArchive() == null) { pFront.SetArchive(new Population(100)); } @@ -280,7 +301,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract double[] tmpD = new double[2]; tmpD[0] = 0; tmpD[1] = 0; - if (this.m_Plot == null) m_Plot = new Plot("Multiobjective Optimization", "Y1", "Y2", tmpD, tmpD); + if (this.m_Plot == null) { + m_Plot = new Plot("Multiobjective Optimization", "Y1", "Y2", tmpD, tmpD); + } // plot init stuff this.initAdditionalData(this.m_Plot, 10); @@ -320,7 +343,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract 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!"); + 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); @@ -358,12 +383,16 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract // and eventually the pop.archive if there is one tmpPop = new Population(); tmpPop.addPopulation(p); - if (p.getArchive() != null) tmpPop.addPopulation(p.getArchive()); + if (p.getArchive() != null) { + tmpPop.addPopulation(p.getArchive()); + } tmpArch.addElementsToArchive(tmpPop); tmpPop = tmpPop.getArchive(); } - if (tmpPop != null) drawProblem(tmpPop, p.getArchive(), plot); + if (tmpPop != null) { + drawProblem(tmpPop, p.getArchive(), plot); + } // else : in this case i got a single objective optimization problem // draw additional data moProblem.drawAdditionalData(plot, p, 10); @@ -381,7 +410,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract plot.clearGraph(index); for (int i = 0; i < pop.size(); i++) { tmpFitness = ((AbstractEAIndividual)pop.get(i)).getFitness(); - if (tmpFitness.length <= 1) tmpFitness = (double[])((AbstractEAIndividual)pop.get(i)).getData("MOFitness"); + if (tmpFitness.length <= 1) { + tmpFitness = (double[])((AbstractEAIndividual)pop.get(i)).getData("MOFitness"); + } plot.setUnconnectedPoint(tmpFitness[0], tmpFitness[1], index); } plot.setUnconnectedPoint(this.m_Border[0][1], this.m_Border[1][1], index); @@ -410,11 +441,15 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract constraint = new double[pop.size()]; if (((AbstractEAIndividual)pop.get(0)).hasData("MOFitness")) { moFitness = new double[pop.size()][]; - } else moFitness = null; + } 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"); + if (moFitness != null) { + moFitness[i] = (double[])((AbstractEAIndividual)pop.get(i)).getData("MOFitness"); + } } mySet.setConnectedMode(false); for (int i = 0; i < trueFitness.length; i++) { @@ -538,7 +573,9 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract * @return */ public double calculateMetric(Population pop) { - if (pop==null || (pop.size()==0)) return Double.NaN; + if (pop==null || (pop.size()==0)) { + return Double.NaN; + } return this.m_Metric.calculateMetricOn(pop, this); } diff --git a/src/eva2/server/go/problems/AbstractOptimizationProblem.java b/src/eva2/server/go/problems/AbstractOptimizationProblem.java index ccd5b3af..67f783ea 100644 --- a/src/eva2/server/go/problems/AbstractOptimizationProblem.java +++ b/src/eva2/server/go/problems/AbstractOptimizationProblem.java @@ -261,8 +261,12 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial @Override public String[] getAdditionalDataHeader() { String[] header = null; - if (this instanceof InterfaceInterestingHistogram) header = new String[]{STAT_SOLUTION_HEADER,"histogram","score"}; - else header = new String[]{STAT_SOLUTION_HEADER}; + 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); @@ -292,7 +296,9 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial System.err.println("Error, invalid type in AbstractOptimizationProblem.appendAdd"); return dat; } - } else return dat; + } else { + return dat; + } } /** This method returns the header for the additional data that is to be written into a file @@ -302,11 +308,14 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial @Override public String[] getAdditionalDataInfo() { 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 info = new String[]{"Representation of the current best individual"}; + 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 { + info = new String[]{"Representation of the current best individual"}; + } info = (String[])checkAndAppendAdd(1, getIndividualTemplate(), info, null); info = (String[])checkAndAppendAdd(1, getIndividualTemplate().getCrossoverOperator(), info, null); @@ -334,7 +343,9 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial Population sols = PostProcess.clusterBestUpdateHistogram((Population)maybeFiltered, this, hist, fitCrit, getDefaultAccuracy()); } vals = new Object[]{solStr, hist, hist.getScore()}; - } else vals = new Object[]{solStr}; + } else { + vals = new Object[]{solStr}; + } vals = checkAndAppendAdd(2, pop.getBestIndividual(), vals, pop); vals = checkAndAppendAdd(2, ((AbstractEAIndividual)pop.getBestIndividual()).getCrossoverOperator(), vals, pop); @@ -369,8 +380,12 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial JTextArea area = new JTextArea(); JScrollPane scroll = new JScrollPane(area); String text = "Best Solution:\n"; - if (generation >= 0) text+=" Generation: " + generation + "\n"; - if (funCalls >= 0) text+=" Evaluations: " + funCalls + "\n"; + if (generation >= 0) { + text+=" Generation: " + generation + "\n"; + } + if (funCalls >= 0) { + text+=" Evaluations: " + funCalls + "\n"; + } text += this.getSolutionRepresentationFor(indy); area.setLineWrap(true); area.setText(text); @@ -450,8 +465,12 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial // 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; + if (clusterSigma > 0) { + return (Population)PostProcess.clusterBest(potOptima, clustering, 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); + } + else { + return potOptima; + } } /** @@ -473,8 +492,12 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial 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.m_Template).length; // scales the effort with the number of problem dimensions + if (mutationStepSize<0) { + mutationStepSize = 0.0001; + } + if (numOfFailures<0) { + numOfFailures = 100*AbstractEAIndividual.getDoublePositionShallow(this.m_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... @@ -510,7 +533,9 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial if (overallDist < epsilon) { return true; } - else return false; + else { + return false; + } } /** @@ -542,7 +567,9 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial // initPerturb = epsilonPhenoSpace/(2*(Mathematics.getAvgRange(((InterfaceDataTypeDouble)orig).getDoubleRange()))); initRelPerturb = epsilonPhenoSpace*0.5; dim=((InterfaceDataTypeDouble)orig).getDoubleRange().length; - if (maxEvaluations<0) maxEvaluations = 500*AbstractEAIndividual.getDoublePositionShallow(prob.m_Template).length; // scales the effort with the number of problem dimensions + if (maxEvaluations<0) { + maxEvaluations = 500*AbstractEAIndividual.getDoublePositionShallow(prob.m_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; @@ -551,7 +578,9 @@ implements InterfaceOptimizationProblem /*, InterfaceParamControllable*/, Serial 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); + 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); diff --git a/src/eva2/server/go/problems/AbstractParallelOptimizationProblem.java b/src/eva2/server/go/problems/AbstractParallelOptimizationProblem.java index d29d58b7..702322c3 100644 --- a/src/eva2/server/go/problems/AbstractParallelOptimizationProblem.java +++ b/src/eva2/server/go/problems/AbstractParallelOptimizationProblem.java @@ -24,7 +24,9 @@ public abstract class AbstractParallelOptimizationProblem extends AbstractOptimi if (this.m_Parallelize) { // this is running on remote maschines String[] nodesList = this.m_Servers.getCheckedServerNodes(); - if ((nodesList == null) || (nodesList.length == 0)) return; + if ((nodesList == null) || (nodesList.length == 0)) { + return; + } this.m_Slaves = new AbstractOptimizationProblem[nodesList.length]; for (int i = 0; i < nodesList.length; i++) { this.m_Slaves[i] = (AbstractOptimizationProblem) RMIProxyRemoteThread.newInstance(this, nodesList[i]); diff --git a/src/eva2/server/go/problems/AbstractProblemBinary.java b/src/eva2/server/go/problems/AbstractProblemBinary.java index db7c7a1a..fcc84b1c 100644 --- a/src/eva2/server/go/problems/AbstractProblemBinary.java +++ b/src/eva2/server/go/problems/AbstractProblemBinary.java @@ -21,14 +21,18 @@ public abstract class AbstractProblemBinary extends AbstractOptimizationProblem } protected void initTemplate() { - if (m_Template == null) this.m_Template = new GAIndividualBinaryData(); + if (m_Template == null) { + this.m_Template = new GAIndividualBinaryData(); + } if (((InterfaceGAIndividual)this.m_Template).getGenotypeLength()!=this.getProblemDimension()) { ((InterfaceDataTypeBinary)this.m_Template).setBinaryDataLength(this.getProblemDimension()); } } public void cloneObjects(AbstractProblemBinary o) { - if (o.m_Template != null) m_Template = (AbstractEAIndividual)o.m_Template.clone(); + if (o.m_Template != null) { + m_Template = (AbstractEAIndividual)o.m_Template.clone(); + } } @Override diff --git a/src/eva2/server/go/problems/AbstractProblemDouble.java b/src/eva2/server/go/problems/AbstractProblemDouble.java index f0a443b6..90bb989d 100644 --- a/src/eva2/server/go/problems/AbstractProblemDouble.java +++ b/src/eva2/server/go/problems/AbstractProblemDouble.java @@ -80,8 +80,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem } protected void initTemplate() { - if (m_Template == null) - m_Template = new ESIndividualDoubleData(); + if (m_Template == null) { + m_Template = new ESIndividualDoubleData(); + } if (getProblemDimension() > 0) { // avoid evil case setting dim to 0 // during object init ((InterfaceDataTypeDouble) this.m_Template) @@ -99,8 +100,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem this.m_DefaultRange = o.m_DefaultRange; this.m_Noise = o.m_Noise; this.SetDefaultAccuracy(o.getDefaultAccuracy()); - if (o.m_Template != null) - this.m_Template = (AbstractEAIndividual) o.m_Template.clone(); + if (o.m_Template != null) { + this.m_Template = (AbstractEAIndividual) o.m_Template.clone(); + } if (o.constraintArray != null) { this.constraintArray = o.constraintArray.clone(); for (int i = 0; i < constraintArray.length; i++) { @@ -149,7 +151,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem // evaluate the vector fitness = this.eval(x); // if indicated, add Gaussian noise - if (m_Noise != 0) RNG.addNoise(fitness, m_Noise); + if (m_Noise != 0) { + RNG.addNoise(fitness, m_Noise); + } // set the fitness setEvalFitness(individual, x, fitness); if (isWithConstraints()) { @@ -160,8 +164,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem protected double[] rotateMaybe(double[] x) { if (isDoRotation()) { - if (rotation == null) - initProblem(); + if (rotation == null) { + initProblem(); + } x = Mathematics.rotate(x, rotation); } return x; @@ -169,8 +174,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem protected double[] inverseRotateMaybe(double[] x) { if (isDoRotation()) { - if (rotation == null) - initProblem(); + if (rotation == null) { + initProblem(); + } x = Mathematics.rotate(x, rotation.inverse()); } return x; @@ -288,8 +294,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem if (isDoRotation()) { rotation = initDefaultRotationMatrix(rotAngle, getProblemDimension()); - } else - rotation = null; + } else { + rotation = null; + } } /** @@ -323,8 +330,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem * The sigma for a gaussian random number. */ public void setNoise(double noise) { - if (noise < 0) - noise = 0; + if (noise < 0) { + noise = 0; + } this.m_Noise = noise; } @@ -390,8 +398,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem public void setDoRotation(boolean doRotation) { this.doRotation = doRotation; - if (!doRotation) - rotation = null; + if (!doRotation) { + rotation = null; + } } public boolean isDoRotation() { @@ -409,8 +418,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem if (isWithConstraints()) { return constraintArray; // return constraintList.getObjects(); - } else - return null; + } else { + return null; + } } /********************************************************************************************************************** @@ -588,26 +598,30 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem @Override public String[] getAdditionalDataHeader() { String[] superHeader = super.getAdditionalDataHeader(); - if (isWithConstraints()) - return ToolBox.appendArrays(superHeader, new String[] { "rawFit", - "numViol", "sumViol" }); - else - return superHeader; + 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; + 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 @@ -623,8 +637,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem // return superVal + " \t" + // BeanInspector.toString(indy.getData(rawFitKey)) + " \t" + // violation.head() + " \t" + violation.tail(); - } else - return superVal; + } else { + return superVal; + } } protected Pair getConstraintViolation( @@ -633,8 +648,9 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem int numViol = 0; for (AbstractConstraint constr : constraintArray) { double v = constr.getViolation(getEvalArray(indy)); - if (v > 0) - numViol++; + if (v > 0) { + numViol++; + } sum += v; } return new Pair(numViol, sum); diff --git a/src/eva2/server/go/problems/AbstractProblemInteger.java b/src/eva2/server/go/problems/AbstractProblemInteger.java index b8773e9b..aa9cbbb4 100644 --- a/src/eva2/server/go/problems/AbstractProblemInteger.java +++ b/src/eva2/server/go/problems/AbstractProblemInteger.java @@ -20,15 +20,21 @@ public abstract class AbstractProblemInteger extends AbstractOptimizationProblem } protected void initTemplate() { - if (m_Template==null) m_Template = new GIIndividualIntegerData(); + if (m_Template==null) { + m_Template = new GIIndividualIntegerData(); + } if (((InterfaceDataTypeInteger)this.m_Template).size()!=this.getProblemDimension()) { ((InterfaceDataTypeInteger)this.m_Template).setIntegerDataLength(this.getProblemDimension()); } } public void cloneObjects(AbstractProblemInteger o) { - if (o.m_Template != null) m_Template = (AbstractEAIndividual)o.m_Template.clone(); - if (o.m_OverallBest != null) m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)o.m_OverallBest).clone(); + if (o.m_Template != null) { + m_Template = (AbstractEAIndividual)o.m_Template.clone(); + } + if (o.m_OverallBest != null) { + m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)o.m_OverallBest).clone(); + } this.m_ProblemDimension = o.m_ProblemDimension; } diff --git a/src/eva2/server/go/problems/AbstractSynchronousOptimizationProblem.java b/src/eva2/server/go/problems/AbstractSynchronousOptimizationProblem.java index 5bd1d42d..00b02258 100644 --- a/src/eva2/server/go/problems/AbstractSynchronousOptimizationProblem.java +++ b/src/eva2/server/go/problems/AbstractSynchronousOptimizationProblem.java @@ -57,7 +57,9 @@ public abstract class AbstractSynchronousOptimizationProblem extends @Override protected void changeProblemAt(double problemTime) { incProblemTime(shiftPerChange); - if (TRACE) System.out.println("problem shiftet at " + problemTime + " per " + shiftPerChange); + if (TRACE) { + System.out.println("problem shiftet at " + problemTime + " per " + shiftPerChange); + } evalsSinceChange = 0.; } @@ -77,7 +79,9 @@ public abstract class AbstractSynchronousOptimizationProblem extends */ protected void setConstantProblemEvals(double constEvals) { constantProblemEvals = constEvals; - if (TRACE) System.out.println("setConstantProblemEvals: " + constEvals); + if (TRACE) { + System.out.println("setConstantProblemEvals: " + constEvals); + } } /* (non-Javadoc) diff --git a/src/eva2/server/go/problems/B1Problem.java b/src/eva2/server/go/problems/B1Problem.java index 6dadd118..deb614dc 100644 --- a/src/eva2/server/go/problems/B1Problem.java +++ b/src/eva2/server/go/problems/B1Problem.java @@ -51,7 +51,9 @@ public class B1Problem extends AbstractProblemBinary implements java.io.Serializ int fitness = 0; for (int i = 0; i < getProblemDimension(); i++) { - if (b.get(i)) fitness++; + if (b.get(i)) { + fitness++; + } } result[0] = fitness; return result; diff --git a/src/eva2/server/go/problems/BKnapsackProblem.java b/src/eva2/server/go/problems/BKnapsackProblem.java index a9309d7e..a638c551 100644 --- a/src/eva2/server/go/problems/BKnapsackProblem.java +++ b/src/eva2/server/go/problems/BKnapsackProblem.java @@ -192,7 +192,9 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S weakest = i; } if ( ((-items[i][1])/((double)items[i][0])) == ((-items[weakest][1])/((double)items[weakest][0])) ) { - if (RNG.flipCoin(0.5)) weakest = i; + if (RNG.flipCoin(0.5)) { + weakest = i; + } } } } @@ -210,7 +212,9 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S weakest = i; } if ( ((-items[i][1])/((double)items[i][0])) == ((-items[weakest][1])/((double)items[weakest][0])) ) { - if (RNG.flipCoin(0.5)) weakest = i; + if (RNG.flipCoin(0.5)) { + weakest = i; + } } } } @@ -219,19 +223,27 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S result = this.eval(tmpBitSet); int weight = 0; for (int i = 0; i < items.length; i++) { - if (tmpBitSet.get(i)) weight += items[i][0]; + if (tmpBitSet.get(i)) { + weight += items[i][0]; + } } for (int i = 0; i < items.length; i++) { if (items[i][0] < this.m_Limit - weight) { // possible candidate - if (stronger < 0) stronger = i; + if (stronger < 0) { + stronger = i; + } else { - if (items[i][1] < items[stronger][1]) stronger = i; + if (items[i][1] < items[stronger][1]) { + stronger = i; + } } } } - if (stronger >= 0) tmpBitSet.set(stronger); + if (stronger >= 0) { + tmpBitSet.set(stronger); + } result = this.eval(tmpBitSet); } @@ -254,7 +266,9 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S double[] result = new double[3]; int l = items.length; - if (getProblemDimension() != l) System.err.println("Error in BKnapsack!"); + if (getProblemDimension() != l) { + System.err.println("Error in BKnapsack!"); + } result[0] = 0; result[1] = 0; // the weight exceed result[2] = 0; // net worth @@ -262,7 +276,9 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S if (b.get(i)) { result[1] += items[i][0]; result[2] += items[i][1]; - } else b.clear(i); + } else { + b.clear(i); + } } // write the solution result[1] = Math.max(0, result[1]- this.m_Limit); @@ -287,8 +303,12 @@ public class BKnapsackProblem extends AbstractProblemBinary implements java.io.S 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 result += "exceeds the weight limit by " + report[1]; + if (report[1] == 0) { + result += "does not exceed the weight limit!"; + } + else { + result += "exceeds the weight limit by " + report[1]; + } result += "\n"; return result; } diff --git a/src/eva2/server/go/problems/ConstrHimmelblauProblem.java b/src/eva2/server/go/problems/ConstrHimmelblauProblem.java index bff7a041..3b0b2706 100644 --- a/src/eva2/server/go/problems/ConstrHimmelblauProblem.java +++ b/src/eva2/server/go/problems/ConstrHimmelblauProblem.java @@ -52,7 +52,9 @@ public class ConstrHimmelblauProblem extends AbstractProblemDouble implements Se 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; + if (useYOffset) { + v+=yOffset; + } return new double[]{v}; } diff --git a/src/eva2/server/go/problems/DynJumpProblem.java b/src/eva2/server/go/problems/DynJumpProblem.java index c27789bd..d17820b0 100644 --- a/src/eva2/server/go/problems/DynJumpProblem.java +++ b/src/eva2/server/go/problems/DynJumpProblem.java @@ -54,7 +54,9 @@ public class DynJumpProblem extends AbstractDynTransProblem { super.changeProblemAt(problemTime); makeTranslation(); /* prooving results */ - if (TRACE) writeFile(); + if (TRACE) { + writeFile(); + } ++changeCounter; } @@ -233,8 +235,9 @@ public class DynJumpProblem extends AbstractDynTransProblem { } catch ( IOException e ) { } finally { - if ( fw != null ) - try { fw.flush(); } catch ( IOException e ) { } + if ( fw != null ) { + try { fw.flush(); } catch ( IOException e ) { } + } } } } @@ -242,8 +245,9 @@ public class DynJumpProblem extends AbstractDynTransProblem { 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"; + if (j != getProblemDimension()) { + s += toPrint[i][j] + "\t"; + } } s += "\n"; } diff --git a/src/eva2/server/go/problems/ERPStarter.java b/src/eva2/server/go/problems/ERPStarter.java index b3efd7ed..10d877a1 100644 --- a/src/eva2/server/go/problems/ERPStarter.java +++ b/src/eva2/server/go/problems/ERPStarter.java @@ -148,7 +148,9 @@ public class ERPStarter { 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)); + if (Mathematics.areFinite(weights)<0) { + erp.setMosoConverter(new MOSOWeightedFitness(weights)); + } } erp.setProblemDimension(filteredVars.length); erp.setRange(range); @@ -158,8 +160,12 @@ public class ERPStarter { for (int i=0; i fitList = new ArrayList(); List parameters=new ArrayList(); parameters.add(this.m_Command); - if (additionalArg!=null && (additionalArg.length()>0)) parameters.add(additionalArg); + if (additionalArg!=null && (additionalArg.length()>0)) { + parameters.add(additionalArg); + } for(int i=0;i 2) d = 2; + if (d < 1) { + d = 1; + } + if (d > 2) { + d = 2; + } this.m_D = d; } public double getD() { @@ -113,7 +117,9 @@ public class F10Problem extends AbstractProblemDoubleOffset implements Interface * @param b The b. */ public void setb(double b) { - if (b < 1.000001) b = 1.000001; + if (b < 1.000001) { + b = 1.000001; + } this.m_b = b; } public double getb() { @@ -127,7 +133,9 @@ public class F10Problem extends AbstractProblemDoubleOffset implements Interface * @param iters The Iterations. */ public void setIterations(int iters) { - if (iters < 2) iters = 2; + if (iters < 2) { + iters = 2; + } this.m_Iterations = iters; } public int getIterations() { diff --git a/src/eva2/server/go/problems/F13Problem.java b/src/eva2/server/go/problems/F13Problem.java index e7ab92c1..fdd62d08 100644 --- a/src/eva2/server/go/problems/F13Problem.java +++ b/src/eva2/server/go/problems/F13Problem.java @@ -83,10 +83,16 @@ public class F13Problem extends AbstractProblemDoubleOffset implements Interface @Override public SolutionHistogram getHistogram() { // EVAERROR.errorMsgOnce("Warning: Restore line in getHistogram for evaluation on F13Problem ???"); - if (getProblemDimension() < 15) return new SolutionHistogram(0, 800, 16); - else if (getProblemDimension() < 25) return new SolutionHistogram(0, 1600, 16); + if (getProblemDimension() < 15) { + return new SolutionHistogram(0, 800, 16); + } + else if (getProblemDimension() < 25) { + return new SolutionHistogram(0, 1600, 16); + } // else if (getProblemDimension() < 35) return new SolutionHistogram(0, 1600, 16); - else return new SolutionHistogram(0, 3200, 12); + else { + return new SolutionHistogram(0, 3200, 12); + } } /********************************************************************************************************************** * These are for GUI diff --git a/src/eva2/server/go/problems/F15Problem.java b/src/eva2/server/go/problems/F15Problem.java index 8cc18403..c34d03ee 100644 --- a/src/eva2/server/go/problems/F15Problem.java +++ b/src/eva2/server/go/problems/F15Problem.java @@ -61,9 +61,15 @@ public class F15Problem extends AbstractProblemDouble implements Serializable, I @Override public SolutionHistogram getHistogram() { - if (getProblemDimension()<15) return new SolutionHistogram(0, 2, 16); - else if (getProblemDimension()<25) return new SolutionHistogram(0, 4, 16); - else return new SolutionHistogram(0, 8, 16); + if (getProblemDimension()<15) { + return new SolutionHistogram(0, 2, 16); + } + else if (getProblemDimension()<25) { + return new SolutionHistogram(0, 4, 16); + } + else { + return new SolutionHistogram(0, 8, 16); + } } @Override diff --git a/src/eva2/server/go/problems/F17Problem.java b/src/eva2/server/go/problems/F17Problem.java index d9999e1b..0017ae7e 100644 --- a/src/eva2/server/go/problems/F17Problem.java +++ b/src/eva2/server/go/problems/F17Problem.java @@ -64,7 +64,11 @@ public class F17Problem extends AbstractProblemDouble implements @Override public SolutionHistogram getHistogram() { - if (getProblemDimension()<15) return new SolutionHistogram(-0.5, 7.5, 16); - else return new SolutionHistogram(-0.5, 15.5, 16); + if (getProblemDimension()<15) { + return new SolutionHistogram(-0.5, 7.5, 16); + } + else { + return new SolutionHistogram(-0.5, 15.5, 16); + } } } diff --git a/src/eva2/server/go/problems/F19Problem.java b/src/eva2/server/go/problems/F19Problem.java index 09475644..10f079bb 100644 --- a/src/eva2/server/go/problems/F19Problem.java +++ b/src/eva2/server/go/problems/F19Problem.java @@ -124,8 +124,12 @@ InterfaceMultimodalProblem, InterfaceInterestingHistogram, InterfaceFirstOrderDe @Override public SolutionHistogram getHistogram() { - if (getProblemDimension()<15) return new SolutionHistogram(0, 8, 16); - else return new SolutionHistogram(0, 40000, 16); + if (getProblemDimension()<15) { + return new SolutionHistogram(0, 8, 16); + } + else { + return new SolutionHistogram(0, 40000, 16); + } } @Override diff --git a/src/eva2/server/go/problems/F1Problem.java b/src/eva2/server/go/problems/F1Problem.java index a14e1c79..ef5e1d6e 100644 --- a/src/eva2/server/go/problems/F1Problem.java +++ b/src/eva2/server/go/problems/F1Problem.java @@ -121,6 +121,8 @@ public class F1Problem extends AbstractProblemDoubleOffset implements Interface2 } // System.out.println(BeanInspector.toString(initR)); return initR; - } else return makeRange(); + } else { + return makeRange(); + } } } diff --git a/src/eva2/server/go/problems/F20Problem.java b/src/eva2/server/go/problems/F20Problem.java index 1be4550c..77c928b6 100644 --- a/src/eva2/server/go/problems/F20Problem.java +++ b/src/eva2/server/go/problems/F20Problem.java @@ -45,8 +45,12 @@ public class F20Problem extends AbstractProblemDouble implements Serializable, I } private double getYOffset() { - if (isShiftFit()) return (getProblemDimension() - 1)*getDefaultRange(); - else return 0; + if (isShiftFit()) { + return (getProblemDimension() - 1)*getDefaultRange(); + } + else { + return 0; + } } private double g(double x, double y) { @@ -100,19 +104,29 @@ public class F20Problem extends AbstractProblemDouble implements Serializable, I @Override public SolutionHistogram getHistogram() { if (getProblemDimension()==10) { - if (getYOffset()==0) return new SolutionHistogram(-5200, -3600, 16); - else return new SolutionHistogram(0, 1600, 16); + if (getYOffset()==0) { + return new SolutionHistogram(-5200, -3600, 16); + } + else { + return new SolutionHistogram(0, 1600, 16); + } } if (getProblemDimension()==30) { - if (getYOffset()==0) return new SolutionHistogram(-15000, -8600, 16); + if (getYOffset()==0) { + return new SolutionHistogram(-15000, -8600, 16); + } // das passst wohl nicht für Multimodales... Also nochmal für 30D. - else return new SolutionHistogram(0, 6400, 16); + else { + return new SolutionHistogram(0, 6400, 16); + } } if (getProblemDimension() <= 5) { double lower = getYOffset()-((getProblemDimension()-1)*getDefaultRange()); return new SolutionHistogram(lower, lower+160, 16); } else if (getProblemDimension() < 15) { return new SolutionHistogram(getYOffset()-5000, getYOffset()-3400, 16); - } else return new SolutionHistogram(getYOffset()-15000, getYOffset()-13400, 16); + } else { + return new SolutionHistogram(getYOffset()-15000, getYOffset()-13400, 16); + } } } diff --git a/src/eva2/server/go/problems/F2Problem.java b/src/eva2/server/go/problems/F2Problem.java index e53aeb0c..068598d9 100644 --- a/src/eva2/server/go/problems/F2Problem.java +++ b/src/eva2/server/go/problems/F2Problem.java @@ -49,7 +49,9 @@ public class F2Problem extends AbstractProblemDoubleOffset implements InterfaceL xii=x[i+1]-m_XOffset; result[0] += (100*(xii-xi*xi)*(xii-xi*xi)+(xi-1)*(xi-1)); } - if (m_YOffset==0 && (result[0]<=0)) result[0]=Math.sqrt(Double.MIN_VALUE); // guard for plots in log scale + if (m_YOffset==0 && (result[0]<=0)) { + result[0]=Math.sqrt(Double.MIN_VALUE); + } // guard for plots in log scale return result; } diff --git a/src/eva2/server/go/problems/F6Problem.java b/src/eva2/server/go/problems/F6Problem.java index 0b1729d1..5ab3ca12 100644 --- a/src/eva2/server/go/problems/F6Problem.java +++ b/src/eva2/server/go/problems/F6Problem.java @@ -133,9 +133,15 @@ implements InterfaceMultimodalProblem, InterfaceFirstOrderDerivableProblem, Inte @Override public SolutionHistogram getHistogram() { - if (getProblemDimension() < 15) return new SolutionHistogram(-0.5, 15.5, 16); - else if (getProblemDimension() < 25) return new SolutionHistogram(-0.5, 39.5, 16); - else return new SolutionHistogram(0, 80, 16); + if (getProblemDimension() < 15) { + return new SolutionHistogram(-0.5, 15.5, 16); + } + else if (getProblemDimension() < 25) { + return new SolutionHistogram(-0.5, 39.5, 16); + } + else { + return new SolutionHistogram(0, 80, 16); + } } @Override diff --git a/src/eva2/server/go/problems/F7Problem.java b/src/eva2/server/go/problems/F7Problem.java index 67add590..554f22ed 100644 --- a/src/eva2/server/go/problems/F7Problem.java +++ b/src/eva2/server/go/problems/F7Problem.java @@ -125,7 +125,9 @@ public class F7Problem extends AbstractProblemDoubleOffset implements Serializab * @param d The mutation operator. */ public void sett(double d) { - if (d < 1) d = 1; + if (d < 1) { + d = 1; + } this.m_t = d; } public double gett() { diff --git a/src/eva2/server/go/problems/F8Problem.java b/src/eva2/server/go/problems/F8Problem.java index ff882d3f..96c1175b 100644 --- a/src/eva2/server/go/problems/F8Problem.java +++ b/src/eva2/server/go/problems/F8Problem.java @@ -118,9 +118,15 @@ public class F8Problem extends AbstractProblemDoubleOffset } @Override public SolutionHistogram getHistogram() { - if (getProblemDimension() < 15) return new SolutionHistogram(-0.1, 7.9, 16); - else if (getProblemDimension() < 25) return new SolutionHistogram(-0.5, 15.5, 16); - else return new SolutionHistogram(0, 16, 16); + if (getProblemDimension() < 15) { + return new SolutionHistogram(-0.1, 7.9, 16); + } + else if (getProblemDimension() < 25) { + return new SolutionHistogram(-0.5, 15.5, 16); + } + else { + return new SolutionHistogram(0, 16, 16); + } } // public double[] getFirstOrderGradients(double[] x) { @@ -197,29 +203,30 @@ public class F8Problem extends AbstractProblemDoubleOffset Arrays.fill(pos, getXOffset()); addOptimum(pos); // the global optimum double refinedX = 0; - if (getProblemDimension()<18) for (int i=0; i1e-10) { return true; - } else return false; + } else { + return false; + } } // else { // if (m_ListOfOptima.isEmpty()) return true; diff --git a/src/eva2/server/go/problems/FLensProblem.java b/src/eva2/server/go/problems/FLensProblem.java index 9bdc4e58..ab655b75 100644 --- a/src/eva2/server/go/problems/FLensProblem.java +++ b/src/eva2/server/go/problems/FLensProblem.java @@ -128,7 +128,9 @@ class MyLensViewer extends JPanel implements InterfaceSolutionViewer { } private void paintLens(AbstractEAIndividual indy, int dim, int height, double radius, int mag, int centerLens, int centerScreen, int segment, Graphics2D g2D) { - if (indy!=null) paintLens(indy.getDoublePosition(), m_LensProblem.testLens(indy.getDoublePosition()), indy.getFitness(0), dim, height, radius, mag, centerLens, centerScreen, segment, g2D); + if (indy!=null) { + paintLens(indy.getDoublePosition(), m_LensProblem.testLens(indy.getDoublePosition()), indy.getFitness(0), dim, height, radius, mag, centerLens, centerScreen, segment, g2D); + } } private static void paintLens(double[] variables, double[] dots, double fit, int dim, int height, double radius, int mag, int centerLens, int centerScreen, @@ -187,8 +189,12 @@ class MyLensViewer extends JPanel implements InterfaceSolutionViewer { InterfaceDataTypeDouble best = (InterfaceDataTypeDouble)pop.getBestIndividual(); //this.m_BestFitness = ((AbstractEAIndividual)best).getFitness(0); if (indiesToPaint.size()==0 || ((AbstractEAIndividual)best).isDominant(indiesToPaint.getBestIndividual())) { - if (indiesToPaint.size()==1) indiesToPaint.set(0, best); - else indiesToPaint.add(best); + if (indiesToPaint.size()==1) { + indiesToPaint.set(0, best); + } + else { + indiesToPaint.add(best); + } this.paint(this.getGraphics()); } } @@ -226,15 +232,19 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser public FLensProblem() { this.m_Template = new ESIndividualDoubleData(); - if (this.m_Show) this.initProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } } public FLensProblem(FLensProblem b) { //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); + if (b.m_Template != null) { + this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); + } //FLensProblem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); + if (b.m_OverallBest != null) { + this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); + } this.m_ProblemDimension = b.m_ProblemDimension; this.m_Noise = b.m_Noise; this.m_XOffSet = b.m_XOffSet; @@ -260,14 +270,18 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser this.m_ProblemFrame.pack(); this.m_ProblemFrame.setVisible(true); //this.m_ProblemFrame.show(); - } else this.m_Panel.resetView(); + } else { + this.m_Panel.resetView(); + } } /** This method gets rid of the problem view frame * */ public void disposeProblemFrame() { - if (this.m_ProblemFrame != null) this.m_ProblemFrame.dispose(); + if (this.m_ProblemFrame != null) { + this.m_ProblemFrame.dispose(); + } this.m_ProblemFrame = null; this.m_Panel = null; } @@ -277,7 +291,9 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser * @param population The current population. */ public void updateProblemFrame(Population population) { - if (this.m_Panel != null) this.m_Panel.updateView(population, false); + if (this.m_Panel != null) { + this.m_Panel.updateView(population, false); + } } /** This method inits the Problem to log multiruns @@ -285,7 +301,9 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser @Override public void initProblem() { this.m_OverallBest = null; - if (this.m_Show) this.initProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } } /** This method inits a given population @@ -304,12 +322,16 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(range); AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this); - if (this.m_Show) this.initProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } } @Override public void evaluatePopulationEnd(Population pop) { - if (this.m_Show) this.updateProblemFrame(pop); + if (this.m_Show) { + this.updateProblemFrame(pop); + } } /** This method evaluate a single individual and sets the fitness values @@ -348,7 +370,9 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser // set a minimum value for the thickness of the lens for (int i = 0; i < x.length; i++) { - if (x[i] < 0.1) x[i] = 0.1; + if (x[i] < 0.1) { + x[i] = 0.1; + } } double[] tmpFit = this.testLens(x); @@ -364,7 +388,9 @@ 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)]; + if (this.m_UseMaterialConst) { + fitness += x[(int)(x.length/2)]; + } ret[0] = fitness; return ret; @@ -480,7 +506,9 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { - if (noise < 0) noise = 0; + if (noise < 0) { + noise = 0; + } this.m_Noise = noise; } public double getNoise() { @@ -534,8 +562,12 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser */ public void setShow(boolean show) { this.m_Show = show; - if (this.m_Show) this.initProblemFrame(); - else this.disposeProblemFrame(); + if (this.m_Show) { + this.initProblemFrame(); + } + else { + this.disposeProblemFrame(); + } } public boolean getShow() { return this.m_Show; @@ -572,7 +604,9 @@ implements InterfaceOptimizationProblem, InterfaceHasSolutionViewer, java.io.Ser * @param indy The new EA individual type. */ public void setEAIndividualTrap(AbstractEAIndividual indy) { - if (indy instanceof InterfaceDataTypeDouble) this.setEAIndividual((InterfaceDataTypeDouble)indy); + if (indy instanceof InterfaceDataTypeDouble) { + this.setEAIndividual((InterfaceDataTypeDouble)indy); + } } /* diff --git a/src/eva2/server/go/problems/FM0Problem.java b/src/eva2/server/go/problems/FM0Problem.java index 46b241e5..c404cf93 100644 --- a/src/eva2/server/go/problems/FM0Problem.java +++ b/src/eva2/server/go/problems/FM0Problem.java @@ -27,8 +27,12 @@ public class FM0Problem extends AbstractMultiModalProblemKnown implements Interf @Override public double getRangeUpperBound(int dim) { - if (dim == 0) return 2.0; - else return 2.8; + if (dim == 0) { + return 2.0; + } + else { + return 2.8; + } } @Override diff --git a/src/eva2/server/go/problems/GPFunctionProblem.java b/src/eva2/server/go/problems/GPFunctionProblem.java index 5f95101a..4d0f3fb7 100644 --- a/src/eva2/server/go/problems/GPFunctionProblem.java +++ b/src/eva2/server/go/problems/GPFunctionProblem.java @@ -112,14 +112,18 @@ public class GPFunctionProblem extends AbstractProblemDouble implements Interfac * @return */ public double scaleFit(double v) { - if (scalingLimit==0.) return 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 { + return v; + } } } diff --git a/src/eva2/server/go/problems/MatlabEvalMediator.java b/src/eva2/server/go/problems/MatlabEvalMediator.java index 4c755d52..8c119550 100644 --- a/src/eva2/server/go/problems/MatlabEvalMediator.java +++ b/src/eva2/server/go/problems/MatlabEvalMediator.java @@ -79,9 +79,13 @@ public class MatlabEvalMediator { // BitSet b = (BitSet)x; // Integer.decode() // - if (question == null) System.err.println("Error: requesting evaluation for null array!"); + 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 (!(x instanceof BitSet)) { + System.err.println("Error, requesting evaluation for invalid data type! " + question.getClass()); + } } // logMPAndSysOut("Synch requesting A requestEval " + getState()); synchronized(requesting) { //MdP @@ -138,16 +142,24 @@ public class MatlabEvalMediator { 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) {}; + 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 (mod<=0) { + mod = Integer.MAX_VALUE; + } } } - if (requesting) logMPOrSysOut("-- MEM Request arrived in MP thread " + runID); - else logMPOrSysOut("-- MEM finished or quit " + runID); + 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 } @@ -172,7 +184,9 @@ public class MatlabEvalMediator { } private void logMP(String msg) { - if (mp!=null) mp.log(msg + "\n"); + if (mp!=null) { + mp.log(msg + "\n"); + } } /** @@ -188,12 +202,16 @@ public class MatlabEvalMediator { * @return */ public Object getQuestion() { - if (mp!=null) logMP("-- Question: " + BeanInspector.toString(question) + "\n"); + if (mp!=null) { + logMP("-- Question: " + BeanInspector.toString(question) + "\n"); + } return question; } double[] getAnswer() { - if (mp!=null) logMP("-- mediator delivering " + BeanInspector.toString(answer) + "\n"); + if (mp!=null) { + logMP("-- mediator delivering " + BeanInspector.toString(answer) + "\n"); + } return answer; } diff --git a/src/eva2/server/go/problems/MatlabProblem.java b/src/eva2/server/go/problems/MatlabProblem.java index c357dc26..7f19e776 100644 --- a/src/eva2/server/go/problems/MatlabProblem.java +++ b/src/eva2/server/go/problems/MatlabProblem.java @@ -139,7 +139,9 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf protected void initTemplate() { switch (dataType) { case typeDouble: - if (m_Template == null || !(m_Template instanceof ESIndividualDoubleData)) m_Template = new ESIndividualDoubleData(); + if (m_Template == null || !(m_Template instanceof ESIndividualDoubleData)) { + m_Template = new ESIndividualDoubleData(); + } if (getProblemDimension() > 0) { // avoid evil case setting dim to 0 during object init ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(getProblemDimension()); ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(range); @@ -147,11 +149,15 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf break; case typeBinary: ///// binary alternative - if (m_Template == null || !(m_Template instanceof GAIndividualBinaryData)) m_Template = new GAIndividualBinaryData(getProblemDimension()); + if (m_Template == null || !(m_Template instanceof GAIndividualBinaryData)) { + m_Template = new GAIndividualBinaryData(getProblemDimension()); + } break; case typeInteger: int[][] intRange=makeIntRange(range); - if (m_Template == null || !(m_Template instanceof GIIndividualIntegerData)) m_Template = new GIIndividualIntegerData(intRange); + if (m_Template == null || !(m_Template instanceof GIIndividualIntegerData)) { + m_Template = new GIIndividualIntegerData(intRange); + } break; } } @@ -204,7 +210,9 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf this.range[i][j]=globalRange[i][j]; } } - } else this.range=null; + } else { + this.range=null; + } if (initRange!=null) { // these may be Matlab objects, so I do it by foot, just to be sure not to clone them within Matlab instead of here this.initialRange = new double[initRange.length][initRange[0].length]; @@ -213,9 +221,13 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf this.initialRange[i][j]=initRange[i][j]; } } - } else this.initialRange=null; + } else { + this.initialRange=null; + } - if (Arrays.deepEquals(initialRange, range)) initialRange=null; + if (Arrays.deepEquals(initialRange, range)) { + initialRange=null; + } dataType=datType; // store the data type log("### Data type is " + dataType); @@ -248,7 +260,9 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf dos = null; } else if (swtch && (dos == null)) { try { - if (fname==null || (fname.length()==0)) fname = defTestOut; + if (fname==null || (fname.length()==0)) { + fname = defTestOut; + } // System.err.println("Opening "+fname); dos = new PrintStream(new FileOutputStream(fname)); } catch (FileNotFoundException e) { @@ -261,7 +275,9 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf if ((verboLevel >= 0) && (verboLevel <= 3)) { verbosityLevel = verboLevel; } - else System.err.println("Error, invalid verbosity level for statistics output!"); + else { + System.err.println("Error, invalid verbosity level for statistics output!"); + } } public String jmiInterfaceNameTipText() { @@ -323,7 +339,9 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf } public void setSeedPopulation(double[][] seedData, double[][] seedDataFit) { - if (seedData==null) seedPopulation=null; + if (seedData==null) { + seedPopulation=null; + } else { if ((seedData.length!=seedDataFit.length) || (seedData[0].length!=getProblemDimension())) { @@ -396,8 +414,12 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf log("Setting text listener, verbo " + verbosityLevel + "\n"); runnable.setTextListener(this); runnable.setVerbosityLevel(verbosityLevel); - if (verbosityLevel>0) runnable.setOutputTo(2); // both file + window - else runnable.setOutputTo(1); // only window + if (verbosityLevel>0) { + runnable.setOutputTo(2); + } // both file + window + else { + runnable.setOutputTo(1); + } // only window runnable.setOutputFullStatsToText(outputAllStatsField); if (seedPopulation!=null) { @@ -428,12 +450,18 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf } } Object specVal = null; // avoid giving chars to the converter method here - the ascii value would be assigned instead of the string - if (specValues[i] instanceof Character) specVal = ""+specValues[i]; - else specVal = specValues[i]; + if (specValues[i] instanceof Character) { + specVal = ""+specValues[i]; + } + else { + specVal = specValues[i]; + } if ((paramName == null) || (!BeanInspector.setMem(opt, paramName, specVal))) { log("... Fail!\n"); System.err.println("Unable to set parameter " + paramName + ", skipping..."); - } else log("... Ok.\n"); + } else { + log("... Ok.\n"); + } } log(BeanInspector.toString(BeanInspector.getMemberDescriptions(opt, true))); } @@ -463,7 +491,9 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf // log("\nppp are " + BeanInspector.toString(runnable.getGOParams().getPostProcessParams())); new Thread(new WaitForEvARunnable(runnable, this)).start(); } - } else System.err.println("Nothing to be done."); + } else { + System.err.println("Nothing to be done."); + } } /** @@ -504,14 +534,18 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf } public String getInfoString() { - if (runnable == null) return ""; + if (runnable == null) { + return ""; + } StringBuffer sb = new StringBuffer(""); sb.append(runnable.terminatedBecause()); return sb.toString(); } public int getFunctionCalls() { - if (runnable == null) return 0; + if (runnable == null) { + return 0; + } return runnable.getGOParams().getOptimizer().getPopulation().getFunctionCalls(); } @@ -584,8 +618,12 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf * @return */ public int getProgress() { - if (runnable == null) return 0; - else return runnable.getProgress(); + if (runnable == null) { + return 0; + } + else { + return runnable.getProgress(); + } } public static String globalInfo() { diff --git a/src/eva2/server/go/problems/PSymbolicRegression.java b/src/eva2/server/go/problems/PSymbolicRegression.java index eaf9ca7d..e36ad46f 100644 --- a/src/eva2/server/go/problems/PSymbolicRegression.java +++ b/src/eva2/server/go/problems/PSymbolicRegression.java @@ -67,15 +67,19 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements public PSymbolicRegression(PSymbolicRegression b) { //AbstractOptimizationProblem - if (b.m_Template != null) + if (b.m_Template != null) { this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); + } //F1Problem - if (b.m_OverallBest != null) + if (b.m_OverallBest != null) { this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - if (b.m_GPArea != null) + } + if (b.m_GPArea != null) { this.m_GPArea = (GPArea)b.m_GPArea.clone(); - if (b.m_TargetFunction != null) + } + if (b.m_TargetFunction != null) { this.m_TargetFunction = (InterfaceRegressionFunction)b.m_TargetFunction.clone(); + } if (b.m_X != null) { this.m_X = new double[b.m_X.length]; for (int i = 0; i < this.m_X.length; i++) { @@ -110,7 +114,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements */ @Override public void initProblem() { - if (m_TargetFunction == null) m_TargetFunction = new RFKoza_GPI_7_3(); + if (m_TargetFunction == null) { + m_TargetFunction = new RFKoza_GPI_7_3(); + } this.m_OverallBest = null; this.m_C = new double[this.m_NumberOfConstants]; for (int i = 0; i < this.m_C.length; i++) { @@ -182,7 +188,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements /** This method init the enviroment panel if necessary. */ private void initEnvironmentPanel() { - if (this.m_Plot == null) this.m_Plot = new Plot("Symbolic Regression", "x", "y", true); + if (this.m_Plot == null) { + this.m_Plot = new Plot("Symbolic Regression", "x", "y", true); + } } /** This method evaluates a given population and set the fitness values @@ -210,12 +218,16 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements this.evaluate(tmpIndy); tmpConst.SetFitness(0, tmpIndy.getFitness(0)); population.incrFunctionCalls(); - if (tmpBestConst.getFitness(0) > tmpConst.getFitness(0)) tmpBestConst = (AbstractEAIndividual)tmpConst.clone(); + if (tmpBestConst.getFitness(0) > tmpConst.getFitness(0)) { + tmpBestConst = (AbstractEAIndividual)tmpConst.clone(); + } } ((GAPIndividualProgramData)tmpIndy).setNumbers((InterfaceDataTypeDouble)tmpBestConst); tmpIndy.SetFitness(0, tmpBestConst.getFitness(0)); } else { - if (m_UseLocalHillClimbing) EVAERROR.errorMsgOnce("Error: local hill climbing only works on GAPIndividualProgramData individuals!"); + if (m_UseLocalHillClimbing) { + EVAERROR.errorMsgOnce("Error: local hill climbing only works on GAPIndividualProgramData individuals!"); + } this.evaluate(tmpIndy); population.incrFunctionCalls(); } @@ -237,8 +249,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements tmpIndy = (InterfaceDataTypeProgram) individual; program = tmpIndy.getProgramData()[0]; - if ((tmpIndy instanceof GAPIndividualProgramData) && (this.m_UseInnerConst)) + if ((tmpIndy instanceof GAPIndividualProgramData) && (this.m_UseInnerConst)) { this.m_C = ((GAPIndividualProgramData)tmpIndy).getDoubleData(); + } fitness = 0; for (int j = 0; j < this.m_NumberOfCheckPoints; j++) { @@ -252,11 +265,15 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements 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)) this.m_OverallBest = null; + 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(); if (this.m_Show) { - if (m_Plot==null) this.initEnvironmentPanel(); + if (m_Plot==null) { + this.initEnvironmentPanel(); + } this.m_Plot.clearAll(); program = ((InterfaceDataTypeProgram)this.m_OverallBest).getProgramData()[0]; for (int i = 0; i < this.m_NumberOfCheckPoints; i++) { @@ -323,7 +340,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements public static Object getSensorValue(String sensor, double[] vars, double[] consts) { if (sensor.charAt(0)=='X') { try { - if (sensor.length()==1) return vars; + if (sensor.length()==1) { + return vars; + } int index=Integer.parseInt(sensor.substring(1)); return new Double(vars[index]); } catch(Exception e) { @@ -335,7 +354,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements return new Double(consts[index]); } else if (sensor.charAt(0)=='N') { return (double)vars.length; - } else return new Double(0); + } 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]); // 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); @@ -374,7 +395,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { - if (noise < 0) noise = 0; + if (noise < 0) { + noise = 0; + } this.m_Noise = noise; } public double getNoise() { @@ -430,7 +453,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements * @param b The new number of check points. */ public void setNumberOfCheckPoints(int b) { - if (b < 0) b = 1; + if (b < 0) { + b = 1; + } this.m_NumberOfCheckPoints = b; } public int getNumberOfCheckPoints() { @@ -452,7 +477,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements } @Override public GPArea getArea() { - if (m_GPArea==null) initProblem(); + if (m_GPArea==null) { + initProblem(); + } return this.m_GPArea; } public String areaTipText() { @@ -464,7 +491,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements */ public void setShowResult(boolean b) { this.m_Show = b; - if (this.m_Show) this.initEnvironmentPanel(); + if (this.m_Show) { + this.initEnvironmentPanel(); + } else if (this.m_Plot != null) { this.m_Plot.dispose(); this.m_Plot = null; @@ -484,7 +513,9 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements this.m_TargetFunction = b; } public InterfaceRegressionFunction getTargetFunction() { - if (m_TargetFunction==null) initProblem(); + if (m_TargetFunction==null) { + initProblem(); + } return this.m_TargetFunction; } public String targetFunctionTipText() { @@ -598,8 +629,12 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements if (prog instanceof AbstractGPNode) { AbstractGPNode gpNode = (AbstractGPNode)prog; return gpNode.getNumberOfNodes(); - } else return 0; - } else return 0; + } else { + return 0; + } + } else { + return 0; + } } /** @@ -619,8 +654,12 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements // System.out.println(d + "\n" + gpNode.getStringRepresentation()); //} return d; - } else return 0; - } else return 0; + } else { + return 0; + } + } else { + return 0; + } } /** diff --git a/src/eva2/server/go/problems/SimpleProblemWrapper.java b/src/eva2/server/go/problems/SimpleProblemWrapper.java index 3529fad1..f77cd1e0 100644 --- a/src/eva2/server/go/problems/SimpleProblemWrapper.java +++ b/src/eva2/server/go/problems/SimpleProblemWrapper.java @@ -57,7 +57,9 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem { // evaluate the vector fitness = ((SimpleProblemDouble)simProb).eval(x); // if indicated, add Gaussian noise - if (m_Noise != 0) RNG.addNoise(fitness, m_Noise); + if (m_Noise != 0) { + RNG.addNoise(fitness, m_Noise); + } // set the fitness individual.setFitness(fitness); } else if (simProb instanceof SimpleProblemBinary) { @@ -128,7 +130,9 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem { ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange()); } else if (m_Template instanceof InterfaceDataTypeBinary) { ((InterfaceDataTypeBinary)this.m_Template).setBinaryDataLength(simProb.getProblemDimension()); - } else System.err.println("Individual type not valid!"); + } else { + System.err.println("Individual type not valid!"); + } } protected double[][] makeRange() { @@ -168,12 +172,16 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem { 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(); + if (m_plot == null) { + openPlot(); + } else { if (!m_plot.isValid()) { m_plot.dispose(); openPlot(); - } else m_plot.clearAll(); + } else { + m_plot.clearAll(); + } } } else if (m_plot != null) { m_plot.dispose(); @@ -193,7 +201,9 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem { * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { - if (noise < 0) noise = 0; + if (noise < 0) { + noise = 0; + } this.m_Noise = noise; } public double getNoise() { diff --git a/src/eva2/server/go/problems/TF1Problem.java b/src/eva2/server/go/problems/TF1Problem.java index 7d8b884b..0c72c4e4 100644 --- a/src/eva2/server/go/problems/TF1Problem.java +++ b/src/eva2/server/go/problems/TF1Problem.java @@ -41,15 +41,19 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem public TF1Problem(TF1Problem b) { //AbstractOptimizationProblem - if (b.m_Template != null) + if (b.m_Template != null) { this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); + } //AbstractMultiObjectiveOptimizationProblem - if (b.m_MOSOConverter != null) + if (b.m_MOSOConverter != null) { this.m_MOSOConverter = (InterfaceMOSOConverter)b.m_MOSOConverter.clone(); - if (b.m_Metric != null) + } + if (b.m_Metric != null) { this.m_Metric = (InterfaceParetoFrontMetric)b.m_Metric.clone(); - if (b.m_ParetoFront != null) + } + if (b.m_ParetoFront != null) { this.m_ParetoFront = (Population)b.m_ParetoFront.clone(); + } if (b.m_Border != null) { this.m_Border = new double[b.m_Border.length][2]; for (int i = 0; i < this.m_Border.length; i++) { @@ -130,10 +134,18 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem individual.SetFitness(i, fitness[i]); } if (this.m_ApplyConstraints) { - if (fitness[0] > 0.5) individual.addConstraintViolation(fitness[0]-0.5); - if (x[1] > 0.1) individual.addConstraintViolation(x[1]-0.1); - if (x[2] > 0.1) individual.addConstraintViolation(x[2]-0.1); - if (x[3] > 0.1) individual.addConstraintViolation(x[3]-0.1); + if (fitness[0] > 0.5) { + individual.addConstraintViolation(fitness[0]-0.5); + } + if (x[1] > 0.1) { + individual.addConstraintViolation(x[1]-0.1); + } + if (x[2] > 0.1) { + individual.addConstraintViolation(x[2]-0.1); + } + if (x[3] > 0.1) { + individual.addConstraintViolation(x[3]-0.1); + } } individual.checkAreaConst4Parallelization(this.m_AreaConst4Parallelization); } @@ -257,7 +269,9 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem * @param noise The sigma for a gaussian random number. */ public void setNoise(double noise) { - if (noise < 0) noise = 0; + if (noise < 0) { + noise = 0; + } this.m_Noise = noise; } public double getNoise() { diff --git a/src/eva2/server/go/problems/WaitForEvARunnable.java b/src/eva2/server/go/problems/WaitForEvARunnable.java index 084604db..da93accc 100644 --- a/src/eva2/server/go/problems/WaitForEvARunnable.java +++ b/src/eva2/server/go/problems/WaitForEvARunnable.java @@ -44,7 +44,9 @@ class WaitForEvARunnable implements Runnable { mp.log("reported results.\n"); mp.notifyFinished(); mp.log("notified finish.\n"); - if (mp.verbosityLevel > 0) System.out.println("Optimization finished: " + mp.getInfoString()); + if (mp.verbosityLevel > 0) { + System.out.println("Optimization finished: " + mp.getInfoString()); + } } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); diff --git a/src/eva2/server/go/problems/inference/metabolic/TimeSeries.java b/src/eva2/server/go/problems/inference/metabolic/TimeSeries.java index f33f4182..d6bb67dc 100755 --- a/src/eva2/server/go/problems/inference/metabolic/TimeSeries.java +++ b/src/eva2/server/go/problems/inference/metabolic/TimeSeries.java @@ -112,11 +112,13 @@ public class TimeSeries implements Serializable { j = 0; st = new StringTokenizer(dataFile[i]); while (st.hasMoreElements()) - if (i > 0) - data[i - 1][j++] = st.nextElement().toString(); - else - names.put(st.nextElement().toString().replaceAll("\"", - ""), new Integer(j++)); + if (i > 0) { + data[i - 1][j++] = st.nextElement().toString(); + } + else { + names.put(st.nextElement().toString().replaceAll("\"", + ""), new Integer(j++)); + } } /* @@ -140,8 +142,9 @@ public class TimeSeries implements Serializable { j = ((Integer) names.get(name)).intValue(); for (i = 0; i < data.length; i++) { if (!data[i][j].equals("-1") - && !data[i][j].equals("NaN")) - count++; + && !data[i][j].equals("NaN")) { + count++; + } } values = new double[2][count]; // /* @@ -184,12 +187,15 @@ public class TimeSeries implements Serializable { * thrown. */ public double[] getTimes(String metabolite) throws Exception { - if (names == null) - System.err.println("getTimes: names is null"); - if (!names.containsKey(metabolite)) - throw new Exception("No data measured for this metabolite"); - if (names.get(metabolite) == null) - System.err.println("get(metabolite) is null"); + if (names == null) { + System.err.println("getTimes: names is null"); + } + if (!names.containsKey(metabolite)) { + throw new Exception("No data measured for this metabolite"); + } + if (names.get(metabolite) == null) { + System.err.println("get(metabolite) is null"); + } return ((double[][]) names.get(metabolite))[0]; } @@ -218,8 +224,9 @@ public class TimeSeries implements Serializable { * thrown. */ public double[] getValues(String metabolite) throws Exception { - if (!names.containsKey(metabolite)) - throw new Exception("No data measured for this metabolite"); + if (!names.containsKey(metabolite)) { + throw new Exception("No data measured for this metabolite"); + } return ((double[][]) names.get(metabolite))[1]; } diff --git a/src/eva2/server/go/strategies/ANPSO.java b/src/eva2/server/go/strategies/ANPSO.java index 29bf64f1..16e74015 100644 --- a/src/eva2/server/go/strategies/ANPSO.java +++ b/src/eva2/server/go/strategies/ANPSO.java @@ -356,8 +356,12 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi 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); + } 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)... @@ -365,11 +369,15 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // 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 + 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_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"); } @@ -383,7 +391,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // 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; + if (s[i][j]>maxNeighborCntNicheGraph) { + s[i][j]=maxNeighborCntNicheGraph; + } // if i and j had been close to each other for at least two generations // they are connected by an edge @@ -396,7 +406,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // 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; + if (s[i][j] < minNeighborCntNicheGraph) { + s[i][j] = minNeighborCntNicheGraph; + } } } } @@ -432,7 +444,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi 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)"); + if (sorted[indy.getIndividualIndex()]!=null) { + throw new RuntimeException("Error, inconsistency in ANPSO! (index wrong)"); + } sorted[indy.getIndividualIndex()] = indy; } return sorted; @@ -503,7 +517,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi boolean TRACEMTHD = false; // ... and use the corresponding particles to create the subswarms - if (TRACEMTHD) System.out.println("---------"); + if (TRACEMTHD) { + System.out.println("---------"); + } for (Set connSet : connectedComps){ if (connSet.size() > 1){// create niche Population pop = new Population(connSet.size()); @@ -515,9 +531,13 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi } pop.add(indy); } - if (TRACEMTHD) System.out.print(" subswarm size ssize " + pop.size()); + 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)); + if (TRACEMTHD) { + System.out.print(" removing " + (pop.size()-maxInitialSubSwarmSize)); + } tmpPop = pop.getWorstNIndividuals(pop.size()-maxInitialSubSwarmSize, -1); tmpPop.synchSize(); // Population testPop=(Population)pop.clone(); @@ -536,7 +556,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi pop.synchSize(); } setOfSubswarms.add(pop); - if (TRACEMTHD) System.out.print("\nNew subswarm of size: " + pop.size()); + 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()); @@ -549,7 +571,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi // System.err.println("Wrong subswarm " + i); // } // } - if (TRACEMTHD) System.out.println(); + if (TRACEMTHD) { + System.out.println(); + } newMainPop.synchSize(); 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; i0) { pop.addAll(generateG1((int)(numToInit * this.g1))); - if (TRACE) System.out.println("s1: " + pop.size()); + if (TRACE) { + System.out.println("s1: " + pop.size()); + } generateG2(pop, (int)(numToInit * this.g2)); - if (TRACE) System.out.println("s2: " + pop.size()); + if (TRACE) { + System.out.println("s2: " + pop.size()); + } generateG3(pop, poolSize-pop.size()); - if (TRACE) System.out.println("s3: " + pop.size()); + if (TRACE) { + System.out.println("s3: " + pop.size()); + } } return pop; } @@ -381,8 +391,12 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ } private static BitSet getBinaryData(AbstractEAIndividual indy) { - if (indy instanceof InterfaceGAIndividual) return ((InterfaceGAIndividual)indy).getBGenotype(); - else if (indy instanceof InterfaceDataTypeBinary) return ((InterfaceDataTypeBinary)indy).getBinaryData(); + 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()); } @@ -764,7 +778,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } @Override diff --git a/src/eva2/server/go/strategies/CBNPSO.java b/src/eva2/server/go/strategies/CBNPSO.java index 5c72fd36..0f35e826 100644 --- a/src/eva2/server/go/strategies/CBNPSO.java +++ b/src/eva2/server/go/strategies/CBNPSO.java @@ -53,7 +53,9 @@ public class CBNPSO extends ClusterBasedNichingEA implements Serializable { setOptimizer(new ParticleSwarmOptimization(popSize, 2.05, 2.05, PSOTopologyEnum.grid, 2)); ParamAdaption[] defAdpt = new ParamAdaption[]{getDefaultSinusoidalAdaption()}; setParameterControl(defAdpt); - if (threshAdaption) addParameterControl(getDefaultThreshAdaption()); + if (threshAdaption) { + addParameterControl(getDefaultThreshAdaption()); + } setPopulationSize(popSize); } @@ -83,7 +85,9 @@ public class CBNPSO extends ClusterBasedNichingEA implements Serializable { 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(); + 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"; + } else { + return "CBN-PSO"; + } } public static String globalInfo() { @@ -173,7 +187,9 @@ public class CBNPSO extends ClusterBasedNichingEA implements Serializable { double fitThres = 100; if (prob instanceof InterfaceInterestingHistogram) { fitThres = ((InterfaceInterestingHistogram)prob).getHistogram().getUpperBound(); - } else EVAERROR.errorMsgOnce("Warning, problem does not define a fitness threshold!"); + } else { + EVAERROR.errorMsgOnce("Warning, problem does not define a fitness threshold!"); + } SolutionSet solSet = getAllSolutions(); Population archived = solSet.getSolutions(); @@ -184,21 +200,27 @@ public class CBNPSO extends ClusterBasedNichingEA implements Serializable { if (archived.size()>0) { return ((double)interesting.size())/((double)archived.size()); - } else return -1; + } else { + return -1; + } } @Override public String[] getAdditionalDataHeader() { String[] addVals = {"interestingRatio"}; - if (getCurrentPeriod()>=0) addVals = new String[]{"interestingRatio", "adaptPeriod"}; + 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"}; + if (getCurrentPeriod()>=0) { + addVals = new String[]{"Ratio of interesting solutions within all archived solutions", + "Current sigma adaptation period"}; + } return ToolBox.appendArrays(super.getAdditionalDataInfo(), addVals); } @@ -212,20 +234,33 @@ public class CBNPSO extends ClusterBasedNichingEA implements Serializable { ParamAdaption[] adaptors = super.getParameterControl(); SinusoidalParamAdaption sinA=null; CbpsoFitnessThresholdBasedAdaption ftA=null; - if (adaptors!=null) for (int i=0; i=0) addVals = new Object[]{getInterestingSolutionRatio(), freq}; - else addVals = new Object[]{getInterestingSolutionRatio()}; + 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/server/go/strategies/CHCAdaptiveSearchAlgorithm.java b/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java index 3c3f9538..128d10dd 100644 --- a/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java +++ b/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java @@ -87,7 +87,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S @Override public void initByPopulation(Population pop, boolean reset) { this.m_Population = (Population)pop.clone(); - if (reset) this.m_Population.init(); + if (reset) { + this.m_Population.init(); + } AbstractEAIndividual tmpIndy = ((AbstractEAIndividual)(this.m_Population.get(0))); if (tmpIndy instanceof InterfaceGAIndividual) { this.m_DifferenceThreshold = (int)(((InterfaceGAIndividual)tmpIndy).getGenotypeLength()*this.m_InitialDifferenceThreshold); @@ -128,8 +130,12 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S for (int i = 0; i < parents.size(); i++) { tmpIndy = ((AbstractEAIndividual)parents.get(i)); - if (tmpIndy == null) System.out.println("Individual null "+i); - if (this.m_Population == null) System.out.println("population null "+i); + if (tmpIndy == null) { + System.out.println("Individual null "+i); + } + if (this.m_Population == null) { + System.out.println("population null "+i); + } partners = this.m_RecombSelectionOperator.findPartnerFor(tmpIndy, this.m_Population, this.m_NumberOfPartners); if (this.computeHammingDistance(tmpIndy, partners) > this.m_DifferenceThreshold) { @@ -157,7 +163,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S tmpB2 = ((InterfaceGAIndividual) partners.get(i)).getBGenotype(); tmpDist = 0; for (int j = 0; j < ((InterfaceGAIndividual)dad).getGenotypeLength(); j++) { - if (tmpB1.get(j) == tmpB2.get(j)) tmpDist++; + if (tmpB1.get(j) == tmpB2.get(j)) { + tmpDist++; + } } result = Math.max(result, tmpDist); } @@ -179,8 +187,12 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S tmpBitSet = mutant.getBGenotype(); for (int j = 0; j < mutant.getGenotypeLength(); j++) { if (RNG.flipCoin(this.m_DivergenceRate)) { - if (tmpBitSet.get(j)) tmpBitSet.clear(j); - else tmpBitSet.set(j); + if (tmpBitSet.get(j)) { + tmpBitSet.clear(j); + } + else { + tmpBitSet.set(j); + } } } mutant.SetBGenotype(tmpBitSet); @@ -231,13 +243,17 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized @@ -355,7 +371,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S * @param partners */ public void setNumberOfPartners(int partners) { - if (partners < 0) partners = 0; + if (partners < 0) { + partners = 0; + } this.m_NumberOfPartners = partners; } public int getNumberOfPartners() { diff --git a/src/eva2/server/go/strategies/ClusterBasedNichingEA.java b/src/eva2/server/go/strategies/ClusterBasedNichingEA.java index ac9a0462..04fa7d37 100644 --- a/src/eva2/server/go/strategies/ClusterBasedNichingEA.java +++ b/src/eva2/server/go/strategies/ClusterBasedNichingEA.java @@ -182,7 +182,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis @Override public void init() { - if (m_Undifferentiated==null) this.m_Undifferentiated = new Population(m_PopulationSize); + if (m_Undifferentiated==null) { + this.m_Undifferentiated = new Population(m_PopulationSize); + } else { m_Undifferentiated.resetProperties(); m_Undifferentiated.setTargetSize(m_PopulationSize); @@ -225,7 +227,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // if (useDistraction) distraction = new Distraction(distrDefaultStrength, Distraction.METH_BEST); convergedCnt = 0; collisions=0; - if (evalPop) this.evaluatePopulation(this.m_Undifferentiated); + if (evalPop) { + this.evaluatePopulation(this.m_Undifferentiated); + } this.m_Optimizer.initByPopulation(m_Undifferentiated, false); this.m_Undifferentiated = m_Optimizer.getPopulation(); // required for changes to the population by the optimizer m_Population = m_Undifferentiated; @@ -239,7 +243,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis @Override public void initByPopulation(Population pop, boolean reset) { this.m_Undifferentiated = (Population)pop.clone(); - if (reset) this.m_Undifferentiated.init(); + if (reset) { + this.m_Undifferentiated.init(); + } initDefaults(reset); } @@ -253,7 +259,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } private void plot(int gen) { - if (!(this.m_Problem instanceof TF1Problem) && !(this.m_Problem instanceof Interface2DBorderProblem)) return; + if (!(this.m_Problem instanceof TF1Problem) && !(this.m_Problem instanceof Interface2DBorderProblem)) { + return; + } double[] a = new double[2]; a[0] = 0.0; a[1] = 0.0; @@ -342,10 +350,18 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis AbstractEAIndividual indy2) { // DPointSet popRep; double[] pos1, pos2; - if (indy1 instanceof InterfaceDataTypeDouble) pos1=((InterfaceDataTypeDouble)indy1).getDoubleData(); - else pos1=(indy1).getDoublePosition(); - if (indy2 instanceof InterfaceDataTypeDouble) pos2=((InterfaceDataTypeDouble)indy2).getDoubleData(); - else pos2 =(indy2).getDoublePosition(); + if (indy1 instanceof InterfaceDataTypeDouble) { + pos1=((InterfaceDataTypeDouble)indy1).getDoubleData(); + } + else { + pos1=(indy1).getDoublePosition(); + } + if (indy2 instanceof InterfaceDataTypeDouble) { + pos2=((InterfaceDataTypeDouble)indy2).getDoubleData(); + } + else { + pos2 =(indy2).getDoublePosition(); + } tp.getFunctionArea().drawLine(pos1, pos2); } @@ -416,7 +432,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (term) { // System.out.println("Twice the halting window passed without improvement and still no phenotypic convergence!!!"); return true; - } else return false; + } else { + return false; + } } } @@ -469,12 +487,16 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis EvolutionStrategies es = (EvolutionStrategies)m_Optimizer; int mu = Math.max(1,(int)(muLambdaRatio*species.size())); if (mu >= species.size()) { - if (TRACE) System.err.println("warning, muLambdaRatio produced mu >= lambda.. reducing to mu=lambda-1"); + if (TRACE) { + System.err.println("warning, muLambdaRatio produced mu >= lambda.. reducing to mu=lambda-1"); + } mu = Math.max(1,species.size() - 1); } es.setMu(mu); es.setLambda(species.size()); - if (TRACE) System.out.println("mu: "+es.getMu() + " / lambda: " + es.getLambda()); + if (TRACE) { + System.out.println("mu: "+es.getMu() + " / lambda: " + es.getLambda()); + } } if (TRACE) { System.out.println("Bef: spec size: " + species.size() + ", target size " + species.getTargetSize()); @@ -494,7 +516,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis System.out.println("Best aft: " + BeanInspector.toString(retPop.getBestFitness())); } if (retPop.size() != retPop.getTargetSize()) { - if (TRACE) System.out.println("correcting popsize after opt: " + retPop.getTargetSize() + " to " + retPop.size()); + if (TRACE) { + System.out.println("correcting popsize after opt: " + retPop.getTargetSize() + " to " + retPop.size()); + } retPop.synchSize(); } @@ -532,9 +556,13 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis for (int i=0; i 0) { - if (m_Undifferentiated.getGeneration()<=1) plot(m_Undifferentiated.getGeneration()); + if (m_Undifferentiated.getGeneration()<=1) { + plot(m_Undifferentiated.getGeneration()); + } } if (sleepTime > 0) { try { @@ -551,12 +579,16 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // this.capMutationRate(this.m_Undifferentiated, 0); // MK this sets mutation rate to 0! why? possibly to guarantee contraction of the species? m_Undifferentiated.putData(InterfaceSpeciesAware.populationTagKey, InterfaceSpeciesAware.explorerPopTag); m_Undifferentiated = optimizeSpecies(m_Undifferentiated, false); - } else m_Undifferentiated.incrGeneration(); + } else { + m_Undifferentiated.incrGeneration(); + } Population curSpecies; // optimize the clustered species for (int i = this.m_Species.size() - 1; i >= 0; i--) { - if (TRACE) System.out.println("-Deme " + i + " size: " + ((Population)this.m_Species.get(i)).size()); + if (TRACE) { + System.out.println("-Deme " + i + " size: " + ((Population)this.m_Species.get(i)).size()); + } curSpecies = ((Population)this.m_Species.get(i)); curSpecies.SetFunctionCalls(0); curSpecies.synchSize(); @@ -568,17 +600,23 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // System.out.println("Diff.Size : " + ((Population)this.m_Species.get(i)).size() +"/"+((Population)this.m_Species.get(i)).getPopulationSize()); // } convergedCnt++; - if (TRACE_EVTS) System.out.println("!!!! Converged Spec!"); + if (TRACE_EVTS) { + System.out.println("!!!! Converged Spec!"); + } if (TRACE) { testSpeciesForConvergence(curSpecies); System.out.print("--Converged: "+convergedCnt + " - " + testSpeciesForConvergence(curSpecies)); } - if (TRACE) System.out.println(curSpecies.getBestEAIndividual()); + if (TRACE) { + System.out.println(curSpecies.getBestEAIndividual()); + } // memorize the best one.... // AbstractEAIndividual best = (AbstractEAIndividual)curSpecies.getBestEAIndividual().getClone(); AbstractEAIndividual best = curSpecies.getBestHistoric(); // usually we want the best alltogether - if (best == null) best = (AbstractEAIndividual)curSpecies.getBestEAIndividual().getClone(); + if (best == null) { + best = (AbstractEAIndividual)curSpecies.getBestEAIndividual().getClone(); + } // if (useDistraction) { // Add distractor! // if (distraction == null) distraction = new Distraction(distrDefaultStrength, Distraction.METH_BEST); // distraction.addDistractorFrom(curSpecies); @@ -617,7 +655,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // } // This is necessary to keep track of the function calls needed m_Undifferentiated.incrFunctionCallsBy(curSpecies.getFunctionCalls()); - if (TRACE) System.out.println("### funcalls: "+m_Undifferentiated.getFunctionCalls()); + if (TRACE) { + System.out.println("### funcalls: "+m_Undifferentiated.getFunctionCalls()); + } } ////////////////////// @@ -627,31 +667,40 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis for (int i = 0; i < this.m_Species.size(); i++) { this.m_Population.addPopulation((Population)this.m_Species.get(i)); } - if (m_doomedPop.size()>0) m_Population.addPopulation(reinitPop); // this is just so that the numbers match up... + if (m_doomedPop.size()>0) { + m_Population.addPopulation(reinitPop); + } // this is just so that the numbers match up... m_Population.synchSize(); } ////////////////////// if ((this.m_Undifferentiated.getFunctionCalls()+(reinitPop==null ? 0 : (reinitPop.size()))) % this.m_PopulationSize != 0) { - if (TRACE) System.out.println("### mismatching number of funcalls, inactive species?");// Correcting by " + (m_PopulationSize - (m_Undifferentiated.getFunctionCalls() % m_PopulationSize))); + if (TRACE) { + System.out.println("### mismatching number of funcalls, inactive species?"); + }// Correcting by " + (m_PopulationSize - (m_Undifferentiated.getFunctionCalls() % m_PopulationSize))); // if (TRACE) System.out.println("### undiff " + ((isActive(m_Undifferentiated)) ? "active!" : "inactive!")); // m_Undifferentiated.incrFunctionCallsBy(m_PopulationSize - (m_Undifferentiated.getFunctionCalls() % m_PopulationSize)); } //else if (TRACE) System.out.println("### undiff active: " + isActive(m_Undifferentiated)); // possible species differentiation and convergence if (this.m_Undifferentiated.getGeneration()%this.m_SpeciesCycle == 0) { - if (TRACE) System.out.println("Species cycle:"); + if (TRACE) { + System.out.println("Species cycle:"); + } initClustering(); if (this.m_UseSpeciesDifferentiation) { ///////////////////////////// species differentiation phase - if (TRACE) printState("---Species Differentation", reinitPop); + if (TRACE) { + printState("---Species Differentation", reinitPop); + } Population[] clusters; ArrayList newSpecies = new ArrayList(); //cluster the undifferentiated population clusters = this.m_CAForSpeciesDifferentation.cluster(this.m_Undifferentiated, m_Population); - if (TRACE) - System.out.println("clustered undiff to " + clusters.length); + if (TRACE) { + System.out.println("clustered undiff to " + clusters.length); + } for (int j = 1; j < clusters.length; j++) { // loop new clusters splitFromFirst(m_Undifferentiated, clusters[j], false); newSpecies.add(clusters[j]); @@ -662,13 +711,21 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // if (curSpecies.size()>m_minGroupSize) { // only active populations are clustered // check if a species has differentiated any further clusters = this.m_CAForSpeciesDifferentation.cluster(curSpecies, m_Population); - if (TRACE) System.out.println("clustered " + i + " to " + clusters.length); - if (clusters[0].size()>0) mergeToFirst(m_Undifferentiated, clusters[0], false); + if (TRACE) { + System.out.println("clustered " + i + " to " + clusters.length); + } + if (clusters[0].size()>0) { + mergeToFirst(m_Undifferentiated, clusters[0], false); + } for (int j = 1; j < clusters.length; j++) { // set up new species // this is treated as a split only if more than one cluster was found // so if clustering results in a list of size 2: [undiff,spec], the curSpecies only is maintained. - if (clusters.length<=2) clusters[j].addDataFromPopulation(curSpecies); // copy earlier data to corresponding new cluster - else splitFromFirst(curSpecies, clusters[j], true); + if (clusters.length<=2) { + clusters[j].addDataFromPopulation(curSpecies); + } // copy earlier data to corresponding new cluster + else { + splitFromFirst(curSpecies, clusters[j], true); + } newSpecies.add(clusters[j]); } @@ -678,7 +735,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // } } this.m_Species = newSpecies; - if (TRACE) printState("---After differentiation", reinitPop); + if (TRACE) { + printState("---After differentiation", reinitPop); + } //if (this.m_Show) this.plot(); } // end of species differentiation @@ -699,15 +758,21 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis int[] assocSpec = m_CAForSpeciesMerging.associateLoners(m_Undifferentiated, m_Species.toArray(new Population[m_Species.size()]), m_Population); for (int i=m_Undifferentiated.size()-1; i>=0; i--) { // backwards or die! if (assocSpec[i]>=0) { - if (TRACE_EVTS) System.out.println("!!! Loner merge to " + i ); + if (TRACE_EVTS) { + System.out.println("!!! Loner merge to " + i ); + } // loner i should be merged to species assocSpec[i] AbstractEAIndividual tmpIndy = (AbstractEAIndividual)this.m_Undifferentiated.get(i); - if (m_Topology!=null) plotLine(m_Topology, tmpIndy, m_Species.get(assocSpec[i]).getBestEAIndividual()); + if (m_Topology!=null) { + plotLine(m_Topology, tmpIndy, m_Species.get(assocSpec[i]).getBestEAIndividual()); + } this.m_Undifferentiated.remove(i); m_Species.get(assocSpec[i]).add(tmpIndy); // TODO merge information from loners? } } - if (TRACE) printState("---After loner-merges", reinitPop); + if (TRACE) { + printState("---After loner-merges", reinitPop); + } Population spec1, spec2; // test if species are close to already archived solutions - deactivate them if so assocSpec = m_CAForSpeciesMerging.associateLoners(m_Archive, m_Species.toArray(new Population[m_Species.size()]), m_Population); @@ -721,12 +786,16 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // the species has not yet been deactivated specToRemove.add(assocSpec[i]); collisions ++; - if (TRACE) System.out.println("Inactive merge - resetting " + spec1.size() + " surplus indies"); + if (TRACE) { + System.out.println("Inactive merge - resetting " + spec1.size() + " surplus indies"); + } if (spec1.getBestEAIndividual().isDominating(aIndy)) { // update the archived one with the better one? No rather not - it may happen that a large species is assoctiated which is quite large and spans over several optima - in that case an earlier found may get lost // m_Archive.set(i, spec1.getBestEAIndividual()); } - if (TRACE_EVTS) System.out.println("!!! Reinit Spec " + assocSpec[i] + ", fit " + spec1.getBestEAIndividual()); + if (TRACE_EVTS) { + System.out.println("!!! Reinit Spec " + assocSpec[i] + ", fit " + spec1.getBestEAIndividual()); + } m_doomedPop.addPopulation(spec1); } } @@ -734,12 +803,18 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis int lastRemoved = Integer.MAX_VALUE; while (!specToRemove.isEmpty()) { // backwards sorted or DIE! int specIndex = specToRemove.poll(); - if (specIndex > lastRemoved) System.err.println("Stupid queue!!!"); - if (TRACE) System.out.println("Removing species at index " + specIndex); + if (specIndex > lastRemoved) { + System.err.println("Stupid queue!!!"); + } + if (TRACE) { + System.out.println("Removing species at index " + specIndex); + } m_Species.remove(specIndex); // warning, dont try to remove Integer object but index i! lastRemoved = specIndex; } - if (TRACE) printState("---After archive-merges", reinitPop); + if (TRACE) { + printState("---After archive-merges", reinitPop); + } // Now test if species should be merged among each other for (int i1 = 0; i1 < this.m_Species.size(); i1++) { spec1 = (Population)this.m_Species.get(i1); @@ -747,14 +822,18 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis spec2 = (Population)this.m_Species.get(i2); if (this.m_CAForSpeciesMerging.mergingSpecies(spec1, spec2, m_Population)) { - if (TRACE_EVTS || TRACE) System.out.println("!!! -Merging species (" + i1 +", " +i2 +") ["+spec1.size()+"/"+spec2.size()+"]"); + if (TRACE_EVTS || TRACE) { + System.out.println("!!! -Merging species (" + i1 +", " +i2 +") ["+spec1.size()+"/"+spec2.size()+"]"); + } mergeToFirst(spec1, spec2, true); this.m_Species.remove(i2); i2--; } } } - if (TRACE) printState("---After merging", reinitPop); + if (TRACE) { + printState("---After merging", reinitPop); + } } /// end of species merging if (m_maxSpeciesSize >= m_minGroupSize) { @@ -762,7 +841,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis for (int i=0; im_maxSpeciesSize) { - if (TRACE_EVTS) System.out.println("!!! Reinit indies " + (m_maxSpeciesSize - curSpec.size())); + if (TRACE_EVTS) { + System.out.println("!!! Reinit indies " + (m_maxSpeciesSize - curSpec.size())); + } ArrayList sorted = curSpec.getSorted(reduceSizeComparator); for (int k=m_maxSpeciesSize; k0) m_Population.addPopulation(m_doomedPop); // this is just so that the numbers match up... + if (m_doomedPop.size()>0) { + m_Population.addPopulation(m_doomedPop); + } // this is just so that the numbers match up... m_Population.synchSize(); if (TRACE) { System.out.println("Doomed size: " + m_doomedPop.size()); @@ -828,8 +913,12 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (getClusterDiffDist()>0) { // assume that it should be set if (this.m_CAForSpeciesDifferentation instanceof InterfaceClusteringDistanceParam) { ((InterfaceClusteringDistanceParam)m_CAForSpeciesDifferentation).setClustDistParam(getClusterDiffDist()); - if (TRACE) System.out.println("### Clustering distance parameter set to "+ getClusterDiffDist()); - } else EVAERROR.errorMsgOnce("Warning: cluster distance is defined in CBN but the clustering method " + m_CAForSpeciesDifferentation.getClass() + " cant interpret it!"); + if (TRACE) { + System.out.println("### Clustering distance parameter set to "+ getClusterDiffDist()); + } + } else { + EVAERROR.errorMsgOnce("Warning: cluster distance is defined in CBN but the clustering method " + m_CAForSpeciesDifferentation.getClass() + " cant interpret it!"); + } } this.m_CAForSpeciesDifferentation.initClustering(m_Population); } @@ -890,13 +979,21 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis */ protected void mergeToFirst(Population spec1, Population spec2, boolean plot) { // System.out.println("Merging " + spec2.size() + " to " + spec1.size()); - if (plot && (m_Topology!=null)) plotLine(m_Topology, spec1.getBestEAIndividual(), spec2.getBestEAIndividual()); + if (plot && (m_Topology!=null)) { + plotLine(m_Topology, spec1.getBestEAIndividual(), spec2.getBestEAIndividual()); + } spec1.addPopulation(spec2); // keep longer history - if (spec2.getHistoryLength() > spec1.getHistoryLength()) spec1.SetHistory(spec2.getHistory()); - if (spec2.getGeneration() > spec1.getGeneration()) spec1.setGenerationTo(spec2.getGeneration()); + if (spec2.getHistoryLength() > spec1.getHistoryLength()) { + spec1.SetHistory(spec2.getHistory()); + } + if (spec2.getGeneration() > spec1.getGeneration()) { + spec1.setGenerationTo(spec2.getGeneration()); + } // possibly notify the optimizer of the merging event to merge population based information - if (m_Optimizer instanceof InterfaceSpeciesAware) ((InterfaceSpeciesAware)m_Optimizer).mergeToFirstPopulationEvent(spec1, spec2); + if (m_Optimizer instanceof InterfaceSpeciesAware) { + ((InterfaceSpeciesAware)m_Optimizer).mergeToFirstPopulationEvent(spec1, spec2); + } } /** @@ -917,7 +1014,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis newSp.SetHistory(new LinkedList()); } - if (m_Optimizer instanceof InterfaceSpeciesAware) ((InterfaceSpeciesAware)m_Optimizer).splitFromFirst(parentSp, newSp); + if (m_Optimizer instanceof InterfaceSpeciesAware) { + ((InterfaceSpeciesAware)m_Optimizer).splitFromFirst(parentSp, newSp); + } } // /** @@ -971,10 +1070,14 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized @@ -1052,7 +1155,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis @Override public void setPopulation(Population pop){ this.m_Undifferentiated = pop; - if (m_Archive==null) m_Archive = new Population(); + if (m_Archive==null) { + m_Archive = new Population(); + } m_Archive.setPopMetric(pop.getPopMetric()); m_Population.setPopMetric(pop.getPopMetric()); m_doomedPop.setPopMetric(pop.getPopMetric()); @@ -1082,7 +1187,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis for (Population sp : m_Species) { sols.add(sp.getBestIndividual()); } - if (m_Undifferentiated.size()>0) sols.add(m_Undifferentiated.getBestIndividual()); + if (m_Undifferentiated.size()>0) { + sols.add(m_Undifferentiated.getBestIndividual()); + } // if (!sols.checkNoNullIndy()) { // System.err.println("error in CBN..."); // } @@ -1192,7 +1299,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } public void setShowCycle(int b){ this.m_ShowCycle = b; - if (b<=0) m_Topology=null; + if (b<=0) { + m_Topology=null; + } } public String showCycleTipText() { return "Determines how often show is performed (generations); set to zero to deactivate."; @@ -1348,13 +1457,17 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis * @return average population measures */ protected double[] getAvgSpeciesMeasures() { - if (m_Species==null || (m_Species.size()==0)) return new double[]{0}; + if (m_Species==null || (m_Species.size()==0)) { + return new double[]{0}; + } else { double[] measures = m_Species.get(0).getPopulationMeasures(); for (int i=1; i1) Mathematics.svDiv((double)m_Species.size(), measures, measures); + if (m_Species.size()>1) { + Mathematics.svDiv((double)m_Species.size(), measures, measures); + } return measures; } } @@ -1402,7 +1515,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // int numExpectedOptima = (int)((((double)getPopulationSize())*0.9)/((ClusteringDensityBased)m_CAForSpeciesDifferentation).getMinimumGroupSize()); // this.clusterDiffDist = EsDpiNiching.calcEstimatedNicheRadius(((AbstractProblemDouble)m_Problem).makeRange(), numExpectedOptima, new EuclideanMetric()); setUpperBoundClustDiff((InterfaceProblemDouble) m_Problem); - } else System.err.println("Warning, unable to calculate standard niche radius in CBN-EA"); + } else { + System.err.println("Warning, unable to calculate standard niche radius in CBN-EA"); + } } } @@ -1433,13 +1548,17 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (adpt.getControlledParam().equals("clusterDiffDist")) { if (adpt instanceof InterfaceHasUpperDoubleBound) { ((InterfaceHasUpperDoubleBound)adpt).SetUpperBnd(clusterDiffDist); - } else System.err.println("Warning, unknown parameter adaption type for automatic setting of upper bound of the clustering sigma (CBN-EA)"); + } else { + System.err.println("Warning, unknown parameter adaption type for automatic setting of upper bound of the clustering sigma (CBN-EA)"); + } } } } // double estRad = EsDpiNiching.calcEstimatedNicheRadius(prob.makeRange(), expectedPeaks, metric); // setClusterDiffDist(estRad); - } else System.err.println("Warning, unable to calculate standard niche radius in CBN-EA"); + } else { + System.err.println("Warning, unable to calculate standard niche radius in CBN-EA"); + } } public double getClusterDiffDist() { diff --git a/src/eva2/server/go/strategies/ClusteringHillClimbing.java b/src/eva2/server/go/strategies/ClusteringHillClimbing.java index 80fd0560..a106f5ef 100644 --- a/src/eva2/server/go/strategies/ClusteringHillClimbing.java +++ b/src/eva2/server/go/strategies/ClusteringHillClimbing.java @@ -128,7 +128,9 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } @Override public void init() { @@ -162,7 +164,9 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } @Override @@ -175,10 +179,16 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { Pair popD; int funCallsBefore=m_Population.getFunctionCalls(); int evalsNow, lastOverhead = (m_Population.getFunctionCalls() % hcEvalCycle); - if (lastOverhead>0) evalsNow = (2*hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle)); - else evalsNow = hcEvalCycle; + if (lastOverhead>0) { + evalsNow = (2*hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle)); + } + else { + evalsNow = hcEvalCycle; + } do { - if (TRACE) System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow); + if (TRACE) { + System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow); + } popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, evalsNow, 0.5, mutator); // (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5); if (popD.head().getFunctionCalls()==funCallsBefore) { @@ -188,17 +198,25 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { } while (popD.head().getFunctionCalls()==funCallsBefore); improvement = popD.tail(); m_Population = popD.head(); - if (TRACE) System.out.println("num inds after clusterLS: " + m_Population.size()); + if (TRACE) { + System.out.println("num inds after clusterLS: " + m_Population.size()); + } popD.head().setGenerationTo(m_Population.getGeneration()+1); if (doReinitialization && (improvement < minImprovement)) { - if (TRACE) System.out.println("improvement below " + minImprovement); + if (TRACE) { + System.out.println("improvement below " + minImprovement); + } if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit! // is performed for nm and cma, and if hc has too low sigma - if (TRACE) System.out.println("REINIT!!"); + if (TRACE) { + System.out.println("REINIT!!"); + } - if (localSearchMethod == PostProcessMethod.hillClimber) mutator.setSigma(initialStepSize); + if (localSearchMethod == PostProcessMethod.hillClimber) { + mutator.setSigma(initialStepSize); + } // store results archive.SetFunctionCalls(m_Population.getFunctionCalls()); @@ -218,9 +236,13 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { m_Population.incrFunctionCallsBy(tmpPop.size()); } else { // decrease step size for hc - if (localSearchMethod != PostProcessMethod.hillClimber) System.err.println("Invalid case in ClusteringHillClimbing!"); + if (localSearchMethod != PostProcessMethod.hillClimber) { + System.err.println("Invalid case in ClusteringHillClimbing!"); + } mutator.setSigma(mutator.getSigma()*reduceFactor); - if (TRACE) System.out.println("mutation stepsize reduced to " + mutator.getSigma()); + if (TRACE) { + System.out.println("mutation stepsize reduced to " + mutator.getSigma()); + } } } // System.out.println("funcalls: " + evalCnt); diff --git a/src/eva2/server/go/strategies/DifferentialEvolution.java b/src/eva2/server/go/strategies/DifferentialEvolution.java index 96b45ac1..805f92af 100644 --- a/src/eva2/server/go/strategies/DifferentialEvolution.java +++ b/src/eva2/server/go/strategies/DifferentialEvolution.java @@ -151,7 +151,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial AbstractEAIndividual x1Indy = getRandomIndy(pop); x1 = getGenotype(x1Indy); - if (parents != null) parents.add(x1Indy); + if (parents != null) { + parents.add(x1Indy); + } result = new double[x1.length]; isEmpty = true; @@ -166,15 +168,20 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } iterations++; } - if (!isEmpty && (parents != null)) parents.add(x2Indy); + if (!isEmpty && (parents != null)) { + parents.add(x2Indy); + } while (isEmpty) { // for n (popSize) iterations there were only zero vectors found // so now the hard way: construct a random vector for (int i = 0; i < x1.length; i++) { - if (RNG.flipCoin(1/(double)x1.length)) + if (RNG.flipCoin(1/(double)x1.length)) { result[i] = 0.01*RNG.gaussianDouble(0.1); - else result[i] = 0; + } + else { + result[i] = 0; + } isEmpty = (isEmpty && (result[i]==0)); } // single parent! dont add another one @@ -200,7 +207,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial x1 = indy.getDoubleData(); - if (parents != null) parents.add((AbstractEAIndividual)indy); + if (parents != null) { + parents.add((AbstractEAIndividual)indy); + } result = new double[x1.length]; isEmpty = true; @@ -215,15 +224,20 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } iterations++; } - if (!isEmpty && (parents != null)) parents.add(x2Indy); + if (!isEmpty && (parents != null)) { + parents.add(x2Indy); + } while (isEmpty) { // for n (popSize) iterations there were only zero vectors found // so now the hard way: construct a random vector for (int i = 0; i < x1.length; i++) { - if (RNG.flipCoin(1/(double)x1.length)) + if (RNG.flipCoin(1/(double)x1.length)) { result[i] = 0.01*RNG.gaussianDouble(0.1); - else result[i] = 0; + } + else { + result[i] = 0; + } isEmpty = (isEmpty && (result[i]==0)); } // single parent! dont add another one @@ -258,7 +272,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } double[] xb = getGenotype(xbIndy); - if (parents != null) parents.add(xbIndy); // given indy argument is already listed + if (parents != null) { + parents.add(xbIndy); + } // given indy argument is already listed for (int i = 0; i < x1.length; i++) { result[i] = xb[i] - x1[i]; @@ -295,11 +311,17 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial AbstractEAIndividual indy; InterfaceDataTypeDouble esIndy; - if (doLogParents) parents = new Vector(); - else parents = null; + if (doLogParents) { + parents = new Vector(); + } + else { + parents = null; + } try { // select one random indy as starting individual. its a parent in any case. - if (parentIndex<0) parentIndex = RNG.randomInt(0, pop.size()-1); + if (parentIndex<0) { + parentIndex = RNG.randomInt(0, pop.size()-1); + } indy = (AbstractEAIndividual)(pop.getEAIndividual(parentIndex)).getClone(); esIndy = (InterfaceDataTypeDouble)indy; } catch (java.lang.ClassCastException e) { @@ -314,7 +336,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial case DE1_Rand_1: { // this is DE1 or DE/rand/1 double[] delta = this.fetchDeltaRandom(pop); - if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly + if (parents != null) { + parents.add(pop.getEAIndividual(parentIndex)); + } // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { vX[i] = oX[i] + this.getCurrentF()*delta[i]; } @@ -324,7 +348,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // this is DE/current-to-rand/1 double[] rndDelta = this.fetchDeltaRandom(pop); double[] bestDelta = this.fetchDeltaCurrentRandom(pop, esIndy); - if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly + if (parents != null) { + parents.add(pop.getEAIndividual(parentIndex)); + } // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { vX[i] = oX[i] + this.getCurrentLambda() * bestDelta[i] + this.getCurrentF() * rndDelta[i]; } @@ -334,7 +360,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // this is DE2 or DE/current-to-best/1 double[] rndDelta = this.fetchDeltaRandom(pop); double[] bestDelta = this.fetchDeltaBest(pop, esIndy); - if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly + if (parents != null) { + parents.add(pop.getEAIndividual(parentIndex)); + } // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { vX[i] = oX[i] + this.getCurrentLambda() * bestDelta[i] + this.getCurrentF() * rndDelta[i]; } @@ -344,7 +372,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // DE/best/2 AbstractEAIndividual bestIndy = getBestIndy(pop); oX = getGenotype(bestIndy); - if (parents != null) parents.add(bestIndy); // Add best instead of preselected + if (parents != null) { + parents.add(bestIndy); + } // Add best instead of preselected double[] delta1 = this.fetchDeltaRandom(pop); double[] delta2 = this.fetchDeltaRandom(pop); for (int i = 0; i < oX.length; i++) { @@ -354,7 +384,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } case TrigonometricDE : { // this is trigonometric mutation - if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly + if (parents != null) { + parents.add(pop.getEAIndividual(parentIndex)); + } // Add wherever oX is used directly if (RNG.flipCoin(this.m_Mt)) { double[] xk, xl; double p, pj, pk, pl; @@ -382,7 +414,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } else { // this is DE1 double[] delta = this.fetchDeltaRandom(pop); - if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly + if (parents != null) { + parents.add(pop.getEAIndividual(parentIndex)); + } // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { vX[i] = oX[i] + this.getCurrentF()*delta[i]; } @@ -401,30 +435,46 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } } // setting the new genotype and fitness - if (forceRange) Mathematics.projectToRange(nX, esIndy.getDoubleRange()); // why did this never happen before? + if (forceRange) { + Mathematics.projectToRange(nX, esIndy.getDoubleRange()); + } // why did this never happen before? esIndy.SetDoubleGenotype(nX); indy.SetAge(0); indy.resetConstraintViolation(); double[] fit = new double[1]; fit[0] = 0; indy.setFitness(fit); - if (parents != null) indy.setParents(parents); + if (parents != null) { + indy.setParents(parents); + } return indy; } private double getCurrentK() { - if (randomizeFKLambda) return RNG.randomDouble(m_k*0.8, m_k * 1.2); - else return m_k; + if (randomizeFKLambda) { + return RNG.randomDouble(m_k*0.8, m_k * 1.2); + } + else { + return m_k; + } } private double getCurrentLambda() { - if (randomizeFKLambda) return RNG.randomDouble(m_Lambda*0.8, m_Lambda * 1.2); - else return m_Lambda; + if (randomizeFKLambda) { + return RNG.randomDouble(m_Lambda*0.8, m_Lambda * 1.2); + } + else { + return m_Lambda; + } } private double getCurrentF() { - if (randomizeFKLambda) return RNG.randomDouble(m_F*0.8, m_F * 1.2); - else return m_F; + if (randomizeFKLambda) { + return RNG.randomDouble(m_F*0.8, m_F * 1.2); + } + else { + return m_F; + } } private AbstractEAIndividual getBestIndy(Population pop) { @@ -452,8 +502,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial @Override public void optimize() { - if (generational) optimizeGenerational(); - else optimizeSteadyState(); + if (generational) { + optimizeGenerational(); + } + else { + optimizeSteadyState(); + } } /** @@ -468,11 +522,19 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial int parentIndex; // required for dynamic problems especially // m_Problem.evaluatePopulationStart(m_Population); - if (children==null) children = new Population(m_Population.size()); - else children.clear(); + if (children==null) { + children = new Population(m_Population.size()); + } + else { + children.clear(); + } for (int i = 0; i < this.m_Population.size(); i++) { - if (cyclePop) parentIndex=i; - else parentIndex=RNG.randomInt(0, this.m_Population.size()-1); + if (cyclePop) { + parentIndex=i; + } + else { + parentIndex=RNG.randomInt(0, this.m_Population.size()-1); + } AbstractEAIndividual indy = generateNewIndividual(m_Population, parentIndex); children.add(indy); } @@ -497,8 +559,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial int nextDoomed = getNextDoomed(m_Population, 0); for (int i = 0; i < this.m_Population.size(); i++) { AbstractEAIndividual indy = children.getEAIndividual(i); - if (cyclePop) parentIndex=i; - else parentIndex=RNG.randomInt(0, this.m_Population.size()-1); + if (cyclePop) { + parentIndex=i; + } + else { + parentIndex=RNG.randomInt(0, this.m_Population.size()-1); + } if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one m_Population.replaceIndividualAt(nextDoomed, indy); nextDoomed = getNextDoomed(m_Population, nextDoomed+1); @@ -508,9 +574,13 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial repl.insertIndividual(indy, m_Population, null); } else { // index = RNG.randomInt(0, this.m_Population.size()-1); - if (!compareToParent) parentIndex = RNG.randomInt(0, this.m_Population.size()-1); + if (!compareToParent) { + parentIndex = RNG.randomInt(0, this.m_Population.size()-1); + } AbstractEAIndividual orig = (AbstractEAIndividual)this.m_Population.get(parentIndex); - if (indy.isDominatingDebConstraints(orig)) this.m_Population.replaceIndividualAt(parentIndex, indy); + if (indy.isDominatingDebConstraints(orig)) { + this.m_Population.replaceIndividualAt(parentIndex, indy); + } } } } @@ -546,8 +616,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial for (int i = 0; i < this.m_Population.size(); i++) { - if (cyclePop) index=i; - else index=RNG.randomInt(0, this.m_Population.size()-1); + if (cyclePop) { + index=i; + } + else { + index=RNG.randomInt(0, this.m_Population.size()-1); + } indy = generateNewIndividual(m_Population, index); // if (cyclePop) indy = this.generateNewIndividual(this.m_Population, i); // else indy = this.generateNewIndividual(this.m_Population, -1); @@ -571,9 +645,13 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } else { // index = RNG.randomInt(0, this.m_Population.size()-1); - if (!compareToParent) index = RNG.randomInt(0, this.m_Population.size()-1); + if (!compareToParent) { + index = RNG.randomInt(0, this.m_Population.size()-1); + } orig = (AbstractEAIndividual)this.m_Population.get(index); - if (indy.isDominatingDebConstraints(orig)) this.m_Population.replaceIndividualAt(index, indy); + if (indy.isDominatingDebConstraints(orig)) { + this.m_Population.replaceIndividualAt(index, indy); + } } } } @@ -632,7 +710,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial protected int getNextDoomed(Population pop, int startIndex) { if (maximumAge > 0) { for (int i=startIndex; i= maximumAge) return i; + if (((AbstractEAIndividual)pop.get(i)).getAge() >= maximumAge) { + return i; + } } } return -1; @@ -654,7 +734,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial if (m_Listener!=null&&m_Listener.removeElement(ea)) { return true; - } else return false; + } else { + return false; + } } /** Something has changed * @param name @@ -768,8 +850,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial * @param k */ public void setK(double k) { - if (k < 0) k = 0; - if (k > 1) k = 1; + if (k < 0) { + k = 0; + } + if (k > 1) { + k = 1; + } this.m_k = k; } public double getK() { @@ -797,8 +883,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial */ public void setMt (double l) { this.m_Mt = l; - if (this.m_Mt < 0) this.m_Mt = 0; - if (this.m_Mt > 1) this.m_Mt = 1; + if (this.m_Mt < 0) { + this.m_Mt = 0; + } + if (this.m_Mt > 1) { + this.m_Mt = 1; + } } public double getMt() { return this.m_Mt; diff --git a/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java b/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java index 90e4f24e..79a44202 100644 --- a/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java +++ b/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java @@ -111,8 +111,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization 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)); + if (normEmaSpd > (upperChgLim*spdLim)) { + setSpeedLimit(Math.min(maxSpeedLimit, incFact * spdLim)); + } + else if (normEmaSpd < (lowerChgLim*spdLim)) { + setSpeedLimit(Math.max(minSpeedLimit, decFact*spdLim)); + } } /** @@ -155,8 +159,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization Mathematics.projectToRange(newPos, range); } - if (indy instanceof InterfaceDataTypeDouble) ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(newPos); - else endy.SetDoubleGenotype(newPos); + if (indy instanceof InterfaceDataTypeDouble) { + ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(newPos); + } + else { + endy.SetDoubleGenotype(newPos); + } resetFitness(indy); @@ -172,7 +180,9 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization if (m_Plot != null) { double[] curPosition = ((InterfaceDataTypeDouble)m_Population.getBestEAIndividual()).getDoubleData(); - if (lastBestPlot != null) this.m_Plot.setConnectedPoint(lastBestPlot[0], lastBestPlot[1], 0); + if (lastBestPlot != null) { + this.m_Plot.setConnectedPoint(lastBestPlot[0], lastBestPlot[1], 0); + } this.m_Plot.setConnectedPoint(curPosition[0], curPosition[1], 0); lastBestPlot = curPosition.clone(); } @@ -182,7 +192,9 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization protected void plotIndy(double[] curPosition, double[] curVelocity, int index) { if (this.m_Show) { if (plotBestOnly) { - if (index != ((Integer)(m_Population.getBestEAIndividual().getData(indexKey)))) return; + 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); @@ -304,8 +316,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization for (int i = 0; i < lastVelocity.length; i++) { // the component from the old velocity curVelocity[i] = this.m_InertnessOrChi * lastVelocity[i]; - if (algType.getSelectedTag().getID()==1) chi=m_InertnessOrChi; - else chi = 1.; + if (algType.getSelectedTag().getID()==1) { + chi=m_InertnessOrChi; + } + else { + chi = 1.; + } // random perturbation //curVelocity[i] += (this.phi0 * chi * RNG.randomDouble(-1., 1.) * (range[i][1] - range[i][0])); curVelocity[i] += (this.phi0 * chi * getSpeedLimit(index) * RNG.randomDouble(-1., 1.) * (range[i][1] - range[i][0])); @@ -315,7 +331,9 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization curVelocity[i] += (getIndySocialModifier(index, chi) * (localBestPos[i]-curPosition[i])); } return curVelocity; - } else return super.updateVelocity(index, lastVelocity, bestPosition, curPosition, localBestPos, range); + } else { + return super.updateVelocity(index, lastVelocity, bestPosition, curPosition, localBestPos, range); + } } protected double getProblemSpecificAttraction(int i, double chi) { @@ -350,10 +368,16 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization */ @Override protected double getSpeedLimit(int index) { - if (index >= ((double)(m_Population.size() * highEnergyRatio))) return m_SpeedLimit; + if (index >= ((double)(m_Population.size() * highEnergyRatio))) { + return m_SpeedLimit; + } else { - if (highEnergyRaise == 0.) return maxSpeedLimit; - else return m_SpeedLimit * highEnergyRaise; + if (highEnergyRaise == 0.) { + return maxSpeedLimit; + } + else { + return m_SpeedLimit * highEnergyRaise; + } } } @@ -363,8 +387,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization 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 System.arraycopy(m_Population.getIndividual(detectAnchor).getFitness(), 0, detectFit, 0, detectFit.length); + if (detectFit == null) { + detectFit = (m_Population.getIndividual(detectAnchor).getFitness()).clone(); + } + else { + System.arraycopy(m_Population.getIndividual(detectAnchor).getFitness(), 0, detectFit, 0, detectFit.length); + } } } @@ -424,7 +452,9 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization protected void evaluatePopulation(Population population) { envHasChanged = false; super.evaluatePopulation(population); - if (m_Show && plotBestOnly) plotBestIndy(); + if (m_Show && plotBestOnly) { + plotBestIndy(); + } envHasChanged = detectChange(m_Population); @@ -469,7 +499,9 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization 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())); + if (detectAnchor >= 0) { + return !(java.util.Arrays.equals(detectFit, m_Population.getIndividual(detectAnchor).getFitness())); + } else { System.err.println("warning, inconsistency in detectChange"); } @@ -486,14 +518,18 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization @Override public void setPopulation(Population pop) { super.setPopulation(pop); - if (detectAnchor>=pop.size()) detectAnchor=0; + if (detectAnchor>=pop.size()) { + detectAnchor=0; + } } @Override public void init() { super.init(); setEmaPeriods(15); - if (doSpeedAdaptation) setSpeedLimit(2*getInitialVelocity()); + if (doSpeedAdaptation) { + setSpeedLimit(2*getInitialVelocity()); + } } @@ -563,8 +599,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization **/ public void setQuantumRatio(double quantumRatio) { this.quantumRatio = quantumRatio; - if (quantumRatio == 0.) GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", true); - else GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", false); + if (quantumRatio == 0.) { + GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", true); + } + else { + GenericObjectEditor.setHideProperty(this.getClass(), "quantumCloudDia", false); + } } /** @@ -593,8 +633,12 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization **/ public void setHighEnergyRatio(double highEnergyRatio) { this.highEnergyRatio = highEnergyRatio; - if (highEnergyRatio == 0.) GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", true); - else GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", false); + if (highEnergyRatio == 0.) { + GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", true); + } + else { + GenericObjectEditor.setHideProperty(this.getClass(), "highEnergyRaise", false); + } } /** @@ -660,7 +704,9 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization this.changeDetectStrategy = changeDetectStrategy; if (changeDetectStrategy.getSelectedTag().getID() == 0) { // random anchor detectAnchor = 0; // this will be set to a random individual - } else detectAnchor = -1; + } else { + detectAnchor = -1; + } } public String phi0TipText() { diff --git a/src/eva2/server/go/strategies/EvolutionStrategyIPOP.java b/src/eva2/server/go/strategies/EvolutionStrategyIPOP.java index 07614f96..da1fd5ac 100644 --- a/src/eva2/server/go/strategies/EvolutionStrategyIPOP.java +++ b/src/eva2/server/go/strategies/EvolutionStrategyIPOP.java @@ -71,7 +71,9 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf 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 @@ -205,16 +207,24 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf // 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; + 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; + 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; + if (!ret && (rcmaMute.testCCondition(pop, 10e14))) { + ret = true; + } // System.out.println("ret is " + ret); } } @@ -231,9 +241,15 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf @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()); + 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; @@ -309,7 +325,9 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf */ public void setStagThreshold(double stagThreshold) { this.stagThreshold = stagThreshold; - if (fitConvTerm != null) fitConvTerm.setConvergenceThreshold(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."; @@ -327,7 +345,9 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf public void setStagnationGenerations(int stagTime) { this.stagTimeArbitrary = stagTime; if (isStagnationTimeUserDef()) { - if (fitConvTerm != null) fitConvTerm.setStagnationTime(stagTime); + if (fitConvTerm != null) { + fitConvTerm.setStagnationTime(stagTime); + } } } public String stagnationGenerationsTipText() { @@ -347,8 +367,12 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf this.useArbitraryStagTime = useArbitraryStagTime; GenericObjectEditor.setShowProperty(this.getClass(), "stagnationGenerations", useArbitraryStagTime); if (fitConvTerm != null) { - if (useArbitraryStagTime) fitConvTerm.setStagnationTime(getStagnationGenerations()); - else fitConvTerm.setStagnationTime(calcDefaultStagnationTime()); + if (useArbitraryStagTime) { + fitConvTerm.setStagnationTime(getStagnationGenerations()); + } + else { + fitConvTerm.setStagnationTime(calcDefaultStagnationTime()); + } } } public String stagnationTimeUserDefTipText() { @@ -356,7 +380,9 @@ public class EvolutionStrategyIPOP extends EvolutionStrategies implements Interf } private double getMeanArchivedDist() { - if (bestList==null) return 0.; + if (bestList==null) { + return 0.; + } else { Population tmpPop=new Population(bestList.size()); tmpPop.addAll(bestList); diff --git a/src/eva2/server/go/strategies/EvolutionaryProgramming.java b/src/eva2/server/go/strategies/EvolutionaryProgramming.java index a69d94e4..295f56ef 100644 --- a/src/eva2/server/go/strategies/EvolutionaryProgramming.java +++ b/src/eva2/server/go/strategies/EvolutionaryProgramming.java @@ -126,12 +126,16 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized diff --git a/src/eva2/server/go/strategies/FloodAlgorithm.java b/src/eva2/server/go/strategies/FloodAlgorithm.java index 84b0dfbf..f633c1ea 100644 --- a/src/eva2/server/go/strategies/FloodAlgorithm.java +++ b/src/eva2/server/go/strategies/FloodAlgorithm.java @@ -147,9 +147,13 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable for (int i = 0; i < m_FitnessCalls; i++) { this.m_Test = (GAIndividualBinaryData)((this.m_Best).clone()); this.m_Test.defaultMutate(); - if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) this.m_Best = this.m_Test; + if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { + this.m_Best = this.m_Test; + } this.m_FitnessCallsNeeded = i; - if (this.m_Best.defaultEvaulateAsMiniBits() == 0) i = this.m_FitnessCalls +1; + if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { + i = this.m_FitnessCalls +1; + } } } @@ -184,12 +188,16 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will return a string describing all properties of the optimizer @@ -199,8 +207,12 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable @Override public String getStringRepresentation() { String result = ""; - if (this.m_Population.size() > 1) result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; - else result += "Simulated Annealing:\n"; + if (this.m_Population.size() > 1) { + result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; + } + else { + result += "Simulated Annealing:\n"; + } result += "Optimization Problem: "; result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Population.getStringRepresentation(); @@ -287,7 +299,9 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable } public void setDrainRate(double a){ this.m_DrainRate = a; - if (this.m_DrainRate < 0) this.m_DrainRate = 0.0; + if (this.m_DrainRate < 0) { + this.m_DrainRate = 0.0; + } } public String drainRateTipText() { return "Set the drain rate that reduces the current flood level each generation."; diff --git a/src/eva2/server/go/strategies/GradientDescentAlgorithm.java b/src/eva2/server/go/strategies/GradientDescentAlgorithm.java index 34e50469..209d9b19 100644 --- a/src/eva2/server/go/strategies/GradientDescentAlgorithm.java +++ b/src/eva2/server/go/strategies/GradientDescentAlgorithm.java @@ -169,7 +169,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser double[] oldchange = null; double[] gradient = ((InterfaceFirstOrderDerivableProblem) m_Problem).getFirstOrderGradients(params); - if (TRACE) System.out.println("GDA: " + BeanInspector.toString(params) + ", grad: " + BeanInspector.toString(gradient)); + if (TRACE) { + System.out.println("GDA: " + BeanInspector.toString(params) + ", grad: " + BeanInspector.toString(gradient)); + } if ((oldgradient != null) && (wstepsize != null)) { // LOCAL adaption for (int li = 0; li < wstepsize.length; li++) { double prod = gradient[li] * oldgradient[li]; @@ -196,16 +198,26 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser for (int j = 0; j < newparams.length; j++) { if (lock[j] == 0) { double tempstepsize = 1; - if (this.localStepSizeAdaption) tempstepsize *= wstepsize[j]; - if (this.globalStepSizeAdaption) tempstepsize *= indystepsize; + if (this.localStepSizeAdaption) { + tempstepsize *= wstepsize[j]; + } + if (this.globalStepSizeAdaption) { + tempstepsize *= indystepsize; + } double wchange = signum(tempstepsize * gradient[j]) * Math.min(maximumabsolutechange,Math.abs(tempstepsize * gradient[j])); //indystepsize * gradient[j]; - if (this.manhattan) wchange = this.signum(wchange) * tempstepsize; + if (this.manhattan) { + wchange = this.signum(wchange) * tempstepsize; + } if (dograddesc) { wchange += this.momentumweigth * oldchange[j]; } newparams[j] = params[j] - wchange; - if (newparams[j] < range[j][0]) newparams[j] = range[j][0]; - if (newparams[j] > range[j][1]) newparams[j] = range[j][1]; + if (newparams[j] < range[j][0]) { + newparams[j] = range[j][0]; + } + if (newparams[j] > range[j][1]) { + newparams[j] = range[j][1]; + } // for (int g = 0; g < newparams.length; g++) { // System.out.println("Param " + g +": " + newparams[g]); // } @@ -244,7 +256,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser indy = ((AbstractEAIndividual)this.m_Population.get(i)); // Hashtable history = (Hashtable) indyhash.get(indy); if (indy.getFitness()[0] > recoverythreshold) { - if (TRACE) System.out.println("Gradient Descent: Fitness critical:" + indy.getFitness()[0]); + if (TRACE) { + System.out.println("Gradient Descent: Fitness critical:" + indy.getFitness()[0]); + } ((InterfaceDataTypeDouble) indy).SetDoublePhenotype((double[]) indy.getData(oldParamsKey)); double[] changes = (double[]) indy.getData(changesKey); int[] lock = (int[]) indy.getData(lockKey); @@ -301,7 +315,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser private double momentumweigth = 0.1; protected void firePropertyChangedEvent(String name) { - if (this.m_Listener != null)this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } @Override @@ -364,7 +380,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } public static void main(String[] args) { GradientDescentAlgorithm program = new GradientDescentAlgorithm(); @@ -393,7 +411,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser } public void setAdaptStepSizeGlobally(boolean globalstepsizeadaption) { this.globalStepSizeAdaption = globalstepsizeadaption; - if (globalstepsizeadaption && localStepSizeAdaption) setAdaptStepSizeLocally(false); + if (globalstepsizeadaption && localStepSizeAdaption) { + setAdaptStepSizeLocally(false); + } } public String adaptStepSizeGloballyTipText() { return "Use a single step size per individual - (priority over local step size)."; @@ -435,7 +455,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser } public void setAdaptStepSizeLocally(boolean stepsizeadaption) { this.localStepSizeAdaption = stepsizeadaption; - if (globalStepSizeAdaption && localStepSizeAdaption) setAdaptStepSizeGlobally(false); + if (globalStepSizeAdaption && localStepSizeAdaption) { + setAdaptStepSizeGlobally(false); + } } public String adaptStepSizeLocallyTipText() { return "Use a step size parameter in any dimension."; diff --git a/src/eva2/server/go/strategies/HillClimbing.java b/src/eva2/server/go/strategies/HillClimbing.java index 6f5de1d9..69d5cef4 100644 --- a/src/eva2/server/go/strategies/HillClimbing.java +++ b/src/eva2/server/go/strategies/HillClimbing.java @@ -82,8 +82,12 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { indy = ((AbstractEAIndividual) this.m_Population.get(i)); tmpD = indy.getMutationProbability(); indy.setMutationProbability(1.0); - if (mutator == null) indy.mutate(); - else mutator.mutate(indy); + if (mutator == null) { + indy.mutate(); + } + else { + mutator.mutate(indy); + } indy.setMutationProbability(tmpD); } this.m_Problem.evaluate(this.m_Population); @@ -191,12 +195,16 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will return a string describing all properties of the optimizer @@ -206,8 +214,12 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { @Override public String getStringRepresentation() { String result = ""; - if (this.m_Population.size() > 1) result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; - else result += "Hill Climbing:\n"; + if (this.m_Population.size() > 1) { + result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; + } + else { + result += "Hill Climbing:\n"; + } result += "Optimization Problem: "; result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Population.getStringRepresentation(); diff --git a/src/eva2/server/go/strategies/InterfaceOptimizer.java b/src/eva2/server/go/strategies/InterfaceOptimizer.java index 5265f5a2..1939eb23 100644 --- a/src/eva2/server/go/strategies/InterfaceOptimizer.java +++ b/src/eva2/server/go/strategies/InterfaceOptimizer.java @@ -83,7 +83,6 @@ public interface InterfaceOptimizer { /** * This method allows you to set an identifier for the algorithm * @param name The identifier - * @deprecated */ public void setIdentifier(String name); public String getIdentifier(); diff --git a/src/eva2/server/go/strategies/IslandModelEA.java b/src/eva2/server/go/strategies/IslandModelEA.java index 0509b013..3fba9f22 100644 --- a/src/eva2/server/go/strategies/IslandModelEA.java +++ b/src/eva2/server/go/strategies/IslandModelEA.java @@ -113,12 +113,15 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I this.m_Islands[i] = (InterfaceOptimizer) this.m_Optimizer.clone(); this.m_Islands[i].setIdentifier(""+i); this.m_Islands[i].init(); - if (this.m_LogLocalChanges) + if (this.m_LogLocalChanges) { this.m_Islands[i].addPopulationChangedEventListener(this); + } } } else { // this is running on remote machines - if (this.m_LocalServer == null) this.m_LocalServer = RMIServer.getInstance(); + if (this.m_LocalServer == null) { + this.m_LocalServer = RMIServer.getInstance(); + } try { myLocal = (InterfacePopulationChangedEventListener) RMIProxyLocal.newInstance(this); } catch(Exception e) { @@ -133,8 +136,9 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I this.m_Islands[i] = (InterfaceOptimizer) RMIProxyRemoteThread.newInstance(this.m_Optimizer, nodesList[i]); this.m_Islands[i].setIdentifier(""+i); this.m_Islands[i].init(); - if (this.m_LogLocalChanges) + if (this.m_LogLocalChanges) { this.m_Islands[i].addPopulationChangedEventListener(myLocal); + } } } @@ -183,26 +187,32 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I this.m_Islands[i] = (InterfaceOptimizer) this.m_Optimizer.clone(); this.m_Islands[i].setIdentifier(""+i); this.m_Islands[i].init(); - if (this.m_LogLocalChanges) + if (this.m_LogLocalChanges) { this.m_Islands[i].addPopulationChangedEventListener(this); + } } } else { // this is running on remote machines - if (this.m_LocalServer == null) this.m_LocalServer = RMIServer.getInstance(); + if (this.m_LocalServer == null) { + this.m_LocalServer = RMIServer.getInstance(); + } try { myLocal = (InterfacePopulationChangedEventListener) RMIProxyLocal.newInstance(this); } catch(Exception e) { System.err.println("Island Model EA warning on local RMIServer... but i'll try to start anyway!"); } String[] nodesList = this.m_Servers.getCheckedServerNodes(); - if ((nodesList == null) || (nodesList.length == 0)) return; + if ((nodesList == null) || (nodesList.length == 0)) { + return; + } this.m_Islands = new InterfaceOptimizer[nodesList.length]; for (int i = 0; i < nodesList.length; i++) { this.m_Islands[i] = (InterfaceOptimizer) RMIProxyRemoteThread.newInstance(this.m_Optimizer, nodesList[i]); this.m_Islands[i].setIdentifier(""+i); this.m_Islands[i].init(); - if (this.m_LogLocalChanges) + if (this.m_LogLocalChanges) { this.m_Islands[i].addPopulationChangedEventListener(myLocal); + } } } @@ -223,9 +233,15 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I for (int i = 0; i < this.m_Islands.length; i++) { if (this.m_Islands[i].getPopulation().size() > 0) { this.m_Islands[i].optimize(); - if (TRACE ) System.out.println(BeanInspector.toString(m_Islands[i].getPopulation())); - } else this.m_Islands[i].getPopulation().incrGeneration(); - if (TRACE) System.out.println("----"); + if (TRACE ) { + System.out.println(BeanInspector.toString(m_Islands[i].getPopulation())); + } + } else { + this.m_Islands[i].getPopulation().incrGeneration(); + } + if (TRACE) { + System.out.println("----"); + } } this.m_Population.incrGeneration(); if ((this.m_Population.getGeneration() % this.m_MigrationRate) == 0) { @@ -252,7 +268,9 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I String gen = "["; for (int i = 0; i < this.m_Islands.length; i++) { gen += this.m_Islands[i].getPopulation().getGeneration()+"; "; - if (this.m_Islands[i].getPopulation().getGeneration() != G) allReachedG = false; + if (this.m_Islands[i].getPopulation().getGeneration() != G) { + allReachedG = false; + } } if (!allReachedG) { System.out.println("Waiting...."+gen+"] ?= " + G); @@ -274,7 +292,9 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I // System.out.println("Fitnesscalls :" + this.m_Population.getFunctionCalls()); this.firePropertyChangedEvent(Population.nextGenerationPerformed, this.m_Optimizer.getPopulation()); double plotValue = (this.m_Problem.getDoublePlotValue(this.m_Population)).doubleValue(); - if (this.m_Show) this.m_Plot.setConnectedPoint(this.m_Population.getFunctionCalls(), plotValue, 0); + if (this.m_Show) { + this.m_Plot.setConnectedPoint(this.m_Population.getFunctionCalls(), plotValue, 0); + } // now they are synchronized this.m_Migration.migrate(this.m_Islands); } @@ -292,12 +312,16 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name, Population population) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized @@ -447,7 +471,9 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I double cFCOpt = opt.getPopulation().getFunctionCalls(); double plotValue = (this.m_Problem.getDoublePlotValue(opt.getPopulation())).doubleValue(); - if (this.m_Show) this.m_Plot.setConnectedPoint(cFCOpt, plotValue, (sourceID+1)); + if (this.m_Show) { + this.m_Plot.setConnectedPoint(cFCOpt, plotValue, (sourceID+1)); + } //System.out.println("Someone has finished, ("+this.m_Generation+"/"+this.m_Performed+")"); //System.out.println(sourceID + " is at generation "+ opt.getPopulation().getGeneration() +" i'm at " +this.m_Generation); @@ -578,8 +604,12 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I * @param n Number of processors. */ public void setNumberLocalCPUs(int n) { - if (n>=1) this.m_numLocalCPUs = n; - else System.err.println("Number of CPUs must be at least 1!"); + if (n>=1) { + this.m_numLocalCPUs = n; + } + else { + System.err.println("Number of CPUs must be at least 1!"); + } } // TODO Deactivated from GUI because the current implementation does not really parallelize on a multicore. // Instead, the new direct problem parallelization can be used. diff --git a/src/eva2/server/go/strategies/MemeticAlgorithm.java b/src/eva2/server/go/strategies/MemeticAlgorithm.java index 0d22e57b..74c87787 100644 --- a/src/eva2/server/go/strategies/MemeticAlgorithm.java +++ b/src/eva2/server/go/strategies/MemeticAlgorithm.java @@ -119,24 +119,28 @@ public class MemeticAlgorithm implements InterfaceOptimizer, @Override public void optimize() { - if (TRACE) System.out.println("global search"); + if (TRACE) { + System.out.println("global search"); + } this.m_GlobalOptimizer.optimize(); if ((globalSearchIterations>0) && (((this.m_GlobalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0)) && (this.localSearchSteps > 0) && (this.m_Problem instanceof InterfaceLocalSearchable)) { // here the local search is performed - if (TRACE) - System.out.println("Performing local search on " + subsetsize - + " individuals."); + if (TRACE) { + System.out.println("Performing local search on " + subsetsize + + " individuals."); + } Population gop = this.m_GlobalOptimizer.getPopulation(); Population subset = selectorPlug.selectFrom(gop, subsetsize); Population subsetclone = new Population(); for (int i = 0; i < subset.size(); i++) { subsetclone.add(((AbstractEAIndividual) subset.get(i)).clone()); } - if (subset.size() != subsetsize) - System.err.println("ALERT! identical individual instances in subset"); + if (subset.size() != subsetsize) { + System.err.println("ALERT! identical individual instances in subset"); + } Hashtable antilamarckismcache = new Hashtable(); if (!this.lamarckism) { for (int i = 0; i < subset.size(); i++) { @@ -184,15 +188,17 @@ public class MemeticAlgorithm implements InterfaceOptimizer, gop.SetFunctionCalls(gop.getFunctionCalls() + (int) Math.round(localSearchSteps * cost * subset.size())); - if (TRACE) - System.out.println("Population size after local search:" + gop.size()); + if (TRACE) { + System.out.println("Population size after local search:" + gop.size()); + } this.setPopulation(gop); } - if (TRACE) - System.out.println("function calls" - + this.m_GlobalOptimizer.getPopulation().getFunctionCalls()); + if (TRACE) { + System.out.println("function calls" + + this.m_GlobalOptimizer.getPopulation().getFunctionCalls()); + } this.firePropertyChangedEvent(Population.nextGenerationPerformed); } @@ -212,14 +218,18 @@ public class MemeticAlgorithm implements InterfaceOptimizer, if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** * Something has changed */ protected void firePropertyChangedEvent(String name) { if (this.m_Listener != null) { - if (TRACE) System.out.println("firePropertyChangedEvent MA"); + if (TRACE) { + System.out.println("firePropertyChangedEvent MA"); + } this.m_Listener.registerPopulationStateChanged(this, name); } } diff --git a/src/eva2/server/go/strategies/MonteCarloSearch.java b/src/eva2/server/go/strategies/MonteCarloSearch.java index 9a3c2bbf..9b4a3327 100644 --- a/src/eva2/server/go/strategies/MonteCarloSearch.java +++ b/src/eva2/server/go/strategies/MonteCarloSearch.java @@ -130,9 +130,13 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl for (int i = 0; i < m_FitnessCalls; i++) { this.m_Test = new GAIndividualBinaryData(); this.m_Test.defaultInit(m_Problem); - if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) this.m_Best = this.m_Test; + if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { + this.m_Best = this.m_Test; + } this.m_FitnessCallsNeeded = i; - if (this.m_Best.defaultEvaulateAsMiniBits() == 0) i = this.m_FitnessCalls +1; + if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { + i = this.m_FitnessCalls +1; + } } } @@ -167,12 +171,16 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will return a string describing all properties of the optimizer diff --git a/src/eva2/server/go/strategies/MultiObjectiveCMAES.java b/src/eva2/server/go/strategies/MultiObjectiveCMAES.java index d5df1752..b854c798 100644 --- a/src/eva2/server/go/strategies/MultiObjectiveCMAES.java +++ b/src/eva2/server/go/strategies/MultiObjectiveCMAES.java @@ -399,8 +399,9 @@ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable { * @param name */ protected void firePropertyChangedEvent(String name) { - if (this.m_Listener != null) - this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } public int getLambda() { diff --git a/src/eva2/server/go/strategies/MultiObjectiveEA.java b/src/eva2/server/go/strategies/MultiObjectiveEA.java index bced3ba9..6d4fcd3b 100644 --- a/src/eva2/server/go/strategies/MultiObjectiveEA.java +++ b/src/eva2/server/go/strategies/MultiObjectiveEA.java @@ -138,7 +138,9 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl private double[][] showMay(Population pop) { Population tmp = new Population(); tmp.addPopulation(pop); - if (pop.getArchive() != null) tmp.addPopulation(pop.getArchive()); + if (pop.getArchive() != null) { + tmp.addPopulation(pop.getArchive()); + } double[][] fitness = new double[tmp.size()][]; for (int i = 0; i < tmp.size(); i++) { @@ -148,8 +150,12 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl minY = fitness[0]; maxY = fitness[0]; for (int i = 1; i < fitness.length; i++) { - if (minY[0] > fitness[i][0]) minY = fitness[i]; - if (maxY[1] > fitness[i][1]) maxY = fitness[i]; + if (minY[0] > fitness[i][0]) { + minY = fitness[i]; + } + if (maxY[1] > fitness[i][1]) { + maxY = fitness[i]; + } } double[][] result = new double[2][]; result[0] = minY; @@ -169,11 +175,15 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized diff --git a/src/eva2/server/go/strategies/NelderMeadSimplex.java b/src/eva2/server/go/strategies/NelderMeadSimplex.java index 52beb40c..b3ad3b16 100644 --- a/src/eva2/server/go/strategies/NelderMeadSimplex.java +++ b/src/eva2/server/go/strategies/NelderMeadSimplex.java @@ -87,16 +87,24 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte public void addPopulationChangedEventListener( InterfacePopulationChangedEventListener ea) { if (ea!=null) { - if (m_Listener == null) m_Listener = new Vector(); - if (!m_Listener.contains(ea)) m_Listener.add(ea); + if (m_Listener == null) { + m_Listener = new Vector(); + } + if (!m_Listener.contains(ea)) { + m_Listener.add(ea); + } } } @Override public boolean removePopulationChangedEventListener( InterfacePopulationChangedEventListener ea) { - if (m_Listener==null) return false; - else return m_Listener.remove(ea); + if (m_Listener==null) { + return false; + } + else { + return m_Listener.remove(ea); + } } @Override @@ -174,7 +182,9 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte for (int i=0; i= 1. || (perturbRelative <= 0.)) { System.err.println("Warning: perturbation ratio should lie between 0 and 1! (NelderMeadSimplex:createNMSPopulation)"); } @@ -453,7 +475,9 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte double[] dat = ((InterfaceDataTypeDouble)indy).getDoubleData(); if (dat[i]==range[i][1]) { // in this case the bound is said to be too close dat[i]=Math.max(dat[i]-curPerturb, range[i][0]); - } else dat[i] = Math.min(dat[i]+curPerturb, range[i][1]); + } else { + dat[i] = Math.min(dat[i]+curPerturb, range[i][1]); + } ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(dat); indy.resetConstraintViolation(); initialPop.add((AbstractEAIndividual)indy.clone()); diff --git a/src/eva2/server/go/strategies/NicheGraph.java b/src/eva2/server/go/strategies/NicheGraph.java index 0bf9b559..b787f4c4 100644 --- a/src/eva2/server/go/strategies/NicheGraph.java +++ b/src/eva2/server/go/strategies/NicheGraph.java @@ -50,7 +50,9 @@ public class NicheGraph implements java.io.Serializable { * @param v */ public void addVertex(String v){ - if (!containsVertex(v)) graphTable.put(v, new TreeSet()); + if (!containsVertex(v)) { + graphTable.put(v, new TreeSet()); + } } /** @@ -59,8 +61,12 @@ public class NicheGraph implements java.io.Serializable { * @param v2 */ public void addEdge(String v1, String v2){ - if (!containsVertex(v1)) addVertex(v1); - if (!containsVertex(v2)) addVertex(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); @@ -123,7 +129,9 @@ public class NicheGraph implements java.io.Serializable { private boolean isComponent(String v, ArrayList> l) { for (Set set : l){ - if (set.contains(v)) return true; + if (set.contains(v)) { + return true; + } } return false; } diff --git a/src/eva2/server/go/strategies/NichePSO.java b/src/eva2/server/go/strategies/NichePSO.java index 664bc668..97768320 100644 --- a/src/eva2/server/go/strategies/NichePSO.java +++ b/src/eva2/server/go/strategies/NichePSO.java @@ -181,7 +181,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * */ public NichePSO(){ - if (log) initLogFile(); + if (log) { + initLogFile(); + } initMainSwarm(); // not really necessary if init is called before optimization but this way init doesnt change the parameters of a newly constructed object initSubswarmOptimizerTemplate(); @@ -338,7 +340,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac indicesToReinit=null; // show in plot //MainSwarm.setShow(true); - if (isPlot()) initPlotSwarm(); + if (isPlot()) { + initPlotSwarm(); + } } /** @tested @@ -372,20 +376,26 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } // main swarm: if (getMainSwarm().getPopulation().size() == 0){// || mainSwarm.getPopulation().size() == 1){ - if (isVerbose()) System.out.print("MainSwarm size is 0\n"); + if (isVerbose()) { + System.out.print("MainSwarm size is 0\n"); + } // increment the generationcount for the terminator: // 1 generation equals one optimize call including the optimization of the // (possibly empty) mainswarm and all subswarms getMainSwarm().getPopulation().incrGeneration(); } - else getMainSwarm().optimize(); + else { + getMainSwarm().optimize(); + } maybeReinitIndies(); // subswarms: for (int i = 0; i < getSubSwarms().size(); ++i) { ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); - if (subswarm.isActive()) subswarm.optimize(); + if (subswarm.isActive()) { + subswarm.optimize(); + } // System.out.println(i + " " + subswarm.getPopulation().getFunctionCalls()); } @@ -452,7 +462,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac */ public void scheduleNewParticlesToPopulation(int[] particleIndices) { if (particleIndices != null) { - if (indicesToReinit==null) indicesToReinit = new Vector(); + if (indicesToReinit==null) { + indicesToReinit = new Vector(); + } indicesToReinit.add(particleIndices); } } @@ -500,7 +512,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Deactivation */ protected void deactivationEventFor(ParticleSubSwarmOptimization subswarm) { - if (isVerbose()) System.out.println("deactivating subswarm"); + if (isVerbose()) { + System.out.println("deactivating subswarm"); + } deactivatedSwarm.add(subswarm); // only for plotting deactivationOccured = true; } @@ -514,7 +528,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac ParticleSubSwarmOptimization currentsubswarm = getSubSwarms().get(i); //.. if it meets the criterion of the deactivation strategy if (getDeactivationStrategy().shouldDeactivateSubswarm(currentsubswarm)){ - if (isVerbose()) System.out.println("deactivation in NPSO!"); + if (isVerbose()) { + System.out.println("deactivation in NPSO!"); + } deactivationEventFor(currentsubswarm); scheduleNewParticlesToPopulation(getDeactivationStrategy().deactivateSubswarm(currentsubswarm, getMainSwarm())); } @@ -532,8 +548,12 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac avgSize+=currentsubswarm.m_Population.size(); } } - if (actCnt>0) return (avgSize/actCnt); - else return 0; + if (actCnt>0) { + return (avgSize/actCnt); + } + else { + return 0; + } } protected int countActiveSubswarms(){ @@ -541,7 +561,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac // check for every subswarm... for (int i = 0; i < getSubSwarms().size(); ++i){ ParticleSubSwarmOptimization currentsubswarm = getSubSwarms().get(i); - if (currentsubswarm.isActive()) actCnt++; + if (currentsubswarm.isActive()) { + actCnt++; + } } return actCnt; } @@ -549,7 +571,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Merging */ protected void mergingEventFor(int i, int j){ - if (isVerbose()) System.out.print("merge condition \n"); + if (isVerbose()) { + System.out.print("merge condition \n"); + } ParticleSubSwarmOptimization borg = getSubSwarms().get(i); ParticleSubSwarmOptimization others= getSubSwarms().get(j); this.borg.add((ParticleSubSwarmOptimization)borg.clone()); // for plotting only @@ -564,14 +588,18 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac */ protected void mergeSubswarmsIfPossible(){ boolean runagain = false; - if (isVerbose()) System.out.println("possibly merging " + getSubSwarms().size() + " subswarms..."); + if (isVerbose()) { + System.out.println("possibly merging " + getSubSwarms().size() + " subswarms..."); + } // check for every two subswarms... for (int i = 0; i < getSubSwarms().size(); ++i){ // System.out.print(" " + getSubSwarms().get(i).getPopulation().size()); for (int j = i+1; j < getSubSwarms().size(); ++j){ //... if they should be merged according to the merging strategy if (getMergingStrategy().shouldMergeSubswarms(getSubSwarms().get(i), getSubSwarms().get(j))){ - if (isVerbose()) System.out.println("Merging in NPSO!"); + if (isVerbose()) { + System.out.println("Merging in NPSO!"); + } mergingEventFor(i,j); // for plotting getMergingStrategy().mergeSubswarms(i, j, getSubSwarms(), getMainSwarm()); runagain = true; // merged subswarm may overlap with another swarm now. This might not have been considered in this run... @@ -580,7 +608,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } } // System.out.println(); - if (runagain) mergeSubswarmsIfPossible(); + if (runagain) { + mergeSubswarmsIfPossible(); + } } /********************************************************************************************************************** @@ -593,7 +623,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * @return */ protected void absorbtionEventFor(AbstractEAIndividual indy, ParticleSubSwarmOptimization subswarm){ - if (isVerbose()) System.out.print("Absorbtion \n"); + if (isVerbose()) { + System.out.print("Absorbtion \n"); + } absorbtionOccurd = true; this.indytoabsorb.add(indy); } @@ -610,7 +642,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac for (int j = 0; j < getSubSwarms().size(); ++j){ ParticleSubSwarmOptimization currentsubwarm = getSubSwarms().get(j); if (getAbsorptionStrategy().shouldAbsorbParticleIntoSubswarm(currentindy, currentsubwarm, this.getMainSwarm())){ - if (isVerbose()) System.out.println("Absorbing particle (NPSO)"); + if (isVerbose()) { + System.out.println("Absorbing particle (NPSO)"); + } absorbtionEventFor(currentindy, currentsubwarm); getAbsorptionStrategy().absorbParticle(currentindy, currentsubwarm, this.getMainSwarm()); --i; // ith particle is removed, all indizes shift one position to the left @@ -619,14 +653,18 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } } } - if (runagain) absorbParticlesIfPossible(); + if (runagain) { + absorbParticlesIfPossible(); + } } /********************************************************************************************************************** * Subswarm Creation */ protected void subswarmCreationEventFor(AbstractEAIndividual currentindy, ParticleSubSwarmOptimization subswarm) { - if (isVerbose()) System.out.print("creating subswarm\n"); + if (isVerbose()) { + System.out.print("creating subswarm\n"); + } creationOccurd = true; this.indyconverged.add(currentindy); for (int i = 0; i < subswarm.getPopulation().size(); ++i){ @@ -646,7 +684,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac AbstractEAIndividual currentindy = getMainSwarm().getPopulation().getEAIndividual(i); //... that meets the convergence-criteria of the creation strategie if (getSubswarmCreationStrategy().shouldCreateSubswarm(currentindy,getMainSwarm())){ - if (isVerbose()) System.out.println("Creating sub swarm (NPSO)"); + if (isVerbose()) { + System.out.println("Creating sub swarm (NPSO)"); + } // use an optimizer according to the template ParticleSubSwarmOptimization newSubswarm = getNewSubSwarmOptimizer(); // and create a subswarm from the given particle @@ -666,7 +706,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** @tested @@ -684,7 +726,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** @tested nn * This method is required to free the memory on a RMIServer, @@ -764,7 +808,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } } - if (isVerbose()) System.out.println("Active populations: " + activeCnt); + if (isVerbose()) { + System.out.println("Active populations: " + activeCnt); + } // set correct number of generations metapop.setGenerationTo(getMainSwarm().getPopulation().getGeneration()); @@ -852,8 +898,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac Vector subSwarms = getSubSwarms(); // AbstractEAIndividual[] representatives = new AbstractEAIndividual[getSubSwarms().size()+1]; for (int i = 0; i < getSubSwarms().size(); ++i){ - if (!onlyInactive || (!subSwarms.get(i).isActive())) - representatives.add((AbstractEAIndividual)(subSwarms.get(i)).m_BestIndividual.clone()); + if (!onlyInactive || (!subSwarms.get(i).isActive())) { + representatives.add((AbstractEAIndividual)(subSwarms.get(i)).m_BestIndividual.clone()); + } } if (!onlyInactive && (getMainSwarm().getPopulation().size() != 0)) { representatives.add((AbstractEAIndividual)getMainSwarm().m_BestIndividual.clone()); // assures at least one solution, even if no subswarm has been created @@ -995,7 +1042,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } public SelectedTag getMainSwarmAlgoType() { - if (mainSwarmAlgoType != getMainSwarm().getAlgoType().getSelectedTagID()) System.err.println("Error in NichePSO:getMainSwarmAlgoType() !!"); + if (mainSwarmAlgoType != getMainSwarm().getAlgoType().getSelectedTagID()) { + System.err.println("Error in NichePSO:getMainSwarmAlgoType() !!"); + } return getMainSwarm().getAlgoType(); } @@ -1294,7 +1343,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } public double getMedianSubswarmSize() { - if (getSubSwarms().size() == 0) return 0; + if (getSubSwarms().size() == 0) { + return 0; + } double[] size = new double[getSubSwarms().size()]; for (int i = 0; i < getSubSwarms().size(); ++i){ if (getSubSwarms().get(i) == null) { // happend once - cant reproduce... @@ -1450,7 +1501,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac // path File outputPath = new File(getDirForCurrentExperiment()+"\\NichePSO-LogFiles\\"); - if (!outputPath.exists()) outputPath.mkdirs(); + if (!outputPath.exists()) { + outputPath.mkdirs(); + } //String outputPath = getDirForCurrentExperiment()+"/NichePSO-LogFiles/"; //OutputPath = OutputPath + dirForCurrentExperiment+"\\NichePSO-LogFiles\\"; @@ -1463,7 +1516,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac File f = new File(outputPath,name); // plattform independent representation... try { - if (outputFile != null) outputFile.close(); // close old file + if (outputFile != null) { + outputFile.close(); + } // close old file outputFile = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (f))); } catch (FileNotFoundException e) { System.out.println("Could not open output file! Filename: " + name); @@ -1478,7 +1533,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac */ protected void writeToLogFile(String line) { String write = line + "\n"; - if (outputFile == null) return; + if (outputFile == null) { + return; + } try { outputFile.write(write, 0, write.length()); outputFile.flush(); @@ -1502,7 +1559,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac AbstractEAIndividual indy = pop.getEAIndividual(i); //Integer tmp = (Integer)indy.getData("particleIndex"); // here getData was a cpu-time hotspot -> AbstractEAIndividual now has an index as "direct member" //if (index.equals(tmp)) return indy; - if (index.intValue() == indy.getIndividualIndex()) return indy; + if (index.intValue() == indy.getIndividualIndex()) { + return indy; + } } return null; } @@ -1515,11 +1574,15 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac AbstractEAIndividual indy = null; Population pop = getMainSwarm().getPopulation(); indy = getIndyByParticleIndexAndPopulation(pop, index); - if (indy != null) return indy; + if (indy != null) { + return indy; + } for (int i = 0; i < getSubSwarms().size(); ++i){ pop = getSubSwarms().get(i).getPopulation(); indy = getIndyByParticleIndexAndPopulation(pop, index); - if (indy != null) return indy; + if (indy != null) { + return indy; + } } return null; } @@ -1529,7 +1592,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac */ protected AbstractEAIndividual getIndyWithMinStdDev(){ Population mainpop = getMainSwarm().getPopulation(); - if (mainpop.size() == 0) return null; + if (mainpop.size() == 0) { + return null; + } double min = Double.POSITIVE_INFINITY; int minindex = 0; @@ -1558,7 +1623,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac a[1] = 0.0; this.m_TopologySwarm = new TopoPlot("NichePSO-MainSwarm","x","y",a,a); this.m_TopologySwarm.setParams(60,60); - if (m_Problem instanceof Interface2DBorderProblem) this.m_TopologySwarm.setTopology((Interface2DBorderProblem)this.m_Problem); // draws colored plot + if (m_Problem instanceof Interface2DBorderProblem) { + this.m_TopologySwarm.setTopology((Interface2DBorderProblem)this.m_Problem); + } // draws colored plot } /** @tested @@ -1656,7 +1723,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac DPointIcon icon = new Chart2DDPointIconText(id+ds); ((Chart2DDPointIconText)icon).setIcon(new Chart2DDPointIconCircle()); point.setIcon(icon); - if (d < boundary) this.m_TopologySwarm.getFunctionArea().addDElement(point); + if (d < boundary) { + this.m_TopologySwarm.getFunctionArea().addDElement(point); + } } } @@ -1780,8 +1849,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac //...draw circle for best if (!swarm.isActive()){ plotCircleForIndy((AbstractEAIndividual)best,"[I]-Merging "+String.valueOf(index)); - }else - plotCircleForIndy((AbstractEAIndividual)best,getMaxStdDevFromSwarmAsString(swarm)+"-Merging "+String.valueOf(index)); + }else { + plotCircleForIndy((AbstractEAIndividual)best,getMaxStdDevFromSwarmAsString(swarm)+"-Merging "+String.valueOf(index)); + } //...draw SubSwarm as connected lines to best popRep = new DPointSet(); @@ -2068,7 +2138,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac * @return */ public static final GOParameters stdNPSO(NichePSO npso, AbstractOptimizationProblem problem, long randSeed, int evalCnt) { - if (npso == null) npso = new NichePSO(); + if (npso == null) { + npso = new NichePSO(); + } int popSize = 100; npso.setMainSwarmSize(popSize); // double avgRange = Mathematics.getAvgRange(((InterfaceDataTypeDouble)problem.getIndividualTemplate()).getDoubleRange()); @@ -2120,7 +2192,9 @@ public class NichePSO implements InterfaceAdditionalPopulationInformer, Interfac } public static final NichePSO starNPSO(NichePSO npso, int evalCnt) { - if (npso == null) npso = new NichePSO(); + if (npso == null) { + npso = new NichePSO(); + } int popSize = 200; npso.setMainSwarmSize(popSize); // double avgRange = Mathematics.getAvgRange(((InterfaceDataTypeDouble)problem.getIndividualTemplate()).getDoubleRange()); diff --git a/src/eva2/server/go/strategies/ParticleFilterOptimization.java b/src/eva2/server/go/strategies/ParticleFilterOptimization.java index 2a0e31bc..ff3a28a6 100644 --- a/src/eva2/server/go/strategies/ParticleFilterOptimization.java +++ b/src/eva2/server/go/strategies/ParticleFilterOptimization.java @@ -60,7 +60,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S public static final boolean TRACE = false; public ParticleFilterOptimization() { - if (withShow) setWithShow(true); + if (withShow) { + setWithShow(true); + } } public ParticleFilterOptimization(double vInit, double mute, double immiQuote, double rotDeg, double selScaling) { @@ -69,7 +71,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S randomImmigrationQuota = immiQuote; rotationDeg = rotDeg; m_ParentSelection = new SelectParticleWheel(selScaling); - if (withShow) setWithShow(true); + if (withShow) { + setWithShow(true); + } } public ParticleFilterOptimization(ParticleFilterOptimization a) { @@ -80,7 +84,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S //this.m_NumberOfPartners = a.m_NumberOfPartners; //this.m_UseElitism = a.m_UseElitism; this.m_ParentSelection = (InterfaceSelection)a.m_ParentSelection.clone(); - if (a.withShow) setWithShow(true); + if (a.withShow) { + setWithShow(true); + } } public void hideHideable() { @@ -149,11 +155,15 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S // DONT forget cloning -> selection does only shallow copies! int targetSize = this.m_Population.getTargetSize(); if (randomImmigrationQuota>0) { - if (randomImmigrationQuota>1.) System.err.println("Error, invalid immigration quota!"); + if (randomImmigrationQuota>1.) { + System.err.println("Error, invalid immigration quota!"); + } else { targetSize = (int)(this.m_Population.getTargetSize() * (1.-randomImmigrationQuota)); targetSize = Math.max(1, targetSize); // guarantee at least one to be selected - if (targetSize < this.m_Population.getTargetSize()) doImmigr=true; + if (targetSize < this.m_Population.getTargetSize()) { + doImmigr=true; + } } } @@ -169,13 +179,17 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S parents.add(immi); } parents.synchSize(); - if (TRACE) System.out.println("Added " + i + " random individuals"); + if (TRACE) { + System.out.println("Added " + i + " random individuals"); + } } parents.SetFunctionCalls(pop.getFunctionCalls()); parents.setGenerationTo(pop.getGeneration()); - if (withShow) drawPop(parents, 3, true); + if (withShow) { + drawPop(parents, 3, true); + } return parents; } @@ -188,18 +202,26 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S applyMotionModel((AbstractEAIndividual)((AbstractEAIndividual)pop.get(i)), 0.); indCount++; } - if (withShow) drawPop(pop, 1, false); + if (withShow) { + drawPop(pop, 1, false); + } } private void drawPop(Population pop, int graphLabel, boolean useCircles) { if (myPlot != null) { - if (graphLabel < 0) graphLabel = indCount; + if (graphLabel < 0) { + graphLabel = indCount; + } for (int i=0; i 0 ) try { Thread.sleep(sleepTime); } catch(Exception e) {} - if (withShow) clearPlot(); + if (sleepTime > 0 ) { + try { Thread.sleep(sleepTime); } catch(Exception e) {} + } + if (withShow) { + clearPlot(); + } // predict step predict(nextGeneration); - if (TRACE) System.out.println("Speed is " + BeanInspector.toString(ParticleSwarmOptimization.getPopulationVelSpeed(m_Population, 3, MutateESCorrVector.vectorKey, null, null)) + " popM " + BeanInspector.toString(m_Population.getPopulationMeasures(new EuclideanMetric()))); + if (TRACE) { + System.out.println("Speed is " + BeanInspector.toString(ParticleSwarmOptimization.getPopulationVelSpeed(m_Population, 3, MutateESCorrVector.vectorKey, null, null)) + " popM " + BeanInspector.toString(m_Population.getPopulationMeasures(new EuclideanMetric()))); + } m_Population = evaluatePopulation(nextGeneration); @@ -254,10 +282,14 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized @@ -373,7 +405,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S if (myPlot!=null) { myPlot.clearAll(); double[][] range = null; - if ((m_Population != null) && (m_Population.size() > 0)) range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); + if ((m_Population != null) && (m_Population.size() > 0)) { + range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); + } if (range != null) { myPlot.setCornerPoints(range, 0); } @@ -385,10 +419,14 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S **/ public void setWithShow(boolean wShow) { this.withShow = wShow; - if (!withShow) myPlot = null; + if (!withShow) { + myPlot = null; + } else { double[][] range; - if ((m_Population != null) && (m_Population.size() > 0)) range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); + if ((m_Population != null) && (m_Population.size() > 0)) { + range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); + } else { range = new double[2][]; range[0] = new double[2]; diff --git a/src/eva2/server/go/strategies/ParticleSubSwarmOptimization.java b/src/eva2/server/go/strategies/ParticleSubSwarmOptimization.java index dfec241a..1265dd60 100644 --- a/src/eva2/server/go/strategies/ParticleSubSwarmOptimization.java +++ b/src/eva2/server/go/strategies/ParticleSubSwarmOptimization.java @@ -204,7 +204,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO 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; + if (index.intValue() == indy.getIndividualIndex()) { + return indy; + } } return null; } @@ -244,7 +246,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO * 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; + 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 @@ -277,7 +281,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO Vector fitArchive_new = new Vector(); int end = fitArchive_old.size(); int start = 0; - if (end >= fitnessArchiveSize) start = end-fitnessArchiveSize; + if (end >= fitnessArchiveSize) { + start = end-fitnessArchiveSize; + } for (int j = start; j < end; ++j){ fitArchive_new.add(fitArchive_old.get(j)); @@ -342,8 +348,12 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO // ESIndividualDoubleData max = (ESIndividualDoubleData)template.clone(); double[][] range = null; - if (template instanceof ESIndividualDoubleData) range = ((ESIndividualDoubleData)template).getDoubleRange(); - else range = ((InterfaceDataTypeDouble)template).getDoubleRange(); + 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){ @@ -383,7 +393,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO * @return */ protected static double mean(Vector vec,int range){ - if (vec.size() < range) range = vec.size(); + 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(); @@ -399,7 +411,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO */ 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 + 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); @@ -442,7 +456,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO * @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)"); + if (particleIndices == null) { + throw new RuntimeException("Error, unable to use null index array (ParticleSubSwarmOptimization.addNewParticlesToPOpulation)"); + } Population tmp = new Population(); tmp.setTargetSize(particleIndices.length); @@ -572,7 +588,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO * @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; + if (getPopulation().size() == 0 || getPopulation().size() == 1) { + return 0; + } double max = Double.NEGATIVE_INFINITY; //PhenotypeMetric metric = new PhenotypeMetric(); @@ -617,7 +635,9 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO for (int i = 0; i < pop.size(); ++i){ AbstractEAIndividual indy = pop.getEAIndividual(i); AbstractEAIndividual neigbor = getMemberNeighbor(indy); - if (neigbor == null) return -1; + if (neigbor == null) { + return -1; + } sum += distance(indy, neigbor); } return sum/(double)pop.size(); @@ -709,10 +729,14 @@ public class ParticleSubSwarmOptimization extends ParticleSwarmOptimizationGCPSO mindist = dist; index = i; } - } else found=true; + } else { + found=true; + } } - if (!found) System.err.println("getNeighbor: particle searching for neighbor is not part of the swarm"); + if (!found) { + System.err.println("getNeighbor: particle searching for neighbor is not part of the swarm"); + } return getPopulation().getEAIndividual(index); } diff --git a/src/eva2/server/go/strategies/ParticleSwarmOptimizationGCPSO.java b/src/eva2/server/go/strategies/ParticleSwarmOptimizationGCPSO.java index 801f1681..234e38b2 100644 --- a/src/eva2/server/go/strategies/ParticleSwarmOptimizationGCPSO.java +++ b/src/eva2/server/go/strategies/ParticleSwarmOptimizationGCPSO.java @@ -100,8 +100,12 @@ public class ParticleSwarmOptimizationGCPSO extends ParticleSwarmOptimization { 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); + 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]; @@ -172,7 +176,9 @@ public class ParticleSwarmOptimizationGCPSO extends ParticleSwarmOptimization { { gbestParticleHasChanged = true; gbestParticleIndex = index; - } else gbestParticleHasChanged = false; + } else { + gbestParticleHasChanged = false; + } /** numOfSuccesses,numOfFailures */ // check if the gbestParticle improved over the last iteration diff --git a/src/eva2/server/go/strategies/PopulationBasedIncrementalLearning.java b/src/eva2/server/go/strategies/PopulationBasedIncrementalLearning.java index 17c32a03..5d5376bf 100644 --- a/src/eva2/server/go/strategies/PopulationBasedIncrementalLearning.java +++ b/src/eva2/server/go/strategies/PopulationBasedIncrementalLearning.java @@ -70,7 +70,9 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j if ((m_initialProbabilities!=null) && (m_initialProbabilities.length==((PBILPopulation)m_Population).getProbabilityVector().length)) { ((PBILPopulation)m_Population).setProbabilityVector(m_initialProbabilities); } else { - if (m_initialProbabilities!=null) System.err.println("Warning: initial probability vector doesnt match in length!"); + if (m_initialProbabilities!=null) { + System.err.println("Warning: initial probability vector doesnt match in length!"); + } } this.evaluatePopulation(this.m_Population); this.firePropertyChangedEvent(Population.nextGenerationPerformed); @@ -165,12 +167,16 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will return a string describing all properties of the optimizer @@ -287,7 +293,9 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j */ public void setLearningRate (double LearningRate) { this.m_LearningRate = LearningRate; - if (this.m_LearningRate < 0) this.m_LearningRate = 0; + if (this.m_LearningRate < 0) { + this.m_LearningRate = 0; + } } public double getLearningRate() { return this.m_LearningRate; @@ -301,8 +309,12 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j */ public void setMutationRate (double m) { this.m_MutationRate = m; - if (this.m_MutationRate < 0) this.m_MutationRate = 0; - if (this.m_MutationRate > 1) this.m_MutationRate = 1; + if (this.m_MutationRate < 0) { + this.m_MutationRate = 0; + } + if (this.m_MutationRate > 1) { + this.m_MutationRate = 1; + } } public double getMutationRate() { return this.m_MutationRate; @@ -316,7 +328,9 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j */ public void setMutateSigma (double m) { this.m_MutateSigma = m; - if (this.m_MutateSigma < 0) this.m_MutateSigma = 0; + if (this.m_MutateSigma < 0) { + this.m_MutateSigma = 0; + } } public double getMutateSigma() { return this.m_MutateSigma; @@ -330,7 +344,9 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j */ public void setPositiveSamples (int PositiveSamples) { this.m_NumberOfPositiveSamples = PositiveSamples; - if (this.m_NumberOfPositiveSamples < 1) this.m_NumberOfPositiveSamples = 1; + if (this.m_NumberOfPositiveSamples < 1) { + this.m_NumberOfPositiveSamples = 1; + } } public int getPositiveSamples() { return this.m_NumberOfPositiveSamples; diff --git a/src/eva2/server/go/strategies/ScatterSearch.java b/src/eva2/server/go/strategies/ScatterSearch.java index 8a1659d9..817baf1a 100644 --- a/src/eva2/server/go/strategies/ScatterSearch.java +++ b/src/eva2/server/go/strategies/ScatterSearch.java @@ -158,20 +158,28 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, refSet = null; combinations = null; template = problem.getIndividualTemplate(); - if (!(template instanceof InterfaceDataTypeDouble)) System.err.println("Requiring double data!"); + if (!(template instanceof InterfaceDataTypeDouble)) { + System.err.println("Requiring double data!"); + } else { Object dim = BeanInspector.callIfAvailable(problem, "getProblemDimension", null); - if (dim==null) System.err.println("Couldnt get problem dimension!"); + if (dim==null) { + System.err.println("Couldnt get problem dimension!"); + } probDim = (Integer)dim; range = ((InterfaceDataTypeDouble)template).getDoubleRange(); - if (TRACE) System.out.println("Range is " + BeanInspector.toString(range)); + if (TRACE) { + System.out.println("Range is " + BeanInspector.toString(range)); + } } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } // public double eval(double[] x) { @@ -212,7 +220,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, // refset regeneration // goto L if (!firstTime) { - if (lastImprovementCount == 0) refSet = regenerateRefSet(); + if (lastImprovementCount == 0) { + refSet = regenerateRefSet(); + } } firstTime = false; @@ -228,7 +238,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, oldRefSet = (Population) refSet.clone(); lastImprovementCount = 0; } - if (TRACE) System.out.println("No combinations: " + combinations.size()); + if (TRACE) { + System.out.println("No combinations: " + combinations.size()); + } if (combinations.size()>0) { updateRefSet(refSet, combinations, oldRefSet); } @@ -252,18 +264,24 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, // absolute fitness criterion return (cand.getFitness(0) < localSearchFitnessFilter); } - } else return false; + } else { + return false; + } } private Population regenerateRefSet() { Population diversifiedPop = diversify(); int keep = refSetSize/2; Population newRefSet = refSet.cloneWithoutInds(); - if (TRACE) System.out.println("regen after " + refSet.getFunctionCalls() + ", best is " + refSet.getBestEAIndividual().getFitness(0)); + if (TRACE) { + System.out.println("regen after " + refSet.getFunctionCalls() + ", best is " + refSet.getBestEAIndividual().getFitness(0)); + } newRefSet.addAll(refSet.getBestNIndividuals(keep, fitCrit)); - if (TRACE) System.out.println("keeping " + keep + " indies from former ref set, best is " + newRefSet.getBestEAIndividual().getFitness(0)); + if (TRACE) { + System.out.println("keeping " + keep + " indies from former ref set, best is " + newRefSet.getBestEAIndividual().getFitness(0)); + } int h=newRefSet.size(); ArrayList distVects = new ArrayList(); @@ -353,7 +371,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, if (isDoLocalSolver(bestCand, refSet)) { Pair lsRet = localSolver(bestCand, localSearchSteps); - if ((Math.abs(lsRet.tail() - localSearchSteps)/localSearchSteps) > 0.05) System.err.println("Warning, more than 5% difference in local search step"); + if ((Math.abs(lsRet.tail() - localSearchSteps)/localSearchSteps) > 0.05) { + System.err.println("Warning, more than 5% difference in local search step"); + } bestCand = lsRet.head(); refSet.incrFunctionCallsBy(lsRet.tail()); if (TRACE) { @@ -362,7 +382,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } if (bestCand.isDominatingEqual(worstRef)) { - if (TRACE) System.out.println("cand is dominating worst ref!"); + if (TRACE) { + System.out.println("cand is dominating worst ref!"); + } if (diversityCriterionFulfilled(bestCand, refSet, oldRefSet)) { // System.out.println("diversity criterion is fulfilled! replacing fit " + worstRef.getFitness(0)); int replIndex = refSet.indexOf(worstRef); @@ -378,17 +400,27 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, // System.out.println("Improvements: " + lastImprovementCount); candidates.remove(bestIndex); } else { - if (TRACE) System.out.println("cand is too bad!"); + if (TRACE) { + System.out.println("cand is too bad!"); + } // if the best candidate is worse and no local search is performed, all following will be worse - at least in the uni-criterial case // so we can just clear the rest of the candidates - if (!doLocalSearch && (bestCand.getFitness().length == 1)) candidates.clear(); - else candidates.remove(bestIndex); + if (!doLocalSearch && (bestCand.getFitness().length == 1)) { + candidates.clear(); + } + else { + candidates.remove(bestIndex); + } } } private Pair localSolver(AbstractEAIndividual cand, int hcSteps) { - if (localSearchMethod.getSelectedTagID()==0) return localSolverHC(cand, hcSteps); - else return PostProcess.localSolverNMS(cand, hcSteps, nelderMeadInitPerturbation, problem); + if (localSearchMethod.getSelectedTagID()==0) { + return localSolverHC(cand, hcSteps); + } + else { + return PostProcess.localSolverNMS(cand, hcSteps, nelderMeadInitPerturbation, problem); + } } private Pair localSolverHC(AbstractEAIndividual cand, int hcSteps) { @@ -436,7 +468,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, if (minDistFulfilled && (improvementEpsilon > 0)) { boolean minImprovementFulfilled = (cand.getFitness(0) < ((1.-improvementEpsilon) * popComPheno.getBestEAIndividual().getFitness(0))); return minImprovementFulfilled; - } else return minDistFulfilled; + } else { + return minDistFulfilled; + } } /** @@ -478,12 +512,18 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, // if (TRACE) System.out.println("combi T ww, " + i+ "/" + j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); combs.add(combineTypeTwo(indy1, indy2)); - if (RNG.flipCoin(0.5)) combs.add(combineTypeOne(indy1, indy2)); - else combs.add(combineTypeThree(indy1, indy2)); + if (RNG.flipCoin(0.5)) { + combs.add(combineTypeOne(indy1, indy2)); + } + else { + combs.add(combineTypeThree(indy1, indy2)); + } } } - if (TRACE) System.out.println("created combinations " + combs.size() + " best is " + combs.getBestEAIndividual().getFitness(0) ); + if (TRACE) { + System.out.println("created combinations " + combs.size() + " best is " + combs.getBestEAIndividual().getFitness(0) ); + } return combs; } @@ -508,7 +548,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } double[] candidate = bFirst ? v1 : v2; double[] combi = bAdd ? Mathematics.vvAdd(candidate, dVect) : Mathematics.vvSub(candidate, dVect); - if (checkRange) Mathematics.projectToRange(combi, range); + if (checkRange) { + Mathematics.projectToRange(combi, range); + } ((InterfaceDataTypeDouble)resIndy).SetDoubleGenotype(combi); problem.evaluate(resIndy); refSet.incrFunctionCalls(); @@ -554,7 +596,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, private double getMinInCol(int col, int maxRow, double[][] vals) { double dmin = vals[col][0]; - if (dmin < 0) return dmin; // tweak for trick + if (dmin < 0) { + return dmin; + } // tweak for trick for (int j=1; j= 1.0000001) System.err.println("Check this: sum>=1 in selectInterv"); + if (sum >= 1.0000001) { + System.err.println("Check this: sum>=1 in selectInterv"); + } return sel; } @@ -716,7 +764,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } @Override public void freeWilly() {} @@ -860,7 +910,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, ss.setDoLocalSearch(true); ss.setLocalSearchSteps(localSearchSteps); ss.setLocalSearchFitnessFilter(localSearchFitnessFilter); - } else ss.setDoLocalSearch(false); + } else { + ss.setDoLocalSearch(false); + } Population pop = new Population(); pop.setTargetSize(refSetSize); pop.init(); diff --git a/src/eva2/server/go/strategies/SimulatedAnnealing.java b/src/eva2/server/go/strategies/SimulatedAnnealing.java index 57ae1672..26e7655a 100644 --- a/src/eva2/server/go/strategies/SimulatedAnnealing.java +++ b/src/eva2/server/go/strategies/SimulatedAnnealing.java @@ -153,9 +153,13 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa for (int i = 0; i < m_FitnessCalls; i++) { this.m_Test = (GAIndividualBinaryData)((this.m_Best).clone()); this.m_Test.defaultMutate(); - if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) this.m_Best = this.m_Test; + if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { + this.m_Best = this.m_Test; + } this.m_FitnessCallsNeeded = i; - if (this.m_Best.defaultEvaulateAsMiniBits() == 0) i = this.m_FitnessCalls +1; + if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { + i = this.m_FitnessCalls +1; + } } } @@ -187,10 +191,14 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will return a string describing all properties of the optimizer @@ -200,8 +208,12 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa @Override public String getStringRepresentation() { String result = ""; - if (this.m_Population.size() > 1) result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; - else result += "Simulated Annealing:\n"; + if (this.m_Population.size() > 1) { + result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; + } + else { + result += "Simulated Annealing:\n"; + } result += "Optimization Problem: "; result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Population.getStringRepresentation(); @@ -284,7 +296,9 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa } public void setAlpha(double a){ this.m_Alpha = a; - if (this.m_Alpha > 1) this.m_Alpha = 1.0; + if (this.m_Alpha > 1) { + this.m_Alpha = 1.0; + } } public String alphaTipText() { return "Set alpha, which is used to degrade the temperaure."; diff --git a/src/eva2/server/go/strategies/SteadyStateGA.java b/src/eva2/server/go/strategies/SteadyStateGA.java index baf7af98..5c9ce89b 100644 --- a/src/eva2/server/go/strategies/SteadyStateGA.java +++ b/src/eva2/server/go/strategies/SteadyStateGA.java @@ -129,10 +129,14 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable { if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized @@ -235,7 +239,9 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable { * @param partners */ public void setNumberOfPartners(int partners) { - if (partners < 0) partners = 0; + if (partners < 0) { + partners = 0; + } this.m_NumberOfPartners = partners; } public int getNumberOfPartners() { diff --git a/src/eva2/server/go/strategies/ThresholdAlgorithm.java b/src/eva2/server/go/strategies/ThresholdAlgorithm.java index a8e6ff44..9cc5a855 100644 --- a/src/eva2/server/go/strategies/ThresholdAlgorithm.java +++ b/src/eva2/server/go/strategies/ThresholdAlgorithm.java @@ -144,9 +144,13 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa for (int i = 0; i < m_FitnessCalls; i++) { this.m_Test = (GAIndividualBinaryData)((this.m_Best).clone()); this.m_Test.defaultMutate(); - if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) this.m_Best = this.m_Test; + if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { + this.m_Best = this.m_Test; + } this.m_FitnessCallsNeeded = i; - if (this.m_Best.defaultEvaulateAsMiniBits() == 0) i = this.m_FitnessCalls +1; + if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { + i = this.m_FitnessCalls +1; + } } } @@ -177,10 +181,14 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will return a string describing all properties of the optimizer @@ -190,8 +198,12 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa @Override public String getStringRepresentation() { String result = ""; - if (this.m_Population.size() > 1) result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; - else result += "Threshold Algorithm:\n"; + if (this.m_Population.size() > 1) { + result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; + } + else { + result += "Threshold Algorithm:\n"; + } result += "Optimization Problem: "; result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Population.getStringRepresentation(); @@ -274,7 +286,9 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa } public void setAlpha(double a){ this.m_Alpha = a; - if (this.m_Alpha > 1) this.m_Alpha = 1.0; + if (this.m_Alpha > 1) { + this.m_Alpha = 1.0; + } } public String alphaTipText() { return "Set alpha, which is used to degrade the threshold."; diff --git a/src/eva2/server/go/strategies/Tribes.java b/src/eva2/server/go/strategies/Tribes.java index ab9ead27..62604d8d 100644 --- a/src/eva2/server/go/strategies/Tribes.java +++ b/src/eva2/server/go/strategies/Tribes.java @@ -237,7 +237,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { population.addAll(swarm.toPopulation()); population.init(); // necessary to allow for multi-runs - if (m_Show) show(); + if (m_Show) { + show(); + } } @@ -259,7 +261,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { indy.setFitness(bestMemPos.getFitness()); ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(bestMemPos.getPos()); return indy; - } else return bestExp; + } else { + return bestExp; + } } @Override @@ -317,7 +321,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { } population.clear(); population.addAll(swarm.toPopulation()); - if (m_Show) plotAll(population); + if (m_Show) { + plotAll(population); + } m_problem.evaluatePopulationEnd(population); // this.population.incrFunctionCallsby(evals); @@ -638,7 +644,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { */ @Override public void setPopulation(Population pop) { - if (pop == null) return; + if (pop == null) { + return; + } population = pop; if (population.get(0) instanceof InterfaceDataTypeDouble) { range = ((InterfaceDataTypeDouble)population.get(0)).getDoubleRange(); @@ -691,7 +699,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { protected TribesExplorer positionToExplorer(TribesPosition pos) { TribesExplorer tmp = (TribesExplorer)population.get(0); - if (tmp == null) System.err.println("Error in Tribes::positionToExplorer!"); + if (tmp == null) { + System.err.println("Error in Tribes::positionToExplorer!"); + } TribesExplorer indy = tmp.clone(); indy.clearPosVel(); indy.SetDoubleGenotype(pos.getPos()); @@ -712,10 +722,14 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } protected void firePropertyChangedEvent(String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } public boolean notifyAfter(int evals) { @@ -820,6 +834,8 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { */ public void setShow(boolean show) { m_Show = show; - if (!show) m_Plot = null; + if (!show) { + m_Plot = null; + } } } diff --git a/src/eva2/server/go/strategies/WingedMultiObjectiveEA.java b/src/eva2/server/go/strategies/WingedMultiObjectiveEA.java index 62ac2089..619ea188 100644 --- a/src/eva2/server/go/strategies/WingedMultiObjectiveEA.java +++ b/src/eva2/server/go/strategies/WingedMultiObjectiveEA.java @@ -223,12 +223,16 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria if (m_Listener==ea) { m_Listener=null; return true; - } else return false; + } else { + return false; + } } /** Something has changed */ protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + if (this.m_Listener != null) { + this.m_Listener.registerPopulationStateChanged(this, name); + } } /** This method will set the problem that is to be optimized diff --git a/src/eva2/server/go/strategies/tribes/TribesExplorer.java b/src/eva2/server/go/strategies/tribes/TribesExplorer.java index e586dbcb..243fc446 100644 --- a/src/eva2/server/go/strategies/tribes/TribesExplorer.java +++ b/src/eva2/server/go/strategies/tribes/TribesExplorer.java @@ -977,7 +977,9 @@ v[d] = cmin * v[d]; public void initByValue(Object obj, InterfaceOptimizationProblem opt) { if (obj instanceof double[]) { double[] x = (double[]) obj; - if (x.length != position.x.length) System.err.println("Init value and requested length doesn't match!"); + if (x.length != position.x.length) { + System.err.println("Init value and requested length doesn't match!"); + } this.SetDoubleGenotype(x); } else { this.init(opt); diff --git a/src/eva2/server/go/strategies/tribes/TribesPosition.java b/src/eva2/server/go/strategies/tribes/TribesPosition.java index da3dd652..078aec5c 100644 --- a/src/eva2/server/go/strategies/tribes/TribesPosition.java +++ b/src/eva2/server/go/strategies/tribes/TribesPosition.java @@ -692,7 +692,9 @@ public class TribesPosition implements java.io.Serializable { No need of a very precise solution */ - if (TRACE) System.out.println("sunny start"); + if (TRACE) { + System.out.println("sunny start"); + } // INITIALISATION for (n = 0; n < swarm.size; n++) { @@ -830,7 +832,9 @@ public class TribesPosition implements java.io.Serializable { System.out.print(swarm.Best.position.x[d]+" "); */ swarm.bestMem.getPos().isolation=swarm.bestMem.getPos().fitness[0]; - if (TRACE) System.out.println("sunny end, ret " + swarm.bestMem.getPos().toString()); + if (TRACE) { + System.out.println("sunny end, ret " + swarm.bestMem.getPos().toString()); + } return swarm.bestMem.getPos(); } @@ -853,7 +857,9 @@ public class TribesPosition implements java.io.Serializable { return true; } else { // Total error approach - if(calcTotalError(f1) { 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 (fit1[fitCriterion] == fit2[fitCriterion]) { + return 0; + } + else { + return (fit1[fitCriterion] < fit2[fitCriterion]) ? -1 : 1; + } } - if (o1domO2 ^ o2domO1) return (o1domO2 ? -1 : 1); - else return 0; // these are not comparable + if (o1domO2 ^ o2domO1) { + return (o1domO2 ? -1 : 1); + } + else { + return 0; + } // these are not comparable } } diff --git a/src/eva2/server/go/tools/FileTools.java b/src/eva2/server/go/tools/FileTools.java index 9e560e53..a062a08d 100644 --- a/src/eva2/server/go/tools/FileTools.java +++ b/src/eva2/server/go/tools/FileTools.java @@ -109,7 +109,9 @@ public class FileTools { f = new File(filename+"."+i); } while (!f.createNewFile()); return f; - } else return f; + } else { + return f; + } } catch(IOException e) { System.err.println("IOException when trying to create new file!"); System.err.println(e.getMessage()); @@ -136,10 +138,18 @@ public class FileTools { 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 return false; // user break + if (opt==JOptionPane.OK_OPTION) { + finished=true; + } + if (opt==JOptionPane.CANCEL_OPTION) { + return false; + } + } else { + finished=true; + } + } else { + return false; + } // user break } while (!finished); // wait until user selected valid file if (returnVal==JFileChooser.APPROVE_OPTION) { @@ -164,7 +174,9 @@ public class FileTools { JOptionPane.ERROR_MESSAGE); return false; } - } else return false; + } else { + return false; + } } /** @@ -194,7 +206,9 @@ public class FileTools { JOptionPane.ERROR_MESSAGE); } } - if (fc!=null) fc=null; + if (fc!=null) { + fc=null; + } return obj; } @@ -221,7 +235,9 @@ public class FileTools { 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; + if (opt!=JOptionPane.OK_OPTION) { + return false; + } } // we may save the file String msg; @@ -233,7 +249,9 @@ public class FileTools { "Save object to folder", JOptionPane.ERROR_MESSAGE); return false; - } else return true; + } else { + return true; + } } } diff --git a/src/eva2/server/go/tools/GeneralGEOFaker.java b/src/eva2/server/go/tools/GeneralGEOFaker.java index 0af9772e..d5fcc6c4 100644 --- a/src/eva2/server/go/tools/GeneralGEOFaker.java +++ b/src/eva2/server/go/tools/GeneralGEOFaker.java @@ -114,7 +114,9 @@ public class GeneralGEOFaker extends JPanel { * @return the loaded object, or null if the operation was cancelled */ protected Object openObject() { - if (m_FileChooser == null) createFileChooser(); + if (m_FileChooser == null) { + createFileChooser(); + } int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selected = m_FileChooser.getSelectedFile(); @@ -137,7 +139,9 @@ public class GeneralGEOFaker extends JPanel { * @param object The object to save. */ protected void saveObject(Object object) { - if (m_FileChooser == null) createFileChooser(); + if (m_FileChooser == null) { + createFileChooser(); + } int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File sFile = m_FileChooser.getSelectedFile(); diff --git a/src/eva2/server/go/tools/GeneralGenericObjectEditorPanel.java b/src/eva2/server/go/tools/GeneralGenericObjectEditorPanel.java index 21bc84ae..e345f380 100644 --- a/src/eva2/server/go/tools/GeneralGenericObjectEditorPanel.java +++ b/src/eva2/server/go/tools/GeneralGenericObjectEditorPanel.java @@ -174,7 +174,9 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe * @return the loaded object, or null if the operation was cancelled */ protected Object openObject() { - if (m_FileChooser == null) createFileChooser(); + if (m_FileChooser == null) { + createFileChooser(); + } int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { @@ -203,7 +205,9 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe * @param object the object to save. */ protected void saveObject(Object object) { - if (m_FileChooser == null) createFileChooser(); + if (m_FileChooser == null) { + createFileChooser(); + } int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File sFile = m_FileChooser.getSelectedFile(); @@ -261,8 +265,12 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe 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 remove(m_ObjectChooser); + if (m_ClassesLongName.size() > 1) { + add(m_ObjectChooser, BorderLayout.NORTH); + } + else { + remove(m_ObjectChooser); + } } protected void updateChooser() { @@ -274,7 +282,9 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe break; } } - if (!found) m_ObjectNames.addElement(objectName); + if (!found) { + m_ObjectNames.addElement(objectName); + } m_ObjectChooser.getModel().setSelectedItem(objectName); } diff --git a/src/eva2/server/go/tools/ImpactOfDimensionOnMOEAs.java b/src/eva2/server/go/tools/ImpactOfDimensionOnMOEAs.java index d0bb49a8..22f3aa13 100644 --- a/src/eva2/server/go/tools/ImpactOfDimensionOnMOEAs.java +++ b/src/eva2/server/go/tools/ImpactOfDimensionOnMOEAs.java @@ -79,7 +79,9 @@ public class ImpactOfDimensionOnMOEAs { tmpS = ""+i+";"; for (int j = 0; j < log[i].length; j++) { tmpS += log[i][j]; - if (j < log[i].length-1) tmpS += ";"; + if (j < log[i].length-1) { + tmpS += ";"; + } } tmpS += "\n"; m_OutputFile.write(tmpS); @@ -120,8 +122,12 @@ public class ImpactOfDimensionOnMOEAs { fitness[j] += x[k]; } } - 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]; + 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]; + } } ((AbstractEAIndividual)pop.get(i)).setFitness(fitness); } diff --git a/src/eva2/server/go/tools/ParetoFrontLocalTester.java b/src/eva2/server/go/tools/ParetoFrontLocalTester.java index c76853e6..26bc4b0f 100644 --- a/src/eva2/server/go/tools/ParetoFrontLocalTester.java +++ b/src/eva2/server/go/tools/ParetoFrontLocalTester.java @@ -135,7 +135,9 @@ public class ParetoFrontLocalTester { */ private void writeToFile(String line) { String write = line + "\n"; - if (this.m_OutputFile == null) return; + if (this.m_OutputFile == null) { + return; + } try { this.m_OutputFile.write(write, 0, write.length()); this.m_OutputFile.flush(); diff --git a/src/eva2/server/go/tools/PortfolioFrontTester.java b/src/eva2/server/go/tools/PortfolioFrontTester.java index 81692b85..f61616ab 100644 --- a/src/eva2/server/go/tools/PortfolioFrontTester.java +++ b/src/eva2/server/go/tools/PortfolioFrontTester.java @@ -185,9 +185,15 @@ public class PortfolioFrontTester { private int exceedingLimit(double limit, double x1, double x2, double x3) { int result = 0; - if (x1 > limit) result++; - if (x2 > limit) result++; - if (x3 > limit) result++; + if (x1 > limit) { + result++; + } + if (x2 > limit) { + result++; + } + if (x3 > limit) { + result++; + } return result; } @@ -303,7 +309,9 @@ public class PortfolioFrontTester { */ private void writeToFile(String line) { String write = line + "\n"; - if (this.m_OutputFile == null) return; + if (this.m_OutputFile == null) { + return; + } try { this.m_OutputFile.write(write, 0, write.length()); this.m_OutputFile.flush(); diff --git a/src/eva2/server/modules/AbstractGOParameters.java b/src/eva2/server/modules/AbstractGOParameters.java index f3f34343..377958d7 100644 --- a/src/eva2/server/modules/AbstractGOParameters.java +++ b/src/eva2/server/modules/AbstractGOParameters.java @@ -75,15 +75,21 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser */ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); + if (this.m_Optimizer != null) { + this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); + } } public boolean removePopulationChangedEventListener( InterfacePopulationChangedEventListener ea) { if (m_Listener==ea) { m_Listener=null; - if (this.m_Optimizer!=null) this.m_Optimizer.removePopulationChangedEventListener(ea); + if (this.m_Optimizer!=null) { + this.m_Optimizer.removePopulationChangedEventListener(ea); + } return true; - } else return false; + } else { + return false; + } } /** @@ -122,35 +128,50 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser @Override public void addInformableInstance(InterfaceNotifyOnInformers o) { - if (toInformAboutInformers==null) toInformAboutInformers=new LinkedList(); - if (!toInformAboutInformers.contains(o)) toInformAboutInformers.add(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); + if (toInformAboutInformers==null) { + return false; + } + else { + return toInformAboutInformers.remove(o); + } } private void fireNotifyOnInformers() { - if (toInformAboutInformers!=null) for (InterfaceNotifyOnInformers listener : toInformAboutInformers) { - listener.setInformers(getInformerList()); - } + if (toInformAboutInformers!=null) { + for (InterfaceNotifyOnInformers listener : toInformAboutInformers) { +listener.setInformers(getInformerList()); +} } } @Override public void setOptimizer(InterfaceOptimizer optimizer) { this.m_Optimizer = optimizer; this.m_Optimizer.setProblem(this.m_Problem); - if (this.m_Listener != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); + if (this.m_Listener != null) { + this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); + } fireNotifyOnInformers(); } private List getInformerList() { LinkedList ret = new LinkedList(); - if (m_Problem instanceof InterfaceAdditionalPopulationInformer) ret.add(m_Problem); - if (m_Optimizer instanceof InterfaceAdditionalPopulationInformer) ret.add((InterfaceAdditionalPopulationInformer)m_Optimizer); + if (m_Problem instanceof InterfaceAdditionalPopulationInformer) { + ret.add(m_Problem); + } + if (m_Optimizer instanceof InterfaceAdditionalPopulationInformer) { + ret.add((InterfaceAdditionalPopulationInformer)m_Optimizer); + } return ret; } diff --git a/src/eva2/server/modules/GAParameters.java b/src/eva2/server/modules/GAParameters.java index e6610892..9bb157f4 100644 --- a/src/eva2/server/modules/GAParameters.java +++ b/src/eva2/server/modules/GAParameters.java @@ -138,7 +138,9 @@ public class GAParameters extends AbstractGOParameters implements InterfaceGOPar * @param partners */ public void setNumberOfPartners(int partners) { - if (partners < 0) partners = 0; + if (partners < 0) { + partners = 0; + } ((GeneticAlgorithm)this.m_Optimizer).setNumberOfPartners(partners); } public int getNumberOfPartners() { diff --git a/src/eva2/server/modules/PBILParameters.java b/src/eva2/server/modules/PBILParameters.java index 28ef97cf..a380c669 100644 --- a/src/eva2/server/modules/PBILParameters.java +++ b/src/eva2/server/modules/PBILParameters.java @@ -114,7 +114,9 @@ public class PBILParameters extends AbstractGOParameters implements InterfaceGOP * @param LearningRate */ public void setLearningRate (double LearningRate) { - if (LearningRate < 0) LearningRate = 0; + if (LearningRate < 0) { + LearningRate = 0; + } ((PopulationBasedIncrementalLearning)this.m_Optimizer).setLearningRate(LearningRate); } public double getLearningRate() { @@ -128,8 +130,12 @@ public class PBILParameters extends AbstractGOParameters implements InterfaceGOP * @param m */ public void setMutationRate (double m) { - if (m < 0) m = 0; - if (m > 1) m = 1; + if (m < 0) { + m = 0; + } + if (m > 1) { + m = 1; + } ((PopulationBasedIncrementalLearning)this.m_Optimizer).setMutationRate(m); } @@ -144,7 +150,9 @@ public class PBILParameters extends AbstractGOParameters implements InterfaceGOP * @param m */ public void setMutateSigma (double m) { - if (m < 0) m = 0; + if (m < 0) { + m = 0; + } ((PopulationBasedIncrementalLearning)this.m_Optimizer).setMutateSigma(m); } public double getMutateSigma() { @@ -158,7 +166,9 @@ public class PBILParameters extends AbstractGOParameters implements InterfaceGOP * @param PositiveSamples */ public void setPositiveSamples (int PositiveSamples) { - if (PositiveSamples < 1) PositiveSamples = 1; + if (PositiveSamples < 1) { + PositiveSamples = 1; + } ((PopulationBasedIncrementalLearning)this.m_Optimizer).setPositiveSamples(PositiveSamples); } public int getPositiveSamples() { diff --git a/src/eva2/server/modules/SAParameters.java b/src/eva2/server/modules/SAParameters.java index 79fc7b86..07be9df6 100644 --- a/src/eva2/server/modules/SAParameters.java +++ b/src/eva2/server/modules/SAParameters.java @@ -116,7 +116,9 @@ public class SAParameters extends AbstractGOParameters implements InterfaceGOPar return ((SimulatedAnnealing)this.m_Optimizer).getAlpha(); } public void setAlpha(double a){ - if (a > 1) a = 1.0; + if (a > 1) { + a = 1.0; + } ((SimulatedAnnealing)this.m_Optimizer).setAlpha(a); } public String alphaTipText() { diff --git a/src/eva2/server/stat/AbstractStatistics.java b/src/eva2/server/stat/AbstractStatistics.java index d2faf812..ac7e77c8 100644 --- a/src/eva2/server/stat/AbstractStatistics.java +++ b/src/eva2/server/stat/AbstractStatistics.java @@ -122,19 +122,26 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter if (dataListeners==null) { dataListeners=new LinkedList(); } - if (l!=null && !dataListeners.contains(l)) dataListeners.add(l); + if (l!=null && !dataListeners.contains(l)) { + dataListeners.add(l); + } } @Override public boolean removeDataListener(InterfaceStatisticsListener l) { - if (dataListeners==null) return false; - else return dataListeners.remove(l); + if (dataListeners==null) { + return false; + } + else { + return dataListeners.remove(l); + } } private void fireDataListeners() { - if (dataListeners!=null) for (InterfaceStatisticsListener l : dataListeners) { - l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentStatDoubleData); - } + if (dataListeners!=null) { + for (InterfaceStatisticsListener l : dataListeners) { +l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentStatDoubleData); +} } } private void fireDataListenersFinalize() { @@ -142,7 +149,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter LinkedList toRemove = new LinkedList(); for (InterfaceStatisticsListener l : dataListeners) { boolean rm = l.notifyMultiRunFinished(currentStatHeader, finalObjectData); - if (rm) toRemove.add(l); + if (rm) { + toRemove.add(l); + } } for (InterfaceStatisticsListener l : toRemove) { dataListeners.remove(l); @@ -158,18 +167,19 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter * @param start if true, give the start signal, otherwise the stop signal */ private void fireDataListenersStartStop(int runNumber, boolean normal, boolean start) { - if (dataListeners!=null) for (InterfaceStatisticsListener l : dataListeners) { - if (start) { - l.notifyRunStarted(runNumber, m_StatsParams.getMultiRuns(), - currentStatHeader, currentStatMetaInfo); - } else { - l.notifyRunStopped(optRunsPerformed, normal); + if (dataListeners!=null) { + for (InterfaceStatisticsListener l : dataListeners) { + if (start) { + l.notifyRunStarted(runNumber, m_StatsParams.getMultiRuns(), + currentStatHeader, currentStatMetaInfo); + } else { + l.notifyRunStopped(optRunsPerformed, normal); // if (optRunsPerformed > 1) { - l.finalMultiRunResults(currentStatHeader, - finalObjectData); + l.finalMultiRunResults(currentStatHeader, + finalObjectData); // } - } - } +} +} } } @Override @@ -202,7 +212,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter cnt++; fname=fnameBase+"."+cnt; } - if (TRACE) System.out.println("FileName =" + fname); + if (TRACE) { + System.out.println("FileName =" + fname); + } try { resultOut = new PrintWriter(new FileOutputStream(fname)); } catch (Exception e) { @@ -211,7 +223,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter } resultOut.println("StartDate:" + startDate); resultOut.println("On Host:" + getHostName()); - } else resultOut = null; + } else { + resultOut = null; + } } /** @@ -264,7 +278,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter firstPlot = true; optRunsPerformed = 0; convergenceCnt = 0; - if (saveParams) m_StatsParams.saveInstance(); + if (saveParams) { + m_StatsParams.saveInstance(); + } initOutput(infoString); bestIndyAllRuns = null; bestFeasibleAllRuns = null; @@ -274,8 +290,12 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter runBestFitList = new ArrayList(); // if (refineMultiRuns) meanCollection = new ArrayList(); // else meanCollection = null; - if (refineMultiRuns) sumDataCollection = new ArrayList(); - else sumDataCollection = null; + if (refineMultiRuns) { + sumDataCollection = new ArrayList(); + } + else { + sumDataCollection = null; + } finalObjectData = null; @@ -293,51 +313,79 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter lastInformerList = null; lastSols = null; iterationCounter = 0; - if (printRunIntroVerbosity()) printToTextListener("\n****** Multirun "+runNumber); + if (printRunIntroVerbosity()) { + printToTextListener("\n****** Multirun "+runNumber); + } if (params != null) { - if (printRunIntroVerbosity()) printToTextListener("\nModule parameters: "); - if (printRunIntroVerbosity()) printToTextListener(BeanInspector.niceToString(params)); + if (printRunIntroVerbosity()) { + printToTextListener("\nModule parameters: "); + } + if (printRunIntroVerbosity()) { + printToTextListener(BeanInspector.niceToString(params)); + } } - if (printRunIntroVerbosity()) printToTextListener("\nStatistics parameters: "); - if (printRunIntroVerbosity()) printToTextListener(BeanInspector.niceToString(getStatisticsParameter()) + '\n'); + if (printRunIntroVerbosity()) { + printToTextListener("\nStatistics parameters: "); + } + if (printRunIntroVerbosity()) { + printToTextListener(BeanInspector.niceToString(getStatisticsParameter()) + '\n'); + } functionCalls = 0; fireDataListenersStartStop(runNumber, true, true); } @Override public void stopOptPerformed(boolean normal, String stopMessage) { - if (TRACE) System.out.println("AbstractStatistics.stopOptPerformed"); - if (lastSols==null) System.err.println("WARNING, possibly there was no call to createNextGenerationPerformed before calling stopOptPerformed (AnstractStatistics)."); + if (TRACE) { + System.out.println("AbstractStatistics.stopOptPerformed"); + } + if (lastSols==null) { + System.err.println("WARNING, possibly there was no call to createNextGenerationPerformed before calling stopOptPerformed (AnstractStatistics)."); + } if (iterationCounter < sumDataCollection.size()) { // no good: later run was shorter than the first one. What to do? Discard the longer one: - if (TRACE) System.err.println("Error in AbstractStatistics: later run was shorter than earlier one... discarding rest..."); + if (TRACE) { + System.err.println("Error in AbstractStatistics: later run was shorter than earlier one... discarding rest..."); + } for (int i=sumDataCollection.size()-1; i>=iterationCounter; i--) { sumDataCollection.remove(i); } } optRunsPerformed++; functionCallSum += functionCalls; - if (printRunStoppedVerbosity() && (stopMessage != null)) printToTextListener(" Termination message: " + stopMessage + "\n"); - if (printRunStoppedVerbosity()) printToTextListener(" Function calls run: " + functionCalls + ", sum: " + functionCallSum + "\n"); + if (printRunStoppedVerbosity() && (stopMessage != null)) { + printToTextListener(" Termination message: " + stopMessage + "\n"); + } + if (printRunStoppedVerbosity()) { + printToTextListener(" Function calls run: " + functionCalls + ", sum: " + functionCallSum + "\n"); + } // check if target zero was reached if (bestCurrentIndy != null) { if (Mathematics.norm(bestOfRunIndy.getFitness()) < this.m_StatsParams.getConvergenceRateThreshold()) { convergenceCnt++; } - if (printRunStoppedVerbosity()) printIndy("Last best", bestCurrentIndy); + if (printRunStoppedVerbosity()) { + printIndy("Last best", bestCurrentIndy); + } } if (bestOfRunIndy != null) { runBestFitList.add(bestOfRunIndy); - if (printRunStoppedVerbosity()) printIndy("Run best", bestOfRunIndy); + if (printRunStoppedVerbosity()) { + printIndy("Run best", bestOfRunIndy); + } // if (meanBestOfRunFitness==null) { // meanBestOfRunFitness=bestRunIndividual.getFitness().clone(); // } else addSecond(meanBestOfRunFitness, bestRunIndividual.getFitness()); } if (feasibleFoundAfter>0) { - if (printRunStoppedVerbosity()) printToTextListener(" Feasible ind. found after " + feasibleFoundAfter + " evaluations.\n"); + if (printRunStoppedVerbosity()) { + printToTextListener(" Feasible ind. found after " + feasibleFoundAfter + " evaluations.\n"); + } } else { - if (printRunStoppedVerbosity()) printToTextListener(" NO feasible individual found.\n"); + if (printRunStoppedVerbosity()) { + printToTextListener(" NO feasible individual found.\n"); + } } if (printRunStoppedVerbosity()) { printToTextListener(" Solution correlations (min,max,avg,med,var): " + BeanInspector.toString(((Population)lastSols).getCorrelations((Population)lastSols)) + "\n"); @@ -352,19 +400,25 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter printToTextListener("* Run best feasible individual equals best individual.\n"); } else { if (bestOfRunIndy instanceof AbstractEAIndividual) { - if (((AbstractEAIndividual)bestOfRunIndy).violatesConstraint()) - printToTextListener(" Run best individual violates constraints by " + ((AbstractEAIndividual)bestOfRunIndy).getConstraintViolation() + "\n"); - if (((AbstractEAIndividual)bestOfRunIndy).isMarkedPenalized()) - printToTextListener(" Run best individual is penalized.\n"); + if (((AbstractEAIndividual)bestOfRunIndy).violatesConstraint()) { + printToTextListener(" Run best individual violates constraints by " + ((AbstractEAIndividual)bestOfRunIndy).getConstraintViolation() + "\n"); + } + if (((AbstractEAIndividual)bestOfRunIndy).isMarkedPenalized()) { + printToTextListener(" Run best individual is penalized.\n"); + } } printIndy("Run best feasible", bestOfRunFeasibleIndy); } } } - if (finalObjectData==null) finalObjectData = new ArrayList(); + if (finalObjectData==null) { + finalObjectData = new ArrayList(); + } finalObjectData.add(currentStatObjectData); - if (!printRunStoppedVerbosity() && printFinalVerbosity()) printToTextListener("."); + if (!printRunStoppedVerbosity() && printFinalVerbosity()) { + printToTextListener("."); + } // if (currentBestFit!= null) { // if (printRunStoppedVerbosity()) printToTextListener(" Best Fitness: " + BeanInspector.toString(currentBestFit) + "\n"); // } @@ -373,7 +427,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter @Override public void postProcessingPerformed(Population resultPop) { // called from processor - if (!printRunStoppedVerbosity() && printFinalVerbosity() && optRunsPerformed >= m_StatsParams.getMultiRuns()) printToTextListener("\n"); + if (!printRunStoppedVerbosity() && printFinalVerbosity() && optRunsPerformed >= m_StatsParams.getMultiRuns()) { + printToTextListener("\n"); + } if (printRunStoppedVerbosity()) { if (resultPop!=null && (resultPop.size()>0)) { printToTextListener("Resulting population: \n"); @@ -395,7 +451,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter // if (bestCurrentIndy!=null) pop.add(bestCurrentIndy); // if (bestOfRunIndy!=null) pop.add(bestOfRunIndy); // if (bestOfRunFeasibleIndy!=null) pop.add(bestOfRunFeasibleIndy); - if (bestIndyAllRuns!=null) pop.add(bestIndyAllRuns); + if (bestIndyAllRuns!=null) { + pop.add(bestIndyAllRuns); + } return pop; } @@ -403,10 +461,16 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter printToTextListener("* " + prefix + " ind.: " + BeanInspector.toString(indy) + '\n'); printToTextListener(" solution data : " + AbstractEAIndividual.getDefaultDataString(indy) + '\n'); printToTextListener(" solution fit : " + BeanInspector.toString(indy.getFitness())); - if (!(indy instanceof AbstractEAIndividual)) printToTextListener(" - feasibility unknown\n"); + if (!(indy instanceof AbstractEAIndividual)) { + printToTextListener(" - feasibility unknown\n"); + } else { - if (((AbstractEAIndividual)indy).isMarkedPenalized() || ((AbstractEAIndividual)indy).violatesConstraint()) printToTextListener(" - infeasible\n"); - else printToTextListener("\n"); + if (((AbstractEAIndividual)indy).isMarkedPenalized() || ((AbstractEAIndividual)indy).violatesConstraint()) { + printToTextListener(" - infeasible\n"); + } + else { + printToTextListener("\n"); + } } } @@ -430,8 +494,12 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter } protected void finalizeOutput() { - if (printFinalVerbosity()) printToTextListener("*******\n Runs performed: " + optRunsPerformed + ", reached target " + convergenceCnt + " times with threshold " + m_StatsParams.getConvergenceRateThreshold() + ", rate " + convergenceCnt/(double)m_StatsParams.getMultiRuns() + '\n'); - if (printFinalVerbosity()) printToTextListener(" Average function calls: " + (functionCallSum/optRunsPerformed) + "\n"); + if (printFinalVerbosity()) { + printToTextListener("*******\n Runs performed: " + optRunsPerformed + ", reached target " + convergenceCnt + " times with threshold " + m_StatsParams.getConvergenceRateThreshold() + ", rate " + convergenceCnt/(double)m_StatsParams.getMultiRuns() + '\n'); + } + if (printFinalVerbosity()) { + printToTextListener(" Average function calls: " + (functionCallSum/optRunsPerformed) + "\n"); + } if (printFinalVerbosity() && (feasibleFoundAfterSum>=0.)) { printToTextListener(" Feasible solution found in " + numOfRunsFeasibleFound + " of " + optRunsPerformed + " runs \n"); @@ -441,19 +509,27 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter if (printFinalVerbosity() && (statDataSumOverAll != null)) { printToTextListener(" Averaged sum of run statistical data: (" + optRunsPerformed + " runs):"); for (int i=0; i1) { if (runBestFitList.size()>0) { @@ -461,27 +537,37 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter if (printFinalVerbosity()) { double[] meanBestFit=getMeanBestFit(false); printToTextListener(" MultiRun stats: Mean best fitness: " + BeanInspector.toString(meanBestFit)+"\n"); - if (meanBestFit.length==1) printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFitList, meanBestFit[0])) + "\n"); + if (meanBestFit.length==1) { + printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFitList, meanBestFit[0])) + "\n"); + } printToTextListener(" MultiRun stats: Median best fitn.: " + BeanInspector.toString(getMedianBestFit(false))+"\n"); } } - if (printFinalVerbosity() && (bestFeasibleAllRuns != null)) printIndy("Overall best feasible", bestFeasibleAllRuns); + if (printFinalVerbosity() && (bestFeasibleAllRuns != null)) { + printIndy("Overall best feasible", bestFeasibleAllRuns); + } // if ((runBestFeasibleList.size()>0) && (!equalLists(runBestFeasibleList, runBestFitList))) { // is there a difference between best feasibles and best fit? if (runBestFeasibleList.size()>0) { // always output feasible stats even if theyre equal if (printFinalVerbosity()) { double[] meanBestFeasibleFit=getMeanBestFit(true); printToTextListener(" MultiRun stats: Mean best feasible fitness (" + numOfRunsFeasibleFound + " runs): " + BeanInspector.toString(meanBestFeasibleFit)+"\n"); - if (meanBestFeasibleFit.length==1) printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFeasibleList, meanBestFeasibleFit[0])) + "\n"); + if (meanBestFeasibleFit.length==1) { + printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFeasibleList, meanBestFeasibleFit[0])) + "\n"); + } printToTextListener(" MultiRun stats: Median best feasible fitn. (: " + numOfRunsFeasibleFound + " runs): " + BeanInspector.toString(getMedianBestFit(true))+"\n"); } } if (refineMultiRuns && (sumDataCollection != null)) { - if (printFinalVerbosity()) printToTextListener(" Averaged performance:\n"); + if (printFinalVerbosity()) { + printToTextListener(" Averaged performance:\n"); + } // the summed-up values of the mean collection is divided by the number of runs for (int i=0; i= 1) l.print(s); + if (m_StatsParams.getOutputTo().getSelectedTagID() >= 1) { + l.print(s); + } } } @@ -707,7 +798,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter ArrayListheaderEntries = new ArrayList(); headerEntries.add("FunctionCalls"); for (int i=0; i headerInfo = new ArrayList(); headerInfo.add("The number of function evaluations"); for (int i=0; i iter = values.iterator(); int cnt=0; iter.next(); // skip the first field (function calls) which is not regarded here - if (!lastIsShowFull) while (iter.hasNext()) { - iter.next(); - if (!isRequestedField(cnt++)) iter.remove(); - // the cnt variable is one behind the index in the values list, because of the function calls field. - } + if (!lastIsShowFull) { + while (iter.hasNext()) { + iter.next(); + if (!isRequestedField(cnt++)) { + iter.remove(); + } + } + } return values; // return StringTools.concatValues(values, textFieldDelimiter); } @@ -851,21 +949,31 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter */ protected List getAdditionalHeaderMetaInfo(List informerList, List metaInfo) { LinkedList headers = new LinkedList(); - if (metaInfo!=null && (metaInfo.size()>0)) System.err.println("Warning, metaInfo list should be empty in AbstractStatistics.getAdditionalHeaderMetaInfo"); + if (metaInfo!=null && (metaInfo.size()>0)) { + System.err.println("Warning, metaInfo list should be empty in AbstractStatistics.getAdditionalHeaderMetaInfo"); + } for (InterfaceAdditionalPopulationInformer informer : informerList) { headers.addAll(Arrays.asList(informer.getAdditionalDataHeader())); - if (metaInfo!=null) metaInfo.addAll(Arrays.asList(informer.getAdditionalDataInfo())); + if (metaInfo!=null) { + metaInfo.addAll(Arrays.asList(informer.getAdditionalDataInfo())); + } // hdr = hdr + "\t " + informer.getAdditionalDataHeader(pop); } Iterator hIter = headers.iterator(); Iterator mIter = (metaInfo!=null) ? metaInfo.iterator() : null; - if (!lastIsShowFull) while (hIter.hasNext()) { - if (mIter!=null && mIter.hasNext()) mIter.next(); - if (!isRequestedAdditionalField(hIter.next())) { - hIter.remove(); - if (mIter!=null && mIter.hasNext()) mIter.remove(); - } - } + if (!lastIsShowFull) { + while (hIter.hasNext()) { + if (mIter!=null && mIter.hasNext()) { + mIter.next(); + } + if (!isRequestedAdditionalField(hIter.next())) { + hIter.remove(); + if (mIter!=null && mIter.hasNext()) { + mIter.remove(); + } + } + } + } return headers; } @@ -936,7 +1044,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter // if (doTextOutput()) printToTextListener(getOutputHeader(null, null)+'\n'); firstPlot = false; } - if ((iterationCounter == 0) && printHeaderByVerbosity()) printToTextListener(getOutputHeaderFieldNamesAsString(null)+'\n'); + if ((iterationCounter == 0) && printHeaderByVerbosity()) { + printToTextListener(getOutputHeaderFieldNamesAsString(null)+'\n'); + } if (doTextOutput() && printLineByVerbosity(calls)) { Pair addInfo = getOutputData(null, null); @@ -964,8 +1074,12 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter System.err.println("Error in AbstractStatistics.updateAdditionalInfo: mismatching info arrays!"); } else { for (int i=0; i informerList) { lastInformerList = informerList; - if (TRACE) printToTextListener(".. in createNextGenPerformed after " + pop.getFunctionCalls() + " evals.\n"); - if (resultOut != null) resultOut.flush(); + if (TRACE) { + printToTextListener(".. in createNextGenPerformed after " + pop.getFunctionCalls() + " evals.\n"); + } + if (resultOut != null) { + resultOut.flush(); + } if (firstPlot) { initPlots(pop, informerList); // if (doTextOutput()) printToTextListener(getOutputHeader(informer, pop)+'\n'); @@ -1094,7 +1224,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter if (iterationCounter==0) { String headerLine = StringTools.concatFields(currentStatHeader, textFieldDelimiter); - if (printHeaderByVerbosity()) printToTextListener(headerLine+'\n'); + if (printHeaderByVerbosity()) { + printToTextListener(headerLine+'\n'); + } } lastSols = (opt!=null) ? new Population(opt.getAllSolutions().getSolutions()) : pop; @@ -1131,8 +1263,12 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter // "generation performed" event the same number of times. // thus: dont do an update for events that are "too late" sumDataEntry = null; - } else sumDataEntry = sumDataCollection.get(iterationCounter); - if (sumDataEntry != null) updateSum(sumDataEntry, currentStatDoubleData); // this adds up data of a single iteration across multiple runs + } else { + sumDataEntry = sumDataCollection.get(iterationCounter); + } + if (sumDataEntry != null) { + updateSum(sumDataEntry, currentStatDoubleData); + } // this adds up data of a single iteration across multiple runs } } @@ -1149,8 +1285,12 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter // } plotCurrentResults(); fireDataListeners(); - if (TRACE) printToTextListener(".. done createNextGenPerformed after " + pop.getFunctionCalls() + " evals.\n"); - if (resultOut != null) resultOut.flush(); + if (TRACE) { + printToTextListener(".. done createNextGenPerformed after " + pop.getFunctionCalls() + " evals.\n"); + } + if (resultOut != null) { + resultOut.flush(); + } iterationCounter++; } @@ -1184,10 +1324,16 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter // ingeniously shifting i by two since the stats counter starts at 0 // after two evaluations have already happened: initialization and first optimization // this allows the last iteration to be within the displayed set if k is a divisor of whole iterations as expected - if ((i==0) || (k==0)) return true; + if ((i==0) || (k==0)) { + return true; + } else { - if (i<=2) return (i % k) == 0; // show more at the beginning (always first time) - else return ((i+2) % k) == 0; + if (i<=2) { + return (i % k) == 0; + } // show more at the beginning (always first time) + else { + return ((i+2) % k) == 0; + } } } @@ -1197,7 +1343,9 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter private static void divideMean(Double[] mean, double d) { for (int j=0; j(10); // onlineData.add(statObjects); } @@ -158,17 +168,25 @@ public class EvAJob implements Serializable, InterfaceStatisticsListener { public void notifyRunStopped(int runsPerformed, boolean completedLastRun) { numRuns=runsPerformed; lastRunIncompl = !completedLastRun; - if (TRACE) System.out.println("EvAJob.notifyRunStopped, " + runsPerformed + " " + completedLastRun); + if (TRACE) { + System.out.println("EvAJob.notifyRunStopped, " + runsPerformed + " " + completedLastRun); + } } @Override public boolean notifyMultiRunFinished(String[] header, List multiRunFinalObjDat) { fieldHeaders=header; multiRunFinalObjectData = multiRunFinalObjDat; - if (lastRunIncompl) state=StateEnum.incomplete; - else state=StateEnum.complete; + if (lastRunIncompl) { + state=StateEnum.incomplete; + } + else { + state=StateEnum.complete; + } // jobFinished=true; - if (TRACE) System.out.println("multi run finished!"); + if (TRACE) { + System.out.println("multi run finished!"); + } return true; } @@ -182,15 +200,21 @@ public class EvAJob implements Serializable, InterfaceStatisticsListener { public int getFieldIndex(String field) { if (fieldHeaders!=null) { for (int i=0; i jobsToWorkWith = new ArrayList(); for (int i=0; i commonFields = getCommonFields(jobsToWorkWith); - if (commonFields!=null && !commonFields.isEmpty()) for (String field : commonFields) { - textout.println("###\t"+ field + " statistical evaluation"); + if (commonFields!=null && !commonFields.isEmpty()) { + for (String field : commonFields) { +textout.println("###\t"+ field + " statistical evaluation"); - if(singleStats.length > 0){ - textout.println("one-sampled statistics"); - for (int j=-1; j 0){ - textout.println("two-sampled stats:"); - for(int i=0; i 0){ +textout.println("one-sampled statistics"); +for (int j=-1; j 0){ +textout.println("two-sampled stats:"); +for(int i=0; iavg2) return "1"; - else return "0"; + if (avg1avg2) { + return "1"; + } + else { + return "0"; + } } /** @@ -314,13 +333,17 @@ public class EvAStatisticalEvaluation { } } else { for (String f : lSoFar) { - if (j.getFieldIndex(f)>=0) tmpL.add(f); + if (j.getFieldIndex(f)>=0) { + tmpL.add(f); + } } lSoFar=tmpL; tmpL = new LinkedList(); } } - if (TRACE) System.out.println("Common fields are " + BeanInspector.toString(lSoFar)); + if (TRACE) { + System.out.println("Common fields are " + BeanInspector.toString(lSoFar)); + } return lSoFar; } diff --git a/src/eva2/server/stat/GraphSelectionEnum.java b/src/eva2/server/stat/GraphSelectionEnum.java index 76896d23..cde11637 100644 --- a/src/eva2/server/stat/GraphSelectionEnum.java +++ b/src/eva2/server/stat/GraphSelectionEnum.java @@ -31,7 +31,9 @@ public enum GraphSelectionEnum { if (GraphSelectionEnum.values().length != toolTips.length) { System.err.println("Error, mismatching length of info strings in GraphSelectionEnum"); return null; - } else return toolTips; + } else { + return toolTips; + } } // public static boolean doPlotCurrentBest(StringSelection sel) { diff --git a/src/eva2/server/stat/MovingAverage.java b/src/eva2/server/stat/MovingAverage.java index 5116895c..3b3fbd61 100644 --- a/src/eva2/server/stat/MovingAverage.java +++ b/src/eva2/server/stat/MovingAverage.java @@ -61,8 +61,9 @@ public class MovingAverage { m_Average = 0; int tail = m_index; //if (m_overflow=true) - if (m_overflow) // MK 12/06 - tail = m_size; + if (m_overflow) { + tail = m_size; + } for (int i=0;i informerList) { - if (runnumber==0) bestIndividualAllover = null; + if (runnumber==0) { + bestIndividualAllover = null; + } bestRunIndy = null; } @@ -101,11 +109,15 @@ public class StatisticsDummy implements InterfaceStatistics, InterfaceTextListen @Override public void print(String str) { - if (consoleOut) System.out.print(str); + if (consoleOut) { + System.out.print(str); + } } @Override public void println(String str) { - if (consoleOut) System.out.println(str); + if (consoleOut) { + System.out.println(str); + } } @Override diff --git a/src/eva2/server/stat/StatisticsStandalone.java b/src/eva2/server/stat/StatisticsStandalone.java index fadde0e5..e9ecc719 100644 --- a/src/eva2/server/stat/StatisticsStandalone.java +++ b/src/eva2/server/stat/StatisticsStandalone.java @@ -66,8 +66,12 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac 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)); + if (resultFileName==null) { + m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_WINDOW); + } + else { + m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_FILE)); + } } public StatisticsStandalone() { @@ -101,7 +105,9 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac @Override public void plotSpecificData(PopulationInterface pop, List informerList) { - if (TRACE) System.out.println(" m_SpecificData !!"); + if (TRACE) { + System.out.println(" m_SpecificData !!"); + } double[] specificData = pop.getSpecificData(); if (specificData != null) { for (int i = 0; i < specificData.length; i++) { diff --git a/src/eva2/tools/BasicResourceLoader.java b/src/eva2/tools/BasicResourceLoader.java index 7384019c..080ce9e0 100644 --- a/src/eva2/tools/BasicResourceLoader.java +++ b/src/eva2/tools/BasicResourceLoader.java @@ -204,7 +204,9 @@ public class BasicResourceLoader implements ResourceLoader private static void trimAll(String[] entries) { for (int i=0; i= start) && (data[i][col] <= end)) { - if (cnt == 0) startIndex = i; + if (cnt == 0) { + startIndex = i; + } cnt++; - } else if (cnt > 0) break; + } else if (cnt > 0) { + break; + } } double[][] selData = new double[cnt][data[0].length]; @@ -271,8 +277,12 @@ public class BasicResourceLoader implements ResourceLoader 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]); + 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; @@ -281,8 +291,12 @@ public class BasicResourceLoader implements ResourceLoader } 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]]); + 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; @@ -302,7 +316,9 @@ public class BasicResourceLoader implements ResourceLoader int i=0; if (pref != null) { for (String prefix : pref) { - if (str.startsWith(prefix)) return i; + if (str.startsWith(prefix)) { + return i; + } i++; } } @@ -636,14 +652,20 @@ public class BasicResourceLoader implements ResourceLoader if (bytes != null) { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); prop.load(bais); - if (prop != null) return prop; + if (prop != null) { + return prop; + } } ///////////// int slInd = resourceName.lastIndexOf('/'); String planBResName; - if (slInd != -1) planBResName = resourceName.substring(slInd + 1); - else planBResName = resourceName; + 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()) { @@ -652,7 +674,9 @@ public class BasicResourceLoader implements ResourceLoader } 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."); + } else { + System.err.println("Warning in readProperties: neither " + resourceName + " nor " + planBResName + " could be read."); + } return userProps; } diff --git a/src/eva2/tools/CubicSpline.java b/src/eva2/tools/CubicSpline.java index 32368147..6fe41f08 100644 --- a/src/eva2/tools/CubicSpline.java +++ b/src/eva2/tools/CubicSpline.java @@ -32,7 +32,9 @@ public class CubicSpline{ // 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"); + 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]; @@ -58,8 +60,12 @@ public class CubicSpline{ // METHODS // Resets the x y data arrays - primarily for use in BiCubicSpline public void resetData(double[] x, double[] y){ - if(x.length!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length"); - if(this.npoints!=x.length)throw new IllegalArgumentException("Original array length not matched by new array length"); + if(x.length!=y.length) { + throw new IllegalArgumentException("Arrays x and y are of different length"); + } + if(this.npoints!=x.length) { + throw new IllegalArgumentException("Original array length not matched by new array length"); + } for(int i=0; isamples.length) K = samples.length; + if (TRACE) { + System.out.println("K"+K); + } + if (K>samples.length) { + K = samples.length; + } int counter=0; m_C = new double[K][]; for (int i=0;i x2 ) - return -1; - if (x1 <= x2 ) - return 1; + if (x1 > x2 ) { + return -1; + } + if (x1 <= x2 ) { + return 1; + } return 0; } /** diff --git a/src/eva2/tools/MultirunRefiner.java b/src/eva2/tools/MultirunRefiner.java index 33f09b9f..a199b400 100644 --- a/src/eva2/tools/MultirunRefiner.java +++ b/src/eva2/tools/MultirunRefiner.java @@ -42,13 +42,17 @@ public class MultirunRefiner { public MultirunRefiner(File f) { starter(); - if (!readFile(f)) System.err.println("Error, couldnt open file " + f); + if (!readFile(f)) { + System.err.println("Error, couldnt open file " + f); + } } public MultirunRefiner(String fileName) { starter(); File f=new File(fileName); - if (!readFile(f)) System.err.println("Error, couldnt open file " + f); + if (!readFile(f)) { + System.err.println("Error, couldnt open file " + f); + } } public MultirunRefiner(String text, int numRuns) { @@ -255,11 +259,15 @@ public class MultirunRefiner { if (numExp==1) { mean = new double[3]; result.add(iteration, mean); - } else mean = result.get(iteration); + } else { + mean = result.get(iteration); + } mean[0] += tmp[1]; mean[1] += tmp[2]; mean[2] += tmp[3]; - } else System.err.println("Error in MultiRunRefiner!"); + } else { + System.err.println("Error in MultiRunRefiner!"); + } iteration++; } } @@ -349,7 +357,9 @@ public class MultirunRefiner { to++; } if (to < searchme.length()) { - if (to == searchme.length()-1) to = searchme.length(); + if (to == searchme.length()-1) { + to = searchme.length(); + } tmpString = searchme.substring(from, to); try { tmpOutput.add(i, new Double(tmpString)); diff --git a/src/eva2/tools/PairComparator.java b/src/eva2/tools/PairComparator.java index 7359033f..66034256 100644 --- a/src/eva2/tools/PairComparator.java +++ b/src/eva2/tools/PairComparator.java @@ -33,8 +33,14 @@ public class PairComparator implements Comparator> { return 0; } - if (d1==d2) return 0; - else if (d1 > d2) return 1; - else return -1; + 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 eed29971..7461fc6b 100644 --- a/src/eva2/tools/ReflectPackage.java +++ b/src/eva2/tools/ReflectPackage.java @@ -63,7 +63,9 @@ public class ReflectPackage { } dir = path + "/" + pckgname.replace(".","/"); - if (TRACE) System.out.println(".. opening " + path); + if (TRACE) { + System.out.println(".. opening " + path); + } directory = new File(dir); @@ -78,7 +80,9 @@ public class ReflectPackage { // 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); + if (TRACE) { + System.err.println(directory.getPath() + " doesnt exist in " + path + ", dir was " + dir); + } return 0; } } catch(ClassNotFoundException e) { @@ -136,7 +140,9 @@ public class ReflectPackage { } private static int addClass(HashSet set, Class cls) { - if (TRACE) System.out.println("adding class " + cls.getName()); + 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; @@ -150,7 +156,9 @@ public class ReflectPackage { ArrayList assClasses = new ArrayList(); for (int i=0; i packageName.length()+1) isInSubPackage = true; - else isInSubPackage = false; + if (lastDash > packageName.length()+1) { + isInSubPackage = true; + } + else { + isInSubPackage = false; + } } if (includeSubs || !isInSubPackage) { // take the right ones String clsName = jarEntryName.replace("/", "."); @@ -195,7 +209,9 @@ public class ReflectPackage { if (reqSuperCls.isAssignableFrom(cls)) { cntAdded += addClass(set, cls); } - } else 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) { @@ -211,7 +227,9 @@ public class ReflectPackage { 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..."); + } else if (missedJarsOnClassPath == 2) { + System.err.println("Couldnt open jar from class path more than once..."); + } //e.printStackTrace(); } return cntAdded; @@ -249,16 +267,24 @@ public class ReflectPackage { } catch (Exception e) { System.err.println(e.getMessage()); } - } else dynCP = getClassPathElements(); + } else { + dynCP = getClassPathElements(); + } } - if (TRACE) System.out.println("classpath is " + classPath); + if (TRACE) { + System.out.println("classpath is " + classPath); + } 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()); + if (TRACE) { + System.out.println("requesting classes assignable from " + reqSuperCls.getName()); + } return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, reqSuperCls); } @@ -506,14 +558,17 @@ public class ReflectPackage { 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); - } + 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!"); diff --git a/src/eva2/tools/SelectedTag.java b/src/eva2/tools/SelectedTag.java index e4d76572..35149f3c 100644 --- a/src/eva2/tools/SelectedTag.java +++ b/src/eva2/tools/SelectedTag.java @@ -53,7 +53,9 @@ public class SelectedTag implements java.io.Serializable { m_Selected = i; } } - if (m_Selected == -1) throw new IllegalArgumentException("Selected tag is not valid"); + if (m_Selected == -1) { + throw new IllegalArgumentException("Selected tag is not valid"); + } } private void init(int selID, String[] tagStrings) { @@ -61,9 +63,13 @@ public class SelectedTag implements java.io.Serializable { 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 (selID == i) { + m_Selected = i; + } } - if (m_Selected == -1) throw new IllegalArgumentException("Selected tag is not valid"); + if (m_Selected == -1) { + throw new IllegalArgumentException("Selected tag is not valid"); + } } //~ Methods //////////////////////////////////////////////////////////////// @@ -75,7 +81,9 @@ public class SelectedTag implements java.io.Serializable { * @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 ((i >= 0) && (i < this.m_Tags.length)) { + this.m_Selected = i; + } return this; } @@ -127,7 +135,9 @@ public class SelectedTag implements java.io.Serializable { public int getTagIDByString(String str) { for (int i=0; i=args.length)) break; // if a key was found look at next argument + 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 + 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) { @@ -150,7 +162,9 @@ public final class StringTools { } } } - if (!found) unrecogs.add(i); + if (!found) { + unrecogs.add(i); + } } return unrecogs.toArray(new Integer[unrecogs.size()]); } @@ -193,9 +207,13 @@ public final class StringTools { * @return */ public static String checkSingleStringArg(String key, Object object, int i) { - if (object==null) return null; + if (object==null) { + return null; + } if (object instanceof String) { - if (i==0) return (String)object; + 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; @@ -203,7 +221,9 @@ public final class StringTools { } if (object instanceof String[]) { String[] arr = (String[])object; - if (i0) res.append("\n"); // insert newline + if (res.length()>0) { + res.append("\n"); + } // insert newline res.append(rest.substring(0, nextBreak+1)); rest = rest.substring(nextBreak+1); } @@ -257,7 +281,9 @@ public final class StringTools { for (int i=0; i=0 && (index <= endIndex)) return index; + if (index>=0 && (index <= endIndex)) { + return index; + } } return -1; } diff --git a/src/eva2/tools/TXTFileFilter.java b/src/eva2/tools/TXTFileFilter.java index 706f2755..fdfae8dc 100644 --- a/src/eva2/tools/TXTFileFilter.java +++ b/src/eva2/tools/TXTFileFilter.java @@ -27,11 +27,17 @@ public class TXTFileFilter extends FileFilter { @Override public boolean accept(java.io.File file) { - if (file.isDirectory()) return true; + if (file.isDirectory()) { + 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"))) return true; - else return false; + (fileName.substring(fileName.lastIndexOf('.')+1, fileName.length()).equals("txt"))) { + return true; + } + else { + return false; + } } @Override diff --git a/src/eva2/tools/ToolBox.java b/src/eva2/tools/ToolBox.java index bda1b9fe..bfe1941d 100644 --- a/src/eva2/tools/ToolBox.java +++ b/src/eva2/tools/ToolBox.java @@ -144,13 +144,17 @@ public final class ToolBox { * @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 (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); + if (row[i]<=upper && row[i]>=lower) { + matching.add(row); + } } return matching.toArray(new double[matching.size()][dat[0].length]); diff --git a/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java b/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java index 22296986..9820fd29 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java +++ b/src/eva2/tools/chart2d/Chart2DDPointContentSelectable.java @@ -33,11 +33,17 @@ public class Chart2DDPointContentSelectable implements InterfaceDPointWithConten @Override public void paint( Graphics g ){ Color prev = g.getColor(); - if (this.m_Indy.isMarked()) this.m_Fill = Color.RED; - else this.m_Fill = Color.LIGHT_GRAY; + if (this.m_Indy.isMarked()) { + this.m_Fill = Color.RED; + } + 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); - if (this.m_Border != null) g.setColor(m_Border); + 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.setColor(prev); } diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java b/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java index 0826556d..fda8dd8e 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconCircle.java @@ -27,7 +27,9 @@ public class Chart2DDPointIconCircle implements DPointIcon { g.setColor(m_Fill); 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); + 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.setColor(prev); } diff --git a/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java b/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java index 7514819f..67dbcbd0 100644 --- a/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java +++ b/src/eva2/tools/chart2d/Chart2DDPointIconPoint.java @@ -28,7 +28,9 @@ public class Chart2DDPointIconPoint implements DPointIcon { g.setColor(m_Fill); 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); + 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.setColor(prev); } diff --git a/src/eva2/tools/chart2d/DArea.java b/src/eva2/tools/chart2d/DArea.java index 762b8010..2ced7acd 100644 --- a/src/eva2/tools/chart2d/DArea.java +++ b/src/eva2/tools/chart2d/DArea.java @@ -181,14 +181,18 @@ public class DArea extends JComponent implements DParent, Printable { */ 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())); + 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; } @@ -211,8 +215,9 @@ public class DArea extends JComponent implements DParent, Printable { * @return the maxmal x-value */ public double getMaxX() { - if (max_x != null) - return max_x.doubleValue(); + if (max_x != null) { + return max_x.doubleValue(); + } return 0; } @@ -222,8 +227,9 @@ public class DArea extends JComponent implements DParent, Printable { * @return the maximal y-value */ public double getMaxY() { - if (max_y != null) - return max_y.doubleValue(); + if (max_y != null) { + return max_y.doubleValue(); + } return 0; } @@ -277,8 +283,9 @@ public class DArea extends JComponent implements DParent, Printable { * @return the minmal x-value */ public double getMinX() { - if (min_x != null) - return min_x.doubleValue(); + if (min_x != null) { + return min_x.doubleValue(); + } return 0; } @@ -288,8 +295,9 @@ public class DArea extends JComponent implements DParent, Printable { * @return the minmal y-value */ public double getMinY() { - if (min_y != null) - return min_y.doubleValue(); + if (min_y != null) { + return min_y.doubleValue(); + } return 0; } @@ -301,14 +309,18 @@ public class DArea extends JComponent implements DParent, Printable { 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()); + 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; } @@ -362,8 +374,9 @@ public class DArea extends JComponent implements DParent, Printable { */ @Override public void paint(Graphics g) { - if (TRACE) - System.out.println("DArea.paint(Graphics)"); + if (TRACE) { + System.out.println("DArea.paint(Graphics)"); + } if (auto_focus) { container.restore(); visible_rect = (DRectangle) container.getRectangle().clone(); @@ -376,11 +389,13 @@ public class DArea extends JComponent implements DParent, Printable { super.paint(g); measures.setGraphics(g); - if (grid.isVisible() && !grid_to_front) - paintGrid(measures); + if (grid.isVisible() && !grid_to_front) { + paintGrid(measures); + } container.paint(measures); - if (grid.isVisible() && grid_to_front) - paintGrid(measures); + if (grid.isVisible() && grid_to_front) { + paintGrid(measures); + } } /** @@ -389,8 +404,9 @@ public class DArea extends JComponent implements DParent, Printable { * auto_grid option */ private void paintGrid(DMeasures m) { - if (TRACE) - System.out.println("DArea.paintGrid(DMeasures)"); + if (TRACE) { + System.out.println("DArea.paintGrid(DMeasures)"); + } grid.rectangle = getDRectangle(); if (auto_grid) { Border b = getBorder(); @@ -419,14 +435,16 @@ public class DArea extends JComponent implements DParent, Printable { * the measures of the area */ private void paintGrid(ScaledBorder sb, DMeasures m) { - if (TRACE) - System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)"); + 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); + if (m.x_scale == null && m.y_scale == null) { + grid.paint(m); + } else {// selber malen Graphics g = m.g; @@ -437,10 +455,12 @@ public class DArea extends JComponent implements DParent, Printable { 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++; + 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 ); @@ -450,15 +470,17 @@ public class DArea extends JComponent implements DParent, Printable { 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); + 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); + 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); } @@ -482,20 +504,25 @@ public class DArea extends JComponent implements DParent, 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; + 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; + 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; + if (sb != null) { + ((ScaledBorder) sb).show_outer_border = true; + } return ret; } @@ -554,20 +581,24 @@ public class DArea extends JComponent implements DParent, Printable { */ @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(); + 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(); + 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 @@ -579,8 +610,9 @@ public class DArea extends JComponent implements DParent, Printable { @Override public void restoreBorder() { dborder = container.getDBorder(); - if (TRACE) - System.out.println("DArea.restoreBorder -> " + dborder); + if (TRACE) { + System.out.println("DArea.restoreBorder -> " + dborder); + } } /** @@ -592,8 +624,9 @@ public class DArea extends JComponent implements DParent, Printable { public void setAutoFocus(boolean b) { boolean old = auto_focus; auto_focus = b; - if (old != b) - repaint(); + if (old != b) { + repaint(); + } } /** @@ -608,8 +641,9 @@ public class DArea extends JComponent implements DParent, Printable { grid.rectangle = getDRectangle(); grid.setVisible(true); } - if (b == auto_grid) - return; + if (b == auto_grid) { + return; + } auto_grid = b; repaint(); } @@ -650,8 +684,9 @@ public class DArea extends JComponent implements DParent, Printable { public void setGridToFront(boolean aFlag) { boolean old = grid_to_front; grid_to_front = aFlag; - if (old != aFlag && grid.isVisible()) - repaint(); + if (old != aFlag && grid.isVisible()) { + repaint(); + } } /** @@ -661,8 +696,9 @@ public class DArea extends JComponent implements DParent, Printable { * visible or not */ public void setGridVisible(boolean aFlag) { - if (TRACE) - System.out.println("DArea.setGridVisisble: " + aFlag); + if (TRACE) { + System.out.println("DArea.setGridVisisble: " + aFlag); + } grid.rectangle = getDRectangle(); grid.setVisible(aFlag); } @@ -674,12 +710,14 @@ public class DArea extends JComponent implements DParent, Printable { * maximal number of grid lines */ public void setMaxGrid(int no) { - if (no < 1) - return; + if (no < 1) { + return; + } int old = max_grid; max_grid = no; - if (old != no) - repaint(); + if (old != no) { + repaint(); + } } /** @@ -690,9 +728,10 @@ public class DArea extends JComponent implements DParent, Printable { * 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."); + if (max < min_rect.getX() + min_rect.getWidth()) { + throw new IllegalArgumentException( + "Maximal x-value axes intersects minmal rectangle."); + } max_x = new Double(max); } @@ -705,9 +744,10 @@ public class DArea extends JComponent implements DParent, Printable { * 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."); + if (may < min_rect.getY() + min_rect.getHeight()) { + throw new IllegalArgumentException( + "Maximal y-value axes intersects minmal rectangle."); + } max_y = new Double(may); } @@ -730,10 +770,12 @@ public class DArea extends JComponent implements DParent, Printable { * 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(); + if (rect.isEmpty()) { + min_rect = DEFAULT_MIN_RECT; + } + else { + min_rect = (DRectangle) rect.clone(); + } } /** @@ -744,9 +786,10 @@ public class DArea extends JComponent implements DParent, Printable { * the minimal x-value */ public void setMinX(double mix) { - if (mix > min_rect.getX()) - throw new IllegalArgumentException( - "Mimimal y-value axes intersects minmal rectangle."); + if (mix > min_rect.getX()) { + throw new IllegalArgumentException( + "Mimimal y-value axes intersects minmal rectangle."); + } min_x = new Double(mix); } @@ -758,9 +801,10 @@ public class DArea extends JComponent implements DParent, Printable { * the minimal y-value */ public void setMinY(double miy) { - if (miy > min_rect.getY()) - throw new IllegalArgumentException( - "Mimimal y-value axes intersects minmal rectangle."); + if (miy > min_rect.getY()) { + throw new IllegalArgumentException( + "Mimimal y-value axes intersects minmal rectangle."); + } min_y = new Double(miy); } @@ -789,12 +833,14 @@ public class DArea extends JComponent implements DParent, Printable { * 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 (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) { @@ -813,8 +859,9 @@ public class DArea extends JComponent implements DParent, Printable { * the scale function for the x-axis */ public void setXScale(DFunction x_s) { - if (x_s == null && measures.x_scale == null) - return; + if (x_s == null && measures.x_scale == null) { + return; + } measures.x_scale = x_s; repaint(); } @@ -828,8 +875,9 @@ public class DArea extends JComponent implements DParent, Printable { * the scale function for the y-axis */ public void setYScale(DFunction y_s) { - if (y_s == null && measures.y_scale == null) - return; + 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 4673c6dd..7e9031ae 100644 --- a/src/eva2/tools/chart2d/DArray.java +++ b/src/eva2/tools/chart2d/DArray.java @@ -45,10 +45,14 @@ public class DArray implements DIntDoubleMap{ * @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"); + 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; @@ -62,14 +66,20 @@ public class DArray implements DIntDoubleMap{ */ @Override public boolean setImage(int source, double image){ - if(source<0 || source>=size) throw - new ArrayIndexOutOfBoundsException(source); + 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; + if( value[source] == min || value[source] == max || (value[source]==minPositive)) { + restore = true; + } value[source] = image; - if( restore ) min_max_changed = restore() || min_max_changed; + if( restore ) { + min_max_changed = restore() || min_max_changed; + } return min_max_changed; } @@ -86,8 +96,12 @@ public class DArray implements DIntDoubleMap{ // } @Override public double getImage(int source){ - if(source<0) new ArrayIndexOutOfBoundsException(source); - if(source>=size && size > 1) return value[size-1]; + if(source<0) { + new ArrayIndexOutOfBoundsException(source); + } + if(source>=size && size > 1) { + return value[size-1]; + } return value[source]; } @@ -103,13 +117,17 @@ public class DArray implements DIntDoubleMap{ public boolean addImage(double image){ if( size >= value.length ){ int new_length = (int)(value.length * capacity_multiplier); - if( !(new_length > value.length) ) new_length++; + 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;} + 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; } @@ -136,17 +154,27 @@ public class DArray implements DIntDoubleMap{ */ @Override public boolean restore(){ - if( size == 0 ) return false; + 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]; + if (value[i]>0 && (value[i] max ) { + max = value[i]; + } } - if (Double.isInfinite(minPositive)) minPositive=-1; + if (Double.isInfinite(minPositive)) { + minPositive=-1; + } return (old_min != min) || (old_max != max); } @@ -166,8 +194,10 @@ public class DArray implements DIntDoubleMap{ */ @Override public double getMinImageValue(){ - if( size == 0 ) throw - new IllegalArgumentException("DArray is empty. No minimal value exists"); + if( size == 0 ) { + throw +new IllegalArgumentException("DArray is empty. No minimal value exists"); + } return min; } @@ -177,8 +207,10 @@ public class DArray implements DIntDoubleMap{ */ @Override public double getMinPositiveImageValue() { - if ( size==0) throw - new IllegalArgumentException("DArray is empty. No minimal value exists"); + if ( size==0) { + throw + new IllegalArgumentException("DArray is empty. No minimal value exists"); + } return (minPositive < 0) ? max : minPositive; } /** @@ -188,8 +220,10 @@ public class DArray implements DIntDoubleMap{ */ @Override public double getMaxImageValue(){ - if( size == 0 ) throw - new IllegalArgumentException("DArray is empty. No maximal value exists"); + if( size == 0 ) { + throw +new IllegalArgumentException("DArray is empty. No maximal value exists"); + } return max; } @@ -203,14 +237,26 @@ public class DArray implements DIntDoubleMap{ */ @Override public boolean equals(Object o){ - if( !(o instanceof DArray) ) return false; + 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; + 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 x + width ) return false; - if( p.y > y + height ) return false; + 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; } @@ -87,24 +109,32 @@ public class DRectangle extends DComponent public void setHeight(double h) { if (Double.isInfinite(h) || Double.isNaN(h)) { System.err.println("Warning, infinite vaule for height!"); - } else height = h; + } 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; + } 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; + } 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; + } else { + y = v; + } } /** @@ -115,30 +145,56 @@ public class DRectangle extends DComponent * @return */ private boolean contains( double ox, double oy ){ - if (( ox < x ) || ( oy < y ) || ( ox > x + width ) || ( oy > y + height )) return false; - else return true; + 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; + 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; + 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(); + 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; @@ -148,12 +204,18 @@ public class DRectangle extends DComponent 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; + 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; + } } /** @@ -167,8 +229,12 @@ public class DRectangle extends DComponent EVAERROR.errorMsgOnce("Warning, inserted invalid point (NaN/infinity) in " + this.getClass().getSimpleName()); return false; } - if( isAll() ) return false; - if( contains( p ) ) return false; + if( isAll() ) { + return false; + } + if( contains( p ) ) { + return false; + } if( isEmpty() ){ x = p.x; y = p.y; width = height = 0; status = PART; @@ -178,12 +244,16 @@ public class DRectangle extends DComponent width += x - p.x; x = p.x; } - else if( p.x > x + width ) width = p.x - 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; + else if( p.y > y + height ) { + height = p.y - y; + } return true; } @@ -195,7 +265,9 @@ public class DRectangle extends DComponent * @return true if the size changed */ public boolean insert( DRectangle rect ){ - if( isAll() || rect.isEmpty() ) return false; + 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; @@ -212,7 +284,9 @@ public class DRectangle extends DComponent public Object clone(){ DRectangle copy = new DRectangle( x, y, width, height ); copy.status = status; - if( color != null ) copy.color = new Color( color.getRGB() ); + if( color != null ) { + copy.color = new Color( color.getRGB() ); + } return copy; } @@ -229,11 +303,21 @@ public class DRectangle extends DComponent } 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; + 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; } diff --git a/src/eva2/tools/chart2d/ScaledBorder.java b/src/eva2/tools/chart2d/ScaledBorder.java index 68387011..21fb9051 100644 --- a/src/eva2/tools/chart2d/ScaledBorder.java +++ b/src/eva2/tools/chart2d/ScaledBorder.java @@ -211,12 +211,18 @@ public class ScaledBorder implements Border @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height){ - if( under_construction ) System.out.println("ScaledBorder.paintBorder()"); + 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(); + 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 ); @@ -283,10 +289,11 @@ public class ScaledBorder implements Border 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( 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; @@ -312,7 +319,9 @@ public class ScaledBorder implements Border * @param insets */ private void drawYValues( Graphics g, Insets insets){ - if( under_construction ) System.out.println("ScaledBorder.drawYValues()"); + if( under_construction ) { + System.out.println("ScaledBorder.drawYValues()"); + } FontMetrics fm = g.getFontMetrics(); int fontAsc = fm.getAscent(), v2m = fm.stringWidth("0") / y_values2marker; @@ -327,11 +336,17 @@ public class ScaledBorder implements Border 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 ); + 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; + 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 ){ } @@ -355,21 +370,31 @@ public class ScaledBorder implements Border } 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; + 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); + 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()"); + if( under_construction ) { + System.out.println("ScaledBorder.drawXValues()"); + } FontMetrics fm = g.getFontMetrics(); double mx = cd.width / src_rect.width; @@ -377,13 +402,17 @@ public class ScaledBorder implements Border 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++; + 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); + 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 ){ } @@ -396,8 +425,12 @@ public class ScaledBorder implements Border } 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; + 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; @@ -408,28 +441,40 @@ public class ScaledBorder implements Border src_dX = aBitBigger( src_dX ); n = (int)( src_rect.x / src_dX ); - if( n * src_dX < src_rect.x ) n++; + 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 ); + 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; + 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( !suits ) { + ok = false; + } + else { + ok = true; + } } - if( src_dX < minimal_increment ) src_dX = minimal_increment; + if( src_dX < minimal_increment ) { + src_dX = minimal_increment; + } return src_dX; } @@ -442,20 +487,30 @@ public class ScaledBorder implements Border * @return the displayable value */ public static double aBitBigger( double min ){ - if( min <= 0 || Double.isInfinite(min) || Double.isNaN(min)) return 1; + 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; + 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; + if( d <= min ) { + d *= 2.5; + } + if( d <= min ) { + d *= 2; + } } } return d; @@ -494,8 +549,12 @@ public class ScaledBorder implements Border * @param next index of the pattern to switch to */ protected void setNextPattern(boolean xOrY, int next) { - if (xOrY) nextXPattern=next; - else nextYPattern=next; + if (xOrY) { + nextXPattern=next; + } + else { + nextYPattern=next; + } toggleDecPattern(xOrY); } @@ -526,8 +585,12 @@ public class ScaledBorder implements Border * @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); + if (bXorY) { + ((java.text.DecimalFormat)format_x).applyPattern(pattern); + } + else { + ((java.text.DecimalFormat)format_y).applyPattern(pattern); + } } /** @@ -537,15 +600,23 @@ public class ScaledBorder implements Border */ @Override public Insets getBorderInsets(Component c){ - if( under_construction ) System.out.println("ScaledBorder.getBorderInsets()"); - if( !do_refresh && old_insets != null ) return old_insets; + if( under_construction ) { + System.out.println("ScaledBorder.getBorderInsets()"); + } + if( !do_refresh && old_insets != null ) { + return old_insets; + } Graphics g = c.getGraphics(); Insets insets = new Insets(0, 0, 0, 0); - if( show_outer_border ) insets = outer_border.getBorderInsets( c ); + if( show_outer_border ) { + insets = outer_border.getBorderInsets( c ); + } - if( g == null ) return insets; + if( g == null ) { + return insets; + } FontMetrics fm = g.getFontMetrics(); // int fontAsc = fm.getAscent(); @@ -561,18 +632,26 @@ public class ScaledBorder implements Border } // left: - if( y_label != null ) insets.left += fm.getAscent() + fm.getDescent(); + 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; + 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 (((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!"); } @@ -580,9 +659,13 @@ public class ScaledBorder implements Border // 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 ); + if( y_scale != null ) { + v = y_scale.getImageOf( v ); + } int w = fm.stringWidth( format_y.format(v) ); - if( w > maxWidth ) maxWidth = w; + if( w > maxWidth ) { + maxWidth = w; + } // avoid nearly endless loop for large src_rect.y value and small src_dY } @@ -590,20 +673,30 @@ public class ScaledBorder implements Border // bottom: insets.bottom += 1 + fontHeight + x_label2border; - if( x_label != null ) insets.bottom += fontHeight; + if( x_label != null ) { + insets.bottom += fontHeight; + } // top: - if( show_arrows ) insets.top += y_values2arrow + arrow_length; + if( show_arrows ) { + insets.top += y_values2arrow + arrow_length; + } insets.top += axis2border; // right: - if( show_arrows ) insets.right += x_values2arrow + arrow_length; + 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 ++; + if( k < 0 ) { + k ++; + } int w = fm.stringWidth( format_x.format(k * src_dX) ); - if( w / 2 > insets.right ) insets.right = w / 2; + 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 d234de83..b8c8b55f 100644 --- a/src/eva2/tools/chart2d/SlimRect.java +++ b/src/eva2/tools/chart2d/SlimRect.java @@ -31,8 +31,12 @@ public class SlimRect { * @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; + if (( ox < x ) || ( oy < y ) || ( ox > x + width ) || ( oy > y + height )) { + return false; + } + else { + return true; + } } /** @@ -92,12 +96,18 @@ public class SlimRect { 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; + 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; + } } /** diff --git a/src/eva2/tools/jproxy/ComAdapter.java b/src/eva2/tools/jproxy/ComAdapter.java index 0428bc18..eab904b9 100644 --- a/src/eva2/tools/jproxy/ComAdapter.java +++ b/src/eva2/tools/jproxy/ComAdapter.java @@ -47,8 +47,9 @@ public class ComAdapter { * */ public static ComAdapter getInstance() { - if (m_instance != null) - return m_instance; + if (m_instance != null) { + return m_instance; + } m_instance = new ComAdapter(); return m_instance; } @@ -150,8 +151,9 @@ public class ComAdapter { RMIInvocationHandler ret = null; while (ret == null) { ret = getConnection(hostName).getRMIHandler(c); - if (ret == null) - System.out.println("Error in getRMIHandler"); + if (ret == null) { + System.out.println("Error in getRMIHandler"); + } } return ret; } @@ -276,8 +278,9 @@ public class ComAdapter { * */ public String[] getAvailableHostNameList() { - if (m_AvailableHostNameList.size() == 0) - evalAvailableHostNameList(); + if (m_AvailableHostNameList.size() == 0) { + evalAvailableHostNameList(); + } String[] ret = new String[m_AvailableHostNameList.size()]; m_AvailableHostNameList.toArray(ret); return ret; @@ -371,8 +374,9 @@ public class ComAdapter { } int ret = 0; for (int i = 0; i < list.length; i++) { - if (list[i].indexOf(MainAdapterImpl.MAIN_ADAPTER_NAME) != -1) - ret++; + if (list[i].indexOf(MainAdapterImpl.MAIN_ADAPTER_NAME) != -1) { + ret++; + } } System.err.println("error in ComAdapter.getNumberOfServersonHost"); //System.out.println(" ret === "+ret); @@ -507,7 +511,9 @@ public class ComAdapter { // search for an already established connection to the given host // and return it if found RMIConnection ret = (RMIConnection) m_Connections.get(i); - if (Host.equals(ret.getHostName())) return ret; + if (Host.equals(ret.getHostName())) { + return ret; + } } // else create and add new RMIConnection RMIConnection ret = null; @@ -517,12 +523,17 @@ public class ComAdapter { new MainAdapterClientImpl("localhost")); } else { MainAdapter Adapter = (MainAdapter)createRMIMainConnect(Host); - if (Adapter != null) - ret = createRMIConnection(Host, Adapter, - (MainAdapterClient) RMIProxyLocal.newInstance(new MainAdapterClientImpl(Host))); + if (Adapter != null) { + ret = createRMIConnection(Host, Adapter, + (MainAdapterClient) RMIProxyLocal.newInstance(new MainAdapterClientImpl(Host))); + } } - if (ret != null) m_Connections.add(ret); - else System.err.println("Warning no valid connection !!"); + if (ret != null) { + m_Connections.add(ret); + } + else { + System.err.println("Warning no valid connection !!"); + } return ret; } @@ -566,26 +577,35 @@ class RMIRegistration implements Runnable { @Override public void run() { - if (TRACE) - System.out.println("LaunchRMIRegistry on Client on PORT " + ComAdapter.PORT); + if (TRACE) { + System.out.println("LaunchRMIRegistry on Client on PORT " + ComAdapter.PORT); + } try { reg = java.rmi.registry.LocateRegistry.createRegistry(ComAdapter.PORT); } catch (Throwable e) { - if (TRACE) System.out.println("Registry notcreated !!" + e.getMessage()); + if (TRACE) { + System.out.println("Registry notcreated !!" + e.getMessage()); + } reg = null; } if (reg == null) { - if (TRACE) System.out.println("Try to get registry with getRegistry on PORT " + ComAdapter.PORT); + if (TRACE) { + System.out.println("Try to get registry with getRegistry on PORT " + ComAdapter.PORT); + } try { reg = java.rmi.registry.LocateRegistry.getRegistry(ComAdapter.PORT); } catch (Throwable e) { - if (TRACE) System.out.println("registry not created !!" + e.getMessage()); + if (TRACE) { + System.out.println("registry not created !!" + e.getMessage()); + } reg = null; } } - if (reg != null && TRACE) System.out.println("--> got RMIREGISTRY"); + if (reg != null && TRACE) { + System.out.println("--> got RMIREGISTRY"); + } comAd.setRMIRegistry(reg); } diff --git a/src/eva2/tools/jproxy/JProxyRemoteThread.java b/src/eva2/tools/jproxy/JProxyRemoteThread.java index a48013d5..36911d2f 100644 --- a/src/eva2/tools/jproxy/JProxyRemoteThread.java +++ b/src/eva2/tools/jproxy/JProxyRemoteThread.java @@ -72,8 +72,9 @@ public class JProxyRemoteThread implements InvocationHandler, Serializable { * */ private JProxyRemoteThread(Serializable object, String host) throws RMIServerNotAvailableException { - if (m_ComAdapter == null) - m_ComAdapter = ComAdapter.getInstance(); + if (m_ComAdapter == null) { + m_ComAdapter = ComAdapter.getInstance(); + } m_RMIThreadHandler = m_ComAdapter.getRMIThreadHandler(object, host); } @@ -81,8 +82,9 @@ public class JProxyRemoteThread implements InvocationHandler, Serializable { * */ private JProxyRemoteThread(Serializable object) throws RMIServerNotAvailableException { - if (m_ComAdapter == null) - m_ComAdapter = ComAdapter.getInstance(); + if (m_ComAdapter == null) { + m_ComAdapter = ComAdapter.getInstance(); + } m_RMIThreadHandler = m_ComAdapter.getRMIThreadHandler(object); } diff --git a/src/eva2/tools/jproxy/MainAdapterClientImpl.java b/src/eva2/tools/jproxy/MainAdapterClientImpl.java index c02edb2e..ce076836 100644 --- a/src/eva2/tools/jproxy/MainAdapterClientImpl.java +++ b/src/eva2/tools/jproxy/MainAdapterClientImpl.java @@ -40,7 +40,9 @@ public class MainAdapterClientImpl implements MainAdapterClient { */ @Override public RMIInvocationHandler getRMIHandler(Object obj) { - if (TRACE) System.out.println("MainAdapterClientImpl.getRMIHandler"); + if (TRACE) { + System.out.println("MainAdapterClientImpl.getRMIHandler"); + } RMIInvocationHandler ret = null; try { ret = new RMIInvocationHandlerImpl(obj); @@ -54,7 +56,9 @@ public class MainAdapterClientImpl implements MainAdapterClient { */ @Override public RMIThreadInvocationHandler getRMIThreadHandler(Object obj) { - if (TRACE) System.out.println("MainAdapterClientImpl.getRMIThreadHandler"); + if (TRACE) { + System.out.println("MainAdapterClientImpl.getRMIThreadHandler"); + } RMIThreadInvocationHandler ret = null; try { ret = new RMIThreadInvocationHandlerImpl(obj); diff --git a/src/eva2/tools/jproxy/RMIInvocationHandlerImpl.java b/src/eva2/tools/jproxy/RMIInvocationHandlerImpl.java index 19b6ee78..32dbcea4 100644 --- a/src/eva2/tools/jproxy/RMIInvocationHandlerImpl.java +++ b/src/eva2/tools/jproxy/RMIInvocationHandlerImpl.java @@ -34,12 +34,16 @@ public class RMIInvocationHandlerImpl extends UnicastRemoteObject implements RMI * */ public RMIInvocationHandlerImpl(Object obj) throws RemoteException { - if (TRACE) System.out.println("RMIInvokationHandlerImpl"); + if (TRACE) { + System.out.println("RMIInvokationHandlerImpl"); + } m_AdapterName = obj.getClass().getName()+"_"+RNG.randomInt(0,10000); try { m_Object = obj; m_list = m_Object.getClass().getMethods(); - if (TRACE) System.out.println(" --> rebind : "+m_AdapterName+" RMIInvokationHandlerImpl of object "+obj.getClass().getName()); + if (TRACE) { + System.out.println(" --> rebind : "+m_AdapterName+" RMIInvokationHandlerImpl of object "+obj.getClass().getName()); + } Naming.rebind(m_AdapterName,this); } catch (Exception e) { System.err.println(" Naming.rebind --> ERROR" + e.getMessage()); @@ -54,7 +58,9 @@ public class RMIInvocationHandlerImpl extends UnicastRemoteObject implements RMI try { m_Object = obj; m_list = m_Object.getClass().getMethods(); - if (TRACE) System.out.println(" -----> rebind : "+m_AdapterName+" "+this.getClass().getName()+" of object "+obj.getClass().getName()); + if (TRACE) { + System.out.println(" -----> rebind : "+m_AdapterName+" "+this.getClass().getName()+" of object "+obj.getClass().getName()); + } Naming.rebind(m_AdapterName,this); } catch (Exception e) { System.err.println(" Naming.rebind --> ERROR " + obj + " " + e.getMessage()); @@ -84,13 +90,19 @@ public class RMIInvocationHandlerImpl extends UnicastRemoteObject implements RMI Object ret=null; String Name = ""; //System.out.println("calling "+m); - if (TRACE) Name = Thread.currentThread().getName(); + if (TRACE) { + Name = Thread.currentThread().getName(); + } try { - if (TRACE) System.out.println( Name+" Before invoke on server :" +m); + if (TRACE) { + System.out.println( Name+" Before invoke on server :" +m); + } //Method[] list = m_Object.getClass().getMethods(); boolean invoked = false; for (int i=0;i " + ret.getClass()); + if (TRACE) { + System.out.println(" --> " + ret.getClass()); + } return ret; } /** * */ public static Object newInstance (Object c) { - if (TRACE) System.out.println("RMIProxyLocal:"+c.getClass().getName()); + if (TRACE) { + System.out.println("RMIProxyLocal:"+c.getClass().getName()); + } RMIProxyLocal proxyLocal = new RMIProxyLocal(c); Object ret = java.lang.reflect.Proxy.newProxyInstance ( c.getClass().getClassLoader(), @@ -51,14 +57,18 @@ public class RMIProxyLocal implements InvocationHandler, Serializable { proxyLocal); proxyLocal.setWrapper(ret); proxyLocal.setOriginalClass(c.getClass()); - if (TRACE) System.out.println(" --> " + ret.getClass()); + if (TRACE) { + System.out.println(" --> " + ret.getClass()); + } return ret; } /** * */ private RMIProxyLocal (Object c) { - if (TRACE) System.out.println("RMIProxyLocal:"+c.getClass().getName()); + if (TRACE) { + System.out.println("RMIProxyLocal:"+c.getClass().getName()); + } try { m_RMIHandler = new RMIInvocationHandlerImpl(c); } catch (Exception e) { @@ -105,7 +115,9 @@ public class RMIProxyLocal implements InvocationHandler, Serializable { * @param originalClass the originalClass to set */ public void setOriginalClass(Class originalClass) { - if (TRACE) System.out.println("setting original proxy class "+originalClass.getName()); + if (TRACE) { + System.out.println("setting original proxy class "+originalClass.getName()); + } this.originalClass = originalClass; } } diff --git a/src/eva2/tools/jproxy/RMIProxyLocalThread.java b/src/eva2/tools/jproxy/RMIProxyLocalThread.java index 5fce2e02..f1f558ab 100644 --- a/src/eva2/tools/jproxy/RMIProxyLocalThread.java +++ b/src/eva2/tools/jproxy/RMIProxyLocalThread.java @@ -34,7 +34,9 @@ public class RMIProxyLocalThread implements InvocationHandler,Serializable { c.getClass().getInterfaces(), Proxy); Proxy.setWrapper(ret); - if (TRACE) System.out.println("RMIProxyLocalThread "+c.getClass() + " ret " + ret.getClass()); + if (TRACE) { + System.out.println("RMIProxyLocalThread "+c.getClass() + " ret " + ret.getClass()); + } return ret; } /** @@ -47,7 +49,9 @@ public class RMIProxyLocalThread implements InvocationHandler,Serializable { c.getClass().getInterfaces(), Proxy); Proxy.setWrapper(ret); - if (TRACE) System.out.println("RMIProxyLocalThread "+c.getClass() + " ret " + ret.getClass()); + if (TRACE) { + System.out.println("RMIProxyLocalThread "+c.getClass() + " ret " + ret.getClass()); + } return ret; } /** diff --git a/src/eva2/tools/jproxy/RMIProxyRemote.java b/src/eva2/tools/jproxy/RMIProxyRemote.java index 6e4eb2c5..25938234 100644 --- a/src/eva2/tools/jproxy/RMIProxyRemote.java +++ b/src/eva2/tools/jproxy/RMIProxyRemote.java @@ -66,9 +66,13 @@ public class RMIProxyRemote implements InvocationHandler,Serializable { */ private RMIProxyRemote (Object c, String host) { m_ObjectName = c.getClass().getName(); - if (m_Adapter==null) m_Adapter = ComAdapter.getInstance(); + if (m_Adapter==null) { + m_Adapter = ComAdapter.getInstance(); + } m_RMIHandler = m_Adapter.getRMIHandler(c,host); - if (TRACE) System.out.println("creating RMIProxyRemote " + c.getClass() + " " + host); + if (TRACE) { + System.out.println("creating RMIProxyRemote " + c.getClass() + " " + host); + } } /** * @@ -81,14 +85,18 @@ public class RMIProxyRemote implements InvocationHandler,Serializable { System.out.println("RMIProxyRemote error ex "+e.getMessage()); e.printStackTrace(); } - if (TRACE) System.out.println("creating RMIProxyRemote " + c.getClass() + " " + Client.getClass()); + if (TRACE) { + System.out.println("creating RMIProxyRemote " + c.getClass() + " " + Client.getClass()); + } } /** * */ private RMIProxyRemote (Object c) { m_ObjectName = c.getClass().getName(); - if (m_Adapter==null) m_Adapter = ComAdapter.getInstance(); + if (m_Adapter==null) { + m_Adapter = ComAdapter.getInstance(); + } m_RMIHandler = m_Adapter.getRMIHandler(c); } /** diff --git a/src/eva2/tools/jproxy/RMIProxyRemoteThread.java b/src/eva2/tools/jproxy/RMIProxyRemoteThread.java index 7340efbc..35bc34f8 100644 --- a/src/eva2/tools/jproxy/RMIProxyRemoteThread.java +++ b/src/eva2/tools/jproxy/RMIProxyRemoteThread.java @@ -44,8 +44,9 @@ public class RMIProxyRemoteThread implements InvocationHandler, } private static void maybeLoadAdapter() { - if (m_Adapter==null) - m_Adapter = ComAdapter.getInstance(); + if (m_Adapter==null) { + m_Adapter = ComAdapter.getInstance(); + } } /** diff --git a/src/eva2/tools/jproxy/RMIThreadInvocationHandlerImpl.java b/src/eva2/tools/jproxy/RMIThreadInvocationHandlerImpl.java index ded542e3..82de3a0f 100644 --- a/src/eva2/tools/jproxy/RMIThreadInvocationHandlerImpl.java +++ b/src/eva2/tools/jproxy/RMIThreadInvocationHandlerImpl.java @@ -55,7 +55,9 @@ public class RMIThreadInvocationHandlerImpl extends UnicastRemoteObject implemen try { m_Object = ThreadProxy.newInstance(obj); m_list = m_Object.getClass().getMethods(); - if (TRACE) System.out.println(" --> rebind : "+m_AdapterName+" RMIThreadInvokationHandlerImpl of object "+obj.getClass().getName()); + if (TRACE) { + System.out.println(" --> rebind : "+m_AdapterName+" RMIThreadInvokationHandlerImpl of object "+obj.getClass().getName()); + } Naming.rebind(m_AdapterName,this); } catch (Exception e) { System.out.println(" Naming.rebind --> ERROR" + e.getMessage()); @@ -77,7 +79,9 @@ public class RMIThreadInvocationHandlerImpl extends UnicastRemoteObject implemen try { m_Object = ThreadProxy.newInstance(obj); m_list = m_Object.getClass().getMethods(); - if (TRACE) System.out.println(" -----> rebind : "+m_AdapterName+" "+this.getClass().getName()+" of object "+obj.getClass().getName()); + if (TRACE) { + System.out.println(" -----> rebind : "+m_AdapterName+" "+this.getClass().getName()+" of object "+obj.getClass().getName()); + } Naming.rebind(m_AdapterName,this); } catch (Exception e) { System.out.println(" Naming.rebind --> ERROR" + e.getMessage()); @@ -104,9 +108,13 @@ public class RMIThreadInvocationHandlerImpl extends UnicastRemoteObject implemen public Object invoke (String m, Object[] args) throws RemoteException { Object ret=null; String Name = ""; - if (TRACE) Name = Thread.currentThread().getName(); + if (TRACE) { + Name = Thread.currentThread().getName(); + } try { - if (TRACE) System.out.println( Name+" Before invoke on server :" +m); + if (TRACE) { + System.out.println( Name+" Before invoke on server :" +m); + } //Method[] list = m_Object.getClass().getMethods(); boolean invoked = false; for (int i=0;i= m_Instances.length) - m_index = 0; + if (m_Instances == null) { + init(MAXinstances); + } + if (m_index >= m_Instances.length) { + m_index = 0; + } if (m_Instances[m_index] == null) { ret = new XThread(x, m, Para); m_Instances[m_index] = ret; @@ -92,10 +99,12 @@ public class XThread extends Thread implements Serializable { */ public static XThread getXThread(Object x, String m, Object[] Para, int MAXinstances) { XThread ret = null; - if (m_Instances == null) - init(MAXinstances); - if (m_index >= m_Instances.length) - m_index = 0; + if (m_Instances == null) { + init(MAXinstances); + } + if (m_index >= m_Instances.length) { + m_index = 0; + } if (m_Instances[m_index] == null) { ret = new XThread(x, m, Para); m_Instances[m_index] = ret; diff --git a/src/eva2/tools/math/BayNet.java b/src/eva2/tools/math/BayNet.java index 8028e271..a5b5f767 100644 --- a/src/eva2/tools/math/BayNet.java +++ b/src/eva2/tools/math/BayNet.java @@ -80,8 +80,12 @@ public class BayNet { } private static BitSet getBinaryData(AbstractEAIndividual indy) { - if (indy instanceof InterfaceGAIndividual) return ((InterfaceGAIndividual)indy).getBGenotype(); - else if (indy instanceof InterfaceDataTypeBinary) return ((InterfaceDataTypeBinary)indy).getBinaryData(); + 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()); } @@ -834,15 +838,17 @@ public class BayNet { 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."); + 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."); + 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 all bits to zero bitSet.clear(offset, offset + length - 1); @@ -850,13 +856,15 @@ public class BayNet { // 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); + if ((mask & absValue) > 0) { + bitSet.set(offset + i); + } } // setting up the sign - if (value < 0) - bitSet.set(offset + length - 1); + if (value < 0) { + bitSet.set(offset + length - 1); + } return bitSet; } diff --git a/src/eva2/tools/math/Jama/LUDecomposition.java b/src/eva2/tools/math/Jama/LUDecomposition.java index 44794c99..5d0b7d14 100644 --- a/src/eva2/tools/math/Jama/LUDecomposition.java +++ b/src/eva2/tools/math/Jama/LUDecomposition.java @@ -185,8 +185,9 @@ public class LUDecomposition implements java.io.Serializable { 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; + if (LU[j][j] == 0) { + return false; + } } return true; diff --git a/src/eva2/tools/math/Jama/Matrix.java b/src/eva2/tools/math/Jama/Matrix.java index 92bfe642..df477d12 100644 --- a/src/eva2/tools/math/Jama/Matrix.java +++ b/src/eva2/tools/math/Jama/Matrix.java @@ -184,9 +184,13 @@ public class Matrix implements Cloneable, Serializable { int nn = 0; int mm = 0; for ( int im=0;im getMinMaxDiag() { - if (m<1 || n<1) return null; + if (m<1 || n<1) { + return null; + } double v = get(0,0); Pair ret = new Pair(v,v); @@ -1225,8 +1231,9 @@ public class Matrix implements Cloneable, Serializable { // 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."); + 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); @@ -1243,12 +1250,16 @@ public class Matrix implements Cloneable, Serializable { v.addElement(row = new double[n]); int j = 0; do { - if (j >= n) throw new java.io.IOException - ("Row " + v.size() + " is too long."); + 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."); + 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][]; @@ -1280,7 +1291,9 @@ public class Matrix implements Cloneable, Serializable { * @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!"); + if ((v.length != n) || (rowIndex<0) || (rowIndex>=m)) { + throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); + } rowSubtract(rowIndex, rowIndex, v); } @@ -1291,7 +1304,9 @@ public class Matrix implements Cloneable, Serializable { * @param B */ public void rowSubtract(double[] v) { - if ((v.length != n)) throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); + if ((v.length != n)) { + throw new IllegalArgumentException("Invalid matrix dimensions for rowMinus!"); + } rowSubtract(0, m-1, v); } diff --git a/src/eva2/tools/math/Jama/QRDecomposition.java b/src/eva2/tools/math/Jama/QRDecomposition.java index 19000ce8..b5c563a3 100644 --- a/src/eva2/tools/math/Jama/QRDecomposition.java +++ b/src/eva2/tools/math/Jama/QRDecomposition.java @@ -96,8 +96,9 @@ public class QRDecomposition implements java.io.Serializable { public boolean isFullRank () { for (int j = 0; j < n; j++) { - if (Rdiag[j] == 0) - return false; + if (Rdiag[j] == 0) { + return false; + } } return true; } diff --git a/src/eva2/tools/math/Jama/util/Maths.java b/src/eva2/tools/math/Jama/util/Maths.java index 427dfdd4..1484af67 100644 --- a/src/eva2/tools/math/Jama/util/Maths.java +++ b/src/eva2/tools/math/Jama/util/Maths.java @@ -14,8 +14,9 @@ public class Maths { } else if (b != 0) { r = a/b; r = bb*Math.sqrt(1+r*r); - } else - r = 0.0; + } else { + r = 0.0; + } return r; } } diff --git a/src/eva2/tools/math/Mathematics.java b/src/eva2/tools/math/Mathematics.java index b06bcfc2..38ff9d1d 100644 --- a/src/eva2/tools/math/Mathematics.java +++ b/src/eva2/tools/math/Mathematics.java @@ -22,10 +22,12 @@ public class Mathematics { * @return */ public static double[][] adjoint(double[][] a) { - if (a == null) - return null; - if (a.length != a[0].length) - return null; + 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++) { @@ -55,25 +57,31 @@ public class Mathematics { * 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]; + 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); + if (matrix[0][k] != 0) { + det += matrix[0][k] * adjoint(matrix, 0, k); + } } return det; } @@ -93,11 +101,13 @@ public class Mathematics { * 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!"); + 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); @@ -119,9 +129,10 @@ public class Mathematics { * 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"); + 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); @@ -329,11 +340,13 @@ public class Mathematics { */ public static double hyperbolicInterpolation(double x, double x0, double x1, double f0, double f1) { - if (x1 == 0) - return lerp(f0, f1, (x - x0) / (-x0)); + if (x1 == 0) { + return lerp(f0, f1, (x - x0) / (-x0)); + } double l = lerp(x0 / x1, 1, x); - if (l == 0) - return linearInterpolation(x, x0, x1, f0, f1); + if (l == 0) { + return linearInterpolation(x, x0, x1, f0, f1); + } return lerp(f0, f1, x / l); } @@ -360,14 +373,17 @@ public class Mathematics { * @return */ public static double[][] inverse(double[][] a) { - if (a == null) - return null; - if (a.length != a[0].length) - return null; + if (a == null) { + return null; + } + if (a.length != a[0].length) { + return null; + } double det = determinant(a); - if (det == 0) - return null; + if (det == 0) { + return null; + } double[][] b = adjoint(a); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { @@ -395,7 +411,9 @@ public class Mathematics { */ public static int areFinite(double[][] v) { for (int i=0; i=0) return i; + if (areFinite(v[i])>=0) { + return i; + } } return -1; } @@ -409,7 +427,9 @@ public class Mathematics { */ public static int areFinite(double ... v) { for (int i=0; i upper)) - return false; + if (v < lower || (v > upper)) { + return false; + } return true; } @@ -437,8 +458,9 @@ public class Mathematics { */ 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; + if (x[i] < range[i][0] || (x[i] > range[i][1])) { + return false; + } } return true; } @@ -452,7 +474,9 @@ public class Mathematics { */ public static boolean isValidVec(double[][] d) { for (int i=0; i range.length) - System.err - .println("Invalid vector length, x is longer than range! (Mathematics.projectToRange)"); + 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++; @@ -991,8 +1027,9 @@ public class Mathematics { Matrix resVec = rotMatrix.times(new Matrix(x, x.length)); x = resVec.getColumnPackedCopy(); return x; - } else - return x; + } else { + return x; + } } /** @@ -1007,10 +1044,12 @@ public class Mathematics { 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); + if (randomize) { + rotate(vect, RNG.randomDouble(-alpha, alpha), i, j); + } + else { + rotate(vect, alpha, i, j); + } } } } @@ -1113,11 +1152,13 @@ public class Mathematics { int i, j, m = 0, n = 0; for (i = 0; i < a.length; i++) { - if (i == k) - continue; + if (i == k) { + continue; + } for (j = 0; j < a[0].length; j++) { - if (j == l) - continue; + if (j == l) { + continue; + } b[m][n++] = a[i][j]; } m++; @@ -1430,7 +1471,9 @@ public class Mathematics { */ public static boolean contains(int[] list, int i) { for (int k:list) { - if (k==i) return true; + if (k==i) { + return true; + } } return false; } diff --git a/src/eva2/tools/math/SpecialFunction.java b/src/eva2/tools/math/SpecialFunction.java index 93515c43..66f8af22 100644 --- a/src/eva2/tools/math/SpecialFunction.java +++ b/src/eva2/tools/math/SpecialFunction.java @@ -145,7 +145,9 @@ public final class SpecialFunction extends Object { * @return The log10 */ static public double log10(double x) throws ArithmeticException { - if( x <= 0.0 ) throw new ArithmeticException("range exception"); + if( x <= 0.0 ) { + throw new ArithmeticException("range exception"); + } return Math.log(x)/2.30258509299404568401; } @@ -157,7 +159,9 @@ public final class SpecialFunction extends Object { * @throws ArithmeticException */ static public double logb(double b, double x) throws ArithmeticException { - if( x <= 0.0 ) throw new ArithmeticException("range exception"); + if( x <= 0.0 ) { + throw new ArithmeticException("range exception"); + } return Math.log(x)/Math.log(b); } @@ -170,7 +174,9 @@ public final class SpecialFunction extends Object { static public double cosh(double x) throws ArithmeticException { double a; a = x; - if( a < 0.0 ) a = Math.abs(x); + if( a < 0.0 ) { + a = Math.abs(x); + } a = Math.exp(a); return 0.5*(a+1/a); } @@ -181,12 +187,20 @@ public final class SpecialFunction extends Object { */ static public double sinh(double x) throws ArithmeticException { double a; - if(x == 0.0) return x; + if(x == 0.0) { + return x; + } a = x; - if( a < 0.0 ) a = Math.abs(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); + if( x < 0.0 ) { + return -0.5*(a-1/a); + } + else { + return 0.5*(a-1/a); + } } /** @@ -195,12 +209,20 @@ public final class SpecialFunction extends Object { */ static public double tanh(double x) throws ArithmeticException { double a; - if( x == 0.0 ) return x; + if( x == 0.0 ) { + return x; + } a = x; - if( a < 0.0 ) a = Math.abs(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) ); + if(x < 0.0 ) { + return -( 1.0-2.0/(a+1.0) ); + } + else { + return ( 1.0-2.0/(a+1.0) ); + } } /** @@ -209,7 +231,9 @@ public final class SpecialFunction extends Object { */ static public double acosh(double x) throws ArithmeticException { - if( x < 1.0 ) throw new ArithmeticException("range exception"); + if( x < 1.0 ) { + throw new ArithmeticException("range exception"); + } return Math.log( x + Math.sqrt(x*x-1)); } @@ -220,7 +244,9 @@ public final class SpecialFunction extends Object { static public double asinh(double xx) throws ArithmeticException { double x; int sign; - if(xx == 0.0) return xx; + if(xx == 0.0) { + return xx; + } if( xx < 0.0 ) { sign = -1; x = -xx; @@ -236,8 +262,10 @@ public final class SpecialFunction extends Object { * @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( x > 1.0 || x < -1.0 ) { + throw + new ArithmeticException("range exception"); + } return 0.5 * Math.log( (1.0+x)/(1.0-x) ); } @@ -302,7 +330,9 @@ public final class SpecialFunction extends Object { +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; + if (x < 0.0) { + ans = -ans; + } return ans; } } @@ -321,11 +351,17 @@ public final class SpecialFunction extends Object { double BIGNO = 1.0e+10; double BIGNI = 1.0e-10; - if(n == 0) return j0(x); - if(n == 1) return j1(x); + if(n == 0) { + return j0(x); + } + if(n == 1) { + return j1(x); + } ax=Math.abs(x); - if(ax == 0.0) return 0.0; + if(ax == 0.0) { + return 0.0; + } else if (ax > (double)n) { tox=2.0/ax; @@ -353,9 +389,13 @@ public final class SpecialFunction extends Object { ans *= BIGNI; sum *= BIGNI; } - if (jsum) sum += bj; + if (jsum) { + sum += bj; + } jsum=!jsum; - if (j == n) ans=bjp; + if (j == n) { + ans=bjp; + } } sum=2.0*sum-bj; ans /= sum; @@ -432,8 +472,12 @@ public final class SpecialFunction extends Object { static public double yn(int n, double x) throws ArithmeticException { double by,bym,byp,tox; - if(n == 0) return y0(x); - if(n == 1) return y1(x); + if(n == 0) { + return y0(x); + } + if(n == 1) { + return y1(x); + } tox=2.0/x; by=y1(x); @@ -454,8 +498,12 @@ public final class SpecialFunction extends Object { */ static public double fac(double x) throws ArithmeticException { double d = Math.abs(x); - if(Math.floor(d) == d) return (double)fac( (int)x ); - else return gamma(x+1.0); + if(Math.floor(d) == d) { + return (double)fac( (int)x ); + } + else { + return gamma(x+1.0); + } } /** @@ -465,10 +513,16 @@ public final class SpecialFunction extends Object { static public int fac(int j) throws ArithmeticException { int i = j; int d = 1; - if(j < 0) i = Math.abs(j); + if(j < 0) { + i = Math.abs(j); + } while( i > 1) { d *= i--; } - if(j < 0) return -d; - else return d; + if(j < 0) { + return -d; + } + else { + return d; + } } @@ -517,7 +571,9 @@ public final class SpecialFunction extends Object { if( q > 33.0 ) { if( x < 0.0 ) { p = Math.floor(q); - if( p == q ) throw new ArithmeticException("gamma: overflow"); + if( p == q ) { + throw new ArithmeticException("gamma: overflow"); + } i = (int)p; z = q - p; if( z > 0.5 ) { @@ -525,7 +581,9 @@ public final class SpecialFunction extends Object { z = q - p; } z = q * Math.sin( Math.PI * z ); - if( z == 0.0 ) throw new ArithmeticException("gamma: overflow"); + if( z == 0.0 ) { + throw new ArithmeticException("gamma: overflow"); + } z = Math.abs(z); z = Math.PI/(z * stirf(q) ); @@ -563,7 +621,9 @@ public final class SpecialFunction extends Object { x += 1.0; } - if( (x == 2.0) || (x == 3.0) ) return z; + if( (x == 2.0) || (x == 3.0) ) { + return z; + } x -= 2.0; p = polevl( x, P, 6 ); @@ -624,12 +684,18 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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); @@ -654,8 +720,9 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 r = pk/qk; t = Math.abs( (ans - r)/r ); ans = r; - } else - t = 1.0; + } else { + t = 1.0; + } pkm2 = pkm1; pkm1 = pk; @@ -690,13 +757,19 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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); @@ -729,7 +802,9 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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 ); @@ -749,7 +824,9 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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 ); @@ -766,7 +843,9 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 throws ArithmeticException { - if( k < 0 || x < 0 ) return 0.0; + if( k < 0 || x < 0 ) { + return 0.0; + } return igamc((double)(k+1) ,x); } @@ -782,7 +861,9 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 throws ArithmeticException { - if( k < 0 || x < 0 ) return 0.0; + if( k < 0 || x < 0 ) { + return 0.0; + } return igam((double)(k+1),x); } @@ -802,10 +883,14 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 x = a * SQRTH; z = Math.abs(x); - if( z < SQRTH ) y = 0.5 + 0.5 * erf(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( x > 0 ) { + y = 1.0 - y; + } } return y; @@ -868,16 +953,26 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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( a < 0 ) { + return( 2.0 ); + } + else { + return( 0.0 ); + } } z = Math.exp(z); @@ -892,11 +987,17 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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 ) return 2.0; - else return( 0.0 ); + if( a < 0 ) { + return 2.0; + } + else { + return( 0.0 ); + } } @@ -933,7 +1034,9 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 4.92673942608635921086E4 }; - if( Math.abs(x) > 1.0 ) return( 1.0 - erfc(x) ); + 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; @@ -1011,15 +1114,19 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 q = -x; w = lgamma(q); p = Math.floor(q); - if( p == q ) throw new ArithmeticException("lgam: Overflow"); + 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"); + if( z == 0.0 ) { + throw new + ArithmeticException("lgamma: Overflow"); + } z = LOGPI - Math.log( z ) - w; return z; } @@ -1031,31 +1138,43 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 z *= x; } while( x < 2.0 ) { - if( x == 0.0 ) throw new - ArithmeticException("lgamma: Overflow"); + 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); + 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"); + 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 ); + 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; + 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; } @@ -1079,12 +1198,18 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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 ) return 0.0; - if( xx == 1.0 ) return 1.0; + if( xx == 0.0 ) { + return 0.0; + } + if( xx == 1.0 ) { + return 1.0; + } throw new ArithmeticException("ibeta: Domain error!"); } @@ -1112,17 +1237,23 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 if( flag && (b * x) <= 1.0 && x <= 0.95) { t = pseries(a, b, x); - if( t <= MACHEP ) t = 1.0 - MACHEP; - else t = 1.0 - t; + if( t <= MACHEP ) { + t = 1.0 - MACHEP; + } + else { + t = 1.0 - 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; + if( y < 0.0 ) { + w = incbcf( a, b, x ); + } + else { + w = incbd( a, b, x ) / xc; + } /* Multiply w by the factor a b _ _ _ @@ -1137,22 +1268,32 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 t *= w; t *= gamma(a+b) / (gamma(a) * gamma(b)); if( flag ) { - if( t <= MACHEP ) t = 1.0 - MACHEP; - else t = 1.0 - t; + if( t <= MACHEP ) { + t = 1.0 - MACHEP; + } + 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( y < MINLOG ) { + t = 0.0; + } + else { + t = Math.exp(y); + } if( flag ) { - if( t <= MACHEP ) t = 1.0 - MACHEP; - else t = 1.0 - t; + if( t <= MACHEP ) { + t = 1.0 - MACHEP; + } + else { + t = 1.0 - t; + } } return t; } @@ -1204,14 +1345,19 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 qkm2 = qkm1; qkm1 = qk; - if( qk != 0 ) r = pk/qk; + if( qk != 0 ) { + r = pk/qk; + } if( r != 0 ) { t = Math.abs( (ans - r)/r ); ans = r; - } else - t = 1.0; + } else { + t = 1.0; + } - if( t < thresh ) return ans; + if( t < thresh ) { + return ans; + } k1 += 1.0; k2 += 1.0; @@ -1286,14 +1432,19 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 qkm2 = qkm1; qkm1 = qk; - if( qk != 0 ) r = pk/qk; + if( qk != 0 ) { + r = pk/qk; + } if( r != 0 ) { t = Math.abs( (ans - r)/r ); ans = r; - } else - t = 1.0; + } else { + t = 1.0; + } - if( t < thresh ) return ans; + if( t < thresh ) { + return ans; + } k1 += 1.0; k2 -= 1.0; @@ -1351,8 +1502,12 @@ Direct inquiries to 30 Frost Street, Cambridge, MA 02140 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( t < MINLOG ) { + s = 0.0; + } + else { + s = Math.exp(t); + } } return s; } diff --git a/src/eva2/tools/math/StatisticUtils.java b/src/eva2/tools/math/StatisticUtils.java index 6b16eb88..63e1739c 100644 --- a/src/eva2/tools/math/StatisticUtils.java +++ b/src/eva2/tools/math/StatisticUtils.java @@ -41,7 +41,9 @@ public class StatisticUtils 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!=y2.length) { + throw new RuntimeException("Error, mismatching vectors for correlation calculation in StatisticUtils.correlation(double[], double[])"); + } if (n <= 1) { return 1.0; @@ -245,8 +247,12 @@ public class StatisticUtils sumSquared += (vector[i] * vector[i]); } double denom; - if (finiteSet) denom=n; - else denom=(n-1); + if (finiteSet) { + denom=n; + } + else { + denom=(n-1); + } double result = (sumSquared - (sum * sum / (double) n)) / denom; // We don't like negative variance diff --git a/src/eva2/tools/math/interpolation/PolyInterpolation.java b/src/eva2/tools/math/interpolation/PolyInterpolation.java index b25511ea..41c82aa6 100644 --- a/src/eva2/tools/math/interpolation/PolyInterpolation.java +++ b/src/eva2/tools/math/interpolation/PolyInterpolation.java @@ -145,8 +145,9 @@ public class PolyInterpolation public double[] getYandDerivatives(double x, int ndDerivateNumber) throws InterpolationException { - if (ndDerivateNumber < 0) - throw new InterpolationException("Negative derivative numbers make no sense."); + if (ndDerivateNumber < 0) { + throw new InterpolationException("Negative derivative numbers make no sense."); + } else if (ndDerivateNumber == 0) { double[] pd = new double[1]; @@ -202,9 +203,10 @@ public class PolyInterpolation public PolynomialInterpolationResult polynomialInterpolation(double x) throws InterpolationException { - if (abstractDataSet == null) - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } return polynomialInterpolation( abstractDataSet.getXData(), abstractDataSet.getYData(), @@ -236,9 +238,10 @@ public class PolyInterpolation double x) throws InterpolationException { - if (abstractDataSet == null) - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } return polynomialInterpolation( abstractDataSet.getXData(), abstractDataSet.getYData(), @@ -272,8 +275,9 @@ public class PolyInterpolation double x) throws InterpolationException { - if (xa == null || ya == null) - throw new InterpolationException("No data."); + 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]; @@ -311,8 +315,9 @@ public class PolyInterpolation "Two identical x values. The values must be distinct."); den = 1.0; } - else - throw new InterpolationException("Two identical x values."); + else { + throw new InterpolationException("Two identical x values."); + } } den = w / den; d[i] = hp * den; @@ -348,9 +353,10 @@ public class PolyInterpolation public double[] calculatePolynomialCoefficients() throws InterpolationException { - if (abstractDataSet == null) - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } return calculatePolynomialCoefficients( abstractDataSet.getXData(), abstractDataSet.getYData()); @@ -380,9 +386,10 @@ public class PolyInterpolation public double[] calculatePolynomialCoefficients(AbstractDataSet abstractDataSet) throws InterpolationException { - if (abstractDataSet == null) - throw new InterpolationException( - "No data." + " The AbstractDataSet was not defined."); + if (abstractDataSet == null) { + throw new InterpolationException( + "No data." + " The AbstractDataSet was not defined."); + } return calculatePolynomialCoefficients( abstractDataSet.getXData(), abstractDataSet.getYData()); diff --git a/src/eva2/tools/math/interpolation/SplineInterpolation.java b/src/eva2/tools/math/interpolation/SplineInterpolation.java index 279b0de1..3caa3ffe 100644 --- a/src/eva2/tools/math/interpolation/SplineInterpolation.java +++ b/src/eva2/tools/math/interpolation/SplineInterpolation.java @@ -145,17 +145,19 @@ public class SplineInterpolation 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."); + 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; + if (yp0 > 0.99e30) { + y2[0] = u[0] = 0.0; + } else { y2[0] = -0.5; @@ -224,15 +226,18 @@ public class SplineInterpolation while (khi - klo > 1) { k = (khi + klo) >> 1; - if (xa[k] > x) - khi = k; - else - klo = k; + 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."); + 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 = @@ -275,15 +280,18 @@ public class SplineInterpolation while (khi - klo > 1) { k = (khi + klo) >> 1; - if (xa[k] > x) - khi = k; - else - klo = k; + 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."); + 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 = diff --git a/src/eva2/tools/matlab/JMatLink.java b/src/eva2/tools/matlab/JMatLink.java index a7152f98..a54f8654 100644 --- a/src/eva2/tools/matlab/JMatLink.java +++ b/src/eva2/tools/matlab/JMatLink.java @@ -133,8 +133,9 @@ public class JMatLink extends Thread { */ public static JMatLink getInstance() { // System.out.println("JMatLink getInstance () {"); - if (m_Instance == null) - m_Instance = new JMatLink(); + if (m_Instance == null) { + m_Instance = new JMatLink(); + } return m_Instance; } @@ -312,8 +313,9 @@ public class JMatLink extends Thread { private JMatLink() { - if (debugB) - System.out.println("JMatLink constructor"); + if (debugB) { + System.out.println("JMatLink constructor"); + } runner = new Thread(this); @@ -664,8 +666,9 @@ public class JMatLink extends Thread { // evaluate expression "evalS" in specified engine Ep - if (debugB) - System.out.println("eval(ep,String) in " + epI + " " + evalS); + if (debugB) { + System.out.println("eval(ep,String) in " + epI + " " + evalS); + } lockEngineLock(); @@ -681,8 +684,9 @@ public class JMatLink extends Thread { releaseEngineLock(); - if (debugB) - System.out.println("eval(ep,String) out " + epI + " " + evalS); + if (debugB) { + System.out.println("eval(ep,String) out " + epI + " " + evalS); + } // return retValI; Return value indicates success @@ -1197,8 +1201,9 @@ public class JMatLink extends Thread { double[][] vDD = new double[1][valuesD.length]; // 1xn array - if (debugB) - System.out.println("length = " + valuesD.length); + if (debugB) { + System.out.println("length = " + valuesD.length); + } vDD[0] = valuesD; // copy row @@ -1414,9 +1419,10 @@ public class JMatLink extends Thread { // get the output buffer from MATLAB - if (debugB) - System.out - .println("Thread in: " + Thread.currentThread().getName()); + if (debugB) { + System.out + .println("Thread in: " + Thread.currentThread().getName()); + } lockEngineLock(); @@ -1432,9 +1438,10 @@ public class JMatLink extends Thread { releaseEngineLock(); - if (debugB) - System.out.println("Thread out: " - + Thread.currentThread().getName()); + if (debugB) { + System.out.println("Thread out: " + + Thread.currentThread().getName()); + } return engOutputBufferS; @@ -1513,8 +1520,9 @@ public class JMatLink extends Thread { int tempRetVal; - if (debugB) - System.out.println("JMatLink: thread is running"); + if (debugB) { + System.out.println("JMatLink: thread is running"); + } while (true) { @@ -1623,13 +1631,15 @@ public class JMatLink extends Thread { // System.out.println("JMatLink: thread awoke and passed lock"); - if (destroyJMatLinkB == true) - break; + if (destroyJMatLinkB == true) { + break; + } } // end while - if (debugB) - System.out.println("JMatLink: thread terminated"); + if (debugB) { + System.out.println("JMatLink: thread terminated"); + } } // end run diff --git a/src/eva2/tools/print/PagePrinter.java b/src/eva2/tools/print/PagePrinter.java index 797c2ce4..e8c3c0b8 100644 --- a/src/eva2/tools/print/PagePrinter.java +++ b/src/eva2/tools/print/PagePrinter.java @@ -54,9 +54,13 @@ public class PagePrinter 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; + if( old.width > h || old.height > w ) { + rec_fit_in = true; + } } - else rec_fit_in = true; + else { + rec_fit_in = true; + } JLabel[] text = new JLabel[4]; text[0] = new JLabel("The component which should be printed"); @@ -108,8 +112,9 @@ public class PagePrinter JOptionPane.QUESTION_MESSAGE, null, null, null ); - if( choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.CLOSED_OPTION ) - return Printable.NO_SUCH_PAGE; + if( choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.CLOSED_OPTION ) { + return Printable.NO_SUCH_PAGE; + } else if( choice == JOptionPane.OK_OPTION ){ @@ -142,11 +147,15 @@ public class PagePrinter c.paint( g ); c.setSize( old ); } - else c.paint( g ); + else { + c.paint( g ); + } } } } - else c.paint( g ); + else { + c.paint( g ); + } return Printable.PAGE_EXISTS; } } diff --git a/src/simpleprobs/SimpleB1.java b/src/simpleprobs/SimpleB1.java index fc7373a9..834ed29b 100644 --- a/src/simpleprobs/SimpleB1.java +++ b/src/simpleprobs/SimpleB1.java @@ -13,7 +13,9 @@ public class SimpleB1 extends SimpleProblemBinary { int fitness = 0; for (int i = 0; i < getProblemDimension(); i++) { - if (b.get(i)) fitness++; + if (b.get(i)) { + fitness++; + } } result[0] = fitness; return result;