//RegressionResult
        double runCalculation(SimplexConstant[] consts)
        {
            ObjectiveFunctionDelegate objFunc = new ObjectiveFunctionDelegate(minimizeAngle);
            RegressionResult          result  = NelderMeadSimplex.Regress(consts, tolerance, maxEvals, objFunc);

            return(result.Constants[0]);
        }
Beispiel #2
0
 /// <summary>
 /// Test to see if we can fit a parabola
 /// </summary>
 public static void SimplexTest1()
 {
     Console.WriteLine("Starting SimplexTest1");
     SimplexConstant[] constants = new SimplexConstant[] { new SimplexConstant(3, 1), new SimplexConstant(5, 1) };
     double tolerance = 1e-6;
     int maxEvals = 1000;
     ObjectiveFunctionDelegate objFunction = new ObjectiveFunctionDelegate(_objFunction1);
     RegressionResult result = NelderMeadSimplex.Regress(constants, tolerance, maxEvals, objFunction);
     _printResult(result);
 }
Beispiel #3
0
        /// <summary>
        /// Test on the Rosenbrock function
        /// </summary>
        public static void SimplexTest2()
        {
            Console.WriteLine("\n\nStarting SimplexTest2");

            // we are regressing for frequency, amplitude, and phase offset
            SimplexConstant[] constants = new SimplexConstant[] { new SimplexConstant(-1.2, .1), new SimplexConstant(1, .1)};
            double tolerance = 1e-10;
            int maxEvals = 1000;
            ObjectiveFunctionDelegate objFunction = new ObjectiveFunctionDelegate(_objFunction2);
            RegressionResult result = NelderMeadSimplex.Regress(constants, tolerance, maxEvals, objFunction);
            _printResult(result);
        }
Beispiel #4
0
        /// <summary>
        /// Test to see if we can fit a parabola
        /// </summary>
        private static void _simplexTest1()
        {
            Console.WriteLine("Starting SimplexTest1");
            SimplexConstant[] nss       = new SimplexConstant[] { new SimplexConstant(0, 1), new SimplexConstant(0, 1), new SimplexConstant(0, 1), new SimplexConstant(0, 1), new SimplexConstant(1, 1), new SimplexConstant(1, 1) };
            double[]          tt        = { 5.0, 10.0, 15.0, 20.0, 25.0 };
            double[]          Y         = { 0.001770949, 0.008396027, 0.013860686, 0.019379306, 0.023731833 };
            double            tolerance = 1e-6;
            int maxEvals = 1000;
            ObjectiveFunctionDelegate objFunction = new ObjectiveFunctionDelegate(_objFunction1);
            RegressionResult          result      = NelderMeadSimplex.Regress(nss, tt, Y, tolerance, maxEvals, objFunction);

            _printResult(result);
        }
    // Run cost minimization
    Vector3 IDecisionManager.getNextDesiredPoint()
    {
        // What are the variables to minimize (position)
        SimplexConstant[] constants = new SimplexConstant[] { new SimplexConstant(this.sensorModule.gps.position.x, 1),
                                                              new SimplexConstant(this.sensorModule.gps.position.y, 1),
                                                              new SimplexConstant(this.sensorModule.gps.position.z, 1) };
        double tolerance = 1e-30;
        int    maxEvals  = 10000;

        // What's the objective function
        ObjectiveFunctionDelegate objFunction = new ObjectiveFunctionDelegate(_objFunction1);
        RegressionResult          result      = NelderMeadSimplex.Regress(constants, tolerance, maxEvals, objFunction);
        Vector3 r = new Vector3((float)result.Constants[0], (float)result.Constants[1], (float)result.Constants[2]);

//		Debug.Log (result.TerminationReason.ToString ());
        return(r);
    }
