コード例 #1
0
ファイル: AnalyticalPTSP.cs プロジェクト: t-h-e/HeuristicLab
 public static double Evaluate(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
   // Analytical evaluation
   var firstSum = 0.0;
   for (var i = 0; i < tour.Length - 1; i++) {
     for (var j = i + 1; j < tour.Length; j++) {
       var prod1 = distance(tour[i], tour[j]) * probabilities[tour[i]] * probabilities[tour[j]];
       for (var k = i + 1; k < j; k++) {
         prod1 = prod1 * (1 - probabilities[tour[k]]);
       }
       firstSum += prod1;
     }
   }
   var secondSum = 0.0;
   for (var j = 0; j < tour.Length; j++) {
     for (var i = 0; i < j; i++) {
       var prod2 = distance(tour[j], tour[i]) * probabilities[tour[i]] * probabilities[tour[j]];
       for (var k = j + 1; k < tour.Length; k++) {
         prod2 = prod2 * (1 - probabilities[tour[k]]);
       }
       for (var k = 0; k < i; k++) {
         prod2 = prod2 * (1 - probabilities[tour[k]]);
       }
       secondSum += prod2;
     }
   }
   return firstSum + secondSum;
 }
コード例 #2
0
 private DoubleArray Randomize(IRandom random, int length, DoubleMatrix bounds) {
   var result = new DoubleArray(length);
   for (int i = 0; i < length; i++) {
     result[i] = random.NextDouble() * bounds[i % bounds.Rows, 1] - bounds[i % bounds.Rows, 0];
   }
   return result;
 }
コード例 #3
0
 public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, Func<int, int, double> distance, DoubleArray probabilities) {
   if (move.IsInvert) {
     return PTSPAnalyticalInversionMoveEvaluator.EvaluateMove(permutation,
       new InversionMove(move.Index1, move.Index2, move.Permutation), distance, probabilities);
   } else {
     return PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(permutation,
       new TranslocationMove(move.Index1, move.Index1, move.Index2), distance, probabilities);
   }
 }
コード例 #4
0
 private DoubleArray Average(IRandom random, ItemArray<DoubleArray> parents) {
   int length = parents[0].Length;
   var result = new DoubleArray(length);
   for (int i = 0; i < length; i++) {
     for (int p = 0; p < parents.Length; p++) {
       result[i] += parents[p][i];
     }
     result[i] /= parents.Length;
   }
   return result;
 }
コード例 #5
0
    /// <summary>
    /// Performs a normally distributed all position manipulation on the given 
    /// <paramref name="vector"/> and rounds the result to the next feasible value.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown when the sigma vector is null or of length 0.</exception>
    /// <param name="sigma">The sigma vector determining the strength of the mutation.</param>
    /// <param name="random">A random number generator.</param>
    /// <param name="vector">The integer vector to manipulate.</param>#
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <returns>The manipulated integer vector.</returns>
    public static void Apply(IRandom random, IntegerVector vector, IntMatrix bounds, DoubleArray sigma) {
      if (sigma == null || sigma.Length == 0) throw new ArgumentException("RoundedNormalAllPositionsManipulator: Vector containing the standard deviations is not defined.", "sigma");
      if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2) throw new ArgumentException("RoundedNormalAllPositionsManipulator: Invalid bounds specified.", "bounds");
      var N = new NormalDistributedRandom(random, 0.0, 1.0);
      for (int i = 0; i < vector.Length; i++) {
        int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];

        int value = (vector[i] + (int)Math.Round((N.NextDouble() * sigma[i % sigma.Length])) - min) / step;
        max = FloorFeasible(min, max, step, max - 1);
        vector[i] = RoundFeasible(min, max, step, value);
      }
    }
コード例 #6
0
 /// <summary>
 /// Mutates the endogenous strategy parameters.
 /// </summary>
 /// <param name="random">The random number generator to use.</param>
 /// <param name="vector">The strategy vector to manipulate.</param>
 /// <param name="generalLearningRate">The general learning rate dampens the mutation over all dimensions.</param>
 /// <param name="learningRate">The learning rate dampens the mutation in each dimension.</param>
 /// <param name="bounds">The minimal and maximal value for each component, bounds are cycled if the length of bounds is smaller than the length of vector</param>
 public static void Apply(IRandom random, DoubleArray vector, double generalLearningRate, double learningRate, DoubleMatrix bounds) {
   NormalDistributedRandom N = new NormalDistributedRandom(random, 0.0, 1.0);
   double generalMultiplier = Math.Exp(generalLearningRate * N.NextDouble());
   for (int i = 0; i < vector.Length; i++) {
     double change = vector[i] * generalMultiplier * Math.Exp(learningRate * N.NextDouble());
     if (bounds != null) {
       double min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1];
       if (min == max) vector[i] = min;
       else {
         if (change < min || change > max) change = Math.Max(min, Math.Min(max, change));
         vector[i] = change;
       }
     }
   }
 }
コード例 #7
0
    protected override void OnContentChanged() {
      base.OnContentChanged();
      if (Content != null) {
        if (arrayView.Content != null) DeregisterArrayEvents((DoubleArray)arrayView.Content);
        var array = new DoubleArray(Content.Model.ModelWeights.ToArray());
        array.Resizable = false;
        array.ElementNames = Content.RegressionSolutions.Select(s => s.Name);

        RegisterArrayEvents(array);

        arrayView.Content = array;
        arrayView.Locked = Content.ProblemData == RegressionEnsembleProblemData.EmptyProblemData;
        averageEstimatesCheckBox.Checked = Content.Model.AverageModelEstimates;
      } else {
        arrayView.Content = null;
        averageEstimatesCheckBox.Checked = false;
      }
    }
コード例 #8
0
    public static OrienteeringEvaluationResult Apply(IntegerVector solution, DoubleArray scores,
      DistanceMatrix distances, double maximumDistance, double pointVisitingCosts, double distancePenaltyFactor) {

      double score = solution.Sum(t => scores[t]);
      double distance = distances.CalculateTourLength(solution.ToList(), pointVisitingCosts);

      double distanceViolation = distance - maximumDistance;

      double penalty = 0.0;
      penalty += distanceViolation > 0 ? distanceViolation * distancePenaltyFactor : 0;

      double quality = score - penalty;

      return new OrienteeringEvaluationResult {
        Quality = new DoubleValue(quality),
        Penalty = new DoubleValue(penalty),
        Distance = new DoubleValue(distance)
      };
    }
コード例 #9
0
    protected virtual void btnImpactCalculation_Click(object sender, EventArgs e) {
      var mainForm = (MainForm.WindowsForms.MainForm)MainFormManager.MainForm;
      var view = new StringConvertibleArrayView();
      view.Caption = Content.Name + " Variable Impacts";
      view.Show();

      Task.Factory.StartNew(() => {
        try {
          mainForm.AddOperationProgressToView(view, "Calculating variable impacts for " + Content.Name);

          var impacts = RegressionSolutionVariableImpactsCalculator.CalculateImpacts(Content);
          var impactArray = new DoubleArray(impacts.Select(i => i.Item2).ToArray());
          impactArray.ElementNames = impacts.Select(i => i.Item1);
          view.Content = (DoubleArray)impactArray.AsReadOnly();
        }
        finally {
          mainForm.RemoveOperationProgressFromView(view);
        }
      });
    }
コード例 #10
0
    public static void MyClassInitialize(TestContext testContext) {
      random = new MersenneTwister();
      coordinates = new DoubleMatrix(ProblemSize, 2);
      distances = new DistanceMatrix(ProblemSize, ProblemSize);
      for (var i = 0; i < ProblemSize; i++) {
        coordinates[i, 0] = random.Next(ProblemSize * 10);
        coordinates[i, 1] = random.Next(ProblemSize * 10);
      }
      for (var i = 0; i < ProblemSize - 1; i++) {
        for (var j = i + 1; j < ProblemSize; j++) {
          distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2)));
          distances[j, i] = distances[i, j];
        }
      }

      probabilities = new DoubleArray(ProblemSize);
      for (var i = 0; i < ProblemSize; i++) {
        probabilities[i] = random.NextDouble();
      }

      realizations = new ItemList<BoolArray>(RealizationsSize);
      for (var i = 0; i < RealizationsSize; i++) {
        var countOnes = 0;
        var newRealization = new BoolArray(ProblemSize);
        while (countOnes < 4) { //only generate realizations with at least 4 cities visited
          countOnes = 0;
          for (var j = 0; j < ProblemSize; j++) {
            newRealization[j] = random.NextDouble() < probabilities[j];
            if (newRealization[j]) countOnes++;
          }
        }
        realizations.Add(newRealization);
      }

      tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random);
    }
