Exemplo n.º 1
0
        private static InterpolationTypes GetSmartType(float from, float to, InterpolationTypes type)
        {
            switch (type)
            {
            case InterpolationTypes.SmartSquared:
                //Debug.LogFormat("Determining Smart type for {0} -> {1}: '{2}' -> '{3}'!", from, to, type,
                //    to > from ? InterpolationTypes.Squared : InterpolationTypes.InverseSquared);
                return(to > from ? InterpolationTypes.Squared : InterpolationTypes.InverseSquared);

            case InterpolationTypes.SmartInverseSquared:
                //Debug.LogFormat("Determining Smart type for {0} -> {1}: '{2}' -> '{3}'!", from, to, type,
                //    to > from ? InterpolationTypes.InverseSquared : InterpolationTypes.Squared);
                return(to > from ? InterpolationTypes.InverseSquared : InterpolationTypes.Squared);

            case InterpolationTypes.SmartCubic:
                //Debug.LogFormat("Determining Smart type for {0} -> {1}: '{2}' -> '{3}'!", from, to, type,
                //    to > from ? InterpolationTypes.Cubic : InterpolationTypes.InverseCubic);
                return(to > from ? InterpolationTypes.Cubic : InterpolationTypes.InverseCubic);

            case InterpolationTypes.SmartInverseCubic:
                //Debug.LogFormat("Determining Smart type for {0} -> {1}: '{2}' -> '{3}'!", from, to, type,
                //    to > from ? InterpolationTypes.InverseCubic : InterpolationTypes.Cubic);
                return(to > from ? InterpolationTypes.InverseCubic : InterpolationTypes.Cubic);

            default:
                return(type);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the appropriate interpolation method based on the InterpolationType passed in.
        /// </summary>
        /// <param name="interpolationType">The InterpolationTypes to get.</param>
        /// <returns>The interpolation method associated with the InterpolationType, otherwise null.</returns>
        private static InterpolationMethod GetInterpolationFromType(InterpolationTypes interpolationType)
        {
            switch (interpolationType)
            {
            case InterpolationTypes.Linear: return(LinearTime);

            case InterpolationTypes.QuadIn: return(EaseInQuadTime);

            case InterpolationTypes.QuadOut: return(EaseOutQuadTime);

            case InterpolationTypes.QuadInOut: return(EaseInOutQuadTime);

            case InterpolationTypes.CubicIn: return(EaseInCubicTime);

            case InterpolationTypes.CubicOut: return(EaseOutCubicTime);

            case InterpolationTypes.CubicInOut: return(EaseInOutCubicTime);

            case InterpolationTypes.ExponentialIn: return(EaseInExponentialTime);

            case InterpolationTypes.ExponentialOut: return(EaseOutExponentialTime);

            case InterpolationTypes.ExponentialInOut: return(EaseInOutExponentialTime);

            case InterpolationTypes.SineIn: return(EaseInSineTime);

            case InterpolationTypes.SineOut: return(EaseOutSineTime);

            case InterpolationTypes.SineInOut: return(EaseInOutSineTime);

            default: return(null);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Apply the given interpolation to the value t (range 0 to 1) a given number of times.
        /// </summary>
        /// <param name="t">The interpolation value (range 0 to 1)</param>
        /// <param name="type">The interpolation to use</param>
        /// <param name="repeats">The amount of times the interpolation will be applied (range 0 to 10)</param>
        /// <returns>The interpolated value (range 0 to 1)</returns>
        public static float ApplyLerpRepeatedly(float t, InterpolationTypes type, int repeats)
        {
            repeats = Mathf.Clamp(repeats, 0, 10);

            for (byte i = 0; i < repeats; i++)
            {
                t = ApplyLerp(t, type);
            }

            return(t);
        }
Exemplo n.º 4
0
        private async void ScaleMenuFlyoutItem_Click(object sender, RoutedEventArgs e)
        {
            AddToUndo(WriteableOutputImage.Clone());

            ScaleImageDialog    dialog = new ScaleImageDialog();
            ContentDialogResult result = await dialog.ShowAsync();

            InterpolationTypes interpolationTypes = dialog.Interpolation;
            double             scale = await dialog.GetScaleValue();

            WriteableOutputImage = BitmapResizeHelper.Resize(WriteableOutputImage, (int)(WriteableOutputImage.PixelWidth * scale), (int)(WriteableOutputImage.PixelHeight * scale), interpolationTypes);

            await UpdateOutputImage();
        }
Exemplo n.º 5
0
    void Update()
    {
        if (InterpolationType != _LastInterpolationType)
        {
            SetupInterpolator();
            _LastInterpolationType = InterpolationType;
        }

        if (_Interpolator != null)
        {
            _Interpolator.Update(Time.time);
            var point = _Interpolator.GetDataPoint(Time.time - Delay);
            ObjectToMove.position = point;
        }
    }
Exemplo n.º 6
0
        internal static NativeMethods.InterpolationTypes ToNativeInterpolationTypes(this InterpolationTypes interpolationTypes)
        {
            switch (interpolationTypes)
            {
            case InterpolationTypes.NearestNeighbor:
                return(NativeMethods.InterpolationTypes.NearestNeighbor);

            case InterpolationTypes.Bilinear:
                return(NativeMethods.InterpolationTypes.Bilinear);

            case InterpolationTypes.Quadratic:
                return(NativeMethods.InterpolationTypes.Quadratic);

            default:
                throw new ArgumentOutOfRangeException(nameof(interpolationTypes), interpolationTypes, null);
            }
        }
Exemplo n.º 7
0
    public Texture2D GetTexture(int width, InterpolationTypes type = InterpolationTypes.Linear)
    {
        Texture2D texture = new Texture2D(width, 1);

        Color[] pixelColors = new Color[width];

        for (int i = 0; i < pixelColors.Length; i++)
        {
            float t = (float)i / (width - 1);
            pixelColors[i] = Evaluate(t, type);
        }

        texture.SetPixels(pixelColors);
        texture.Apply();

        return(texture);
    }
Exemplo n.º 8
0
        // ----------------------------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Apply the given interpolation to the value t (range 0 to 1).
        /// </summary>
        /// <param name="t">The interpolation value (range 0 to 1)</param>
        /// <param name="type">The interpolation to use</param>
        /// <returns>The interpolated value (range 0 to 1)</returns>
        public static float ApplyLerp(float t, InterpolationTypes type)
        {
            t = Mathf.Clamp01(t);
            float i = 1f - t;                                                           // Store inverted t for inverted functions

            // Calculations based on the exmaples avaliable at http://sol.gfxile.net/interpolation/
            switch (type)
            {
            case InterpolationTypes.Linear:
                return(t);

            case InterpolationTypes.Smooth:                                                      // Regular smoothstep
                return(t * t * (3 - 2 * t));

            case InterpolationTypes.Smoother:                                                    // Based on the formula by Ken Perlin.
                return(t = t * t * t * (t * (t * 6 - 15) + 10));

            case InterpolationTypes.Squared:
            case InterpolationTypes.SmartSquared:
                return(t * t);

            case InterpolationTypes.InverseSquared:
            case InterpolationTypes.SmartInverseSquared:
                return(1f - (i * i));

            case InterpolationTypes.Cubic:
            case InterpolationTypes.SmartCubic:
                return(t * t * t);

            case InterpolationTypes.InverseCubic:
            case InterpolationTypes.SmartInverseCubic:
                return(1f - (i * i * i));

            case InterpolationTypes.Sin:
                return(t * (Mathf.PI / 2f));

            case InterpolationTypes.InverseSin:
                return(1f - (i * (Mathf.PI / 2f)));

            default:
                Debug.LogWarningFormat("Unhandled LerpType '{0}' requested!", type);
                return(t);
            }
        }
Exemplo n.º 9
0
    void Start()
    {
        var options = System.Enum.GetValues(typeof(InterpolationTypes)).Cast <int>();

        InterpolationTypeDropDown.AddOptions(options.Select(e => ((InterpolationTypes)e).ToString()).ToList());
        InterpolationTypeDropDown.value = (int)InterpolationType;

        InterpolationTypeDropDown.onValueChanged.AddListener((value) => InterpolationType = (InterpolationTypes)value);

        DelayInput.text            = Delay.ToString();
        HistoryLengthInput.text    = HistoryLength.ToString();
        MaxExtrapolationInput.text = MaxExtrapolation.ToString();

        DelayInput.onValueChanged.AddListener((value) => Delay = float.Parse(value));
        HistoryLengthInput.onValueChanged.AddListener((value) => HistoryLength       = float.Parse(value));
        MaxExtrapolationInput.onValueChanged.AddListener((value) => MaxExtrapolation = float.Parse(value));

        SetupInterpolator();
        NetworkSimulator.SetPackageListener(OnPackage);
    }
Exemplo n.º 10
0
    void DrawSettingsBlock()
    {
        Rect rect = new Rect(borderSize, gradientTexHeight * 2 + borderSize, _gradientPreviewTexRect.width, _gradientPreviewTexRect.height * 2);

        GUILayout.BeginArea(rect);

        EditorGUI.BeginChangeCheck();
        Color selectedKeyColor = (_currentlySelected == null) ? Color.white : _currentlySelected.BoundKey.Color;
        Color color            = EditorGUILayout.ColorField(selectedKeyColor);

        if (EditorGUI.EndChangeCheck())
        {
            _currentlySelected.BoundKey.Color = color;
            GUI.changed = true;
        }

        EditorGUI.BeginChangeCheck();
        InterpolationTypes selectedType = (InterpolationTypes)EditorGUILayout.EnumPopup(_gradient.interpolationTypes);

        if (EditorGUI.EndChangeCheck())
        {
            _type       = selectedType;
            GUI.changed = true;
        }

        if (GUILayout.Button("Save as PNG"))
        {
            Texture2D texture  = _gradient.GetTexture(64, _type);
            byte[]    bytes    = texture.EncodeToPNG();
            string    fileName = string.Format("Gradient{0}x{1}.png", texture.width, texture.height);
            string    filePath = string.Format(@"{0}/{1}/", Application.dataPath, "Textures");

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            File.WriteAllBytes(filePath + fileName, bytes);
        }

        GUILayout.EndArea();
    }
Exemplo n.º 11
0
    Color Evaluate(float time, InterpolationTypes type)
    {
        int ti = 0;

        for (int i = 0; i < ColorKeys.Count - 1; i++)
        {
            if ((time >= ColorKeys[i].Time) && (time <= ColorKeys[i + 1].Time))
            {
                ti = i;
                break;
            }
        }

        Color color = new Color();

        switch (type)
        {
        case (InterpolationTypes.ConstantMin):
        {
            color = ColorKeys[ti].Color;

            break;
        }

        case (InterpolationTypes.Linear):
        {
            // InverseLerp: (t - ti) / (tii - ti)
            float localTime = Mathf.InverseLerp(ColorKeys[ti].Time, ColorKeys[ti + 1].Time, time);
            color = Color.Lerp(ColorKeys[ti].Color, ColorKeys[ti + 1].Color, localTime);

            break;
        }
        }

        return(color);
    }
Exemplo n.º 12
0
        public static void ResizeImage <T>(Matrix <T> src, Matrix <T> dst, InterpolationTypes interpolationTypes = InterpolationTypes.Bilinear)
            where T : struct
        {
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }

            src.ThrowIfDisposed(nameof(src));
            dst.ThrowIfDisposed(nameof(dst));

            var templateRows    = (uint)src.TemplateRows;
            var templateColumns = (uint)src.TemplateColumns;

            if (templateRows != dst.TemplateRows || templateColumns != dst.TemplateColumns)
            {
                throw new ArgumentException();
            }

            var inType = src.MatrixElementType.ToNativeMatrixElementType();
            var ret    = NativeMethods.resize_image_matrix(inType,
                                                           src.NativePtr,
                                                           templateRows,
                                                           templateColumns,
                                                           dst.NativePtr,
                                                           interpolationTypes.ToNativeInterpolationTypes());

            switch (ret)
            {
            case NativeMethods.ErrorType.MatrixElementTemplateSizeNotSupport:
                throw new ArgumentException($"{nameof(src.TemplateColumns)} or {nameof(src.TemplateRows)} is not supported.");

            case NativeMethods.ErrorType.MatrixElementTypeNotSupport:
                throw new ArgumentException($"{src.MatrixElementType} is not supported.");
            }
        }
Exemplo n.º 13
0
        public SoftwareFCurve(RMX_ActionFCurve fcurve)
        {
            switch (fcurve.Type)
            {
            case "OBJECT": Type = FCurveTypes.Object; break;

            case "BONE": Type = FCurveTypes.Bone; break;

            default: Debug.ThrowError("", "Unsuported type: " + fcurve.Type); break;
            }

            DataPath = fcurve.DataPath;
            Index    = fcurve.Index;

            var values = fcurve.Coordinates.Values;
            var types  = fcurve.InterpolationTypes.Content;

            KeyFrames = new List <SoftwareKeyFrame>();
            int i2 = 0, loop = values.Length / 2;

            for (int i = 0; i != loop; ++i)
            {
                InterpolationTypes interpolationType = InterpolationTypes.Bezier;
                switch (types[i])
                {
                case 'B': interpolationType = InterpolationTypes.Bezier; break;

                case 'L': interpolationType = InterpolationTypes.Linear; break;

                case 'C': interpolationType = InterpolationTypes.Constant; break;
                }

                KeyFrames.Add(new SoftwareKeyFrame(new Vector2(values[i2], values[i2 + 1]), interpolationType));
                i2 += 2;
            }
        }
Exemplo n.º 14
0
 //------------------------------------------------------------------------------------------------
 public FuturesSeriesBuilder(List<string> tickers, List<DateTime> daterange, List<DateTime> holidays,
                             string futuresStaticMoniker, ICarbonClient client, string carbonEnv = "PRD", 
                             RollMethods rollMthd = RollMethods.FirstNoticeDate,
                             InterpolationTypes interpType = InterpolationTypes.None,
                             List<string> contractSortOrder = null,
                             Dictionary<string,DateTime> rollmap = null, 
                             SmoothingTypes smoothingType = SmoothingTypes.None)
 //------------------------------------------------------------------------------------------------
 {
     initFutureSeriesBuilder(tickers, daterange, holidays, futuresStaticMoniker, client, carbonEnv, rollMthd, interpType, contractSortOrder, rollmap, smoothingType);
    
 }
Exemplo n.º 15
0
        // Allows intialisation code reuse
        //------------------------------------------------------------------------------------------------
        private void initFutureSeriesBuilder(List<string> tickers, List<DateTime> daterange, List<DateTime> holidays,
                                             string futuresStaticMoniker, ICarbonClient client, string carbonEnv = "PRD", 
                                             RollMethods rolMthd = RollMethods.FirstNoticeDate,
                                             InterpolationTypes interpType = InterpolationTypes.None,
                                             List<string> contractSortOrder = null ,
                                             Dictionary<string,DateTime> rollmap = null,
                                             SmoothingTypes smoothingType = SmoothingTypes.None)
        //------------------------------------------------------------------------------------------------
        {
            // defaults
            dateRange_ = daterange;
            startDate_ = daterange.Min();
            endDate_ = daterange.Max();
            carbonEnv_ = carbonEnv;
            rollMethod_ = rolMthd; //RollMethods.LastTradeDate; //
            holidays_ = holidays;
            futuresStaticMoniker_ = futuresStaticMoniker;
            interpType_ = interpType;
            smoothingType_ = smoothingType;

            if (contractSortOrder == null)
            {
                contractSortOrder_ = new List<string>();
            }
            else
            {
                contractSortOrder_ = contractSortOrder;
            }

            if (rolMthd == RollMethods.Custom && rollmap == null)
            {
                throw new ArgumentException("Custom roll dates required for custom rolls!");
            }

            ContractMonthLookupTable_ = new Dictionary<ContractMonths, string>
            {
                {ContractMonths.PrevFrontMonth, "PrevFront"},
                {ContractMonths.FrontMonth, "Front"},
                {ContractMonths.BackMonth, "Back"},
                {ContractMonths.SecondBackMonth, "SecondBack"}
            };

            Tuple<List<Tuple<string, ContractMonths>> /*rootTickers*/, List<string> /*contracts*/> tickerListTuple;

            // Get Static
            FuturesStatic = getFuturesStatic(tickers, futuresStaticMoniker, client, carbonEnv, out tickerListTuple, startDate_, endDate_, contractSortOrder_);

            // Add custom roll if present
            if (rollmap != null)
            {
                var sb = new SeriesBuilder<string,DateTime>();
                foreach (var kvp in rollmap)
                {
                    sb.Add(kvp.Key, kvp.Value);
                }
                FuturesStatic.AddColumn("custom_roll", sb.Series);
            }
            inputTickers_           = tickers;
            contractTickers_        = tickerListTuple.Item2;
            RollingContractSpecs_   = tickerListTuple.Item1;
            var contracts = FuturesStatic.RowKeys.ToList(); // get all the tickers (in case no tickers supplied

            // Get prices
            Console.WriteLine("Getting Futures prices");
            RawFuturesPrices = getAllFuturesPricesInDateRange(contracts, startDate_, endDate_, client);
            RawFuturesPrices.Print();

            // Align Futures Prices & interpolate gaps
            alignRawPriceFrameWithDateRange(dateRange_);
            //interpolateRawPriceFrame(interpType_);
        }
Exemplo n.º 16
0
 public SoftwareKeyFrame(Vector2 cordinate, InterpolationTypes interpolationType)
 {
     Cordinate = cordinate;
     InterpolationType = interpolationType;
 }
Exemplo n.º 17
0
        public static Array2D <T> ExtractImageChip <T>(Array2DBase image, ChipDetails chipLocation, InterpolationTypes type = InterpolationTypes.Bilinear)
            where T : struct
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            if (chipLocation == null)
            {
                throw new ArgumentNullException(nameof(chipLocation));
            }

            image.ThrowIfDisposed();
            chipLocation.ThrowIfDisposed();

            if (!chipLocation.IsValid())
            {
                throw new ArgumentException($"{nameof(chipLocation)} is invalid item.");
            }

            var chip        = new Array2D <T>();
            var array2DType = image.ImageType.ToNativeArray2DType();
            var ret         = NativeMethods.extract_image_chip2(array2DType,
                                                                image.NativePtr,
                                                                chipLocation.NativePtr,
                                                                chip.ImageType.ToNativeArray2DType(),
                                                                type.ToNativeInterpolationTypes(),
                                                                chip.NativePtr);

            switch (ret)
            {
            case NativeMethods.ErrorType.Array2DTypeTypeNotSupport:
                throw new ArgumentException("Output or input type is not supported.");
            }

            return(chip);
        }
Exemplo n.º 18
0
 public static extern ErrorType extract_image_chip_matrix2(MatrixElementType img_type, IntPtr in_img, IntPtr chip_location, MatrixElementType array_type, InterpolationTypes type, IntPtr out_chip);
Exemplo n.º 19
0
 public static extern ErrorType transform_image(Array2DType inType, IntPtr inImg, Array2DType outType, IntPtr outImg, PointMappingTypes pointMappingTypes, IntPtr mappingObj, InterpolationTypes interpolationTypes);
Exemplo n.º 20
0
 public static extern ErrorType resize_image2(Array2DType inType, IntPtr inImg, Array2DType outType, IntPtr outImg, InterpolationTypes interpolationTypes);
Exemplo n.º 21
0
        public static void RotateImage(Array2DBase inputImage, Array2DBase outputImage, double angle, InterpolationTypes interpolationTypes = InterpolationTypes.Quadratic)
        {
            if (inputImage == null)
            {
                throw new ArgumentNullException(nameof(inputImage));
            }
            if (outputImage == null)
            {
                throw new ArgumentNullException(nameof(outputImage));
            }
            if (inputImage == outputImage)
            {
                throw new ArgumentException();
            }

            inputImage.ThrowIfDisposed(nameof(inputImage));
            outputImage.ThrowIfDisposed(nameof(outputImage));

            var inType  = inputImage.ImageType.ToNativeArray2DType();
            var outType = outputImage.ImageType.ToNativeArray2DType();
            var ret     = NativeMethods.rotate_image2(inType, inputImage.NativePtr, outType, outputImage.NativePtr, angle, interpolationTypes.ToNativeInterpolationTypes());

            switch (ret)
            {
            case NativeMethods.ErrorType.Array2DTypeTypeNotSupport:
                throw new ArgumentException("Output or input type is not supported.");
            }
        }
Exemplo n.º 22
0
        public static Matrix <T> ResizeImage <T>(Matrix <T> matrix, uint row, uint column, InterpolationTypes interpolationTypes = InterpolationTypes.Bilinear)
            where T : struct
        {
            if (matrix == null)
            {
                throw new ArgumentNullException(nameof(matrix));
            }

            matrix.ThrowIfDisposed(nameof(matrix));

            var templateRows    = (uint)matrix.TemplateRows;
            var templateColumns = (uint)matrix.Columns;

            var result = Matrix <T> .CreateTemplateParameterizeMatrix(templateRows, templateColumns);

            result.SetSize((int)row, (int)column);

            ResizeImage(matrix, result, interpolationTypes);

            return(result);
        }
Exemplo n.º 23
0
 public KeyFrame(BinaryReader reader)
 {
     Cordinate         = reader.ReadVector2();
     InterpolationType = (InterpolationTypes)reader.ReadInt32();
 }
Exemplo n.º 24
0
 private void SetCurveTypeSelector(InterpolationTypes interpolationTypes)
 {
     if (interpolationTypes == InterpolationTypes.None)
     {
         foreach (ToolStripMenuItem item in m_curveTypeSelector.DropDownItems)
             item.Checked = false;
         m_curveTypeSelector.Text = "(Multiple)".Localize("CurveTypeSelector");
     }
     else
     {
         foreach (ToolStripMenuItem item in m_curveTypeSelector.DropDownItems)
         {
             if (((InterpolationTypes)item.Tag == interpolationTypes))
             {
                 item.Checked = true;
                 m_curveTypeSelector.Text = item.Text;
             }
             else
                 item.Checked = false;
         }
     }
 }
Exemplo n.º 25
0
        // ----------------------------------------------------------------------------------------------------------------------------------------------

        #region Lerping

        /// <summary>
        /// Lerp from float a to b by the factor t (range 0 to 1).
        /// Uses smooth (ease-in and -out) interpolation as a default, but supports many different interpolation curves.
        /// </summary>
        /// <param name="from">The start value (t = 0)</param>
        /// <param name="to">The target value (t = 1)</param>
        /// <param name="t">The interpolation value (range 0 to 1)</param>
        /// <param name="type">The interpolation to use</param>
        /// <returns>The interpolated value between from and to.</returns>
        public static float Lerp(float from, float to, float t, InterpolationTypes type = InterpolationTypes.Smooth)
        {
            type = GetSmartType(from, to, type);
            t    = ApplyLerp(t, type);
            return(Mathf.Lerp(from, to, t));
        }
Exemplo n.º 26
0
        public static void ResizeImage(Array2DBase inputImage, Array2DBase outputImage, InterpolationTypes interpolationTypes = InterpolationTypes.Bilinear)
        {
            if (inputImage == null)
            {
                throw new ArgumentNullException(nameof(inputImage));
            }
            if (outputImage == null)
            {
                throw new ArgumentNullException(nameof(outputImage));
            }
            if (inputImage == outputImage)
            {
                throw new ArgumentException();
            }

            inputImage.ThrowIfDisposed(nameof(inputImage));
            outputImage.ThrowIfDisposed(nameof(outputImage));

            var inType  = inputImage.ImageType.ToNativeArray2DType();
            var outType = outputImage.ImageType.ToNativeArray2DType();
            var ret     = Native.resize_image2(inType, inputImage.NativePtr, outType, outputImage.NativePtr, interpolationTypes.ToNativeInterpolationTypes());

            switch (ret)
            {
            case Native.ErrorType.InputArrayTypeNotSupport:
                throw new ArgumentException($"Input {inputImage.ImageType} is not supported.");

            case Native.ErrorType.OutputArrayTypeNotSupport:
                throw new ArgumentException($"Output {outputImage.ImageType} is not supported.");
            }
        }
Exemplo n.º 27
0
        //------------------------------------------------------------------------------------------------
        public Frame<DateTime, string> interpolateRawPriceFrame(Frame<DateTime, string> df, InterpolationTypes interpType)
        //------------------------------------------------------------------------------------------------
        {
            int frameLength = df.RowCount;
            int columnCount = df.ColumnCount;
            var columns = RawFuturesPrices.Columns;

            if (interpType == InterpolationTypes.None) return df;

            Dictionary<string, Series<DateTime, double>> resList = new Dictionary<string, Series<DateTime, double>>();

            foreach (string colName in RawFuturesPrices.ColumnKeys)
            {
                var srs = columns[colName];
                var idx = df.RowKeys.ToList();
                double prev = double.NaN;

                idx.Sort();

                // Find first non-NaN number
                List<int> startIndices  = new List<int>();
                List<int> endIndices    = new List<int>();
                SeriesBuilder<DateTime, double> sb = new SeriesBuilder<DateTime, double>();

                // Forward pass for start idx
                int validIdx = -1;
                for (int i = 0; i < frameLength; ++i)
                {
                    double current = srs.TryGetAs<double>(idx[i]).OrDefault(double.NaN);

                    // Interpolate if missing
                     if (!double.IsNaN(current))
                    {
                        validIdx = i;
                        //continue;
                    }

                    startIndices.Add(validIdx);
                }

                // Backward pass for end idx
                validIdx = -1;
                for (int i = frameLength-1; i >= 0; --i)
                {
                    double current = srs.TryGetAs<double>(idx[i]).OrDefault(double.NaN);

                    // Interpolate if missing
                    if (!double.IsNaN(current))
                    {
                        validIdx = i;
                        //continue;
                    }

                    endIndices.Add(validIdx);
                }

                endIndices.Reverse();
                
                // Run over and do interpolation
                for (int i = 0; i < frameLength; ++i)
                {
                    int startidx        = startIndices[i];
                    int endidx          = endIndices[i];
                    double current      = double.NaN;
                    DateTime dte        = idx[i];

                    // Cases for interpolation....
                    if (startidx == -1)
                    {
                        // Just take last price if it's there
                        if (endidx == -1) continue;
                        else
                        {
                            startidx = endidx;
                        }
                    }

                    if (endidx == -1)
                    {
                        endidx = startidx;
                    }

                    if (startidx == endidx)
                    {
                        current = srs.GetAs<double>(idx[startidx]);
                    }
                    else
                    {
                        switch (interpType)
                        {
                            case InterpolationTypes.Linear:
                                DateTime startDate  = idx[startidx];
                                DateTime endDate    = idx[endidx];
                                double startValue   = srs.GetAs<double>(startDate);
                                double endValue     = srs.GetAs<double>(endDate);

                                current = startValue +
                                          (endValue - startValue)*
                                          (dte - startDate).TotalDays / (endDate - startDate).TotalDays;
                                break;
                            case InterpolationTypes.FlatForward:
                                current  = srs.GetAs<double>(idx[startidx]);
                                break;

                            default:
                                throw new ArgumentException("Illegal interpolation type (we shouldn't be here...)");
                        }
                    }

                    sb.Add(dte, current);
                }
                resList[colName] = sb.Series;
            }

            df = Frame.FromColumns(resList);

            return df;
        }
Exemplo n.º 28
0
 public static extern ErrorType rotate_image2(Array2DType inType, IntPtr inImg, Array2DType outType, IntPtr outImg, double angle, InterpolationTypes interpolationTypes);
Exemplo n.º 29
0
 /// <summary>
 /// Lerp from Vector3 a to b by the factor t (range 0 to 1).
 /// Uses smooth (ease-in and -out) interpolation as a default, but supports many different interpolation curves.
 /// </summary>
 /// <param name="from">The start value (t = 0)</param>
 /// <param name="to">The target value (t = 1)</param>
 /// <param name="t">The interpolation value (range 0 to 1)</param>
 /// <param name="type">The interpolation to use</param>
 /// <returns>The interpolated value between from and to.</returns>
 public static Vector3 Lerp(Vector3 from, Vector3 to, float t, InterpolationTypes type = InterpolationTypes.Smooth)
 {
     t = ApplyLerp(t, type);
     return(Vector3.Lerp(from, to, t));
 }
Exemplo n.º 30
0
 public static extern ErrorType extract_image_chip2(Array2DType img_type, IntPtr in_img, IntPtr chip_location, Array2DType array_type, InterpolationTypes type, IntPtr out_chip);
Exemplo n.º 31
0
 /// <summary>
 /// Lerp from Vector3Int a to b by the factor t (range 0 to 1) with rounding.
 /// Uses smooth (ease-in and -out) interpolation as a default, but supports many different interpolation curves.
 /// </summary>
 /// <param name="from">The start value (t = 0)</param>
 /// <param name="to">The target value (t = 1)</param>
 /// <param name="t">The interpolation value (range 0 to 1)</param>
 /// <param name="type">The interpolation to use</param>
 /// <param name="rounding">The type of rounding to apply to the result.</param>
 /// <returns>The interpolated value between from and to.</returns>
 public static Vector3Int Lerp(Vector3Int from, Vector3Int to, float t, InterpolationTypes type = InterpolationTypes.Smooth, IntRounding rounding = IntRounding.Regular)
 {
     t = ApplyLerp(t, type);
     return(ApplyRounding(Vector3.Lerp(from, to, t), rounding));
 }
Exemplo n.º 32
0
        //------------------------------------------------------------------------------------------------
        public FuturesSeriesBuilder(List<string> tickers,
            DateTime start,
            DateTime end,
            string calendarCode,
            string futuresStaticMoniker,
            ICarbonClient client,
            string carbonEnv = "PRD",
            RollMethods rollMthd = RollMethods.FirstNoticeDate,
            InterpolationTypes interpType = InterpolationTypes.None,
            List<string> contractSortOrder = null ,
            Dictionary<string,DateTime> rollmap = null,
            SmoothingTypes smoothingType = SmoothingTypes.None)
        //------------------------------------------------------------------------------------------------
        {
            // defaults
            startDate_ = start;
            endDate_ = end;
            carbonEnv_ = carbonEnv;
            rollMethod_ = rollMthd; //RollMethods.FirstNoticeDate;
            smoothingType_ = smoothingType;
            futuresStaticMoniker_ = futuresStaticMoniker;

            // Holidays
            holidays_ = new List<DateTime>();
            if (calendarCode != "")
            {
                var nodaHols = client.GetCalendarAsync(calendarCode).Result.Dates;

                foreach (LocalDate hol in nodaHols)
                {
                    holidays_.Add(hol.ToDateTime());
                }
            }

            // DateRange
            dateRange_ = new List<DateTime>();

            LocalDate currentDate = client.RollDateAsync(DateUtils.ToLocalDate(startDate_), 0, DateUnit.Bd, BusinessDayConvention.Following, calendarCode).Result;
            LocalDate endDate = DateUtils.ToLocalDate(endDate_);
            while (currentDate <= endDate)
            {
                dateRange_.Add(DateUtils.ToDateTime(currentDate));

                currentDate = client.RollDateAsync(currentDate, 1, DateUnit.Bd, BusinessDayConvention.Following, calendarCode).Result;
            }

            initFutureSeriesBuilder(tickers, dateRange_, holidays_, futuresStaticMoniker_, client, carbonEnv, rollMthd, interpType, contractSortOrder);

        }
Exemplo n.º 33
0
 /// <summary>
 /// Lerp from Quaternion a to b by the factor t (range 0 to 1).
 /// Uses smooth (ease-in and -out) interpolation as a default, but supports many different interpolation curves.
 /// </summary>
 /// <param name="from">The start value (t = 0)</param>
 /// <param name="to">The target value (t = 1)</param>
 /// <param name="t">The interpolation value (range 0 to 1)</param>
 /// <param name="type">The interpolation to use</param>
 /// <returns>The interpolated value between from and to.</returns>
 public static Quaternion Lerp(Quaternion from, Quaternion to, float t, InterpolationTypes type = InterpolationTypes.Smooth)
 {
     t = ApplyLerp(t, type);
     return(Quaternion.Lerp(from, to, t));
 }
Exemplo n.º 34
0
        public static Matrix <T> ExtractImageChip <T>(MatrixBase image, ChipDetails chipLocation, InterpolationTypes type = InterpolationTypes.NearestNeighbor)
            where T : struct
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            if (chipLocation == null)
            {
                throw new ArgumentNullException(nameof(chipLocation));
            }

            image.ThrowIfDisposed();
            chipLocation.ThrowIfDisposed();

            if (!chipLocation.IsValid())
            {
                throw new ArgumentException($"{nameof(chipLocation)} is invalid item.");
            }

            var chip        = new Matrix <T>();
            var elementType = image.MatrixElementType.ToNativeMatrixElementType();
            var ret         = NativeMethods.extract_image_chip_matrix2(elementType,
                                                                       image.NativePtr,
                                                                       chipLocation.NativePtr,
                                                                       chip.MatrixElementType.ToNativeMatrixElementType(),
                                                                       type.ToNativeInterpolationTypes(),
                                                                       chip.NativePtr);

            switch (ret)
            {
            case NativeMethods.ErrorType.MatrixElementTypeNotSupport:
                throw new ArgumentException($"{image.MatrixElementType} is not supported.");
            }

            return(chip);
        }
Exemplo n.º 35
0
        //------------------------------------------------------------------------------------------------
        // Copy constructor
        public FuturesSeriesBuilder(FuturesSeriesBuilder copy2clone)
        //------------------------------------------------------------------------------------------------
        {
            // Copy constructor
            carbonEnv_ = copy2clone.carbonEnv_;
            futuresStaticMoniker_ = copy2clone.futuresStaticMoniker_;
            startDate_ = copy2clone.startDate_;
            endDate_ = copy2clone.endDate_;
            dateRange_ = copy2clone.dateRange_;
            holidays_ = copy2clone.holidays_;
            rollMethod_ = copy2clone.rollMethod_;
            inputTickers_ = copy2clone.inputTickers_;
            contractTickers_ = copy2clone.contractTickers_;
            RollingContractSpecs_ = copy2clone.RollingContractSpecs_;
            ContractMonthLookupTable_ = copy2clone.ContractMonthLookupTable_;
            interpType_ = copy2clone.interpType_;
            contractSortOrder_ = copy2clone.contractSortOrder_;
            smoothingType_ = copy2clone.smoothingType_;

            FuturesStatic = copy2clone.FuturesStatic == null ? null : copy2clone.FuturesStatic.Clone();
            RawFuturesPrices = copy2clone.RawFuturesPrices == null? null: copy2clone.RawFuturesPrices.Clone();
            RollingFuturesData = copy2clone.RollingFuturesData == null? null: copy2clone.RollingFuturesData.Clone();

        }
Exemplo n.º 36
0
        public static void TransformImage(Array2DBase inputImage, Array2DBase outputImage, PointTransformBase pointTransform, InterpolationTypes interpolationTypes = InterpolationTypes.Quadratic)
        {
            if (inputImage == null)
            {
                throw new ArgumentNullException(nameof(inputImage));
            }
            if (outputImage == null)
            {
                throw new ArgumentNullException(nameof(outputImage));
            }
            if (pointTransform == null)
            {
                throw new ArgumentNullException(nameof(pointTransform));
            }
            if (inputImage == outputImage)
            {
                throw new ArgumentException();
            }

            inputImage.ThrowIfDisposed(nameof(inputImage));
            outputImage.ThrowIfDisposed(nameof(outputImage));

            var inType  = inputImage.ImageType.ToNativeArray2DType();
            var outType = outputImage.ImageType.ToNativeArray2DType();
            var ret     = NativeMethods.transform_image(inType,
                                                        inputImage.NativePtr,
                                                        outType,
                                                        outputImage.NativePtr,
                                                        pointTransform.GetNativePointMappingTypes(),
                                                        pointTransform.NativePtr,
                                                        interpolationTypes.ToNativeInterpolationTypes());

            switch (ret)
            {
            case NativeMethods.ErrorType.Array2DTypeTypeNotSupport:
                throw new ArgumentException("Output or input type is not supported.");
            }
        }
Exemplo n.º 37
0
 /// <summary>
 /// Lerp from int a to b by the factor t (range 0 to 1) with rounding.
 /// Uses smooth (ease-in and -out) interpolation as a default, but supports many different interpolation curves.
 /// </summary>
 /// <param name="from">The start value (t = 0)</param>
 /// <param name="to">The target value (t = 1)</param>
 /// <param name="t">The interpolation value (range 0 to 1)</param>
 /// <param name="type">The interpolation to use</param>
 /// <param name="rounding">The type of rounding to apply to the result.</param>
 /// <returns>The interpolated value between from and to rounded to the nearest integer.</returns>
 public static int Lerp(int from, int to, float t, InterpolationTypes type = InterpolationTypes.Smooth, IntRounding rounding = IntRounding.Regular)
 {
     type = GetSmartType(from, to, type);
     t    = ApplyLerp(t, type);
     return(ApplyRounding(Mathf.Lerp(from, to, t), rounding));
 }