public ParticleSwarm(int population_size, int dimension_count, CostEvaluationMethod evaluator, double[] lower_bounds, double[] upper_bounds) { mDimensionCount = dimension_count; mLowerBounds = lower_bounds; mUpperBounds = upper_bounds; mParticleGenerator = (constraints) => { SimpleParticle p = new SimpleParticle(this, mDimensionCount, constraints); double lower_bound; double upper_bound; double range; for (int d = 0; d < mDimensionCount; ++d) { lower_bound = lower_bounds[d]; upper_bound = upper_bounds[d]; range = upper_bound - lower_bound; p[d, ParticleVectorType.Position] = lower_bound + range * RandomEngine.NextDouble(); p[d, ParticleVectorType.Velocity] = 0; } Particle cast_p = p as Particle; return(cast_p); }; mParticles = new Particle[population_size]; mLocalBestParticles = new Particle[population_size]; mEvaluator = evaluator; }
public override int SelectAction(int state_id, QModel Q) { double r = RandomEngine.NextDouble(); if (r < 1 - mEpsilon) { double maxQ = double.MinValue; double Qval = maxQ; List <int> action_list = Q.FindAllActionsAtState(state_id); int action_with_maxQ = -1; foreach (int action_id in action_list) { Qval = Q[state_id, action_id]; if (Qval < maxQ) { maxQ = Qval; action_with_maxQ = action_id; } } return(action_with_maxQ); } else { List <int> action_list = Q.FindAllActionsAtState(state_id); int action_count = action_list.Count; return(action_list[(int)(r * action_count) % action_count]); } }
public override int SelectAction(int state_id, QModel Q) { double r = RandomEngine.NextDouble(); List <int> actions = Q.FindAllActionsAtState(state_id); double sum = 0; Dictionary <int, double> acc_weights = new Dictionary <int, double>(); foreach (int action_id in actions) { sum += Q[state_id, action_id]; acc_weights[action_id] = sum; } foreach (int action_id in actions) { acc_weights[action_id] /= sum; if (r <= acc_weights[action_id]) { return(action_id); } } return(-1); }
public virtual Particle GenerateParticle(object info) { if (mParticleGenerator != null) { return(mParticleGenerator(info)); } SimpleParticle p = new SimpleParticle(this, mDimensionCount, info); if (mLowerBounds != null && mUpperBounds != null) { double lower_bound; double upper_bound; double range; for (int i = 0; i < mDimensionCount; ++i) { lower_bound = mLowerBounds[i]; upper_bound = mUpperBounds[i]; range = upper_bound - lower_bound; p[i, ParticleVectorType.Position] = lower_bound + range * RandomEngine.NextDouble(); } } Particle cast_p = p as Particle; if (cast_p == null) { throw new ArgumentNullException(); } return(cast_p); }
public ContinuousSolution[] Recombine(ContinuousSolution[] subset, object constraints) { ContinuousSolution a = subset[0]; ContinuousSolution b = subset[1]; ContinuousSolution d = (a - b) / 2; double[] lower_bounds = null; double[] upper_bounds = null; if (mLowerBounds == null || mUpperBounds == null) { if (constraints != null && constraints is Tuple <double[], double[]> ) { Tuple <double[], double[]> bounds = constraints as Tuple <double[], double[]>; lower_bounds = bounds.Item1; upper_bounds = bounds.Item2; } else { throw new InvalidCastException(); } } else { lower_bounds = mLowerBounds; upper_bounds = mUpperBounds; } if (lower_bounds.Length < d.Length) { throw new IndexOutOfRangeException(); } if (upper_bounds.Length < d.Length) { throw new IndexOutOfRangeException(); } ContinuousSolution[] children = new ContinuousSolution[subset.Length]; for (int i = 0; i < subset.Length; ++i) { double[] x = new double[d.Length]; for (int j = 0; j < d.Length; ++j) { int direction = RandomEngine.NextDouble() < 0.5 ? 1 : -1; double r = RandomEngine.NextDouble(); x[j] = subset[i][j] + d[j] * direction * r; x[j] = System.Math.Max(lower_bounds[j], x[j]); x[j] = System.Math.Min(upper_bounds[j], x[j]); } children[i] = new ContinuousSolution(x, double.MaxValue); } return(children); }
public AdaptiveRandomSearch(int search_space_size, CreateNeighborMethod generator) { mSearchSpaceSize = search_space_size; mSolutionGenerator = generator; if (mSolutionGenerator == null) { mSolutionGenerator = (x, step_size, constraints) => { double[] lower_bounds = null; double[] upper_bounds = null; if (mLowerBounds == null || mUpperBounds == null) { if (constraints is Tuple <double[], double[]> ) { Tuple <double[], double[]> bounds = constraints as Tuple <double[], double[]>; lower_bounds = bounds.Item1; upper_bounds = bounds.Item2; } else { throw new InvalidCastException(); } } else { lower_bounds = mLowerBounds; upper_bounds = mUpperBounds; } if (lower_bounds.Length < x.Length) { throw new ArgumentOutOfRangeException(); } if (upper_bounds.Length < x.Length) { throw new ArgumentOutOfRangeException(); } for (int i = 0; i < x.Length; ++i) { // must check boundary ... double min = System.Math.Max(lower_bounds[i], x[i] - step_size); double max = System.Math.Min(upper_bounds[i], x[i] + step_size); double new_val = min + (max - min) * RandomEngine.NextDouble(); x[i] = new_val; } return(x); }; } }
public virtual void RandomSearch(double[] lower_bounds, double[] upper_bounds, object constraints) //initialize random solution { double lower_bound; double upper_bound; double range; for (int d = 0; d < mData.Length; ++d) { lower_bound = lower_bounds[d]; upper_bound = upper_bounds[d]; range = upper_bound - lower_bound; mData[d] = lower_bound + range * RandomEngine.NextDouble(); } this.UpdateCost(); }
public SmileModelFitterTest() { VolatilityFunctionProvider <T> model = Model; T data = ModelData; int n = STRIKES.Length; _noisyVols = new double[n]; _errors = new double[n]; _cleanVols = new double[n]; Arrays.fill(_errors, 1e-4); for (int i = 0; i < n; i++) { _cleanVols[i] = model.volatility(F, STRIKES[i], TIME_TO_EXPIRY, data); _noisyVols[i] = _cleanVols[i] + UNIFORM.NextDouble() * _errors[i]; } _fitter = getFitter(F, STRIKES, TIME_TO_EXPIRY, _cleanVols, _errors, model); _nosiyFitter = getFitter(F, STRIKES, TIME_TO_EXPIRY, _noisyVols, _errors, model); }
public virtual void TransiteState(Ant ant, int state_index) { int current_state_id = ant.CurrentState; List <int> candidate_states = GetCandidateNextStates(ant, current_state_id); if (candidate_states.Count == 0) { return; } int selected_state_id = -1; double[] acc_prob = new double[candidate_states.Count]; double product_sum = 0; for (int i = 0; i < candidate_states.Count; ++i) { int candidate_state_id = candidate_states[i]; double pheromone = mPheromones[current_state_id, candidate_state_id]; double heuristic_cost = GetHeuristicValue(current_state_id, candidate_state_id); double product = System.Math.Pow(pheromone, m_alpha) * System.Math.Pow(heuristic_cost, m_beta); product_sum += product; acc_prob[i] = product_sum; } double r = RandomEngine.NextDouble(); for (int i = 0; i < candidate_states.Count; ++i) { acc_prob[i] /= product_sum; if (r <= acc_prob[i]) { selected_state_id = candidate_states[i]; break; } } if (selected_state_id != -1) { ant.Add(selected_state_id); } }
public override ContinuousSolution Minimize(double[] x_0, CostEvaluationMethod evaluate, GradientEvaluationMethod calc_gradient, TerminationEvaluationMethod should_terminate, object constraints = null) { double?improvement = null; int iteration = 0; if (mLocalSearch == null) { throw new ArgumentNullException(); } mLocalSearch.LowerBounds = mLowerBounds; mLocalSearch.UpperBounds = mUpperBounds; double[] x = (double[])x_0.Clone(); double fx = evaluate(x, mLowerBounds, mUpperBounds, constraints); ContinuousSolution best_solution = new ContinuousSolution(x, fx); while (!should_terminate(improvement, iteration)) { int r_index = (int)(RandomEngine.NextDouble() * x.Length); double[] x_pi = GetNeighbor(x, r_index, constraints); double fx_pi = evaluate(x_pi, mLowerBounds, mUpperBounds, constraints); ContinuousSolution x_pi_refined = mLocalSearch.Minimize(x_pi, evaluate, calc_gradient, mLocalSearchTerminationCondition, constraints); if (best_solution.TryUpdateSolution(x_pi_refined.Values, x_pi_refined.Cost, out improvement)) { OnSolutionUpdated(best_solution, iteration); } x = best_solution.Values; fx = best_solution.Cost; OnStepped(best_solution, iteration); iteration++; } return(best_solution); }
public void UpdateParticleVelocity() { for (int i = 0; i < mParticles.Length; ++i) { for (int j = 0; j < mDimensionCount; ++j) { double oldV = mParticles[i][j, ParticleVectorType.Velocity]; double Xj = mParticles[i][j, ParticleVectorType.Position]; double X_lbest = mLocalBestParticles[i][j, ParticleVectorType.Position]; double X_gbest = mGlobalBestSolution[j, ParticleVectorType.Position]; double r1 = RandomEngine.NextDouble(); double r2 = RandomEngine.NextDouble(); double r3 = RandomEngine.NextDouble(); double w = 0.5 + r3 / 2; double newV = w * oldV + mC1 * r1 * (X_lbest - Xj) + mC2 * r2 * (X_gbest - Xj); mParticles[i][j, ParticleVectorType.Velocity] = newV; } } }
protected ContinuousSolution Reproduce(ContinuousSolution[] pop, ContinuousSolution p0, double[] lower_bounds, double[] upper_bounds) { ContinuousSolution[] parents = SelectParents(pop, p0); ContinuousSolution p1 = parents[0]; ContinuousSolution p2 = parents[1]; ContinuousSolution p3 = parents[2]; int cut_point = RandomEngine.NextInt(mDimension); ContinuousSolution child = new ContinuousSolution(mDimension); for (int i = 0; i < mDimension; ++i) { child[i] = p0[i]; if (i == cut_point || RandomEngine.NextDouble() < mCrossoverRate) { child[i] = p1[i] + mWeightingFactor * (p2[i] - p3[i]); child[i] = System.Math.Max(lower_bounds[i], child[i]); child[i] = System.Math.Min(upper_bounds[i], child[i]); } } return(child); }
public override void TransiteState(Ant ant, int state_index) { int current_state_id = ant.CurrentState; List <int> candidate_states = GetCandidateNextStates(ant, current_state_id); if (candidate_states.Count == 0) { return; } int selected_state_id = -1; double[] acc_prob = new double[candidate_states.Count]; double product_sum = 0; double max_product = double.MinValue; int state_id_with_max_prob = -1; for (int i = 0; i < candidate_states.Count; ++i) { int candidate_state_id = candidate_states[i]; double pheromone = mPheromones[current_state_id, candidate_state_id]; double heuristic_value = GetHeuristicValue(current_state_id, candidate_state_id); double product = System.Math.Pow(pheromone, m_alpha) * System.Math.Pow(heuristic_value, m_beta); product_sum += product; acc_prob[i] = product_sum; if (product > max_product) { max_product = product; state_id_with_max_prob = candidate_state_id; } } double r = RandomEngine.NextDouble(); if (r <= m_Q) { selected_state_id = state_id_with_max_prob; } else { r = RandomEngine.NextDouble(); for (int i = 0; i < candidate_states.Count; ++i) { acc_prob[i] /= product_sum; if (r <= acc_prob[i]) { selected_state_id = candidate_states[i]; break; } } } if (selected_state_id != -1) { ant.Add(selected_state_id); LocalPheromoneUpdate(current_state_id, selected_state_id); } }
static GeneralizedLeastSquareTest() { SIN_FUNCTIONS = new List <>(); for (int i = 0; i < WEIGHTS.Length; i++) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int k = i; int k = i; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.function.Function<double, double> func = new java.util.function.Function<double, double>() System.Func <double, double> func = (final double?x) => { return(Math.Sin((2 * k + 1) * x)); }; SIN_FUNCTIONS.Add(func); } TEST_FUNCTION = new BasisFunctionAggregation <>(SIN_FUNCTIONS, WEIGHTS); VECTOR_TRIG_FUNCTIONS = new List <>(); for (int i = 0; i < WEIGHTS.Length; i++) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int k = i; int k = i; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.function.Function<com.opengamma.strata.collect.array.DoubleArray, double> func = new java.util.function.Function<com.opengamma.strata.collect.array.DoubleArray, double>() System.Func <DoubleArray, double> func = (final DoubleArray x) => { ArgChecker.isTrue(x.size() == 2); return(Math.Sin((2 * k + 1) * x.get(0)) * Math.Cos((2 * k + 1) * x.get(1))); }; VECTOR_TRIG_FUNCTIONS.Add(func); } VECTOR_TEST_FUNCTION = new BasisFunctionAggregation <>(VECTOR_TRIG_FUNCTIONS, WEIGHTS); SIN_EXP_FUNCTION = (final double[] x) => { return(Math.Sin(Math.PI * x[0] / 10.0) * Math.Exp(-x[1] / 5.0)); }; const int n = 10; X = new double?[n]; Y = new double[n]; SIGMA = new double[n]; X_TRIG = new List <>(); Y_TRIG = new List <>(); SIGMA_TRIG = new List <>(); for (int i = 0; i < n; i++) { X[i] = i / 5.0; Y[i] = TEST_FUNCTION.apply(X[i]); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final double[] temp = new double[2]; double[] temp = new double[2]; temp[0] = 2.0 * RANDOM.NextDouble(); temp[1] = 2.0 * RANDOM.NextDouble(); X_TRIG.Add(DoubleArray.copyOf(temp)); Y_TRIG.Add(VECTOR_TEST_FUNCTION.apply(X_TRIG[i])); SIGMA[i] = 0.01; SIGMA_TRIG.Add(0.01); } SIGMA_COS_EXP = new List <>(); X_SIN_EXP = new List <>(); Y_SIN_EXP = new List <>(); for (int i = 0; i < 20; i++) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final double[] temp = new double[2]; double[] temp = new double[2]; temp[0] = 10.0 * RANDOM.NextDouble(); temp[1] = 10.0 * RANDOM.NextDouble(); X_SIN_EXP.Add(temp); Y_SIN_EXP.Add(SIN_EXP_FUNCTION.apply(X_SIN_EXP[i])); SIGMA_COS_EXP.Add(0.01); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final com.opengamma.strata.math.impl.interpolation.BasisFunctionGenerator generator = new com.opengamma.strata.math.impl.interpolation.BasisFunctionGenerator(); BasisFunctionGenerator generator = new BasisFunctionGenerator(); BASIS_FUNCTIONS = generator.generateSet(BasisFunctionKnots.fromUniform(0.0, 2.0, 20, 3)); BasisFunctionKnots[] knots = new BasisFunctionKnots[2]; knots[0] = BasisFunctionKnots.fromUniform(0, 10, 10, 3); knots[1] = BasisFunctionKnots.fromUniform(0, 10, 10, 3); BASIS_FUNCTIONS_2D = generator.generateSet(knots); }
public override ContinuousSolution Minimize(CostEvaluationMethod evaluate, GradientEvaluationMethod calc_gradient, TerminationEvaluationMethod should_terminate, object constraints = null) { double?improvement = null; int iteration = 0; ContinuousSolution[] pop = new ContinuousSolution[mPopSize]; double[] lower_bounds = null; double[] upper_bounds = null; if (mLowerBounds == null || mUpperBounds == null) { if (constraints is Tuple <double[], double[]> ) { Tuple <double[], double[]> bounds = constraints as Tuple <double[], double[]>; lower_bounds = bounds.Item1; upper_bounds = bounds.Item2; } else { throw new InvalidCastException(); } } else { lower_bounds = mLowerBounds; upper_bounds = mUpperBounds; } if (lower_bounds.Length < mDimension) { throw new IndexOutOfRangeException(); } if (upper_bounds.Length < mDimension) { throw new IndexOutOfRangeException(); } double[,] init_strategy_bounds = new double[mDimension, 2]; for (int j = 0; j < mDimension; ++j) { init_strategy_bounds[j, 0] = 0; init_strategy_bounds[j, 1] = (upper_bounds[j] - lower_bounds[j]) * 0.05; } ContinuousSolution best_solution = null; for (int i = 0; i < mPopSize; ++i) { double[] x = mSolutionGenerator(mDimension, constraints); double fx = evaluate(x, mLowerBounds, mUpperBounds, constraints); ContinuousSolution s = new ContinuousSolution(x, fx); double[] strategy = new double[mDimension]; for (int j = 0; j < mDimension; ++j) { strategy[j] = init_strategy_bounds[j, 0] + (init_strategy_bounds[j, 1] - init_strategy_bounds[j, 0]) * RandomEngine.NextDouble(); } s.SetMutationStrategy(strategy); pop[i] = s; } pop = pop.OrderBy(s => s.Cost).ToArray(); best_solution = pop[0].Clone() as ContinuousSolution; ContinuousSolution[] children = new ContinuousSolution[mPopSize]; ContinuousSolution[] generation = new ContinuousSolution[mPopSize * 2]; while (!should_terminate(improvement, iteration)) { for (int i = 0; i < mPopSize; ++i) { children[i] = Mutate(pop[i], lower_bounds, upper_bounds, constraints); children[i].Cost = evaluate(children[i].Values, mLowerBounds, mUpperBounds, constraints); } children = children.OrderBy(s => s.Cost).ToArray(); if (best_solution.TryUpdateSolution(children[0].Values, children[0].Cost, out improvement)) { OnSolutionUpdated(best_solution, iteration); } for (int i = 0; i < mPopSize; ++i) { generation[i] = pop[i]; } for (int i = 0; i < mPopSize; ++i) { generation[i + mPopSize] = children[i]; } for (int i = 0; i < generation.Length; ++i) { int wins = 0; ContinuousSolution si = generation[i]; for (int j = 0; j < mBoutSize; ++j) { ContinuousSolution sj = generation[RandomEngine.NextInt(generation.Length)]; if (si.Cost < sj.Cost) { wins++; } } si.SetWins(wins); } generation = generation.OrderByDescending(s => s.GetWins()).ToArray(); for (int i = 0; i < mPopSize; ++i) { pop[i] = generation[i]; } OnStepped(best_solution, iteration); iteration++; } return(best_solution); }
/// <summary> /// {@inheritDoc} /// </summary> public virtual double nextRandom() { double u = _engine.NextDouble() - 0.5; return(_mu - _b * Math.Sign(u) * Math.Log(1 - 2 * Math.Abs(u))); }
/// <summary> /// {@inheritDoc} /// </summary> public virtual double nextRandom() { return(_mu + _sigma * (Math.Pow(_engine.NextDouble(), -_ksi) - 1) / _ksi); }