Return-Path: X-Original-To: archive-asf-public-internal@cust-asf2.ponee.io Delivered-To: archive-asf-public-internal@cust-asf2.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by cust-asf2.ponee.io (Postfix) with ESMTP id 9D768200C67 for ; Sun, 30 Apr 2017 17:38:11 +0200 (CEST) Received: by cust-asf.ponee.io (Postfix) id 9C3FB160BA9; Sun, 30 Apr 2017 15:38:11 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id 7C191160BA4 for ; Sun, 30 Apr 2017 17:38:08 +0200 (CEST) Received: (qmail 22701 invoked by uid 500); 30 Apr 2017 15:38:07 -0000 Mailing-List: contact commits-help@commons.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@commons.apache.org Delivered-To: mailing list commits@commons.apache.org Received: (qmail 22489 invoked by uid 99); 30 Apr 2017 15:38:07 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Sun, 30 Apr 2017 15:38:07 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 579BDE0285; Sun, 30 Apr 2017 15:38:07 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit From: erans@apache.org To: commits@commons.apache.org Date: Sun, 30 Apr 2017 15:38:08 -0000 Message-Id: In-Reply-To: <9b33c704a5fc46188f24df6de5cb7e66@git.apache.org> References: <9b33c704a5fc46188f24df6de5cb7e66@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [2/3] commons-numbers git commit: Removed "Commons Math" code examples. archived-at: Sun, 30 Apr 2017 15:38:11 -0000 http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/LowDiscrepancyGeneratorComparison.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/LowDiscrepancyGeneratorComparison.java b/src/userguide/java/org/apache/commons/math4/userguide/LowDiscrepancyGeneratorComparison.java deleted file mode 100644 index 3ec4be4..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/LowDiscrepancyGeneratorComparison.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.RenderingHints; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JTextArea; - -import org.apache.commons.complex.geometry.euclidean.twod.Vector2D; -import org.apache.commons.complex.random.HaltonSequenceGenerator; -import org.apache.commons.complex.random.JDKRandomGenerator; -import org.apache.commons.complex.random.MersenneTwister; -import org.apache.commons.complex.random.RandomGenerator; -import org.apache.commons.complex.random.RandomVectorGenerator; -import org.apache.commons.complex.random.SobolSequenceGenerator; -import org.apache.commons.complex.random.UncorrelatedRandomVectorGenerator; -import org.apache.commons.complex.random.UniformRandomGenerator; -import org.apache.commons.complex.util.FastMath; -import org.apache.commons.complex.util.Pair; -import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame; - -/** - * Plots 2D samples drawn from various pseudo / quasi-random generators. - */ -public class LowDiscrepancyGeneratorComparison { - - public static List makeCircle(int samples, final RandomVectorGenerator generator) { - List points = new ArrayList(); - for (double i = 0; i < samples; i++) { - double[] vector = generator.nextVector(); - Vector2D point = new Vector2D(vector); - points.add(point); - } - - // normalize points first - points = normalize(points); - - // now test if the sample is within the unit circle - List circlePoints = new ArrayList(); - for (Vector2D p : points) { - double criteria = FastMath.pow(p.getX(), 2) + FastMath.pow(p.getY(), 2); - if (criteria < 1.0) { - circlePoints.add(p); - } - } - - return circlePoints; - } - - public static List makeRandom(int samples, RandomVectorGenerator generator) { - List points = new ArrayList(); - for (double i = 0; i < samples; i++) { - double[] vector = generator.nextVector(); - Vector2D point = new Vector2D(vector); - points.add(point); - } - - return normalize(points); - } - - public static List normalize(final List input) { - // find the mininum and maximum x value in the dataset - double minX = Double.MAX_VALUE; - double maxX = Double.MIN_VALUE; - for (Vector2D p : input) { - minX = FastMath.min(minX, p.getX()); - maxX = FastMath.max(maxX, p.getX()); - } - - double minY, maxY; - - // use the minimum to detect if we either have input values in the range [0, 1] or [-sqrt(3), sqrt(3)] - if (FastMath.abs(minX) < 0.1) { - minX = minY = 0.0; - maxX = maxY = 1.0; - } else { - minX = minY = -FastMath.sqrt(3); - maxX = maxY = FastMath.sqrt(3); - } - - double rangeX = maxX - minX; - double rangeY = maxY - minY; - List points = new ArrayList(); - for (Vector2D p : input) { - double[] arr = p.toArray(); - // normalize to the range [-1, 1] - arr[0] = (arr[0] - minX) / rangeX * 2 - 1; - arr[1] = (arr[1] - minY) / rangeY * 2 - 1; - points.add(new Vector2D(arr)); - } - return points; - } - - @SuppressWarnings("serial") - public static class Display extends ExampleFrame { - - public Display() { - setTitle("Commons-Math: Pseudo/Quasi-random examples"); - setSize(800, 800); - - setLayout(new GridBagLayout()); - - int[] datasets = new int[] { 256, 1000, 2500, 1000 }; - List> generators = new ArrayList>(); - - generators.add(new Pair("Uncorrelated\nUniform(JDK)", - new UncorrelatedRandomVectorGenerator(2, new UniformRandomGenerator(new JDKRandomGenerator())))); - generators.add(new Pair("Independent\nRandom(MT)", new RandomVectorGenerator() { - - RandomGenerator[] rngs = new RandomGenerator[] { - new MersenneTwister(0), - new MersenneTwister(1) - }; - - public double[] nextVector() { - final double[] vector = new double[2]; - vector[0] = rngs[0].nextDouble(); - vector[1] = rngs[1].nextDouble(); - return vector; - } - - })); - generators.add(new Pair("HaltonSequence", new HaltonSequenceGenerator(2))); - generators.add(new Pair("SobolSequence", new SobolSequenceGenerator(2))); - - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.VERTICAL; - c.gridx = 1; - c.gridy = 0; - c.insets = new Insets(2, 2, 2, 2); - - for (Pair pair : generators) { - JTextArea text = new JTextArea(pair.getFirst()); - text.setEditable(false); - text.setOpaque(false); - add(text, c); - c.gridx++; - } - int saveY = ++c.gridy; - - c.gridx = 0; - for (int type = 0; type < 4; type++) { - JLabel text = new JLabel("n=" + String.valueOf(datasets[type])); - text.setOpaque(false); - add(text, c); - c.gridy++; - } - - c.gridy = saveY; - for (int type = 0; type < 4; type++) { - c.gridx = 1; - - for (Pair pair : generators) { - List points = null; - int samples = datasets[type]; - switch (type) { - case 0: - points = makeRandom(samples, pair.getValue()); - break; - case 1: - points = makeRandom(samples, pair.getValue()); - break; - case 2: - points = makeRandom(samples, pair.getValue()); - break; - case 3: - points = makeCircle(samples, pair.getValue()); - break; - } - add(new Plot(points), c); - c.gridx++; - } - - c.gridy++; - } - } - } - - @SuppressWarnings("serial") - public static class Plot extends JComponent { - - private static double PAD = 10; - - private List points; - - public Plot(final List points) { - this.points = points; - } - - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D)g; - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - int w = getWidth(); - int h = getHeight(); - - g2.clearRect(0, 0, w, h); - - g2.setPaint(Color.black); - g2.drawRect(0, 0, w - 1, h - 1); - - for (Vector2D point : points) { - Vector2D p = transform(point, w, h); - double[] arr = p.toArray(); - g2.draw(new Rectangle2D.Double(arr[0] - 1, arr[1] - 1, 2, 2)); - } - } - - @Override - public Dimension getPreferredSize() { - return new Dimension(140, 140); - } - - private Vector2D transform(Vector2D point, int width, int height) { - double[] arr = point.toArray(); - return new Vector2D(new double[] { PAD + (arr[0] + 1) / 2.0 * (width - 2 * PAD), - height - PAD - (arr[1] + 1) / 2.0 * (height - 2 * PAD) }); - } - } - - public static void main(String[] args) { - ExampleUtils.showExampleFrame(new Display()); - } -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/RealDistributionComparison.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/RealDistributionComparison.java b/src/userguide/java/org/apache/commons/math4/userguide/RealDistributionComparison.java deleted file mode 100644 index 8ad4d1f..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/RealDistributionComparison.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import org.apache.commons.complex.distribution.BetaDistribution; -import org.apache.commons.complex.distribution.CauchyDistribution; -import org.apache.commons.complex.distribution.ChiSquaredDistribution; -import org.apache.commons.complex.distribution.ExponentialDistribution; -import org.apache.commons.complex.distribution.FDistribution; -import org.apache.commons.complex.distribution.GammaDistribution; -import org.apache.commons.complex.distribution.LevyDistribution; -import org.apache.commons.complex.distribution.LogNormalDistribution; -import org.apache.commons.complex.distribution.NormalDistribution; -import org.apache.commons.complex.distribution.ParetoDistribution; -import org.apache.commons.complex.distribution.RealDistribution; -import org.apache.commons.complex.distribution.TDistribution; -import org.apache.commons.complex.distribution.WeibullDistribution; -import org.apache.commons.complex.random.MersenneTwister; -import org.apache.commons.complex.random.RandomGenerator; -import org.apache.commons.complex.util.FastMath; -import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame; - -import com.xeiam.xchart.Chart; -import com.xeiam.xchart.ChartBuilder; -import com.xeiam.xchart.Series; -import com.xeiam.xchart.SeriesMarker; -import com.xeiam.xchart.StyleManager.ChartType; -import com.xeiam.xchart.StyleManager.LegendPosition; -import com.xeiam.xchart.XChartPanel; - -/** - * Displays pdf/cdf for real distributions. - */ -public class RealDistributionComparison { - - public static void addPDFSeries(Chart chart, RealDistribution distribution, String desc, int lowerBound, int upperBound) { - // generates Log data - List xData = new ArrayList(); - List yData = new ArrayList(); - int samples = 100; - double stepSize = (upperBound - lowerBound) / (double) samples; - for (double x = lowerBound; x <= upperBound; x += stepSize) { - try { - double density = distribution.density(x); - if (! Double.isInfinite(density) && ! Double.isNaN(density)) { - xData.add(x); - yData.add(density); - } - } catch (Exception e) { - // ignore - // some distributions may reject certain values depending on the parameter settings - } - } - - Series series = chart.addSeries(desc, xData, yData); - series.setMarker(SeriesMarker.NONE); - series.setLineStyle(new BasicStroke(1.2f)); - } - - public static void addCDFSeries(Chart chart, RealDistribution distribution, String desc, int lowerBound, int upperBound) { - // generates Log data - List xData = new ArrayList(); - List yData = new ArrayList(); - int samples = 100; - double stepSize = (upperBound - lowerBound) / (double) samples; - for (double x = lowerBound; x <= upperBound; x += stepSize) { - double density = distribution.cumulativeProbability(x); - if (! Double.isInfinite(density) && ! Double.isNaN(density)) { - xData.add(x); - yData.add(density); - } - } - - Series series = chart.addSeries(desc, xData, yData); - series.setMarker(SeriesMarker.NONE); - series.setLineStyle(new BasicStroke(1.2f)); - } - - public static Chart createChart(String title, int minX, int maxX, LegendPosition position) { - Chart chart = new ChartBuilder().width(235).height(200).build(); - - // Customize Chart - chart.setChartTitle(title); - chart.getStyleManager().setChartTitleVisible(true); - chart.getStyleManager().setChartTitleFont(new Font("Arial", Font.PLAIN, 10)); - chart.getStyleManager().setLegendPosition(position); - chart.getStyleManager().setLegendVisible(true); - chart.getStyleManager().setLegendFont(new Font("Arial", Font.PLAIN, 10)); - chart.getStyleManager().setLegendPadding(6); - chart.getStyleManager().setLegendSeriesLineLength(6); - chart.getStyleManager().setAxisTickLabelsFont(new Font("Arial", Font.PLAIN, 9)); - - chart.getStyleManager().setXAxisMin(minX); - chart.getStyleManager().setXAxisMax(maxX); - chart.getStyleManager().setChartBackgroundColor(Color.white); - chart.getStyleManager().setChartPadding(4); - - chart.getStyleManager().setChartType(ChartType.Line); - return chart; - } - - public static JComponent createComponent(String distributionName, int minX, int maxX, String[] seriesText, RealDistribution... series) { - JComponent container = new JPanel(); - container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS)); - - container.add(new JLabel(distributionName)); - - Chart chart = createChart("PDF", minX, maxX, LegendPosition.InsideNE); - int i = 0; - for (RealDistribution d : series) { - addPDFSeries(chart, d, seriesText[i++], minX, maxX); - } - container.add(new XChartPanel(chart)); - - chart = createChart("CDF", minX, maxX, LegendPosition.InsideSE); - i = 0; - for (RealDistribution d : series) { - addCDFSeries(chart, d, seriesText[i++], minX, maxX); - } - container.add(new XChartPanel(chart)); - - container.setBorder(BorderFactory.createLineBorder(Color.black, 1)); - return container; - } - - @SuppressWarnings("serial") - public static class Display extends ExampleFrame { - - private JComponent container; - - public Display() { - setTitle("Commons-Math: Real distributions overview"); - setSize(1320, 920); - - container = new JPanel(); - container.setLayout(new GridBagLayout()); - - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.VERTICAL; - c.gridx = 0; - c.gridy = 0; - c.insets = new Insets(2, 2, 2, 2); - - JComponent comp = null; - - comp = createComponent("Normal", -5, 5, - new String[] { "μ=0,σ\u00B2=0.2", "μ=0,σ\u00B2=1", "μ=0,σ\u00B2=5", "μ=-2,σ\u00B2=0.5" }, - new NormalDistribution(0, FastMath.sqrt(0.2)), - new NormalDistribution(), - new NormalDistribution(0, FastMath.sqrt(5)), - new NormalDistribution(-2, FastMath.sqrt(0.5))); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Beta", 0, 1, - new String[] { "α=β=0.5", "α=5,β=1", "α=1,β=3", "α=2,β=2", "α=2,β=5" }, - new BetaDistribution(0.5, 0.5), - new BetaDistribution(5, 1), - new BetaDistribution(1, 3), - new BetaDistribution(2, 2), - new BetaDistribution(2, 5)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Cauchy", -5, 5, - new String[] { "x=0,γ=0.5", "x=0,γ=1", "x=0,γ=2", "x=-2,γ=1" }, - new CauchyDistribution(0, 0.5), - new CauchyDistribution(0, 1), - new CauchyDistribution(0, 2), - new CauchyDistribution(-2, 1)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("ChiSquared", 0, 5, - new String[] { "k=1", "k=2", "k=3", "k=4", "k=6" }, - new ChiSquaredDistribution(1), - new ChiSquaredDistribution(2), - new ChiSquaredDistribution(3), - new ChiSquaredDistribution(4), - new ChiSquaredDistribution(6)); - container.add(comp, c); - - c.gridy++; - c.gridx = 0; - comp = createComponent("Exponential", 0, 5, - new String[] { "λ=0.5", "λ=1", "λ=1.5", "λ=2.5" }, - new ExponentialDistribution(0.5), - new ExponentialDistribution(1), - new ExponentialDistribution(1.5), - new ExponentialDistribution(2.5)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Fisher-Snedecor", 0, 5, - new String[] { "d1=1,d2=1", "d1=2,d2=1", "d1=5,d2=2", "d1=100,d2=1", "d1=100,d2=100" }, - new FDistribution(1, 1), - new FDistribution(2, 1), - new FDistribution(5, 2), - new FDistribution(100, 1), - new FDistribution(100, 100)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Gamma", 0, 20, - new String[] { "k=1,θ=2", "k=2,θ=2", "k=3,θ=2", "k=5,θ=1", "k=9,θ=0.5" }, - new GammaDistribution(1, 2), - new GammaDistribution(2, 2), - new GammaDistribution(3, 2), - new GammaDistribution(5, 1), - new GammaDistribution(9, 0.5)); - container.add(comp, c); - - c.gridx++; - RandomGenerator rng = new MersenneTwister(0); - comp = createComponent("Levy", 0, 3, - new String[] { "c=0.5", "c=1", "c=2", "c=4", "c=8" }, - new LevyDistribution(rng, 0, 0.5), - new LevyDistribution(rng, 0, 1), - new LevyDistribution(rng, 0, 2), - new LevyDistribution(rng, 0, 4), - new LevyDistribution(rng, 0, 8)); - container.add(comp, c); - - c.gridy++; - c.gridx = 0; - comp = createComponent("Log-Normal", 0, 3, - new String[] { "μ=0,σ\u00B2=10", "μ=0,σ\u00B2=1.5", "μ=0,σ\u00B2=1", "μ=0,σ\u00B2=0.5", "μ=0,σ\u00B2=0.25", "μ=0,σ\u00B2=0.125" }, - new LogNormalDistribution(0, 10), - new LogNormalDistribution(0, 1.5), - new LogNormalDistribution(0, 1), - new LogNormalDistribution(0, 0.5), - new LogNormalDistribution(0, 0.25), - new LogNormalDistribution(0, 0.125)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Pareto", 0, 5, - new String[] { "x=1,α=1", "x=1,α=2", "x=1,α=3", "x=1,α=10" }, - new ParetoDistribution(1, 1), - new ParetoDistribution(1, 2), - new ParetoDistribution(1, 3), - new ParetoDistribution(1, 10)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Student-T", -5, 5, - new String[] { "df=1", "df=2", "df=5", "df=10000" }, - new TDistribution(1), - new TDistribution(2), - new TDistribution(5), - new TDistribution(10000)); - container.add(comp, c); - - c.gridx++; - comp = createComponent("Weibull", 0, 3, - new String[] { "λ=0.5,k=1", "λ=1,k=1", "λ=1.5,k=1", "λ=5,k=1" }, - new WeibullDistribution(0.5, 1), - new WeibullDistribution(1, 1), - new WeibullDistribution(1.5, 1), - new WeibullDistribution(5, 1)); - container.add(comp, c); - - JScrollPane scrollPane = new JScrollPane(container); - add(scrollPane); - - } - - @Override - public Component getMainPanel() { - return container; - } - - } - - public static void main(String[] args) { - ExampleUtils.showExampleFrame(new Display()); - } -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java b/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java deleted file mode 100644 index 6313054..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide.clustering; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Graphics; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; - -import org.apache.commons.complex.ml.clustering.CentroidCluster; -import org.apache.commons.complex.ml.clustering.Clusterable; -import org.apache.commons.complex.ml.clustering.KMeansPlusPlusClusterer; -import org.apache.commons.complex.userguide.ExampleUtils; -import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame; - -/** - * This example shows how clustering can be applied to images. - */ -@SuppressWarnings("serial") -public class ImageClusteringExample { - - public static class Display extends ExampleFrame { - - private BufferedImage referenceImage; - private BufferedImage clusterImage; - - private Raster referenceRaster; - - private ImagePainter painter; - - private JSpinner clusterSizeSpinner; - - public Display() throws Exception { - setTitle("Commons-Math: Image Clustering Example"); - setSize(900, 350); - - setLayout(new FlowLayout()); - - Box bar = Box.createHorizontalBox(); - - referenceImage = ExampleUtils.resizeImage( - ImageIO.read(new File("resources/ColorfulBird.jpg")), - 350, - 240, - BufferedImage.TYPE_INT_RGB); - - referenceRaster = referenceImage.getData(); - - clusterImage = new BufferedImage(referenceImage.getWidth(), - referenceImage.getHeight(), - BufferedImage.TYPE_INT_RGB); - - JLabel picLabel = new JLabel(new ImageIcon(referenceImage)); - bar.add(picLabel); - - painter = new ImagePainter(clusterImage.getWidth(), clusterImage.getHeight()); - bar.add(painter); - - JPanel controlBox = new JPanel(); - controlBox.setLayout(new GridLayout(5, 1)); - controlBox.setBorder(BorderFactory.createLineBorder(Color.black, 1)); - - JPanel sizeBox = new JPanel(); - JLabel sizeLabel = new JLabel("Clusters:"); - sizeBox.add(sizeLabel); - - SpinnerNumberModel model = new SpinnerNumberModel(3, 2, 10, 1); - clusterSizeSpinner = new JSpinner(model); - - sizeLabel.setLabelFor(clusterSizeSpinner); - sizeBox.add(clusterSizeSpinner); - controlBox.add(sizeBox, BorderLayout.NORTH); - - JButton startButton = new JButton("Cluster"); - startButton.setActionCommand("cluster"); - controlBox.add(startButton, BorderLayout.CENTER); - - bar.add(controlBox); - - add(bar); - - startButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - clusterImage(); - } - }); - } - - private void clusterImage() { - List pixels = new ArrayList(); - for (int row = 0; row < referenceImage.getHeight(); row++) { - for (int col = 0; col < referenceImage.getWidth(); col++) { - pixels.add(new PixelClusterable(col, row)); - } - } - - int clusterSize = ((Number) clusterSizeSpinner.getValue()).intValue(); - KMeansPlusPlusClusterer clusterer = - new KMeansPlusPlusClusterer(clusterSize); - List> clusters = clusterer.cluster(pixels); - - WritableRaster raster = clusterImage.getRaster(); - for (CentroidCluster cluster : clusters) { - double[] color = cluster.getCenter().getPoint(); - for (PixelClusterable pixel : cluster.getPoints()) { - raster.setPixel(pixel.x, pixel.y, color); - } - } - - Display.this.repaint(); - } - - private class PixelClusterable implements Clusterable { - - private final int x; - private final int y; - private double[] color; - - public PixelClusterable(int x, int y) { - this.x = x; - this.y = y; - this.color = null; - } - - @Override - public double[] getPoint() { - if (color == null) { - color = referenceRaster.getPixel(x, y, (double[]) null); - } - return color; - } - - } - - private class ImagePainter extends Component { - - private int width; - private int height; - - public ImagePainter(int width, int height) { - this.width = width; - this.height = height; - } - - public Dimension getPreferredSize() { - return new Dimension(width, height); - } - - @Override - public Dimension getMinimumSize() { - return getPreferredSize(); - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); - } - - public void paint(Graphics g) { - g.drawImage(clusterImage, 0, 0, this); - } - } - } - - public static void main(String[] args) throws Exception { - ExampleUtils.showExampleFrame(new Display()); - } -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/filter/CannonballExample.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/filter/CannonballExample.java b/src/userguide/java/org/apache/commons/math4/userguide/filter/CannonballExample.java deleted file mode 100644 index 984c914..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/filter/CannonballExample.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with this - * work for additional information regarding copyright ownership. The ASF - * licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law - * or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - */ - -package org.apache.commons.complex.userguide.filter; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.JComponent; -import javax.swing.JPanel; - -import org.apache.commons.complex.filter.DefaultMeasurementModel; -import org.apache.commons.complex.filter.DefaultProcessModel; -import org.apache.commons.complex.filter.KalmanFilter; -import org.apache.commons.complex.filter.MeasurementModel; -import org.apache.commons.complex.filter.ProcessModel; -import org.apache.commons.complex.linear.MatrixUtils; -import org.apache.commons.complex.linear.RealMatrix; -import org.apache.commons.complex.linear.RealVector; -import org.apache.commons.complex.random.RandomGenerator; -import org.apache.commons.complex.random.Well19937c; -import org.apache.commons.complex.util.FastMath; -import org.apache.commons.complex.userguide.ExampleUtils; -import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame; - -import com.xeiam.xchart.Chart; -import com.xeiam.xchart.ChartBuilder; -import com.xeiam.xchart.Series; -import com.xeiam.xchart.SeriesLineStyle; -import com.xeiam.xchart.SeriesMarker; -import com.xeiam.xchart.XChartPanel; -import com.xeiam.xchart.StyleManager.ChartType; -import com.xeiam.xchart.StyleManager.LegendPosition; - -public class CannonballExample { - - public static class Cannonball { - - private final double[] gravity = { 0, -9.81 }; - private final double[] velocity; - private final double[] location; - - private final double timeslice; - private final double measurementNoise; - - private final RandomGenerator rng; - - public Cannonball(double timeslice, double angle, double initialVelocity, double measurementNoise, int seed) { - this.timeslice = timeslice; - - final double angleInRadians = FastMath.toRadians(angle); - this.velocity = new double[] { - initialVelocity * FastMath.cos(angleInRadians), - initialVelocity * FastMath.sin(angleInRadians) - }; - - this.location = new double[] { 0, 0 }; - - this.measurementNoise = measurementNoise; - this.rng = new Well19937c(seed); - } - - public double getX() { - return location[0]; - } - - public double getY() { - return location[1]; - } - - public double getMeasuredX() { - return location[0] + rng.nextGaussian() * measurementNoise; - } - - public double getMeasuredY() { - return location[1] + rng.nextGaussian() * measurementNoise; - } - - public double getXVelocity() { - return velocity[0]; - } - - public double getYVelocity() { - return velocity[1]; - } - - public void step() { - // Break gravitational force into a smaller time slice. - double[] slicedGravity = gravity.clone(); - for ( int i = 0; i < slicedGravity.length; i++ ) { - slicedGravity[i] *= timeslice; - } - - // Apply the acceleration to velocity. - double[] slicedVelocity = velocity.clone(); - for ( int i = 0; i < velocity.length; i++ ) { - velocity[i] += slicedGravity[i]; - slicedVelocity[i] = velocity[i] * timeslice; - location[i] += slicedVelocity[i]; - } - - // Cannonballs shouldn't go into the ground. - if ( location[1] < 0 ) { - location[1] = 0; - } - } - } - - public static void cannonballTest(Chart chart) { - - // time interval for each iteration - final double dt = 0.1; - // the number of iterations to run - final int iterations = 144; - // measurement noise (m) - final double measurementNoise = 30; - // initial velocity of the cannonball - final double initialVelocity = 100; - // shooting angle - final double angle = 45; - - // the cannonball itself - final Cannonball cannonball = new Cannonball(dt, angle, initialVelocity, measurementNoise, 1000); - - // A = [ 1, dt, 0, 0 ] => x(n+1) = x(n) + vx(n) - // [ 0, 1, 0, 0 ] => vx(n+1) = vx(n) - // [ 0, 0, 1, dt ] => y(n+1) = y(n) + vy(n) - // [ 0, 0, 0, 1 ] => vy(n+1) = vy(n) - final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { - { 1, dt, 0, 0 }, - { 0, 1, 0, 0 }, - { 0, 0, 1, dt }, - { 0, 0, 0, 1 } - }); - - // The control vector, which adds acceleration to the kinematic equations. - // 0 => x(n+1) = x(n+1) - // 0 => vx(n+1) = vx(n+1) - // -9.81*dt^2 => y(n+1) = y(n+1) - 1/2 * 9.81 * dt^2 - // -9.81*dt => vy(n+1) = vy(n+1) - 9.81 * dt - final RealVector controlVector = - MatrixUtils.createRealVector(new double[] { 0, 0, 0.5 * -9.81 * dt * dt, -9.81 * dt } ); - - // The control matrix B only update y and vy, see control vector - final RealMatrix B = MatrixUtils.createRealMatrix(new double[][] { - { 0, 0, 0, 0 }, - { 0, 0, 0, 0 }, - { 0, 0, 1, 0 }, - { 0, 0, 0, 1 } - }); - - // After state transition and control, here are the equations: - // - // x(n+1) = x(n) + vx(n) - // vx(n+1) = vx(n) - // y(n+1) = y(n) + vy(n) - 0.5 * 9.81 * dt^2 - // vy(n+1) = vy(n) + -9.81 * dt - // - // Which, if you recall, are the equations of motion for a parabola. - - // We only observe the x/y position of the cannonball - final RealMatrix H = MatrixUtils.createRealMatrix(new double[][] { - { 1, 0, 0, 0 }, - { 0, 0, 0, 0 }, - { 0, 0, 1, 0 }, - { 0, 0, 0, 0 } - }); - - // This is our guess of the initial state. I intentionally set the Y value - // wrong to illustrate how fast the Kalman filter will pick up on that. - final double speedX = cannonball.getXVelocity(); - final double speedY = cannonball.getYVelocity(); - final RealVector initialState = MatrixUtils.createRealVector(new double[] { 0, speedX, 100, speedY } ); - - // The initial error covariance matrix, the variance = noise^2 - final double var = measurementNoise * measurementNoise; - final RealMatrix initialErrorCovariance = MatrixUtils.createRealMatrix(new double[][] { - { var, 0, 0, 0 }, - { 0, 1e-3, 0, 0 }, - { 0, 0, var, 0 }, - { 0, 0, 0, 1e-3 } - }); - - // we assume no process noise -> zero matrix - final RealMatrix Q = MatrixUtils.createRealMatrix(4, 4); - - // the measurement covariance matrix - final RealMatrix R = MatrixUtils.createRealMatrix(new double[][] { - { var, 0, 0, 0 }, - { 0, 1e-3, 0, 0 }, - { 0, 0, var, 0 }, - { 0, 0, 0, 1e-3 } - }); - - final ProcessModel pm = new DefaultProcessModel(A, B, Q, initialState, initialErrorCovariance); - final MeasurementModel mm = new DefaultMeasurementModel(H, R); - final KalmanFilter filter = new KalmanFilter(pm, mm); - - final List realX = new ArrayList(); - final List realY = new ArrayList(); - final List measuredX = new ArrayList(); - final List measuredY = new ArrayList(); - final List kalmanX = new ArrayList(); - final List kalmanY = new ArrayList(); - - for (int i = 0; i < iterations; i++) { - - // get real location - realX.add(cannonball.getX()); - realY.add(cannonball.getY()); - - // get measured location - final double mx = cannonball.getMeasuredX(); - final double my = cannonball.getMeasuredY(); - - measuredX.add(mx); - measuredY.add(my); - - // iterate the cannon simulation to the next timeslice. - cannonball.step(); - - final double[] state = filter.getStateEstimation(); - kalmanX.add(state[0]); - kalmanY.add(state[2]); - - // update the kalman filter with the measurements - filter.predict(controlVector); - filter.correct(new double[] { mx, 0, my, 0 } ); - } - - chart.setXAxisTitle("Distance (m)"); - chart.setYAxisTitle("Height (m)"); - - Series dataset = chart.addSeries("true", realX, realY); - dataset.setMarker(SeriesMarker.NONE); - - dataset = chart.addSeries("measured", measuredX, measuredY); - dataset.setLineStyle(SeriesLineStyle.DOT_DOT); - dataset.setMarker(SeriesMarker.NONE); - - dataset = chart.addSeries("kalman", kalmanX, kalmanY); - dataset.setLineColor(Color.red); - dataset.setLineStyle(SeriesLineStyle.DASH_DASH); - dataset.setMarker(SeriesMarker.NONE); - } - - public static Chart createChart(String title, LegendPosition position) { - Chart chart = new ChartBuilder().width(650).height(450).build(); - - // Customize Chart - chart.setChartTitle(title); - chart.getStyleManager().setChartTitleVisible(true); - chart.getStyleManager().setChartTitleFont(new Font("Arial", Font.PLAIN, 12)); - chart.getStyleManager().setLegendPosition(position); - chart.getStyleManager().setLegendVisible(true); - chart.getStyleManager().setLegendFont(new Font("Arial", Font.PLAIN, 12)); - chart.getStyleManager().setLegendPadding(6); - chart.getStyleManager().setLegendSeriesLineLength(10); - chart.getStyleManager().setAxisTickLabelsFont(new Font("Arial", Font.PLAIN, 10)); - - chart.getStyleManager().setChartBackgroundColor(Color.white); - chart.getStyleManager().setChartPadding(4); - - chart.getStyleManager().setChartType(ChartType.Line); - return chart; - } - - public static JComponent createComponent() { - JComponent container = new JPanel(); - container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS)); - - Chart chart = createChart("Cannonball", LegendPosition.InsideNE); - cannonballTest(chart); - container.add(new XChartPanel(chart)); - - container.setBorder(BorderFactory.createLineBorder(Color.black, 1)); - return container; - } - - @SuppressWarnings("serial") - public static class Display extends ExampleFrame { - - private JComponent container; - - public Display() { - setTitle("Commons Math: Kalman Filter - Cannonball"); - setSize(800, 600); - - container = new JPanel(); - JComponent comp = createComponent(); - container.add(comp); - - add(container); - } - - @Override - public Component getMainPanel() { - return container; - } - } - - public static void main(String[] args) { - ExampleUtils.showExampleFrame(new Display()); - } -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/filter/ConstantVoltageExample.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/filter/ConstantVoltageExample.java b/src/userguide/java/org/apache/commons/math4/userguide/filter/ConstantVoltageExample.java deleted file mode 100644 index 3fd35ef..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/filter/ConstantVoltageExample.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with this - * work for additional information regarding copyright ownership. The ASF - * licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law - * or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - */ - -package org.apache.commons.complex.userguide.filter; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.JComponent; -import javax.swing.JPanel; - -import org.apache.commons.complex.filter.DefaultMeasurementModel; -import org.apache.commons.complex.filter.DefaultProcessModel; -import org.apache.commons.complex.filter.KalmanFilter; -import org.apache.commons.complex.filter.MeasurementModel; -import org.apache.commons.complex.filter.ProcessModel; -import org.apache.commons.complex.linear.Array2DRowRealMatrix; -import org.apache.commons.complex.linear.ArrayRealVector; -import org.apache.commons.complex.linear.RealMatrix; -import org.apache.commons.complex.linear.RealVector; -import org.apache.commons.complex.random.RandomGenerator; -import org.apache.commons.complex.random.Well19937c; -import org.apache.commons.complex.userguide.ExampleUtils; -import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame; - -import com.xeiam.xchart.Chart; -import com.xeiam.xchart.ChartBuilder; -import com.xeiam.xchart.Series; -import com.xeiam.xchart.SeriesLineStyle; -import com.xeiam.xchart.SeriesMarker; -import com.xeiam.xchart.XChartPanel; -import com.xeiam.xchart.StyleManager.ChartType; -import com.xeiam.xchart.StyleManager.LegendPosition; - -public class ConstantVoltageExample { - - public static class VoltMeter { - - private final double initialVoltage; - private final double processNoise; - private final double measurementNoise; - private final RandomGenerator rng; - - private double voltage; - - public VoltMeter(double voltage, double processNoise, double measurementNoise, int seed) { - this.initialVoltage = voltage; - this.voltage = voltage; - this.processNoise = processNoise; - this.measurementNoise = measurementNoise; - rng = new Well19937c(seed); - } - - /** - * Returns the real voltage without any measurement noise. - * - * @return the real voltage - */ - public double getVoltage() { - return voltage; - } - - public double getMeasuredVoltage() { - return getVoltage() + rng.nextGaussian() * measurementNoise; - } - - public void step() { - // we apply only the process noise - voltage = initialVoltage + rng.nextGaussian() * processNoise; - } - } - - /** constant voltage test */ - public static void constantVoltageTest(Chart chart1, Chart chart2) { - - final double voltage = 1.25d; - final double measurementNoise = 0.2d; // measurement noise (V) - std dev - final double processNoise = 1e-5d; - - final VoltMeter voltMeter = new VoltMeter(voltage, processNoise, measurementNoise, 2); - - // the state transition matrix -> constant - final RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d }); - - // the control matrix -> no control input - final RealMatrix B = new Array2DRowRealMatrix(new double[] { 0d }); - - // the measurement matrix -> we measure the voltage directly - final RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d }); - - // the initial state vector -> slightly wrong - final RealVector x0 = new ArrayRealVector(new double[] { 1.45 }); - - // the process covariance matrix - final RealMatrix Q = new Array2DRowRealMatrix(new double[] { processNoise * processNoise }); - - // the initial error covariance -> assume a large error at the beginning - final RealMatrix P0 = new Array2DRowRealMatrix(new double[] { 0.1 }); - - // the measurement covariance matrix -> put the "real" variance - RealMatrix R = new Array2DRowRealMatrix(new double[] { measurementNoise * measurementNoise }); - - final ProcessModel pm = new DefaultProcessModel(A, B, Q, x0, P0); - final MeasurementModel mm = new DefaultMeasurementModel(H, R); - final KalmanFilter filter = new KalmanFilter(pm, mm); - - final List xAxis = new ArrayList(); - final List realVoltageSeries = new ArrayList(); - final List measuredVoltageSeries = new ArrayList(); - final List kalmanVoltageSeries = new ArrayList(); - - final List covSeries = new ArrayList(); - - for (int i = 0; i < 300; i++) { - xAxis.add(i); - - voltMeter.step(); - - realVoltageSeries.add(voltMeter.getVoltage()); - - // get the measured voltage from the volt meter - final double measuredVoltage = voltMeter.getMeasuredVoltage(); - measuredVoltageSeries.add(measuredVoltage); - - kalmanVoltageSeries.add(filter.getStateEstimation()[0]); - covSeries.add(filter.getErrorCovariance()[0][0]); - - filter.predict(); - filter.correct(new double[] { measuredVoltage }); - } - - chart1.setYAxisTitle("Voltage"); - chart1.setXAxisTitle("Iteration"); - - Series dataset = chart1.addSeries("real", xAxis, realVoltageSeries); - dataset.setMarker(SeriesMarker.NONE); - - dataset = chart1.addSeries("measured", xAxis, measuredVoltageSeries); - dataset.setLineStyle(SeriesLineStyle.DOT_DOT); - dataset.setMarker(SeriesMarker.NONE); - - dataset = chart1.addSeries("filtered", xAxis, kalmanVoltageSeries); - dataset.setLineColor(Color.red); - dataset.setLineStyle(SeriesLineStyle.DASH_DASH); - dataset.setMarker(SeriesMarker.NONE); - - // Error covariance chart - - chart2.setYAxisTitle("(Voltage)²"); - chart2.setXAxisTitle("Iteration"); - - dataset = chart2.addSeries("cov", xAxis, covSeries); - dataset.setLineColor(Color.black); - dataset.setLineStyle(SeriesLineStyle.SOLID); - dataset.setMarker(SeriesMarker.NONE); - - } - - public static Chart createChart(String title, int width, int height, - LegendPosition position, boolean legendVisible) { - Chart chart = new ChartBuilder().width(width).height(height).build(); - - // Customize Chart - chart.setChartTitle(title); - chart.getStyleManager().setChartTitleVisible(true); - chart.getStyleManager().setChartTitleFont(new Font("Arial", Font.PLAIN, 12)); - chart.getStyleManager().setLegendPosition(position); - chart.getStyleManager().setLegendVisible(legendVisible); - chart.getStyleManager().setLegendFont(new Font("Arial", Font.PLAIN, 12)); - chart.getStyleManager().setLegendPadding(6); - chart.getStyleManager().setLegendSeriesLineLength(10); - chart.getStyleManager().setAxisTickLabelsFont(new Font("Arial", Font.PLAIN, 10)); - - chart.getStyleManager().setChartBackgroundColor(Color.white); - chart.getStyleManager().setChartPadding(4); - - chart.getStyleManager().setChartType(ChartType.Line); - return chart; - } - - public static JComponent createComponent() { - JComponent container = new JPanel(); - container.setLayout(new BoxLayout(container, BoxLayout.LINE_AXIS)); - - Chart chart1 = createChart("Voltage", 550, 450, LegendPosition.InsideNE, true); - Chart chart2 = createChart("Error Covariance", 450, 450, LegendPosition.InsideNE, false); - - constantVoltageTest(chart1, chart2); - - container.add(new XChartPanel(chart1)); - container.add(new XChartPanel(chart2)); - - container.setBorder(BorderFactory.createLineBorder(Color.black, 1)); - return container; - } - - @SuppressWarnings("serial") - public static class Display extends ExampleFrame { - - private JComponent container; - - public Display() { - setTitle("Commons-Math: Kalman Filter example"); - setSize(1100, 700); - - container = new JPanel(); - - JComponent comp = createComponent(); - container.add(comp); - - add(container); - } - - @Override - public Component getMainPanel() { - return container; - } - } - - public static void main(String[] args) { - ExampleUtils.showExampleFrame(new Display()); - } - -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/genetics/HelloWorldExample.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/genetics/HelloWorldExample.java b/src/userguide/java/org/apache/commons/math4/userguide/genetics/HelloWorldExample.java deleted file mode 100644 index c86a7d7..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/genetics/HelloWorldExample.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide.genetics; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.complex.exception.util.LocalizedFormats; -import org.apache.commons.complex.genetics.AbstractListChromosome; -import org.apache.commons.complex.genetics.Chromosome; -import org.apache.commons.complex.genetics.ElitisticListPopulation; -import org.apache.commons.complex.genetics.GeneticAlgorithm; -import org.apache.commons.complex.genetics.InvalidRepresentationException; -import org.apache.commons.complex.genetics.MutationPolicy; -import org.apache.commons.complex.genetics.OnePointCrossover; -import org.apache.commons.complex.genetics.Population; -import org.apache.commons.complex.genetics.StoppingCondition; -import org.apache.commons.complex.genetics.TournamentSelection; -import org.apache.commons.complex.util.FastMath; -import org.apache.commons.complex.util.Precision; - -public class HelloWorldExample { - public static final int POPULATION_SIZE = 1000; - public static final double CROSSOVER_RATE = 0.9; - public static final double MUTATION_RATE = 0.03; - public static final double ELITISM_RATE = 0.1; - public static final int TOURNAMENT_ARITY = 2; - - public static final String TARGET_STRING = "Hello World!"; - public static final int DIMENSION = TARGET_STRING.length(); - - public static void main(String[] args) { - long startTime = System.currentTimeMillis(); - - // initialize a new genetic algorithm - GeneticAlgorithm ga = new GeneticAlgorithm(new OnePointCrossover(), CROSSOVER_RATE, - new RandomCharacterMutation(), MUTATION_RATE, - new TournamentSelection(TOURNAMENT_ARITY)); - - // initial population - Population initial = getInitialPopulation(); - - // stopping condition - StoppingCondition stoppingCondition = new StoppingCondition() { - - int generation = 0; - -// @Override - public boolean isSatisfied(Population population) { - Chromosome fittestChromosome = population.getFittestChromosome(); - - if (generation == 1 || generation % 10 == 0) { - System.out.println("Generation " + generation + ": " + fittestChromosome.toString()); - } - generation++; - - double fitness = fittestChromosome.fitness(); - if (Precision.equals(fitness, 0.0, 1e-6)) { - return true; - } else { - return false; - } - } - }; - - System.out.println("Starting evolution ..."); - - // run the algorithm - Population finalPopulation = ga.evolve(initial, stoppingCondition); - - // Get the end time for the simulation. - long endTime = System.currentTimeMillis(); - - // best chromosome from the final population - Chromosome best = finalPopulation.getFittestChromosome(); - System.out.println("Generation " + ga.getGenerationsEvolved() + ": " + best.toString()); - System.out.println("Total execution time: " + (endTime - startTime) + "ms"); - } - - private static List randomRepresentation(int length) { - return asList(RandomStringUtils.randomAscii(length)); - } - - private static List asList(String str) { - return Arrays.asList(ArrayUtils.toObject(str.toCharArray())); - } - - private static Population getInitialPopulation() { - List popList = new LinkedList(); - - for (int i = 0; i < POPULATION_SIZE; i++) { - popList.add(new StringChromosome(randomRepresentation(DIMENSION))); - } - return new ElitisticListPopulation(popList, 2 * popList.size(), ELITISM_RATE); - } - - /** - * String Chromosome represented by a list of characters. - */ - public static class StringChromosome extends AbstractListChromosome { - - public StringChromosome(List repr) { - super(repr); - } - - public StringChromosome(String str) { - this(asList(str)); - } - - public double fitness() { - String target = TARGET_STRING; - int f = 0; // start at 0; the best fitness - List chromosome = getRepresentation(); - for (int i = 0, c = target.length(); i < c; i++) { - // subtract the ascii difference between the target character and the chromosome character. - // Thus 'c' is fitter than 'd' when compared to 'a'. - f -= FastMath.abs(target.charAt(i) - chromosome.get(i).charValue()); - } - return f; - } - - @Override - protected void checkValidity(List repr) throws InvalidRepresentationException { - for (char c : repr) { - if (c < 32 || c > 126) { - throw new InvalidRepresentationException(LocalizedFormats.INVALID_FIXED_LENGTH_CHROMOSOME); - } - } - } - - public List getStringRepresentation() { - return getRepresentation(); - } - - @Override - public StringChromosome newFixedLengthChromosome(List repr) { - return new StringChromosome(repr); - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - for (Character i : getRepresentation()) { - sb.append(i.charValue()); - } - return String.format("(f=%s '%s')", getFitness(), sb.toString()); - } - - } - - private static class RandomCharacterMutation implements MutationPolicy { - public Chromosome mutate(Chromosome original) { - if (!(original instanceof StringChromosome)) { - throw new IllegalArgumentException(); - } - - StringChromosome strChromosome = (StringChromosome) original; - List characters = strChromosome.getStringRepresentation(); - - int mutationIndex = GeneticAlgorithm.getRandomGenerator().nextInt(characters.size()); - - List mutatedChromosome = new ArrayList(characters); - char newValue = (char) (32 + GeneticAlgorithm.getRandomGenerator().nextInt(127 - 32)); - mutatedChromosome.set(mutationIndex, newValue); - - return strChromosome.newFixedLengthChromosome(mutatedChromosome); - } - } -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/genetics/ImageEvolutionExample.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/genetics/ImageEvolutionExample.java b/src/userguide/java/org/apache/commons/math4/userguide/genetics/ImageEvolutionExample.java deleted file mode 100644 index 38ab9a2..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/genetics/ImageEvolutionExample.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide.genetics; - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; - -import org.apache.commons.complex.genetics.Chromosome; -import org.apache.commons.complex.genetics.ElitisticListPopulation; -import org.apache.commons.complex.genetics.GeneticAlgorithm; -import org.apache.commons.complex.genetics.Population; -import org.apache.commons.complex.genetics.TournamentSelection; -import org.apache.commons.complex.genetics.UniformCrossover; -import org.apache.commons.complex.userguide.ExampleUtils; -import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame; - -/** - * This example shows a more advanced use of a genetic algorithm: approximate a raster image - * with ~100 semi-transparent polygons of length 6. - *

- * The fitness function is quite simple yet expensive to compute: - * - * - draw the polygons of a chromosome to an image - * - compare each pixel with the corresponding reference image - *

- * To improve the speed of the calculation, we calculate the fitness not on the original image size, - * but rather on a scaled down version, which is sufficient to demonstrate the power of such a genetic algorithm. - *

- * TODO: - * - improve user interface - * - make algorithm parameters configurable - * - add a gallery of results after x iterations / minutes (either automatic or based on button click) - * - allow loading / selection of other images - * - add logging in the user interface, e.g. number of generations, time spent, ... - * - * @see Evolving Images with JavaScript and canvas (Nihilogic) - */ -@SuppressWarnings("serial") -public class ImageEvolutionExample { - - public static final int POPULATION_SIZE = 40; - public static final int TOURNAMENT_ARITY = 5; - public static final float MUTATION_RATE = 0.02f; - public static final float MUTATION_CHANGE = 0.1f; - - public static final int POLYGON_LENGTH = 6; - public static final int POLYGON_COUNT = 100; - - public static class Display extends ExampleFrame { - - private GeneticAlgorithm ga; - private Population currentPopulation; - private Chromosome bestFit; - - private Thread internalThread; - private volatile boolean noStopRequested; - - private BufferedImage ref; - - private BufferedImage referenceImage; - private BufferedImage testImage; - - private ImagePainter painter; - - public Display() throws Exception { - setTitle("Commons-Math: Image Evolution Example"); - setSize(600, 400); - - setLayout(new FlowLayout()); - - Box bar = Box.createHorizontalBox(); - - ref = ImageIO.read(new File("resources/monalisa.png")); - //ref = ImageIO.read(new File("resources/feather-small.gif")); - - referenceImage = resizeImage(ref, 50, 50, BufferedImage.TYPE_INT_ARGB); - testImage = new BufferedImage(referenceImage.getWidth(), referenceImage.getHeight(), BufferedImage.TYPE_INT_ARGB); - - JLabel picLabel = new JLabel(new ImageIcon(ref)); - bar.add(picLabel); - - painter = new ImagePainter(ref.getWidth(), ref.getHeight()); - bar.add(painter); - - // set the images used for calculating the fitness function: - // refImage - the reference image - // testImage - the test image to draw the current chromosome - PolygonChromosome.setRefImage(referenceImage); - PolygonChromosome.setTestImage(testImage); - - add(bar); - - JButton startButton = new JButton("Start"); - startButton.setActionCommand("start"); - add(startButton); - - startButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (isAlive()) { - stopRequest(); - } else { - startEvolution(); - } - } - }); - - // initialize a new genetic algorithm - ga = new GeneticAlgorithm(new UniformCrossover(0.5), 1.0, - new RandomPolygonMutation(MUTATION_RATE, MUTATION_CHANGE), 1.0, - new TournamentSelection(TOURNAMENT_ARITY)); - - // initial population - currentPopulation = getInitialPopulation(); - bestFit = currentPopulation.getFittestChromosome(); - } - - public boolean isAlive() { - return internalThread != null && internalThread.isAlive(); - } - - public void stopRequest() { - noStopRequested = false; - internalThread.interrupt(); - internalThread = null; - } - - public void startEvolution() { - noStopRequested = true; - Runnable r = new Runnable() { - public void run() { - int evolution = 0; - while (noStopRequested) { - currentPopulation = ga.nextGeneration(currentPopulation); - - System.out.println("generation: " + evolution++ + ": " + bestFit.toString()); - bestFit = currentPopulation.getFittestChromosome(); - - painter.repaint(); - } - } - }; - - internalThread = new Thread(r); - internalThread.start(); - } - - private class ImagePainter extends Component { - - private int width; - private int height; - - public ImagePainter(int width, int height) { - this.width = width; - this.height = height; - } - - public Dimension getPreferredSize() { - return new Dimension(width, height); - } - - @Override - public Dimension getMinimumSize() { - return getPreferredSize(); - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); - } - - public void paint(Graphics g) { - PolygonChromosome chromosome = (PolygonChromosome) bestFit; - chromosome.draw((Graphics2D) g, ref.getWidth(), ref.getHeight()); - } - - } - - } - - public static void main(String[] args) throws Exception { - ExampleUtils.showExampleFrame(new Display()); - } - - private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height, int type) throws IOException { - BufferedImage resizedImage = new BufferedImage(width, height, type); - Graphics2D g = resizedImage.createGraphics(); - g.drawImage(originalImage, 0, 0, width, height, null); - g.dispose(); - return resizedImage; - } - - private static Population getInitialPopulation() { - List popList = new LinkedList(); - for (int i = 0; i < POPULATION_SIZE; i++) { - popList.add(PolygonChromosome.randomChromosome(POLYGON_LENGTH, POLYGON_COUNT)); - } - return new ElitisticListPopulation(popList, popList.size(), 0.25); - } - -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/genetics/Polygon.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/genetics/Polygon.java b/src/userguide/java/org/apache/commons/math4/userguide/genetics/Polygon.java deleted file mode 100644 index 9fb4ef0..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/genetics/Polygon.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide.genetics; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.geom.GeneralPath; - -import org.apache.commons.complex.genetics.GeneticAlgorithm; -import org.apache.commons.complex.random.RandomGenerator; -import org.apache.commons.complex.util.FastMath; - -/** - * Represents a fixed size polgon with its fill color. - */ -public class Polygon { - - // the polygon in packed representation: - // index | data - // 0 | red component - // 1 | green component - // 2 | blue component - // 3 | alpha channel - // 4 | first x coordinate - // 5 | first y coordinate - // 6 | second x coordinate - // ... - // N | last y coordinate - // --------------------------- - /// size = 4 + 2*polygonlength - private float[] data; - - /** - * Creates a new random Polygon of the given length. - */ - public static Polygon randomPolygon(int length) { - final int polygonSize = 4 + 2 * length; - - final RandomGenerator random = GeneticAlgorithm.getRandomGenerator(); - - Polygon p = new Polygon(); - p.data = new float[polygonSize]; - - p.data[0] = random.nextFloat(); // r - p.data[1] = random.nextFloat(); // g - p.data[2] = random.nextFloat(); // b - p.data[3] = FastMath.max(0.2f, random.nextFloat() * random.nextFloat()); // a - - float px = random.nextFloat(); - float py = random.nextFloat(); - - for (int k = 0; k < length; k++) { - p.data[4 + 2*k] = px + (random.nextFloat() - 0.5f); - p.data[5 + 2*k] = py + (random.nextFloat() - 0.5f); - } - return p; - } - - /** - * Return a new Polygon, mutated with the given rate and amount. - *

- * Each component of the Polygon may be mutated according to the specified mutation rate. - * In case a component is going to be mutated, its value will be randomly modified in the - * uniform range of [-mutationAmount, +mutationAmount]. - * - * @param mutationRate the mutation rate - * @param mutationAmount the mutation amount - * @return a new Polygon - */ - public Polygon mutate(float mutationRate, float mutationAmount) { - Polygon mutated = new Polygon(); - int size = data.length; - mutated.data = new float[size]; - for (int i = 0; i < size; i++) { - float val = this.data[i]; - if (GeneticAlgorithm.getRandomGenerator().nextFloat() < mutationRate) { - val += GeneticAlgorithm.getRandomGenerator().nextFloat() * mutationAmount * 2 - mutationAmount; - - if (val < 0f) { - val = 0f; - } else if (val > 1f) { - val = 1f; - } - } - mutated.data[i] = val; - } - return mutated; - } - - /** - * Draw the Polygon to the buffer of the given size. - */ - public void draw(Graphics2D g, int width, int height) { - g.setColor(new Color(data[0], data[1], data[2], data[3])); - - GeneralPath path = new GeneralPath(); - path.moveTo(data[4] * width, data[5] * height); - - int polygonLength = (data.length - 4) / 2; - for (int j = 1; j < polygonLength; j++) { - path.lineTo(data[4 + j * 2] * width, data[5 + j * 2] * height); - } - path.closePath(); - - g.fill(path); - } -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/genetics/PolygonChromosome.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/genetics/PolygonChromosome.java b/src/userguide/java/org/apache/commons/math4/userguide/genetics/PolygonChromosome.java deleted file mode 100644 index c078cc4..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/genetics/PolygonChromosome.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide.genetics; - -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.complex.genetics.AbstractListChromosome; -import org.apache.commons.complex.genetics.Chromosome; -import org.apache.commons.complex.genetics.InvalidRepresentationException; - -/** - * A simple chromosome representing a list of polygons. - */ -public class PolygonChromosome extends AbstractListChromosome { - - /** The reference image for fitness testing. */ - private static BufferedImage refImage; - /** The image buffer used to draw the current chromosome during fitness testing. */ - private static BufferedImage testImage; - - public static void setRefImage(BufferedImage ref) { - refImage = ref; - } - - public static void setTestImage(BufferedImage image) { - testImage = image; - } - - public PolygonChromosome(List representation) { - super(representation); - } - - @Override - protected void checkValidity(List chromosomeRepresentation) throws InvalidRepresentationException { - // do nothing - } - - @Override - public AbstractListChromosome newFixedLengthChromosome(List chromosomeRepresentation) { - return new PolygonChromosome(chromosomeRepresentation); - } - - /** - * Return the internal representation, which is needed for our custom mutation policy. - * - * @return the list of polygons - */ - public List getPolygonRepresentation() { - return getRepresentation(); - } - - /** - * Calculate the fitness function for this chromosome. - *

- * For this purpose, we first draw the polygons on the test buffer, and - * then compare the resulting image pixel by pixel with the reference image. - */ - public double fitness() { - - Graphics2D g2 = testImage.createGraphics(); - - int width = testImage.getWidth(); - int height = testImage.getHeight(); - - draw(g2, width, height); - g2.dispose(); - - int[] refPixels = refImage.getData().getPixels(0, 0, refImage.getWidth(), refImage.getHeight(), (int[]) null); - int[] testPixels = testImage.getData().getPixels(0, 0, testImage.getWidth(), testImage.getHeight(), (int[]) null); - - int diff = 0; - int p = width * height * 4 - 1; // 4 channels: rgba - int idx = 0; - - do { - if (idx++ % 4 != 0) { // ignore the alpha channel for fitness - int dp = testPixels[p] - refPixels[p]; - if (dp < 0) { - diff -= dp; - } else { - diff += dp; - } - } - } while(--p > 0); - - return (1.0 - diff / (width * height * 3.0 * 256)); - } - - public void draw(Graphics2D g, int width, int height) { - g.setBackground(Color.WHITE); - g.clearRect(0, 0, width, height); - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); - - List polygons = getPolygonRepresentation(); - for (Polygon p : polygons) { - p.draw(g, width, height); - } - } - - @Override - public String toString() { - return String.format("(f=%s)", getFitness()); - } - - public static Chromosome randomChromosome(int polygonLength, int polygonCount) { - List list = new ArrayList(polygonCount); - for (int j = 0; j < polygonCount; j++) { - list.add(Polygon.randomPolygon(polygonLength)); - } - return new PolygonChromosome(list); - } - -} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/genetics/RandomPolygonMutation.java ---------------------------------------------------------------------- diff --git a/src/userguide/java/org/apache/commons/math4/userguide/genetics/RandomPolygonMutation.java b/src/userguide/java/org/apache/commons/math4/userguide/genetics/RandomPolygonMutation.java deleted file mode 100644 index af7f0e2..0000000 --- a/src/userguide/java/org/apache/commons/math4/userguide/genetics/RandomPolygonMutation.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.complex.userguide.genetics; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.complex.genetics.Chromosome; -import org.apache.commons.complex.genetics.MutationPolicy; - -public class RandomPolygonMutation implements MutationPolicy { - - private float mutationRate; - private float mutationAmount; - - public RandomPolygonMutation(float mutationRate, float mutationAmount) { - this.mutationRate = mutationRate; - this.mutationAmount = mutationAmount; - } - - public Chromosome mutate(Chromosome chromosome) { - if (!(chromosome instanceof PolygonChromosome)) { - throw new IllegalArgumentException(); - } - - PolygonChromosome polygons = (PolygonChromosome) chromosome; - List repr = polygons.getPolygonRepresentation(); - - List newRepr = new ArrayList(repr.size()); - for (Polygon p : repr) { - newRepr.add(p.mutate(mutationRate, mutationAmount)); - } - return new PolygonChromosome(newRepr); - } -}