示例#1
0
        public void AbsoluteMinMax()
        {
            Vector x  = Vector.LinSpace(128, -1, 1);
            var    _x = x.Get <float>();

            double min = x.AbsoluteMinimum();
            double max = x.AbsoluteMaximum();

            double _min = 1e9, _max = 0.0;

            for (int i = 0; i < x.Size; i++)
            {
                if (Math.Abs(_x[i]) < Math.Abs(_min))
                {
                    _min = Math.Abs(_x[i]);
                }
                if (Math.Abs(_x[i]) > Math.Abs(_max))
                {
                    _max = Math.Abs(_x[i]);
                }
            }

            Assert.IsTrue(Math.Abs(min - _min) <= 1e-7);
            Assert.IsTrue(Math.Abs(max - _max) <= 1e-7);
        }
        public static double Eigenvalue(double[,] array)
        {
            Matrix <double> A = DenseMatrix.OfArray(array);

            Evd <double>     eigen       = A.Evd();
            Matrix <double>  eigenvect   = eigen.EigenVectors;
            Vector <Complex> eigenvalues = eigen.EigenValues;

            return(eigenvalues.AbsoluteMaximum().Real);
        }
    void gain_process()
    {
        float maxnum = 0.0f;

        maxnum = gain.AbsoluteMaximum();
        for (int i = 0; i < gain.Count; i++)
        {
            gain[i] /= maxnum;
        }
    }
示例#4
0
        private void ComputePlane(int index)
        {
            Vector <float> p_mass = GetMassPoint();

            Vector <float> n_mass = Vector <float> .Build.Dense(3);

            foreach (Vector <float> n in Normals)
            {
                n_mass += n;
            }
            n_mass = (n_mass / (float)Normals.Count).Normalize(1);

            Vector <float> ppt = p_mass - Intersections[index];
            Vector <float> e   = ppt / ppt.AbsoluteMaximum();

            Vector <float> nnt = n_mass + Normals[index];
            Vector <float> n_e = nnt / nnt.AbsoluteMaximum();

            Vector <float> net = Cross(n_e, e);
            Vector <float> n_s = net / net.AbsoluteMaximum();

            PlaneNs.Add(n_s);
        }
示例#5
0
        /// <summary>
        /// Determines the initial search point.
        /// </summary>
        /// <param name="αprev">The previous α value.</param>
        /// <param name="location">The location.</param>
        /// <param name="values">The function values.</param>
        /// <returns>System.Double.</returns>
        private double DetermineInitialSearchPoint(double αprev, [NotNull] Vector <double> location, ref FunctionValues values)
        {
            // prefetch
            var ψ0          = _ψ0;
            var ψ1          = _ψ1;
            var ψ2          = _ψ2;
            var α0          = _α0;
            var useQuadStep = _quadStepEnabled;

            // for clarity and caching
            var φ   = values.φ;
            var φ0  = values.φ0;
            var dφ0 = values.dφ0;
            var f0  = values.f0;
            var Δf0 = values.Δf0;

            // check if this is the first iteration
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            var isFirstIteration = αprev == 0.0D;

            if (isFirstIteration)
            {
                // if there is a user-defined starting value, then we'll use it.
                if (α0.IsFinite())
                {
                    return(α0);
                }

                // if the starting point is nonzero, calculate a better α
                var supremumNormOfLocation = location.AbsoluteMaximum();
                if (supremumNormOfLocation > 0.0D)
                {
                    var supremumNormOfGradientAtLocation = Δf0.AbsoluteMaximum();
                    return(ψ0 * supremumNormOfLocation / supremumNormOfGradientAtLocation);
                }

                // if the function value is nonzero, calculate the next better α
                var absoluteOfValueAtLocation = Math.Abs(f0);
                if (absoluteOfValueAtLocation > 0.0D)
                {
                    var squaredEuclideanNormOfGradientAtLocation = Δf0 * Δf0;
                    return(ψ0 * absoluteOfValueAtLocation / squaredEuclideanNormOfGradientAtLocation);
                }

                // in any other case, use α = 1
                return(1.0D);
            }

            // check if the user wishes to use quadstep, then check if quadstep may be used
            if (useQuadStep)
            {
                // the key idea here is to find a quadratic approximation q(α) = aα²+bα+c that
                // fulfills the condition q(0)=φ(0), q'(0)=φ'(0) and q(ψ1αprev)=φ(ψ1*αprev).

                // only if the function value at the new position r=ψ1*αprev is actually
                // smaller than the value at the starting position, we'll attempt to
                // interpolate through the starting position and the value at r.
                var r  = ψ1 * αprev;
                var φr = φ(r);
                if (φr <= φ0)
                {
                    var d = r * r;
                    var a = -(φ0 - φr + φr * dφ0) / d;

                    // find the minimizer
                    var rmin = 0.5D * (d * dφ0) / (φ0 - φr + r * dφ0);

                    // in order to have a valid minimizer here, the function must be concave.
                    // This is only the case if a is positve.
                    // We do not need to check the second derivative, since the second
                    // derivative of a concave quadratic function is positive at every point.
                    if (a > 0.0D && rmin >= 0)
                    {
                        return(rmin);
                    }
                }
            }

            // in any other case, simply use a smaller step width than before
            return(ψ2 * αprev);
        }
