/// <summary>
        /// Creates a transfer function from RGB and alpha cubic splines.
        /// </summary>
        /// <param name="tcp">Transfer control points to use.</param>
        /// <returns>An array of RGBA colors corresponding to each isovalue 0-255.</returns>
        public static Color[] CreateTransferFunction(TransferControlPoints tcp)
        {
            Debug.Assert(tcp.rgbPoints.Count == tcp.rgbIsoValues.Count);
            Debug.Assert(tcp.alphaPoints.Count == tcp.alphaIsoValues.Count);
            Debug.Assert(tcp.rgbIsoValues[0] == 0 && tcp.rgbIsoValues[tcp.rgbIsoValues.Count - 1] == 255,
                "The first and last isovalues must be 0 and 255, respectively.");
            Debug.Assert(tcp.alphaIsoValues[0] == 0 && tcp.alphaIsoValues[tcp.alphaIsoValues.Count - 1] == 255,
                "The first and last isovalues must be 0 and 255, respectively.");

            // Calculate the cubic splines for the RGB and alpha values.
            CubicSpline<Cubic3> rgbSpline = new CubicSpline<Cubic3>();
            CubicSpline<Cubic1> alphaSpline = new CubicSpline<Cubic1>();
            rgbSpline.Calculate(tcp.rgbPoints);
            alphaSpline.Calculate(tcp.alphaPoints);

            // Create the transfer function from the two splines.
            Color[] transferFunc = new Color[256];

            // ...RGB portion.
            int index = 0;
            for (int i = 0; i < rgbSpline.Count; ++i)
            {
                int interval = tcp.rgbIsoValues[i + 1] - tcp.rgbIsoValues[i];
                Debug.Assert(interval > 0, "Isovalues must be incremental by at least 1/increment.");

                // Fill in the color at the isovalues covered by the current spline segment.
                for (int j = 0; j < interval; ++j)
                {
                    float position = j / (float)interval;
                    transferFunc[index++] = rgbSpline.GetPointOnSpline(i, position).ToColor();
                }
            }
            transferFunc[index] = rgbSpline.GetPointOnSpline(rgbSpline.Count - 1, 1f).ToColor();

            // ...alpha portion.
            index = 0;
            for (int i = 0; i < alphaSpline.Count; ++i)
            {
                int interval = tcp.alphaIsoValues[i + 1] - tcp.alphaIsoValues[i];
                Debug.Assert(interval > 0, "Isovalues must be incremental by at least 1/increment.");

                // Fill in the alpha at the isovalues covered by the current spline segment.
                for (int j = 0; j < interval; ++j)
                {
                    float position = j / (float)interval;
                    transferFunc[index++].A = alphaSpline.GetPointOnSpline(i, position).ToByte();
                }
            }
            transferFunc[index].A = alphaSpline.GetPointOnSpline(alphaSpline.Count - 1, 1f).ToByte();

            return transferFunc;
        }
Пример #2
0
        /// <summary>
        /// Maps <see cref="MSHealthAPI.MSHealthActivity"/> instance to <see cref="NikePlusAPI.NikePlusActivity"/> instance.
        /// </summary>
        /// <param name="activityIn"><see cref="MSHealthAPI.MSHealthActivity"/> instance to map.</param>
        /// <returns><see cref="NikePlusAPI.NikePlusActivity"/> instance.</returns>
        public static NikePlusActivity ToNikePlusActicity(this MSHealthActivity activityIn)
        {
            NikePlusActivity loActivityOut = null;
            if (activityIn != null)
            {
                loActivityOut = new NikePlusActivity();
                // Distance
                double ldDistance = 0;
                if (activityIn.SplitDistance != null &&
                    activityIn.DistanceSummary != null &&
                    activityIn.DistanceSummary.TotalDistance != null)
                {
                    ldDistance = activityIn.DistanceSummary.TotalDistance.Value / activityIn.SplitDistance.Value;
                    if (activityIn.SplitDistance.Value == MSHealthActivity.SPLIT_DISTANCE_MILE)
                        ldDistance = ldDistance * 1.609344; //1609.344;
                    if (loActivityOut.MetricSummary == null)
                        loActivityOut.MetricSummary = new NikePlusMetricSummary();
                    loActivityOut.MetricSummary.Distance = ldDistance;
                }
                // Duration
                if (activityIn.Duration != null)
                {
                    loActivityOut.Duration = activityIn.Duration.Value.TotalMilliseconds;
                    if (loActivityOut.MetricSummary == null)
                        loActivityOut.MetricSummary = new NikePlusMetricSummary();
                    loActivityOut.MetricSummary.Duration = activityIn.Duration;
                }
                // Start Time
                if (activityIn.StartTime != null &&
                    activityIn.StartTime.HasValue)
                    loActivityOut.StartTime = activityIn.StartTime.Value;
                // Status
                loActivityOut.Status = NikePlusActivityStatus.COMPLETE;
                // Type
                switch (activityIn.Type)
                {
                    case MSHealthActivityType.Run:
                        loActivityOut.Type = NikePlusActivityType.RUN;
                        break;
                    case MSHealthActivityType.Bike:
                        loActivityOut.Type = NikePlusActivityType.CYCLE;
                        break;
                    case MSHealthActivityType.Sleep:
                        loActivityOut.Type = NikePlusActivityType.SLEEPING;
                        break;
                    default:
                        loActivityOut.Type = NikePlusActivityType.OTHER;
                        break;
                }
                // Calories
                if (activityIn.CaloriesBurnedSummary != null &&
                    activityIn.CaloriesBurnedSummary.TotalCalories != null)
                {
                    if (loActivityOut.MetricSummary == null)
                        loActivityOut.MetricSummary = new NikePlusMetricSummary();
                    loActivityOut.MetricSummary.Calories = activityIn.CaloriesBurnedSummary.TotalCalories;
                }
                // Device
                loActivityOut.DeviceType = NikePlusDeviceType.WATCH; // Nike doesn't recognize MSBand as valid device, so, set as WATCH
                                                                     // Get valid MapPoints (with Location Latitude and Longitude)
                IEnumerable<MSHealthMapPoint> loMapPoints = null;
                if (activityIn.MapPoints != null &&
                    activityIn.MapPoints.Any())
                {
                    loMapPoints = activityIn.MapPoints
                        .Where(loMP => loMP.IsPaused != null &&
                               !loMP.IsPaused.Value &&
                               loMP.SecondsSinceStart != null)
                        .OrderBy(loMP => loMP.Ordinal);
                }
                // Metrics
                List<NikePlusMetric> loMetrics = new List<NikePlusMetric>();
                NikePlusMetric loMetricDistance = new NikePlusMetric() { Type = NikePlusMetricType.DISTANCE };
                NikePlusMetric loMetricHeartRate = new NikePlusMetric() { Type = NikePlusMetricType.HEARTRATE };
                NikePlusMetric loMetricSpeed = new NikePlusMetric { Type = NikePlusMetricType.SPEED };
                NikePlusMetric loMetricCalories = new NikePlusMetric { Type = NikePlusMetricType.CALORIES };
                SortedDictionary<float, float> loDistanceToDurationNodes = new SortedDictionary<float, float>();
                SortedDictionary<float, float> loHeartRateToDurationNodes = new SortedDictionary<float, float>();
                SortedDictionary<float, float> loSpeedToDurationNodes = new SortedDictionary<float, float>();
                SortedDictionary<float, float> loCaloriesToDurationNodes = new SortedDictionary<float, float>();
                SortedDictionary<float, float> loDurationToDistanceNodes = new SortedDictionary<float, float>();
                double ldTotalDistance = 0;
                float lfTotalSeconds = 0;
                if (loMapPoints != null &&
                    loMapPoints.Any())
                {
                    foreach (MSHealthMapPoint loMapPoint in loMapPoints)
                    {
                        // Location
                        if (loMapPoint.Location != null)
                        {
                            // Latitude/Longitude
                            if (loMapPoint.Location.Latitude != null &&
                                loMapPoint.Location.Longitude != null)
                            {
                                if (loActivityOut.GPSData == null)
                                    loActivityOut.GPSData = new NikePlusGPS();
                                if (loActivityOut.GPSData.Waypoints == null)
                                    loActivityOut.GPSData.Waypoints = new List<NikePlusWaypoint>();
                                NikePlusWaypoint loWaypoint = new NikePlusWaypoint()
                                {
                                    Latitude = loMapPoint.Location.Latitude.Value / MSHealthGPSPoint.LATITUDE_FACTOR,
                                    Longitude = loMapPoint.Location.Longitude.Value / MSHealthGPSPoint.LONGITUDE_FACTOR,
                                };
                                // Elevation
                                if (loMapPoint.Location.ElevationFromMeanSeaLevel != null)
                                {
                                    loWaypoint.Elevation = loMapPoint.Location.ElevationFromMeanSeaLevel.Value / MSHealthGPSPoint.ELEVATION_FACTOR;
                                }
                                loActivityOut.GPSData.Waypoints.Add(loWaypoint);
                            }
                        }
                        // Distance
                        if (loMapPoint.TotalDistance != null &&
                            loMapPoint.SecondsSinceStart != null)
                        {
                            ldDistance = loMapPoint.TotalDistance.Value / activityIn.SplitDistance.Value;
                            if (activityIn.SplitDistance.Value == MSHealthActivity.SPLIT_DISTANCE_MILE)
                                ldDistance = ldDistance * 1.609344;
                            if (!loDistanceToDurationNodes.ContainsKey(loMapPoint.SecondsSinceStart.Value))
                                loDistanceToDurationNodes.Add(loMapPoint.SecondsSinceStart.Value, (float)ldDistance);
                            if (!loDurationToDistanceNodes.ContainsKey((float)ldDistance))
                                loDurationToDistanceNodes.Add((float)ldDistance, loMapPoint.SecondsSinceStart.Value);
                            ldTotalDistance = ldDistance;
                            lfTotalSeconds = loMapPoint.SecondsSinceStart.Value;
                        }
                        // Heart rate
                        if (loMapPoint.HeartRate != null)
                        {
                            if (!loHeartRateToDurationNodes.ContainsKey(loMapPoint.SecondsSinceStart.Value))
                                loHeartRateToDurationNodes.Add(loMapPoint.SecondsSinceStart.Value, loMapPoint.HeartRate.Value);
                        }
                        // Speed
                        if (loMapPoint.Speed != null)
                        {
                            // TODO: Determine if conversion is necessary
                            if (!loSpeedToDurationNodes.ContainsKey(loMapPoint.SecondsSinceStart.Value))
                                loSpeedToDurationNodes.Add(loMapPoint.SecondsSinceStart.Value, (float)loMapPoint.Speed.Value);
                        }
                    }
                    MSHealthMapPoint loLastMapPoint = loMapPoints.LastOrDefault();
                    if (loLastMapPoint != null &&
                        loLastMapPoint.SecondsSinceStart != null)
                        lfTotalSeconds = loLastMapPoint.SecondsSinceStart.Value;
                }
                else
                {
                    if (activityIn.MinuteSummaries != null &&
                        activityIn.MinuteSummaries.Any())
                    {
                        lfTotalSeconds = 0;
                        ldTotalDistance = 0;
                        IEnumerable<MSHealthSummary> loSummaries = activityIn.MinuteSummaries.OrderBy(loSumm => loSumm.StartTime);
                        foreach (MSHealthSummary loSummary in loSummaries)
                        {
                            lfTotalSeconds += 60;
                            // Calories
                            if (loSummary.CaloriesBurnedSummary != null &&
                                loSummary.CaloriesBurnedSummary.TotalCalories != null)
                            {
                                if (!loCaloriesToDurationNodes.ContainsKey(lfTotalSeconds))
                                    loCaloriesToDurationNodes.Add(lfTotalSeconds, loSummary.CaloriesBurnedSummary.TotalCalories.Value);
                            }
                            // Heart Rate
                            if (loSummary.HeartRateSummary != null &&
                                loSummary.HeartRateSummary.AverageHeartRate != null)
                            {
                                if (!loHeartRateToDurationNodes.ContainsKey(lfTotalSeconds))
                                    loHeartRateToDurationNodes.Add(lfTotalSeconds, loSummary.HeartRateSummary.AverageHeartRate.Value);
                            }
                            // Distance
                            if (activityIn.SplitDistance != null &&
                                loSummary.DistanceSummary != null &&
                                loSummary.DistanceSummary.TotalDistance != null)
                            {
                                ldDistance = loSummary.DistanceSummary.TotalDistance.Value / activityIn.SplitDistance.Value;
                                if (activityIn.SplitDistance.Value == MSHealthActivity.SPLIT_DISTANCE_MILE)
                                    ldDistance = ldDistance * 1.609344;
                                ldTotalDistance += ldDistance;
                                if (!loDistanceToDurationNodes.ContainsKey(lfTotalSeconds))
                                    loDistanceToDurationNodes.Add(lfTotalSeconds, (float)ldTotalDistance);
                                if (!loDurationToDistanceNodes.ContainsKey((float)ldDistance))
                                    loDurationToDistanceNodes.Add((float)ldDistance, lfTotalSeconds);
                            }
                        }
                    }
                    loActivityOut.IsGPSActivity = false;
                }
                // Interpolate metrics to each 10 seconds.
                List<float> loIntervals = new List<float>();
                for (float lfInterval = 10; lfInterval < lfTotalSeconds; lfInterval += 10)
                    loIntervals.Add(lfInterval);
                CubicSpline loCubicSpline = null;
                float[] loValues = null;
                /*
				 * GPS
				 */
                if (loActivityOut.GPSData != null &&
                    loActivityOut.GPSData.Waypoints != null &&
                    loActivityOut.GPSData.Waypoints.Any())
                {
                    // Configure GPS Data
                    loActivityOut.IsGPSActivity = true;
                    loActivityOut.GPSData.IntervalUnit = NikePlusIntervalUnit.SEC;
                    loActivityOut.GPSData.IntervalMetric = Math.Floor((double)lfTotalSeconds / (double)loActivityOut.GPSData.Waypoints.Count);
                    // Elevation
                    if (activityIn.DistanceSummary != null)
                    {
                        if (activityIn.DistanceSummary.ElevationGain != null)
                            loActivityOut.GPSData.ElevationGain = activityIn.DistanceSummary.ElevationGain / MSHealthDistanceSummary.ELEVATION_FACTOR;
                        if (activityIn.DistanceSummary.ElevationLoss != null)
                            loActivityOut.GPSData.ElevationLoss = activityIn.DistanceSummary.ElevationLoss / MSHealthDistanceSummary.ELEVATION_FACTOR;
                        if (activityIn.DistanceSummary.MaxElevation != null)
                            loActivityOut.GPSData.ElevationMax = activityIn.DistanceSummary.MaxElevation / MSHealthDistanceSummary.ELEVATION_FACTOR;
                        if (activityIn.DistanceSummary.MinElevation != null)
                            loActivityOut.GPSData.ElevationMin = activityIn.DistanceSummary.MinElevation / MSHealthDistanceSummary.ELEVATION_FACTOR;
                    }
                    // GPS can be loaded using GPX format
                    try { loActivityOut.GPX = activityIn.ToGPX(); }
                    catch { /* Do nothing */ }
                }
                /*
				 * Metrics
				 */
                // Distance
                if (loDistanceToDurationNodes.Any())
                {
                    if (!loDistanceToDurationNodes.ContainsKey(0))
                        loDistanceToDurationNodes.Add(0, 0);
                    loCubicSpline = new CubicSpline(loDistanceToDurationNodes.Keys.ToArray(), loDistanceToDurationNodes.Values.ToArray());
                    loValues = loCubicSpline.Eval(loIntervals.ToArray());
                    // Configure Metric Intervals and Values
                    loMetricDistance.Values = (from lfValue in loValues select lfValue < 0 ? "0" : lfValue.ToString()).ToList();
                    loMetricDistance.IntervalUnit = NikePlusIntervalUnit.SEC;
                    loMetricDistance.IntervalMetric = 10;
                    loMetrics.Add(loMetricDistance);
                }
                // Heart Rate
                if (loHeartRateToDurationNodes.Any())
                {
                    if (!loHeartRateToDurationNodes.ContainsKey(0))
                        loHeartRateToDurationNodes.Add(0, 0);
                    loCubicSpline = new CubicSpline(loHeartRateToDurationNodes.Keys.ToArray(), loHeartRateToDurationNodes.Values.ToArray());
                    loValues = loCubicSpline.Eval(loIntervals.ToArray());
                    // Configure Metric Intervals and Values
                    loMetricHeartRate.Values = (from lfValue in loValues select lfValue < 0 ? "0" : ((int)lfValue).ToString()).ToList();
                    loMetricHeartRate.IntervalUnit = NikePlusIntervalUnit.SEC;
                    loMetricHeartRate.IntervalMetric = 10;
                    loMetrics.Add(loMetricHeartRate);
                }
                // Speed
                if (loSpeedToDurationNodes.Any())
                {
                    if (!loSpeedToDurationNodes.ContainsKey(0))
                        loSpeedToDurationNodes.Add(0, 0);
                    loCubicSpline = new CubicSpline(loSpeedToDurationNodes.Keys.ToArray(), loSpeedToDurationNodes.Values.ToArray());
                    loValues = loCubicSpline.Eval(loIntervals.ToArray());
                    // Configure Metric Intervals and Values
                    loMetricSpeed.Values = (from lfValue in loValues select lfValue < 0 ? "0" : lfValue.ToString()).ToList();
                    loMetricSpeed.IntervalUnit = NikePlusIntervalUnit.SEC;
                    loMetricSpeed.IntervalMetric = 10;
                    //loMetrics.Add(loMetricSpeed);
                }
                // Calories
                if (loCaloriesToDurationNodes.Any())
                {
                    if (!loCaloriesToDurationNodes.ContainsKey(0))
                        loCaloriesToDurationNodes.Add(0, 0);
                    loCubicSpline = new CubicSpline(loCaloriesToDurationNodes.Keys.ToArray(), loCaloriesToDurationNodes.Values.ToArray());
                    loValues = loCubicSpline.Eval(loIntervals.ToArray());
                    // Configure Metric Intervals and Values
                    loMetricCalories.Values = (from lfValue in loValues select lfValue < 0 ? "0" : lfValue.ToString()).ToList();
                    loMetricCalories.IntervalUnit = NikePlusIntervalUnit.SEC;
                    loMetricCalories.IntervalMetric = 10;
                    loMetrics.Add(loMetricCalories);
                }
                // Snapshots
                if (loDurationToDistanceNodes != null &&
                    loDurationToDistanceNodes.Any())
                {
                    loActivityOut.SummaryV2 = new NikePlusActivitySummaryV2();
                    loActivityOut.SummaryV2.Snapshots = new List<NikePlusSnapshotV2>();
                    NikePlusSnapshotV2 loSnapshot = null;
                    // Kilometers
                    int liTotalDistance = (int)(ldTotalDistance / 1d);
                    loIntervals = new List<float>();
                    for (float lfInterval = 1; lfInterval <= liTotalDistance; lfInterval++)
                        loIntervals.Add(lfInterval);
                    loCubicSpline = null;
                    loValues = null;
                    if (!loDurationToDistanceNodes.ContainsKey(0))
                        loDurationToDistanceNodes.Add(0, 0);
                    loCubicSpline = new CubicSpline(loDurationToDistanceNodes.Keys.ToArray(), loDurationToDistanceNodes.Values.ToArray());
                    loValues = loCubicSpline.Eval(loIntervals.ToArray());
                    loSnapshot = new NikePlusSnapshotV2();
                    loSnapshot.Name = "kmSplit";
                    loSnapshot.DataSeries = new List<NikePlusDataSerieV2>();
                    for (int liValue = 0; liValue < loValues.Length; liValue++)
                    {
                        NikePlusDataSerieV2 loDataSerie = new NikePlusDataSerieV2();
                        loDataSerie.Metrics = new NikePlusMetricV2()
                        {
                            Distance = (liValue + 1),
                            Duration = loValues[liValue] * 1000, // Seconds to Milliseconds
                        };
                        loDataSerie.ObjectType = "dataPoint";
                        loSnapshot.DataSeries.Add(loDataSerie);
                    }
                    loActivityOut.SummaryV2.Snapshots.Add(loSnapshot);
                    // Miles (1.609344)
                    liTotalDistance = (int)(ldTotalDistance / 1.609344d);
                    loIntervals = new List<float>();
                    for (float lfInterval = 1; lfInterval <= liTotalDistance; lfInterval++)
                        loIntervals.Add(lfInterval * 1.609344f);
                    loCubicSpline = null;
                    loValues = null;
                    if (!loDurationToDistanceNodes.ContainsKey(0))
                        loDurationToDistanceNodes.Add(0, 0);
                    loCubicSpline = new CubicSpline(loDurationToDistanceNodes.Keys.ToArray(), loDurationToDistanceNodes.Values.ToArray());
                    loValues = loCubicSpline.Eval(loIntervals.ToArray());
                    loSnapshot = new NikePlusSnapshotV2();
                    loSnapshot.Name = "mileSplit";
                    loSnapshot.DataSeries = new List<NikePlusDataSerieV2>();
                    for (int liValue = 0; liValue < loValues.Length; liValue++)
                    {
                        NikePlusDataSerieV2 loDataSerie = new NikePlusDataSerieV2();
                        loDataSerie.Metrics = new NikePlusMetricV2()
                        {
                            Distance = (liValue + 1),
                            Duration = loValues[liValue] * 1000, // Seconds to Milliseconds
                        };
                        loDataSerie.ObjectType = "dataPoint";
                        loSnapshot.DataSeries.Add(loDataSerie);
                    }
                    loActivityOut.SummaryV2.Snapshots.Add(loSnapshot);
                }
                // Set metrics
                if (loMetrics != null &&
                    loMetrics.Any())
                    loActivityOut.Metrics = loMetrics;
                /*
				Newtonsoft.Json.JsonSerializerSettings loSerializerSettings = null;
				loSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
				loSerializerSettings.Converters.Add(new NikePlusActivityPostConverterV2());
				string lsActivityOutJson = Newtonsoft.Json.JsonConvert.SerializeObject(loActivityOut, loSerializerSettings);
				System.Diagnostics.Debug.WriteLine(lsActivityOutJson);
				//loActivityOut = null;//*/
            }
            return loActivityOut;
        }
