예제 #1
0
        private IDistribution createGaussianMixture(double mean, double std, double mean2, double std2)
        {
            IDistribution d1 = create1DGaussian(mean, std);
            IDistribution d2 = create1DGaussian(mean2, std2);

            int dim = 1;

            string [] names = new string [1] {
                "x"
            };
            double [] mins = new double [1] {
                0.00
            };
            double [] maxs = new double [1] {
                100.0
            };
            IBlauSpace s = BlauSpace.create(dim, names, mins, maxs);
            Mixture    d = new Mixture(s);

            d.Add(d1, 0.75);
            d.Add(d2, 0.25);
            d.DistributionComplete();

            return(d);
        }
예제 #2
0
        public void TestCombinatorics()
        {
            Model model = new Model("Test Model", Guid.NewGuid());
            BasicReactionSupporter brs = new BasicReactionSupporter();

            InitializeForTesting(brs);

            Mixture mixture = new Mixture(model, "Contents of vat 1", Guid.NewGuid());

            MaterialCatalog cat = brs.MyMaterialCatalog;

            AddSubstance(ref mixture, cat["Nitrous Acid"], 100, 20);
            AddSubstance(ref mixture, cat["Potassium Hydroxide"], 150, 41);
            AddSubstance(ref mixture, cat["Water"], 100, 100);
            Assert.IsTrue(mixture.Mass.Equals(350D), "Mass is not 350 kg");
            Assert.IsTrue(Math.Abs(mixture.Temperature - (18150D / 350D)) < 0.00001, "Temperature is not 51.86724 C.");

            IMaterial matl = mixture.RemoveMaterial(cat["Nitrous Acid"]);

            Debug.WriteLine("Removing all avaliable " + matl.MaterialType.Name);
            DiagnosticAids.DumpMaterial(mixture);
            Assert.IsTrue(mixture.Mass.Equals(250D), "Mass is not 250 kg");

            Debug.WriteLine("Adding " + matl.MaterialType.Name + " back in.");
            mixture.AddMaterial(matl);
            DiagnosticAids.DumpMaterial(mixture);
            Assert.IsTrue(mixture.Mass.Equals(350D), "Mass is not 350 kg");

            Debug.WriteLine("Removing 50 kg of the " + matl.MaterialType.Name);
            matl = mixture.RemoveMaterial(matl.MaterialType, 50.0);
            DiagnosticAids.DumpMaterial(mixture);
            Assert.IsTrue(mixture.Mass.Equals(300D), "Mass is not 300 kg");
        }
예제 #3
0
        /// <summary>
        ///   Initializes the model with initial values obtained
        ///   throught a run of the K-Means clustering algorithm.
        /// </summary>
        public void Initialize(KMeans kmeans)
        {
            int components = clusters.Count;

            if (kmeans.K != components)
            {
                throw new ArgumentException("The number of clusters does not match.", "kmeans");
            }

            // Initialize the Mixture Model with data from K-Means
            var proportions   = kmeans.Clusters.Proportions;
            var distributions = new NormalDistribution[components];

            for (int i = 0; i < components; i++)
            {
                double[] mean = kmeans.Clusters.Centroids[i];
                double[,] covariance = kmeans.Clusters.Covariances[i];

                if (!covariance.IsPositiveDefinite())
                {
                    covariance = Matrix.Identity(kmeans.Dimension);
                }

                distributions[i] = new NormalDistribution(mean, covariance);
            }

            this.model = new Mixture <NormalDistribution>(proportions, distributions);
        }
            public TCTestJig(double tSrc, double tMix, double tAmb, double tSet, double rampRatePerMinute, double err, TemperatureControllerMode tcMode, bool tcEnabled)
            {
                BasicReactionSupporter brs = new BasicReactionSupporter();

                Initialize(brs);
                m_mixture = new Mixture(null, "Test Mixture");
                brs.MyReactionProcessor.Watch(m_mixture);
                Container container = new Container(1000, m_mixture);                // Container full volume is 1000 liters.

                m_tempController = new TemperatureController(container);

                m_mixture.AddMaterial(brs.MyMaterialCatalog["Water"].CreateMass(250, tMix));          // Add 250 kg.
                m_mixture.AddMaterial(brs.MyMaterialCatalog["Sodium Nitrite"].CreateMass(100, tMix)); // Add 100 kg NaNO2.

                m_tempController.AmbientTemperature = tAmb;                                           // degreeC

                // Error band functionality has been obsoleted.
                //m_tempController.ErrorBand = err;         // +/- err degreeC dead band.
                m_err = err;                                             // Used for acceptability of non-precise results.

                m_tempController.SetAmbientThermalConductance(.30, .25); // .25 W/degreeC
                m_tempController.SetAmbientThermalConductance(.60, .50); // .50 W/degreeC
                m_tempController.SetAmbientThermalConductance(.90, .75); // .75 W/degreeC
                m_tempController.SetThermalConductance(.30, .40);        // .4 W/degreeC
                m_tempController.SetThermalConductance(.60, .80);        // .8 W/degreeC
                m_tempController.SetThermalConductance(.90, .120);       // 1.2 W/degreeC

                m_tempController.TCEnabled             = tcEnabled;      // Temperature control system is on.
                m_tempController.TCMode                = tcMode;         // Temperature control system maintains a constant deltaT, or a constant tSrc.
                m_tempController.TCSetpoint            = tSet;
                m_tempController.TCSrcTemperature      = tSrc;           // Syltherm (e.g.) temperature.
                m_tempController.TCSrcDelta            = tSrc;           // To be used if/when the system is in constant delta mode.
                m_tempController.TCTemperatureRampRate = new TemperatureRampRate(5.0, TimeSpan.FromMinutes(1));
            }
예제 #5
0
        private void InitializeWeightsAndDistributionsMixture()
        {
            _distributionWeights = new double[_NumberOfStates][];
            for (var i = 0; i < _NumberOfStates; i++)
            {
                _distributionWeights[i]    = new double[_NumberOfDistributionsInState];
                _distributionWeights[i][0] = 0.5;
                _distributionWeights[i][1] = 0.5;
            }
            var util   = new TestDataUtils();
            var series = util.GetSvcData(util.FTSEFilePath, new DateTime(2010, 12, 18), new DateTime(2011, 12, 18));

            var distributions = CreateEmissions(series, _NumberOfStates * _NumberOfComponents * _NumberOfDistributionsInState);

            _distributions = new Mixture <IMultivariateDistribution> [_NumberOfStates][];
            var index = 0;

            for (int i = 0; i < _NumberOfStates; i++)
            {
                _distributions[i] = new Mixture <IMultivariateDistribution> [_NumberOfDistributionsInState];
                for (int k = 0; k < _NumberOfDistributionsInState; k++)
                {
                    _distributions[i][k] = new Mixture <IMultivariateDistribution>(_NumberOfComponents, series[0].Length);
                    for (int j = 0; j < _NumberOfComponents; j++)
                    {
                        ((Mixture <IMultivariateDistribution>)_distributions[i][k]).Components[j] = distributions[index];
                        index++;
                    }
                }
            }
        }