コード例 #11
0
 /// <summary>
 ///      Computes the next value of this indicator from the given state
 /// </summary>
 /// <param name="time"></param>
 /// <param name="input">The input given to the indicator</param>
 /// <returns>A new value for this indicator</returns>
 protected override DoubleArray Forward(long time, DoubleArray input)
 {
     _window.Add(input);
     _windowTimes.Add(time);
     return(Forward(_windowTimes, _window, time, input));
 }
コード例 #12
0
ファイル: Program.cs プロジェクト: aaronjanssen3120/nice
 public TimeSeries(DoubleArray x, DoubleArray y)
 {
     //DoubleArray x = x;
      //DoubleArray y=y;
 }
コード例 #13
0
 public OrienteeringEvaluationResult Evaluate(IntegerVector solution, DoubleArray scores,
                                              DistanceMatrix distances, double maximumDistance, double pointVisitingCosts)
 {
     return(Apply(solution, scores, distances, maximumDistance, pointVisitingCosts,
                  ((IValueParameter <DoubleValue>)DistancePenaltyFactorParameter).Value.Value));
 }
コード例 #14
0
ファイル: ChoiceFormat.gen.cs プロジェクト: bcrusu/jvm4csharp
 public void setChoices(DoubleArray arg0, ObjectArray<String> arg1)
 {
     Instance.CallMethod("setChoices", "([D[Ljava/lang/String;)V", arg0, arg1);
 }
        /// <summary>
        /// Create a <seealso cref="RawOptionData"/> object for calibration from data and shift one smile.
        /// </summary>
        /// <param name="tenors">  the list of tenors </param>
        /// <param name="expiries">  the list of expiries </param>
        /// <param name="strikeLikeType">  the type of the strike-like dimension </param>
        /// <param name="strikeLikeData">  the data related to the strike-like dimension </param>
        /// <param name="dataType">  the type of the data </param>
        /// <param name="dataArray">  the array with the raw data, including potential Double.NaN for missing data. </param>
        /// <param name="i">  the index of the tenor to shift </param>
        /// <param name="j">  the index of the expiry to shift </param>
        /// <param name="shift">  the size of the shift </param>
        /// <returns> the raw option data object </returns>
        public static TenorRawOptionData rawDataShiftSmile(IList <Tenor> tenors, IList <Period> expiries, ValueType strikeLikeType, DoubleArray strikeLikeData, ValueType dataType, double[][][] dataArray, int i, int j, double shift)
        {
            IDictionary <Tenor, RawOptionData> raw = new SortedDictionary <Tenor, RawOptionData>();

            for (int looptenor = 0; looptenor < dataArray.Length; looptenor++)
            {
                double[][] shiftedData = java.util.dataArray[looptenor].Select(row => row.clone()).ToArray(l => new double[l][]);   // deep copy of 2d array
                if (looptenor == i)
                {
                    for (int k = 0; k < shiftedData[j].Length; k++)
                    {
                        shiftedData[j][k] += shift;
                    }
                }
                DoubleMatrix matrix = DoubleMatrix.ofUnsafe(shiftedData);
                raw[tenors[looptenor]] = RawOptionData.of(expiries, strikeLikeData, strikeLikeType, matrix, dataType);
            }
            return(TenorRawOptionData.of(raw));
        }
コード例 #16
0
ファイル: PathPTSPTour.cs プロジェクト: t-h-e/HeuristicLab
 public PathPTSPTour(DoubleMatrix coordinates, DoubleArray probabilities)
   : base() {
   this.coordinates = coordinates;
   this.probabilities = probabilities;
   Initialize();
 }
コード例 #17
0
 public BoundCurveExtrapolator bind(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator)
 {
     return(new Bound(xValues, yValues, interpolator));
 }
コード例 #18
0
 /// <summary>
 /// Obtains an instance from volatility.
 /// </summary>
 /// <param name="expiry">  the time to expiry associated to the data </param>
 /// <param name="delta">  the delta of the different data points, must be positive and sorted in ascending order,
 ///   the put will have as delta the opposite of the numbers </param>
 /// <param name="volatility">  the volatilities </param>
 /// <param name="parameterMetadata">  the parameter metadata </param>
 /// <returns> the smile definition </returns>
 public static SmileDeltaParameters of(double expiry, DoubleArray delta, DoubleArray volatility, IList <ParameterMetadata> parameterMetadata)
 {
     ArgChecker.notNull(delta, "delta");
     ArgChecker.notNull(volatility, "volatility");
     return(new SmileDeltaParameters(expiry, delta, volatility, parameterMetadata));
 }
コード例 #19
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Obtains an instance from volatility.
 /// <para>
 /// {@code GenericVolatilitySurfaceYearFractionParameterMetadata} is used for parameter metadata.
 ///
 /// </para>
 /// </summary>
 /// <param name="expiry">  the time to expiry associated to the data </param>
 /// <param name="delta">  the delta of the different data points, must be positive and sorted in ascending order,
 ///   the put will have as delta the opposite of the numbers </param>
 /// <param name="volatility">  the volatilities </param>
 /// <returns> the smile definition </returns>
 public static SmileDeltaParameters of(double expiry, DoubleArray delta, DoubleArray volatility)
 {
     return(of(expiry, delta, volatility, createParameterMetadata(expiry, delta)));
 }
コード例 #20
0
        //-------------------------------------------------------------------------
        private static ImmutableList <ParameterMetadata> createParameterMetadata(double expiry, DoubleArray delta)
        {
            ArgChecker.notNull(delta, "delta");
            int nbDelta = delta.size();

            ParameterMetadata[] parameterMetadata = new ParameterMetadata[2 * nbDelta + 1];
            parameterMetadata[nbDelta] = GenericVolatilitySurfaceYearFractionParameterMetadata.of(expiry, DeltaStrike.of(0.5d));
            for (int i = 0; i < nbDelta; i++)
            {
                parameterMetadata[i] = GenericVolatilitySurfaceYearFractionParameterMetadata.of(expiry, DeltaStrike.of(1d - delta.get(i)));          // Put
                parameterMetadata[2 * nbDelta - i] = GenericVolatilitySurfaceYearFractionParameterMetadata.of(expiry, DeltaStrike.of(delta.get(i))); // Call
            }
            return(ImmutableList.copyOf(parameterMetadata));
        }
コード例 #21
0
        /// <summary>
        /// Obtains an instance from market data at-the-money, delta, risk-reversal and strangle.
        /// </summary>
        /// <param name="expiry">  the time to expiry associated to the data </param>
        /// <param name="atmVolatility">  the at-the-money volatility </param>
        /// <param name="delta">  the delta of the different data points, must be positive and sorted in ascending order,
        ///   the put will have as delta the opposite of the numbers </param>
        /// <param name="riskReversal">  the risk reversal volatility figures, in the same order as the delta </param>
        /// <param name="strangle">  the strangle volatility figures, in the same order as the delta </param>
        /// <param name="parameterMetadata">  the parameter metadata </param>
        /// <returns> the smile definition </returns>
        public static SmileDeltaParameters of(double expiry, double atmVolatility, DoubleArray delta, DoubleArray riskReversal, DoubleArray strangle, IList <ParameterMetadata> parameterMetadata)
        {
            ArgChecker.notNull(delta, "delta");
            ArgChecker.notNull(riskReversal, "riskReversal");
            ArgChecker.notNull(strangle, "strangle");
            int nbDelta = delta.size();

            ArgChecker.isTrue(nbDelta == riskReversal.size(), "Length of delta {} should be equal to length of riskReversal {}", delta.size(), riskReversal.size());
            ArgChecker.isTrue(nbDelta == strangle.size(), "Length of delta {} should be equal to length of strangle {} ", delta.size(), strangle.size());

            double[] volatility = new double[2 * nbDelta + 1];
            volatility[nbDelta] = atmVolatility;
            for (int i = 0; i < nbDelta; i++)
            {
                volatility[i] = strangle.get(i) + atmVolatility - riskReversal.get(i) / 2.0;               // Put
                volatility[2 * nbDelta - i] = strangle.get(i) + atmVolatility + riskReversal.get(i) / 2.0; // Call
            }
            return(of(expiry, delta, DoubleArray.ofUnsafe(volatility), parameterMetadata));
        }