示例#6
0
        public Vector <Complex32> GaussSolver(SystemArrays array)
        {
            #region "Initialize Vectors & Complex Numbers"
            Vector <Complex32> Vbus = Vector <Complex32> .Build.Dense(array.numBuses);

            Vector <Complex32> PQbus = Vector <Complex32> .Build.Dense(array.numBuses);

            double tolerance = 1.0e-6;

            Complex32 accel    = new Complex32(1.6f, 0.0f); //remove
            Complex32 sumIRem  = new Complex32(0.0f, 0.0f);
            Complex32 sumPVRem = new Complex32(0.0f, 0.0f);

            #endregion
            //assume that this is MakeYBus
            #region Call the method to Generate Vbus complex vector flat start nd fixed voltages
            Vbus = makeVBus(array);
            #endregion

            #region Calculate PQbus which defines net apparent scheduled power into each bus
            PQbus = makePQBus(array);
            #endregion

            #region "Iterate & Calculate Vbus at all buses"

            #region Initialize arrays & variables
            //make new array of PV bus fixed setpoint magnitudes
            Complex32[] VbusSet = new Complex32[array.numBuses];

            //generate a vector for the previous oteratopm calculated values of Vbus
            //to subtract from latest calculated, and compare to tolerance
            Vector <Complex32> VbusOld = Vector <Complex32> .Build.Dense(array.numBuses);

            Vector <Complex32> VbusDiff = Vector <Complex32> .Build.Dense(array.numBuses);

            //initialize Ybus
            array = InitializeYBus(array);

            //initialize the 'previous' Vbus values to the initial flat start values
            Vbus.CopyTo(VbusOld);

            //Define the maximum, absolute magnitude of bus voltage difference of all buses
            //since previous iteration
            double diff = 1.0;
            #endregion

            while (diff > tolerance)
            {
                //SOLVE V for each bus once
                //parallel for(0,array.numBuses, 1=>
                for (int i = 0; i < array.numBuses; i++)
                {
                    #region Solve for PQ (load) buses (Type 1)
                    if (array.bus[i].BusType == 1)
                    {
                        //calculate all remote  bus current components
                        for (int j = 0; j < array.numBuses; j++)
                        {
                            if (j == 1)
                            {
                                continue;
                            }
                            //sum of components at remote bus numbers greater than i
                            sumIRem += array.Ybus[i, j] * Vbus[j];
                        }
                        //calculate local bus current components
                        //Vbus[i] = (i/array.Ybus[i,i]) * ((PQbus[i].Conjugate() / Vbus[i].Conjugate()) - sumIRem);
                        Vbus[i] = (i / array.Ybus[i, i]) * ((PQbus[i] / Vbus[i].Conjugate()) - sumIRem);

                        //calculate acceleration and update Vbus with accelerated values
                        VbusDiff[i] = Vbus[i] - VbusOld[i];
                        Vbus[i]     = VbusOld[i] + VbusDiff[i] * accel;
                    }
                    sumIRem  = 0;
                    sumPVRem = 0;
                    #endregion

                    #region Solve for PV (generator) buses (Type 2)
                    if (array.bus[i].BusType == 2)
                    {
                        VbusSet[i] = Vbus[i].Magnitude;

                        //calculate all remote bus current components
                        for (int j = 0; j < array.numBuses; j++)
                        {
                            sumPVRem += array.Ybus[i, j] * Vbus[j];
                        }

                        //calculate first VARs at the local bus
                        float Qnew = -(Vbus[i].Conjugate() * sumPVRem).Imaginary;

                        sumPVRem = 0;
                        //calculate local voltage usigng new value of Q
                        PQbus[i] = new Complex32(PQbus[i].Real, Qnew);

                        for (int j = 0; j < array.numBuses; j++)
                        {
                            if (j == i)
                            {
                                continue;
                            }
                            sumPVRem += array.Ybus[i, j] * Vbus[j];
                        }

                        Vbus[i] = (1 / array.Ybus[i, i]) * ((PQbus[i].Conjugate()) - sumPVRem);
                        //force Vbus[i] magnitude to voltage setpoint, and angle to newly calculated Vbus[i] voltage
                        Vbus[i] = VbusSet[i] * Vbus[i] / Vbus[i].Magnitude;
                    }
                    #endregion


                    //goto next bus
                    sumIRem  = 0;
                    sumPVRem = 0;
                }

                //ALL BUS voltages have been calculated for this iteration
                //start next iteration (k)
                iterations++;

                //give the magnitude of greatest value in VbusDiff vector
                diff = VbusDiff.AbsoluteMaximum().Real;

                //note: you cannot set one vector equal to the other or they will be considered the same
                //You must instead copy the values from one to the other
                //copy the latest Vbus Vector elements to VbusOld vector
                Vbus.CopyTo(VbusOld);
            }
            #endregion

            return(Vbus);
        }