Пример #3
0
    public void CreateBoxCast(Vector3 from, Vector3 to, float midPointHeight, float heightTh, float curveTh, bool catmull)
    {
        if (from != to)
        {
            var relativePosition = to - from;
            var distanceHalf     = relativePosition.magnitude / 2;

            rotation = Quaternion.LookRotation(relativePosition, Vector3.up);
            matrix   = Matrix4x4.TRS(from, rotation, Vector3.one);
            center   = matrix.MultiplyPoint3x4(new Vector3(0, 1f, distanceHalf));
            half     = new Vector3(0.1f, 0.1f, distanceHalf);
            localUp  = rotation * Vector3.up;
            LayerMask mask = LayerMask.GetMask("Default");
            hit = Physics.BoxCastAll(center, half, -localUp, rotation, 2f, mask);

            //TODO: to optimize eventually
            for (int i = 0; i < hit.Length; i++)
            {
                hit[i].point = matrix.inverse.MultiplyPoint3x4(hit[i].point);
            }

            hit = hit.OrderByDescending(h => h.point.y).ToArray();

            for (int i = 0; i < hit.Length; i++)
            {
                hit[i].point = matrix.MultiplyPoint3x4(hit[i].point);
            }

            midPoint = (to + from) / 2;
            //TODO: remember this number 0.05
            midPoint = midPoint + rotation * Vector3.up * midPointHeight;
            midPoint = matrix.inverse.MultiplyPoint3x4(midPoint);

            localTargetPosition = matrix.inverse.MultiplyPoint3x4(to);

            if (!catmull)
            {
                if (hit[0].point != Vector3.zero)
                {
                    var highPoint = matrix.inverse.MultiplyPoint3x4(hit[0].point);
                    if (Math.Abs(highPoint.z - localTargetPosition.z) > curveTh)
                    {
                        if (highPoint.y > midPoint.y)
                        {
                            highestHitPoint = highPoint;
                            midPointHit     = true;
                        }
                        else
                        {
                            highestHitPoint = midPoint;
                            midPointHit     = false;
                        }
                    }
                }

                _inputX[0] = 0;
                _inputX[1] = highestHitPoint.z;
                _inputX[2] = localTargetPosition.z;


                _inputY[0] = 0;
                _inputY[1] = highestHitPoint.y + heightTh;
                _inputY[2] = localTargetPosition.y;

                curve = CreateCurve(_inputX, _inputY);
            }
            else
            {
                if (hit[0].point != Vector3.zero)
                {
                    var highPoint = matrix.inverse.MultiplyPoint3x4(hit[0].point);

                    if (highPoint.y > midPoint.y)
                    {
                        highestHitPoint = highPoint;
                        midPointHit     = true;
                    }
                    else
                    {
                        highestHitPoint = midPoint;
                        midPointHit     = false;
                    }

                    if (hit.Length > 1)
                    {
                        var secondPoint = matrix.inverse.MultiplyPoint3x4(hit[1].point);

                        if (secondPoint.y > midPoint.y)
                        {
                            secondHighestHitPoint = secondPoint;
                        }
                        else
                        {
                            secondHighestHitPoint = midPoint;
                        }
                    }
                }

                threeHits[0]     = Vector3.zero;
                threeHits[1]     = highestHitPoint + new Vector3(0, heightTh, 0);
                threeHits[2]     = localTargetPosition;
                catmullRomSpline = new CatmullRom(threeHits);

                // if (highestHitPoint == secondHighestHitPoint)
                // {
                //     threeHits[0] = Vector3.zero;
                //     threeHits[1] = highestHitPoint + new Vector3(0, heightTh, 0);
                //     threeHits[2] = localTargetPosition;
                //     catmullRomSpline = new CatmullRom(threeHits);
                // }
                // else
                // {
                //     fourHits[0] = Vector3.zero;
                //     fourHits[1] = highestHitPoint + new Vector3(0, heightTh, 0);;
                //     fourHits[2] = secondHighestHitPoint + new Vector3(0, heightTh, 0);;
                //     fourHits[3] = localTargetPosition;
                //     catmullRomSpline = new CatmullRom(fourHits);
                // }
            }
        }
    }
        private IInterpolation toInterpolation(IndexRange range)
        {
            double[] x    = new double[range.Length];
            double[] y    = new double[x.Length];
            Index    next = range.Min.Copy();

            switch (range.Direction)
            {
            case Direction.Horizontal:
                for (int i = 0; i < x.Length; i++)
                {
                    Cell cell = this._cellularFloor.FindCell(next);
                    x[i]    = cell.U;
                    y[i]    = this.Potentials[cell];
                    next.I += 1;
                }
                break;

            case Direction.Vertical:
                for (int i = 0; i < x.Length; i++)
                {
                    Cell cell = this._cellularFloor.FindCell(next);
                    x[i]    = cell.V;
                    y[i]    = this.Potentials[cell];
                    next.J += 1;
                }
                break;

            default:
                break;
            }
            IInterpolation interpolator = null;

            switch (Activity.InterpolationMethod)
            {
            case SpatialAnalysis.FieldUtility.InterpolationMethod.CubicSpline:
                if (x.Length > 1)
                {
                    interpolator = CubicSpline.InterpolateBoundariesSorted(x, y,
                                                                           SplineBoundaryCondition.Natural, 0,
                                                                           SplineBoundaryCondition.Natural, 0);
                }
                else
                {
                    interpolator = LinearSpline.InterpolateSorted(x, y);
                }
                break;

            //case FieldUtility.InterpolationMethod.Barycentric:
            //    interpolator = Barycentric.InterpolatePolynomialEquidistantSorted(x, y);
            //    break;
            case SpatialAnalysis.FieldUtility.InterpolationMethod.Linear:
                interpolator = LinearSpline.InterpolateSorted(x, y);
                break;

            default:
                break;
            }
            x    = null;
            y    = null;
            next = null;
            return(interpolator);
        }
Пример #5
0
        private static float[,] CalcFitMatrix(List <List <float> > measuredValues, float compareValue, List <float> rowMeasurementPoints, List <float> columnMeasurementPoints, int fitDataMatrixWidth, int fitDataMatrixHeight, string fileName)
        {
            var         currentRowIndex = 0;
            CubicSpline fitDataCurve    = new CubicSpline();

            var   fitDataMatrix = new float[fitDataMatrixWidth, fitDataMatrixHeight];
            float stepSize      = (rowMeasurementPoints[rowMeasurementPoints.Count - 1] - rowMeasurementPoints[0]) / (fitDataMatrixWidth - 1);

            float[] columnIndexes = new float[fitDataMatrixWidth];
            for (int i = 0; i < fitDataMatrixWidth; i++)
            {
                columnIndexes[i] = rowMeasurementPoints[0] + i * stepSize;
            }

            var rowIndexes = new float[fitDataMatrixHeight];

            for (var rowIndex = 0; rowIndex < fitDataMatrixHeight; rowIndex++)
            {
                rowIndexes[rowIndex] = rowIndex;
            }

            foreach (var rowMeasuredSize in measuredValues)
            {
                fitDataCurve = new CubicSpline();
                float[] rowFitData = fitDataCurve.FitAndEval(rowMeasurementPoints.ToArray(), rowMeasuredSize.ToArray(), columnIndexes);
                var     rowNumber  = (int)columnMeasurementPoints[currentRowIndex];

                var yIndex = 0;
                foreach (var rowFitDataValue in rowFitData)
                {
                    fitDataMatrix[yIndex, rowNumber] = rowFitDataValue;
                    yIndex++;
                }

                //        string path = @"spline-wikipedia.png";
                //      PlotSplineSolution("test", rowMeasurementPoints.ToArray(), rowMeasuredSize.ToArray(), columnIndexes, rowFitData, path);
                currentRowIndex++;
            }

            //process all column pixels
            var columnMeasureSizesAsFloat = new List <float>();

            foreach (var yAxisMeasurePoint in columnMeasurementPoints)
            {
                columnMeasureSizesAsFloat.Add(yAxisMeasurePoint);
            }

            for (var columnIndex = 0; columnIndex < fitDataMatrixWidth; columnIndex++)
            {
                fitDataCurve = new CubicSpline();

                var columnFitData = new List <float>();

                for (var columnFitDataIndex = 0; columnFitDataIndex < columnMeasurementPoints.Count; columnFitDataIndex++)
                {
                    columnFitData.Add(fitDataMatrix[columnIndex, (int)columnMeasurementPoints[columnFitDataIndex]]);
                }

                float[] columnValues = fitDataCurve.FitAndEval(columnMeasureSizesAsFloat.ToArray(), columnFitData.ToArray(), rowIndexes);

                var measureMatrixRowIndex = 0;
                foreach (var columnValue in columnValues)
                {
                    fitDataMatrix[columnIndex, measureMatrixRowIndex] = columnValue;

                    measureMatrixRowIndex++;
                }
            }

            if (fileName != null)
            {
                //export matrix to csv
                var stringBuilder = new StringBuilder();
                for (var rowIndex = 0; rowIndex < fitDataMatrixHeight; rowIndex++)
                {
                    for (var columnIndex = 0; columnIndex < fitDataMatrixWidth; columnIndex++)
                    {
                        stringBuilder.Append(fitDataMatrix[columnIndex, rowIndex] + ";");
                    }
                }

                DebugManager.SaveStringToTextFile(stringBuilder, fileName + ".txt");

                using (var heatmap = new Bitmap(fitDataMatrixWidth, fitDataMatrixHeight))
                {
                    var g = Graphics.FromImage(heatmap);

                    var lowestOffsetX  = compareValue;
                    var highestOffsetX = compareValue;
                    for (var columnIndex = 0; columnIndex < fitDataMatrixWidth; columnIndex++)
                    {
                        for (var rowIndex = 0; rowIndex < fitDataMatrixHeight; rowIndex++)
                        {
                            if (fitDataMatrix[columnIndex, rowIndex] < lowestOffsetX)
                            {
                                lowestOffsetX = fitDataMatrix[columnIndex, rowIndex];
                            }
                            if (fitDataMatrix[columnIndex, rowIndex] > highestOffsetX)
                            {
                                highestOffsetX = fitDataMatrix[columnIndex, rowIndex];
                            }
                        }
                    }

                    var totalLowestOffset  = compareValue - lowestOffsetX;
                    var totalHighestOffset = highestOffsetX - compareValue;

                    for (var columnIndex = 0; columnIndex < fitDataMatrixWidth; columnIndex++)
                    {
                        for (var rowIndex = 0; rowIndex < fitDataMatrixHeight; rowIndex++)
                        {
                            if (fitDataMatrix[columnIndex, rowIndex] > compareValue)
                            {
                                var xPercentageOffset = (fitDataMatrix[columnIndex, rowIndex] - compareValue) / totalHighestOffset;
                                var bluep             = ((int)(xPercentageOffset * (255)));
                                var greenp            = 255 - (int)(xPercentageOffset * (255));
                                g.DrawLine(new Pen(Color.FromArgb(255, 0, greenp, bluep)), columnIndex, rowIndex, columnIndex + 1, rowIndex);
                            }
                            else if (fitDataMatrix[columnIndex, rowIndex] < compareValue)
                            {
                                var xPercentageOffset = (compareValue - fitDataMatrix[columnIndex, rowIndex]) / totalLowestOffset;
                                var redp   = ((int)(xPercentageOffset * (255)));
                                var greenp = 255 - (int)(xPercentageOffset * (255));
                                g.DrawLine(new Pen(Color.FromArgb(255, redp, greenp, 0)), columnIndex, rowIndex, columnIndex + 1, rowIndex);
                            }
                            else if (fitDataMatrix[columnIndex, rowIndex] == 1)
                            {
                                g.DrawLine(new Pen(Color.Green), columnIndex, rowIndex, columnIndex + 1, rowIndex);
                            }
                        }
                    }

                    if (fileName != null)
                    {
                        DebugManager.SaveImage(heatmap, fileName + ".png");
                    }
                }
            }

            return(fitDataMatrix);
        }
        public override void ExecuteExample()
        {
            MathDisplay.WriteLine("<b>Linear interpolation between points</b>");

            // 1. Generate 20 samples of the function x*x-2*x on interval [0, 10]
            MathDisplay.WriteLine(@"1. Generate 20 samples of the function x*x-2*x on interval [0, 10]");
            double[] points = Generate.LinearSpaced(20, 0, 10);
            var      values = Generate.Map <double, double>(points, TargetFunction1);

            MathDisplay.WriteLine();

            // 2. Create a linear spline interpolation based on arbitrary points
            var method = Interpolate.Linear(points, values);

            MathDisplay.WriteLine(@"2. Create a linear spline interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation support integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Differentiate at point 5.2
            MathDisplay.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
            MathDisplay.WriteLine();

            // 6. Integrate at point 5.2
            MathDisplay.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
            MathDisplay.WriteLine();

            // 7. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"7. Interpolate ten random points and compare to function results");
            var rng = new MersenneTwister(1);

            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 10]
                var point = rng.NextDouble() * 10;
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunction1(point).ToString("N05"));
            }

            MathDisplay.WriteLine();


            // <seealso cref="http://en.wikipedia.org/wiki/Spline_interpolation">Spline interpolation</seealso>
            MathDisplay.WriteLine("<b>Akima spline interpolation</b>");

            // 1. Generate 10 samples of the function x*x-2*x on interval [0, 10]
            MathDisplay.WriteLine(@"1. Generate 10 samples of the function x*x-2*x on interval [0, 10]");
            points = Generate.LinearSpaced(10, 0, 10);
            values = Generate.Map <double, double>(points, TargetFunction1);
            MathDisplay.WriteLine();

            // 2. Create akima spline interpolation
            method = CubicSpline.InterpolateAkima(points, values);
            MathDisplay.WriteLine(@"2. Create akima spline interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation supports integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", ((IInterpolation)method).SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", ((IInterpolation)method).SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Differentiate at point 5.2
            MathDisplay.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
            MathDisplay.WriteLine();

            // 6. Integrate at point 5.2
            MathDisplay.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
            MathDisplay.WriteLine();

            // 7. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"7. Interpolate ten random points and compare to function results");
            rng = new MersenneTwister(1);
            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 10]
                var point = rng.NextDouble() * 10;
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunction1(point).ToString("N05"));
            }

            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Barycentric rational interpolation without poles</b>");

            // 1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]
            MathDisplay.WriteLine(@"1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]");
            points = Generate.LinearSpaced(10, -5, 5);
            values = Generate.Map <double, double>(points, TargetFunctionWithoutPolesEx);
            MathDisplay.WriteLine();

            // 2. Create a floater hormann rational pole-free interpolation based on arbitrary points
            // This method is used by default when create an interpolation using Interpolate.Common method
            method = Interpolate.RationalWithoutPoles(points, values);
            MathDisplay.WriteLine(@"2. Create a floater hormann rational pole-free interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation support integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"5. Interpolate ten random points and compare to function results");
            rng = new MersenneTwister(1);
            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 5]
                var point = rng.NextDouble() * 5;
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunctionWithoutPolesEx(point).ToString("N05"));
            }

            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Rational interpolation with poles</b>");

            // 1. Generate 20 samples of the function f(x) = x on interval [-5, 5]
            MathDisplay.WriteLine(@"1. Generate 20 samples of the function f(x) = x on interval [-5, 5]");
            points = Generate.LinearSpaced(20, -5, 5);
            values = Generate.Map <double, double>(points, TargetFunctionWithPolesEx);
            MathDisplay.WriteLine();

            // 2. Create a burlish stoer rational interpolation based on arbitrary points
            method = Interpolate.RationalWithPoles(points, values);
            MathDisplay.WriteLine(@"2. Create a burlish stoer rational interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation support integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"5. Interpolate ten random points and compare to function results");
            rng = new MersenneTwister(1);
            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 5]
                var point = rng.Next(0, 5);
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunctionWithPolesEx(point).ToString("N05"));
            }

            MathDisplay.WriteLine();
        }