예제 #6
0
        public void TestBoilingPoints()
        {
            Substance h2o = (Substance)m_brs.MyMaterialCatalog["Water"].CreateMass(1.0, 31);

            double pressure_1Atm = 101325.0;             // pascals.

            Console.WriteLine("BP of water is " + m_brs.MyMaterialCatalog["Water"].GetEstimatedBoilingPoint(pressure_1Atm) + ".");
            Console.WriteLine("BP of ethanol is " + m_brs.MyMaterialCatalog["Ethanol"].GetEstimatedBoilingPoint(pressure_1Atm) + ".");

            m_brs.MyMaterialCatalog.Add(new MaterialType(null, "Rock", Guid.NewGuid(), 4.5, 3.2, MaterialState.Solid, 76, 455));
            //			m_brs.MyMaterialCatalog["Rock"].SetVaporPressureCurveData(new double[]{1.0,2.0,3.0},new double[]{1.0,2.0,3.0});
            //			m_brs.MyMaterialCatalog["Rock"].SetAntoinesCoefficients3(3,6,9);
            //			m_brs.MyMaterialCatalog["Rock"].SetAntoinesCoefficientsExt(3,6);
            //			m_brs.MyMaterialCatalog["Rock"].SetAntoinesCoefficientsExt(3,6,9,12,15,18,21,24,27);
            //			m_brs.MyMaterialCatalog["Rock"].AddEmissionsClassifications(new string[]{"VOC","SARA","HAP","NATA","GHG","ODC"});


            Mixture m = new Mixture("Stone Soup");

            m.AddMaterial((Substance)m_brs.MyMaterialCatalog["Water"].CreateMass(10.0, 37.0));
            m.AddMaterial((Substance)m_brs.MyMaterialCatalog["Rock"].CreateMass(10.0, 37.0));
            m_brs.MyMaterialCatalog["Rock"].STPState = MaterialState.Solid;

            Console.WriteLine("BP of " + m.Name + " is " + m.GetEstimatedBoilingPoint(pressure_1Atm) + ".");

            m = new Mixture("Primordium");
            m.AddMaterial((Substance)m_brs.MyMaterialCatalog["Water"].CreateMass(10.0, 37.0));
            m.AddMaterial((Substance)m_brs.MyMaterialCatalog["Ethanol"].CreateMass(10.0, 37.0));

            Console.WriteLine("BP of " + m.Name + " is " + m.GetEstimatedBoilingPoint(pressure_1Atm) + ".");
        }
예제 #7
0
        public void TestRemoval()
        {
            Model model = new Model("Test Model", Guid.NewGuid());
            BasicReactionSupporter brs = new BasicReactionSupporter();

            InitializeForTesting(brs);

            Mixture         mixture = new Mixture(model, "Contents of vat 1", Guid.NewGuid());
            MaterialCatalog cat     = brs.MyMaterialCatalog;

            mixture.AddMaterial(cat["Acetone"].CreateMass(100, 20));
            mixture.AddMaterial(cat["Potassium Sulfate"].CreateMass(100, 20));
            mixture.AddMaterial(cat["Ammonia"].CreateMass(100, 20));
            Debug.WriteLine("Mixture has the following stuff...");
            DiagnosticAids.DumpMaterial(mixture);
            Assert.IsTrue(mixture.Mass.Equals(300D), "Mixture is not 300 kg");

            Debug.WriteLine("Removing 100 kg of Acetone.");
            IMaterial matl = mixture.RemoveMaterial(cat["Acetone"], 100);

            DiagnosticAids.DumpMaterial(matl);
            Assert.IsTrue(mixture.Mass.Equals(200D), "Mixture is not 200 kg");
            Debug.WriteLine("Remaining is the following mixture:");
            DiagnosticAids.DumpMaterial(mixture);
        }
예제 #8
0
        public static void Run()
        {
            Console.WriteLine("Case4 \n");

            var successor = new Successor();

            Console.WriteLine("var successor = new Successor()");
            Console.WriteLine("successor.CommonProc()");
            successor.CommonProc();
            Console.WriteLine();

            var director = new Director(new CommonModel());

            Console.WriteLine("var director = new Director(new CommonUtil())");
            Console.WriteLine("director.CommonProc()");
            director.CommonProc();
            Console.WriteLine();

            var mixture = new Mixture();

            Console.WriteLine("var mixture = new Mixture()");
            Console.WriteLine("mixture.Hello(\"World\")");
            Console.WriteLine(mixture.Hello("World"));
            Console.WriteLine();
        }
예제 #9
0
        static BsonDocument MixtureToBson(Mixture m)
        {
            var mixtureDoc = m.ToBsonDocument();

            mixtureDoc["Experts"] = ToBson(m.Experts.Select(ExpertToBson));
            return(mixtureDoc);
        }
예제 #10
0
        public void TestPressureTransfer()
        {
            Tester tester = new Tester(m_brs, m_lateBound);

            tester.AddGallons("Dimethylsulfide", 10);
            tester.AddGallons("Water", 10);

            // Create a mixture with a 200,000 gallon volume.
            MaterialType mt            = m_brs.MyMaterialCatalog["Unknown"];
            Mixture      addend        = new Mixture("Addend", Guid.NewGuid());
            double       desiredVolume = 200000 * K.litersPerGallon;

            addend.AddMaterial(mt.CreateMass(desiredVolume, 35.0));
            //Console.WriteLine("There are " + (addend.Volume/K.litersPerGallon) + " gallons of " + mt.Name + " being added.");

            double controlTemperature = 35 + K.CELSIUS_TO_KELVIN;

            tester.DoPressureTransfer(addend, controlTemperature);

            Mixture emission  = tester.LastEmission;
            Mixture resultant = tester.CurrentMixture;

            string knownGood = "Mixture (40.00 deg C) of 32.1142 kg of Dimethylsulfide and 24.0567 kg of Water";

            EvaluateResults(knownGood, "Pressure Transfer", emission);
        }
예제 #11
0
        public void OnMaterialChanged(IMaterial material, MaterialChangeType mct)
        {
            if (m_diagnostics)
            {
                _Debug.WriteLine("ReactionProcessor notified of change type " + mct + " to material " + material);
            }
            if (mct == MaterialChangeType.Contents)
            {
                Mixture tmpMixture = material as Mixture;
                if (tmpMixture != null)
                {
                    Mixture          mixture = tmpMixture;
                    ReactionInstance ri      = null;
                    if (m_diagnostics)
                    {
                        _Debug.WriteLine("Processing change type " + mct + " to mixture " + mixture.Name);
                    }

                    // If multiple reactions could occur? Only the first happens, but then the next change allows the next reaction, etc.
                    foreach (Reaction reaction in m_reactions)
                    {
                        if (ri != null)
                        {
                            continue;
                        }
                        if (m_diagnostics)
                        {
                            _Debug.WriteLine("Examining mixture for presence of reaction " + reaction.Name);
                        }
                        ri = reaction.React(mixture);
                    }
                }
            }
        }