コード例 #22
0
 /// <summary>
 /// Obtains an instance from market data at-the-money, delta, risk-reversal and strangle.
 /// <para>
 /// {@code GenericVolatilitySurfaceYearFractionParameterMetadata} is used for parameter metadata.
 ///
 /// </para>
 /// </summary>
 /// <param name="expiry">  the time to expiry associated to the data </param>
 /// <param name="atmVolatility">  the at-the-money volatility </param>
 /// <param name="delta">  the delta of the different data points, must be positive and sorted in ascending order,
 ///   the put will have as delta the opposite of the numbers </param>
 /// <param name="riskReversal">  the risk reversal volatility figures, in the same order as the delta </param>
 /// <param name="strangle">  the strangle volatility figures, in the same order as the delta </param>
 /// <returns> the smile definition </returns>
 public static SmileDeltaParameters of(double expiry, double atmVolatility, DoubleArray delta, DoubleArray riskReversal, DoubleArray strangle)
 {
     return(of(expiry, atmVolatility, delta, riskReversal, strangle, createParameterMetadata(expiry, delta)));
 }
コード例 #23
0
 private ValueDerivatives(double value, DoubleArray derivatives)
 {
     JodaBeanUtils.notNull(derivatives, "derivatives");
     this.value       = value;
     this.derivatives = derivatives;
 }
コード例 #24
0
ファイル: NKLandscape.cs プロジェクト: t-h-e/HeuristicLab
 public static double[] Normalize(DoubleArray weights) {
   double sum = 0;
   double[] w = new double[weights.Length];
   foreach (var v in weights) {
     sum += Math.Abs(v);
   }
   for (int i = 0; i < weights.Length; i++) {
     w[i] = Math.Abs(weights[i]) / sum;
   }
   return w;
 }
コード例 #25
0
 public static double EvaluateMove(Permutation tour, InversionMove move, Func<int, int, double> distance, DoubleArray probabilities) {
   var afterMove = (Permutation)tour.Clone();
   InversionManipulator.Apply(afterMove, move.Index1, move.Index2);
   return AnalyticalProbabilisticTravelingSalesmanProblem.Evaluate(afterMove, distance, probabilities);
 }
コード例 #26
0
 private DoubleScenarioArray(DoubleArray values)
 {
     JodaBeanUtils.notNull(values, "values");
     this.values = values;
 }
コード例 #27
0
ファイル: PathPTSPTour.cs プロジェクト: t-h-e/HeuristicLab
 private PathPTSPTour(PathPTSPTour original, Cloner cloner)
   : base(original, cloner) {
   this.coordinates = cloner.Clone(original.coordinates);
   this.probabilities = cloner.Clone(original.probabilities);
   this.permutation = cloner.Clone(original.permutation);
   this.quality = cloner.Clone(original.quality);
   Initialize();
 }
コード例 #28
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Obtains an instance from the specified array of values.
 /// </summary>
 /// <param name="values">  the values, one value for each scenario </param>
 /// <returns> an instance with the specified values </returns>
 public static DoubleScenarioArray of(DoubleArray values)
 {
     return(new DoubleScenarioArray(values));
 }
コード例 #29
0
 protected abstract double EvaluateMove(Permutation permutation, Func<int, int, double> distance, DoubleArray probabilities);
コード例 #30
0
 /// <summary>
 /// Obtains an instance from the specified list of values.
 /// </summary>
 /// <param name="values">  the values, one value for each scenario </param>
 /// <returns> an instance with the specified values </returns>
 public static DoubleScenarioArray of(IList <double> values)
 {
     return(new DoubleScenarioArray(DoubleArray.copyOf(values)));
 }
コード例 #31
0
    private void ReplacePoints(List<int> tour, List<int> visitablePoints,
      DistanceMatrix distances, double maxLength, DoubleArray scores,
      ref double tourLength, ref double tourScore, ref int evaluations, ref bool solutionChanged) {

      for (int tourPosition = 1; tourPosition < tour.Count - 1; tourPosition++) {
        // If an optimization has been done, start from the beginning
        if (solutionChanged) break;

        for (int i = 0; i < visitablePoints.Count; i++) {
          // If an optimization has been done, start from the beginning
          if (solutionChanged) break;

          evaluations++;

          double detour = distances.CalculateReplacementCosts(tour, tourPosition, visitablePoints[i]);

          double oldPointScore = scores[tour[tourPosition]];
          double newPointScore = scores[visitablePoints[i]];

          if ((tourLength + detour <= maxLength) && (newPointScore > oldPointScore)) {
            // Replace the old point by the new one
            tour[tourPosition] = visitablePoints[i];

            // Update the overall tour tourLength
            tourLength += detour;

            // Update the scores achieved by visiting this point
            tourScore += newPointScore - oldPointScore;

            // Re-run this optimization
            solutionChanged = true;
          }
        }
      }
    }
コード例 #32
0
 /// <summary>
 /// Obtains an instance using a function to create the entries.
 /// <para>
 /// The function is passed the scenario index and returns the value for that index.
 ///
 /// </para>
 /// </summary>
 /// <param name="size">  the number of elements </param>
 /// <param name="valueFunction">  the function used to obtain each value </param>
 /// <returns> an instance initialized using the function </returns>
 /// <exception cref="IllegalArgumentException"> is size is zero or less </exception>
 public static DoubleScenarioArray of(int size, System.Func <int, double> valueFunction)
 {
     ArgChecker.notNegativeOrZero(size, "size");
     return(new DoubleScenarioArray(DoubleArray.of(size, valueFunction)));
 }
コード例 #33
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Obtains an instance from a value and array of derivatives.
 /// </summary>
 /// <param name="value">  the value </param>
 /// <param name="derivatives">  the derivatives of the value </param>
 /// <returns> the object </returns>
 public static ValueDerivatives of(double value, DoubleArray derivatives)
 {
     return(new ValueDerivatives(value, derivatives));
 }
 public virtual BoundCurveInterpolator bind(DoubleArray xValues, DoubleArray yValues)
 {
     return(new Bound(xValues, yValues));
 }
コード例 #35
0
 private ComplexArray GetSignal(DoubleArray xList, DoubleArray zList)
 {
     return(ComplexArray.From(xList, zList));
 }