Пример #7
0
    private static IReadOnlyCollection <DataPoint> GeneratePointsFromBitmap(Stream stream)
    {
        const double fmax       = 19000.0;
        const double fmin       = 20.0;
        const double dbrange    = 16.0;
        const double dbmax      = 1.0;
        const double sampleRate = 48000.0;
        const int    sampleSize = 16384;

        // Create a Bitmap object from an image file.
        using var iBitmap = new Bitmap(stream);
        //using var oBitmap = new Bitmap(iBitmap.Width, iBitmap.Height);

        var first = 0;
        //var last = 0;
        double min = iBitmap.Height;
        double max = 0;

        // Get the color of a pixel within myBitmap.
        var points = new Collection <KeyValuePair <int, double> >();

        for (var x = 0; x < iBitmap.Width; x++)
        {
            var list = new List <int>();
            for (var y = 0; y < iBitmap.Height; y++)
            {
                var pixelColor = iBitmap.GetPixel(x, y);
                if ((pixelColor.R > 200) && (pixelColor.G < 25) && (pixelColor.B < 25))
                {
                    if (first == 0)
                    {
                        first = x;
                    }
                    //else last = x;
                    //oBitmap.SetPixel(x, y, Color.FromArgb(255, 0, 0));
                    list.Add(y);
                }
            }
            if (list.Count > 0)
            {
                var a = iBitmap.Height - list.Average();
                points.Add(new KeyValuePair <int, double>(x, a));
                if (a < min)
                {
                    min = a;
                }

                if (a > max)
                {
                    max = a;
                }
            }
        }

        //var size = last - first + 1;
        var mag = max - min + 1;

        //calculate gain & offset
        var scale = dbrange / mag;
        var shift = dbmax - max * scale;

        //check
        //var n_min = min * scale + shift;
        //var n_max = max * scale + shift;

        //convert bitmap to frequency spectrum
        var ex = new List <double>();
        var ey = new List <double>();

        for (var x = 0; x < points.Count; x++)
        {
            var df = Math.Log10(fmax / fmin);                      //over aproximately 3 decades
            var f  = 20.0 * Math.Pow(10.0, df * x / points.Count); //convert log horizontal image pixels to linear frequency scale in Hz
            var y  = points[x].Value * scale + shift;              //scale and shift vertical image pixels to correct magnitude in dB

            ex.Add(f);
            ey.Add(Math.Pow(10.0, y / 20.0));
        }

        //interpolate frequency spectrum to match Audyssey responseData length
        var frequency       = Enumerable.Range(0, sampleSize).Select(p => p * sampleRate / sampleSize).ToArray();
        var spline          = CubicSpline.InterpolateAkima(ex, ey);
        var frequencyPoints = new List <DataPoint>();

        foreach (var f in frequency)
        {
            if (f < fmin)
            {   // exptrapolate
                frequencyPoints.Add(new DataPoint(f, double.NegativeInfinity));
            }
            else
            {
                frequencyPoints.Add(f > fmax
                    ? new DataPoint(f, double.NegativeInfinity)
                    : new DataPoint(f, 20 * Math.Log10(spline.Interpolate(f))));
            }
        }

        //oBitmap.Save(Path.ChangeExtension(path, "jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

        return(frequencyPoints);
    }
Пример #8
0
    public void CrearPista(Vector3 a)
    {
        var r = new System.Random();
        int m = 500;

        Punto[] puntos = new Punto[m];
        Punto   Centro = new Punto(a.x, a.z);


        for (int i = 0; i < m; i++)
        {
            //COORDENADAS POLARES argumentos en radianes
            puntos[i]    = new Punto(125 * UnityEngine.Random.value, UnityEngine.Random.value * 2 * Mathf.PI, 1);
            puntos[i].x += Centro.x;
            puntos[i].y += Centro.y;
        }
        List <Punto> l = new List <Punto>();

        for (int i = 0; i < puntos.Length; i++)
        {
            l.Add(puntos[i]);
        }
        l.Add(puntos[0]);
        puntos = l.ToArray();
        ConvexHull   ch = new ConvexHull();
        List <float> ll = new List <float>();

        for (int i = 0; i < puntos.Length; i++)
        {
            ll.Add(puntos[i].x);
            ll.Add(puntos[i].y);
        }
        FloatArray fa       = new FloatArray(ll.ToArray());
        FloatArray contorno = ch.computePolygon(fa, false);


        float[] xx;
        float[] yy;
        float[] xs, ys;

        desglosarFloatArrayEnVectoresNormales(contorno, out xx, out yy);
        Punto[] convexo = Punto.CrearArregloDesdeArreglos(xx, yy);



        ////////////////////////////////////// AGREGAR DIFICULTAD
        float ancho = UnityEngine.Random.Range(5f, 9f);

        Punto[] convexo2 = new Punto[convexo.Length * 2];

        deformar(ref convexo);

        separarPuntos(ref convexo);

        xx = Punto.getAbscisas(convexo);

        yy = Punto.getOrdenadas(convexo);

        CubicSpline.FitParametric(xx, yy, n, out xs, out ys, 1, -1, 1, -1);

        /////////////////////////////////////////////////////////////////////////

        /*
         * en xs y en ys estan las posiciones x,y de cada punto de la pista
         */



        LS.Add(Instantiate(this.suelo, new Vector3(0, -1, 0), Quaternion.Euler(Vector3.zero), this.transform));
        float[] angulosEnGrados = new float[n];

        for (int i = 0; i < xs.Length - 1; i++)
        {
            angulosEnGrados[i] = 180 * Mathf.Atan2(ys[i + 1] - ys[i], -xs[i + 1] + xs[i]) / Mathf.PI;
        }

        IList <Punto> listaRoja       = new List <Punto>();
        IList <Punto> listaCheckpoint = new List <Punto>();

        Punto[]    puntosInteriores;
        int        offset = r.Next();
        Vector3    pos, pos2 = new Vector3();
        Quaternion rot;

        for (int i = 0; i < xs.Length - 1; i++)
        {
            pos = new Vector3(xs[i], 0, ys[i]);
            rot = Quaternion.Euler(0, angulosEnGrados[i], 0);
            pared.transform.position = pos;
            pared.transform.rotation = rot;

            LPA.Add(Instantiate(pared, pos, rot, this.transform));
            if (i % 10 == 0)
            {
                pared.transform.Translate(ancho / 2 * -Vector3.back, Space.Self);
                pos2 = pared.transform.position;
                pared.transform.Translate(ancho / 2 * -Vector3.back, Space.Self);
                listaRoja.Add(new Punto(pared.transform.position));
            }
            else
            {
                pared.transform.Translate((ancho + Mathf.Sin(i / 10)) * -Vector3.back, Space.Self);
                listaRoja.Add(new Punto(pared.transform.position));
            }

            if (i % 5 == 0)
            {
                pared.transform.Translate(ancho / 2 * Vector3.back, Space.Self);
                checkpoint.transform.rotation   = Quaternion.Euler(0, angulosEnGrados[i], 0);
                checkpoint.transform.position   = pared.transform.position;
                checkpoint.transform.localScale = new Vector3(0.1f, checkpoint.transform.localScale.y, ancho);
                LCH.Add(Instantiate(checkpoint, pared.transform.position, Quaternion.Euler(0, angulosEnGrados[i], 0), this.transform));
            }
            if (UnityEngine.Random.value > 0.97f)
            {
                obstaculo.transform.position = pos;
                obstaculo.transform.rotation = rot;
                obstaculo.transform.Translate(UnityEngine.Random.Range(1, ancho - 1) * Vector3.forward, Space.Self);
                LO.Add(Instantiate(obstaculo, this.transform));
            }
            posIni[i / 10]       = pos2;
            EvolutionManager.ini = posIni[i / 10];
        }


        puntosInteriores = listaRoja.ToArray();
        puntosInteriores[puntosInteriores.Length - 1] = puntosInteriores[0];
        arreglarAngulos(ref puntosInteriores);

        Punto[] PC = listaCheckpoint.ToArray();
        float[] xx2;
        float[] yy2;
        float[] xs2, ys2;
        float[] angulosEnGrados2 = new float[n2];
        float[] angulosEnGrados3 = new float[n / 10];
        xx2 = Punto.getAbscisas(puntosInteriores);
        yy2 = Punto.getOrdenadas(puntosInteriores);
        CubicSpline.FitParametric(xx2, yy2, n2, out xs2, out ys2, 1, -1, 1, -1);

        for (int i = 0; i < xs2.Length - 1; i++)
        {
            angulosEnGrados2[i] = 180 * Mathf.Atan2(ys2[i + 1] - ys2[i], -xs2[i + 1] + xs2[i]) / Mathf.PI;
        }

        for (int i = 0; i < xs2.Length - 1; i++)
        {
            paredRoja.transform.rotation = Quaternion.Euler(0, angulosEnGrados2[i], 0);
            paredRoja.transform.position = new Vector3(xs2[i], 0, ys2[i]);
            LPR.Add(Instantiate(paredRoja, new Vector3(xs2[i], 0, ys2[i]), Quaternion.Euler(0, angulosEnGrados2[i], 0), this.transform));
        }
        //Cuando lee esta variable, los autos van a estar creados para una pista vieja

        ////////////////////////////////////7
    }
        internal void CalculatePath(CCPoint startPosition, float startSlopeDx, float startSlopeDy, CCPoint endPosition, float endSlopeDx = float.NaN, float endSlopeDy = float.NaN)
        {
            //List<CCPoint> pathPoints = new List<CCPoint>();
            // fixes for numerical problems
            if (startSlopeDx < 0.0001 && 0 < startSlopeDx)
            {
                startSlopeDx = 0.001f;
            }
            if (startSlopeDx > -0.0001 && 0 > startSlopeDx)
            {
                startSlopeDx = -0.001f;
            }
            if (startSlopeDy < 0.0001 && 0 < startSlopeDy)
            {
                startSlopeDy = 0.001f;
            }
            if (startSlopeDy > -0.0001 && 0 > startSlopeDy)
            {
                startSlopeDy = -0.001f;
            }
            if (startSlopeDx == 0)
            {
                startSlopeDx = 0.001f;
            }
            if (startSlopeDy == 0)
            {
                startSlopeDy = 0.001f;
            }

            /*
             * // ALTERNATIVE METHOD:
             * // create a path that is a circular arc
             * // for this 1. find the rotational center
             * // 2. rotate the start point towards the end point around the rotational center, step by step, and add these points to the path
             *
             * // SPECIAL CASE: the path is a straight line
             * CCPoint normalizedVectorStartEnd = CCPoint.Normalize(endPosition - startPosition);
             * const float DELTA = 0.01f;
             * if (CCPoint.Distance(normalizedVectorStartEnd, new CCPoint(startSlopeDx, startSlopeDy)) < DELTA)
             * {
             *  pathPoints.Add(startPosition);
             *  pathPoints.Add(endPosition);
             * }
             *  // 1.1 solve yStart = -1/(dy/dx) * xStart + n  for n (line through start perpendicular to the start direction)
             *  // 1.2 get the midpoint between start and end
             *  // 1.3 solve yMid = -1/((endY-startY)/(endX-startX)) * xMid + n2  for n2 (line through midpoint perpendicular to the line from start to end)
             *  // 1.4 solve -1/(dy/dx) * x + n = -1/((endY-startY)/(endX-startX)) * x + n2  for x (intersection of the previous two lines, aka "the rotational center")
             *
             *  // 1.1
             *  // yStart = - dx/dy * xStart + n
             *  // yStart + dx/dy * xStart = n
             *  float n = startPosition.Y + (startSlopeDx / startSlopeDy) * startPosition.X;
             *  // 1.2
             *  CCPoint midPoint = (endPosition + startPosition) / 2;
             *  // 1.3
             *  // yMid + ((endX-startX)/(endY-startY)) * xMid = n2
             *  float n2 = midPoint.Y + ((endPosition.X - startPosition.X) / (endPosition.Y - startPosition.Y)) * midPoint.X;
             *  // 1.4
             *  // - dx/dy * x + n = - ((endX-startX)/(endY-startY)) * x + n2
             *  // - dx/dy * x + ((endX-startX)/(endY-startY)) * x = n2 - n
             *  // x = (n2 - n) / ((dx/dy) - ((endX-startX)/(endY-startY)))
             *  float xRotCenter = (n2 - n) / (((endPosition.X - startPosition.X) / (endPosition.Y - startPosition.Y)) - (startSlopeDx / startSlopeDy));
             *  float yRotCenter = -(startSlopeDx / startSlopeDy) * xRotCenter + n;
             *  CCPoint rotationPoint = new CCPoint(xRotCenter, yRotCenter);
             *
             *  // 2.1 find out whether to rotate left or right
             *  // for that rotate the start-direction-vector by 90° and by -90° and check which rotated vector is closer to the rotation point
             *  CCPoint rotatedLeft = CCPoint.RotateByAngle(new CCPoint(startSlopeDx, startSlopeDy), CCPoint.Zero, (float)Math.PI / 2) + startPosition;
             *  CCPoint rotatedRight = CCPoint.RotateByAngle(new CCPoint(startSlopeDx, startSlopeDy), CCPoint.Zero, -(float)Math.PI / 2) + startPosition;
             *  float angleSign;
             *  if (CCPoint.Distance(rotatedLeft, rotationPoint) < CCPoint.Distance(rotatedRight, rotationPoint))
             *  {
             *      // the rotation point is on your left, so rotate to the left
             *      angleSign = 1;
             *  }
             *  else
             *  {
             *      // the rotation point is on your right, so rotate to the right
             *      angleSign = -1;
             *  }
             *
             *  // ALTERNATE PATH COMPUTATION:
             *  // compute the angle between the vectors starting at the rotational center and ending in a) the startpoint b) the endpoint.
             *  // The path points are then generated by rotating the startpoint (using that point for each rotation) and increasing the angle
             *  // of rotation until it reaches the computed angle between the vectors.
             *  // The number of steps is dependent on the length of the line, calculated from the radius * the angle.
             *  float radius = CCPoint.Distance(rotationPoint, startPosition);
             *  CCPoint normalizedVectorRotStart = CCPoint.Normalize(startPosition - rotationPoint);
             *  CCPoint normalizedVectorRotEnd   = CCPoint.Normalize(endPosition - rotationPoint);
             *  float angleStart = Constants.DxDyToRadians(normalizedVectorRotStart.X, normalizedVectorRotStart.Y);
             *  float angleEnd   = Constants.DxDyToRadians(normalizedVectorRotEnd.X, normalizedVectorRotEnd.Y);
             *  // make sure angles are positive
             *  if (angleStart < 0) angleStart = (float)(2.0 * Math.PI) + angleStart;
             *  if (angleEnd < 0) angleEnd = (float)(2.0 * Math.PI) + angleEnd;
             *  // normalize the angles
             *  float angleShift = (float)(2.0 * Math.PI) - angleStart;
             *  angleEnd = (angleEnd + angleShift) % (float)(2.0 * Math.PI);
             *  float angleDestination = angleSign == 1 ? angleEnd : (float)(2.0*Math.PI) - angleEnd;
             *  //int steps = (int)(radius * angleDestination);
             *  //if (steps < 200) steps = 200;
             *  int steps = 250;
             *  for (int i=0; i < steps; i++)
             *  {
             *      CCPoint pathPoint = CCPoint.RotateByAngle(startPosition, rotationPoint, angleSign * angleDestination * ((float)i / (float)steps));
             *      pathPoints.Add(pathPoint);
             *  }
             *  pathPoints.Add(endPosition);
             * }
             */
            // SPECIAL CASE: the path is a straight line
            CCPoint     normalizedVectorStartEnd = CCPoint.Normalize(endPosition - startPosition);
            const float DELTA = 0.01f;

            if (CCPoint.Distance(normalizedVectorStartEnd, new CCPoint(startSlopeDx, startSlopeDy)) < DELTA)
            {
                Path = new CCPoint[] { startPosition, endPosition };
            }
            else
            {
                // calculate a spline
                // as the first point of the input-path add a new point
                // this point realises the start slope
                float firstX = startPosition.X - startSlopeDx;
                float firstY = startPosition.Y - startSlopeDy;
                // also create another point as the third point
                // it makes sure that the plane HAS TO MOVE a little bit in a somewhat straight way first
                float secondX = startPosition.X + 1 * startSlopeDx;
                float secondY = startPosition.Y + 1 * startSlopeDy;
                float thirdX  = startPosition.X + 10 * startSlopeDx;
                float thirdY  = startPosition.Y + 10 * startSlopeDy;

                // now calculate a special midpoint; it strongly defines the curvature of the path
                // start with the midpoint between start and end
                CCPoint midpoint = new CCPoint((endPosition.X + startPosition.X) / 2, (endPosition.Y + startPosition.Y) / 2);
                // now we need the perpendicular line going through that point (midpoint.Y = (-1/m)*midpoint.X + np) (mp = -1/m)
                float m  = (endPosition.Y - startPosition.Y) / (endPosition.X - startPosition.X);
                float mp = -1 / m;
                float np = midpoint.Y - midpoint.X * mp;
                // now get the line extending from the starting point with the startSlope (startPosition.Y = startSlope*startPosition.X + ns)
                float ns = startPosition.Y - (startSlopeDy / startSlopeDx) * startPosition.X;
                // next find the intersection point that these lines form (startSlope*x + ns = mp*x + np)
                // x*(startSlope - mp) = np - ns;
                float x = (np - ns) / ((startSlopeDy / startSlopeDx) - mp);
                float y = mp * x + np;
                // finally, as the special curvature point calculate the midpoint between the start-end-midpoint and intersection point
                float curvaturePointX = midpoint.X + ((x - midpoint.X) / 3f);
                float curvaturePointY = midpoint.Y + ((y - midpoint.Y) / 3f);
                // ADDITIONAL PROCESS FOR REFINING THIS FURTHER:
                // first get the curvature point as a vector relative to the midpoint
                CCPoint curveVector = new CCPoint(curvaturePointX - midpoint.X, curvaturePointY - midpoint.Y);
                // if it's not (0,0) (i.e. if there is any curvature at all)
                float curveFactor         = 0;
                float halfDistance        = CCPoint.Distance(startPosition, midpoint);
                float magicDistanceFactor = halfDistance / 900f < 1 ? halfDistance / 900f : 1;
                if (!curveVector.Equals(CCPoint.Zero))
                {
                    // normalize it
                    curveVector = CCPoint.Normalize(curveVector);
                    // now we need to calculate the factor by which it is to be scaled
                    // for that we calculate the scalar product of the normalized direction vector of the starting slope and the normalized direction vector from start to end point
                    float scalarProduct = CCPoint.Dot(new CCPoint(startSlopeDx, startSlopeDy), CCPoint.Normalize(new CCPoint(endPosition.X - startPosition.X, endPosition.Y - startPosition.Y)));
                    // the larger this product, the less curvature
                    curveFactor = 1 - scalarProduct;
                    //Console.WriteLine("CurveVector: " + curveVector);
                    //Console.WriteLine("CurveFactor: " + curveFactor);
                    //Console.WriteLine("Distance: " + CCPoint.Distance(startPosition, midpoint));
                    // now calculate the curvature point
                    curvaturePointX = midpoint.X + curveVector.X * curveFactor * (1.3f - 0.8f * magicDistanceFactor) * halfDistance * (curveFactor > 1 ? -1 : 1);
                    curvaturePointY = midpoint.Y + curveVector.Y * curveFactor * (1.3f - 0.8f * magicDistanceFactor) * halfDistance * (curveFactor > 1 ? -1 : 1);
                    //Console.WriteLine("Midpoint: " + midpoint);
                    //Console.WriteLine("CurvaturePoint: " + curvaturePointX + "," + curvaturePointY);
                }
                float[] xValues, yValues;
                magicDistanceFactor = halfDistance / 900f;
                if (curveFactor / magicDistanceFactor > 0.55f)
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, curvaturePointX, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, curvaturePointY, endPosition.Y };
                }
                else
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, endPosition.Y };
                }
                //var xValues = new float[] { startPosition.X, curvaturePointX, endPosition.X };
                //var yValues = new float[] { startPosition.Y, curvaturePointY, endPosition.Y };
                CubicSpline.FitParametric(xValues, yValues, POINTS_PER_PATH / 4, out float[] pathX1, out float[] pathY1); // startSlopeDx, startSlopeDy, endSlopeDx, endSlopeDy);
                                                                                                                          // get the point before the endpoint to adjust the curvature
                float xBeforeEnd = pathX1[pathX1.Length - 2];
                float yBeforeEnd = pathY1[pathY1.Length - 2];
                if (curveFactor / magicDistanceFactor > 0.55f)
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, curvaturePointX, xBeforeEnd, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, curvaturePointY, yBeforeEnd, endPosition.Y };
                }
                else
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, xBeforeEnd, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, yBeforeEnd, endPosition.Y };
                }
                CubicSpline.FitParametric(xValues, yValues, POINTS_PER_PATH, out float[] pathX, out float[] pathY);
                var newPath = new CCPoint[pathX.Length];

                // for the output skip the first point (start slope point)
                // and replace it with the start point
                newPath[0] = startPosition;
                for (int i = 1; i < pathX.Length; i++)
                {
                    newPath[i] = new CCPoint(pathX[i], pathY[i]);
                }
                Path = newPath;
            }

            // calculate and update the PathLength
            var pathLength = 0f;

            for (int i = 0; i < Path.Length - 1; i++)
            {
                pathLength += Constants.DistanceBetween(Path[i], Path[i + 1]);
            }
            PathLength = pathLength;
            // reset the advancement to 0
            AdvancementAsQuasiIndex = 0f;
        }