예제 #12
0
        public void TestVacuumDry()
        {
            Tester tester = new Tester(m_brs, m_lateBound);

            tester.AddGallons("Dimethylsulfide", 500);
            tester.AddGallons("Water", 100);

            double controlTemperature = 35.0 + K.CELSIUS_TO_KELVIN;
            double leakRateOfAir      = 1.0 /*lbm per hour*/ * K.kgPerPound;
            double leakDuration       = 1.0;        /*hour*/
            double systemPressure     = 760 * K.pascalsPer_mmHg;

            Hashtable materialGuidToVolumeFraction = new Hashtable();

            materialGuidToVolumeFraction.Add(m_brs.MyMaterialCatalog["Water"].Guid, 0.5);
            materialGuidToVolumeFraction.Add(m_brs.MyMaterialCatalog["Dimethylsulfide"].Guid, 0.5);

            double massOfDriedProductCake = tester.CurrentMixture.Mass * .6;

            tester.DoVacuumDry(controlTemperature, systemPressure, leakRateOfAir, leakDuration, materialGuidToVolumeFraction, massOfDriedProductCake);

            Mixture emission  = tester.LastEmission;
            Mixture resultant = tester.CurrentMixture;

            string knownGood = "Mixture (35.00 deg C) of 1.0619 kg of Dimethylsulfide and 0.0151 kg of Water";

            EvaluateResults(knownGood, "Vacuum Dry", emission);
        }
예제 #13
0
        private void EvaluateResults(string knownGood, string testName, Mixture emission)
        {
            string result = emission.ToString("F2", "F4");

            Assert.AreEqual(knownGood, result,
                            String.Format("{0} test failed - result was {1} but should have been {2}.", testName, result, knownGood));
        }
예제 #14
0
 protected override void afterWriteNodeLogic()
 {
     if (Mixture.wasAnySubFieldModified() || Constituent.wasAnySubFieldModified())
     {
         _recalculateRegListMembership();
     }
 }
예제 #15
0
        private UnivariateContinuousDistribution GetDistribution(double [] samples)
        {
            if (samples.Length < 10)
            {
                return(new EmpiricalDistribution(samples));
            }
            else
            {
                Accord.Math.Random.Generator.Seed = 0;
                // determining the optimal number of clusters is not easy, we use
                // a simple heuristics based on the numeber of samples
                var clusterCount = (int)Math.Ceiling(Math.Log(samples.Length, 10));
                var kmean        = new KMeans(clusterCount);
                var clusters     = kmean.Learn(samples.Select(x => new double[] { x }).ToArray());
                var components   = new NormalDistribution[clusters.Count];
                for (int i = 0; i < clusters.Count; i++)
                {
                    var cluster = clusters[i];
                    components[i] = new NormalDistribution(cluster.Centroid.First()); //, cluster.Proportion);
                }

                var mix = new Mixture <NormalDistribution>(components);
                mix.Fit(samples);
                return(mix);
            }
        }
예제 #16
0
        public void TestBoilingPoints2()
        {
            m_brs.MyMaterialCatalog.Add(new MaterialType(null, "Tula4", Guid.NewGuid(), 1.0, 1.0, MaterialState.Solid, 299, 1.0));
            Substance heptane           = (Substance)m_brs.MyMaterialCatalog["Heptane"].CreateMass(940, 31);
            Substance methyleneChloride = (Substance)m_brs.MyMaterialCatalog["Methylene Chloride"].CreateMass(1036, 31);
            Substance tula4             = (Substance)m_brs.MyMaterialCatalog["Tula4"].CreateMass(217.2, 31);

            double pressure_1Atm = 101325.0;             // pascals.

            Console.WriteLine("BP of Heptane is " + m_brs.MyMaterialCatalog["Heptane"].GetEstimatedBoilingPoint(pressure_1Atm) + ".");
            Console.WriteLine("BP of Methylene Chloride is " + m_brs.MyMaterialCatalog["Methylene Chloride"].GetEstimatedBoilingPoint(pressure_1Atm) + ".");
            Console.WriteLine("BP of Tula4 is " + m_brs.MyMaterialCatalog["Tula4"].GetEstimatedBoilingPoint(pressure_1Atm) + ".");

            Mixture m = new Mixture("Aamir's Soup");

            m.AddMaterial(heptane);
            m.AddMaterial(methyleneChloride);
            m.AddMaterial(tula4);

            Console.WriteLine("BP of " + m.Name + " is " + m.GetEstimatedBoilingPoint(pressure_1Atm) + ".");

            Substance water = (Substance)m_brs.MyMaterialCatalog["Water"].CreateMass(100, 37);

            Console.WriteLine("\r\n...By the way, BP of water is " + water.GetEstimatedBoilingPoint(pressure_1Atm) + ".  ;-)");
        }
예제 #17
0
        public void TestVolumetricsOfDissolvedGases()
        {
            Model model = new Model("Test Model", Guid.NewGuid());
            BasicReactionSupporter brs = new BasicReactionSupporter();

            InitializeForTesting(brs);
            brs.MyMaterialCatalog.Add(new MaterialType(model, "Nitrous Oxide", Guid.NewGuid(), .001, 5, MaterialState.Gas));
            brs.MyMaterialCatalog.Add(new MaterialType(model, "Pixie Breath", Guid.NewGuid(), .001, 5, MaterialState.Gas));

            Mixture mixture = new Mixture(model, "Contents of vat 1", Guid.NewGuid());

            MaterialCatalog cat = brs.MyMaterialCatalog;

            AddSubstance(ref mixture, cat["Nitrous Oxide"], 100, 20);

            Assert.IsTrue(mixture.Volume.Equals(100000D), "Mass is not 10000 liters");

            AddSubstance(ref mixture, cat["Water"], 100, 50);
            Assert.IsTrue(mixture.Volume.Equals(100D), "Mass is not 100 liters");

            RemoveSubstance(ref mixture, cat["Water"], 100);
            Assert.IsTrue(mixture.Volume.Equals(100000D), "Mass is not 10000 liters");

            AddSubstance(ref mixture, cat["Pixie Breath"], 100, 20);
            Assert.IsTrue(mixture.Volume.Equals(200000D), "Mass is not 100 liters");
        }
        private void Initialize(double[][] observations)
        {
            var algo = new KMeans();

            for (var j = 0; j < NumberOfStates; j++)
            {
                _pi[j] = 1d / NumberOfStates;
            }

            for (var j = 0; j < NumberOfStates; j++)
            {
                _tpm[j] = (double[])_pi.Clone();
            }

            var k          = _pi.Length * NumberOfComponents;
            var dimentions = observations[0].Length;

            algo.CreateClusters(observations, k, KMeans.KMeansDefaultIterations, (k > 3) ? InitialClusterSelectionMethod.Furthest : InitialClusterSelectionMethod.Random);
            _emission = new Mixture <IMultivariateDistribution> [_pi.Length];

            for (int i = 0; i < _pi.Length; i++)
            {
                _emission[i] = new Mixture <IMultivariateDistribution>(NumberOfComponents, dimentions);
                for (int j = 0; j < NumberOfComponents; j++)
                {
                    var mean       = algo.ClusterCenters[j + NumberOfComponents * i];
                    var covariance = algo.ClusterCovariances[j + NumberOfComponents * i];

                    _emission[i].Components[j] = new NormalDistribution(mean, covariance);
                }
            }
        }