Beispiel #6
0
        public void Minimize()
        {
            SetCoefficients();

            Console.WriteLine("Starting minimization...");
            SimplexConstant[] constants = new SimplexConstant[Coefficients.Length];
            for (int i = 0; i < Coefficients.Length; i++)
            {
                constants[i] = new SimplexConstant(Coefficients[i], Math.Abs(Coefficients[i]) / 2);
            }
            double tolerance = 1e-6;
            int    maxEvals  = 1000;
            ObjectiveFunctionDelegate objFunction = new ObjectiveFunctionDelegate(SpiderObjectiveFunction);
            RegressionResult          result      = NelderMeadSimplex.Regress(constants, tolerance, maxEvals, objFunction);

            Coefficients = result.Constants;
            PrintCoefficients(Coefficients);
        }
        private void optimizeVolumes(Individual individual)
        {
            //Initialization for optimizer
            double p = 0;

            double[] organWeightsInit = null;
            uint     numberOfTry      = 0;

            _objectiveWeight = individual.InputWeight;

            while (p == 0)
            {
                //Random organ weight
                organWeightsInit = organWeightsFrom(createRandomOrgansVolumesFrom(individual, getOrganVolumeForIndividual));

                //skale skin
                organWeightsInit[_skinIndex] = getDefaultSkinWeight(_muSigmas[_skinIndex]);

                //compensate with fat to get our target weight
                updateFatWeight(organWeightsInit);

                p = probabilityOrgans(organWeightsInit);
                numberOfTry++;
                if (numberOfTry > _maxIterations)
                {
                    throw new CannotCreateIndividualWithConstraintsException(_reportGenerator.StringReportFor(individual.OriginData));
                }
            }

            //Start optimization
            var result = NelderMeadSimplex.Regress(simplexConstantFrom(organWeightsNonFatFrom(organWeightsInit)), 1e-6, 10000,
                                                   probabilityOrgansWrapper);

            //Retrieve results and scale fat volume to match objective bodyweight
            var organWeights = organWeightsWithFatFrom(transformedWeights(result.Constants));

            setOrganVolumesTo(individual, organVolumesFrom(organWeights));
        }
Beispiel #8
0
            protected override CalibrationCurve FitPoints(IList <WeightedPoint> weightedPoints)
            {
                double?bestLod   = null;
                double bestScore = double.MaxValue;
                var    xValues   = weightedPoints.Select(pt => pt.X).Distinct().OrderBy(x => x).ToArray();

                for (int i = 0; i < xValues.Length - 1; i++)
                {
                    var simplexConstant = new NelderMeadSimplex.SimplexConstant((xValues[i] + xValues[i + 1]) / 2,
                                                                                (xValues[i + 1] - xValues[i]) / 4);
                    var regressionResult = NelderMeadSimplex.Regress(new[] { simplexConstant }, 0, 50,
                                                                     constants => LodObjectiveFunction(constants[0], weightedPoints));
                    if (regressionResult.ErrorValue < bestScore)
                    {
                        bestLod   = regressionResult.Constants[0];
                        bestScore = regressionResult.ErrorValue;
                    }
                }
                if (!bestLod.HasValue)
                {
                    return(LinearFit(weightedPoints));
                }
                return(GetCalibrationCurveWithLod(bestLod.Value, weightedPoints));
            }