Пример #10
0
        public List <Tuple <DateTime, VolumeIndicator> > GetRangeOfVolumeIndicator(DateTime Start, DateTime End)
        {
            List <Tuple <DateTime, VolumeIndicator> > oVolumeIndicatorData = new List <Tuple <DateTime, VolumeIndicator> >();

            try
            {
                DateTime StartWithOffset = Start;
                if ((int)(End - Start).TotalDays < 20)
                {
                    StartWithOffset = Start.AddDays(-(20 - (int)(End - Start).TotalDays));
                }
                var HistData = GetDataForRange(StartWithOffset, End);
                if (HistData.Count() == 0)
                {
                    return(oVolumeIndicatorData);
                }

                double[] VolumeList   = HistData.Select(x => Convert.ToDouble(x.Volume)).ToArray();
                double   StdForVolume = VolumeList.StandardDeviation();
                double   StdForPrice  = HistData.Select(x => Convert.ToDouble(x.Close)).ToArray().StandardDeviation();

                CubicSpline oCSTotalData = CubicSpline.InterpolateNaturalSorted(
                    VolumeList.Select((s, i2) => new { i2, s })
                    .Select(t => Convert.ToDouble(t.i2)).ToArray(),
                    VolumeList);


                var ListOfDiff = VolumeList.Select((s, i2) => new { i2, s })
                                 .ToList().Select(f => oCSTotalData.Differentiate(Convert.ToDouble(f.i2))).ToArray();

                int i = 0;
                foreach (var hqd in HistData)
                {
                    VolumeIndicator oVi          = new VolumeIndicator();
                    bool            bHighVolume  = (ListOfDiff[i] > 0 && VolumeList[i] > StdForVolume);
                    bool            bLowVolume   = (ListOfDiff[i] <= 0 && VolumeList[i] < StdForVolume);
                    bool            bHighRange   = (Convert.ToDouble(hqd.Close - hqd.Open) > StdForPrice);
                    bool            bLowRange    = (-Convert.ToDouble(hqd.Open - hqd.Close) > StdForPrice);
                    bool            bUpBars      = (hqd.Close > hqd.Open);
                    bool            bNeutralBars = (hqd.Close.Equals(hqd.Open));

                    if (bHighVolume && bHighRange && bUpBars && !bNeutralBars)
                    {
                        oVi.VolumeIndicatorType = VolumeIndicatorType.VolumeClimaxUp;
                    }
                    else if (bHighVolume && bHighRange && !bUpBars && !bNeutralBars)
                    {
                        oVi.VolumeIndicatorType = VolumeIndicatorType.VolumeClimaxDown;
                    }
                    else if (bHighVolume && bHighRange && bNeutralBars)
                    {
                        oVi.VolumeIndicatorType = VolumeIndicatorType.VolumeClimaxPlusHighVolumeChurn;
                    }
                    else if (bHighVolume && !bHighRange)
                    {
                        oVi.VolumeIndicatorType = VolumeIndicatorType.HighVolumeChurn;
                    }
                    else if (!bHighVolume && bLowVolume)
                    {
                        oVi.VolumeIndicatorType = VolumeIndicatorType.LowVolume;
                    }
                    else
                    {
                        oVi.VolumeIndicatorType = VolumeIndicatorType.Unknown;
                    }
                    oVi.Strength = 100;
                    oVolumeIndicatorData.Add(new Tuple <DateTime, VolumeIndicator>(hqd.Date, oVi));

                    i++;
                }
            }catch (Exception ex)
            {
                ImperaturGlobal.GetLog().Error(string.Format("Error in GetRangeOfVolumeIndicator"), ex);
            }
            return(oVolumeIndicatorData);
        }
Пример #11
0
        void CalculateAndDrawLines()
        {
            float[] xs = new float[_NotesXValues.Count];                       // list of x values
            Dictionary <float, String> ids = new Dictionary <float, String>(); // map x to id

            Vector2 vLastLeft  = new Vector2(-100, 0);
            Vector2 vLastRight = vLastLeft;

            _posYears.Clear();
            _years.Clear();

            _txlistNotes.Clear();
            _posListNotes.Clear();

            // build: xs to hold x values
            //        dIds to hold x->id
            int m = 0;

            foreach (var n in _NotesXValues)
            {
                float x = (float)Math.Round(n.Value, ROUND);

                xs[m++] = x; // note x values

                if (ids.ContainsKey(x) == false)
                {
                    ids.Add(x, n.Key); // note id foreach x value
                }
            }

            Array.Sort(xs);

            // now we've the x values and we know which x value is which note...

            for (int j = 0; j < xs.Length - 1; ++j) // draw from left to right - xs is sorted
            {
                float left, right;

                left  = xs[j];
                right = xs[j + 1];

                float width = right - left;
                float h     = posLnZero.Y - 25;

                if (width > 22)
                #region draw parametric line
                {
                    // draw parametric line

                    // Ranges for line
                    float   half = left + width / 2;
                    float[] ixs  = { left, half, right };
                    float[] iys  = { posLnZero.Y, h, posLnZero.Y };

                    float[] xout, yout;

                    int nOutputPoints = (int)Math.Max(10, Math.Round(width / 4, 0));

                    CubicSpline.FitParametric(ixs, iys, nOutputPoints, out xout, out yout);

                    for (int k = 0; k < xout.Length - 1; ++k)
                    {
                        Vector2 pt1 = new Vector2(xout[k], yout[k]);
                        Vector2 pt2 = new Vector2(xout[k + 1], yout[k + 1]);

                        DrawLine(pt1, pt2, _clrGlobal);
                    }

                    // draw years

                    Vector2 pt = new Vector2(left + width / 2, posLnZero.Y - 25 - 14); //todo magic

                    _posYears.Add(pt);

                    // The current left, right x-values

                    float a = left;
                    float b = right;

                    if (ids.ContainsKey(a) && ids.ContainsKey(b))
                    {
                        //String[] id = { ids[a], ids[b] }; // note ids

                        TimeSpan   ts;
                        DateTime[] dts = { _Notes[ids[a]].dtUnified, _Notes[ids[b]].dtUnified };

                        if (dts[0] > dts[1])
                        {
                            ts = dts[0] - dts[1];
                        }
                        else
                        {
                            ts = dts[1] - dts[0];
                        }

                        DateTime dt = DateTime.MinValue + ts;
                        _years.Add(Math.Max(1, dt.Year - 1));

                        DateTime dtLeft  = dts[0];
                        DateTime dtRight = dts[1];

                        if (dtLeft.Year != yearprev)
                        {
                            TexXyz texLeft = new TexXyz();
                            texLeft.LoadContent_CAS_SizeM_UnsignedX(_mgr.GraphicsDevice, _sb, _mgr.Content);
                            texLeft.Update(dtLeft.Year);

                            _txlistNotes.Add(texLeft);
                            _posListNotes.Add(new Vector2(left, posNotes.Y));
                        }

                        TexXyz texRight = new TexXyz();
                        texRight.LoadContent_CAS_SizeM_UnsignedX(_mgr.GraphicsDevice, _sb, _mgr.Content);
                        texRight.Update(dtRight.Year);

                        _txlistNotes.Add(texRight);
                        _posListNotes.Add(new Vector2(right, posNotes.Y));

                        yearprev = dtRight.Year;
                    }
#if DEBUG
                    else
                    {
                        Debug.WriteLine("Internal error CwaNoteStatsImage CalculateDrawLines missing key");
                    }
#endif
                } // if draw
                #endregion
                else
                {
                    // curve is too small, so just draw a small line
                    DrawLine(new Vector2(left, posLnZero.Y), new Vector2(right, posLnZero.Y), _clrGlobal);
                }
            }

            for (int i = 1; i < _posListNotes.Count; ++i)
            {
                float w = _posListNotes[i].X - _posListNotes[i - 1].X;

                if (w < 30)
                {
                    Vector2 left = _posListNotes[i];
                    left.X          += 7;
                    _posListNotes[i] = left;

                    Vector2 right = _posListNotes[i - 1];
                    right.X -= 7;
                    _posListNotes[i - 1] = right;
                }
            }

            // calculate the years difference textures

            _txYearsDif = new TexXyz[_years.Count];

            for (int w = 0; w < _years.Count; ++w)
            {
                if (_years[w] > 0)
                {
                    _txYearsDif[w] = new TexXyz();
                    _txYearsDif[w].LoadContent_CAS_SizeM_UnsignedX(_mgr.GraphicsDevice, _sb, _mgr.Content);
                    _txYearsDif[w].Update(_years[w]);
                    bool updated = _txYearsDif[w].UpdateConsume;
                }
            }
        }