예제 #19
0
        public void TestMVTrackerWithNullMixtures()
        {
            Highpoint.Sage.SimCore.Model model = new Highpoint.Sage.SimCore.Model("MVTTracker model");
            BasicReactionSupporter       brs   = new BasicReactionSupporter();

            InitializeForTesting(brs);

            Mixture current = new Mixture(model, "current", Guid.NewGuid());

            current.AddMaterial(brs.MyMaterialCatalog["Water"].CreateMass(150, 30));
            current.AddMaterial(brs.MyMaterialCatalog["Aluminum Hydroxide"].CreateMass(200, 35));

            MassVolumeTracker cmvt = new MassVolumeTracker(brs.MyReactionProcessor);

            cmvt.SetInitialMixture(null);
            cmvt.SetInflowMixture(null);
            cmvt.SetOutflowMixture(null);
            cmvt.SetVesselCapacity(1000);

            cmvt.Process();

            //_Debug.WriteLine("Temperatures: " + cmvt.TemperatureHistory.ToString());
            _Debug.WriteLine("Masses      : " + cmvt.MassHistory.ToString());
            _Debug.WriteLine("Volumes     : " + cmvt.VolumeHistory.ToString());

            _Debug.Assert(cmvt.MassHistory.ToString().Equals("[0/0/0/0]"));
            _Debug.Assert(cmvt.VolumeHistory.ToString().Equals("[0/0/0/0]"));
        }
예제 #20
0
 public void Reset()
 {
     m_initialMixture     = new Mixture("Test mixture");
     m_aggregateEmissions = new Mixture("Aggregate emissions");
     // Defaults from WebEmit.
     SetParams(35.0, 40.0, 40.0, 35.0, 200000, 581, 790, 760, 1.0, 0.1, 5.0, 1.0, 1.0, 500);
 }
예제 #21
0
        public void DistributionSpaceIterator_GaussianMixtureTest()
        {
            Console.WriteLine("DistributionSpaceIterator_GaussianMixtureTest");

            double        mean  = 70.0;
            double        std   = 1.0;
            IDistribution d1    = create1DGaussian(mean, std);
            double        mean2 = 20.0;
            double        std2  = 1.0;
            IDistribution d2    = create1DGaussian(mean2, std2);

            int dim = 1;

            string [] names = new string [1] {
                "x"
            };
            double [] mins = new double [1] {
                0.00
            };
            double [] maxs = new double [1] {
                100.0
            };
            IBlauSpace s = BlauSpace.create(dim, names, mins, maxs);
            Mixture    d = new Mixture(s);

            d.Add(d1, 0.75);
            d.Add(d2, 0.25);
            d.DistributionComplete();


            SingletonLogger.Instance().DebugLog(typeof(dist_tests), "original distribution: " + d);
            DistributionSpace ds = new DistributionSpace(d);

            int [] steps = new int[ds.ParamSpace.Dimension];

            for (int N = 3; N <= 5; N++)
            {
                for (int i = 0; i < ds.ParamSpace.Dimension; i++)
                {
                    steps[i] = N;
                }

                IDistributionSpaceIterator it = ds.iterator(steps);

                int count   = 0;
                int validCt = 0;
                foreach (IDistribution diter in it)
                {
                    if (diter.IsValid())
                    {
                        validCt++;
                        SingletonLogger.Instance().DebugLog(typeof(dist_tests), "iterator distribution: " + diter);
                    }
                    count++;
                }
                Assert.AreEqual((N + 1) * (N + 1) * (N + 1) * (N + 1) * (N + 1) * (N + 1), count);
                SingletonLogger.Instance().InfoLog(typeof(dist_tests), "N=" + N + "  valid distributions: " + validCt + " / total: " + count);
            }
        }
예제 #22
0
        /// <summary>
        ///   Predicts the next observation occurring after a given observation sequence.
        /// </summary>
        ///
        /// <param name="observations">A sequence of observations. Predictions will be made regarding
        ///   the next observations that should be coming after the last observation in this sequence.</param>
        /// <param name="probabilities">The continuous probability distribution describing the next observations
        ///   that are likely to be generated. Taking the mode of this distribution might give the most likely
        ///   next value in the observed sequence.</param>
        ///
        public TObservation Predict <TUnivariate>(TObservation[] observations, out Mixture <TUnivariate> probabilities)
            where TUnivariate : DistributionBase, TDistribution, IUnivariateDistribution <double>
        {
            double probability;

            // Compute the next observation (as if it were multidimensional)
            return(predict(observations, out probability, out probabilities)[0]);
        }
예제 #23
0
 /// <summary>
 ///     Trains Gaussian Mixture Model
 /// </summary>
 /// <param name="observations">Observation matrix</param>
 /// <param name="numberOfIterations">Number Of Iterations</param>
 public void Train(double[][] observations, int numberOfIterations, double likelihoodTolerance)
 {
     if (_initialize)
     {
         Initialize(observations);
     }
     _mixture = (Mixture <IMultivariateDistribution>)_mixture.Evaluate(observations, out _likelihood);
 }
예제 #24
0
 public GaussianMixtureColorModel(Mixture <VectorGaussian> mixture)
 {
     if (mixture == null)
     {
         throw new ArgumentNullException("mixture");
     }
     this.mixture = mixture;
 }
예제 #25
0
 public ReactionCollector(Mixture mixture)
 {
     m_mixture                     = mixture;
     m_reactions                   = new ArrayList();
     m_reactionInstances           = new ArrayList();
     m_reactionHandler             = OnReactionHappened;
     m_mixture.OnReactionHappened += m_reactionHandler;
 }
예제 #26
0
 public Dispensary(IExecutive executive, Mixture mixture)
 {
     m_executive                 = executive;
     m_getProcessor              = s_dummyIdec;
     m_waiters                   = new List <IDetachableEventController>();
     PeekMixture                 = mixture;
     executive.ExecutiveStarted += delegate { m_waiters.Clear(); PeekMixture.Clear(); };
 }
