You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by er...@apache.org on 2017/04/30 15:38:07 UTC
[1/3] commons-numbers git commit: Removed "Commons Math" code
examples.
Repository: commons-numbers
Updated Branches:
refs/heads/master bd596bee4 -> a960a5ca7
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/geometry/GeometryExample.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/geometry/GeometryExample.java b/src/userguide/java/org/apache/commons/math4/userguide/geometry/GeometryExample.java
deleted file mode 100644
index bfa3c48..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/geometry/GeometryExample.java
+++ /dev/null
@@ -1,280 +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.geometry;
-
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.geom.Point2D;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.swing.BorderFactory;
-import javax.swing.JButton;
-import javax.swing.JComponent;
-import javax.swing.JPanel;
-import javax.swing.JSplitPane;
-
-import org.apache.commons.complex.geometry.enclosing.Encloser;
-import org.apache.commons.complex.geometry.enclosing.EnclosingBall;
-import org.apache.commons.complex.geometry.enclosing.WelzlEncloser;
-import org.apache.commons.complex.geometry.euclidean.twod.DiskGenerator;
-import org.apache.commons.complex.geometry.euclidean.twod.Euclidean2D;
-import org.apache.commons.complex.geometry.euclidean.twod.Segment;
-import org.apache.commons.complex.geometry.euclidean.twod.Vector2D;
-import org.apache.commons.complex.geometry.euclidean.twod.hull.ConvexHull2D;
-import org.apache.commons.complex.geometry.euclidean.twod.hull.ConvexHullGenerator2D;
-import org.apache.commons.complex.geometry.euclidean.twod.hull.MonotoneChain;
-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;
-import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame;
-import org.piccolo2d.PCamera;
-import org.piccolo2d.PCanvas;
-import org.piccolo2d.PNode;
-import org.piccolo2d.event.PBasicInputEventHandler;
-import org.piccolo2d.event.PInputEvent;
-import org.piccolo2d.event.PMouseWheelZoomEventHandler;
-import org.piccolo2d.nodes.PPath;
-import org.piccolo2d.nodes.PText;
-
-/**
- * Simple example illustrating some parts of the geometry package.
- *
- * TODO:
- * - select tolerance level
- * - allow editing of the point set
- */
-public class GeometryExample {
-
- public static List<Vector2D> createRandomPoints(int size) {
- RandomGenerator random = new MersenneTwister();
-
- // create the cloud container
- List<Vector2D> points = new ArrayList<Vector2D>(size);
- // fill the cloud with a random distribution of points
- for (int i = 0; i < size; i++) {
- points.add(new Vector2D(FastMath.round(random.nextDouble() * 400 + 100),
- FastMath.round(random.nextDouble() * 400 + 100)));
- }
-
- return points;
- }
-
- public static List<Vector2D> createCircle(int samples) {
- List<Vector2D> points = new ArrayList<Vector2D>();
- final Vector2D center = new Vector2D(300, 300);
- double range = 2.0 * FastMath.PI;
- double step = range / (samples + 1);
- for (double angle = 0; angle < range; angle += step) {
- Vector2D circle = new Vector2D(FastMath.cos(angle), FastMath.sin(angle));
- points.add(circle.scalarMultiply(200).add(center));
- }
-
- return points;
- }
-
- public static List<Vector2D> createCross() {
- List<Vector2D> points = new ArrayList<Vector2D>();
-
- for (int i = 100; i < 500; i += 10) {
- points.add(new Vector2D(300, i));
- points.add(new Vector2D(i, 300));
- }
-
- return points;
- }
-
- public static PCanvas createCanvas() {
- final PCanvas canvas = new PCanvas();
- final PCamera camera = canvas.getCamera();
-
- final PText tooltipNode = new PText();
- tooltipNode.setPickable(false);
- camera.addChild(tooltipNode);
-
- camera.addInputEventListener(new PBasicInputEventHandler() {
- public void mouseMoved(final PInputEvent event) {
- updateToolTip(event);
- }
-
- public void mouseDragged(final PInputEvent event) {
- updateToolTip(event);
- }
-
- public void updateToolTip(final PInputEvent event) {
- final PNode n = event.getPickedNode();
- final Object object = (Object) n.getAttribute("tooltip");
- if (object != null) {
- final String tooltipString = object.toString();
- final Point2D p = event.getCanvasPosition();
-
- event.getPath().canvasToLocal(p, camera);
-
- tooltipNode.setText(tooltipString);
- tooltipNode.setOffset(p.getX() + 8, p.getY() - 8);
- } else {
- tooltipNode.setText(null);
- }
- }
- });
-
- // uninstall default zoom event handler
- canvas.removeInputEventListener(canvas.getZoomEventHandler());
-
- // install mouse wheel zoom event handler
- final PMouseWheelZoomEventHandler mouseWheelZoomEventHandler = new PMouseWheelZoomEventHandler();
- canvas.addInputEventListener(mouseWheelZoomEventHandler);
-
- return canvas;
- }
-
- @SuppressWarnings("serial")
- public static class Display extends ExampleFrame {
-
- private List<Vector2D> points;
- private PCanvas canvas;
- private JComponent container;
- private JComponent controlPanel;
-
- public Display() {
- setTitle("Commons Math: Geometry Examples");
- setSize(800, 700);
-
- container = new JPanel(new BorderLayout());
- canvas = createCanvas();
- container.add(canvas);
- container.setBorder(BorderFactory.createLineBorder(Color.black, 1));
-
- controlPanel = new JPanel();
- JButton random = new JButton("Randomize");
- controlPanel.add(random);
-
- random.addActionListener(new ActionListener() {
-
-// @Override
- public void actionPerformed(ActionEvent e) {
- canvas.getLayer().removeAllChildren();
-
- points = createRandomPoints(1000);
- paintConvexHull();
- }
- });
-
- JButton circle = new JButton("Circle");
- controlPanel.add(circle);
-
- circle.addActionListener(new ActionListener() {
-
-// @Override
- public void actionPerformed(ActionEvent e) {
- canvas.getLayer().removeAllChildren();
-
- points = createCircle(100);
- paintConvexHull();
- }
- });
-
- JButton cross = new JButton("Cross");
- controlPanel.add(cross);
-
- cross.addActionListener(new ActionListener() {
-
-// @Override
- public void actionPerformed(ActionEvent e) {
- canvas.getLayer().removeAllChildren();
-
- points = createCross();
- paintConvexHull();
- }
- });
-
- JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, container, controlPanel);
- splitpane.setDividerLocation(600);
-
- add(splitpane);
-
- points = createRandomPoints(1000);
- paintConvexHull();
- }
-
- @Override
- public Component getMainPanel() {
- return container;
- }
-
- public void paintConvexHull() {
- PNode pointSet = new PNode();
- for (Vector2D point : points) {
- final PNode node = PPath.createEllipse(point.getX() - 1, point.getY() - 1, 2, 2);
- node.addAttribute("tooltip", point);
- node.setPaint(Color.gray);
- pointSet.addChild(node);
- }
-
- canvas.getLayer().addChild(pointSet);
-
- ConvexHullGenerator2D generator = new MonotoneChain(true, 1e-6);
- ConvexHull2D hull = generator.generate(points); //AklToussaintHeuristic.reducePoints(points));
-
- PNode hullNode = new PNode();
- for (Vector2D vertex : hull.getVertices()) {
- final PPath node = PPath.createEllipse(vertex.getX() - 1, vertex.getY() - 1, 2, 2);
- node.addAttribute("tooltip", vertex);
- node.setPaint(Color.red);
- node.setStrokePaint(Color.red);
- hullNode.addChild(node);
- }
-
- for (Segment line : hull.getLineSegments()) {
- final PPath node = PPath.createLine(line.getStart().getX(), line.getStart().getY(),
- line.getEnd().getX(), line.getEnd().getY());
- node.setPickable(false);
- node.setPaint(Color.red);
- node.setStrokePaint(Color.red);
- hullNode.addChild(node);
- }
-
- canvas.getLayer().addChild(hullNode);
-
- Encloser<Euclidean2D, Vector2D> encloser =
- new WelzlEncloser<Euclidean2D, Vector2D>(1e-10, new DiskGenerator());
- EnclosingBall<Euclidean2D, Vector2D> ball = encloser.enclose(points);
-
- final double radius = ball.getRadius();
- PPath ballCenter =
- PPath.createEllipse(ball.getCenter().getX() - 1, ball.getCenter().getY() - 1, 2, 2);
- ballCenter.setStrokePaint(Color.blue);
- ballCenter.setPaint(Color.blue);
- canvas.getLayer().addChild(0, ballCenter);
-
- PPath ballNode =
- PPath.createEllipse(ball.getCenter().getX() - radius, ball.getCenter().getY() - radius,
- radius * 2, radius * 2);
- ballNode.setTransparency(1.0f);
- ballNode.setStrokePaint(Color.blue);
- canvas.getLayer().addChild(0, ballNode);
- }
- }
-
- public static void main(final String[] argv) {
- ExampleUtils.showExampleFrame(new Display());
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRings.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRings.java b/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRings.java
deleted file mode 100644
index d4ce758..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRings.java
+++ /dev/null
@@ -1,109 +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.sofm;
-
-import org.apache.commons.complex.geometry.euclidean.threed.Vector3D;
-import org.apache.commons.complex.geometry.euclidean.threed.Rotation;
-import org.apache.commons.complex.random.UnitSphereRandomVectorGenerator;
-import org.apache.commons.complex.distribution.RealDistribution;
-import org.apache.commons.complex.distribution.UniformRealDistribution;
-
-/**
- * Class that creates two intertwined rings.
- * Each ring is composed of a cloud of points.
- */
-public class ChineseRings {
- /** Points in the two rings. */
- private final Vector3D[] points;
-
- /**
- * @param orientationRing1 Vector othogonal to the plane containing the
- * first ring.
- * @param radiusRing1 Radius of the first ring.
- * @param halfWidthRing1 Half-width of the first ring.
- * @param radiusRing2 Radius of the second ring.
- * @param halfWidthRing2 Half-width of the second ring.
- * @param numPointsRing1 Number of points in the first ring.
- * @param numPointsRing2 Number of points in the second ring.
- */
- public ChineseRings(Vector3D orientationRing1,
- double radiusRing1,
- double halfWidthRing1,
- double radiusRing2,
- double halfWidthRing2,
- int numPointsRing1,
- int numPointsRing2) {
- // First ring (centered at the origin).
- final Vector3D[] firstRing = new Vector3D[numPointsRing1];
- // Second ring (centered around the first ring).
- final Vector3D[] secondRing = new Vector3D[numPointsRing2];
-
- // Create two rings lying in xy-plane.
- final UnitSphereRandomVectorGenerator unit
- = new UnitSphereRandomVectorGenerator(2);
-
- final RealDistribution radius1
- = new UniformRealDistribution(radiusRing1 - halfWidthRing1,
- radiusRing1 + halfWidthRing1);
- final RealDistribution widthRing1
- = new UniformRealDistribution(-halfWidthRing1, halfWidthRing1);
-
- for (int i = 0; i < numPointsRing1; i++) {
- final double[] v = unit.nextVector();
- final double r = radius1.sample();
- // First ring is in the xy-plane, centered at (0, 0, 0).
- firstRing[i] = new Vector3D(v[0] * r,
- v[1] * r,
- widthRing1.sample());
- }
-
- final RealDistribution radius2
- = new UniformRealDistribution(radiusRing2 - halfWidthRing2,
- radiusRing2 + halfWidthRing2);
- final RealDistribution widthRing2
- = new UniformRealDistribution(-halfWidthRing2, halfWidthRing2);
-
- for (int i = 0; i < numPointsRing2; i++) {
- final double[] v = unit.nextVector();
- final double r = radius2.sample();
- // Second ring is in the xz-plane, centered at (radiusRing1, 0, 0).
- secondRing[i] = new Vector3D(radiusRing1 + v[0] * r,
- widthRing2.sample(),
- v[1] * r);
- }
-
- // Move first and second rings into position.
- final Rotation rot = new Rotation(Vector3D.PLUS_K,
- orientationRing1.normalize());
- int count = 0;
- points = new Vector3D[numPointsRing1 + numPointsRing2];
- for (int i = 0; i < numPointsRing1; i++) {
- points[count++] = rot.applyTo(firstRing[i]);
- }
- for (int i = 0; i < numPointsRing2; i++) {
- points[count++] = rot.applyTo(secondRing[i]);
- }
- }
-
- /**
- * Gets all the points.
- */
- public Vector3D[] getPoints() {
- return points.clone();
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRingsClassifier.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRingsClassifier.java b/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRingsClassifier.java
deleted file mode 100644
index d769fc7..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/sofm/ChineseRingsClassifier.java
+++ /dev/null
@@ -1,335 +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.sofm;
-
-import java.util.Iterator;
-import java.io.PrintWriter;
-import java.io.IOException;
-import org.apache.commons.complex.ml.neuralnet.SquareNeighbourhood;
-import org.apache.commons.complex.ml.neuralnet.FeatureInitializer;
-import org.apache.commons.complex.ml.neuralnet.FeatureInitializerFactory;
-import org.apache.commons.complex.ml.neuralnet.MapUtils;
-import org.apache.commons.complex.ml.neuralnet.twod.NeuronSquareMesh2D;
-import org.apache.commons.complex.ml.neuralnet.sofm.LearningFactorFunction;
-import org.apache.commons.complex.ml.neuralnet.sofm.LearningFactorFunctionFactory;
-import org.apache.commons.complex.ml.neuralnet.sofm.NeighbourhoodSizeFunction;
-import org.apache.commons.complex.ml.neuralnet.sofm.NeighbourhoodSizeFunctionFactory;
-import org.apache.commons.complex.ml.neuralnet.sofm.KohonenUpdateAction;
-import org.apache.commons.complex.ml.neuralnet.sofm.KohonenTrainingTask;
-import org.apache.commons.complex.ml.distance.DistanceMeasure;
-import org.apache.commons.complex.ml.distance.EuclideanDistance;
-import org.apache.commons.complex.random.RandomGenerator;
-import org.apache.commons.complex.random.Well19937c;
-import org.apache.commons.complex.stat.descriptive.SummaryStatistics;
-import org.apache.commons.complex.geometry.euclidean.threed.Vector3D;
-import org.apache.commons.complex.util.FastMath;
-import org.apache.commons.complex.exception.MathUnsupportedOperationException;
-
-/**
- * SOFM for categorizing points that belong to each of two intertwined rings.
- *
- * The output currently consists in 3 text files:
- * <ul>
- * <li>"before.chinese.U.seq.dat": U-matrix of the SOFM before training</li>
- * <li>"after.chinese.U.seq.dat": U-matrix of the SOFM after training</li>
- * <li>"after.chinese.hit.seq.dat": Hit histogram after training</li>
- * <ul>
- */
-public class ChineseRingsClassifier {
- /** SOFM. */
- private final NeuronSquareMesh2D sofm;
- /** Rings. */
- private final ChineseRings rings;
- /** Distance function. */
- private final DistanceMeasure distance = new EuclideanDistance();
-
- public static void main(String[] args) {
- final ChineseRings rings = new ChineseRings(new Vector3D(1, 2, 3),
- 25, 2,
- 20, 1,
- 2000, 1500);
- final ChineseRingsClassifier classifier = new ChineseRingsClassifier(rings, 15, 15);
- printU("before.chinese.U.seq.dat", classifier);
- classifier.createSequentialTask(100000).run();
- printU("after.chinese.U.seq.dat", classifier);
- printHit("after.chinese.hit.seq.dat", classifier);
- }
-
- /**
- * @param rings Training data.
- * @param dim1 Number of rows of the SOFM.
- * @param dim2 Number of columns of the SOFM.
- */
- public ChineseRingsClassifier(ChineseRings rings,
- int dim1,
- int dim2) {
- this.rings = rings;
- sofm = new NeuronSquareMesh2D(dim1, false,
- dim2, false,
- SquareNeighbourhood.MOORE,
- makeInitializers());
- }
-
- /**
- * Creates training tasks.
- *
- * @param numTasks Number of tasks to create.
- * @param numSamplesPerTask Number of training samples per task.
- * @return the created tasks.
- */
- public Runnable[] createParallelTasks(int numTasks,
- long numSamplesPerTask) {
- final Runnable[] tasks = new Runnable[numTasks];
- final LearningFactorFunction learning
- = LearningFactorFunctionFactory.exponentialDecay(1e-1,
- 5e-2,
- numSamplesPerTask / 2);
- final double numNeurons = FastMath.sqrt(sofm.getNumberOfRows() * sofm.getNumberOfColumns());
- final NeighbourhoodSizeFunction neighbourhood
- = NeighbourhoodSizeFunctionFactory.exponentialDecay(0.5 * numNeurons,
- 0.2 * numNeurons,
- numSamplesPerTask / 2);
-
- for (int i = 0; i < numTasks; i++) {
- final KohonenUpdateAction action = new KohonenUpdateAction(distance,
- learning,
- neighbourhood);
- tasks[i] = new KohonenTrainingTask(sofm.getNetwork(),
- createRandomIterator(numSamplesPerTask),
- action);
- }
-
- return tasks;
- }
-
- /**
- * Creates a training task.
- *
- * @param numSamples Number of training samples.
- * @return the created task.
- */
- public Runnable createSequentialTask(long numSamples) {
- return createParallelTasks(1, numSamples)[0];
- }
-
- /**
- * Computes the U-matrix.
- *
- * @return the U-matrix of the network.
- */
- public double[][] computeU() {
- return MapUtils.computeU(sofm, distance);
- }
-
- /**
- * Computes the hit histogram.
- *
- * @return the histogram.
- */
- public int[][] computeHitHistogram() {
- return MapUtils.computeHitHistogram(createIterable(),
- sofm,
- distance);
- }
-
- /**
- * Computes the quantization error.
- *
- * @return the quantization error.
- */
- public double computeQuantizationError() {
- return MapUtils.computeQuantizationError(createIterable(),
- sofm.getNetwork(),
- distance);
- }
-
- /**
- * Computes the topographic error.
- *
- * @return the topographic error.
- */
- public double computeTopographicError() {
- return MapUtils.computeTopographicError(createIterable(),
- sofm.getNetwork(),
- distance);
- }
-
- /**
- * Creates the features' initializers.
- * They are sampled from a uniform distribution around the barycentre of
- * the rings.
- *
- * @return an array containing the initializers for the x, y and
- * z coordinates of the features array of the neurons.
- */
- private FeatureInitializer[] makeInitializers() {
- final SummaryStatistics[] centre = new SummaryStatistics[] {
- new SummaryStatistics(),
- new SummaryStatistics(),
- new SummaryStatistics()
- };
- for (Vector3D p : rings.getPoints()) {
- centre[0].addValue(p.getX());
- centre[1].addValue(p.getY());
- centre[2].addValue(p.getZ());
- }
-
- final double[] mean = new double[] {
- centre[0].getMean(),
- centre[1].getMean(),
- centre[2].getMean()
- };
- final double s = 0.1;
- final double[] dev = new double[] {
- s * centre[0].getStandardDeviation(),
- s * centre[1].getStandardDeviation(),
- s * centre[2].getStandardDeviation()
- };
-
- return new FeatureInitializer[] {
- FeatureInitializerFactory.uniform(mean[0] - dev[0], mean[0] + dev[0]),
- FeatureInitializerFactory.uniform(mean[1] - dev[1], mean[1] + dev[1]),
- FeatureInitializerFactory.uniform(mean[2] - dev[2], mean[2] + dev[2])
- };
- }
-
- /**
- * Creates an iterable that will present the points coordinates.
- *
- * @return the iterable.
- */
- private Iterable<double[]> createIterable() {
- return new Iterable<double[]>() {
- public Iterator<double[]> iterator() {
- return new Iterator<double[]>() {
- /** Data. */
- final Vector3D[] points = rings.getPoints();
- /** Number of samples. */
- private int n = 0;
-
- /** {@inheritDoc} */
- public boolean hasNext() {
- return n < points.length;
- }
-
- /** {@inheritDoc} */
- public double[] next() {
- return points[n++].toArray();
- }
-
- /** {@inheritDoc} */
- public void remove() {
- throw new MathUnsupportedOperationException();
- }
- };
- }
- };
- }
-
- /**
- * Creates an iterator that will present a series of points coordinates in
- * a random order.
- *
- * @param numSamples Number of samples.
- * @return the iterator.
- */
- private Iterator<double[]> createRandomIterator(final long numSamples) {
- return new Iterator<double[]>() {
- /** Data. */
- final Vector3D[] points = rings.getPoints();
- /** RNG. */
- final RandomGenerator rng = new Well19937c();
- /** Number of samples. */
- private long n = 0;
-
- /** {@inheritDoc} */
- public boolean hasNext() {
- return n < numSamples;
- }
-
- /** {@inheritDoc} */
- public double[] next() {
- ++n;
- return points[rng.nextInt(points.length)].toArray();
- }
-
- /** {@inheritDoc} */
- public void remove() {
- throw new MathUnsupportedOperationException();
- }
- };
- }
-
- /**
- * Prints the U-matrix of the map to the given filename.
- *
- * @param filename File.
- * @param sofm Classifier.
- */
- private static void printU(String filename,
- ChineseRingsClassifier sofm) {
- PrintWriter out = null;
- try {
- out = new PrintWriter(filename);
-
- final double[][] uMatrix = sofm.computeU();
- for (int i = 0; i < uMatrix.length; i++) {
- for (int j = 0; j < uMatrix[0].length; j++) {
- out.print(uMatrix[i][j] + " ");
- }
- out.println();
- }
- out.println("# Quantization error: " + sofm.computeQuantizationError());
- out.println("# Topographic error: " + sofm.computeTopographicError());
- } catch (IOException e) {
- // Do nothing.
- } finally {
- if (out != null) {
- out.close();
- }
- }
- }
-
- /**
- * Prints the hit histogram of the map to the given filename.
- *
- * @param filename File.
- * @param sofm Classifier.
- */
- private static void printHit(String filename,
- ChineseRingsClassifier sofm) {
- PrintWriter out = null;
- try {
- out = new PrintWriter(filename);
-
- final int[][] histo = sofm.computeHitHistogram();
- for (int i = 0; i < histo.length; i++) {
- for (int j = 0; j < histo[0].length; j++) {
- out.print(histo[i][j] + " ");
- }
- out.println();
- }
- } catch (IOException e) {
- // Do nothing.
- } finally {
- if (out != null) {
- out.close();
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/pom.xml
----------------------------------------------------------------------
diff --git a/src/userguide/pom.xml b/src/userguide/pom.xml
deleted file mode 100644
index 2f8ac91..0000000
--- a/src/userguide/pom.xml
+++ /dev/null
@@ -1,85 +0,0 @@
-<?xml version="1.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.
--->
-<!--
- Stripped down maven pom used for generating example code for the commons math userguide.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-math4-examples</artifactId>
- <version>4.0-SNAPSHOT</version>
- <name>Commons Math User Guide</name>
- <inceptionYear>2003</inceptionYear>
- <description>Examples</description>
- <url>http://commons.apache.org/math/</url>
- <issueManagement>
- <system>jira</system>
- <url>http://issues.apache.org/jira/browse/MATH</url>
- </issueManagement>
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/math/trunk</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/math/trunk</developerConnection>
- <url>http://svn.apache.org/viewvc/commons/proper/math/trunk</url>
- </scm>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <maven.compiler.source>1.7</maven.compiler.source>
- <maven.compiler.target>1.7</maven.compiler.target>
- </properties>
-
- <build>
- <sourceDirectory>java</sourceDirectory>
- </build>
- <reporting>
- </reporting>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-math4</artifactId>
- <classifier>tools</classifier>
- <version>4.0-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-math4</artifactId>
- <version>4.0-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>com.xeiam.xchart</groupId>
- <artifactId>xchart</artifactId>
- <version>2.3.0</version>
- </dependency>
- <dependency>
- <groupId>org.piccolo2d</groupId>
- <artifactId>piccolo2d-core</artifactId>
- <version>3.0</version>
- </dependency>
- <dependency>
- <groupId>org.piccolo2d</groupId>
- <artifactId>piccolo2d-extras</artifactId>
- <version>3.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.1</version>
- </dependency>
- </dependencies>
-</project>
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/resources/ColorfulBird.jpg
----------------------------------------------------------------------
diff --git a/src/userguide/resources/ColorfulBird.jpg b/src/userguide/resources/ColorfulBird.jpg
deleted file mode 100644
index 5753596..0000000
Binary files a/src/userguide/resources/ColorfulBird.jpg and /dev/null differ
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/resources/feather-small.gif
----------------------------------------------------------------------
diff --git a/src/userguide/resources/feather-small.gif b/src/userguide/resources/feather-small.gif
deleted file mode 100644
index 9696a00..0000000
Binary files a/src/userguide/resources/feather-small.gif and /dev/null differ
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/resources/monalisa.png
----------------------------------------------------------------------
diff --git a/src/userguide/resources/monalisa.png b/src/userguide/resources/monalisa.png
deleted file mode 100644
index f35a3b2..0000000
Binary files a/src/userguide/resources/monalisa.png and /dev/null differ
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/resources/references.txt
----------------------------------------------------------------------
diff --git a/src/userguide/resources/references.txt b/src/userguide/resources/references.txt
deleted file mode 100644
index f05294b..0000000
--- a/src/userguide/resources/references.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-monalisa.png - http://commons.wikimedia.org/wiki/File:Mona_Lisa.jpg
-the image is public domain in the United States, and those countries with a copyright term of life of the author plus 100 years or less.
-
-ColorfulBird.jpg - http://www.wall321.com/Animals/Birds/colorful_birds_tropical_head_3888x2558_wallpaper_6566
\ No newline at end of file
[3/3] commons-numbers git commit: Removed "Commons Math" code
examples.
Posted by er...@apache.org.
Removed "Commons Math" code examples.
Project: http://git-wip-us.apache.org/repos/asf/commons-numbers/repo
Commit: http://git-wip-us.apache.org/repos/asf/commons-numbers/commit/a960a5ca
Tree: http://git-wip-us.apache.org/repos/asf/commons-numbers/tree/a960a5ca
Diff: http://git-wip-us.apache.org/repos/asf/commons-numbers/diff/a960a5ca
Branch: refs/heads/master
Commit: a960a5ca73b1f5b8bdce7fc75502b75e6d945aff
Parents: bd596be
Author: Gilles Sadowski <gi...@harfang.homelinux.org>
Authored: Sun Apr 30 17:32:32 2017 +0200
Committer: Gilles Sadowski <gi...@harfang.homelinux.org>
Committed: Sun Apr 30 17:32:32 2017 +0200
----------------------------------------------------------------------
src/userguide/README | 8 -
.../userguide/ClusterAlgorithmComparison.java | 304 -----
.../commons/math4/userguide/ExampleUtils.java | 114 --
.../userguide/FastMathTestPerformance.java | 1142 ------------------
.../IntegerDistributionComparison.java | 239 ----
.../LowDiscrepancyGeneratorComparison.java | 253 ----
.../userguide/RealDistributionComparison.java | 309 -----
.../clustering/ImageClusteringExample.java | 203 ----
.../userguide/filter/CannonballExample.java | 321 -----
.../filter/ConstantVoltageExample.java | 240 ----
.../userguide/genetics/HelloWorldExample.java | 187 ---
.../genetics/ImageEvolutionExample.java | 230 ----
.../math4/userguide/genetics/Polygon.java | 121 --
.../userguide/genetics/PolygonChromosome.java | 135 ---
.../genetics/RandomPolygonMutation.java | 49 -
.../userguide/geometry/GeometryExample.java | 280 -----
.../math4/userguide/sofm/ChineseRings.java | 109 --
.../userguide/sofm/ChineseRingsClassifier.java | 335 -----
src/userguide/pom.xml | 85 --
src/userguide/resources/ColorfulBird.jpg | Bin 98227 -> 0 bytes
src/userguide/resources/feather-small.gif | Bin 7128 -> 0 bytes
src/userguide/resources/monalisa.png | Bin 29270 -> 0 bytes
src/userguide/resources/references.txt | 4 -
23 files changed, 4668 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/README
----------------------------------------------------------------------
diff --git a/src/userguide/README b/src/userguide/README
deleted file mode 100644
index a6bcedd..0000000
--- a/src/userguide/README
+++ /dev/null
@@ -1,8 +0,0 @@
-This directory contains source code that is not part of the Apache
-Commons Math library. It contains syntactically correct and working
-examples of use.
-
-In order to run one of the applications (a class that must contain a
-"main" method), you would type (in a shell console) a command similar
-to the following:
- $ mvn -q exec:java -Dexec.mainClass=org.apache.commons.complex.userguide.sofm.ChineseRingsClassifier
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/ClusterAlgorithmComparison.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/ClusterAlgorithmComparison.java b/src/userguide/java/org/apache/commons/math4/userguide/ClusterAlgorithmComparison.java
deleted file mode 100644
index dba2ed7..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/ClusterAlgorithmComparison.java
+++ /dev/null
@@ -1,304 +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.Shape;
-import java.awt.geom.Ellipse2D;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import javax.swing.JComponent;
-import javax.swing.JLabel;
-
-import org.apache.commons.complex.distribution.NormalDistribution;
-import org.apache.commons.complex.geometry.euclidean.twod.Vector2D;
-import org.apache.commons.complex.ml.clustering.CentroidCluster;
-import org.apache.commons.complex.ml.clustering.Cluster;
-import org.apache.commons.complex.ml.clustering.Clusterable;
-import org.apache.commons.complex.ml.clustering.Clusterer;
-import org.apache.commons.complex.ml.clustering.DBSCANClusterer;
-import org.apache.commons.complex.ml.clustering.DoublePoint;
-import org.apache.commons.complex.ml.clustering.FuzzyKMeansClusterer;
-import org.apache.commons.complex.ml.clustering.KMeansPlusPlusClusterer;
-import org.apache.commons.complex.random.RandomAdaptor;
-import org.apache.commons.complex.random.RandomGenerator;
-import org.apache.commons.complex.random.SobolSequenceGenerator;
-import org.apache.commons.complex.random.Well19937c;
-import org.apache.commons.complex.util.FastMath;
-import org.apache.commons.complex.util.Pair;
-import org.apache.commons.complex.userguide.ExampleUtils.ExampleFrame;
-
-/**
- * Plots clustering results for various algorithms and datasets.
- * Based on
- * <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html">scikit learn</a>.
- */
-public class ClusterAlgorithmComparison {
-
- public static List<Vector2D> makeCircles(int samples, boolean shuffle, double noise, double factor, final RandomGenerator random) {
- if (factor < 0 || factor > 1) {
- throw new IllegalArgumentException();
- }
-
- NormalDistribution dist = new NormalDistribution(random, 0.0, noise, 1e-9);
-
- List<Vector2D> points = new ArrayList<Vector2D>();
- double range = 2.0 * FastMath.PI;
- double step = range / (samples / 2.0 + 1);
- for (double angle = 0; angle < range; angle += step) {
- Vector2D outerCircle = new Vector2D(FastMath.cos(angle), FastMath.sin(angle));
- Vector2D innerCircle = outerCircle.scalarMultiply(factor);
-
- points.add(outerCircle.add(generateNoiseVector(dist)));
- points.add(innerCircle.add(generateNoiseVector(dist)));
- }
-
- if (shuffle) {
- Collections.shuffle(points, new RandomAdaptor(random));
- }
-
- return points;
- }
-
- public static List<Vector2D> makeMoons(int samples, boolean shuffle, double noise, RandomGenerator random) {
- NormalDistribution dist = new NormalDistribution(random, 0.0, noise, 1e-9);
-
- int nSamplesOut = samples / 2;
- int nSamplesIn = samples - nSamplesOut;
-
- List<Vector2D> points = new ArrayList<Vector2D>();
- double range = FastMath.PI;
- double step = range / (nSamplesOut / 2.0);
- for (double angle = 0; angle < range; angle += step) {
- Vector2D outerCircle = new Vector2D(FastMath.cos(angle), FastMath.sin(angle));
- points.add(outerCircle.add(generateNoiseVector(dist)));
- }
-
- step = range / (nSamplesIn / 2.0);
- for (double angle = 0; angle < range; angle += step) {
- Vector2D innerCircle = new Vector2D(1 - FastMath.cos(angle), 1 - FastMath.sin(angle) - 0.5);
- points.add(innerCircle.add(generateNoiseVector(dist)));
- }
-
- if (shuffle) {
- Collections.shuffle(points, new RandomAdaptor(random));
- }
-
- return points;
- }
-
- public static List<Vector2D> makeBlobs(int samples, int centers, double clusterStd,
- double min, double max, boolean shuffle, RandomGenerator random) {
-
- NormalDistribution dist = new NormalDistribution(random, 0.0, clusterStd, 1e-9);
-
- double range = max - min;
- Vector2D[] centerPoints = new Vector2D[centers];
- for (int i = 0; i < centers; i++) {
- double x = random.nextDouble() * range + min;
- double y = random.nextDouble() * range + min;
- centerPoints[i] = new Vector2D(x, y);
- }
-
- int[] nSamplesPerCenter = new int[centers];
- int count = samples / centers;
- Arrays.fill(nSamplesPerCenter, count);
-
- for (int i = 0; i < samples % centers; i++) {
- nSamplesPerCenter[i]++;
- }
-
- List<Vector2D> points = new ArrayList<Vector2D>();
- for (int i = 0; i < centers; i++) {
- for (int j = 0; j < nSamplesPerCenter[i]; j++) {
- Vector2D point = new Vector2D(dist.sample(), dist.sample());
- points.add(point.add(centerPoints[i]));
- }
- }
-
- if (shuffle) {
- Collections.shuffle(points, new RandomAdaptor(random));
- }
-
- return points;
- }
-
- public static List<Vector2D> makeRandom(int samples) {
- SobolSequenceGenerator generator = new SobolSequenceGenerator(2);
- generator.skipTo(999999);
- List<Vector2D> points = new ArrayList<Vector2D>();
- for (double i = 0; i < samples; i++) {
- double[] vector = generator.nextVector();
- vector[0] = vector[0] * 2 - 1;
- vector[1] = vector[1] * 2 - 1;
- Vector2D point = new Vector2D(vector);
- points.add(point);
- }
-
- return points;
- }
-
- public static Vector2D generateNoiseVector(NormalDistribution distribution) {
- return new Vector2D(distribution.sample(), distribution.sample());
- }
-
- public static List<DoublePoint> normalize(final List<Vector2D> input, double minX, double maxX, double minY, double maxY) {
- double rangeX = maxX - minX;
- double rangeY = maxY - minY;
- List<DoublePoint> points = new ArrayList<DoublePoint>();
- for (Vector2D p : input) {
- double[] arr = p.toArray();
- arr[0] = (arr[0] - minX) / rangeX * 2 - 1;
- arr[1] = (arr[1] - minY) / rangeY * 2 - 1;
- points.add(new DoublePoint(arr));
- }
- return points;
- }
-
- @SuppressWarnings("serial")
- public static class Display extends ExampleFrame {
-
- public Display() {
- setTitle("Commons-Math: Cluster algorithm comparison");
- setSize(800, 800);
-
- setLayout(new GridBagLayout());
-
- int nSamples = 1500;
-
- RandomGenerator rng = new Well19937c(0);
- List<List<DoublePoint>> datasets = new ArrayList<List<DoublePoint>>();
-
- datasets.add(normalize(makeCircles(nSamples, true, 0.04, 0.5, rng), -1, 1, -1, 1));
- datasets.add(normalize(makeMoons(nSamples, true, 0.04, rng), -1, 2, -1, 1));
- datasets.add(normalize(makeBlobs(nSamples, 3, 1.0, -10, 10, true, rng), -12, 12, -12, 12));
- datasets.add(normalize(makeRandom(nSamples), -1, 1, -1, 1));
-
- List<Pair<String, Clusterer<DoublePoint>>> algorithms = new ArrayList<Pair<String, Clusterer<DoublePoint>>>();
-
- algorithms.add(new Pair<String, Clusterer<DoublePoint>>("KMeans\n(k=2)", new KMeansPlusPlusClusterer<DoublePoint>(2)));
- algorithms.add(new Pair<String, Clusterer<DoublePoint>>("KMeans\n(k=3)", new KMeansPlusPlusClusterer<DoublePoint>(3)));
- algorithms.add(new Pair<String, Clusterer<DoublePoint>>("FuzzyKMeans\n(k=3, fuzzy=2)", new FuzzyKMeansClusterer<DoublePoint>(3, 2)));
- algorithms.add(new Pair<String, Clusterer<DoublePoint>>("FuzzyKMeans\n(k=3, fuzzy=10)", new FuzzyKMeansClusterer<DoublePoint>(3, 10)));
- algorithms.add(new Pair<String, Clusterer<DoublePoint>>("DBSCAN\n(eps=.1, min=3)", new DBSCANClusterer<DoublePoint>(0.1, 3)));
-
- GridBagConstraints c = new GridBagConstraints();
- c.fill = GridBagConstraints.VERTICAL;
- c.gridx = 0;
- c.gridy = 0;
- c.insets = new Insets(2, 2, 2, 2);
-
- for (Pair<String, Clusterer<DoublePoint>> pair : algorithms) {
- JLabel text = new JLabel("<html><body>" + pair.getFirst().replace("\n", "<br>"));
- add(text, c);
- c.gridx++;
- }
- c.gridy++;
-
- for (List<DoublePoint> dataset : datasets) {
- c.gridx = 0;
- for (Pair<String, Clusterer<DoublePoint>> pair : algorithms) {
- long start = System.currentTimeMillis();
- List<? extends Cluster<DoublePoint>> clusters = pair.getSecond().cluster(dataset);
- long end = System.currentTimeMillis();
- add(new ClusterPlot(clusters, end - start), c);
- c.gridx++;
- }
- c.gridy++;
- }
- }
-
- }
-
- @SuppressWarnings("serial")
- public static class ClusterPlot extends JComponent {
-
- private static double PAD = 10;
-
- private List<? extends Cluster<DoublePoint>> clusters;
- private long duration;
-
- public ClusterPlot(final List<? extends Cluster<DoublePoint>> clusters, long duration) {
- this.clusters = clusters;
- this.duration = duration;
- }
-
- @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);
-
- int index = 0;
- Color[] colors = new Color[] { Color.red, Color.blue, Color.green.darker() };
- for (Cluster<DoublePoint> cluster : clusters) {
- g2.setPaint(colors[index++]);
- for (DoublePoint point : cluster.getPoints()) {
- Clusterable p = transform(point, w, h);
- double[] arr = p.getPoint();
- g2.fill(new Ellipse2D.Double(arr[0] - 1, arr[1] - 1, 3, 3));
- }
-
- if (cluster instanceof CentroidCluster) {
- Clusterable p = transform(((CentroidCluster<?>) cluster).getCenter(), w, h);
- double[] arr = p.getPoint();
- Shape s = new Ellipse2D.Double(arr[0] - 4, arr[1] - 4, 8, 8);
- g2.fill(s);
- g2.setPaint(Color.black);
- g2.draw(s);
- }
- }
-
- g2.setPaint(Color.black);
- g2.drawString(String.format("%.2f s", duration / 1e3), w - 40, h - 5);
- }
-
- @Override
- public Dimension getPreferredSize() {
- return new Dimension(150, 150);
- }
-
- private Clusterable transform(Clusterable point, int width, int height) {
- double[] arr = point.getPoint();
- return new DoublePoint(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/ExampleUtils.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/ExampleUtils.java b/src/userguide/java/org/apache/commons/math4/userguide/ExampleUtils.java
deleted file mode 100644
index 1b57361..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/ExampleUtils.java
+++ /dev/null
@@ -1,114 +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.Component;
-import java.awt.Graphics2D;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.InputEvent;
-import java.awt.event.KeyEvent;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-
-import javax.imageio.ImageIO;
-import javax.swing.JFileChooser;
-import javax.swing.JFrame;
-import javax.swing.JMenu;
-import javax.swing.JMenuBar;
-import javax.swing.JMenuItem;
-import javax.swing.KeyStroke;
-import javax.swing.SwingUtilities;
-
-public class ExampleUtils {
-
- @SuppressWarnings("serial")
- public static class ExampleFrame extends JFrame {
-
- /**
- * Returns the main panel which should be printed by the screenshot action.
- * <p>
- * By default, it returns the content pane of this frame, but can be overriden
- * in case the frame has a global scroll pane which would cut off any offscreen content.
- *
- * @return the main panel to print
- */
- public Component getMainPanel() {
- return getContentPane();
- }
- }
-
- public static void showExampleFrame(final ExampleFrame frame) {
- Runnable r = new Runnable() {
- public void run() {
- JMenuItem screenshot = new JMenuItem("Screenshot (png)");
- screenshot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, InputEvent.CTRL_DOWN_MASK));
- screenshot.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent ae) {
- JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
- if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
- File file = fileChooser.getSelectedFile();
- BufferedImage img = getScreenShot(frame.getMainPanel());
- try {
- // write the image as a PNG
- ImageIO.write(img, "png", file);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- });
-
- JMenuItem exit = new JMenuItem("Exit");
- exit.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- });
-
- JMenu menu = new JMenu("File");
- menu.add(screenshot);
- menu.add(exit);
- JMenuBar mb = new JMenuBar();
- mb.add(menu);
- frame.setJMenuBar(mb);
-
- frame.setLocationRelativeTo(null);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- };
- SwingUtilities.invokeLater(r);
- }
-
- private static BufferedImage getScreenShot(Component component) {
- BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
- // call the Component's paint method, using the Graphics object of the image.
- component.paint(image.getGraphics());
- return image;
- }
-
- public 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;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/FastMathTestPerformance.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/FastMathTestPerformance.java b/src/userguide/java/org/apache/commons/math4/userguide/FastMathTestPerformance.java
deleted file mode 100644
index 1657174..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/FastMathTestPerformance.java
+++ /dev/null
@@ -1,1142 +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 org.apache.commons.complex.PerfTestUtils;
-import org.apache.commons.complex.util.FastMath;
-
-/**
- * Performance benchmark for FastMath.
- *
- */
-public class FastMathTestPerformance {
- private static final int RUNS = Integer.parseInt(System.getProperty("testRuns","10000000"));
- private static final double F1 = 1d / RUNS;
-
- // Header format
- private static final String FMT_HDR = "%-13s %13s %13s %13s Runs=%d Java %s (%s) %s (%s)";
- // Detail format
- private static final String FMT_DTL = "%-13s %6d %6.1f %6d %6.4f %6d %6.4f";
-
- public static void main(String[] args) {
- System.out.println(String.format(FMT_HDR,
- "Name","StrictMath","FastMath","Math",RUNS,
- System.getProperty("java.version"),
- System.getProperty("java.runtime.version","?"),
- System.getProperty("java.vm.name"),
- System.getProperty("java.vm.version")
- ));
- testAbs();
- testAcos();
- testAsin();
- testAtan();
- testAtan2();
- testCbrt();
- testCos();
- testCosh();
- testExp();
- testExpm1();
- testHypot();
- testLog();
- testLog10();
- testLog1p();
- testPow();
- testSin();
- testSinh();
- testSqrt();
- testTan();
- testTanh();
- testIEEEremainder();
-
- }
-
- @SuppressWarnings("boxing")
- private static void report(String name, long strictMathTime, long fastMathTime, long mathTime) {
- long unitTime = strictMathTime;
- System.out.println(String.format(FMT_DTL,
- name,
- strictMathTime / RUNS, (double) strictMathTime / unitTime,
- fastMathTime / RUNS, (double) fastMathTime / unitTime,
- mathTime / RUNS, (double) mathTime / unitTime
- ));
- }
-
- private static void assertTrue(boolean condition) {
- if (!condition) {
- System.err.println("assertion failed!");
- System.exit(1);
- }
- }
- private static void testLog() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.log(0.01 + i);
- }
- long strictMath = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.log(0.01 + i);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.log(0.01 + i);
- }
- long mathTime = System.nanoTime() - time;
-
- report("log",strictMath,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testLog10() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.log10(0.01 + i);
- }
- long strictMath = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.log10(0.01 + i);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.log10(0.01 + i);
- }
- long mathTime = System.nanoTime() - time;
-
- report("log10",strictMath,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testLog1p() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.log1p(-0.9 + i);
- }
- long strictMath = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.log1p(-0.9 + i);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.log1p(-0.9 + i);
- }
- long mathTime = System.nanoTime() - time;
-
- report("log1p",strictMath,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testPow() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.pow(0.01 + i * F1, i * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.pow(0.01 + i * F1, i * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.pow(0.01 + i * F1, i * F1);
- }
- long mathTime = System.nanoTime() - time;
- report("pow",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testExp() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.exp(100 * i * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.exp(100 * i * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.exp(100 * i * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("exp",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testSin() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.sin(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.sin(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.sin(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("sin",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testAsin() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.asin(0.999 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.asin(0.999 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.asin(0.999 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("asin",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testCos() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.cos(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.cos(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.cos(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("cos",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testAcos() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.acos(0.999 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.acos(0.999 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.acos(0.999 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
- report("acos",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testTan() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.tan(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.tan(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.tan(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("tan",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testAtan() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.atan(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.atan(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.atan(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("atan",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testAtan2() {
- double x = 0;
- long time = System.nanoTime();
- int max = (int) FastMath.floor(FastMath.sqrt(RUNS));
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += StrictMath.atan2((i - max/2) * (100.0 / max), (j - max/2) * (100.0 / max));
- }
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += FastMath.atan2((i - max/2) * (100.0 / max), (j - max/2) * (100.0 / max));
- }
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += Math.atan2((i - max/2) * (100.0 / max), (j - max/2) * (100.0 / max));
- }
- }
- long mathTime = System.nanoTime() - time;
-
- report("atan2",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testHypot() {
- double x = 0;
- long time = System.nanoTime();
- int max = (int) FastMath.floor(FastMath.sqrt(RUNS));
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += StrictMath.atan2((i - max/2) * (100.0 / max), (j - max/2) * (100.0 / max));
- }
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += FastMath.atan2((i - max/2) * (100.0 / max), (j - max/2) * (100.0 / max));
- }
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += Math.atan2((i - max/2) * (100.0 / max), (j - max/2) * (100.0 / max));
- }
- }
- long mathTime = System.nanoTime() - time;
-
- report("hypot",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testIEEEremainder() {
- double x = 0;
- long time = System.nanoTime();
- int max = (int) FastMath.floor(FastMath.sqrt(RUNS));
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += StrictMath.IEEEremainder((i - max/2) * (100.0 / max), (j + 1) * (100.0 / max));
- }
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += FastMath.IEEEremainder((i - max/2) * (100.0 / max), (j + 1) * (100.0 / max));
- }
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < max; i++) {
- for (int j = 0; j < max; j++) {
- x += Math.IEEEremainder((i - max/2) * (100.0 / max), (j + 1) * (100.0 / max));
- }
- }
- long mathTime = System.nanoTime() - time;
-
- report("IEEEremainder",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testCbrt() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.cbrt(100 * i * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.cbrt(100 * i * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.cbrt(100 * i * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("cbrt",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testSqrt() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.sqrt(100 * i * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.sqrt(100 * i * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.sqrt(100 * i * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("sqrt",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testCosh() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.cosh(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.cosh(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.cosh(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("cosh",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testSinh() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.sinh(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.sinh(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.sinh(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("sinh",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testTanh() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.tanh(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.tanh(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.tanh(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
-
- report("tanh",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testExpm1() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.expm1(100 * (i - RUNS/2) * F1);
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.expm1(100 * (i - RUNS/2) * F1);
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.expm1(100 * (i - RUNS/2) * F1);
- }
- long mathTime = System.nanoTime() - time;
- report("expm1",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- private static void testAbs() {
- double x = 0;
- long time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += StrictMath.abs(i * (1 - 0.5 * RUNS));
- }
- long strictTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += FastMath.abs(i * (1 - 0.5 * RUNS));
- }
- long fastTime = System.nanoTime() - time;
-
- x = 0;
- time = System.nanoTime();
- for (int i = 0; i < RUNS; i++) {
- x += Math.abs(i * (1 - 0.5 * RUNS));
- }
- long mathTime = System.nanoTime() - time;
-
- report("abs",strictTime,fastTime,mathTime);
- assertTrue(!Double.isNaN(x));
- }
-
- @SuppressWarnings("boxing")
- private static void testSimpleBenchmark() {
- final String SM = "StrictMath";
- final String M = "Math";
- final String FM = "FastMath";
-
- final int maxWidth = 15;
- final int numStat = 100;
- final int numCall = RUNS / numStat;
-
- final double x = Math.random();
- final double y = Math.random();
-
- PerfTestUtils.timeAndReport("log",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.log(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.log(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.log(x);
- }
- });
-
- PerfTestUtils.timeAndReport("log10",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.log10(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.log10(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.log10(x);
- }
- });
-
- PerfTestUtils.timeAndReport("log1p",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.log1p(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.log1p(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.log1p(x);
- }
- });
-
- PerfTestUtils.timeAndReport("pow",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.pow(x, y);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.pow(x, y);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.pow(x, y);
- }
- });
-
- PerfTestUtils.timeAndReport("exp",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.exp(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.exp(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.exp(x);
- }
- });
-
- PerfTestUtils.timeAndReport("sin",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.sin(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.sin(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.sin(x);
- }
- });
-
- PerfTestUtils.timeAndReport("asin",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.asin(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.asin(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.asin(x);
- }
- });
-
- PerfTestUtils.timeAndReport("cos",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.cos(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.cos(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.cos(x);
- }
- });
-
- PerfTestUtils.timeAndReport("acos",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.acos(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.acos(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.acos(x);
- }
- });
-
- PerfTestUtils.timeAndReport("tan",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.tan(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.tan(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.tan(x);
- }
- });
-
- PerfTestUtils.timeAndReport("atan",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.atan(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.atan(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.atan(x);
- }
- });
-
- PerfTestUtils.timeAndReport("atan2",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.atan2(x, y);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.atan2(x, y);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.atan2(x, y);
- }
- });
-
- PerfTestUtils.timeAndReport("hypot",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.hypot(x, y);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.hypot(x, y);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.hypot(x, y);
- }
- });
-
-
- PerfTestUtils.timeAndReport("cbrt",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.cbrt(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.cbrt(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.cbrt(x);
- }
- });
-
- PerfTestUtils.timeAndReport("sqrt",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.sqrt(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.sqrt(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.sqrt(x);
- }
- });
-
- PerfTestUtils.timeAndReport("cosh",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.cosh(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.cosh(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.cosh(x);
- }
- });
-
- PerfTestUtils.timeAndReport("sinh",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.sinh(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.sinh(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.sinh(x);
- }
- });
-
- PerfTestUtils.timeAndReport("tanh",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.tanh(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.tanh(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.tanh(x);
- }
- });
-
- PerfTestUtils.timeAndReport("expm1",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.expm1(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.expm1(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.expm1(x);
- }
- });
-
- PerfTestUtils.timeAndReport("abs",
- maxWidth,
- numCall,
- numStat,
- false,
- new PerfTestUtils.RunTest(SM) {
- @Override
- public Double call() throws Exception {
- return StrictMath.abs(x);
- }
- },
- new PerfTestUtils.RunTest(M) {
- @Override
- public Double call() throws Exception {
- return Math.abs(x);
- }
- },
- new PerfTestUtils.RunTest(FM) {
- @Override
- public Double call() throws Exception {
- return FastMath.abs(x);
- }
- });
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/a960a5ca/src/userguide/java/org/apache/commons/math4/userguide/IntegerDistributionComparison.java
----------------------------------------------------------------------
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/IntegerDistributionComparison.java b/src/userguide/java/org/apache/commons/math4/userguide/IntegerDistributionComparison.java
deleted file mode 100644
index 9e3c423..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/IntegerDistributionComparison.java
+++ /dev/null
@@ -1,239 +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.BinomialDistribution;
-import org.apache.commons.complex.distribution.GeometricDistribution;
-import org.apache.commons.complex.distribution.HypergeometricDistribution;
-import org.apache.commons.complex.distribution.IntegerDistribution;
-import org.apache.commons.complex.distribution.PascalDistribution;
-import org.apache.commons.complex.distribution.PoissonDistribution;
-import org.apache.commons.complex.distribution.UniformIntegerDistribution;
-import org.apache.commons.complex.distribution.ZipfDistribution;
-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 integer distributions.
- */
-public class IntegerDistributionComparison {
-
- public static void addPDFSeries(Chart chart, IntegerDistribution distribution, String desc, int lowerBound, int upperBound) {
- // generates Log data
- List<Number> xData = new ArrayList<Number>();
- List<Number> yData = new ArrayList<Number>();
- for (int x = lowerBound; x <= upperBound; x += 1) {
- try {
- double probability = distribution.probability(x);
- if (! Double.isInfinite(probability) && ! Double.isNaN(probability)) {
- xData.add(x);
- yData.add(probability);
- }
- } 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, IntegerDistribution distribution, String desc,
- int lowerBound, int upperBound) {
- // generates Log data
- List<Number> xData = new ArrayList<Number>();
- List<Number> yData = new ArrayList<Number>();
- for (int x = lowerBound; x <= upperBound; x += 1) {
- 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,
- IntegerDistribution... 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 (IntegerDistribution d : series) {
- addPDFSeries(chart, d, seriesText[i++], minX, maxX);
- }
- container.add(new XChartPanel(chart));
-
- chart = createChart("CDF", minX, maxX, LegendPosition.InsideSE);
- i = 0;
- for (IntegerDistribution 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: Integer 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("Binomial", 0, 40,
- new String[] { "p=0.5,n=20", "p=0.7,n=20", "p=0.5,n=40" },
- new BinomialDistribution(20, 0.5),
- new BinomialDistribution(20, 0.7),
- new BinomialDistribution(40, 0.5));
- container.add(comp, c);
-
- c.gridx++;
- comp = createComponent("Geometric", 0, 10,
- new String[] { "p=0.2", "p=0.5", "p=0.8" },
- new GeometricDistribution(0.2),
- new GeometricDistribution(0.5),
- new GeometricDistribution(0.8));
- container.add(comp, c);
-
- c.gridx++;
- comp = createComponent("Hypergeometric", 0, 10,
- new String[] { "p=0.3", "p=0.5", "p=0.75" },
- new HypergeometricDistribution(100, 6, 20),
- new HypergeometricDistribution(100, 10, 20),
- new HypergeometricDistribution(100, 15, 20));
- container.add(comp, c);
-
- c.gridx++;
- comp = createComponent("Pascal", 0, 50,
- new String[] { "p=0.3", "p=0.5", "p=0.7" },
- new PascalDistribution(10, 0.3),
- new PascalDistribution(10, 0.5),
- new PascalDistribution(10, 0.7));
- container.add(comp, c);
-
- c.gridy++;
- c.gridx = 0;
- comp = createComponent("Poisson", 0, 20,
- new String[] { "\u03bb=1", "\u03bb=4", "\u03bb=10" },
- new PoissonDistribution(1),
- new PoissonDistribution(4),
- new PoissonDistribution(10));
- container.add(comp, c);
-
- c.gridx++;
- comp = createComponent("Uniform", 0, 30,
- new String[] { "l=1,u=10", "l=5,u=20", "l=1,u=25" },
- new UniformIntegerDistribution(1, 10),
- new UniformIntegerDistribution(5, 20),
- new UniformIntegerDistribution(1, 25));
- container.add(comp, c);
-
- c.gridx++;
- comp = createComponent("Zipf", 0, 15,
- new String[] { "n=10,e=0.5", "n=10,e=1", "n=10,e=2", "n=10,e=5" },
- new ZipfDistribution(10, 0.5),
- new ZipfDistribution(10, 1),
- new ZipfDistribution(10, 2),
- new ZipfDistribution(10, 5));
- 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());
- }
-}
[2/3] commons-numbers git commit: Removed "Commons Math" code
examples.
Posted by er...@apache.org.
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<Vector2D> makeCircle(int samples, final RandomVectorGenerator generator) {
- List<Vector2D> points = new ArrayList<Vector2D>();
- 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<Vector2D> circlePoints = new ArrayList<Vector2D>();
- 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<Vector2D> makeRandom(int samples, RandomVectorGenerator generator) {
- List<Vector2D> points = new ArrayList<Vector2D>();
- 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<Vector2D> normalize(final List<Vector2D> 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<Vector2D> points = new ArrayList<Vector2D>();
- 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<Pair<String, RandomVectorGenerator>> generators = new ArrayList<Pair<String, RandomVectorGenerator>>();
-
- generators.add(new Pair<String, RandomVectorGenerator>("Uncorrelated\nUniform(JDK)",
- new UncorrelatedRandomVectorGenerator(2, new UniformRandomGenerator(new JDKRandomGenerator()))));
- generators.add(new Pair<String, RandomVectorGenerator>("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<String, RandomVectorGenerator>("HaltonSequence", new HaltonSequenceGenerator(2)));
- generators.add(new Pair<String, RandomVectorGenerator>("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<String, RandomVectorGenerator> 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<String, RandomVectorGenerator> pair : generators) {
- List<Vector2D> 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<Vector2D> points;
-
- public Plot(final List<Vector2D> 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<Number> xData = new ArrayList<Number>();
- List<Number> yData = new ArrayList<Number>();
- 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<Number> xData = new ArrayList<Number>();
- List<Number> yData = new ArrayList<Number>();
- 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[] { "\u03bc=0,\u03c3\u00B2=0.2", "\u03bc=0,\u03c3\u00B2=1", "\u03bc=0,\u03c3\u00B2=5", "\u03bc=-2,\u03c3\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[] { "\u03b1=\u03b2=0.5", "\u03b1=5,\u03b2=1", "\u03b1=1,\u03b2=3", "\u03b1=2,\u03b2=2", "\u03b1=2,\u03b2=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,\u03b3=0.5", "x=0,\u03b3=1", "x=0,\u03b3=2", "x=-2,\u03b3=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[] { "\u03bb=0.5", "\u03bb=1", "\u03bb=1.5", "\u03bb=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,\u03b8=2", "k=2,\u03b8=2", "k=3,\u03b8=2", "k=5,\u03b8=1", "k=9,\u03b8=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[] { "\u03bc=0,\u03c3\u00B2=10", "\u03bc=0,\u03c3\u00B2=1.5", "\u03bc=0,\u03c3\u00B2=1", "\u03bc=0,\u03c3\u00B2=0.5", "\u03bc=0,\u03c3\u00B2=0.25", "\u03bc=0,\u03c3\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,\u03b1=1", "x=1,\u03b1=2", "x=1,\u03b1=3", "x=1,\u03b1=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[] { "\u03bb=0.5,k=1", "\u03bb=1,k=1", "\u03bb=1.5,k=1", "\u03bb=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<PixelClusterable> pixels = new ArrayList<PixelClusterable>();
- 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<PixelClusterable> clusterer =
- new KMeansPlusPlusClusterer<PixelClusterable>(clusterSize);
- List<CentroidCluster<PixelClusterable>> clusters = clusterer.cluster(pixels);
-
- WritableRaster raster = clusterImage.getRaster();
- for (CentroidCluster<PixelClusterable> 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<Number> realX = new ArrayList<Number>();
- final List<Number> realY = new ArrayList<Number>();
- final List<Number> measuredX = new ArrayList<Number>();
- final List<Number> measuredY = new ArrayList<Number>();
- final List<Number> kalmanX = new ArrayList<Number>();
- final List<Number> kalmanY = new ArrayList<Number>();
-
- 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<Number> xAxis = new ArrayList<Number>();
- final List<Number> realVoltageSeries = new ArrayList<Number>();
- final List<Number> measuredVoltageSeries = new ArrayList<Number>();
- final List<Number> kalmanVoltageSeries = new ArrayList<Number>();
-
- final List<Number> covSeries = new ArrayList<Number>();
-
- 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<Character>(), 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<Character> randomRepresentation(int length) {
- return asList(RandomStringUtils.randomAscii(length));
- }
-
- private static List<Character> asList(String str) {
- return Arrays.asList(ArrayUtils.toObject(str.toCharArray()));
- }
-
- private static Population getInitialPopulation() {
- List<Chromosome> popList = new LinkedList<Chromosome>();
-
- 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<Character> {
-
- public StringChromosome(List<Character> 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<Character> 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<Character> repr) throws InvalidRepresentationException {
- for (char c : repr) {
- if (c < 32 || c > 126) {
- throw new InvalidRepresentationException(LocalizedFormats.INVALID_FIXED_LENGTH_CHROMOSOME);
- }
- }
- }
-
- public List<Character> getStringRepresentation() {
- return getRepresentation();
- }
-
- @Override
- public StringChromosome newFixedLengthChromosome(List<Character> 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<Character> characters = strChromosome.getStringRepresentation();
-
- int mutationIndex = GeneticAlgorithm.getRandomGenerator().nextInt(characters.size());
-
- List<Character> mutatedChromosome = new ArrayList<Character>(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.
- * <p>
- * 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
- * <p>
- * 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.
- * <p>
- * 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 <a href="http://www.nihilogic.dk/labs/evolving-images/">Evolving Images with JavaScript and canvas (Nihilogic)</a>
- */
-@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<Polygon>(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<Chromosome> popList = new LinkedList<Chromosome>();
- 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.
- * <p>
- * 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<Polygon> {
-
- /** 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<Polygon> representation) {
- super(representation);
- }
-
- @Override
- protected void checkValidity(List<Polygon> chromosomeRepresentation) throws InvalidRepresentationException {
- // do nothing
- }
-
- @Override
- public AbstractListChromosome<Polygon> newFixedLengthChromosome(List<Polygon> chromosomeRepresentation) {
- return new PolygonChromosome(chromosomeRepresentation);
- }
-
- /**
- * Return the internal representation, which is needed for our custom mutation policy.
- *
- * @return the list of polygons
- */
- public List<Polygon> getPolygonRepresentation() {
- return getRepresentation();
- }
-
- /**
- * Calculate the fitness function for this chromosome.
- * <p>
- * 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<Polygon> 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<Polygon> list = new ArrayList<Polygon>(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<Polygon> repr = polygons.getPolygonRepresentation();
-
- List<Polygon> newRepr = new ArrayList<Polygon>(repr.size());
- for (Polygon p : repr) {
- newRepr.add(p.mutate(mutationRate, mutationAmount));
- }
- return new PolygonChromosome(newRepr);
- }
-}