コード例 #36
0
ファイル: HaramiCross.cs プロジェクト: useric/FinanceSharp
        /// <summary>
        ///      Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="timeWindow"></param>
        /// <param name="window">The window of data held in this indicator</param>
        /// <param name="time"></param>
        /// <param name="input"></param>
        /// <returns>A new value for this indicator</returns>
        protected override DoubleArray Forward(IReadOnlyWindow <long> timeWindow, IReadOnlyWindow <DoubleArray> window, long time, DoubleArray input)
        {
            if (!IsReady)
            {
                if (Samples >= Period - _bodyLongAveragePeriod - 1 && Samples < Period - 1)
                {
                    _bodyLongPeriodTotal += GetCandleRange(CandleSettingType.BodyLong, input);
                }

                if (Samples >= Period - _bodyDojiAveragePeriod)
                {
                    _bodyDojiPeriodTotal += GetCandleRange(CandleSettingType.BodyDoji, input);
                }

                return(Constants.Zero);
            }

            double value;

            if (
                // 1st: long
                GetRealBody(window[1]) > GetCandleAverage(CandleSettingType.BodyLong, _bodyLongPeriodTotal, window[1]) &&
                // 2nd: doji
                GetRealBody(input) <= GetCandleAverage(CandleSettingType.BodyDoji, _bodyDojiPeriodTotal, input) &&
                //      engulfed by 1st
                Math.Max(input[CloseIdx], input.Open) < Math.Max(window[1].Close, window[1].Open) &&
                Math.Min(input[CloseIdx], input.Open) > Math.Min(window[1].Close, window[1].Open)
                )
            {
                value = -(int)GetCandleColor(window[1]);
            }
            else
            {
                value = Constants.Zero;
            }

            // add the current range and subtract the first range: this is done after the pattern recognition
            // when avgPeriod is not 0, that means "compare with the previous candles" (it excludes the current candle)

            _bodyLongPeriodTotal += GetCandleRange(CandleSettingType.BodyLong, window[1]) -
                                    GetCandleRange(CandleSettingType.BodyLong, window[_bodyLongAveragePeriod + 1]);

            _bodyDojiPeriodTotal += GetCandleRange(CandleSettingType.BodyDoji, input) -
                                    GetCandleRange(CandleSettingType.BodyDoji, window[_bodyDojiAveragePeriod]);

            return(value);
        }
コード例 #37
0
 private void DeregisterArrayEvents(DoubleArray array) {
   array.ItemChanged -= DoubleArray_Changed;
 }
コード例 #38
0
 /// <summary>
 ///      Computes the next value for this indicator from the given state.
 /// </summary>
 /// <param name="timeWindow"></param>
 /// <param name="window">The window of data held in this indicator</param>
 /// <param name="time"></param>
 /// <param name="input"></param>
 /// <returns>A new value for this indicator</returns>
 protected abstract DoubleArray Forward(IReadOnlyWindow <long> timeWindow, IReadOnlyWindow <DoubleArray> window, long time, DoubleArray input);
コード例 #39
0
    private void Content_ModelChanged(object sender, EventArgs eventArgs) {
      var array = (DoubleArray)arrayView.Content;
      var modelWeights = Content.Model.ModelWeights.ToList();

      if (array.Length != modelWeights.Count) {
        DeregisterArrayEvents(array);
        array = new DoubleArray(Content.Model.ModelWeights.ToArray());
        array.Resizable = false;
        RegisterArrayEvents(array);
      }

      for (int i = 0; i < modelWeights.Count; i++)
        array[i] = modelWeights[i];

      array.ElementNames = Content.RegressionSolutions.Select(s => s.Name);
      averageEstimatesCheckBox.Checked = Content.Model.AverageModelEstimates;
    }
コード例 #40
0
        //-------------------------------------------------------------------------
        // bumping a node point at (nodeExpiry, nodeDelta)
        private double nodeSensitivity(BlackFxOptionSmileVolatilities provider, CurrencyPair pair, ZonedDateTime expiry, double strike, double forward, double nodeExpiry, double nodeDelta)
        {
            double strikeMod  = provider.CurrencyPair.Equals(pair) ? strike : 1.0 / strike;
            double forwardMod = provider.CurrencyPair.Equals(pair) ? forward : 1.0 / forward;

            InterpolatedStrikeSmileDeltaTermStructure smileTerm = (InterpolatedStrikeSmileDeltaTermStructure)provider.Smile;

            double[] times  = smileTerm.Expiries.toArray();
            int      nTimes = times.Length;

            SmileDeltaParameters[] volTermUp = new SmileDeltaParameters[nTimes];
            SmileDeltaParameters[] volTermDw = new SmileDeltaParameters[nTimes];
            int deltaIndex = -1;

            for (int i = 0; i < nTimes; ++i)
            {
                DoubleArray deltas       = smileTerm.VolatilityTerm.get(i).Delta;
                int         nDeltas      = deltas.size();
                int         nDeltasTotal = 2 * nDeltas + 1;
                double[]    deltasTotal  = new double[nDeltasTotal];
                deltasTotal[nDeltas] = 0.5d;
                for (int j = 0; j < nDeltas; ++j)
                {
                    deltasTotal[j] = 1d - deltas.get(j);
                    deltasTotal[2 * nDeltas - j] = deltas.get(j);
                }
                double[] volsUp = smileTerm.VolatilityTerm.get(i).Volatility.toArray();
                double[] volsDw = smileTerm.VolatilityTerm.get(i).Volatility.toArray();
                if (Math.Abs(times[i] - nodeExpiry) < TOLERANCE)
                {
                    for (int j = 0; j < nDeltasTotal; ++j)
                    {
                        if (Math.Abs(deltasTotal[j] - nodeDelta) < TOLERANCE)
                        {
                            deltaIndex = j;
                            volsUp[j] += EPS;
                            volsDw[j] -= EPS;
                        }
                    }
                }
                volTermUp[i] = SmileDeltaParameters.of(times[i], deltas, DoubleArray.copyOf(volsUp));
                volTermDw[i] = SmileDeltaParameters.of(times[i], deltas, DoubleArray.copyOf(volsDw));
            }
            InterpolatedStrikeSmileDeltaTermStructure smileTermUp = InterpolatedStrikeSmileDeltaTermStructure.of(ImmutableList.copyOf(volTermUp), ACT_365F);
            InterpolatedStrikeSmileDeltaTermStructure smileTermDw = InterpolatedStrikeSmileDeltaTermStructure.of(ImmutableList.copyOf(volTermDw), ACT_365F);
            BlackFxOptionSmileVolatilities            provUp      = BlackFxOptionSmileVolatilities.of(NAME, CURRENCY_PAIR, VAL_DATE_TIME, smileTermUp);
            BlackFxOptionSmileVolatilities            provDw      = BlackFxOptionSmileVolatilities.of(NAME, CURRENCY_PAIR, VAL_DATE_TIME, smileTermDw);
            double volUp      = provUp.volatility(pair, expiry, strike, forward);
            double volDw      = provDw.volatility(pair, expiry, strike, forward);
            double totalSensi = 0.5 * (volUp - volDw) / EPS;

            double expiryTime = provider.relativeTime(expiry);
            SmileDeltaParameters singleSmile = smileTerm.smileForExpiry(expiryTime);

            double[] strikesUp = singleSmile.strike(forwardMod).toArray();
            double[] strikesDw = strikesUp.Clone();
            double[] vols      = singleSmile.Volatility.toArray();
            strikesUp[deltaIndex] += EPS;
            strikesDw[deltaIndex] -= EPS;
            double volStrikeUp = LINEAR.bind(DoubleArray.ofUnsafe(strikesUp), DoubleArray.ofUnsafe(vols), FLAT, FLAT).interpolate(strikeMod);
            double volStrikeDw = LINEAR.bind(DoubleArray.ofUnsafe(strikesDw), DoubleArray.ofUnsafe(vols), FLAT, FLAT).interpolate(strikeMod);
            double sensiStrike = 0.5 * (volStrikeUp - volStrikeDw) / EPS;
            SmileDeltaParameters singleSmileUp = smileTermUp.smileForExpiry(expiryTime);
            double strikeUp = singleSmileUp.strike(forwardMod).get(deltaIndex);
            SmileDeltaParameters singleSmileDw = smileTermDw.smileForExpiry(expiryTime);
            double strikeDw = singleSmileDw.strike(forwardMod).get(deltaIndex);
            double sensiVol = 0.5 * (strikeUp - strikeDw) / EPS;

            return(totalSensi - sensiStrike * sensiVol);
        }
コード例 #41
0
ファイル: NKLandscape.cs プロジェクト: t-h-e/HeuristicLab
 public static double Evaluate(BinaryVector vector, BoolMatrix interactions, DoubleArray weights, int seed, out double[] f_i, int q, double p) {
   long x = Encode(vector);
   long[] g = Encode(interactions);
   double[] w = Normalize(weights);
   f_i = new double[interactions.Columns];
   return F(x, g, w, (long)seed, ref f_i, q, p);
 }