예제 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MaterialTransferrer"/> class.
 /// </summary>
 /// <param name="model">The model in which the update is to be run.</param>
 /// <param name="from">The source mixture.</param>
 /// <param name="to">The destination mixture.</param>
 /// <param name="typespecs">The list of typespecs representing what is to be transferred.</param>
 /// <param name="duration">The transfer duration.</param>
 public MaterialTransferrer(IModel model, ref Mixture from, ref Mixture to, List <TypeSpec> typespecs, TimeSpan duration)
 {
     m_startWaiters = new List <IDetachableEventController>();
     m_endWaiters   = new List <IDetachableEventController>();
     m_model        = model;
     m_from         = from;
     m_to           = to;
     m_what         = typespecs;
 }
예제 #28
0
 private void RequestMaterial(DateTime dateTime, double mass)
 {
     m_model.Executive.RequestEvent(new ExecEventReceiver(delegate(IExecutive exec, object userData) {
         Console.WriteLine("{0} : Requested {1} kg. from dispensary - now contains {2}.", exec.Now, mass, m_dispensary.PeekMixture.ToString());
         Mixture m           = m_dispensary.Get(mass);
         m_howMuchRetrieved += mass;
         Console.WriteLine("{0} : Received {1} kg. from dispensary - now contains {2}.", exec.Now, mass, m_dispensary.PeekMixture.ToString());
     }), dateTime, 0.0, null, ExecEventType.Detachable);
 }
예제 #29
0
        /// <summary>
        /// Estimates the boiling point of the material types in the mixture at the provided pressure. This is the point at
        /// which the partial pressure is equal to the external pressure.
        /// </summary>
        /// <param name="m">The mixture whose boiling point is to be computed.</param>
        /// <param name="atPressureInPascals">The pressure in pascals of the surrounding environment.</param>
        /// <returns></returns>
        public static double ComputeBoilingPoint(Mixture m, double atPressureInPascals)
        {
            if (atPressureInPascals < MinPressure)
            {
                throw new VaporPressureException(m.ToString(), atPressureInPascals, MinPressure);
            }

            double upper = double.NaN;
            double lower = double.NaN;

            double temperature = 273;             // deg Kelvin
            double vp          = SumOfPartialPressures(m, temperature);

            if (vp == 0.0)
            {
                return(double.MaxValue);
            }

            if (vp > atPressureInPascals)
            {
                while (vp > atPressureInPascals)
                {
                    upper        = temperature;
                    temperature -= 50.0;
                    vp           = SumOfPartialPressures(m, temperature);
                }
                lower = temperature;
            }
            else
            {
                while (vp < atPressureInPascals)
                {
                    lower        = temperature;
                    temperature += 50.0;
                    vp           = SumOfPartialPressures(m, temperature);
                }
                upper = temperature;
            }

            temperature = (upper + lower) / 2.0;
            vp          = SumOfPartialPressures(m, temperature);
            while ((upper - lower) > 0.5)
            {
                if (vp > atPressureInPascals)
                {
                    upper = temperature;
                }
                if (vp < atPressureInPascals)
                {
                    lower = temperature;
                }
                temperature = (upper + lower) / 2.0;
                vp          = SumOfPartialPressures(m, temperature);
            }
            return(temperature + K.KELVIN_TO_CELSIUS);
        }
