コード例 #1
0
        /// <summary>
        /// Runs an iteration of the KPZ algorithm (with <see cref="GridWidth"/> × <see cref="GridHeight"/> steps).
        /// </summary>
        public void DoHastIterations(uint numberOfIterations)
        {
            var numberOfStepsInIteration = GridWidth * GridHeight;

            KpzNode[,] gridBefore = (KpzNode[, ])Grid.Clone();

            if (_enableStateLogger)
            {
                StateLogger.NewKpzIteration();
            }

            if (_kpzTarget == KpzTarget.FpgaParallelized || _kpzTarget == KpzTarget.FpgaSimulationParallelized)
            {
                KernelsParallelized.DoIterationsWrapper(Grid, !HastlayerGridAlreadyPushed, _randomSeedEnable, numberOfIterations);
            }
            else
            {
                Kernels.DoIterationsWrapper(Grid, !HastlayerGridAlreadyPushed, false,
                                            _random.NextUInt64(), _random.NextUInt64(), numberOfIterations);
            }

            if (_enableStateLogger)
            {
                StateLogger.AddKpzAction("Kernels.DoHastIterations", Grid, gridBefore);
            }
            //HastlayerGridAlreadyPushed = true; // If not commented out, push always
        }
コード例 #2
0
ファイル: NewBehaviour.cs プロジェクト: Serphera/Fluid-sim
        /// <summary>
        /// Calculates the density force of the fluid
        /// </summary>
        /// <param name="particles"></param>
        /// <returns></returns>
        private void CalculateDensity(ref List <FluidParticle> particles)
        {
            for (int i = 0; i < particles.Count; i++)
            {
                particles[i].Density = 1000 * (_particleRadius / 10);

                for (int j = 0; j < particles.Count; j++)
                {
                    if (particles[i] == particles[j])
                    {
                        continue;
                    }

                    var distance = particles[j].Pos - particles[i].Pos;

                    // Distance between particles is less than diameter of particle
                    if (distance.Length() < _particleDiameter)
                    {
                        particles[i].Density += Mass * Kernels.CalculateGeneral(distance, _particleRadius);
                    }
                }

                //particles[i].Pressure = GAS_CONST * (particles[i].Density - REST_DENSITY);
                particles[i].Pressure = (float)((1119 * 1000) * (Math.Pow((particles[i].Density / REST_DENSITY), 7) - 1));
            }
        }
コード例 #3
0
    Vector2 ViscosityForce(Particle p0, Particle p1)
    {
        Vector2 r = p0.position - p1.position;
        Vector2 v = p1.velocity - p0.velocity;

        return(viscosity * v * (mass / p0.density) * Kernels.ViscosityLaplacian(r.magnitude, smoothingRadius));
    }
コード例 #4
0
        /// <summary>
        /// LPC analysis filter
        /// NB! State is kept internally and the
        /// filter always starts with zero state
        /// first d output samples are set to zero
        /// </summary>
        /// <param name="output">O    Output signal</param>
        /// <param name="input">I    Input signal</param>
        /// <param name="B">I    MA prediction coefficients, Q12 [order]</param>
        /// <param name="len">I    Signal length</param>
        /// <param name="d">I    Filter order</param>
        /// <param name="arch">I    Run-time architecture</param>
        internal static void silk_LPC_analysis_filter(
            short[] output,
            int output_ptr,
            short[] input,
            int input_ptr,
            short[] B,
            int B_ptr,
            int len,
            int d)
        {
            int j;

            short[] mem = new short[SilkConstants.SILK_MAX_ORDER_LPC];
            short[] num = new short[SilkConstants.SILK_MAX_ORDER_LPC];

            Inlines.OpusAssert(d >= 6);
            Inlines.OpusAssert((d & 1) == 0);
            Inlines.OpusAssert(d <= len);

            Inlines.OpusAssert(d <= SilkConstants.SILK_MAX_ORDER_LPC);
            for (j = 0; j < d; j++)
            {
                num[j] = (short)(0 - B[B_ptr + j]);
            }
            for (j = 0; j < d; j++)
            {
                mem[j] = input[input_ptr + d - j - 1];
            }
            Kernels.celt_fir(input, input_ptr + d, num, output, output_ptr + d, len - d, d, mem);
            for (j = output_ptr; j < output_ptr + d; j++)
            {
                output[j] = 0;
            }
        }
コード例 #5
0
    Vector2 PressureForce(Particle p0, Particle p1)
    {
        float dividend = p0.pressure + p1.pressure;
        float divisor  = 2 * p0.density * p1.density;

        Vector2 r = p0.position - p1.position;

        return(-mass * (dividend / divisor) * Kernels.GradientSpiky(r, smoothingRadius));
    }
コード例 #6
0
 public void Update()
 {
     _biasOptimizers.ForEach((q, i) => Biases[i] = q.Update());
     Kernels.ForEach((kernel, kernelIndex) =>
     {
         kernel.UpdateForEach <double>((q, idx) =>
                                       ((Optimizer)_weightOptimizers[kernelIndex].GetValue(idx)).Update());
     });
 }
コード例 #7
0
ファイル: Convolution.cs プロジェクト: kapkapas/Neuro
        public override void CopyParametersTo(LayerBase target, float tau)
        {
            base.CopyParametersTo(target);

            var targetConv = target as Convolution;

            Kernels.CopyTo(targetConv.Kernels, tau);
            Bias.CopyTo(targetConv.Bias, tau);
        }
コード例 #8
0
        public override void Initialize()
        {
            int inLength = KernelShape.Volume;

            Kernels.ForEach(K =>
            {
                K.Bias.Value = BiasInit.Initialize(inLength, 1);
                K.Weights.ForEach(W => W.Value = WeightInit.Initialize(inLength, 1));
            });
        }
コード例 #9
0
        private double[,,] ComputeInputGradients(double[,,] input)
        {
            var transposed = Kernels
                             .Transpose()
                             .Select(q => q.Rotate())
                             .ToArray();

            var padded = input.Pad(KernelSize - 1);

            return(MatrixHelper.Convolution(transposed, padded));
        }
コード例 #10
0
 public void RunKernel(string kernelName, Tensor input1, Tensor input2, Tensor output, params object[] extraParameters)
 {
     if (Kernels.TryGetValue(kernelName, out var kernel))
     {
         RunKernel(kernel, input1, input2, output, extraParameters);
     }
     else
     {
         throw new ArgumentException($"Kernel '{kernelName}' not found");
     }
 }
コード例 #11
0
        public void RandomizeWeights(double stddev)
        {
            var dist = new Normal(0, stddev);

            Kernels
            .ForEach((q, kernel) =>
                     q.UpdateForEach <double>((w, idx) => dist.Sample()));

            Kernels
            .ForEach((q, kernel) => q.ForEach((w, i, j, k) =>
                                              _weightOptimizers[kernel][i, j, k].SetValue(w)));
        }