示例#7
0
        private void Readjust()
        {
            double truncateMin = double.NaN;
            double truncateMax = double.NaN;
            double extrapolateMax = double.NaN, extrapolateMin = double.NaN;
            double TFMinVal = double.NaN, TFMaxVal = double.NaN;
            double TFMinPhase = double.NaN, TFMaxPhase = double.NaN;

            TruncateErrorLabel.Text    = "";
            ExtrapolateErrorLabel.Text = "";
            forcedValsErrorLabel.Text  = "";
            bool error = false;
            int  mini  = 0;
            int  maxi  = TFSr.Count - 1;

            TFadjustedZ           = null;
            TFadjustedSr          = null;
            adjustmentScaleFactor = 1;

            // Parse Values
            if (TruncateMinTextBox.Text.Trim() != "" &&
                !Double.TryParse(TruncateMinTextBox.Text, out truncateMin))
            {
                TruncateErrorLabel.Text = "<--- Parse error"; error = true;
            }
            if (TruncateMaxTextBox.Text.Trim() != "" &&
                !Double.TryParse(TruncateMaxTextBox.Text, out truncateMax))
            {
                TruncateErrorLabel.Text = "<--- Parse error"; error = true;
            }

            if (ExtrapolateMaxTextBox.Text.Trim() != "" &&
                !Double.TryParse(ExtrapolateMaxTextBox.Text, out extrapolateMax))
            {
                ExtrapolateErrorLabel.Text = "<--- Parse error"; error = true;
            }
            if (ExtrapolateMinTextBox.Text.Trim() != "" &&
                !Double.TryParse(ExtrapolateMinTextBox.Text, out extrapolateMin))
            {
                ExtrapolateErrorLabel.Text = "<--- Parse error"; error = true;
            }

            if (!double.IsNaN(extrapolateMin) &&
                TFminvalueTextbox.Text.Trim() != "" &&
                !Double.TryParse(TFminvalueTextbox.Text, out TFMinVal))
            {
                forcedValsErrorLabel.Text = "<--- Parse error"; error = true;
            }

            if (!double.IsNaN(extrapolateMax) &&
                TFmaxvalueTextbox.Text.Trim() != "" &&
                !Double.TryParse(TFmaxvalueTextbox.Text, out TFMaxVal))
            {
                forcedValsErrorLabel.Text = "<--- Parse error"; error = true;
            }
            if (!double.IsNaN(extrapolateMin) &&
                TFPhaseMinTextBox.Text.Trim() != "" &&
                !Double.TryParse(TFPhaseMinTextBox.Text, out TFMinPhase))
            {
                forcedValsErrorLabel.Text = "<--- Parse error"; error = true;
            }

            if (!double.IsNaN(extrapolateMax) &&
                TFPhaseMaxTextBox.Text.Trim() != "" &&
                !Double.TryParse(TFPhaseMaxTextBox.Text, out TFMaxPhase))
            {
                forcedValsErrorLabel.Text = "<--- Parse error"; error = true;
            }

            if (error)
            {
                return;
            }

            // Truncation Setup
            if (!Double.IsNaN(truncateMin))
            {
                var v = TFz.Find(x => (x + x * 1e-5 >= truncateMin));
                if (v != null)
                {
                    mini = v.Item1;
                }
                else
                {
                    TruncateErrorLabel.Text = "<--- No values remaining"; error = true;
                }
            }
            if (!Double.IsNaN(truncateMax))
            {
                var v = TFz.Find(x => (x - x * 1e-5 > truncateMax));
                if (v == null)
                {
                    maxi = TFz.Count - 1;
                }
                else if (v.Item1 == 0)
                {
                    TruncateErrorLabel.Text = "<--- No values remaining"; error = true;
                }
                else
                {
                    maxi = v.Item1 - 1;
                }
            }
            if (!error && maxi < mini)
            {
                TruncateErrorLabel.Text = "<--- No values remaining"; error = true;
            }
            if (error)
            {
                TFadjustedZ  = null;
                TFadjustedSr = null;
                return;
            }


            // Truncate
            TFadjustedZ  = TFz.SubVector(mini, maxi - mini + 1);
            TFadjustedSr = TFSr.SubVector(mini, maxi - mini + 1);

            // Must only unwrap once, and must be done before truncation to be consistant with the plotted reference phase
            IEnumerable <double> phase = TFSr.Map(x => x.Phase).Unwrap();

            phase = phase.Skip(mini).Take(maxi - mini + 1);
            IEnumerable <double> phasez = TFadjustedZ;
            IEnumerable <double> magz   = TFadjustedZ;
            IEnumerable <double> mag    = TFadjustedSr.Map(x => x.Magnitude);

            // Extrapolation
            if (!double.IsNaN(extrapolateMax))
            {
                double currentMax = TFadjustedZ.Last();
                if (TFz.Count < 3)
                {
                    ExtrapolateErrorLabel.Text = "<--- At least three datapoints required"; error = true;
                }
                else if (extrapolateMax > currentMax)
                {
                    double dx       = TFadjustedZ[1] - TFadjustedZ[0];
                    int    numextra = (int)((extrapolateMax - currentMax) / dx);
                    if (numextra > 300)
                    {
                        ExtrapolateErrorLabel.Text = "<--- Only 300 points may be extrapolated"; error = true;
                    }
                    else
                    {
                        List <double> newx = new List <double>();
                        double        xi   = TFadjustedZ.Last() + dx;
                        while (xi - dx / 10 < extrapolateMax)
                        {
                            newx.Add(xi);
                            xi = xi + dx;
                        }
                        //newx.Add(extrapolateMax);

                        // append extra finish point, if existing
                        if (!double.IsNaN(TFMaxVal))
                        {
                            magz = magz.Concat(new double[] { extrapolateMax });
                            mag  = mag.Concat(new double[] { TFMaxVal });
                        }

                        // append extra phase point
                        if (!double.IsNaN(TFMaxPhase))
                        {
                            phasez = phasez.Concat(new double[] { extrapolateMax });
                            phase  = phase.Concat(new double[] { TFMaxPhase });
                        }
                        // And interpolate!
                        try {
                            var magspline  = MakeInterpolator(magz, mag); // use forced point, if any
                            var phasepline = MakeInterpolator(phasez, phase);
                            //newx[numextra - 1] = extrapolateMax; // force last point to be the required point
                            var newy = newx.Select(x => Complex.FromPolarCoordinates(
                                                       magspline(x), phasepline(x)));
                            TFadjustedZ = Vector <double> .Build.DenseOfEnumerable(TFadjustedZ.Concat(newx));

                            TFadjustedSr = Vector <Complex> .Build.DenseOfEnumerable(TFadjustedSr.Concat(newy));
                        } catch (Exception e) {
                            ExtrapolateErrorLabel.Text = e.Message; error = true;
                            TFadjustedZ  = null;
                            TFadjustedSr = null;
                            return;
                        }
                    }
                }
            }
            if (!double.IsNaN(extrapolateMin))
            {
                double currentMin = TFadjustedZ[0];
                if (TFz.Count < 3)
                {
                    ExtrapolateErrorLabel.Text = "<--- At least three datapoints required"; error = true;
                }
                else if (extrapolateMin < currentMin)
                {
                    double dx       = TFadjustedZ[1] - TFadjustedZ[0];
                    int    numextra = 1 + (int)((currentMin - extrapolateMin) / dx);
                    if (numextra > 300)
                    {
                        ExtrapolateErrorLabel.Text = "<--- Only 300 points may be extrapolated"; error = true;
                    }
                    else
                    {
                        List <double> newx = new List <double>();
                        double        xi   = TFadjustedZ[0] - dx;
                        while (xi + dx / 10 > extrapolateMin)
                        {
                            newx.Add(xi);
                            xi = xi - dx;
                        }
                        //newx.Add(extrapolateMin);
                        newx.Reverse();

                        // append extra finish point, if existing
                        if (!double.IsNaN(TFMinVal))
                        {
                            magz = (new double[] { extrapolateMin }).Concat(magz);
                            mag  = (new double[] { TFMinVal }).Concat(mag);
                        }

                        // append extra phase point
                        if (!double.IsNaN(TFMinPhase))
                        {
                            phasez = (new double[] { extrapolateMin }).Concat(phasez);
                            phase  = (new double[] { TFMinPhase }).Concat(phase);
                        }

                        try {
                            var magspline  = MakeInterpolator(magz, mag);
                            var phasepline = MakeInterpolator(phasez, phase);
                            var newy       = newx.Select(x => Complex.FromPolarCoordinates(
                                                             magspline(x), phasepline(x)));
                            TFadjustedZ = Vector <double> .Build.DenseOfEnumerable(newx.Concat(TFadjustedZ));

                            TFadjustedSr = Vector <Complex> .Build.DenseOfEnumerable(newy.Concat(TFadjustedSr));
                        }
                        catch (Exception e) {
                            ExtrapolateErrorLabel.Text = e.Message; error = true;
                            TFadjustedZ  = null;
                            TFadjustedSr = null;
                            return;
                        }
                    }
                }
            }
            if (error)
            {
                TFadjustedZ  = null;
                TFadjustedSr = null;
                return;
            }
            // Normalization
            if (NormalizeCheckBox.Checked)
            {
                double max = TFadjustedSr.AbsoluteMaximum().Magnitude;
                if (max > 0)
                {
                    adjustmentScaleFactor = 1 / max;
                    TFadjustedSr          = TFadjustedSr.Divide(max);
                }
            }
        }