Пример #12
0
        private List <Wave> GetListOfWavesFromRange(DateTime StartDate, DateTime EndDate)
        {
            List <double> oPriceData = GetRangeOfDataAsDoubleIncludingLowHigh(StartDate, EndDate);

            if (oPriceData.Count < 5)
            {
                return(new List <Wave>());
            }

            CubicSpline oCSTotalData = CubicSpline.InterpolateAkimaSorted(

                oPriceData.Select((s, i2) => new { i2, s })
                .Select(t => Convert.ToDouble(t.i2)).ToArray(),

                oPriceData.Select(s => Convert.ToDouble(s)).ToArray());


            //create list of Waves
            List <Wave> oWaves = new List <Wave>();

            var FirstVarDiff = oPriceData.Select((s, i2) => new { i2, s })
                               .ToList().Select(f => oCSTotalData.Differentiate(Convert.ToDouble(f.i2))).ToArray();

            int           i                   = 0;
            Momentum      Current             = Momentum.Neutral;
            Momentum      Old                 = Momentum.Neutral;
            List <double> oCalcDoublesForWave = new List <double>();
            bool          bFirst              = true;

            foreach (var fvd in FirstVarDiff)
            {
                if (fvd < 0)
                {
                    Current = Momentum.Negative;
                }
                else if (fvd == 0)
                {
                    Current = Momentum.Neutral;
                }
                else
                {
                    Current = Momentum.Positive;
                }

                if (bFirst)
                {
                    oCalcDoublesForWave.Add(oCSTotalData.Interpolate(i));
                    bFirst = false;
                }
                else
                {
                    if (Current != Old && oCalcDoublesForWave.Count > 1)
                    {
                        oWaves.Add(new Wave
                        {
                            End         = oCalcDoublesForWave.Last(),
                            Start       = oCalcDoublesForWave.First(),
                            Length      = oCalcDoublesForWave.Count,
                            Momentum    = Old,
                            SourceIndex = i
                        });
                        oCalcDoublesForWave.Clear();
                    }
                    else if (Current != Old && oCalcDoublesForWave.Count <= 1)
                    {
                        oCalcDoublesForWave.Clear();
                    }
                    oCalcDoublesForWave.Add(oCSTotalData.Interpolate(i));
                }
                Old = Current;

                i++;
            }
            return(oWaves);
        }
Пример #13
0
        private TradingRecommendation GetTradingRecommendationForCrossOver()
        {
            int[] Intervals = { 50, 200 };
            TradingRecommendation Recommendation      = new TradingRecommendation();
            List <double[]>       MovingAverageObject = new List <double[]>();


            List <double> d1 = Statistics.MovingAverage(
                GetBusinessDayDataForRange(DateTime.Now, Intervals[0]).
                Select(s => Convert.ToDouble(s.Close)).ToArray(), Intervals[0]).ToList();
            List <double> d2 = Statistics.MovingAverage(
                GetBusinessDayDataForRange(DateTime.Now, Intervals[1]).
                Select(s => Convert.ToDouble(s.Close)).ToArray(), Intervals[1]).ToList();

            double[] xd = d1.ToArray();
            double[] yd = d2.Skip(d2.Count() - d1.Count()).ToArray();

            CubicSpline Curvedata = CubicSpline.InterpolateAkima(
                d1.Select((s, i2) => new { i2, s })
                .Select(t => Convert.ToDouble(t.i2)).ToArray(),
                d1);


            while (d1.Count() != d2.Count())
            {
                if (d1.Count() > d2.Count())
                {
                    d2.Insert(0, 0);
                }
                else
                {
                    d1.Insert(0, 0);
                }
            }

            double[] intersects0 = Polyfit(xd, yd, 0);


            List <Tuple <int, double> > Intersects = new List <Tuple <int, double> >();
            int i = 0;

            foreach (double di in yd)
            {
                if (di * 0.999 <= intersects0[0] && di * 1.001 >= intersects0[0])
                {
                    Intersects.Add(new Tuple <int, double>(i, di));
                }
                i++;
            }


            /*
             *
             *
             * CubicSpline Curvedata = CubicSpline.InterpolateAkima(
             * d1.Select((s, i2) => new { i2, s })
             * .Select(t => Convert.ToDouble(t.i2)).ToArray(),
             * d1);
             *
             *
             * while (d1.Count() != d2.Count())
             * {
             *  if (d1.Count() > d2.Count())
             *  {
             *      d2.Insert(0, double.NaN);
             *  }
             *  else
             *  {
             *      d1.Insert(0, double.NaN);
             *  }
             * }
             * List<Tuple<int, double>> Intersects = new List<Tuple<int, double>>();
             * int i = 0;
             * foreach (double di in d1)
             * {
             *  //need to add a little bit of gliding here as well...
             *  if (!double.IsNaN(di) && !double.IsNaN(d2[i]) && (di <= d2[i]*0.92 && di >= d2[i] * 1.07))
             *  {
             *      Intersects.Add(new Tuple<int, double>(i, di));
             *  }
             *  i++;
             * }*/
            try
            {
                int Sellmax = (Intersects.Where(x => Curvedata.Differentiate(x.Item2) < 0).Count() > 0) ? Intersects.Where(x => Curvedata.Differentiate(x.Item2) < 0).Last().Item1 : 0;
                int Buymax  = (Intersects.Where(x => Curvedata.Differentiate(x.Item2) > 0).Count() > 0) ? Intersects.Where(x => Curvedata.Differentiate(x.Item2) > 0).Last().Item1 : 0;

                if (Sellmax > Buymax && Sellmax > 0)
                {
                    return(new TradingRecommendation(
                               Instrument,
                               ImperaturGlobal.GetMoney(0, Instrument.CurrencyCode),
                               ImperaturGlobal.GetMoney(Convert.ToDecimal(Intersects.Where(x => x.Item1.Equals(Sellmax)).Last().Item2), Instrument.CurrencyCode),
                               DateTime.Now,
                               DateTime.Now,
                               TradingForecastMethod.Crossover
                               ));
                }
                if (Buymax > Sellmax && Buymax > 0)
                {
                    return(new TradingRecommendation(
                               Instrument,
                               ImperaturGlobal.GetMoney(Convert.ToDecimal(Intersects.Where(x => x.Item1.Equals(Buymax)).Last().Item2), Instrument.CurrencyCode),
                               ImperaturGlobal.GetMoney(0, Instrument.CurrencyCode),
                               DateTime.Now,
                               DateTime.Now,
                               TradingForecastMethod.Crossover
                               ));
                }
            }
            catch (Exception ex)
            {
                int gg = 0;
            }

            return(Recommendation);
        }
Пример #14
0
        static void Main(string[] args)
        {
            double[] x = new double[]
            {
                2,
                6,
                18,
                36,
                72,
                144,
                432,
                1008
            };

            double[] y = new double[]
            {
                123,
                117,
                107,
                92,
                33,
                32,
                8,
                7
            };

            Console.WriteLine($"X Y");
            for (int i = 0; i < x.Length; i++)
            {
                Console.WriteLine($"{x[i]} {y[i]}");
            }

            Console.WriteLine($"Interpolated:");

            //var spline = CubicSpline.InterpolateNaturalSorted(x, y);
            //var spline = CubicSpline.InterpolateAkimaSorted(x, y);
            var spline = CubicSpline.InterpolatePchipSorted(x, y);
            //var spline = LinearSpline.InterpolateSorted(x, y);
            //var spline = NevillePolynomialInterpolation.InterpolateSorted(x, y);
            //var spline = Barycentric.InterpolateRationalFloaterHormannSorted(x, y);
            //var spline = BulirschStoerRationalInterpolation.InterpolateSorted(x, y);
            //var spline = LogLinear.InterpolateSorted(x, y);
            //var spline = StepInterpolation.InterpolateSorted(x, y);

            var min = x.Min();
            var max = x.Max();

            for (double t = min; t <= max; t += 1)
            {
                double interpolated = spline.Interpolate(t);
                //Console.WriteLine($"{t} {interpolated}");
            }


            // var (a, b) = SimpleRegression.Fit(x, y);
            // for (double t = min; t <= max; t += 1)
            // {
            //     double interpolated = a + b * t;
            //     Console.WriteLine($"{t} {interpolated}");
            // }

            Test2();
        }
Пример #15
0
 public void FewSamples()
 {
     Assert.That(() => CubicSpline.InterpolateNatural(Array.Empty <double>(), Array.Empty <double>()), Throws.ArgumentException);
     Assert.That(() => CubicSpline.InterpolateNatural(new double[1], new double[1]), Throws.ArgumentException);
     Assert.That(CubicSpline.InterpolateNatural(new[] { 1.0, 2.0 }, new[] { 2.0, 2.0 }).Interpolate(1.0), Is.EqualTo(2.0));
 }
Пример #16
0
 public CubicInterpolation(double[] xPoints, double[] yPoints)
 {
     _interpolator = CubicSpline.InterpolateNaturalSorted(xPoints, yPoints);
 }
