1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.math4.legacy.fitting.leastsquares;
18
19 import org.apache.commons.statistics.distribution.NormalDistribution;
20 import org.apache.commons.statistics.distribution.ContinuousDistribution;
21 import org.apache.commons.rng.UniformRandomProvider;
22 import org.apache.commons.rng.sampling.ObjectSampler;
23 import org.apache.commons.rng.sampling.UnitSphereSampler;
24 import org.apache.commons.rng.simple.RandomSource;
25
26 /**
27 * Factory for generating a cloud of points that approximate a circle.
28 */
29 public class RandomCirclePointGenerator implements ObjectSampler<double[]> {
30 /** RNG for the x-coordinate of the center. */
31 private final ContinuousDistribution.Sampler cX;
32 /** RNG for the y-coordinate of the center. */
33 private final ContinuousDistribution.Sampler cY;
34 /** Sampler for the unit circle position of the point. */
35 private final UnitSphereSampler sampler;
36 /** Radius of the circle. */
37 private final double radius;
38
39 /**
40 * @param x Abscissa of the circle center.
41 * @param y Ordinate of the circle center.
42 * @param radius Radius of the circle.
43 * @param xSigma Error on the x-coordinate of the circumference points.
44 * @param ySigma Error on the y-coordinate of the circumference points.
45 */
46 public RandomCirclePointGenerator(double x,
47 double y,
48 double radius,
49 double xSigma,
50 double ySigma) {
51 final UniformRandomProvider rng = RandomSource.XO_SHI_RO_256_PP.create();
52 this.radius = radius;
53 cX = NormalDistribution.of(x, xSigma).createSampler(rng);
54 cY = NormalDistribution.of(y, ySigma).createSampler(rng);
55 sampler = UnitSphereSampler.of(rng, 2);
56 }
57
58 @Override
59 public double[] sample() {
60 // Sample on a unit circle
61 final double[] xy = sampler.sample();
62 // Scale the circle and add error
63 xy[0] = radius * xy[0] + cX.sample();
64 xy[1] = radius * xy[1] + cY.sample();
65 return xy;
66 }
67 }