示例#8
0
        private void Replot()
        {
            TFadjustedSr = null;
            TFadjustedZ  = null;
            double scaleFactor    = 1;
            double bkgScaleFactor = 1;

            if (TFSr != null)
            {
                Readjust();
            }
            if (NormalizeCheckBox.Checked)
            {
                if (BkgSr != null)
                {
                    bkgScaleFactor = (BkgSr.AbsoluteMaximum().Magnitude);
                }
                if (bkgScaleFactor == 0)
                {
                    bkgScaleFactor = 1;
                }
                else
                {
                    bkgScaleFactor = 1 / bkgScaleFactor;
                }
            }

            var    magGP   = MagGraphControl.GraphPane;
            var    phaseGP = phaseGraphControl.GraphPane;
            double begin;

            if (double.TryParse(TruncateMinTextBox.Text, out begin))
            {
                //parsing successful
            }
            else
            {
                //parsing failed.
            }
            magGP.CurveList.Clear();
            phaseGP.CurveList.Clear();
            string normStr = "";

            if (NormalizeCheckBox.Checked)
            {
                normStr = " (normalized)";
            }
            if (Bkgz != null && BkgSr != null)
            {
                AddTFToGps(Bkgz, BkgSr, begin, "Reference" + normStr, Color.Gray, SymbolType.None, drawLine: true,
                           scaleFactor: bkgScaleFactor, style: System.Drawing.Drawing2D.DashStyle.Dash);
            }
            if (TFz != null && TFSr != null)
            {
                AddTFToGps(TFz, TFSr, begin, "TF" + normStr, Color.Blue, SymbolType.XCross, drawLine: false,
                           scaleFactor: adjustmentScaleFactor);
            }
            if (TFadjustedZ != null && TFadjustedSr != null)
            {
                AddTFToGps(TFadjustedZ, TFadjustedSr, begin, "Adjusted TF",
                           color: Color.Black, symbol: SymbolType.XCross, drawLine: true);
            }

            magGP.AxisChange();
            phaseGP.AxisChange();
            MagGraphControl.Invalidate();
            phaseGraphControl.Invalidate();
        }