Пример #17
0
        static void Main(string[] args)
        {
            string storage = @"C:\Users\albinali\Desktop\AccelerationDifference\7cms-160start-end80RPM\Session12-3-18-29-6\";
            WocketsController wc = new WocketsController("", "", "");
            wc.FromXML(storage+"SensorData.xml");

            int[] lostSeconds = new int[wc._Sensors.Count];
            double[] prevUnix = new double[wc._Sensors.Count];
            int i=0;
            int prev_seq=-1;

            double[][] slopes = new double[wc._Sensors.Count][];

            for (i = 0; (i < wc._Sensors.Count); i++)
            {
                slopes[i]=new double[3];
                Wockets.Sensors.Accelerometers.Accelerometer acc=((Wockets.Sensors.Accelerometers.Accelerometer)wc._Sensors[i]);
                slopes[i][0] = (acc._X1G - acc._XN1G) / 2.0;
                slopes[i][1] = (acc._Y1G - acc._YN1G) / 2.0;
                slopes[i][2] = (acc._Z1G - acc._ZN1G) / 2.0;

            }
            for ( i= 0; (i < wc._Sensors.Count); i++)
            {
                double firstT = 0, lastT = 0;
                int count = 0;
                wc._Sensors[i]._RootStorageDirectory = storage + "data\\raw\\PLFormat\\";
                TextWriter tw = new StreamWriter(storage + "sensor" + wc._Sensors[i]._ID + ".csv");
                TextWriter twp = new StreamWriter(storage + "sensorloss" + wc._Sensors[i]._ID + ".csv");
                double totalLoss = 0;
                try
                {
                    int lastDecodedIndex = 0;
                    while (wc._Sensors[i].Load())
                    {
                        if (wc._Sensors[i]._Decoder._Head == 0)
                            lastDecodedIndex = wc._Sensors[i]._Decoder._Data.Length - 1;
                        else
                            lastDecodedIndex = wc._Sensors[i]._Decoder._Head - 1;
                        count++;

                        Wockets.Data.Accelerometers.AccelerationData data = (Wockets.Data.Accelerometers.AccelerationData)wc._Sensors[i]._Decoder._Data[lastDecodedIndex];
                        if (firstT == 0)
                            firstT = data.UnixTimeStamp;

                        if ((lastT>1000) && ((data.UnixTimeStamp- lastT) > 1000))
                            totalLoss += (data.UnixTimeStamp-lastT);

                        lastT = data.UnixTimeStamp;
                        /*int seq= ((data.X&0xff) | ((data.Y<<8)));
                        if (prev_seq >= 0)
                        {
                            if ((prev_seq + 1) != seq)
                                twp.WriteLine(data.UnixTimeStamp + "," + seq);
                        }*/

                        //tw.WriteLine(data.UnixTimeStamp + "," + data.X + "," + data.Y + "," + data.Z+","+seq);
                        tw.WriteLine(data.UnixTimeStamp + "," + data.X + "," + data.Y + "," + data.Z);
                        //prev_seq=seq;
                        if ((prevUnix[i] > 1000) && ((data.UnixTimeStamp - prevUnix[i]) > 60000))
                            lostSeconds[i] += (int)((data.UnixTimeStamp - prevUnix[i]) / 1000.0);

                        prevUnix[i] = data.UnixTimeStamp;

                    }
                }
                catch (Exception)
                {
                }
                double sr = count;
                double timer = (lastT - firstT) / 1000.0;
                sr = sr / timer;
                //tw.WriteLine("SR: " + sr);
                //tw.WriteLine("lost " + lostSeconds[i]);
                tw.Flush();
                tw.Close();
                twp.Flush();
                twp.WriteLine("Total Loss in seconds " + totalLoss/1000 + " in mins" + totalLoss / 60000);
                twp.Close();
            }

            //Environment.Exit(0);
            TextReader[] trs = new StreamReader[wc._Sensors.Count];
            Hashtable[] sensordata = new Hashtable[wc._Sensors.Count];
            string[] sensorlines = new string[wc._Sensors.Count];
            double[] lastTS=new double[wc._Sensors.Count];
            bool[] processed=new bool[wc._Sensors.Count];
            bool[] done=new bool[wc._Sensors.Count];
            int[] indexes=new int[wc._Sensors.Count];
            CubicSpline[][] csplines = new CubicSpline[wc._Sensors.Count][];

            i=0;
            long currentTS=9999999999999999;

            for (i = 0; (i < wc._Sensors.Count); i++)
            {
                trs[i] = new StreamReader(storage + "sensor" + i + ".csv");
                sensordata[i] = new Hashtable();
                processed[i]=true;
                done[i]=false;

                sensorlines[i]=trs[i].ReadLine();
                string[] tokens=sensorlines[i].Split(',');
                lastTS[i]=Convert.ToDouble(tokens[0])/1000.0;
                indexes[i]=0;
                if (lastTS[i] < currentTS)
                    currentTS= (long)lastTS[i];

            }

            bool Alldone=true;
            bool AllProcessed = false;
            TextWriter merged = new StreamWriter(storage + "merged.csv");
            do
            {

                for (i = 0; (i < wc._Sensors.Count); i++)
                {
                    if ((done[i]==false) && (processed[i]))
                    {
                        sensorlines[i] = trs[i].ReadLine();
                        if (sensorlines[i] == null)
                            done[i] = true;
                    }

                    if (done[i] == false)
                    {
                        string[] tokens = sensorlines[i].Split(',');
                        long ts = (long)(Convert.ToDouble(tokens[0]) / 1000.0);
                        if (currentTS != ts)
                        {
                            if (processed[i] == true)
                            {
                                //stop reading
                                processed[i] = false;

                                //correct timestamps
                                int count = sensordata[i].Count;
                                double delta = 1000.0 / count;
                                for (int j=0;(j<indexes[i]);j++)
                                {
                                    string vals = (string)sensordata[i][j];
                                    sensordata[i].Remove(j);
                                    long ctime=(long)((currentTS * 1000.0) + j * delta);
                                    sensordata[i].Add(ctime, vals);
                                }
                            }

                        }
                        else
                        {
                            sensordata[i].Add(indexes[i], tokens[1] + "," + tokens[2] + "," + tokens[3]);
                            indexes[i] = indexes[i] + 1;
                        }
                    }
                }

                AllProcessed = false;
                Alldone = true;
                for (i = 0; (i < wc._Sensors.Count); i++)
                {
                    if (done[i] == false)
                        Alldone = false;
                    if ((done[i]==false) && (processed[i] == true))
                        AllProcessed = true;
                }

                if (AllProcessed==false)
                {
                    //go by milliseconds

                    double start_time = currentTS * 1000.0;

                    double[][] xs = new double[wc._Sensors.Count][];
                    double[][] ys1 = new double[wc._Sensors.Count][];
                    double[][] ys2 = new double[wc._Sensors.Count][];
                    double[][] ys3 = new double[wc._Sensors.Count][];
                    int[] ccounter=new int[wc._Sensors.Count];

                    for (int j=0;(j<wc._Sensors.Count);j++)
                    {
                        xs[j] = new double[sensordata[j].Count];
                        ys1[j] = new double[sensordata[j].Count];
                        ys2[j] = new double[sensordata[j].Count];
                        ys3[j] = new double[sensordata[j].Count];
                        //ccounter[j]=new int[sensordata[j].Count];
                        for (int k = 0; (k < sensordata[j].Count); k++)
                        {
                            xs[j][k] = 0;
                            ys1[j][k] = 0;
                            ys2[j][k] = 0;
                            ys3[j][k] = 0;
                            ccounter[j] = 0;
                        }
                    }
                    for (int t = 0; (t < 1000); t++)
                    {
                        long currentTT=((long)(start_time+t));
                        string output = currentTT.ToString();
                        bool found = false;
                        for (int j = 0; (j < wc._Sensors.Count); j++)
                        {
                            if (sensordata[j].ContainsKey(currentTT))
                            {
                                string[] tokens2=((string)sensordata[j][currentTT]).Split(',');
                                xs[j][ccounter[j]] = currentTT - (long)start_time;
                                ys1[j][ccounter[j]] = (double)Convert.ToInt32(tokens2[0]);
                                ys2[j][ccounter[j]] = (double)Convert.ToInt32(tokens2[1]);
                                ys3[j][ccounter[j]] = (double)Convert.ToInt32(tokens2[2]);
                                ccounter[j] = ccounter[j] + 1;
                            }

                            /*if (sensordata[j].ContainsKey(currentTT))
                            {
                                output += "," + (string)sensordata[j][currentTT];
                               found = true;
                            }
                            else
                                output += ",,,";
                             */
                        }
                        //if (found)
                        //merged.WriteLine(output);
                    }

                    for (int j = 0; (j < wc._Sensors.Count); j++)
                    {
                        csplines[j] = new CubicSpline[3];
                        if (xs[j].Length > 10)
                        {
                            csplines[j][0] = new CubicSpline(xs[j], ys1[j]);
                            csplines[j][1] = new CubicSpline(xs[j], ys2[j]);
                            csplines[j][2] = new CubicSpline(xs[j], ys3[j]);
                        }
                    }

                    for (int t = 0; (t < 1000); )
                    {
                        long currentTT = ((long)(start_time + t));
                        string output = currentTT.ToString();
            //                        bool found = false;

                        for (int j = 0; (j < wc._Sensors.Count); j++)
                        {
                            //if (sensordata[j].ContainsKey(currentTT))
                            //{
                            Wockets.Sensors.Accelerometers.Accelerometer acc = ((Wockets.Sensors.Accelerometers.Accelerometer)wc._Sensors[j]);
                            if (csplines[j][0] != null)
                            {
                                double xx = csplines[j][0].interpolate(t);
                                double yy=csplines[j][1].interpolate(t);
                                double zz=csplines[j][2].interpolate(t);

                                //compute g values
                                xx = (1.0+ ((xx-acc._X1G)/slopes[j][0]))*980;
                                yy = (1.0 + ((yy - acc._Y1G) / slopes[j][1]))*980;
                                zz = (1.0 + ((zz - acc._Z1G) / slopes[j][2]))*980;
                                output += "," + xx +","+yy+","+zz;
                            }else
                                output += ",,,";

             //                               found = true;
                            //}
             //                       else
               //                             output += ",,,";
                        }

                        merged.WriteLine(output);
                        t += 11;
                    }

                    Console.WriteLine("Processing " + currentTS);
                    currentTS += 1;
                    for (i = 0; (i < wc._Sensors.Count); i++)
                    {
                        if (done[i] == false)
                        {
                            sensordata[i] = new Hashtable();
                            processed[i] = true;
                            indexes[i] = 0;
                            //add last read data point
                            string[] tokens = sensorlines[i].Split(',');
                            long ts = (long)(Convert.ToDouble(tokens[0]) / 1000.0);
                            if (currentTS == ts)
                            {
                                sensordata[i].Add(indexes[i], tokens[1] + "," + tokens[2] + "," + tokens[3]);
                                indexes[i] = indexes[i] + 1;
                            }
                        }

                    }
                    AllProcessed = true;

                }

            } while (Alldone == false);

            merged.Close();

            /*
            Classifier classifier;
            FastVector fvWekaAttributes;
            Instances instances;
            string[] activityLabels;
            Hashtable labelIndex;
            int[] labelCounters;

            string storage = @"C:\Users\albinali\Desktop\data\mites data\wockets\";
            WocketsController wc = new WocketsController("", "", "");
            wc.FromXML(storage + "SensorData.xml");
            int[] lostSeconds = new int[wc._Sensors.Count];
            double[] prevUnix = new double[wc._Sensors.Count];
            bool isAllDone = false;

            Session annotatedSession = new Session();
            DTConfiguration classifierConfiguration = new DTConfiguration();

            try
            {
                annotatedSession.FromXML(storage + "\\ActivityLabelsRealtime.xml");
            }
            catch (Exception e)
            {
            }

            try
            {
                classifierConfiguration.FromXML(storage + "\\Configuration.xml");
            }
            catch (Exception e)
            {
            }

            FeatureExtractor.Initialize(wc, classifierConfiguration, annotatedSession.OverlappingActivityLists[0]);

            labelIndex = new Hashtable();

            classifier = new J48();
            if (!File.Exists(storage + "\\model.xml"))
            {
                string[] arffFiles = Directory.GetFileSystemEntries(storage, "output*.arff");
                if (arffFiles.Length != 1)
                    throw new Exception("Multiple Arff Files in Directory");
                instances = new Instances(new StreamReader(arffFiles[0]));
                instances.Class = instances.attribute(FeatureExtractor.ArffAttributeLabels.Length);
                classifier.buildClassifier(instances);
                TextWriter tc = new StreamWriter(storage + "\\model.xml");
                classifier.toXML(tc);
                tc.Flush();
                tc.Close();
            }
            else
            {
                instances = new Instances(new StreamReader(storage + "\\structure.arff"));
                instances.Class = instances.attribute(FeatureExtractor.ArffAttributeLabels.Length);
                classifier.buildClassifier(storage + "\\model.xml", instances);
            }

            fvWekaAttributes = new FastVector(FeatureExtractor.ArffAttributeLabels.Length + 1);
            for (int i = 0; (i < FeatureExtractor.ArffAttributeLabels.Length); i++)
                fvWekaAttributes.addElement(new weka.core.Attribute(FeatureExtractor.ArffAttributeLabels[i]));

            FastVector fvClassVal = new FastVector();
            labelCounters = new int[annotatedSession.OverlappingActivityLists[0].Count + 1];
            activityLabels = new string[annotatedSession.OverlappingActivityLists[0].Count + 1];
            for (int i = 0; (i < annotatedSession.OverlappingActivityLists[0].Count); i++)
            {
                labelCounters[i] = 0;
                string label = "";
                int j = 0;
                for (j = 0; (j < annotatedSession.OverlappingActivityLists.Count - 1); j++)
                    label += annotatedSession.OverlappingActivityLists[j][i]._Name.Replace(' ', '_') + "_";
                label += annotatedSession.OverlappingActivityLists[j][i]._Name.Replace(' ', '_');
                activityLabels[i] = label;
                labelIndex.Add(label, i);
                fvClassVal.addElement(label);
            }

            weka.core.Attribute ClassAttribute = new weka.core.Attribute("activity", fvClassVal);

            int[] lastDecodedIndex = new int[wc._Sensors.Count];
            double[] lastDecodedTime = new double[wc._Sensors.Count];
            bool[] isDone = new bool[wc._Sensors.Count];
            int nextSensor = 0;
            double smallestTimestamp = 0;
            for (int i = 0; (i < wc._Sensors.Count); i++)
            {
                wc._Sensors[i]._RootStorageDirectory = storage + "data\\raw\\PLFormat\\";
                isDone[i] = false;
                lastDecodedTime[i] = 0;
                lastDecodedIndex[i] = 0;
            }
            //double lastTimeStamp=0;
            Wockets.Data.Accelerometers.AccelerationData data = null;
            string previousActivity = "";
            Annotation annotation = null;
            int classificationCounter = 0;
            string mostActivity = "";
            while (isAllDone == false)
            {
                isAllDone = true;
                for (int i = 0; (i < wc._Sensors.Count); i++)
                {

                    if (nextSensor == i)
                    {
                        if (wc._Sensors[i].Load())
                        {
                            if (wc._Sensors[i]._Decoder._Head == 0)
                                lastDecodedIndex[i] = wc._Sensors[i]._Decoder._Data.Length - 1;
                            else
                                lastDecodedIndex[i] = wc._Sensors[i]._Decoder._Head - 1;
                            data = (Wockets.Data.Accelerometers.AccelerationData)wc._Sensors[i]._Decoder._Data[lastDecodedIndex[i]];
                            lastDecodedTime[i] = data.UnixTimeStamp;

                            isAllDone = false;

                            double lastTT = FeatureExtractor.StoreWocketsWindow();

                            if (FeatureExtractor.GenerateFeatureVector(lastTT))
                            {
                                Instance newinstance = new Instance(instances.numAttributes());
                                newinstance.Dataset = instances;
                                for (int k = 0; (k < FeatureExtractor.Features.Length); k++)
                                    newinstance.setValue(instances.attribute(k), FeatureExtractor.Features[k]);
                                double predicted = classifier.classifyInstance(newinstance);
                                string predicted_activity = newinstance.dataset().classAttribute().value_Renamed((int)predicted);
                                int currentIndex = (int)labelIndex[predicted_activity];
                                labelCounters[currentIndex] = (int)labelCounters[currentIndex] + 1;
                                classificationCounter++;

                                if (classificationCounter == classifierConfiguration._SmoothWindows)
                                {
                                    classificationCounter = 0;
                                    int mostCount = 0;
                                    for (int j = 0; (j < labelCounters.Length); j++)
                                    {
                                        if (labelCounters[j] > mostCount)
                                        {
                                            mostActivity = activityLabels[j];
                                            mostCount = labelCounters[j];

                                        }
                                        labelCounters[j] = 0;
                                    }

                                    if (mostCount == classifierConfiguration._SmoothWindows)
                                    {
                                        DateTime mydate = new DateTime();
                                        if (previousActivity == "")
                                        {
                                            annotation = new Annotation();
                                            annotation._StartUnix = data.UnixTimeStamp;
                                            WocketsTimer.GetDateTime((long)(data.UnixTimeStamp),out mydate);
                                            annotation._StartDate = mydate.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK");
                                            annotation._StartHour = mydate.Hour;
                                            annotation._StartMinute = mydate.Minute;
                                            annotation._StartSecond = mydate.Second;
                                            annotation.Activities.Add(new Activity(mostActivity, "Physical Activiites"));
                                        }
                                        else if (previousActivity != mostActivity)
                                        {
                                            annotation._EndUnix = data.UnixTimeStamp;
                                            WocketsTimer.GetDateTime((long)(data.UnixTimeStamp), out mydate);
                                            annotation._EndDate = mydate.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK");
                                            annotation._EndHour = mydate.Hour;
                                            annotation._EndMinute = mydate.Minute;
                                            annotation._EndSecond = mydate.Second;

                                            annotatedSession.Annotations.Add(annotation);

                                            annotation = new Annotation();
                                            annotation._StartUnix = data.UnixTimeStamp;
                                            WocketsTimer.GetDateTime((long)(data.UnixTimeStamp), out mydate);
                                            annotation._StartDate = mydate.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK");
                                            annotation._StartHour = mydate.Hour;
                                            annotation._StartMinute = mydate.Minute;
                                            annotation._StartSecond = mydate.Second;

                                            annotation.Activities.Add(new Activity(mostActivity, "Physical Activiites"));
                                        }

                                        previousActivity = mostActivity;
                                    }

                                }

                            }
                        }
                    }

                    nextSensor = 0;
                    smallestTimestamp = lastDecodedTime[0];
                    for (int j = 0; (j < wc._Sensors.Count); j++)
                    {
                        if (smallestTimestamp > lastDecodedTime[j])
                        {
                            smallestTimestamp = lastDecodedTime[j];
                            nextSensor = j;
                        }
                    }

                }
            }

            TextWriter tw = new StreamWriter(storage + "\\AnnotationIntervals.xml");
            tw.WriteLine(annotatedSession.ToXML());
            tw.Close();
            tw = new StreamWriter(storage + "\\AnnotationIntervals.CSV");
            tw.WriteLine(annotatedSession.ToCSV());
            tw.Close();
             *
             *  *
             * */
        }
Пример #18
0
    // Update is called once per frame
    void Update()
    {
        if (isPlaying)
        {
            if (points == null)
            {
                Debug.Log("points is null");
                return;
            }
            currentFrame++;
            if (currentFrame < frameTick)
            {
                return;
            }
            currentFrame = 0;
            if (spline == null)
            {
                spline = new CubicSpline(this.points, this.segment, this.Smoothness, true);

                List <Vector3> lastPoints = new List <Vector3>();
                for (int i = 0; i < points.Count; i++)
                {
                    lastPoints.Add(points[i].transform.localPosition);
                }
                np2          = calculatePoint(lastPoints);
                totalNum     = np2.Count;
                currentIndex = 0;
                currentNum   = 0;
            }
            //Debug.Log("currentNum:"+ currentNum);
            #region MakeMesh
            //计算当前需要的点数
            // 当前的点数 currentNum+showNum
            if (currentIndex + showNum < totalNum)
            {
                if (currentNum < showNum)
                {
                    //增加不平移
                    currentNum++;
                }
                else
                {
                    //平移
                    currentIndex++;
                }
            }
            else
            {
                if (currentNum > 2)
                {
                    currentIndex++;
                    currentNum--;
                }
                else
                {
                    //重新开始
                    currentIndex = 0;
                    currentNum   = 0;
                }
            }
            GetPointsData();
            UpdateMesh();
            #endregion
        }
    }
Пример #19
0
        internal static void Departing(this FlightContext context)
        {
            /*
             * First check plausible scenarios. The easiest to track is an aerotow.
             *
             * If not, wait until the launch is completed.
             */

            if (context.Flight.LaunchMethod == LaunchMethods.None)
            {
                var departure = context.Flight.PositionUpdates
                                .Where(q => q.Heading != 0 && !double.IsNaN(q.Heading))
                                .OrderBy(q => q.TimeStamp)
                                .Take(5)
                                .ToList();

                if (departure.Count > 4)
                {
                    context.Flight.DepartureHeading = Convert.ToInt16(departure.Average(q => q.Heading));

                    if (context.Flight.DepartureHeading == 0)
                    {
                        context.Flight.DepartureHeading = 360;
                    }

                    // Only start method recognition after the heading has been determined
                    context.Flight.LaunchMethod = LaunchMethods.Unknown | LaunchMethods.Aerotow | LaunchMethods.Winch | LaunchMethods.Self;
                }
                else
                {
                    return;
                }
            }

            if (context.Flight.DepartureTime != null &&
                (context.CurrentPosition.TimeStamp - (context.Flight.PositionUpdates.FirstOrDefault(q => q.Speed > 30)?.TimeStamp ?? context.CurrentPosition.TimeStamp)).TotalSeconds < 10)
            {
                return;
            }

            // We can safely try to extract the correct path

            if (context.Flight.LaunchMethod.HasFlag(LaunchMethods.Unknown | LaunchMethods.Aerotow))
            {
                var encounters = context.TowEncounter().ToList();

                if (encounters.Count(q => q?.Type == EncounterType.Tug || q?.Type == EncounterType.Tow) > 1)
                {
                    return;
                }

                var encounter = encounters.SingleOrDefault(q => q?.Type == EncounterType.Tug || q?.Type == EncounterType.Tow);

                if (encounter != null)
                {
                    context.Flight.LaunchMethod = LaunchMethods.Aerotow
                                                  | (encounter.Type == EncounterType.Tug
                            ? LaunchMethods.OnTow
                            : LaunchMethods.TowPlane
                                                     );

                    context.Flight.Encounters.Add(encounter);

                    context.StateMachine.Fire(FlightContext.Trigger.TrackAerotow);

                    return;
                }
                else if (encounters.Any(q => q == null))
                {
                    return;
                }

                context.Flight.LaunchMethod &= ~LaunchMethods.Aerotow;
            }

            if (context.Flight.LaunchMethod.HasFlag(LaunchMethods.Unknown))
            {
                var x = new DenseVector(context.Flight.PositionUpdates.Select(w => (w.TimeStamp - context.Flight.DepartureTime.Value).TotalSeconds).ToArray());
                var y = new DenseVector(context.Flight.PositionUpdates.Select(w => w.Altitude).ToArray());

                var interpolation = CubicSpline.InterpolateNatural(x, y);

                var r  = new List <double>();
                var r2 = new List <double>();

                for (var i = 0; i < (context.CurrentPosition.TimeStamp - context.Flight.DepartureTime.Value).TotalSeconds; i++)
                {
                    r.Add(interpolation.Differentiate(i));
                    r2.Add(interpolation.Differentiate2(i));
                }

                // When the initial climb has completed
                if (interpolation.Differentiate((context.CurrentPosition.TimeStamp - context.Flight.DepartureTime.Value).TotalSeconds) < 0)
                {
                    // Skip the first element because heading is 0 when in rest
                    var averageHeading = context.Flight.PositionUpdates.Skip(1).Average(q => q.Heading);

                    // ToDo: Add check to see whether there is another aircraft nearby
                    if (context.Flight.PositionUpdates
                        .Skip(1)
                        .Where(q => interpolation.Differentiate((context.CurrentPosition.TimeStamp - context.Flight.DepartureTime.Value).TotalSeconds) > 0)
                        .Select(q => Geo.GetHeadingError(averageHeading, q.Heading))
                        .Any(q => q > 20) ||
                        Geo.DistanceTo(
                            context.Flight.PositionUpdates.First().Location,
                            context.CurrentPosition.Location) > 3000)
                    {
                        context.Flight.LaunchMethod = LaunchMethods.Self;
                    }
                    else
                    {
                        context.Flight.LaunchMethod = LaunchMethods.Winch;
                    }

                    context.Flight.LaunchFinished = context.CurrentPosition.TimeStamp;
                    context.InvokeOnLaunchCompletedEvent();
                    context.StateMachine.Fire(FlightContext.Trigger.LaunchCompleted);
                }
            }
        }