コード例 #12
0
ファイル: NewBehaviour.cs プロジェクト: Serphera/Fluid-sim
        /// <summary>
        /// Calculates Forces acting on the particles
        /// </summary>
        /// <param name="particles"></param>
        /// <returns></returns>
        private void CalculateForces(ref List <FluidParticle> particles)
        {
            for (int i = 0; i < particles.Count; i++)
            {
                particles[i].Force += GRAVITY;

                for (int j = 0; j < particles.Count; j++)
                {
                    if (particles[i] == particles[j])
                    {
                        continue;
                    }

                    var deltaDistance = particles[i].Pos - particles[j].Pos;

                    if (deltaDistance.Length() < _particleDiameter)
                    {
                        // Calculates pressure force contribution
                        // pressure = mass * delta pressure
                        // pressure = pressure / (density of particle acting on current particle * 2.0f)
                        // pressure vector = spikyKernel(delta distance, particle radius) * pressure
                        var pressure = Mass * (particles[i].Pressure + particles[j].Pressure);
                        pressure = pressure / (particles[j].Density * 2.0f);

                        var pressureVector = Kernels.CalculateSpiky(deltaDistance, _particleRadius) * pressure;

                        particles[i].Force -= pressureVector;
                        particles[j].Force += pressureVector;


                        //var pressure = Math.Pow(particles[i].Pressure - , 7)

                        // Calculates viscocity force contribution
                        // viscocity = fluid viscocity * 1 / density of partile acting on current particle
                        // viscocity = mass * laplacian(delta distance, particle radius) * viscocity
                        // viscocity vector = delta velocity * viscocity
                        var viscocity = Viscocity * 1 / particles[j].Density;
                        viscocity = Mass * Kernels.CalculateLaplacian(deltaDistance, _particleRadius) * viscocity;

                        var viscocityVector = (particles[j].Velocity - particles[i].Velocity) * viscocity;

                        particles[i].Force += viscocityVector;
                        particles[j].Force -= viscocityVector;
                    }
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// LPC analysis filter
        /// NB! State is kept internally and the
        /// filter always starts with zero state
        /// first d output samples are set to zero
        /// </summary>
        /// <param name="output">O    Output signal</param>
        /// <param name="output_ptr"></param>
        /// <param name="input">I    Input signal</param>
        /// <param name="input_ptr"></param>
        /// <param name="B">I    MA prediction coefficients, Q12 [order]</param>
        /// <param name="B_ptr"></param>
        /// <param name="len">I    Signal length</param>
        /// <param name="d">I    Filter order</param>
        internal static void silk_LPC_analysis_filter(
            short[] output,
            int output_ptr,
            short[] input,
            int input_ptr,
            short[] B,
            int B_ptr,
            int len,
            int d)
        {
            int j;

            short[] mem = new short[SilkConstants.SILK_MAX_ORDER_LPC];
            short[] num = new short[SilkConstants.SILK_MAX_ORDER_LPC];

            Inlines.OpusAssert(d >= 6);
            Inlines.OpusAssert((d & 1) == 0);
            Inlines.OpusAssert(d <= len);

            Inlines.OpusAssert(d <= SilkConstants.SILK_MAX_ORDER_LPC);
            for (j = 0; j < d; j++)
            {
                num[j] = (short)(0 - B[B_ptr + j]);
            }
            for (j = 0; j < d; j++)
            {
                mem[j] = input[input_ptr + d - j - 1];
            }
#if UNSAFE
            unsafe
            {
                fixed(short *pinput_base = input, poutput_base = output)
                {
                    short *pinput  = pinput_base + input_ptr + d;
                    short *poutput = poutput_base + output_ptr + d;

                    Kernels.celt_fir(pinput, num, poutput, len - d, d, mem);
                }
            }
#else
            Kernels.celt_fir(input, input_ptr + d, num, output, output_ptr + d, len - d, d, mem);
#endif
            for (j = output_ptr; j < output_ptr + d; j++)
            {
                output[j] = 0;
            }
        }
コード例 #14
0
ファイル: TextureXComponent.cs プロジェクト: xenoken/TextureX
    void Start()
    {
        TextureX
        // initialize a new texturex instance with the specified texture. all the following commands will apply to this texture.
        .Use(tex)
        // run a convolution kernel on the texture.
        .Kernel(Kernels.EdgeDetection(3, 3))
        // apply the state of the texture.
        .Apply()
        // save the texture to disk.
        .Save("texturex.png", out bool saved)
        // and you can also keep working on the texture, cool! :D
        .Random()

        .Apply()

        .Save("random.png", out saved)
        ;
    }
コード例 #15
0
        /// <summary>
        /// Runs an iteration of the KPZ algorithm (with <see cref="GridWidth"/> × <see cref="GridHeight"/> steps).
        /// It allows us to debug the steps of the algorithms one by one.
        /// </summary>
        public void DoHastIterationDebug()
        {
            var numberOfStepsInIteration = GridWidth * GridHeight;

            KpzNode[,] gridBefore = (KpzNode[, ])Grid.Clone();

            if (_enableStateLogger)
            {
                StateLogger.NewKpzIteration();
            }

            for (int i = 0; i < numberOfStepsInIteration; i++)
            {
                Kernels.DoIterationsWrapper(Grid, true, true, _random.NextUInt64(), _random.NextUInt64(), 1);
                if (_enableStateLogger)
                {
                    StateLogger.AddKpzAction("Kernels.DoSingleIterationWrapper", Grid, gridBefore);
                }
            }
        }
コード例 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="kernelType"></param>
        /// <param name="parameter">Polynomial:degree, RBF:gamma</param>
        public void setKernel(Kernels kernelType, double parameter)
        {
            switch (kernelType)
            {
            case Kernels.Linear:
                _kernel = new KernelLinear();
                break;

            case Kernels.Polynomial:
                _kernel = new KernelPolynomial((int)parameter);
                break;

            case Kernels.RadialBasisFunction:
                _kernel = new KernelRadialBasisFunction(parameter);
                break;

            default:
                _kernel = new KernelLinear();
                break;
            }
        }
コード例 #17
0
        public override void Connect(Layer inLayer)
        {
            if (inLayer.Shape != InputShape)
            {
                throw new ShapeMismatchException(nameof(inLayer));
            }

            ShapedArray <Neuron> padded = Padder.PadArray(inLayer.Neurons.ToShape(Shape), Paddings, () => new Neuron()
            {
                OutVal = PadVal
            });

            var inConnections = new ShapedArray <List <Synapse> >(PaddedShape, () => new List <Synapse>());

            Kernels.ForEach((kernel, i) =>
            {
                int offset = i * Shape.Volume / KernelsNum;

                IndexGen.ByStrides(PaddedShape, Strides, KernelShape).ForEach((idxKernel, j) =>
                {
                    var outN = (CNeuron)Neurons[offset + j];

                    outN.KernelBias = kernel.Bias;

                    outN.InSynapses = IndexGen.ByStart(KernelShape, Array <int> .FromRef(idxKernel)).Select((idx, k) =>
                    {
                        var S = new CSynapse(padded[idx], outN)
                        {
                            KernelWeight = kernel.Weights[k]
                        };

                        inConnections[idx].Add(S);
                        return((Synapse)S);
                    });
                });
            });

            padded.ForEach((N, i) => N.OutSynapses = Array <Synapse> .FromRef(inConnections[i].ToArray()));
        }
コード例 #18
0
ファイル: Convolution.cs プロジェクト: kapkapas/Neuro
 internal override void SerializeParameters(XmlElement elem)
 {
     base.SerializeParameters(elem);
     Kernels.Serialize(elem, "Kernels");
     Bias.Serialize(elem, "Bias");
 }
コード例 #19
0
        public GPViewModelStatic()
        {
            Kernels = GaussianProcess.KernelHelper.LoadKernels().ToDictionary(_ => _.GetDescription());

            KernelChanged(Kernels.First().Value, Length, Noise);
        }
コード例 #20
0
        /// <summary>
        /// Выполняет параллельную версию алгоритма Apriori.
        /// </summary>
        /// <param name="minimalSupport"></param>
        /// <param name="progressOutput">если это правда, информация о прогрессе отправляется на стандартный вывод</param>
        /// <returns>Список L-элементов с поддержкой> = minimumSupport</returns>
        public List <ILitemset> RunParallelApriori(double minimalSupport, bool progressOutput)
        {
            if (Platforms.InitializeAll().Length == 0)
            {
                return(RunApriori(minimalSupport, progressOutput));
            }

            if (minimalSupport > 1 || minimalSupport <= 0)
            {
                return(null);
            }

            if (customerList == null)
            {
                return(null);
            }

            if (this.customersCount == 0)
            {
                return(new List <ILitemset>());
            }

            int minSupport = (int)Math.Ceiling((double)this.customersCount * minimalSupport);

            Stopwatch watch = null;

            if (progressOutput)
            {
                watch = new Stopwatch();
                watch.Start();
            }

            #region conversion of input to int[]

            int itemsCountInt        = 0;
            int transactionsCountInt = 0;
            int customersCountInt    = 0;

            foreach (ICustomer c in customerList)
            {
                ++customersCountInt;
                foreach (ITransaction t in c.GetTransactions())
                {
                    ++transactionsCountInt;
                    foreach (IItem item in t.GetItems())
                    {
                        ++itemsCountInt;
                    }
                }
            }

            uint itemsCountUInt        = (uint)itemsCountInt;
            uint transactionsCountUInt = (uint)transactionsCountInt;
            uint customersCountUInt    = (uint)customersCountInt;

            int[] items               = new int[itemsCountInt];
            int[] itemsTransactions   = new int[itemsCountInt];
            int[] itemsCustomers      = new int[itemsCountInt];
            int[] transactionsStarts  = new int[transactionsCountInt];
            int[] transactionsLengths = new int[transactionsCountInt];
            int[] customersStarts     = new int[customersCountInt]; // с точки зрения транзакций!
            int[] customersLengths    = new int[customersCountInt]; // с точки зрения транзакций!
            {
                int currItem        = 0;
                int currTransaction = 0;
                int currCustomer    = 0;

                int currTransactionLenth = 0;
                int currCustomerLength   = 0;
                foreach (ICustomer c in customerList)
                {
                    currCustomerLength            = 0;
                    customersStarts[currCustomer] = currTransaction;
                    foreach (ITransaction t in c.GetTransactions())
                    {
                        currTransactionLenth = 0;
                        transactionsStarts[currTransaction] = currItem;
                        foreach (IItem item in t.GetItems())
                        {
                            items[currItem]             = item.GetId();
                            itemsTransactions[currItem] = currTransaction;
                            itemsCustomers[currItem]    = currCustomer;
                            ++currItem;
                            ++currTransactionLenth;
                        }
                        ++currCustomerLength;
                        transactionsLengths[currTransaction] = currTransactionLenth;
                        ++currTransaction;
                    }
                    customersLengths[currCustomer] = currCustomerLength;
                    ++currCustomer;
                }
            }

            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("преобразованный вход @ {0} мс", watch.ElapsedMilliseconds);
                watch.Start();
            }

            //Abstract.Diagnostics = true;

            uint localSize = 32;

            InitOpenCL(progressOutput);

            CommandQueue queue = new CommandQueue(device, context);

            #region input buffers allocation and initialization

            Buffer <int> itemsBuf = new Buffer <int>(context, queue, items);

            Buffer <int> transactionsStartsBuf = new Buffer <int>(context, queue, transactionsStarts);

            Buffer <int> customersStartsBuf = new Buffer <int>(context, queue, customersStarts);

            int[]        itemsCount    = new int[] { itemsCountInt };
            Buffer <int> itemsCountBuf = new Buffer <int>(context, queue, itemsCount);

            int[]        transactionsCount    = new int[] { transactionsCountInt };
            Buffer <int> transactionsCountBuf = new Buffer <int>(context, queue, transactionsCount);

            int[]        customersCount    = new int[] { customersCountInt };
            Buffer <int> customersCountBuf = new Buffer <int>(context, queue, customersCount);

            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("буферы, написанные @ {0} мс", watch.ElapsedMilliseconds);
                watch.Start();
            }

            InitOpenCLPrograms(false, progressOutput);

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("программы построены @ {0} мс", watch.ElapsedMilliseconds);
                watch.Start();
            }

            #region empty buffers allocation and initialization

            Buffer <int> Zero = new Buffer <int>(context, queue, new int[] { 0 });
            Zero.Write(false);
            Buffer <int> One = new Buffer <int>(context, queue, new int[] { 1 });
            One.Write(false);

            Buffer <int> tempItemsBuf = new Buffer <int>(context, queue, itemsCountUInt);
            itemsBuf.Copy(0, itemsCountUInt, tempItemsBuf, 0);

            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("Initialized OpenCL in {0}ms.", watch.ElapsedMilliseconds);
                watch.Restart();
            }

            // time: n*log^2(n)
            #region finding empty id

            int[] tempValue = new int[] { -1 };

            kernelMax.SetArgument(0, tempItemsBuf);
            kernelMax.SetArguments(null, itemsCountInt, 0, itemsCountInt);
            uint globalSize = itemsCountUInt;
            for (int scaling = 1; scaling < itemsCountInt; scaling *= (int)localSize)
            {
                kernelMax.SetArgument(4, scaling);
                globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                kernelMax.Launch1D(queue, globalSize, localSize);
                globalSize /= localSize;
            }

            //tempItemsBuf.Read(tempValue, 0, 1); // debug

            int          emptyId    = -1;
            Buffer <int> emptyIdBuf = new Buffer <int>(context, queue, 1);
            kernelIncrement.SetArgument(0, tempItemsBuf);
            kernelIncrement.SetArguments(null, 1, 0, 1);
            kernelIncrement.Launch1D(queue, 1, 1);

            tempItemsBuf.Copy(0, 1, emptyIdBuf, 0);

            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("empty id @ {0}ms", watch.ElapsedMilliseconds);
                watch.Start();
            }

            // time: 3n + n * ( 1.5n + log^2(n) ) == O(n^2)
            #region finding distinct item ids

            Buffer <int> itemsRemainingBuf = new Buffer <int>(context, queue, itemsCountUInt);
            itemsBuf.Copy(itemsRemainingBuf);
            itemsBuf.Copy(tempItemsBuf);

            int uniqueItemsCount = 0;

            int[]        uniqueItems    = new int[itemsCountInt];
            Buffer <int> uniqueItemsBuf = new Buffer <int>(context, queue, uniqueItems);

            kernelZero.SetArgument(0, uniqueItemsBuf);
            kernelZero.SetArguments(null, itemsCountInt, 0, itemsCountInt);
            kernelZero.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, itemsCountUInt), localSize);

            kernelMin.SetArgument(0, tempItemsBuf);
            kernelMin.SetArguments(null, itemsCountInt, 0, itemsCountInt);
            kernelSubstitute.SetArgument(0, itemsRemainingBuf);
            kernelSubstitute.SetArguments(null, itemsCountInt, 0, itemsCountInt);
            kernelSubstitute.SetArgument(4, emptyIdBuf);
            kernelSubstitute.SetArgument(5, tempItemsBuf);

            while (true)
            {
                globalSize = itemsCountUInt;
                for (int scaling = 1; scaling < itemsCountInt; scaling *= (int)localSize)
                {
                    kernelMin.SetArgument(4, scaling);
                    globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                    kernelMin.Launch1D(queue, globalSize, localSize);
                    globalSize /= localSize;
                }

                if (emptyId == -1)
                {
                    emptyIdBuf.Read();
                    emptyId = emptyIdBuf.Value;
                }
                tempItemsBuf.Read(tempValue, 0, 1);
                if (tempValue[0] == emptyId)
                {
                    break;                     // достигнут конец вычисления
                }
                uniqueItems[uniqueItemsCount] = tempValue[0];
                uniqueItemsCount += 1;
                uniqueItemsBuf.Write(false, 0, (uint)uniqueItemsCount);

                kernelSubstitute.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, itemsCountUInt), localSize);


                itemsRemainingBuf.Copy(0, itemsCountUInt, tempItemsBuf, 0);
            }

            uint uniqueItemsCountUInt = (uint)uniqueItemsCount;

            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("distinct items @ {0}ms", watch.ElapsedMilliseconds);
                watch.Start();
            }

            // time: 2n + n^2 * log^2(n) == O(n^2 * log^2(n))
            #region finding supports for items

            int  itemsSupportsCountInt  = itemsCountInt * uniqueItemsCount;
            uint itemsSupportsCountUInt = (uint)itemsSupportsCountInt;

            int[]        itemsSupportsCount    = new int[] { itemsSupportsCountInt };
            Buffer <int> itemsSupportsCountBuf = new Buffer <int>(context, queue, itemsSupportsCount);

            int[]        itemsSupports    = new int[itemsSupportsCountInt];
            Buffer <int> itemsSupportsBuf = new Buffer <int>(context, queue, itemsSupports);

            kernelZero.SetArgument(0, itemsSupportsBuf);
            kernelZero.SetArguments(null, itemsSupportsCountInt, null, itemsSupportsCountInt);
            kernelZero.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, itemsSupportsCountUInt), localSize);

            Buffer <int> uniqueItemBuf = new Buffer <int>(context, queue, 1);

            kernelCopyIfEqual.SetArgument(0, itemsBuf);
            kernelCopyIfEqual.SetArgument(4, itemsSupportsBuf);
            kernelCopyIfEqual.SetArguments(null, itemsCountInt, 0, itemsCountInt,
                                           null, itemsSupportsCountInt, null, itemsCountInt);
            kernelCopyIfEqual.SetArgument(8, uniqueItemBuf);

            int uniqueItemIndex = 0;
            for (int supportsOffset = 0; supportsOffset < itemsSupports.Length; supportsOffset += items.Length)
            {
                uniqueItemBuf.Value = uniqueItems[uniqueItemIndex];
                uniqueItemBuf.Write();
                kernelCopyIfEqual.SetArgument(6, supportsOffset);

                kernelCopyIfEqual.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, itemsCountUInt), localSize);


                ++uniqueItemIndex;
            }

            kernelSubstituteIfNotEqual.SetArgument(0, itemsSupportsBuf);
            kernelSubstituteIfNotEqual.SetArguments(null, itemsSupportsCountInt, 0, itemsSupportsCountInt);
            kernelSubstituteIfNotEqual.SetArgument(4, One);
            kernelSubstituteIfNotEqual.SetArgument(5, Zero);
            kernelSubstituteIfNotEqual.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, itemsSupportsCountUInt), localSize);


            #endregion

            // time: 2n + n^2 * log^2(n) == O(n^2 * log^2(n))
            #region finding supports for transactions

            int  transactionsSupportsCountInt  = transactionsCountInt * uniqueItemsCount;
            uint transactionsSupportsCountUInt = (uint)transactionsSupportsCountInt;

            int[]        transactionsSupportsCount    = new int[] { transactionsSupportsCountInt };
            Buffer <int> transactionsSupportsCountBuf = new Buffer <int>(context, queue, transactionsSupportsCount);

            int[]        transactionsSupports    = new int[transactionsSupportsCountInt];
            Buffer <int> transactionsSupportsBuf = new Buffer <int>(context, queue, transactionsSupports);

            kernelZero.SetArgument(0, transactionsSupportsBuf);
            kernelZero.SetArguments(null, transactionsSupportsCountInt, null, transactionsSupportsCountInt);
            kernelZero.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, transactionsSupportsCountUInt), localSize);

            Buffer <int> itemsSupportsBufCopy = new Buffer <int>(context, queue, itemsSupports);

            itemsSupportsBuf.Copy(0, itemsSupportsCountUInt, itemsSupportsBufCopy, 0);

            kernelSegmentedOr.SetArgument(0, itemsSupportsBufCopy);
            kernelSegmentedOr.SetArguments(null, itemsSupportsCountInt, null, null,
                                           null, itemsCountInt);


            for (int tn = 0; tn < transactionsCountInt; ++tn)
            {
                kernelSegmentedOr.SetArgument(2, transactionsStarts[tn]);
                kernelSegmentedOr.SetArgument(3, transactionsLengths[tn]);

                globalSize = (uint)transactionsLengths[tn];
                for (int scaling = 1; scaling < transactionsLengths[tn]; scaling *= (int)localSize)
                {
                    kernelSegmentedOr.SetArgument(4, scaling);
                    globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                    kernelSegmentedOr.Launch2D(queue, globalSize, localSize, uniqueItemsCountUInt, 1);
                    globalSize /= localSize;
                }

                int offset       = transactionsStarts[tn];
                int outputOffset = tn;
                for (int i = 0; i < uniqueItemsCount; ++i)
                {
                    itemsSupportsBufCopy.Copy((uint)offset, 1, transactionsSupportsBuf, (uint)outputOffset);


                    if (i == uniqueItemsCount - 1)
                    {
                        break;
                    }

                    offset       += itemsCountInt;
                    outputOffset += transactionsCountInt;
                }
            }


            #endregion

            // time: 2n + n^2 * log^2(n) == O(n^2 * log^2(n))
            #region finding supports for customers

            int  customersSupportsCountInt  = customersCountInt * uniqueItemsCount;
            uint customersSupportsCountUInt = (uint)customersSupportsCountInt;

            int[]        customersSupportsCount    = new int[] { customersSupportsCountInt };
            Buffer <int> customersSupportsCountBuf = new Buffer <int>(context, queue, customersSupportsCount);

            int[]        customersSupports    = new int[customersSupportsCountInt];
            Buffer <int> customersSupportsBuf = new Buffer <int>(context, queue, customersSupports);

            kernelZero.SetArgument(0, customersSupportsBuf);
            kernelZero.SetArguments(null, customersSupportsCountInt, null, customersSupportsCountInt);
            kernelZero.Launch1D(queue, Kernels.GetOptimalGlobalSize(localSize, customersSupportsCountUInt), localSize);

            Buffer <int> transactionsSupportsBufCopy = new Buffer <int>(context, queue, transactionsSupports);

            transactionsSupportsBuf.Copy(0, transactionsSupportsCountUInt, transactionsSupportsBufCopy, 0);

            kernelSegmentedOr.SetArgument(0, transactionsSupportsBufCopy);
            kernelSegmentedOr.SetArguments(null, transactionsSupportsCountInt, null, null,
                                           null, transactionsCountInt);


            for (int cn = 0; cn < customersCountInt; ++cn)
            {
                kernelSegmentedOr.SetArgument(2, customersStarts[cn]);
                kernelSegmentedOr.SetArgument(3, customersLengths[cn]);

                globalSize = (uint)customersLengths[cn];
                for (int scaling = 1; scaling < customersLengths[cn]; scaling *= (int)localSize)
                {
                    kernelSegmentedOr.SetArgument(4, scaling);
                    globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                    kernelSegmentedOr.Launch2D(queue, globalSize, localSize, uniqueItemsCountUInt, 1);
                    globalSize /= localSize;
                }


                int offset       = customersStarts[cn];
                int outputOffset = cn;
                for (int i = 0; i < uniqueItemsCount; ++i)
                {
                    transactionsSupportsBufCopy.Copy((uint)offset, 1, customersSupportsBuf, (uint)outputOffset);


                    if (i == uniqueItemsCount - 1)
                    {
                        break;
                    }

                    offset       += transactionsCountInt;
                    outputOffset += customersCountInt;
                }
            }

            #endregion

            // time: n + n * ( n*log^2(n) + n ) == O(n^2 * log^2(n))
            #region litemsets of size 1

            Buffer <int> customersSupportsBufCopy = new Buffer <int>(context, queue, customersSupports);

            customersSupportsBuf.Copy(0, customersSupportsCountUInt, customersSupportsBufCopy, 0);


            kernelSum.SetArgument(0, customersSupportsBufCopy);
            kernelSum.SetArguments(null, customersSupportsCountInt, null, customersCountInt);

            var litemsets          = new List <ILitemset>();
            var supportedLocations = new List <int>();

            for (int un = 0; un < uniqueItemsCount; ++un)
            {
                int offset = un * customersCountInt;
                kernelSum.SetArgument(2, offset);

                globalSize = customersCountUInt;
                for (int scaling = 1; scaling < customersCountInt; scaling *= (int)localSize)
                {
                    kernelSum.SetArgument(4, scaling);
                    globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                    kernelSum.Launch1D(queue, globalSize, localSize);
                    globalSize /= localSize;
                }


                customersSupportsBufCopy.Read(tempValue, (uint)offset, 1);

                int support = tempValue[0];

                if (support < 0 || support > customersCountInt)
                {
                    Zero.Read();
                    One.Read();
                    emptyIdBuf.Read();
                    itemsSupportsBuf.Read();
                    transactionsSupportsBufCopy.Read();
                    customersSupportsBufCopy.Read();
                    itemsSupportsBuf.Read();
                    transactionsSupportsBuf.Read();
                    customersSupportsBuf.Read();
                    throw new Exception(String.Format("support = {0} не имеет теоретических границ [0, {1}]!",
                                                      support, customersCountInt));
                }

                if (support < minSupport)
                {
                    continue;
                }

                litemsets.Add(new Litemset(support, uniqueItems[un]));
                supportedLocations.Add(un);
            }

            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("отдельные элементы @ {0} мс", watch.ElapsedMilliseconds);
                watch.Start();
            }

            // time: n*log^2(n) + n + n * ( 0.5n + n^2 + 0.5n * n^2 * log^2(n) + n*log^2(n) ) == O(n^4 * log^2(n))
            #region litemsets of size 2 and above

            bool moreCanBeFound = true;


            kernelMax.SetArgument(0, customersSupportsBufCopy);
            kernelMax.SetArguments(null, customersSupportsCountInt, null, customersSupportsCountInt);
            globalSize = customersSupportsCountUInt;
            for (int scaling = 1; scaling < customersSupportsCountInt; scaling *= (int)localSize)
            {
                kernelMax.SetArgument(4, scaling);
                globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                kernelMax.Launch1D(queue, globalSize, localSize);
                globalSize /= localSize;
            }

            bool[] newSupportedLocations = new bool[uniqueItemsCount];
            for (int i = 0; i < uniqueItemsCount; ++i)
            {
                newSupportedLocations[i] = false;
            }

            customersSupportsBufCopy.Read(tempValue, 0, 1);
            if (tempValue[0] < minSupport)
            {
                moreCanBeFound = false;
            }
            else if (supportedLocations.Count == 1)
            {
                moreCanBeFound = false;
            }

            if (moreCanBeFound)
            {
                int[] indices = new int[uniqueItemsCount];

                int[]        locations    = new int[uniqueItemsCount];
                Buffer <int> locationsBuf = new Buffer <int>(context, queue, locations);

                int          currLength    = 1;
                Buffer <int> currLengthBuf = new Buffer <int>(context, queue, 1);

                kernelMulitItemSupport.SetArgument(0, transactionsSupportsBufCopy);
                kernelMulitItemSupport.SetArguments(null, transactionsSupportsCountInt,
                                                    transactionsCountInt);
                kernelMulitItemSupport.SetArgument(3, locationsBuf);
                kernelMulitItemSupport.SetArgument(4, currLengthBuf);

                kernelOr.SetArgument(0, transactionsSupportsBufCopy);
                kernelOr.SetArguments(null, transactionsSupportsCountInt, null, null);

                while (moreCanBeFound)
                {
                    ++currLength;
                    currLengthBuf.Value = currLength;
                    currLengthBuf.Write(false);

                    uint litemsetOffset = (uint)litemsets.Count;

                    for (int i = 0; i < currLength; ++i)
                    {
                        indices[i] = i;
                    }
                    int currIndex = currLength - 1;


                    while (true)
                    {
                        #region initialization of int[] locations
                        for (int i = 0; i < currLength; ++i)
                        {
                            locations[i] = supportedLocations[indices[i]];
                        }
                        locationsBuf.Write(false, 0, (uint)currLength);
                        #endregion

                        #region copying of relevant parts of int[] transactionsSupports
                        for (int i = 0; i < currLength; ++i)
                        {
                            #region debugging
                            //if (currLength == 2
                            //	&& uniqueItems[supportedLocations[indices[0]]] == 2
                            //	&& uniqueItems[supportedLocations[indices[1]]] == 3)
                            //{
                            //	// debug only
                            //	queue.Finish();
                            //	transactionsSupportsBufCopy.Read();
                            //	//transactionsSupportsBuf.Read();
                            //}
                            #endregion

                            int offset = supportedLocations[indices[i]] * transactionsCountInt;
                            transactionsSupportsBuf.Copy((uint)offset, transactionsCountUInt,
                                                         transactionsSupportsBufCopy, (uint)offset);
                        }
                        #endregion



                        int stepNo = 1;
                        while (stepNo < currLength)
                        {
                            kernelMulitItemSupport.SetArgument(5, stepNo);
                            kernelMulitItemSupport.Launch2D(queue, transactionsCountUInt, 1, (uint)currLength, 1);
                            stepNo *= 2;
                            queue.Finish();
                        }


                        for (int cn = 0; cn < customersCountInt; ++cn)
                        {
                            kernelOr.SetArgument(2, supportedLocations[indices[0]] * transactionsCountInt + customersStarts[cn]);
                            kernelOr.SetArgument(3, customersLengths[cn]);

                            globalSize = (uint)customersLengths[cn];
                            for (int scaling = 1; scaling < customersLengths[cn]; scaling *= (int)localSize)
                            {
                                kernelOr.SetArgument(4, scaling);
                                globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                                kernelOr.Launch1D(queue, globalSize, localSize);
                                globalSize /= localSize;
                            }
                        }

                        kernelSum.SetArgument(0, transactionsSupportsBufCopy);
                        kernelSum.SetArguments(null, transactionsSupportsCountInt, null, transactionsCountInt);

                        int offset2 = supportedLocations[indices[0]] * transactionsCountInt;
                        kernelSum.SetArgument(2, offset2);

                        globalSize = transactionsCountUInt;
                        for (int scaling = 1; scaling < transactionsCountInt; scaling *= (int)localSize)
                        {
                            kernelSum.SetArgument(4, scaling);
                            globalSize = Kernels.GetOptimalGlobalSize(localSize, globalSize);
                            kernelSum.Launch1D(queue, globalSize, localSize);
                            globalSize /= localSize;
                        }

                        transactionsSupportsBufCopy.Read(tempValue, (uint)offset2, 1);

                        if (tempValue[0] > transactionsSupportsCountInt)
                        {
                            // это означает, что данные были повреждены из-за:
                            // a) некоторая ошибка памяти gpu,
                            // б) плохая синхронизация,
                            // c) или какая-то другая неизвестная вещь
                            // эта ситуация встречается редко, только с очень большими данными
                            // Неизвестная причина неизвестна
                            itemsSupportsBufCopy.Read();
                            transactionsSupportsBufCopy.Read();
                            customersSupportsBufCopy.Read();
                            itemsSupportsBuf.Read();
                            transactionsSupportsBuf.Read();
                            customersSupportsBuf.Read();
                            // эта ошибка является серьезной: она предотвращает продолжение алгоритма
                            throw new Exception(String.Format("{0} больше {1}, невозможно!\n {2}",
                                                              tempValue[0], transactionsSupportsCountInt, String.Join(",", transactionsSupports)));
                        }


                        if (tempValue[0] >= minSupport)
                        {
                            ILitemset l = new Litemset(new List <IItem>());
                            l.SetSupport(tempValue[0]);
                            for (int i = 0; i < currLength; ++i)
                            {
                                int index  = indices[i];
                                int spprtd = supportedLocations[index];
                                l.AddItem(new Item(uniqueItems[spprtd]));
                                newSupportedLocations[spprtd] = true;
                            }



                            litemsets.Add(l);
                        }

                        #region selecting new indices (from supportedLocations) to analyze
                        if ((currIndex == 0 && indices[currIndex] == supportedLocations.Count - currLength) ||
                            currLength == supportedLocations.Count)
                        {
                            break;
                        }
                        if (indices[currIndex] == supportedLocations.Count - currLength + currIndex)
                        {
                            ++indices[currIndex - 1];
                            if (indices[currIndex - 1] + 1 < indices[currIndex])
                            {
                                while (currIndex < currLength - 1)
                                {
                                    indices[currIndex] = indices[currIndex - 1] + 1;
                                    ++currIndex;
                                }
                                indices[currIndex] = indices[currIndex - 1] + 1;
                            }
                            else
                            {
                                --currIndex;
                            }
                            continue;
                        }
                        indices[currIndex] += 1;
                        #endregion
                    }

                    if (progressOutput)
                    {
                        Log.WriteLine("наконец, {0}, до настоящего времени найдено {1} l-itemsets", currLength, litemsets.Count);
                    }


                    if (litemsets.Count <= litemsetOffset || currLength >= uniqueItemsCount)
                    {
                        moreCanBeFound = false;
                        break;
                    }

                    supportedLocations.Clear();
                    for (int i = 0; i < uniqueItemsCount; ++i)
                    {
                        if (newSupportedLocations[i])
                        {
                            supportedLocations.Add(i);
                            newSupportedLocations[i] = false;
                        }
                    }

                    if (currLength >= supportedLocations.Count)
                    {
                        // слишком мало поддерживаемых отдельных элементов, чтобы сделать кандидата требуемой длины
                        moreCanBeFound = false;
                        break;
                    }
                }

                queue.Finish();

                currLengthBuf.Dispose();
                locationsBuf.Dispose();
            }
            #endregion

            if (progressOutput)
            {
                watch.Stop();
                Log.WriteLine("Сгенерировал все l-itemsets, нашел {0} в {1} мс.", litemsets.Count, watch.ElapsedMilliseconds);
            }

            queue.Finish();

            #region disposing of buffers

            // входные буферы
            itemsBuf.Dispose();
            transactionsStartsBuf.Dispose();
            customersStartsBuf.Dispose();
            itemsCountBuf.Dispose();
            transactionsCountBuf.Dispose();
            customersCountBuf.Dispose();

            // создание элементовПоддержка
            emptyIdBuf.Dispose();

            // хранение уникальных предметов
            uniqueItemBuf.Dispose();
            uniqueItemsBuf.Dispose();

            // поддерживает хранение
            itemsSupportsBuf.Dispose();
            itemsSupportsCountBuf.Dispose();
            itemsSupportsBufCopy.Dispose();
            transactionsSupportsBuf.Dispose();
            transactionsSupportsCountBuf.Dispose();
            transactionsSupportsBufCopy.Dispose();
            customersSupportsBuf.Dispose();
            customersSupportsCountBuf.Dispose();
            customersSupportsBufCopy.Dispose();

            // временная память
            tempItemsBuf.Dispose();
            itemsRemainingBuf.Dispose();

            // константы
            Zero.Dispose();
            One.Dispose();

            #endregion

            queue.Dispose();
            Kernels.Dispose();

            return(litemsets);
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: ISSS163/Image_project
        //PATTERN Фабричный метод (простейший вариант)
        static IFilter CreateFilter(string filterName, List <string> args)
        {
            //количество аргументов
            int argsCount = args == null ? 0 : args.Count;

            try
            {
                switch (filterName)
                {
                case FilterNames.FILTER_BLUR:
                {
                    int size = ParseArg <int>(args, 0, 3, "Invalid size");
                    return(new ConvolutionalFilter(Kernels.GetUniformKernel(size, size)));
                }

                case FilterNames.FILTER_GAUSSIAN_BLUR:
                {
                    int   size  = ParseArg <int>(args, 0, 3, "Invalid size");
                    float sigma = ParseArg <float>(args, 1, 1, "Invalid StdDev");

                    return(new ConvolutionalFilter(Kernels.GetGaussianKernel(size, sigma)));
                }

                case FilterNames.FILTER_UNIFORM_NOISE:
                {
                    int amplitude = ParseArg <int>(args, 0, 3, "Invalid amplitude");
                    return(new UniformNoise(amplitude));
                }

                case FilterNames.FILTER_GAUSSIAN_NOISE:
                {
                    float sigma = ParseArg <float>(args, 0, 0.15f, "Invalid StdDev");
                    return(new GaussianNoise(sigma));
                }

                case FilterNames.FILTER_LAPLACE:
                {
                    return(new EdgeDetection(EdgeDetection.EdgeDetectionAlgorithm.Laplace));
                }

                case FilterNames.FILTER_PREWITT:
                {
                    return(new EdgeDetection(EdgeDetection.EdgeDetectionAlgorithm.Prewitt));
                }

                case FilterNames.FILTER_SHARR:
                {
                    return(new EdgeDetection(EdgeDetection.EdgeDetectionAlgorithm.Sharr));
                }

                case FilterNames.FILTER_SOBEL:
                {
                    return(new EdgeDetection(EdgeDetection.EdgeDetectionAlgorithm.Sobel));
                }

                case FilterNames.FILTER_CONTRAST:
                {
                    float maxValue = ParseArg <float>(args, 0, 255, "Invalid max value");
                    float minValue = ParseArg <float>(args, 1, 0, "Invalid min value");

                    return(new Contrast(maxValue, minValue));
                }

                case FilterNames.FILTER_SHARP:
                {
                    return(new ConvolutionalFilter(Kernels.GetSharpeningKernel()));
                }

                case FilterNames.FILTER_LOG_CONTRAST:
                {
                    return(new LogConstrast());
                }

                case FilterNames.FILTER_HSV:
                {
                    return(new ColorSpaceConversion(ColorSpaceConversion.ConversionType.RGB2HSV));
                }

                case FilterNames.FILTER_HSV2RGB:
                {
                    return(new ColorSpaceConversion(ColorSpaceConversion.ConversionType.HSV2RGB));
                }

                case FilterNames.FILTER_YCbCR:
                {
                    return(new ColorSpaceConversion(ColorSpaceConversion.ConversionType.RGB2YCbCr));
                }

                case FilterNames.FILTER_YCbCR2RGB:
                {
                    return(new ColorSpaceConversion(ColorSpaceConversion.ConversionType.YCbCr2RGB));
                }

                case FilterNames.FILTER_BINARIZATION:
                {
                    float edge = ParseArg <int>(args, 0, 128, "Invalid threshold value");
                    return(new BinarizationFilter(edge));
                }

                case FilterNames.FILTER_IMPULSE_NOISE:
                {
                    float p = ParseArg <float>(args, 0, 0.1f, "Invalid probability value");
                    return(new ImpulseNoise(p));
                }

                case FilterNames.FILTER_GRAYSCALE:
                {
                    return(new ColorSpaceConversion(ColorSpaceConversion.ConversionType.RGB2Gray));
                }

                case FilterNames.FILTER_LOW_PASS:
                {
                    float s = ParseArg <float>(args, 0, 0.15f, "Invalid parameter");
                    return(new FrequencyFilter(FrequencyFilter.FilterMode.LowPass, s));
                }

                case FilterNames.FILTER_HIGH_PASS:
                {
                    float s = ParseArg <float>(args, 0, 0.15f, "Invalid parameter");
                    return(new FrequencyFilter(FrequencyFilter.FilterMode.HighPass, s));
                }

                default:
                    throw new NotSupportedException("Unsupported filter");
                }
            }
            catch (ArgumentException e)
            {
                throw new ArgumentException(filterName + ": " + e.Message, e);
            }
        }