Beispiel #9
0
        private ResultData CalculateHalfLife(ICollection <ProcessedRowData> rowDatas)
        {
            IEnumerable <ProcessedRowData> filteredRowDatas;

            if (EvviesFilter != EvviesFilterEnum.None)
            {
                var applicableRowDatas  = new List <ProcessedRowData>();
                var values              = new Dictionary <double, List <double> >();
                var filteredRowDataList = new List <ProcessedRowData>();
                foreach (var rowData in rowDatas)
                {
                    Debug.Assert(RejectReason.EvviesFilter != rowData.RejectReason);
                    if (null != rowData.RejectReason)
                    {
                        continue;
                    }
                    var value = rowData.Turnover;
                    if (!value.HasValue || double.IsNaN(value.Value) || double.IsInfinity(value.Value))
                    {
                        continue;
                    }
                    var timePoint = GetTimePoint(rowData.RawRowData);
                    if (!timePoint.HasValue)
                    {
                        filteredRowDataList.Add(rowData);
                        continue;
                    }
                    List <double> list;
                    if (!values.TryGetValue(timePoint.Value, out list))
                    {
                        list = new List <double>();
                        values.Add(timePoint.Value, list);
                    }
                    list.Add(value.Value);
                    applicableRowDatas.Add(rowData);
                }
                if (EvviesFilter == EvviesFilterEnum.Oct2011)
                {
                    foreach (var entry in values.ToArray())
                    {
                        var statistics = new Statistics(entry.Value.ToArray());
                        var min        = statistics.Median() - 3 * statistics.StdDev();
                        var max        = statistics.Median() + 3 * statistics.StdDev();
                        if (statistics.Median() + 2 * statistics.StdDev() >= .99)
                        {
                            // Throw away any values of 100% or 99% if they are more than 2 SD above the median.
                            max = Math.Min(.99, max);
                        }
                        var newValues = entry.Value.Where(v => v >= min && v <= max).ToList();
                        if (newValues.Count != entry.Value.Count)
                        {
                            values[entry.Key] = newValues;
                        }
                    }
                }

                var cutoffs = new Dictionary <double, KeyValuePair <double, double> >();
                foreach (var entry in values)
                {
                    var    statistics = new Statistics(entry.Value.ToArray());
                    var    mean       = statistics.Mean();
                    var    stdDev     = statistics.StdDev();
                    double cutoff;
                    if (EvviesFilter == EvviesFilterEnum.TwoStdDev)
                    {
                        cutoff = 2 * stdDev;
                    }
                    else
                    {
                        if (stdDev / mean < .3)
                        {
                            cutoff = 2 * stdDev;
                        }
                        else
                        {
                            cutoff = stdDev;
                        }
                    }
                    cutoffs.Add(entry.Key, new KeyValuePair <double, double>(mean - cutoff, mean + cutoff));
                }
                foreach (var rowData in applicableRowDatas)
                {
                    var cutoff = cutoffs[GetTimePoint(rowData.RawRowData).Value];
                    var value  = rowData.Turnover;
                    rowData.EvviesFilterMin = cutoff.Key;
                    rowData.EvviesFilterMax = cutoff.Value;
                    // Only apply Evvie's Filter to rows that has a time point.
                    if (GetTimePoint(rowData.RawRowData).HasValue)
                    {
                        if (value.Value < cutoff.Key || value.Value > cutoff.Value)
                        {
                            Debug.Assert(null == rowData.RejectReason);
                            rowData.RejectReason = RejectReason.EvviesFilter;
                            continue;
                        }
                    }
                    filteredRowDataList.Add(rowData);
                }
                filteredRowDatas = filteredRowDataList;
            }
            else
            {
                filteredRowDatas = rowDatas.Where(rowData => null == rowData.RejectReason).ToArray();
            }
            if (HalfLifeSettings.SimpleLinearRegression)
            {
                var timePoints = new List <double>();
                var logValues  = new List <double>();
                foreach (var rowData in filteredRowDatas)
                {
                    if (null != rowData.RejectReason)
                    {
                        continue;
                    }
                    double?logValue = Math.Log(1 - rowData.Turnover.Value);
                    if (!logValue.HasValue || double.IsNaN(logValue.Value) || double.IsInfinity(logValue.Value))
                    {
                        rowData.RejectReason = RejectReason.ValueOutOfRange;
                        continue;
                    }
                    double?timePoint = GetTimePoint(rowData.RawRowData);
                    if (!timePoint.HasValue || ExcludedTimePoints.Contains(timePoint.Value))
                    {
                        rowData.RejectReason = RejectReason.NoTimePoint;
                        continue;
                    }
                    logValues.Add(logValue.Value);
                    timePoints.Add(timePoint.Value);
                }
                var    statsTimePoints = new Statistics(timePoints.ToArray());
                var    statsLogValues = new Statistics(logValues.ToArray());
                double rateConstant, stDevRateConstant, rateConstantError, yIntercept;
                double?rSquared = null;
                if (FixedInitialPercent)
                {
                    rateConstant      = statsLogValues.SlopeWithoutIntercept(statsTimePoints);
                    stDevRateConstant = Statistics.StdDevSlopeWithoutIntercept(statsLogValues, statsTimePoints);
                    rateConstantError = stDevRateConstant * GetErrorFactor(timePoints.Count - 1);
                    yIntercept        = 0;
                }
                else
                {
                    rateConstant      = statsLogValues.Slope(statsTimePoints);
                    stDevRateConstant = Statistics.StdDevB(statsLogValues, statsTimePoints);
                    rateConstantError = stDevRateConstant * GetErrorFactor(timePoints.Count - 2);
                    yIntercept        = Statistics.Intercept(statsLogValues, statsTimePoints);
                    rSquared          = Math.Pow(Statistics.R(statsLogValues, statsTimePoints), 2);
                }
                return(new ResultData
                {
                    RateConstant = rateConstant,
                    RateConstantStdDev = stDevRateConstant,
                    RateConstantError = rateConstantError,
                    PointCount = timePoints.Count,
                    YIntercept = yIntercept,
                    RSquared = rSquared,
                    RowDatas = rowDatas.ToArray(),
                    FilteredRowDatas = filteredRowDatas.ToArray(),
                });
            }
            else
            {
                var dataPoints = new List <KeyValuePair <double, double> >();
                foreach (var rowData in filteredRowDatas)
                {
                    double?time = rowData.RawRowData.MsDataFile.TimePoint;
                    double?y;
                    y = 1 - rowData.Turnover;
                    if (!y.HasValue || !time.HasValue)
                    {
                        continue;
                    }
                    dataPoints.Add(new KeyValuePair <double, double>(time.Value, y.Value));
                }
                var timePoints =
                    Workspace.MsDataFiles.Select(msDataFile => msDataFile.TimePoint)
                    .Where(timePoint => timePoint.HasValue).ToList();
                var resultData = new ResultData
                {
                    PointCount       = dataPoints.Count,
                    FilteredRowDatas = filteredRowDatas.ToArray(),
                    RowDatas         = rowDatas.ToArray(),
                };
                if (resultData.RowDatas.Count == 0 || timePoints.Count == 0)
                {
                    resultData.RateConstant = double.NaN;
                    resultData.YIntercept   = double.NaN;
                    return(resultData);
                }
                NelderMeadSimplex.SimplexConstant[] initialParameters;
                double convergenceTolerance = 0;
                int    maxEvaluations       = 1000;
                if (FixedInitialPercent)
                {
                    timePoints.Add(0);
                    double timePointDifference = timePoints.Max().Value - timePoints.Min().Value;
                    initialParameters = new[] { new NelderMeadSimplex.SimplexConstant(1 / timePointDifference, 1.0 / 10 / timePointDifference) };
                    var regressionResult = NelderMeadSimplex.Regress(initialParameters, convergenceTolerance,
                                                                     maxEvaluations,
                                                                     constants =>
                                                                     SumOfResidualsSquared(
                                                                         x => Math.Exp(-constants[0] * x), dataPoints));
                    resultData.RateConstant = -regressionResult.Constants[0];
                }
                else
                {
                    double timePointDifference = timePoints.Max().Value - timePoints.Min().Value;
                    initialParameters = new[]
                    {
                        new NelderMeadSimplex.SimplexConstant(1 / timePointDifference,
                                                              1.0 / 10 / timePointDifference),
                        new NelderMeadSimplex.SimplexConstant(0, .1),
                    };
                    var regressionResult = NelderMeadSimplex.Regress(initialParameters, convergenceTolerance, maxEvaluations,
                                                                     constants => SumOfResidualsSquared(x => Math.Exp(-constants[0] * x + constants[1]), dataPoints));
                    resultData.RateConstant = -regressionResult.Constants[0];
                    resultData.YIntercept   = regressionResult.Constants[1];
                }
                return(resultData);
            }
        }
        protected override OptimizationRunProperties RunOptimization()
        {
            var result = NelderMeadSimplex.Regress(createSimplexConstants(), ConvergenceTolerance, MaxEvaluation, values => _objectiveFunc(ParameterValuesFrom(values)).TotalError);

            return(new OptimizationRunProperties(result.EvaluationCount));
        }