Пример #20
0
        public Collection <DataPoint> GeneratePointsFromBitmap(string filename)
        {
            filename = Path.ChangeExtension(filename, "png");
            if (File.Exists(filename))
            {
                double fmax    = 19000.0;
                double fmin    = 20.0;
                double dbrange = 16.0;
                double dbmax   = 1;

                double sampleRate = 48000;
                int    sampleSize = 16384;

                // Create a Bitmap object from an image file.
                Bitmap iBitmap = new Bitmap(filename);
                Bitmap oBitmap = new Bitmap(iBitmap.Width, iBitmap.Height);

                int    first = 0;
                int    last  = 0;
                int    size  = 0;
                double min   = iBitmap.Height;
                double max   = 0;
                double mag   = 0;

                // Get the color of a pixel within myBitmap.
                Collection <KeyValuePair <int, double> > points = new Collection <KeyValuePair <int, double> >();
                for (var x = 0; x < iBitmap.Width; x++)
                {
                    List <int> list = new List <int>();
                    for (var y = 0; y < iBitmap.Height; y++)
                    {
                        Color pixelColor = iBitmap.GetPixel(x, y);
                        if ((pixelColor.R > 200) && (pixelColor.G < 25) && (pixelColor.B < 25))
                        {
                            if (first == 0)
                            {
                                first = x;
                            }
                            else
                            {
                                last = x;
                            }
                            oBitmap.SetPixel(x, y, Color.FromArgb(255, 0, 0));
                            list.Add(y);
                        }
                    }
                    if (list.Count > 0)
                    {
                        var a = iBitmap.Height - list.Average();
                        points.Add(new KeyValuePair <int, double>(x, a));
                        if (a < min)
                        {
                            min = a;
                        }
                        if (a > max)
                        {
                            max = a;
                        }
                    }
                }

                size = last - first + 1;
                mag  = max - min + 1;

                //calculate gain & offset
                double scale = dbrange / mag;
                double shift = dbmax - max * scale;

                //check
                double n_min = min * scale + shift;
                double n_max = max * scale + shift;

                //convert bitmap to frequency spectrum
                Collection <double> ex = new Collection <double>();
                Collection <double> ey = new Collection <double>();
                for (var x = 0; x < points.Count; x++)
                {
                    double df = Math.Log10(fmax / fmin);                      //over aproximately 3 decades
                    double f  = 20.0 * Math.Pow(10.0, df * x / points.Count); //convert log horizontal image pixels to linear frequency scale in Hz
                    double y  = points[x].Value * scale + shift;              //scale and shift vertical image pixels to correct magnitude in dB

                    ex.Add(f);
                    ey.Add(Math.Pow(10.0, y / 20.0));
                }

                //interpolate frequency spectrum to match Audyssey responseData length
                double[]               frequency        = Enumerable.Range(0, sampleSize).Select(p => p * sampleRate / sampleSize).ToArray();
                CubicSpline            IA               = CubicSpline.InterpolateAkima(ex, ey);
                Collection <DataPoint> frequency_points = new Collection <DataPoint>();
                foreach (var f in frequency)
                {
                    if (f < fmin)
                    {   // exptrapolate
                        frequency_points.Add(new DataPoint(f, double.NegativeInfinity));
                    }
                    else
                    {
                        if (f > fmax)
                        {   // exptrapolate
                            frequency_points.Add(new DataPoint(f, double.NegativeInfinity));
                        }
                        else
                        {   //interpolate
                            frequency_points.Add(new DataPoint(f, 20 * Math.Log10(IA.Interpolate(f))));
                        }
                    }
                }

                oBitmap.Save(Path.ChangeExtension(filename, "jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

                return(frequency_points);
            }
            else
            {
                return(null);
            }
        }
Пример #21
0
 public CubicSplinesInterpolation()
 {
     this.Spl = new CubicSpline();
     InitializeComponent();
 }
        public void LoadTrajectory(com.robotraconteur.robotics.trajectory.JointTrajectory traj, double speed_ratio)
        {
            if (traj.joint_names.Count > 0)
            {
                if (!Enumerable.SequenceEqual(traj.joint_names, joint_names))
                {
                    throw new ArgumentException("Joint names in trajectory must match robot joint names");
                }
            }

            if (traj.waypoints == null)
            {
                throw new ArgumentException("Waypoint list must not be null");
            }

            if (traj.waypoints.Count < 5)
            {
                throw new ArgumentException("Waypoint list must contain five or more waypoints");
            }

            if (traj.waypoints[0].time_from_start != 0)
            {
                throw new ArgumentException("Trajectory time_from_start must equal zero for first waypoint");
            }

            if (traj.interpolation_mode != com.robotraconteur.robotics.trajectory.InterpolationMode.default_ &&
                traj.interpolation_mode != com.robotraconteur.robotics.trajectory.InterpolationMode.cubic_spline)
            {
                throw new ArgumentException($"Only default and cubic_spline interpolation supported for trajectory execution");
            }

            int n_waypoints = traj.waypoints.Count;
            int n_joints    = joint_names.Length;

            var             traj_t = new double[n_waypoints];
            List <double[]> traj_j = Enumerable.Range(1, n_joints).Select(i => new double[n_waypoints]).ToList();

            double last_t = 0;

            for (int i = 0; i < n_waypoints; i++)
            {
                var w = traj.waypoints[i];

                if (w.joint_position.Length != n_joints)
                {
                    throw new ArgumentException($"Waypoint {i} invalid joint array length");
                }

                if (w.joint_velocity.Length != n_joints && w.joint_velocity.Length != 0)
                {
                    throw new ArgumentException($"Waypoint {i} invalid joint velocity array length");
                }

                if (w.position_tolerance.Length != n_joints && w.position_tolerance.Length != 0)
                {
                    throw new ArgumentException($"Waypoint {i} invalid tolerance array length");
                }

                if (w.velocity_tolerance.Length != n_joints && w.velocity_tolerance.Length != 0)
                {
                    throw new ArgumentException($"Waypoint {i} invalid tolerance array length");
                }

                if (i > 0)
                {
                    if (w.time_from_start / speed_ratio <= last_t)
                    {
                        throw new ArgumentException("time_from_start must be increasing");
                    }
                }

                for (int j = 0; j < n_joints; j++)
                {
                    if (w.joint_position[j] > joint_max[j] || w.joint_position[j] < joint_min[j])
                    {
                        throw new ArgumentException($"Waypoint {i} exceeds joint limits");
                    }

                    if (w.joint_velocity.Length > 0)
                    {
                        if (Math.Abs(w.joint_velocity[j] * speed_ratio) > joint_vel_max[j])
                        {
                            throw new ArgumentException($"Waypoint {i} exceeds joint velocity limits");
                        }
                    }
                }

                if (i > 0)
                {
                    var    last_w = traj.waypoints[i - 1];
                    double dt     = w.time_from_start / speed_ratio - last_w.time_from_start / speed_ratio;

                    for (int j = 0; j < n_joints; j++)
                    {
                        double dj = Math.Abs(w.joint_position[j] - last_w.joint_position[j]);
                        if (dj / dt > joint_vel_max[j])
                        {
                            throw new ArgumentException($"Waypoint {i} exceeds joint velocity limits");
                        }
                    }
                }

                traj_t[i] = w.time_from_start / speed_ratio;
                for (int j = 0; j < n_joints; j++)
                {
                    traj_j[j][i] = w.joint_position[j];
                }

                last_t = w.time_from_start / speed_ratio;
            }

            joint_splines = traj_j.Select(x => CubicSpline.InterpolateAkima(traj_t, x)).ToList();
            max_t         = last_t;

            joint_start    = traj.waypoints[0].joint_position;
            joint_end      = traj.waypoints.Last().joint_position;
            waypoint_times = traj_t;
        }
Пример #23
0
 public AirfoilData(CubicSpline liftCubicSpline, CubicSpline dragCubicSpline)
 {
     this.liftCubicSpline = liftCubicSpline;
     this.dragCubicSpline = dragCubicSpline;
 }
Пример #24
0
        static double[][] emd(double[] signal, double[][] mods, int calls, int countOfMods)
        {
            if (originalSignal == null)
            {
                originalSignal = signal;
            }
            //int calls = 0;
            double[] mod = new double[signal.Length];
            //  while (calls<=21)
            {
                double[] localMaximums;
                double[] localMinimums;
                double[] indexesOfLocalMaximums;
                double[] indexesOfLocalMinimums;


                FindExtremums(signal, out localMinimums, out localMaximums, out indexesOfLocalMinimums, out indexesOfLocalMaximums);

                if (calls == 100)
                {
                    GC.Collect();
                }
                if (calls > 150 || indexesOfLocalMaximums.Length <= 1 || indexesOfLocalMinimums.Length <= 1)
                {
                    mods[countOfMods] = originalSignal;
                    return(mods);
                }
                double[]  interpMinimums = new double[signal.Length];
                double[]  interpMaximums = new double[signal.Length];
                Stopwatch sss            = new Stopwatch();
                sss.Start();

                // ToFile(localMinimums);
                // ToFile(localMaximums);
                CubicSpline interp = new CubicSpline();
                interp.BuildSpline(indexesOfLocalMinimums, localMinimums, indexesOfLocalMinimums.Length);

                int min = (int)(indexesOfLocalMinimums[0] < indexesOfLocalMaximums[0]
                    ? indexesOfLocalMaximums[0]
                    : indexesOfLocalMinimums[0]);

                int max = (int)(indexesOfLocalMinimums[indexesOfLocalMinimums.Length - 1] > indexesOfLocalMaximums[indexesOfLocalMaximums.Length - 1]
                    ? indexesOfLocalMaximums[indexesOfLocalMaximums.Length - 1]
                    : indexesOfLocalMinimums[indexesOfLocalMinimums.Length - 1]);
                double[] difference = new double[max - min];
                for (int interpolatedX = min; interpolatedX < max; interpolatedX++)
                {
                    interpMinimums[interpolatedX] = interp.Interpolate(interpolatedX);
                }
                // ToFile(interpMinimums);

                interp.BuildSpline(indexesOfLocalMaximums, localMaximums, indexesOfLocalMaximums.Length);
                for (int interpolatedX = min; interpolatedX < max; interpolatedX++)
                {
                    interpMaximums[interpolatedX] = interp.Interpolate(interpolatedX);
                }

                // ToFile(interpMaximums);
                sss.Stop();

                for (int i = min; i < max; i++)
                {
                    difference[i - min] = signal[i] - (interpMaximums[i] + interpMinimums[i]) / 2;
                }

                int    countOfNulls = 0;
                double mean         = 0;
                for (int i = 0; i < difference.Length - 1; i++)
                {
                    if (difference[i] * difference[i + 1] < 0)
                    {
                        countOfNulls++;
                    }
                    mean += difference[i];
                }
                mean /= difference.Length;
                FindExtremums(difference, out localMinimums, out localMaximums, out indexesOfLocalMinimums, out indexesOfLocalMaximums);
                if (Math.Abs(mean) <= 0.009 && Math.Abs(indexesOfLocalMaximums.Length + indexesOfLocalMinimums.Length - countOfNulls) <= 1)
                {
                    mods[countOfMods] = difference;
                    countOfMods++;
                    var backupLink = originalSignal;
                    originalSignal = new double[max - min];
                    for (int i = min; i < max; i++)
                    {
                        originalSignal[i - min] = backupLink[i] - difference[i - min];
                    }
                    calls++;

                    /* difference = null;
                     * localMinimums = null;
                     * localMaximums = null;
                     * indexesOfLocalMinimums = null;
                     * indexesOfLocalMaximums = null;
                     * interpMaximums = null;
                     * interpMinimums = null;*/
                    return(emd(originalSignal, mods, calls, countOfMods));
                }
                calls++;
                return(emd(difference, mods, calls, countOfMods));
            }
        }
Пример #25
0
    public void CrearPista(Vector3 a)
    {
        var r = new System.Random();
        int m = 500;

        Punto[] puntos = new Punto[m];
        Punto   Centro = new Punto(a.x, a.z);


        for (int i = 0; i < m; i++)
        {
            //COORDENADAS POLARES argumentos en radianes
            puntos[i]    = new Punto(125 * UnityEngine.Random.value, UnityEngine.Random.value * 2 * Mathf.PI, 1);
            puntos[i].x += Centro.x;
            puntos[i].y += Centro.y;
        }
        List <Punto> l = new List <Punto>();

        for (int i = 0; i < puntos.Length; i++)
        {
            l.Add(puntos[i]);
        }
        l.Add(puntos[0]);
        puntos = l.ToArray();
        ConvexHull   ch = new ConvexHull();
        List <float> ll = new List <float>();

        for (int i = 0; i < puntos.Length; i++)
        {
            ll.Add(puntos[i].x);
            ll.Add(puntos[i].y);
        }
        FloatArray fa       = new FloatArray(ll.ToArray());
        FloatArray contorno = ch.computePolygon(fa, false);


        float[] xx;
        float[] yy;
        float[] xs, ys;

        desglosarFloatArrayEnVectoresNormales(contorno, out xx, out yy);
        Punto[] convexo = Punto.CrearArregloDesdeArreglos(xx, yy);



        ////////////////////////////////////// AGREGAR DIFICULTAD
        float ancho = UnityEngine.Random.Range(5f, 9f);

        ancho = (isSeguidorDeLinea) ? ancho / 3 : ancho;
        Punto[] convexo2 = new Punto[convexo.Length * 2];
        if (isDeforme)
        {
            deformar(ref convexo);
        }

        separarPuntos(ref convexo);

        xx = Punto.getAbscisas(convexo);

        yy = Punto.getOrdenadas(convexo);

        CubicSpline.FitParametric(xx, yy, n, out xs, out ys, 1, -1, 1, -1);

        /////////////////////////////////////////////////////////////////////////

        /*
         * en xs y en ys estan las posiciones x,y de cada punto de la pista
         */



        LS.Add(Instantiate(this.suelo, new Vector3(0, -1, 0), Quaternion.Euler(Vector3.zero), this.transform));
        float[] angulosEnGrados = new float[n];

        for (int i = 0; i < xs.Length - 1; i++)
        {
            angulosEnGrados[i] = 180 * Mathf.Atan2(ys[i + 1] - ys[i], -xs[i + 1] + xs[i]) / Mathf.PI;
        }

        IList <Punto> listaRoja  = new List <Punto>();
        IList <Punto> listaBuena = new List <Punto>();

        Punto[] puntosInteriores;
        Punto[] puntosLinea;

        int        offset = r.Next();
        Vector3    pos, pos2 = new Vector3();
        Quaternion rot;
        float      offsetPos;
        float      offsetBuenas;// = UnityEngine.Random.Range(0.5f, ancho - 0.5f);

        for (int i = 0; i < xs.Length - 1; i++)
        {
            pos = new Vector3(xs[i], 0, ys[i]);
            rot = Quaternion.Euler(0, angulosEnGrados[i], 0);
            pared.transform.position = pos;
            pared.transform.rotation = rot;
            LPA.Add(Instantiate(pared, pos, rot, this.transform));
            if (isSeguidorDeLinea)
            {
                offsetBuenas = ancho / 4 * Mathf.Sin(i / n) - ancho / 4;
                pared.transform.Translate((ancho / 2 - offsetBuenas) * -Vector3.back, Space.Self);
                listaBuena.Add(new Punto(pared.transform.position));
                pared.transform.Translate((ancho - offsetBuenas) * -Vector3.back, Space.Self);
            }
            if (i % 10 == 0)
            {
                offsetPos = UnityEngine.Random.Range(0, ancho / 2);
                pared.transform.Translate(offsetPos * -Vector3.back, Space.Self);
                pos2 = pared.transform.position;
                pared.transform.Translate((ancho - offsetPos) * -Vector3.back, Space.Self);
                listaRoja.Add(new Punto(pared.transform.position));
            }
            else
            {
                pared.transform.Translate((ancho) * -Vector3.back, Space.Self);
                listaRoja.Add(new Punto(pared.transform.position));
            }

            if (i % 5 == 0)
            {
                pared.transform.Translate(ancho / 2 * Vector3.back, Space.Self);
                checkpoint.transform.rotation   = Quaternion.Euler(0, angulosEnGrados[i], 0);
                checkpoint.transform.position   = pared.transform.position;
                checkpoint.transform.localScale = new Vector3(0.1f, checkpoint.transform.localScale.y, ancho);
                LCH.Add(Instantiate(checkpoint, pared.transform.position, Quaternion.Euler(0, angulosEnGrados[i], 0), this.transform));
            }
            if ((UnityEngine.Random.value > 0.65f) && !isSeguidorDeLinea)
            {
                powerUp.transform.position = pos;
                powerUp.transform.rotation = rot;
                powerUp.transform.Translate(UnityEngine.Random.Range(1, ancho - 1) * Vector3.forward, Space.Self);
                LPU.Add(Instantiate(powerUp, this.transform));
            }
            if (isObstaculos)
            {
                if (UnityEngine.Random.value > 0.988f)
                {
                    obstaculo.transform.position = pos;
                    obstaculo.transform.rotation = rot;
                    obstaculo.transform.Translate(UnityEngine.Random.Range(1, ancho - 1) * Vector3.forward, Space.Self);
                    LO.Add(Instantiate(obstaculo, this.transform));
                }
            }
            posIni[i / (EvolutionManager.CarCount / 10)] = pos2;
            EvolutionManager.ini = posIni[i / (EvolutionManager.CarCount / 10)];
        }


        puntosLinea = listaBuena.ToArray();

        if (listaBuena.Count > 0)
        {
            puntosLinea[puntosLinea.Length - 1] = puntosLinea[0];
            arreglarAngulos(ref puntosLinea);
        }
        puntosInteriores = listaRoja.ToArray();
        puntosInteriores[puntosInteriores.Length - 1] = puntosInteriores[0];
        arreglarAngulos(ref puntosInteriores);

        float[] xx2, xx3;
        float[] yy2, yy3;
        float[] xs2, ys2, xs3, ys3;
        float[] angulosEnGrados2 = new float[n2];
        float[] angulosEnGrados3 = new float[n2];
        xx2 = Punto.getAbscisas(puntosInteriores);
        yy2 = Punto.getOrdenadas(puntosInteriores);


        if (isSeguidorDeLinea)
        {
            xx3 = Punto.getAbscisas(puntosLinea);
            yy3 = Punto.getOrdenadas(puntosLinea);
            CubicSpline.FitParametric(xx3, yy3, n2, out xs3, out ys3, 1, -1, 1, -1);
            for (int i = 0; i < xx3.Length; i++)
            {
                angulosEnGrados3[i] = 180 * Mathf.Atan2(ys3[i + 1] - ys3[i], -xs3[i + 1] + xs3[i]) / Mathf.PI;

                Linea.transform.rotation = Quaternion.Euler(0, angulosEnGrados3[i], 0);
                Linea.transform.position = new Vector3(xs3[i], 0, ys3[i]);
                LB.Add(Instantiate(Linea, new Vector3(xs3[i], 0, ys3[i]), Quaternion.Euler(0, angulosEnGrados3[i], 0), this.transform));
            }
        }

        CubicSpline.FitParametric(xx2, yy2, n2, out xs2, out ys2, 1, -1, 1, -1);


        for (int i = 0; i < xs2.Length - 1; i++)
        {
            angulosEnGrados2[i] = 180 * Mathf.Atan2(ys2[i + 1] - ys2[i], -xs2[i + 1] + xs2[i]) / Mathf.PI;
        }

        for (int i = 0; i < xs2.Length - 1; i++)
        {
            paredRoja.transform.rotation = Quaternion.Euler(0, angulosEnGrados2[i], 0);
            paredRoja.transform.position = new Vector3(xs2[i], 0, ys2[i]);
            LPR.Add(Instantiate(paredRoja, new Vector3(xs2[i], 0, ys2[i]), Quaternion.Euler(0, angulosEnGrados2[i], 0), this.transform));
        }
    }
Пример #26
0
 private void Start()
 {
     this.spline = new CubicSpline(this.points, this.segment, this.Smoothness, true);
 }
Пример #27
0
 public void FewSamples()
 {
     Assert.That(() => CubicSpline.InterpolateAkima(new double[0], new double[0]), Throws.ArgumentException);
     Assert.That(() => CubicSpline.InterpolateAkima(new double[4], new double[4]), Throws.ArgumentException);
     Assert.That(CubicSpline.InterpolateAkima(new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }, new[] { 2.0, 2.0, 2.0, 2.0, 2.0 }).Interpolate(1.0), Is.EqualTo(2.0));
 }
        /// <summary>
        ///     Gets the charge state (determined by AutoCorrelation algorithm) for a peak in some data.
        /// </summary>
        /// <param name="peak">is the peak whose charge we want to detect.</param>
        /// <param name="peakData">is the PeakData object containing raw data, peaks, etc which are used in the process.</param>
        /// <returns>Returns the charge of the feature.</returns>
        public static int GetChargeState(ThrashV1Peak peak, PeakData peakData, bool debug)
        {
            var minus      = 0.1;
            var plus       = 1.1; // right direction to look
            var startIndex = PeakIndex.GetNearest(peakData.MzList, peak.Mz - peak.FWHM - minus, peak.DataIndex);
            var stopIndex  = PeakIndex.GetNearest(peakData.MzList, peak.Mz + peak.FWHM + plus, peak.DataIndex);
            var numPts     = stopIndex - startIndex;
            var numL       = numPts;

            if (numPts < 5)
            {
                return(-1);
            }

            if (numPts < 256)
            {
                numL = 10 * numPts;
            }

            // TODO: PattersonChargeStateCalculator does a lot of funny stuff around here.
            // variable to help us perform spline interpolation.
            // count is stopIndex - startIndex + 1 because we need to include the values at stopIndex as well
            // NOTE: This output is different from what the DeconEngineV2 code outputs; there are notes in that code
            //    wondering if there was a bug in the previous implementation imported from VB, of starting at startIndex + 1.
            //    That code performed interpolation on the range from startIndex + 1 to stopIndex, inclusive, and minMz set to PeakData.MzList[startIndex + 1].
            //    This code can produce output that more closely matches the DeconEngineV2 output by using
            //    "startIndex, stopIndex - startIndex + 2" as the parameters to "GetRange()", and setting minMz to PeakData.MzList[startIndex + 1].
            //    Since using startIndex and stopIndex directly produces output that mostly differs on fit score by a small amount,
            //    we are changing this code to use them.
            var interpolator = CubicSpline.InterpolateNaturalSorted(
                peakData.MzList.GetRange(startIndex, stopIndex - startIndex + 1).ToArray(),
                peakData.IntensityList.GetRange(startIndex, stopIndex - startIndex + 1).ToArray());

            var minMz = peakData.MzList[startIndex];
            var maxMz = peakData.MzList[stopIndex];

            // List to store the interpolated intensities of the region on which we performed the cubic spline interpolation.
            var iv = new List <double>(numL);

            for (var i = 0; i < numL; i++)
            {
                var xVal = minMz + (maxMz - minMz) * i / numL;
                var fVal = interpolator.Interpolate(xVal);
                iv.Add(fVal);
            }

            if (debug)
            {
                Console.Error.WriteLine("mz,intensity");
                for (var i = 0; i < numL; i++)
                {
                    var xVal = minMz + (maxMz - minMz) * i / numL;
                    Console.Error.WriteLine(xVal + "," + iv[i]);
                }
            }

            // List to store the autocorrelation values at the points in the region.
            var autocorrelationScores = ACss(iv.ToArray());

            if (debug)
            {
                Console.Error.WriteLine("AutoCorrelation values");
                for (var i = 0; i < autocorrelationScores.Count; i++)
                {
                    var score = autocorrelationScores[i];
                    Console.Error.WriteLine((maxMz - minMz) * i / numL + "," + score);
                }
            }

            var minN = 0;

            while (minN < numL - 1 && autocorrelationScores[minN] > autocorrelationScores[minN + 1])
            {
                minN++;
            }

            // Determine the highest CS peak
            double bestAcScore;
            int    bestChargeState;
            var    success = HighestChargeStatePeak(minMz, maxMz, minN, autocorrelationScores, MaxCharge, out bestAcScore,
                                                    out bestChargeState);

            if (!success)
            {
                return(-1); // Didn't find anything
            }
            // List to temporarily store charge list. These charges are calculated at peak values of autocorrelation.
            // Now go back through the CS peaks and make a list of all CS that are at least 10% of the highest
            var charges = GenerateChargeStates(minMz, maxMz, minN, autocorrelationScores, MaxCharge, bestAcScore);

            // Get the final CS value to be returned
            var returnChargeStateVal = -1;
            // TODO: PattersonChargeStateCalculator really doesn't match the following code.
            var fwhm = peak.FWHM; // Store a copy of the FWHM to avoid modifying the actual value

            if (fwhm > 0.1)
            {
                fwhm = 0.1;
            }

            for (var i = 0; i < charges.Count; i++)
            {
                // no point retesting previous charge.
                var tempChargeState = charges[i];
                var skip            = false;
                for (var j = 0; j < i; j++)
                {
                    if (charges[j] == tempChargeState)
                    {
                        skip = true;
                        break;
                    }
                }
                if (skip)
                {
                    continue;
                }
                if (tempChargeState > 0)
                {
                    var          peakA = peak.Mz + 1.0 / tempChargeState;
                    var          found = true;
                    ThrashV1Peak isoPeak;
                    found = peakData.GetPeakFromAllOriginalIntensity(peakA - fwhm, peakA + fwhm, out isoPeak);
                    if (found)
                    {
                        returnChargeStateVal = tempChargeState;
                        if (isoPeak.Mz * tempChargeState < 3000)
                        {
                            break;
                        }
                        // if the mass is greater than 3000, lets make sure that multiple isotopes exist.
                        peakA = peak.Mz - 1.03 / tempChargeState;
                        found = peakData.GetPeakFromAllOriginalIntensity(peakA - fwhm, peakA + fwhm, out isoPeak);
                        if (found)
                        {
                            return(tempChargeState);
                        }
                    }
                    else
                    {
                        peakA = peak.Mz - 1.0 / tempChargeState;
                        found = peakData.GetPeakFromAllOriginalIntensity(peakA - fwhm, peakA + fwhm, out isoPeak);
                        if (found && isoPeak.Mz * tempChargeState < 3000)
                        {
                            return(tempChargeState);
                        }
                    }
                }
            }
            return(returnChargeStateVal);
        }
 public virtual double Interpolate_CubicSpline(double[] x, double[] y, double xValue)
 {
     return(CubicSpline.InterpolateAkima(x, y).Interpolate(xValue));
 }
Пример #30
0
        public Vector <double>[] bvpsolver_zzz(Func <double, Vector <double>, Vector <double> > system,
                                               double ya, double yb,
                                               double xa, double xb,
                                               int N)
        {
            //先求解方程得到初始斜率的估计值,再进行打靶法迭代。--zzz
            Vector <double>[] res;
            Vector <double>   y0;

            double s_guess, s_guess_pre;
            double fais, fais_pre;
            double dfai, ds;
            int    count = 0;

            //计算20组s_guess和fais,然后样条插值得到连续函数,再通过解方程,得到使fais=0的初始s_guess
            int M = 50;

            double[] sLst = Vector <double> .Build.Dense(M, i => yb / M *i).ToArray();

            double[] faisLst = new double[M];
            count = 0;
            while (count < M)
            {
                y0 = Vector <double> .Build.DenseOfArray(new[] { ya, sLst[count] });

                // observer_pr ob_pr = this->write_targetFunc_end;
                res            = RungeKutta.FourthOrder(y0, xa, xb, N, system);
                faisLst[count] = res[N - 1][0] - yb;
                count++;
            }
            //样条插值得到连续函数
            var cubicSpl = CubicSpline.InterpolateNatural(sLst, faisLst);

            /*如果初始值离解太远,牛顿法会不收敛。故采用Mathnet包中的RobustNewtonRaphson
             * double s_cur = 0, s_next;
             * count = 0;
             * while (count < 1000)
             * {
             *  fais = cubicSpl.Interpolate(s_cur);
             *  dfaids = cubicSpl.Differentiate(s_cur);
             *  if (fais < 1e-5 && fais > -1e-5)
             *  {
             *      break;
             *  }
             *
             *  s_next = s_cur - fais / dfaids;
             *  s_cur = s_next;
             *  count += 1;
             * }*/

            //解方程fais=0,得到初始斜率s_guess。该法先尝试牛顿法,如失败会采用二分法(bisection)。
            s_guess = RobustNewtonRaphson.FindRoot(cubicSpl.Interpolate, cubicSpl.Differentiate, 0, yb, 1e-5);

            //利用解得的s_guess,构造s_guess_pre,目的是求导数dfai/ds。
            if (s_guess == 0)
            {
                s_guess_pre = 1e-2;
            }
            else
            {
                s_guess_pre = s_guess * 0.99;
            }
            //求s_guess_pre对应的fais_pre,目的是求导数dfai/ds。
            y0 = Vector <double> .Build.DenseOfArray(new[] { ya, s_guess_pre });

            res      = RungeKutta.FourthOrder(y0, xa, xb, N, system);
            fais_pre = res[N - 1][0] - yb;

            count = 0;
            while (count < 50)
            {
                y0 = Vector <double> .Build.DenseOfArray(new[] { ya, s_guess });

                res  = RungeKutta.FourthOrder(y0, xa, xb, N, system);
                fais = res[N - 1][0] - yb;

                dfai = fais - fais_pre;
                ds   = s_guess - s_guess_pre;
                if (fais < 1e-5 && fais > -1e-5)
                {
                    break;
                }

                fais_pre    = fais;
                s_guess_pre = s_guess;
                s_guess     = s_guess - fais * ds / dfai;
                count++;
            }

            return(res);
        }
Пример #31
0
        public void FixedSecondDerivativeFitsAtArbitraryPoints(double t, double x, double maxAbsoluteError)
        {
            IInterpolation it = CubicSpline.InterpolateBoundaries(_t, _y, SplineBoundaryCondition.SecondDerivative, -5.0, SplineBoundaryCondition.SecondDerivative, -1.0);

            Assert.AreEqual(x, it.Interpolate(t), maxAbsoluteError, "Interpolation at {0}", t);
        }
Пример #32
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello, World!");

                        DoubleArray ee = ArrayRandom.RandomDoubleArray(4096);
            DoubleArray ef = ArrayRandom.RandomDoubleArray(4096);

            TimeSeries myTimeSeries = new TimeSeries(ef,ee);

            TimeSeries myOtherTimeSeries = myTimeSeries;

            myTimeSeries.x = ef;

            myTimeSeries.plot();

            System.Console.WriteLine(myOtherTimeSeries.x);

               // IFigure f2 = ShoPlotHelper.Figure();

            System.Console.WriteLine("Starting Slow");
            System.Console.WriteLine(DateTime.Now);
            ArraySettings.DisableFastMath();
            DoubleArray b = ArrayRandom.RandomDoubleArray(4096);
            DoubleArray a = ArrayRandom.RandomDoubleArray(1024);

            for (int i = 0; i < 100; i++)
            {
                DoubleArray c = ConvComp.Conv(b, a);
                //System.Console.WriteLine(i);
            }
            System.Console.WriteLine(DateTime.Now);

            System.Console.WriteLine("Starting Fast");
            System.Console.WriteLine(DateTime.Now);
            ArraySettings.EnableFastMath();

            CubicSpline cs = new CubicSpline();
            DoubleArray d = ArrayRandom.RandomDoubleArray(4096);
            DoubleArray e = ArrayRandom.RandomDoubleArray(4096);
            DoubleArray g = d.Sort(); cs.Fit(g, e);
            DoubleArray h = cs.Interp(g);
            for (int i = 0; i < 10000; i++)
            {
                //DoubleArray f = ConvComp.Conv(d, e);

                //cs.Fit(g, e);
                 h = cs.Interp(g);
            }

            System.Console.WriteLine(DateTime.Now);
            System.Console.WriteLine("Bye, World!");
        }