コード例 #42
0
ファイル: DarkCloudCover.cs プロジェクト: useric/FinanceSharp
        /// <summary>
        ///      Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="timeWindow"></param>
        /// <param name="window">The window of data held in this indicator</param>
        /// <param name="time"></param>
        /// <param name="input"></param>
        /// <returns>A new value for this indicator</returns>
        protected override DoubleArray Forward(IReadOnlyWindow <long> timeWindow, IReadOnlyWindow <DoubleArray> window, long time, DoubleArray input)
        {
            if (!IsReady)
            {
                if (Samples >= Period - _bodyLongAveragePeriod)
                {
                    _bodyLongPeriodTotal += GetCandleRange(CandleSettingType.BodyLong, window[1]);
                }

                return(Constants.Zero);
            }

            double value;

            if (
                // 1st: white
                GetCandleColor(window[1]) == CandleColor.White &&
                //      long
                GetRealBody(window[1]) > GetCandleAverage(CandleSettingType.BodyLong, _bodyLongPeriodTotal, window[1]) &&
                // 2nd: black
                GetCandleColor(input) == CandleColor.Black &&
                //      open above prior high
                input.Open > window[1].High &&
                //      close within prior body
                input[CloseIdx] > window[1].Open &&
                input[CloseIdx] < window[1].Close - GetRealBody(window[1]) * _penetration
                )
            {
                value = -1d;
            }
            else
            {
                value = Constants.Zero;
            }

            // add the current range and subtract the first range: this is done after the pattern recognition
            // when avgPeriod is not 0, that means "compare with the previous candles" (it excludes the current candle)

            _bodyLongPeriodTotal += GetCandleRange(CandleSettingType.BodyLong, window[1]) -
                                    GetCandleRange(CandleSettingType.BodyLong, window[_bodyLongAveragePeriod + 1]);

            return(value);
        }
コード例 #43
0
 protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
   return EvaluateMove(tour, InversionMoveParameter.ActualValue, distance, probabilities);
 }
コード例 #44
0
        protected internal override QuantileResult quantile(double level, DoubleArray sample, bool isExtrapolated)
        {
            ArgChecker.isTrue(level > 0, "Quantile should be above 0.");
            ArgChecker.isTrue(level < 1, "Quantile should be below 1.");
            int    sampleSize    = sampleCorrection(sample.size());
            double adjustedLevel = checkIndex(level * sampleSize + indexCorrection(), sample.size(), isExtrapolated);

            double[] order = createIndexArray(sample.size());
            double[] s     = sample.toArray();
            DoubleArrayMath.sortPairs(s, order);
            int    lowerIndex  = (int)Math.Floor(adjustedLevel);
            int    upperIndex  = (int)Math.Ceiling(adjustedLevel);
            double lowerWeight = upperIndex - adjustedLevel;
            double upperWeight = 1d - lowerWeight;

            return(QuantileResult.of(lowerWeight * s[lowerIndex - 1] + upperWeight * s[upperIndex - 1], new int[] { (int)order[lowerIndex - 1], (int)order[upperIndex - 1] }, DoubleArray.of(lowerWeight, upperWeight)));
        }
コード例 #45
0
ファイル: PathPTSPTour.cs プロジェクト: t-h-e/HeuristicLab
 public PathPTSPTour(DoubleMatrix coordinates, DoubleArray probabilities, Permutation permutation, DoubleValue quality)
   : base() {
   this.coordinates = coordinates;
   this.probabilities = probabilities;
   this.permutation = permutation;
   this.quality = quality;
   Initialize();
 }
コード例 #46
0
        private CurrencyParameterSensitivities sensitivityCreidtCurve <T>(ImmutableCreditRatesProvider provider, System.Func <ImmutableCreditRatesProvider, CurrencyAmount> valueFn, MetaProperty <ImmutableMap <T, LegalEntitySurvivalProbabilities> > metaProperty, CurrencyAmount valueInit)
        {
            ImmutableMap <T, LegalEntitySurvivalProbabilities> baseCurves = metaProperty.get(provider);
            CurrencyParameterSensitivities result = CurrencyParameterSensitivities.empty();

            foreach (T key in baseCurves.Keys)
            {
                LegalEntitySurvivalProbabilities credit = baseCurves.get(key);
                CreditDiscountFactors            creditDiscountFactors = credit.SurvivalProbabilities;
                DiscountFactors discountFactors = creditDiscountFactors.toDiscountFactors();
                Curve           curve           = checkDiscountFactors(discountFactors);
                int             paramCount      = curve.ParameterCount;
                double[]        sensitivity     = new double[paramCount];
                for (int i = 0; i < paramCount; i++)
                {
                    Curve dscBumped = curve.withParameter(i, curve.getParameter(i) + shift);
                    IDictionary <T, LegalEntitySurvivalProbabilities> mapBumped = new Dictionary <T, LegalEntitySurvivalProbabilities>(baseCurves);
                    mapBumped[key] = LegalEntitySurvivalProbabilities.of(credit.LegalEntityId, createCreditDiscountFactors(creditDiscountFactors, dscBumped));
                    ImmutableCreditRatesProvider providerDscBumped = provider.toBuilder().set(metaProperty, mapBumped).build();
                    sensitivity[i] = (valueFn(providerDscBumped).Amount - valueInit.Amount) / shift;
                }
                result = result.combinedWith(curve.createParameterSensitivity(valueInit.Currency, DoubleArray.copyOf(sensitivity)));
            }
            return(result);
        }
コード例 #47
0
ファイル: AnalyticalPTSP.cs プロジェクト: t-h-e/HeuristicLab
 public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, DoubleArray probabilities) {
   return Evaluate(tour, (a, b) => distanceMatrix[a, b], probabilities);
 }
コード例 #48
0
 public void Visit(DoubleArray array) => CreateBuffers(array);
    public override IOperation Apply() {
      int updateInterval = UpdateIntervalParameter.Value.Value;
      IntValue updateCounter = UpdateCounterParameter.ActualValue;

      if (updateCounter == null) {
        updateCounter = new IntValue(updateInterval);
        UpdateCounterParameter.ActualValue = updateCounter;
      }

      if (updateCounter.Value == updateInterval) {
        var trees = SymbolicExpressionTreeParameter.ActualValue;
        var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
        var problemData = ProblemDataParameter.ActualValue;
        var ds = ProblemDataParameter.ActualValue.Dataset;
        var rows = ProblemDataParameter.ActualValue.TrainingIndices;
        var modelCreator = ModelCreatorParameter.ActualValue;
        var estimationLimits = EstimationLimitsParameter.ActualValue;
        var evaluatedValues = new ItemArray<DoubleArray>(trees.Length);
        for (int i = 0; i < trees.Length; ++i) {
          var model = (IDiscriminantFunctionClassificationModel)modelCreator.CreateSymbolicDiscriminantFunctionClassificationModel(problemData.TargetVariable, trees[i], interpreter, estimationLimits.Lower, estimationLimits.Upper);
          model.RecalculateModelParameters(problemData, rows);
          var values = UseClassValues ? model.GetEstimatedClassValues(ds, rows) : model.GetEstimatedValues(ds, rows);
          evaluatedValues[i] = new DoubleArray(values.ToArray());
        }
        EvaluatedValuesParameter.ActualValue = evaluatedValues;
      }
      return base.Apply();
    }
コード例 #50
0
 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
   var distanceM = (DistanceMatrix)distances;
   Func<int, int, double> distance = (a, b) => distanceM[a, b];
   for (var i = localIterations.Value; i < maxIterations; i++) {
     TranslocationMove bestMove = null;
     var bestQuality = quality.Value; // we have to make an improvement, so current quality is the baseline
     var evaluations = 0.0;
     foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
       var moveQuality = PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
       evaluations++;
       if (maximization && moveQuality > bestQuality
         || !maximization && moveQuality < bestQuality) {
         bestQuality = moveQuality;
         bestMove = move;
       }
     }
     evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
     if (bestMove == null) break;
     TranslocationManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2, bestMove.Index3);
     quality.Value = bestQuality;
     localIterations.Value++;
     cancellation.ThrowIfCancellationRequested();
   }
 }