コード例 #22
0
 public double[][,,] GetWeights()
 {
     return(Kernels.Select(q => q).ToArray());
 }
コード例 #23
0
    void Simulate(float dt)
    {
        /* Compute Density and pressure */
        foreach (Particle p0 in particles)
        {
            p0.density = 0.0f;

            foreach (Particle p1 in grid.GetNearby(p0))
            {
                if (p0 == p1)
                {
                    continue;
                }

                float distSqr = (p0.position - p1.position).sqrMagnitude;

                if (distSqr <= smoothingRadius * smoothingRadius)
                {
                    p0.density += mass * Kernels.Poly6(distSqr, smoothingRadius);
                }
            }

            p0.density = Mathf.Max(p0.density, restDensity);

            ComputeParticlePressure(p0);
        }


        /* Compute forces */
        foreach (Particle p0 in particles)
        {
            p0.force = Vector2.zero;
            Vector2 pressureGradient  = Vector2.zero;
            Vector2 viscosityGradient = Vector2.zero;

            foreach (Particle p1 in grid.GetNearby(p0))
            {
                if (p0 == p1)
                {
                    continue;
                }

                if (usePressureForce == true)
                {
                    pressureGradient += PressureForce(p0, p1);
                }

                if (useViscosityForce == true)
                {
                    viscosityGradient += ViscosityForce(p0, p1);
                }
            }

            p0.force += pressureGradient + viscosityGradient;
            ExternalForces(p0);
        }

        /* Integrate motion */
        /* Leapfrog integration */
        foreach (Particle particle in particles)
        {
            ForceBounds(particle);

            Vector2 acceleration = particle.force;
            particle.velocity += 0.5f * (particle.oldAcceleration + acceleration) * dt;

            Vector2 deltaPos = particle.velocity * dt + 0.5f * acceleration * dt * dt;
            // if (deltaPos.sqrMagnitude > smoothingRadius * smoothingRadius) {
            //  deltaPos = Vector2.zero;
            // }

            particle.position       += deltaPos;
            particle.oldAcceleration = acceleration;
        }
    }