Пример #33
0
        public void NaturalFitsAtArbitraryPoints(double t, double x, double maxAbsoluteError)
        {
            IInterpolation it = CubicSpline.InterpolateNatural(_t, _y);

            Assert.AreEqual(x, it.Interpolate(t), maxAbsoluteError, "Interpolation at {0}", t);
        }
Пример #34
0
        /// <summary>
        /// Creates a spline for each of x and y parameterized with the fraction of progress toward the end point
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="xSpline"></param>
        /// <param name="ySpline"></param>
        public static void CreateParameterizedSplines(Point start, Point end, out CubicSpline xSpline, out CubicSpline ySpline)
        {
            const double randomization       = 0.05;
            const int    maxRandomAllowed    = 50;
            const double newMidPointDistance = 1000.0;
            int          xRandomization      = Math.Min(maxRandomAllowed, Math.Abs((int)(randomization * (end.Y - start.Y))));
            int          yRandomization      = Math.Min(maxRandomAllowed, Math.Abs((int)(randomization * (end.X - start.X))));
            double       moveDistance        = Geometry.DistanceBetweenPoints(start, end);
            int          midPoints           = 1 + (int)(moveDistance / newMidPointDistance);

            xSpline = new CubicSpline(new Point(0, start.X), new Point(1, end.X), 0, xRandomization, midPoints);
            ySpline = new CubicSpline(new Point(0, start.Y), new Point(1, end.Y), 0, yRandomization, midPoints);
        }