コード例 #51
0
ファイル: Extensions.cs プロジェクト: algobasket/Dynamo
 /// <summary>
 /// Convert array of points to list of xyz's
 /// </summary>
 /// <param name="list">The list to convert</param>
 /// <returns></returns>
 public static DoubleArray ToDoubleArray(this double[] list)
 {
     var n = new DoubleArray();
     list.ToList().ForEach(x => n.Append(ref x));
     return n;
 }
        /// <summary>
        /// Create a <seealso cref="RawOptionData"/> object for calibration from data.
        /// </summary>
        /// <param name="tenors">  the list of tenors </param>
        /// <param name="expiries">  the list of expiries </param>
        /// <param name="strikeLikeType">  the type of the strike-like dimension </param>
        /// <param name="strikeLikeData">  the data related to the strike-like dimension </param>
        /// <param name="dataType">  the type of the data </param>
        /// <param name="dataArray">  the array with the raw data, including potential Double.NaN for missing data. </param>
        /// <returns> the raw option data object </returns>
        public static TenorRawOptionData rawData(IList <Tenor> tenors, IList <Period> expiries, ValueType strikeLikeType, DoubleArray strikeLikeData, ValueType dataType, double[][][] dataArray)
        {
            IDictionary <Tenor, RawOptionData> raw = new SortedDictionary <Tenor, RawOptionData>();

            for (int looptenor = 0; looptenor < dataArray.Length; looptenor++)
            {
                DoubleMatrix matrix = DoubleMatrix.ofUnsafe(dataArray[looptenor]);
                raw[tenors[looptenor]] = RawOptionData.of(expiries, strikeLikeData, strikeLikeType, matrix, dataType);
            }
            return(TenorRawOptionData.of(raw));
        }
コード例 #53
0
    private void IncludeNewPoints(List<int> tour, List<int> visitablePoints,
      DistanceMatrix distances, double pointVisitingCosts, double maxLength, DoubleArray scores,
      ref double tourLength, ref double tourScore, ref int evaluations, ref bool solutionChanged) {

      for (int tourPosition = 1; tourPosition < tour.Count; tourPosition++) {
        // If an optimization has been done, start from the beginning
        if (solutionChanged) break;

        for (int i = 0; i < visitablePoints.Count; i++) {
          // If an optimization has been done, start from the beginning
          if (solutionChanged) break;

          evaluations++;

          double detour = distances.CalculateInsertionCosts(tour, tourPosition, visitablePoints[i], pointVisitingCosts);

          // Determine if including the point does not violate any constraint
          if (tourLength + detour <= maxLength) {
            // Insert the new point at this position
            tour.Insert(tourPosition, visitablePoints[i]);

            // Update the overall tour tourLength and score
            tourLength += detour;
            tourScore += scores[visitablePoints[i]];

            // Re-run this optimization
            solutionChanged = true;
          }
        }
      }
    }
コード例 #54
0
        protected override double GetTourInsertionCosts(IVRPProblemInstance instance, IVRPEncoding solution, TourInsertionInfo tourInsertionInfo, int index, int customer,
                                                        out bool feasible)
        {
            CVRPPDTWInsertionInfo insertionInfo = tourInsertionInfo.GetStopInsertionInfo(index) as CVRPPDTWInsertionInfo;

            double costs = 0;

            feasible = tourInsertionInfo.Penalty < double.Epsilon;
            bool tourFeasible = true;

            ICapacitatedProblemInstance cvrp = instance as ICapacitatedProblemInstance;
            double overloadPenalty           = cvrp.OverloadPenalty.Value;

            ITimeWindowedProblemInstance vrptw = instance as ITimeWindowedProblemInstance;
            DoubleArray dueTime          = vrptw.DueTime;
            DoubleArray readyTime        = vrptw.ReadyTime;
            DoubleArray serviceTimes     = vrptw.ServiceTime;
            double      tardinessPenalty = vrptw.TardinessPenalty.Value;

            IPickupAndDeliveryProblemInstance pdp = instance as IPickupAndDeliveryProblemInstance;
            IntArray pickupDeliveryLocation       = pdp.PickupDeliveryLocation;
            double   pickupPenalty = pdp.PickupViolationPenalty.Value;

            double distance    = instance.GetDistance(insertionInfo.Start, insertionInfo.End, solution);
            double newDistance =
                instance.GetDistance(insertionInfo.Start, customer, solution) +
                instance.GetDistance(customer, insertionInfo.End, solution);

            costs += instance.DistanceFactor.Value * (newDistance - distance);

            double demand = instance.Demand[customer];

            if (demand > insertionInfo.ArrivalSpareCapacity)
            {
                tourFeasible = feasible = false;
                if (insertionInfo.ArrivalSpareCapacity >= 0)
                {
                    costs += (demand - insertionInfo.ArrivalSpareCapacity) * overloadPenalty;
                }
                else
                {
                    costs += demand * overloadPenalty;
                }
            }
            int destination = pickupDeliveryLocation[customer];

            bool validPickup = true;

            if (demand < 0 && !insertionInfo.Visited.Contains(destination))
            {
                tourFeasible = feasible = false;
                validPickup  = false;
                costs       += pickupPenalty;
            }

            double time      = 0;
            double tardiness = 0;

            if (index > 0)
            {
                time = (tourInsertionInfo.GetStopInsertionInfo(index - 1) as CVRPTWInsertionInfo).LeaveTime;
            }
            else
            {
                time = insertionInfo.TourStartTime;
            }

            time += instance.GetDistance(insertionInfo.Start, customer, solution);
            if (time > dueTime[customer])
            {
                tardiness += time - dueTime[customer];
            }
            if (time < readyTime[customer])
            {
                time += readyTime[customer] - time;
            }
            time += serviceTimes[customer];
            time += instance.GetDistance(customer, insertionInfo.End, solution);

            double additionalTime = time - (tourInsertionInfo.GetStopInsertionInfo(index) as CVRPTWInsertionInfo).ArrivalTime;

            for (int i = index; i < tourInsertionInfo.GetStopCount(); i++)
            {
                CVRPTWInsertionInfo nextStop = tourInsertionInfo.GetStopInsertionInfo(i) as CVRPTWInsertionInfo;

                if (demand >= 0)
                {
                    if (nextStop.End == destination)
                    {
                        demand = 0;
                        costs -= pickupPenalty;
                        if (tourInsertionInfo.Penalty == pickupPenalty && tourFeasible)
                        {
                            feasible = true;
                        }
                    }
                    else if (nextStop.SpareCapacity < 0)
                    {
                        costs += demand * overloadPenalty;
                    }
                    else if (nextStop.SpareCapacity < demand)
                    {
                        tourFeasible = feasible = false;
                        costs       += (demand - nextStop.SpareCapacity) * overloadPenalty;
                    }
                }
                else if (validPickup)
                {
                    if (nextStop.SpareCapacity < 0)
                    {
                        costs += Math.Max(demand, nextStop.SpareCapacity) * overloadPenalty;
                    }
                }

                if (additionalTime < 0)
                {
                    //arrive earlier than before
                    //wait probably
                    if (nextStop.WaitingTime < 0)
                    {
                        double wait = nextStop.WaitingTime - additionalTime;
                        if (wait > 0)
                        {
                            additionalTime += wait;
                        }
                    }
                    else
                    {
                        additionalTime = 0;
                    }

                    //check due date, decrease tardiness
                    if (nextStop.SpareTime < 0)
                    {
                        costs += Math.Max(nextStop.SpareTime, additionalTime) * tardinessPenalty;
                    }
                }
                else
                {
                    //arrive later than before, probably don't have to wait
                    if (nextStop.WaitingTime > 0)
                    {
                        additionalTime -= Math.Min(additionalTime, nextStop.WaitingTime);
                    }

                    //check due date
                    if (nextStop.SpareTime > 0)
                    {
                        double spare = nextStop.SpareTime - additionalTime;
                        if (spare < 0)
                        {
                            tardiness += -spare;
                        }
                    }
                    else
                    {
                        tardiness += additionalTime;
                    }
                }
            }

            costs += additionalTime * vrptw.TimeFactor.Value;

            if (tardiness > 0)
            {
                tourFeasible = feasible = false;
            }

            costs += tardiness * tardinessPenalty;

            return(costs);
        }