예제 #30
0
            public TSTestJig(double mH2O, double mNANO2)
            {
                m_brs = new BasicReactionSupporter();
                Initialize(m_brs);
                m_mixture = new Mixture(null, "Test Mixture");
                m_brs.MyReactionProcessor.Watch(m_mixture);

                m_mixture.AddMaterial(m_brs.MyMaterialCatalog["Water"].CreateMass(mH2O, 20));            // Add 250 kg.
                m_mixture.AddMaterial(m_brs.MyMaterialCatalog["Sodium Nitrite"].CreateMass(mNANO2, 20)); // Add 100 kg NaNO2.
            }
 public Mixture<VectorGaussian> ToMixture()
 {
     Mixture<VectorGaussian> mixture = new Mixture<VectorGaussian>();
     for (int i = 0; i < weights.Count; ++i)
         mixture.Add(
             VectorGaussian.FromMeanAndVariance(
                 MicrosoftResearch.Infer.Maths.Vector.FromArray(this.means[i]),
                 new PositiveDefiniteMatrix(JaggedArrayToMatrix(this.variances[i]))),
             this.weights[i]);
     return mixture;
 }
        public void ConstructorTest()
        {
            // Create a new mixture containing two Normal distributions
            Mixture<NormalDistribution> mix = new Mixture<NormalDistribution>(
                new NormalDistribution(2, 1), new NormalDistribution(5, 1));

            // Common measures
            double mean   = mix.Mean;     // 3.5
            double median = mix.Median;   // 3.4999998506015895
            double var    = mix.Variance; // 3.25

            // Cumulative distribution functions
            double cdf = mix.DistributionFunction(x: 4.2);              // 0.59897597553494908
            double ccdf = mix.ComplementaryDistributionFunction(x: 4.2); // 0.40102402446505092

            // Probability mass functions
            double pmf1 = mix.ProbabilityDensityFunction(x: 1.2); // 0.14499174984363708
            double pmf2 = mix.ProbabilityDensityFunction(x: 2.3); // 0.19590437513747333
            double pmf3 = mix.ProbabilityDensityFunction(x: 3.7); // 0.13270883471234715
            double lpmf = mix.LogProbabilityDensityFunction(x: 4.2); // -1.8165661905848629

            // Quantile function
            double icdf1 = mix.InverseDistributionFunction(p: 0.17); // 1.5866611690305095
            double icdf2 = mix.InverseDistributionFunction(p: 0.46); // 3.1968506765456883
            double icdf3 = mix.InverseDistributionFunction(p: 0.87); // 5.6437596300843076

            // Hazard (failure rate) functions
            double hf = mix.HazardFunction(x: 4.2); // 0.40541978256972522
            double chf = mix.CumulativeHazardFunction(x: 4.2); // 0.91373394208601633

            // String representation:

            // Mixture(x; 0.5 * N(x; μ = 5, σ² = 1) + 0.5 * N(x; μ = 5, σ² = 1))
            string str = mix.ToString(CultureInfo.InvariantCulture);



            Assert.AreEqual(3.5, mean);
            Assert.AreEqual(3.4999998506015895, median);
            Assert.AreEqual(3.25, var);
            Assert.AreEqual(0.91373394208601633, chf, 1e-10);
            Assert.AreEqual(0.59897597553494908, cdf);
            Assert.AreEqual(0.14499174984363708, pmf1);
            Assert.AreEqual(0.19590437513747333, pmf2);
            Assert.AreEqual(0.13270883471234715, pmf3);
            Assert.AreEqual(-1.8165661905848629, lpmf);
            Assert.AreEqual(0.40541978256972522, hf);
            Assert.AreEqual(0.40102402446505092, ccdf);
            Assert.AreEqual(1.5866611690305095, icdf1);
            Assert.AreEqual(3.1968506765456883, icdf2);
            Assert.AreEqual(5.6437596300843076, icdf3);
            Assert.AreEqual("Mixture(x; 0.5*N(x; μ = 5, σ² = 1) + 0.5*N(x; μ = 5, σ² = 1))", str);
        }
        public GaussianMixtureSurrogated(Mixture<VectorGaussian> mixture)
        {
            this.weights = new List<double>(mixture.Weights);

            this.means = new List<double[]>();
            this.variances = new List<double[][]>();
            for (int i = 0; i < mixture.Components.Count; ++i)
            {
                MicrosoftResearch.Infer.Maths.Vector mean = mixture.Components[i].GetMean();
                PositiveDefiniteMatrix variance = mixture.Components[i].GetVariance();

                this.means.Add(mean.ToArray());
                this.variances.Add(MatrixToJaggedArray(variance.ToArray()));
            }
        }
        public void LogProbabilityDensityFunction()
        {
            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            double[] coefficients = { 0.4, 0.5 };

            var mixture = new Mixture<NormalDistribution>(coefficients, components);

            double expected = System.Math.Log(
                0.4 * components[0].ProbabilityDensityFunction(0.42) +
                0.5 * components[1].ProbabilityDensityFunction(0.42));

            double actual = mixture.LogProbabilityDensityFunction(0.42);

            Assert.AreEqual(expected, actual);
        }
        public void FitTest2()
        {
            double[] coefficients = { 0.50, 0.50 };

            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            var target = new Mixture<NormalDistribution>(coefficients, components);

            double[] values =  { 12512, 1, 1, 0, 1, 6, 6, 5, 7, 5 };
            double[] weights = {     0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            weights = weights.Divide(weights.Sum());
            double[] part1 = values.Submatrix(1, 4);
            double[] part2 = values.Submatrix(5, 9);

            MixtureOptions opt = new MixtureOptions()
            {
                Threshold = 0.000001
            };

            target.Fit(values, weights, opt);

            var mean1 = Accord.Statistics.Tools.Mean(part1);
            var var1 = Accord.Statistics.Tools.Variance(part1);
            Assert.AreEqual(mean1, target.Components[0].Mean, 1e-5);
            Assert.AreEqual(var1, target.Components[0].Variance, 1e-5);

            var mean2 = Accord.Statistics.Tools.Mean(part2);
            var var2 = Accord.Statistics.Tools.Variance(part2);
            Assert.AreEqual(mean2, target.Components[1].Mean, 1e-5);
            Assert.AreEqual(var2, target.Components[1].Variance, 1e-5);

            var expectedMean = Accord.Statistics.Tools.WeightedMean(values, weights);
            var actualMean = target.Mean;
            Assert.AreEqual(expectedMean, actualMean, 1e-5);
        }
        public void FitTest()
        {
            double[] coefficients = { 0.50, 0.50 };

            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            var target = new Mixture<NormalDistribution>(coefficients, components);

            double[] values = { 0, 1, 1, 0, 1, 6, 6, 5, 7, 5 };
            double[] part1 = values.Submatrix(0, 4);
            double[] part2 = values.Submatrix(5, 9);

            MixtureOptions options = new MixtureOptions() { Threshold = 1e-10 };

            target.Fit(values, options);
            var actual = target;

            var mean1 = Accord.Statistics.Tools.Mean(part1);
            var var1 = Accord.Statistics.Tools.Variance(part1);
            Assert.AreEqual(mean1, actual.Components[0].Mean, 1e-6);
            Assert.AreEqual(var1, actual.Components[0].Variance, 1e-6);

            var mean2 = Accord.Statistics.Tools.Mean(part2);
            var var2 = Accord.Statistics.Tools.Variance(part2);
            Assert.AreEqual(mean2, actual.Components[1].Mean, 1e-6);
            Assert.AreEqual(var2, actual.Components[1].Variance, 1e-5);

            var expectedMean = Accord.Statistics.Tools.Mean(values);
            var actualMean = actual.Mean;
            Assert.AreEqual(expectedMean, actualMean, 1e-7);

            var expectedVar = Accord.Statistics.Tools.Variance(values, false);
            var actualVar = actual.Variance;
            Assert.AreEqual(expectedVar, actualVar, 0.15);
        }
        public void ConstructorTest2()
        {
            // Create a new mixture containing two Normal distributions
            Mixture<NormalDistribution> mix = new Mixture<NormalDistribution>(
                new NormalDistribution(2, 1), new NormalDistribution(5, 1));

            // Compute in reverse order
            double var = mix.Variance; // 3.25
            double median = mix.Median;   // 3.4999998506015895
            double mean = mix.Mean;     // 3.5

            Assert.AreEqual(3.5, mean);
            Assert.AreEqual(3.4999998506015895, median);
            Assert.AreEqual(3.25, var);
        }
        public void ConstructorTest1()
        {
            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            var mixture = new Mixture<NormalDistribution>(components);

            double[] expected = { 0.5, 0.5 };

            Assert.IsTrue(expected.IsEqual(mixture.Coefficients));
            Assert.AreEqual(components, mixture.Components);
        }
예제 #39
0
 private SkinGMM()
 {
     // load the +ve and -ve GMMs:
     negative = CreateNegativeSkinModel();
     positive = CreatePositiveSkinModel();
 }
        public void DistributionFunctionPerComponent()
        {
            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            double[] coefficients = { 0.4, 0.5 };

            var mixture = new Mixture<NormalDistribution>(coefficients, components);

            double expected = mixture.DistributionFunction(0, 0.42) +
                              mixture.DistributionFunction(1, 0.42);

            double actual = mixture.DistributionFunction(0.42);

            Assert.AreEqual(expected, actual);
        }
 public GaussianMixtureColorModel(Mixture<VectorGaussian> mixture)
 {
     if (mixture == null)
         throw new ArgumentNullException("mixture");
     this.mixture = mixture;
 }
        public void MixtureDistributionExample()
        {
            var samples1 = new NormalDistribution(mean: -2, stdDev: 1).Generate(100000);
            var samples2 = new NormalDistribution(mean: +4, stdDev: 1).Generate(100000);

            // Mix the samples from both distributions
            var samples = samples1.Concatenate(samples2);

            // Create a new mixture distribution with two Normal components
            var mixture = new Mixture<NormalDistribution>(
                new NormalDistribution(-1),
                new NormalDistribution(+1));

            // Estimate the distribution
            mixture.Fit(samples);

            var a = mixture.Components[0].ToString("N2"); // N(x; μ = -2.00, σ² = 1.00)
            var b = mixture.Components[1].ToString("N2"); // N(x; μ =  4.00, σ² = 1.02)

            Assert.AreEqual("N(x; μ = -2.00, σ² = 1.00)", a);
            Assert.AreEqual("N(x; μ = 4.00, σ² = 1.02)", b);
        }
예제 #43
0
        public void LearnTest12()
        {

            // Suppose we have a set of six sequences and we would like to
            // fit a hidden Markov model with mixtures of Normal distributions
            // as the emission densities. 

            // First, let's consider a set of univariate sequences:
            double[][] sequences =
            {
                new double[] { -0.223, -1.05, -0.574, 0.965, -0.448, 0.265, 0.087, 0.362, 0.717, -0.032 },
                new double[] { -1.05, -0.574, 0.965, -0.448, 0.265, 0.087, 0.362, 0.717, -0.032, -0.346 },
                new double[] { -0.574, 0.965, -0.448, 0.265, 0.087, 0.362, 0.717, -0.032, -0.346, -0.989 },
                new double[] { 0.965, -0.448, 0.265, 0.087, 0.362, 0.717, -0.032, -0.346, -0.989, -0.619 },
                new double[] { -0.448, 0.265, 0.087, 0.362, 0.717, -0.032, -0.346, -0.989, -0.619, 0.02 },
                new double[] { 0.265, 0.087, 0.362, 0.717, -0.032, -0.346, -0.989, -0.619, 0.02, -0.297 },
            };


            // Now we can begin specifing a initial Gaussian mixture distribution. It is
            // better to add some different initial parameters to the mixture components:
            var density = new Mixture<NormalDistribution>(
                new NormalDistribution(mean: 2, stdDev: 1.0), // 1st component in the mixture
                new NormalDistribution(mean: 0, stdDev: 0.6), // 2nd component in the mixture
                new NormalDistribution(mean: 4, stdDev: 0.4), // 3rd component in the mixture
                new NormalDistribution(mean: 6, stdDev: 1.1)  // 4th component in the mixture
            );

            // Let's then create a continuous hidden Markov Model with two states organized in a forward
            //  topology with the underlying univariate Normal mixture distribution as probability density.
            var model = new HiddenMarkovModel<Mixture<NormalDistribution>>(new Forward(2), density);

            // Now we should configure the learning algorithms to train the sequence classifier. We will
            // learn until the difference in the average log-likelihood changes only by as little as 0.0001
            var teacher = new BaumWelchLearning<Mixture<NormalDistribution>>(model)
            {
                Tolerance = 0.0001,
                Iterations = 0,

                // Note, however, that since this example is extremely simple and we have only a few
                // data points, a full-blown mixture wouldn't really be needed. Thus we will have a
                // great chance that the mixture would become degenerated quickly. We can avoid this
                // by specifying some regularization constants in the Normal distribution fitting:

                FittingOptions = new MixtureOptions()
                {
                    Iterations = 1, // limit the inner e-m to a single iteration

                    InnerOptions = new NormalOptions()
                    {
                        Regularization = 1e-5 // specify a regularization constant
                    }
                }
            };

            // Finally, we can fit the model
            double logLikelihood = teacher.Run(sequences);

            // And now check the likelihood of some approximate sequences.
            double[] newSequence = { -0.223, -1.05, -0.574, 0.965, -0.448, 0.265, 0.087, 0.362, 0.717, -0.032 };
            double a1 = Math.Exp(model.Evaluate(newSequence)); // 11729312967893.566

            int[] path = model.Decode(newSequence);

            // We can see that the likelihood of an unrelated sequence is much smaller:
            double a3 = Math.Exp(model.Evaluate(new double[] { 8, 2, 6, 4, 1 })); // 0.0


            Assert.AreEqual(11729312967893.566, a1);
            Assert.AreEqual(0.0, a3);

            Assert.IsFalse(Double.IsNaN(a1));
            Assert.IsFalse(Double.IsNaN(a3));
        }
        public void LearnTest11()
        {

            // Suppose we have a set of six sequences and we would like to
            // fit a hidden Markov model with mixtures of Normal distributions
            // as the emission densities. 

            // First, let's consider a set of univariate sequences:
            double[][] sequences =
            {
                new double[] { 1, 1, 2, 2, 2, 3, 3, 3 },
                new double[] { 1, 2, 2, 2, 3, 3 },
                new double[] { 1, 2, 2, 3, 3, 5 },
                new double[] { 2, 2, 2, 2, 3, 3, 3, 4, 5, 5, 1 },
                new double[] { 1, 1, 1, 2, 2, 5 },
                new double[] { 1, 2, 2, 4, 4, 5 },
            };


            // Now we can begin specifying a initial Gaussian mixture distribution. It is
            // better to add some different initial parameters to the mixture components:
            var density = new Mixture<NormalDistribution>(
                new NormalDistribution(mean: 2, stdDev: 1.0), // 1st component in the mixture
                new NormalDistribution(mean: 0, stdDev: 0.6), // 2nd component in the mixture
                new NormalDistribution(mean: 4, stdDev: 0.4), // 3rd component in the mixture
                new NormalDistribution(mean: 6, stdDev: 1.1)  // 4th component in the mixture
            );

            // Let's then create a continuous hidden Markov Model with two states organized in a forward
            //  topology with the underlying univariate Normal mixture distribution as probability density.
            var model = new HiddenMarkovModel<Mixture<NormalDistribution>>(new Forward(2), density);

            // Now we should configure the learning algorithms to train the sequence classifier. We will
            // learn until the difference in the average log-likelihood changes only by as little as 0.0001
            var teacher = new BaumWelchLearning<Mixture<NormalDistribution>>(model)
            {
                Tolerance = 0.0001,
                Iterations = 0,

                // Note, however, that since this example is extremely simple and we have only a few
                // data points, a full-blown mixture wouldn't really be needed. Thus we will have a
                // great chance that the mixture would become degenerated quickly. We can avoid this
                // by specifying some regularization constants in the Normal distribution fitting:

                FittingOptions = new MixtureOptions()
                {
                    Iterations = 1, // limit the inner e-m to a single iteration

                    InnerOptions = new NormalOptions()
                    {
                        Regularization = 1e-5 // specify a regularization constant
                    }
                }
            };

            // Finally, we can fit the model
            double logLikelihood = teacher.Run(sequences);

            // And now check the likelihood of some approximate sequences.
            double a1 = Math.Exp(model.Evaluate(new double[] { 1, 1, 2, 2, 3 })); // 2.3413833128741038E+45
            double a2 = Math.Exp(model.Evaluate(new double[] { 1, 1, 2, 5, 5 })); // 9.94607618459872E+19

            // We can see that the likelihood of an unrelated sequence is much smaller:
            double a3 = Math.Exp(model.Evaluate(new double[] { 8, 2, 6, 4, 1 })); // 1.5063654166181737E-44

            Assert.IsTrue(a1 > 1e+6);
            Assert.IsTrue(a2 > 1e+6);
            Assert.IsTrue(a3 < 1e-6);

            Assert.IsFalse(Double.IsNaN(a1));
            Assert.IsFalse(Double.IsNaN(a2));
            Assert.IsFalse(Double.IsNaN(a3));
        }
예제 #45
0
 void ComposeRendering(Mixture mixture)
     {
     foreach (Molecule m in mixture.UniqueMolecules)
         {
         this.ComposeRendering(m);
         }
     }
        public void MixtureFitTest()
        {
            var samples1 = new NormalDistribution(mean: -2, stdDev: 0.5).Generate(100000);
            var samples2 = new NormalDistribution(mean: +4, stdDev: 0.5).Generate(100000);

            // Mix the samples from both distributions
            var samples = samples1.Concatenate(samples2);

            // Create a new mixture distribution with two Normal components
            var mixture = new Mixture<NormalDistribution>(new[] { 0.2, 0.8 },
                new NormalDistribution(-1),
                new NormalDistribution(+1));

            // Estimate the distribution
            mixture.Fit(samples, new MixtureOptions
            {
                Iterations = 50,
                Threshold = 0
            });

            var result = mixture.ToString("N2", System.Globalization.CultureInfo.InvariantCulture);

            Assert.AreEqual("Mixture(x; 0.50*N(x; μ = -2.00, σ² = 0.25) + 0.50*N(x; μ = 4.00, σ² = 0.25))", result);
        }
        public void MixtureWeightsFitTest()
        {
            // Randomly initialize some mixture components
            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            // Create an initial mixture
            Mixture<NormalDistribution> mixture = new Mixture<NormalDistribution>(components);

            // Now, suppose we have a weighted data
            // set. Those will be the input points:

            double[] points = { 0, 3, 1, 7, 3, 5, 1, 2, -1, 2, 7, 6, 8, 6 }; // (14 points)

            // And those are their respective unormalized weights:
            double[] weights = { 1, 1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 3, 1, 1 }; // (14 weights)

            // Let's normalize the weights so they sum up to one:
            weights = weights.Divide(weights.Sum());

            // Now we can fit our model to the data:
            mixture.Fit(points, weights);   // done!

            // Our model will be:
            double mean1 = mixture.Components[0].Mean; // 1.41126
            double mean2 = mixture.Components[1].Mean; // 6.53301

            // If we need the GaussianMixtureModel functionality, we can
            // use the estimated mixture to initialize a new model:
            GaussianMixtureModel gmm = new GaussianMixtureModel(mixture);

            Assert.AreEqual(mean1, gmm.Gaussians[0].Mean[0]);
            Assert.AreEqual(mean2, gmm.Gaussians[1].Mean[0]);

            Assert.AreEqual(mean1, 1.4112610766836404, 1e-15);
            Assert.AreEqual(mean2, 6.5330177004151082, 1e-14);

            Assert.AreEqual(mixture.Coefficients[0], gmm.Gaussians[0].Proportion);
            Assert.AreEqual(mixture.Coefficients[1], gmm.Gaussians[1].Proportion);
        }
예제 #48
0
        private void BuildNegativeSkinModel()
        {
            var distributions = new NormalDistribution[Components];

            distributions[0] = ToDistribution(254.37, 254.41, 253.82, 2.77, 2.81, 5.46);
            distributions[1] = ToDistribution(9.39, 8.09, 8.52, 46.84, 33.59, 32.48);
            distributions[2] = ToDistribution(96.57, 96.95, 91.53, 280.69, 156.79, 436.58);
            distributions[3] = ToDistribution(160.44, 162.49, 159.06, 355.98, 115.89, 591.24);
            distributions[4] = ToDistribution(74.98, 63.23, 46.33, 414.84, 245.95, 361.27);
            distributions[5] = ToDistribution(121.83, 60.88, 18.31, 2502.24, 1383.53, 237.18);
            distributions[6] = ToDistribution(202.18, 154.88, 91.04, 957.42, 1766.94, 1582.52);
            distributions[7] = ToDistribution(193.06, 201.93, 206.55, 562.88, 190.23, 447.28);
            distributions[8] = ToDistribution(51.88, 57.14, 61.55, 344.11, 191.77, 433.40);
            distributions[9] = ToDistribution(30.88, 26.84, 25.32, 222.07, 118.65, 182.41);
            distributions[10] = ToDistribution(44.97, 85.96, 131.95, 651.32, 840.52, 963.67);
            distributions[11] = ToDistribution(236.02, 236.27, 230.70, 225.03, 117.29, 331.95);
            distributions[12] = ToDistribution(207.86, 191.20, 164.12, 494.04, 237.69, 533.52);
            distributions[13] = ToDistribution(99.83, 148.11, 188.17, 955.88, 654.95, 916.70);
            distributions[14] = ToDistribution(135.06, 131.92, 123.10, 350.35, 130.30, 388.43);
            distributions[15] = ToDistribution(135.96, 103.89, 66.88, 806.44, 642.20, 350.36);

            var proportions = new[]
            {
                0.0637, 0.0516, 0.0864, 0.0636, 0.0747, 0.0365, 0.0349, 0.0649,
                0.0656, 0.1189, 0.0362, 0.0849, 0.0368, 0.0389, 0.0943, 0.0477
            };

            negative = new Mixture<NormalDistribution>(proportions, distributions);
        }
예제 #49
0
        private void BuildPositiveSkinModel()
        {
            var distributions = new NormalDistribution[Components];

            distributions[0] = ToDistribution(73.53, 29.94, 17.76, 765.40, 121.44, 112.80);
            distributions[1] = ToDistribution(249.71, 233.94, 217.49, 39.94, 154.44, 396.05);
            distributions[2] = ToDistribution(161.68, 116.25, 96.95, 291.03, 60.48, 162.85);
            distributions[3] = ToDistribution(186.07, 136.62, 114.40, 274.95, 64.60, 198.27);
            distributions[4] = ToDistribution(189.26, 98.37, 51.18, 633.18, 222.40, 250.69);
            distributions[5] = ToDistribution(247.00, 152.20, 90.84, 65.23, 691.53, 609.92);
            distributions[6] = ToDistribution(150.10, 72.66, 37.76, 408.63, 200.77, 257.57);
            distributions[7] = ToDistribution(206.85, 171.09, 156.34, 530.08, 155.08, 572.79);
            distributions[8] = ToDistribution(212.78, 152.82, 120.04, 160.57, 84.52, 243.90);
            distributions[9] = ToDistribution(234.87, 175.43, 138.94, 163.80, 121.57, 279.22);
            distributions[10] = ToDistribution(151.19, 97.74, 74.59, 425.40, 73.56, 175.11);
            distributions[11] = ToDistribution(120.52, 77.55, 59.82, 330.45, 70.34, 151.82);
            distributions[12] = ToDistribution(192.20, 119.62, 82.32, 152.76, 92.14, 259.15);
            distributions[13] = ToDistribution(214.29, 136.08, 87.24, 204.90, 140.17, 270.19);
            distributions[14] = ToDistribution(99.57, 54.33, 38.06, 448.13, 90.18, 151.29);
            distributions[15] = ToDistribution(238.88, 203.08, 176.91, 178.38, 156.27, 404.99);

            var proportions = new[]
            {
                0.0294, 0.0331, 0.0654, 0.0756, 0.0554, 0.0314, 0.0454, 0.0469,
                0.0956, 0.0763, 0.1108, 0.0676, 0.0755, 0.0500, 0.0667, 0.0749
            };

            positive = new Mixture<NormalDistribution>(proportions, distributions);
        }