コード例 #24
0
ファイル: Convolution.cs プロジェクト: kapkapas/Neuro
 internal override void DeserializeParameters(XmlElement elem)
 {
     base.DeserializeParameters(elem);
     Kernels.Deserialize(elem["Kernels"]);
     Bias.Deserialize(elem["Bias"]);
 }
コード例 #25
0
ファイル: CELTDecoder.cs プロジェクト: windperson/concentus
        internal void celt_decode_lost(int N, int LM)
        {
            int c;
            int i;
            int C = this.channels;

            int[][]  out_syn      = new int[2][];
            int[]    out_syn_ptrs = new int[2];
            CeltMode mode;
            int      nbEBands;
            int      overlap;
            int      noise_based;

            short[] eBands;

            mode     = this.mode;
            nbEBands = mode.nbEBands;
            overlap  = mode.overlap;
            eBands   = mode.eBands;

            c = 0; do
            {
                out_syn[c]      = this.decode_mem[c];
                out_syn_ptrs[c] = CeltConstants.DECODE_BUFFER_SIZE - N;
            } while (++c < C);

            noise_based = (loss_count >= 5 || start != 0) ? 1 : 0;
            if (noise_based != 0)
            {
                /* Noise-based PLC/CNG */
                int[][] X;
                uint    seed;
                int     end;
                int     effEnd;
                int     decay;
                end    = this.end;
                effEnd = Inlines.IMAX(start, Inlines.IMIN(end, mode.effEBands));

                X = Arrays.InitTwoDimensionalArray <int>(C, N);   /**< Interleaved normalised MDCTs */

                /* Energy decay */
                decay = loss_count == 0 ? ((short)(0.5 + (1.5f) * (((int)1) << (CeltConstants.DB_SHIFT)))) /*Inlines.QCONST16(1.5f, CeltConstants.DB_SHIFT)*/ : ((short)(0.5 + (0.5f) * (((int)1) << (CeltConstants.DB_SHIFT)))) /*Inlines.QCONST16(0.5f, CeltConstants.DB_SHIFT)*/;
                c     = 0; do
                {
                    for (i = start; i < end; i++)
                    {
                        this.oldEBands[c * nbEBands + i] = Inlines.MAX16(backgroundLogE[c * nbEBands + i], this.oldEBands[c * nbEBands + i] - decay);
                    }
                } while (++c < C);
                seed = this.rng;
                for (c = 0; c < C; c++)
                {
                    for (i = start; i < effEnd; i++)
                    {
                        int j;
                        int boffs;
                        int blen;
                        boffs = (eBands[i] << LM);
                        blen  = (eBands[i + 1] - eBands[i]) << LM;
                        for (j = 0; j < blen; j++)
                        {
                            seed            = Bands.celt_lcg_rand(seed);
                            X[c][boffs + j] = (unchecked ((int)seed) >> 20);
                        }

                        VQ.renormalise_vector(X[c], 0, blen, CeltConstants.Q15ONE);
                    }
                }
                this.rng = seed;

                c = 0;
                do
                {
                    Arrays.MemMoveInt(this.decode_mem[c], N, 0, CeltConstants.DECODE_BUFFER_SIZE - N + (overlap >> 1));
                } while (++c < C);

                CeltCommon.celt_synthesis(mode, X, out_syn, out_syn_ptrs, this.oldEBands, start, effEnd, C, C, 0, LM, this.downsample, 0);
            }
            else
            {
                /* Pitch-based PLC */
                int[] window;
                int   fade = CeltConstants.Q15ONE;
                int   pitch_index;
                int[] etmp;
                int[] exc;

                if (loss_count == 0)
                {
                    this.last_pitch_index = pitch_index = CeltCommon.celt_plc_pitch_search(this.decode_mem, C);
                }
                else
                {
                    pitch_index = this.last_pitch_index;
                    fade        = ((short)(0.5 + (.8f) * (((int)1) << (15)))) /*Inlines.QCONST16(.8f, 15)*/;
                }

                etmp   = new int[overlap];
                exc    = new int[CeltConstants.MAX_PERIOD];
                window = mode.window;
                c      = 0; do
                {
                    int   decay;
                    int   attenuation;
                    int   S1 = 0;
                    int[] buf;
                    int   extrapolation_offset;
                    int   extrapolation_len;
                    int   exc_length;
                    int   j;

                    buf = this.decode_mem[c];
                    for (i = 0; i < CeltConstants.MAX_PERIOD; i++)
                    {
                        exc[i] = Inlines.ROUND16(buf[CeltConstants.DECODE_BUFFER_SIZE - CeltConstants.MAX_PERIOD + i], CeltConstants.SIG_SHIFT);
                    }

                    if (loss_count == 0)
                    {
                        int[] ac = new int[CeltConstants.LPC_ORDER + 1];

                        /* Compute LPC coefficients for the last MAX_PERIOD samples before
                         * the first loss so we can work in the excitation-filter domain. */
                        Autocorrelation._celt_autocorr(exc, ac, window, overlap,
                                                       CeltConstants.LPC_ORDER, CeltConstants.MAX_PERIOD);
                        /* Add a noise floor of -40 dB. */
                        ac[0] += Inlines.SHR32(ac[0], 13);
                        /* Use lag windowing to stabilize the Levinson-Durbin recursion. */
                        for (i = 1; i <= CeltConstants.LPC_ORDER; i++)
                        {
                            /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
                            ac[i] -= Inlines.MULT16_32_Q15(2 * i * i, ac[i]);
                        }
                        CeltLPC.celt_lpc(this.lpc[c], ac, CeltConstants.LPC_ORDER);
                    }

                    /* We want the excitation for 2 pitch periods in order to look for a
                     * decaying signal, but we can't get more than MAX_PERIOD. */
                    exc_length = Inlines.IMIN(2 * pitch_index, CeltConstants.MAX_PERIOD);

                    /* Initialize the LPC history with the samples just before the start
                     * of the region for which we're computing the excitation. */
                    {
                        int[] lpc_mem = new int[CeltConstants.LPC_ORDER];
                        for (i = 0; i < CeltConstants.LPC_ORDER; i++)
                        {
                            lpc_mem[i] =
                                Inlines.ROUND16(buf[CeltConstants.DECODE_BUFFER_SIZE - exc_length - 1 - i], CeltConstants.SIG_SHIFT);
                        }

                        /* Compute the excitation for exc_length samples before the loss. */
                        Kernels.celt_fir(exc, (CeltConstants.MAX_PERIOD - exc_length), this.lpc[c], 0,
                                         exc, (CeltConstants.MAX_PERIOD - exc_length), exc_length, CeltConstants.LPC_ORDER, lpc_mem);
                    }

                    /* Check if the waveform is decaying, and if so how fast.
                     * We do this to avoid adding energy when concealing in a segment
                     * with decaying energy. */
                    {
                        int E1 = 1, E2 = 1;
                        int decay_length;
                        int shift = Inlines.IMAX(0, 2 * Inlines.celt_zlog2(Inlines.celt_maxabs16(exc, (CeltConstants.MAX_PERIOD - exc_length), exc_length)) - 20);
                        decay_length = exc_length >> 1;
                        for (i = 0; i < decay_length; i++)
                        {
                            int e;
                            e   = exc[CeltConstants.MAX_PERIOD - decay_length + i];
                            E1 += Inlines.SHR32(Inlines.MULT16_16(e, e), shift);
                            e   = exc[CeltConstants.MAX_PERIOD - 2 * decay_length + i];
                            E2 += Inlines.SHR32(Inlines.MULT16_16(e, e), shift);
                        }
                        E1    = Inlines.MIN32(E1, E2);
                        decay = Inlines.celt_sqrt(Inlines.frac_div32(Inlines.SHR32(E1, 1), E2));
                    }

                    /* Move the decoder memory one frame to the left to give us room to
                     * add the data for the new frame. We ignore the overlap that extends
                     * past the end of the buffer, because we aren't going to use it. */
                    Arrays.MemMoveInt(buf, N, 0, CeltConstants.DECODE_BUFFER_SIZE - N);

                    /* Extrapolate from the end of the excitation with a period of
                     * "pitch_index", scaling down each period by an additional factor of
                     * "decay". */
                    extrapolation_offset = CeltConstants.MAX_PERIOD - pitch_index;

                    /* We need to extrapolate enough samples to cover a complete MDCT
                     * window (including overlap/2 samples on both sides). */
                    extrapolation_len = N + overlap;
                    /* We also apply fading if this is not the first loss. */
                    attenuation = Inlines.MULT16_16_Q15(fade, decay);
                    for (i = j = 0; i < extrapolation_len; i++, j++)
                    {
                        int tmp;
                        if (j >= pitch_index)
                        {
                            j          -= pitch_index;
                            attenuation = Inlines.MULT16_16_Q15(attenuation, decay);
                        }
                        buf[CeltConstants.DECODE_BUFFER_SIZE - N + i] =
                            Inlines.SHL32((Inlines.MULT16_16_Q15(attenuation,
                                                                 exc[extrapolation_offset + j])), CeltConstants.SIG_SHIFT);

                        /* Compute the energy of the previously decoded signal whose
                         * excitation we're copying. */
                        tmp = Inlines.ROUND16(
                            buf[CeltConstants.DECODE_BUFFER_SIZE - CeltConstants.MAX_PERIOD - N + extrapolation_offset + j],
                            CeltConstants.SIG_SHIFT);
                        S1 += Inlines.SHR32(Inlines.MULT16_16(tmp, tmp), 8);
                    }

                    {
                        int[] lpc_mem = new int[CeltConstants.LPC_ORDER];

                        /* Copy the last decoded samples (prior to the overlap region) to
                         * synthesis filter memory so we can have a continuous signal. */
                        for (i = 0; i < CeltConstants.LPC_ORDER; i++)
                        {
                            lpc_mem[i] = Inlines.ROUND16(buf[CeltConstants.DECODE_BUFFER_SIZE - N - 1 - i], CeltConstants.SIG_SHIFT);
                        }

                        /* Apply the synthesis filter to convert the excitation back into
                         * the signal domain. */
                        CeltLPC.celt_iir(buf, CeltConstants.DECODE_BUFFER_SIZE - N, this.lpc[c],
                                         buf, CeltConstants.DECODE_BUFFER_SIZE - N, extrapolation_len, CeltConstants.LPC_ORDER,
                                         lpc_mem);
                    }

                    /* Check if the synthesis energy is higher than expected, which can
                     * happen with the signal changes during our window. If so,
                     * attenuate. */
                    {
                        int S2 = 0;
                        for (i = 0; i < extrapolation_len; i++)
                        {
                            int tmp = Inlines.ROUND16(buf[CeltConstants.DECODE_BUFFER_SIZE - N + i], CeltConstants.SIG_SHIFT);
                            S2 += Inlines.SHR32(Inlines.MULT16_16(tmp, tmp), 8);
                        }
                        /* This checks for an "explosion" in the synthesis. */
                        if (!(S1 > Inlines.SHR32(S2, 2)))
                        {
                            for (i = 0; i < extrapolation_len; i++)
                            {
                                buf[CeltConstants.DECODE_BUFFER_SIZE - N + i] = 0;
                            }
                        }
                        else if (S1 < S2)
                        {
                            int ratio = Inlines.celt_sqrt(Inlines.frac_div32(Inlines.SHR32(S1, 1) + 1, S2 + 1));
                            for (i = 0; i < overlap; i++)
                            {
                                int tmp_g = CeltConstants.Q15ONE
                                            - Inlines.MULT16_16_Q15(window[i], CeltConstants.Q15ONE - ratio);
                                buf[CeltConstants.DECODE_BUFFER_SIZE - N + i] =
                                    Inlines.MULT16_32_Q15(tmp_g, buf[CeltConstants.DECODE_BUFFER_SIZE - N + i]);
                            }
                            for (i = overlap; i < extrapolation_len; i++)
                            {
                                buf[CeltConstants.DECODE_BUFFER_SIZE - N + i] =
                                    Inlines.MULT16_32_Q15(ratio, buf[CeltConstants.DECODE_BUFFER_SIZE - N + i]);
                            }
                        }
                    }

                    /* Apply the pre-filter to the MDCT overlap for the next frame because
                     * the post-filter will be re-applied in the decoder after the MDCT
                     * overlap. */
                    CeltCommon.comb_filter(etmp, 0, buf, CeltConstants.DECODE_BUFFER_SIZE,
                                           this.postfilter_period, this.postfilter_period, overlap,
                                           -this.postfilter_gain, -this.postfilter_gain,
                                           this.postfilter_tapset, this.postfilter_tapset, null, 0);

                    /* Simulate TDAC on the concealed audio so that it blends with the
                     * MDCT of the next frame. */
                    for (i = 0; i < overlap / 2; i++)
                    {
                        buf[CeltConstants.DECODE_BUFFER_SIZE + i] =
                            Inlines.MULT16_32_Q15(window[i], etmp[overlap - 1 - i])
                            + Inlines.MULT16_32_Q15(window[overlap - i - 1], etmp[i]);
                    }
                } while (++c < C);
            }

            this.loss_count = loss_count + 1;
        }