コード例 #55
0
ファイル: ChoiceFormat.gen.cs プロジェクト: bcrusu/jvm4csharp
 public ChoiceFormat(DoubleArray arg0, ObjectArray<String> arg1)
     : base(ProxyCtor.I)
 {
     Instance.CallConstructor("([D[Ljava/lang/String;)V", arg0, arg1);
 }
コード例 #56
0
        protected override void EvaluateTour(VRPEvaluation eval, IVRPProblemInstance instance, Tour tour, IVRPEncoding solution)
        {
            TourInsertionInfo tourInfo = new TourInsertionInfo(solution.GetVehicleAssignment(solution.GetTourIndex(tour)));

            eval.InsertionInfo.AddTourInsertionInfo(tourInfo);
            double originalQuality = eval.Quality;

            IHomogenousCapacitatedProblemInstance cvrpInstance = instance as IHomogenousCapacitatedProblemInstance;
            DoubleArray demand = instance.Demand;

            ITimeWindowedProblemInstance vrptw = instance as ITimeWindowedProblemInstance;
            DoubleArray dueTime      = vrptw.DueTime;
            DoubleArray readyTime    = vrptw.ReadyTime;
            DoubleArray serviceTimes = vrptw.ServiceTime;

            IPickupAndDeliveryProblemInstance pdp = instance as IPickupAndDeliveryProblemInstance;
            IntArray pickupDeliveryLocation       = pdp.PickupDeliveryLocation;

            double capacity = cvrpInstance.Capacity.Value;

            double time        = 0.0;
            double waitingTime = 0.0;
            double serviceTime = 0.0;
            double tardiness   = 0.0;
            double overweight  = 0.0;
            double distance    = 0.0;

            double currentLoad           = 0.0;
            Dictionary <int, bool> stops = new Dictionary <int, bool>();
            int pickupViolations         = 0;

            double tourStartTime = readyTime[0];

            time = tourStartTime;

            //simulate a tour, start and end at depot
            for (int i = 0; i <= tour.Stops.Count; i++)
            {
                int start = 0;
                if (i > 0)
                {
                    start = tour.Stops[i - 1];
                }
                int end = 0;
                if (i < tour.Stops.Count)
                {
                    end = tour.Stops[i];
                }

                //drive there
                double currentDistace = vrptw.GetDistance(start, end, solution);
                time     += currentDistace;
                distance += currentDistace;

                double arrivalTime = time;

                //check if it was serviced on time
                if (time > dueTime[end])
                {
                    tardiness += time - dueTime[end];
                }

                //wait
                double currentWaitingTime = 0.0;
                if (time < readyTime[end])
                {
                    currentWaitingTime = readyTime[end] - time;
                }

                double waitTime = readyTime[end] - time;

                waitingTime += currentWaitingTime;
                time        += currentWaitingTime;

                double spareTime = dueTime[end] - time;

                //service
                double currentServiceTime = serviceTimes[end];
                serviceTime += currentServiceTime;
                time        += currentServiceTime;

                //Pickup / deliver
                double arrivalSpareCapacity = capacity - currentLoad;

                bool validPickupDelivery =
                    validPickupDelivery =
                        ((demand[end] >= 0) ||
                         (stops.ContainsKey(pickupDeliveryLocation[end])));

                if (validPickupDelivery)
                {
                    currentLoad += demand[end];
                }
                else
                {
                    pickupViolations++;
                }

                if (currentLoad > capacity)
                {
                    overweight += currentLoad - capacity;
                }

                double spareCapacity           = capacity - currentLoad;
                CVRPPDTWInsertionInfo stopInfo = new CVRPPDTWInsertionInfo(start, end, spareCapacity, tourStartTime,
                                                                           arrivalTime, time, spareTime, waitTime, new List <int>(stops.Keys), arrivalSpareCapacity);
                tourInfo.AddStopInsertionInfo(stopInfo);

                stops.Add(end, true);
            }

            eval.Quality            += instance.FleetUsageFactor.Value;
            eval.Quality            += instance.DistanceFactor.Value * distance;
            eval.Distance           += distance;
            eval.VehicleUtilization += 1;

            (eval as CVRPEvaluation).Overload += overweight;
            double tourPenalty = 0;
            double penalty     = overweight * cvrpInstance.OverloadPenalty.Value;

            eval.Penalty += penalty;
            eval.Quality += penalty;
            tourPenalty  += penalty;

            (eval as CVRPTWEvaluation).Tardiness  += tardiness;
            (eval as CVRPTWEvaluation).TravelTime += time;

            penalty       = tardiness * vrptw.TardinessPenalty.Value;
            eval.Penalty += penalty;
            eval.Quality += penalty;
            tourPenalty  += penalty;

            (eval as CVRPPDTWEvaluation).PickupViolations += pickupViolations;
            penalty       = pickupViolations * pdp.PickupViolationPenalty.Value;
            eval.Penalty += penalty;
            tourPenalty  += penalty;

            eval.Quality    += penalty;
            eval.Quality    += time * vrptw.TimeFactor.Value;
            tourInfo.Penalty = tourPenalty;
            tourInfo.Quality = eval.Quality - originalQuality;
        }
コード例 #57
0
        //-------------------------------------------------------------------------
        public override IborCapletFloorletVolatilityCalibrationResult calibrate(IborCapletFloorletVolatilityDefinition definition, ZonedDateTime calibrationDateTime, RawOptionData capFloorData, RatesProvider ratesProvider)
        {
            ArgChecker.isTrue(ratesProvider.ValuationDate.Equals(calibrationDateTime.toLocalDate()), "valuationDate of ratesProvider should be coherent to calibrationDateTime");
            ArgChecker.isTrue(definition is SabrIborCapletFloorletVolatilityCalibrationDefinition, "definition should be SabrIborCapletFloorletVolatilityCalibrationDefinition");
            SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition = (SabrIborCapletFloorletVolatilityCalibrationDefinition)definition;
            // unpack cap data, create node caps
            IborIndex index           = sabrDefinition.Index;
            LocalDate calibrationDate = calibrationDateTime.toLocalDate();
            LocalDate baseDate        = index.EffectiveDateOffset.adjust(calibrationDate, ReferenceData);
            LocalDate startDate       = baseDate.plus(index.Tenor);

            System.Func <Surface, IborCapletFloorletVolatilities> volatilitiesFunction = this.volatilitiesFunction(sabrDefinition, calibrationDateTime, capFloorData);
            SurfaceMetadata metadata   = sabrDefinition.createMetadata(capFloorData);
            IList <Period>  expiries   = capFloorData.Expiries;
            DoubleArray     strikes    = capFloorData.Strikes;
            int             nExpiries  = expiries.Count;
            IList <double>  timeList   = new List <double>();
            IList <double>  strikeList = new List <double>();
            IList <double>  volList    = new List <double>();
            IList <ResolvedIborCapFloorLeg> capList = new List <ResolvedIborCapFloorLeg>();
            IList <double> priceList   = new List <double>();
            IList <double> errorList   = new List <double>();
            DoubleMatrix   errorMatrix = capFloorData.Error.orElse(DoubleMatrix.filled(nExpiries, strikes.size(), 1d));

            int[] startIndex = new int[nExpiries + 1];
            for (int i = 0; i < nExpiries; ++i)
            {
                LocalDate   endDate           = baseDate.plus(expiries[i]);
                DoubleArray volatilityForTime = capFloorData.Data.row(i);
                DoubleArray errorForTime      = errorMatrix.row(i);
                reduceRawData(sabrDefinition, ratesProvider, capFloorData.Strikes, volatilityForTime, errorForTime, startDate, endDate, metadata, volatilitiesFunction, timeList, strikeList, volList, capList, priceList, errorList);
                startIndex[i + 1] = volList.Count;
                ArgChecker.isTrue(startIndex[i + 1] > startIndex[i], "no valid option data for {}", expiries[i]);
            }
            // create initial caplet vol surface
            IList <CurveMetadata> metadataList                = sabrDefinition.createSabrParameterMetadata();
            DoubleArray           initialValues               = sabrDefinition.createFullInitialValues();
            IList <Curve>         curveList                   = sabrDefinition.createSabrParameterCurve(metadataList, initialValues);
            SabrParameters        sabrParamsInitial           = SabrParameters.of(curveList[0], curveList[1], curveList[2], curveList[3], sabrDefinition.ShiftCurve, sabrDefinition.SabrVolatilityFormula);
            SabrParametersIborCapletFloorletVolatilities vols = SabrParametersIborCapletFloorletVolatilities.of(sabrDefinition.Name, index, calibrationDateTime, sabrParamsInitial);
            // solve least square
            UncoupledParameterTransforms transform = new UncoupledParameterTransforms(initialValues, sabrDefinition.createFullTransform(TRANSFORMS), new BitArray());

            System.Func <DoubleArray, DoubleArray>  valueFunction    = createPriceFunction(sabrDefinition, ratesProvider, vols, capList, priceList);
            System.Func <DoubleArray, DoubleMatrix> jacobianFunction = createJacobianFunction(sabrDefinition, ratesProvider, vols, capList, priceList, index.Currency);
            NonLinearTransformFunction      transFunc    = new NonLinearTransformFunction(valueFunction, jacobianFunction, transform);
            LeastSquareResults              res          = solver.solve(DoubleArray.filled(priceList.Count, 1d), DoubleArray.copyOf(errorList), transFunc.FittingFunction, transFunc.FittingJacobian, transform.transform(initialValues));
            LeastSquareResultsWithTransform resTransform = new LeastSquareResultsWithTransform(res, transform);

            vols = updateParameters(sabrDefinition, vols, resTransform.ModelParameters);

            return(IborCapletFloorletVolatilityCalibrationResult.ofLeastSquare(vols, res.ChiSq));
        }
        private void checkCalibrationPrice(DoubleArray moneyness, DoubleArray blackVol, DoubleArray startParameters, BitArray @fixed, double shift, double tolerance)
        {
            double[] prices = new double[moneyness.size()];
            for (int i = 0; i < moneyness.size(); i++)
            {
                prices[i] = BlackFormulaRepository.price(FORWARD, FORWARD + moneyness.get(i), TIME_EXPIRY, blackVol.get(i), true);
                // Prices generated from Black implied volatilities
            }
            Pair <LeastSquareResultsWithTransform, DoubleArray> rComputed = SABR_CALIBRATION.calibrateLsShiftedFromPrices(BDA, CALIBRATION_TIME, ACT_365F, EXPIRY_PERIOD, FORWARD, moneyness, ValueType.SIMPLE_MONEYNESS, DoubleArray.ofUnsafe(prices), startParameters, @fixed, shift);
            SabrFormulaData sabrComputed = SabrFormulaData.of(rComputed.First.ModelParameters.toArrayUnsafe());

            for (int i = 0; i < moneyness.size(); i++)
            {
                double ivComputed    = SABR_FORMULA.volatility(FORWARD + shift, FORWARD + moneyness.get(i) + shift, TIME_EXPIRY, sabrComputed.Alpha, sabrComputed.Beta, sabrComputed.Rho, sabrComputed.Nu);
                double priceComputed = BlackFormulaRepository.price(FORWARD + shift, FORWARD + moneyness.get(i) + shift, TIME_EXPIRY, ivComputed, true);
                assertEquals(priceComputed, prices[i], tolerance);
            }
        }
コード例 #59
0
 /// <summary>
 /// Generates a new random real vector normally distributed around the given mean with the given <paramref name="length"/> and in the interval [min,max).
 /// </summary>
 /// <exception cref="ArgumentException">
 /// Thrown when <paramref name="random"/> is null.<br />
 /// Thrown when <paramref name="mean"/> is null or of length 0.<br />
 /// Thrown when <paramref name="sigma"/> is null or of length 0.<br />
 /// </exception>
 /// <remarks>
 /// If no bounds are given the bounds will be set to (double.MinValue;double.MaxValue).
 /// 
 /// If dimensions of the mean do not lie within the given bounds they're set to either to the min or max of the bounds depending on whether the given dimension
 /// for the mean is smaller or larger than the bounds. If min and max for a certain dimension are almost the same the resulting value will be set to min.
 /// 
 /// However, please consider that such static bounds are not really meaningful to optimize.
 /// 
 /// The sigma vector can contain 0 values in which case the dimension will be exactly the same as the given mean.
 /// </remarks>
 /// <param name="random">The random number generator.</param>
 /// <param name="means">The mean vector around which the resulting vector is sampled.</param>
 /// <param name="sigmas">The vector of standard deviations, must have at least one row.</param>
 /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
 /// <param name="maximumTries">The maximum number of tries to sample a value inside the bounds for each dimension. If a valid value cannot be obtained, the mean will be used.</param>
 /// <returns>The newly created real vector.</returns>
 public static RealVector Apply(IntValue lengthValue, IRandom random, RealVector means, DoubleArray sigmas, DoubleMatrix bounds, int maximumTries = 1000) {
   if (lengthValue == null || lengthValue.Value == 0) throw new ArgumentException("Length is not defined or zero");
   if (random == null) throw new ArgumentNullException("Random is not defined", "random");
   if (means == null || means.Length == 0) throw new ArgumentNullException("Mean is not defined", "mean");
   if (sigmas == null || sigmas.Length == 0) throw new ArgumentNullException("Sigma is not defined.", "sigma");
   if (bounds == null || bounds.Rows == 0) bounds = new DoubleMatrix(new[,] { { double.MinValue, double.MaxValue } });
   var length = lengthValue.Value;
   var nd = new NormalDistributedRandom(random, 0, 1);
   var result = new RealVector(length);
   for (int i = 0; i < result.Length; i++) {
     var min = bounds[i % bounds.Rows, 0];
     var max = bounds[i % bounds.Rows, 1];
     var mean = means[i % means.Length];
     var sigma = sigmas[i % sigmas.Length];
     if (min.IsAlmost(max) || mean < min) result[i] = min;
     else if (mean > max) result[i] = max;
     else {
       int count = 0;
       bool inRange;
       do {
         result[i] = mean + sigma * nd.NextDouble();
         inRange = result[i] >= min && result[i] < max;
         count++;
       } while (count < maximumTries && !inRange);
       if (count == maximumTries && !inRange)
         result[i] = mean;
     }
   }
   return result;
 }
コード例 #60
0
        // update vols
        private SabrParametersIborCapletFloorletVolatilities updateParameters(SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition, SabrParametersIborCapletFloorletVolatilities volatilities, DoubleArray newValues)
        {
            SabrParameters sabrParams    = volatilities.Parameters;
            CurveMetadata  alphaMetadata = sabrParams.AlphaCurve.Metadata;
            CurveMetadata  betaMetadata  = sabrParams.BetaCurve.Metadata;
            CurveMetadata  rhoMetadata   = sabrParams.RhoCurve.Metadata;
            CurveMetadata  nuMetadata    = sabrParams.NuCurve.Metadata;
            IList <Curve>  newCurveList  = sabrDefinition.createSabrParameterCurve(ImmutableList.of(alphaMetadata, betaMetadata, rhoMetadata, nuMetadata), newValues);
            SabrParameters newSabrParams = SabrParameters.of(newCurveList[0], newCurveList[1], newCurveList[2], newCurveList[3], sabrDefinition.ShiftCurve, sabrDefinition.SabrVolatilityFormula);
            SabrParametersIborCapletFloorletVolatilities newVols = SabrParametersIborCapletFloorletVolatilities.of(volatilities.Name, volatilities.Index, volatilities.ValuationDateTime, newSabrParams);

            return(newVols);
        }