Esempio n. 1
0
        public override void CalculateWeights(ModelOutput ModelOutput)
        {
            double i_totalIncome, i_totalPopulation;
            double i_baseYpC;
            double i_YpC;

            if (m_baseRegion == -1)
            {
                i_totalIncome = 0;
                i_totalPopulation = 0;
                for (int r = 0; r < LegacyConstants.NoReg; r++)
                {
                    i_totalIncome = i_totalIncome + ModelOutput.Incomes[m_baseYear, r];
                    i_totalPopulation = i_totalPopulation + ModelOutput.Populations[m_baseYear, r];
                }
                i_baseYpC = i_totalIncome / i_totalPopulation;
            }
            else
                i_baseYpC = ModelOutput.Incomes[m_baseYear, m_baseRegion] / ModelOutput.Populations[m_baseYear, m_baseRegion];

            for (int r = 0; r < LegacyConstants.NoReg; r++)
            {
                // TODO -oDavid Anthoff: Change start of "real" period to constant
                for (int t = 50; t <= LegacyConstants.NYear; t++)
                {
                    i_YpC = ModelOutput.Incomes[t, r] / ModelOutput.Populations[t, r];
                    AddWeight(t, r, Math.Pow(i_baseYpC / i_YpC, m_inequalityAversion));
                }
            }
        }
Esempio n. 2
0
 public override void CalculateWeights(ModelOutput ModelOutput)
 {
     for (int i = 0; i < LegacyConstants.NoReg; i++)
     {
         for (int l = m_baseYear; l <= LegacyConstants.NYear; l++)
         {
             if (l >= m_cutoffYear.Value)
                 AddWeight(l, i, 0.0);
             else
                 AddWeight(l, i, 1.0);
         }
     }
 }
Esempio n. 3
0
        public ModelFieldsWindow(ModelOutput fields)
        {
            Fields = new ObservableCollection<ModelOutput.Field>();
            InitializeComponent();

            var d = from p in fields.GetDimensionalFieldsOperator()
                    where (p.Values is IParameter1Dimensional<Timestep, double>) || (p.Values is IParameter1DimensionalTypeless<double>) || (p.Values is IParameter2DimensionalTypeless<double>)
                    orderby p.ComponentName, p.FieldName
                    select p;

            foreach (var i in d)
                Fields.Add(i);

            this.DataContext = Fields;
        }
Esempio n. 4
0
File: Model.cs Progetto: VWille/fund
        public ModelOutput Run(ParameterValues parameters)
        {
            ModelOutput mf = new ModelOutput();

            LoadDimensions(parameters, mf);

            InitVariables(mf);

            ConnectBindings(mf);

            ConnectLeftoversToParameters(mf, parameters);

            RunComponents(mf);

            mf.SwitchOffChecks();

            return mf;
        }
Esempio n. 5
0
        public override void CalculateWeights(ModelOutput ModelOutput)
        {
            double i_newPerCapitaIncome, i_oldPerCapitaIncome;
            double i_perCapitaGrowthRate;
            double df;

            for (int r = 0; r < LegacyConstants.NoReg; r++)
            {
                df = 1;

                for (int t = m_baseYear; t <= LegacyConstants.NYear; t++)
                {
                    AddWeight(t, r, df);
                    i_newPerCapitaIncome = ModelOutput.Incomes[t, r] / ModelOutput.Populations[t, r];
                    i_oldPerCapitaIncome = ModelOutput.Incomes[t - 1, r] / ModelOutput.Populations[t - 1, r];
                    i_perCapitaGrowthRate = (i_newPerCapitaIncome - i_oldPerCapitaIncome) / i_oldPerCapitaIncome;
                    df = df / (1.00 + m_pureRateOfTimePreference + m_riskAversion * i_perCapitaGrowthRate);
                }
            }
        }
Esempio n. 6
0
        public static int DecideBid(Player player)
        {
            int Bid = 0;

            MLContext mlContext = new MLContext();

            // Training code used by ML.NET CLI and AutoML to generate the model
            //ModelBuilder.CreateModel();

            ITransformer mlModel    = mlContext.Model.Load(GetAbsolutePath(MODEL_FILEPATH), out DataViewSchema inputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Create sample data to do a single prediction with it
            ModelInput sampleData = GetModel(player);
            // Try a single prediction
            ModelOutput predictionResult = predEngine.Predict(sampleData);

            Bid = (int)Math.Round(predictionResult.Score);

            return(Bid);
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            // Training code used by ML.NET CLI and AutoML to generate the model
            //ModelBuilder.CreateModel();

            ITransformer mlModel    = mlContext.Model.Load(GetAbsolutePath(MODEL_FILEPATH), out DataViewSchema inputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Create sample data to do a single prediction with it
            ModelInput sampleData = CreateSingleDataSample(mlContext, DATA_FILEPATH);

            // Try a single prediction
            ModelOutput predictionResult = predEngine.Predict(sampleData);

            Console.WriteLine($"Single Prediction --> Actual value: {sampleData.Fare_amount} | Predicted value: {predictionResult.Score}");

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            //由ML.NET CLI和AutoML用于生成模型的训练代码
            //ModelBuilder.CreateModel();

            ITransformer mlModel    = mlContext.Model.Load(GetAbsolutePath(MODEL_FILEPATH), out DataViewSchema inputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // 创建示例数据来对其进行单个预测
            ModelInput sampleData = CreateSingleDataSample(mlContext, DATA_FILEPATH);

            // 尝试一个预测
            ModelOutput predictionResult = predEngine.Predict(sampleData);

            Console.WriteLine($"Single Prediction --> Actual value: {sampleData.Sentiment} | Predicted value: {predictionResult.Prediction}");

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 9
0
        public async Task <object> Post(IFormFile image)
        {
            logger.LogInformation($"Request received at {DateTime.Now}");
            if (image is null)
            {
                logger.LogInformation($"No image was found!");
                return(BadRequest("No image was found. Request body must be form-data in { \"image\": <file> } format"));
            }

            try
            {
                var tempFilePath = Path.GetTempFileName();
                using (var ms = new FileStream(tempFilePath, FileMode.Create))
                {
                    await image.CopyToAsync(ms);

                    logger.LogInformation($"{image.FileName} was saved to {tempFilePath}");
                }

                ModelInput input = new ModelInput {
                    ImageSource = tempFilePath
                };
                ModelOutput output = ConsumeModel.Predict(input, Path.Combine(env.WebRootPath, "MLModel.zip"));

                double probablity = output.Score.Max();
                if (probablity == 0) // The file was probably not an image at all.
                {
                    logger.LogInformation("Error with the file!");
                    return(BadRequest("Error with the file!"));
                }

                logger.LogInformation($"Predicted {output.Prediction} with a probablity of {probablity}.");
                return(new Response(output));
            }
            catch (Exception e)
            {
                logger.LogError(e.ToString());
                return(BadRequest(e));
            }
        }
Esempio n. 10
0
        private static void RunMachineLearningCode(bool simulateLateFriday = false)
        {
            //if (simulateLateFriday)
            //    _ledGreen.Flash(500, 5);
            //else
            //    _ledRed.Flash(250, 10);

            #region Actual demo
            ModelInput inputData;
            if (simulateLateFriday)
            {
                inputData = new ModelInput {
                    Time = @"17:00", DayOfWeek = 5F, DidTeamWin = 1F,
                };
            }
            else
            {
                string workTime = DateTime.Now.AddHours(-4).ToString("HH:mm");

                inputData = new ModelInput {
                    Time = workTime, DayOfWeek = 1F, DidTeamWin = 0F,
                };
            }
            ModelOutput predictionResult = ConsumeModel.Predict(inputData);
            var         workingDay       = simulateLateFriday ? "Friday" : "a normal day";
            Console.WriteLine($"Result from working on {workingDay} has {predictionResult.Score} bolts per 5 minutes");

            if (predictionResult.Score < 10.0f)
            {
                Console.WriteLine("Fail");
                _buzzer.Buzz();
                _ledRed.Flash(100, 10);
            }
            else
            {
                Console.WriteLine("Pass");
                _ledGreen.Flash(200, 2);
            }
            #endregion
        }
        public async Task <IActionResult> Create([Bind("Id,Name,FathersName,MothersName,Dob,Percentage,AnnualIncome,InternetRating,Status,Email")] Application application)
        {
            if (ModelState.IsValid)
            {
                application.ApplicationDate = DateTime.Now;
                application.Status          = "Pending";
                ModelInput input = new ModelInput
                {
                    StudentId = application.Id,
                    CGPA      = application.Percentage
                };
                ModelOutput output = ConsumeModel.Predict(input);
                int         fees   = (int)output.Score;
                fees             = (int)Math.Floor(output.Score / 1000);
                application.Fees = fees * 1000;
                _context.Add(application);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Dashboard)));
            }
            return(View(application));
        }
Esempio n. 12
0
        public static void ConsumeModel()
        {
            // Load the model
            MLContext mlContext = new MLContext();

            ITransformer mlModel = mlContext.Model.Load("MLModel.zip", out var modelInputSchema);

            var predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Use the code below to add input data
            var input = new ModelInput();

            Console.Write("Insert a review: ");
            input.Review = System.Console.ReadLine();


            // Try model on sample data
            // True is Positive, false is Negative
            ModelOutput result = predEngine.Predict(input);

            Console.WriteLine($"Text: {input.Review} | Prediction: {(Convert.ToBoolean(result.Prediction) ? "Positive" : "Negative")} Sentiment");
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            // Training code used by ML.NET CLI and AutoML to generate the model
            //ModelBuilder.CreateModel();

            ITransformer mlModel    = mlContext.Model.Load(GetAbsolutePath(MODEL_FILEPATH), out DataViewSchema inputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Create sample data to do a single prediction with it
            ModelInput sampleData = CreateSingleDataSample(mlContext, DATA_FILEPATH);

            List <ModelInput> misMatched = new List <ModelInput>();


            foreach (var sample in CreateNDataSample(mlContext, DATA_FILEPATH, 1500))
            {
                // Try a single prediction
                ModelOutput _predictionResult = predEngine.Predict(sample);

                //Console.WriteLine($"Single Prediction --> Actual value: {sample.Sentiment} | Predicted value: {_predictionResult.Prediction}");

                if (sample.Sentiment != _predictionResult.Prediction)
                {
                    misMatched.Add(sample);
                }
            }


            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.WriteLine("=============== Number of mismatches {0} ===========================", misMatched.Count);

            foreach (var input in misMatched)
            {
                Console.WriteLine("`{0}` is actually {1}", input.Text, input.Sentiment);
            }
            Console.ReadKey();
        }
Esempio n. 14
0
        protected void InitVariables(ModelOutput mf)
        {
            foreach (var key in _components.Keys)
            {
                var c = _components[key];
                foreach (var v in c.Variables)
                {
                    var dtpes = v.DimensionTypes.ToArray();

                    if (dtpes.Length == 0)
                    {
                        mf.Add0DimensionalVariable(c.Name, v.Name, v.DataType, null);
                    }
                    else if (dtpes.Length == 1)
                    {
                        if (v.Forced == null)
                        {
                            MethodInfo mi  = typeof(ModelOutput).GetMethod("Add1DimensionalVariable");
                            MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { dtpes[0], v.DataType });
                            mi2.Invoke(mf, new object[] { c.Name, v.Name, !v.StoreOutput });
                        }
                        else
                        {
                            mf.Add1DimensionalForcedVariable(c.Name, v.Name, dtpes[0], v.DataType);
                        }
                    }
                    else if (dtpes.Length == 2)
                    {
                        MethodInfo mi  = typeof(ModelOutput).GetMethod("Add2DimensionalVariable");
                        MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { dtpes[0], dtpes[1], v.DataType });
                        mi2.Invoke(mf, new object[] { c.Name, v.Name, !v.StoreOutput });
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }
        }
Esempio n. 15
0
 private void predictBtn_Click(object sender, EventArgs e)
 {
     try
     {
         var input = new ModelInput();
         input.ImageSource = imagePathTb.Text;
         ModelOutput result = ConsumeModel.Predict(input);
         float       score  = (result.Score[0] > result.Score[1] ? result.Score[0] : result.Score[1]);
         if (score < .8)
         {
             statusRtb.Text = $"Neither Cat nor Dog";
         }
         else
         {
             statusRtb.Text = $"Predicted result: {result.Prediction} with a score {score}";
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Esempio n. 16
0
        public ActionResult <string> perform([FromQuery] string sentimentText)
        {
            ModelInput sampleData = new ModelInput()
            {
                Col0 = sentimentText
            };

            //predict sentiment
            ModelOutput prediction           = _predictionEnginePool.Predict(sampleData);
            string      retVal               = string.Empty;
            var         probabilityToPercent = prediction.Probability * 100;

            if (prediction.Prediction)
            {
                retVal = $"'{sentimentText}' is {probabilityToPercent}% sentiment positive";
            }
            else
            {
                retVal = $"'{sentimentText}' is {probabilityToPercent}%  sentiment negative";
            }
            return(retVal);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            // Training code used by ML.NET CLI and AutoML to generate the model
            ModelBuilder.CreateModel();

            ITransformer mlModel    = mlContext.Model.Load(GetAbsolutePath(MODEL_FILEPATH), out DataViewSchema inputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);


            // Create sample data to do a single prediction with it
            string     inputSampleText = "ML.NET is awesome!";
            ModelInput sampleData      = CreateSingleDataSample(inputSampleText);

            // Try a single prediction
            ModelOutput predictionResult = predEngine.Predict(sampleData);

            Console.WriteLine($"Single Prediction --> Prediction for '{inputSampleText}' was PositiveSentiment = {predictionResult.Prediction}");

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            // Create single instance of sample data from first line of dataset for model input
            ModelInput sampleData = CreateSingleDataSample(DATA_FILEPATH);

            // Make a single prediction on the sample data and print results
            ModelOutput predictionResult = ConsumeModel.Predict(sampleData);

            Console.WriteLine("Using model to make single prediction -- Comparing actual GoalDifference with predicted GoalDifference from sample data...\n\n");
            Console.WriteLine($"Hour: {sampleData.Hour}");
            Console.WriteLine($"Weekday: {sampleData.Weekday}");
            Console.WriteLine($"Team1GoalKeeper: {sampleData.Team1GoalKeeper}");
            Console.WriteLine($"Team1Striker: {sampleData.Team1Striker}");
            Console.WriteLine($"Team2GoalKeeper: {sampleData.Team2GoalKeeper}");
            Console.WriteLine($"Team2Striker: {sampleData.Team2Striker}");
            Console.WriteLine($"GoalsTeam1: {sampleData.GoalsTeam1}");
            Console.WriteLine($"GoalsTeam2: {sampleData.GoalsTeam2}");
            Console.WriteLine($"Result: {sampleData.Result}");
            Console.WriteLine($"\n\nActual GoalDifference: {sampleData.GoalDifference} \nPredicted GoalDifference: {predictionResult.Score}\n\n");
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 19
0
        public static void ConsumeModel()
        {
            // Load the model
            MLContext mlContext = new MLContext();

            ITransformer mlModel = mlContext.Model.Load("MLModel.zip", out var modelInputSchema);

            var predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Use the code below to add input data

            var input = new ModelInput();

            input.SentimentText = Console.ReadLine();

            // Try model on sample data
            // True is toxic, false is non-toxic
            ModelOutput result = predEngine.Predict(input);

            Console.WriteLine($"Text: {input.SentimentText} | Prediction: {(Convert.ToBoolean(result.Prediction) ? "Toxic" : "Non Toxic")} sentiment");
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            // Create single instance of sample data from first line of dataset for model input
            ModelInput sampleData = CreateSingleDataSample(DATA_FILEPATH);

            // Make a single prediction on the sample data and print results
            ModelOutput predictionResult = ConsumeModel.Predict(sampleData);

            Console.WriteLine("Using model to make single prediction -- Comparing actual Price with predicted Price from sample data...\n\n");
            Console.WriteLine($"CPU: {sampleData.CPU}");
            Console.WriteLine($"GHz: {sampleData.GHz}");
            Console.WriteLine($"GPU: {sampleData.GPU}");
            Console.WriteLine($"RAM: {sampleData.RAM}");
            Console.WriteLine($"RAMType: {sampleData.RAMType}");
            Console.WriteLine($"Screen: {sampleData.Screen}");
            Console.WriteLine($"Storage: {sampleData.Storage}");
            Console.WriteLine($"SSD: {sampleData.SSD}");
            Console.WriteLine($"Weight: {sampleData.Weight}");
            Console.WriteLine($"\n\nActual Price: {sampleData.Price} \nPredicted Price: {predictionResult.Score}\n\n");
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 21
0
        protected void RunComponents(ModelOutput mf)
        {
            var stateInterfaces = new Dictionary <string, object>(_components.Count);

            foreach (var c in Components)
            {
                Esmf.ComponentStructure.StateStructure s = Esmf.ComponentStructure.StateStructure.LoadFromInterface(c.StateInterfaceType);
                var o = s.ConnectToState(mf, c.Name);
                stateInterfaces.Add(c.Name, o);
            }

            mf.Clock.Reset();

            var clock = mf.Clock;

            while (!clock.IsDone)
            {
                for (int i = 0; i < _componentsOrder.Count; i++)
                {
                    var c = _components[_componentsOrder[i]];
                    //Console.WriteLine(c.Name);
                    var state = stateInterfaces[c.Name];
                    c.RunComponent(clock, state, mf);
                }

                if (!clock.IsLastTimestep)
                {
                    for (int i = 0; i < _componentsOrder.Count; i++)
                    {
                        var c     = _components[_componentsOrder[i]];
                        var state = stateInterfaces[c.Name];
                        c.RunTransitionFunction(clock, state, mf);
                    }
                }

                clock.Advance();
            }
        }
        public void TestLoadFromDiskAndPredictionEngine()
        {
            var dataFile    = GetDataPath("images/images.tsv");
            var imageFolder = Path.GetDirectoryName(dataFile);

            var data = ML.Data.LoadFromTextFile <ModelInput>(
                path: dataFile,
                hasHeader: false,
                separatorChar: '\t',
                allowQuoting: true,
                allowSparse: false);

            var dataProcessPipeline = ML.Transforms.Conversion.MapValueToKey("Label", "Label")
                                      .Append(ML.Transforms.LoadImages("ImagePath_featurized", imageFolder, "ImagePath"))
                                      .Append(ML.Transforms.ResizeImages("ImagePath_featurized", 224, 224, "ImagePath_featurized"))
                                      .Append(ML.Transforms.ExtractPixels("ImagePath_featurized", "ImagePath_featurized"))
                                      .Append(ML.Transforms.DnnFeaturizeImage("ImagePath_featurized", m => m.ModelSelector.ResNet18(m.Environment, m.OutputColumn, m.InputColumn), "ImagePath_featurized"))
                                      .Append(ML.Transforms.Concatenate("Features", new[] { "ImagePath_featurized" }))
                                      .Append(ML.Transforms.NormalizeMinMax("Features", "Features"))
                                      .AppendCacheCheckpoint(ML);

            var trainer = ML.MulticlassClassification.Trainers.OneVersusAll(ML.BinaryClassification.Trainers.AveragedPerceptron(labelColumnName: "Label", numberOfIterations: 10, featureColumnName: "Features"), labelColumnName: "Label")
                          .Append(ML.Transforms.Conversion.MapKeyToValue("PredictedLabel", "PredictedLabel"));

            var trainingPipeline = dataProcessPipeline.Append(trainer);
            var model            = trainingPipeline.Fit(data);

            string modelPath = GetOutputPath("TestSaveToDiskAndPredictionEngine-model.zip");

            ML.Model.Save(model, data.Schema, modelPath);
            var loadedModel = ML.Model.Load(modelPath, out var inputSchema);

            var         predEngine = ML.Model.CreatePredictionEngine <ModelInput, ModelOutput>(loadedModel);
            ModelInput  sample     = ML.Data.CreateEnumerable <ModelInput>(data, false).First();
            ModelOutput result     = predEngine.Predict(sample);

            Assert.Equal("tomato", result.Prediction);
        }
Esempio n. 23
0
        public static void ConsumeTaxiFareModel()
        {
            // Load the model
            MLContext mlContext = new MLContext();

            ITransformer mlModel = mlContext.Model.Load("MLModel.zip", out var modelInputSchema);

            var predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Use the code below to add input data
            var input = new ModelInput();

            input.Passenger_count   = 2;
            input.Trip_time_in_secs = 1200;
            input.Trip_distance     = 2.2f;


            // Try model on sample data
            // True is toxic, false is non-toxic
            ModelOutput result = predEngine.Predict(input);

            Console.WriteLine($"Passenger count: {input.Passenger_count}, Trip time: {input.Trip_time_in_secs}, Trip distance: {input.Trip_distance} | Prediction: {result.Score}");
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            ModelBuilder.CreateModel();
            // Create single instance of sample data from first line of dataset for model input
            ModelInput sampleData = CreateSingleDataSample(DATA_FILEPATH);

            // Make a single prediction on the sample data and print results
            ModelOutput predictionResult = ConsumeModel.Predict(sampleData);

            Console.WriteLine("Using model to make single prediction -- Comparing actual Saving with predicted Saving from sample data...\n\n");
            Console.WriteLine($"Ride Distance (km): {sampleData.Ride_Distance__km_}");
            Console.WriteLine($"Vehicle Type: {sampleData.Vehicle_Type}");
            Console.WriteLine($"Promo Value: {sampleData.Promo_Value}");
            Console.WriteLine($"Fare: {sampleData.Fare}");
            Console.WriteLine($"Paid: {sampleData.Paid}");
            Console.WriteLine($"Hour: {sampleData.Hour}");
            Console.WriteLine($"Minute: {sampleData.Minute}");
            Console.WriteLine($"Class: {sampleData.Class}");
            Console.WriteLine($"Day: {sampleData.Day}");
            Console.WriteLine($"\n\nActual Saving: {sampleData.Saving} \nPredicted Saving: {predictionResult.Score}\n\n");
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            // Create single instance of sample data from first line of dataset for model input
            ModelInput sampleData = CreateSingleDataSample(DATA_FILEPATH);

            // Make a single prediction on the sample data and print results
            ModelOutput predictionResult = ConsumeModel.Predict(sampleData);

            Console.WriteLine("Using model to make single prediction -- Comparing actual TileID with predicted TileID from sample data...\n\n");
            Console.WriteLine($"TilePlayed: {sampleData.TilePlayed}");
            Console.WriteLine($"tile1: {sampleData.Tile1}");
            Console.WriteLine($"tile2: {sampleData.Tile2}");
            Console.WriteLine($"tile3: {sampleData.Tile3}");
            Console.WriteLine($"tile4: {sampleData.Tile4}");
            Console.WriteLine($"tile5: {sampleData.Tile5}");
            Console.WriteLine($"tile6: {sampleData.Tile6}");
            Console.WriteLine($"tile7: {sampleData.Tile7}");
            Console.WriteLine($"tile8: {sampleData.Tile8}");
            Console.WriteLine($"tile9: {sampleData.Tile9}");
            Console.WriteLine($"\n\nActual TileID: {sampleData.TileID} \nPredicted TileID value {predictionResult.Prediction} \nPredicted TileID scores: [{String.Join(",", predictionResult.Score)}]\n\n");
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
        public async Task <IEnumerable <Recognition> > RecognizeAsync(Stream image, params string[] parameters)
        {
            using var bitmap = await image.AsSoftwareBitmapAsync();

            using var frame = VideoFrame.CreateWithSoftwareBitmap(bitmap);
            var imageFeature = ImageFeatureValue.CreateFromVideoFrame(frame);

            binding.Bind("data", imageFeature);

            var evalResult = await session.EvaluateAsync(binding, "0");

            var output = new ModelOutput()
            {
                ClassLabel = (evalResult.Outputs["classLabel"] as TensorString).GetAsVectorView().ToList(),
                Loss       = (evalResult.Outputs["loss"] as IList <IDictionary <string, float> >)[0].ToDictionary(k => k.Key, v => v.Value)
            };

            var result = output.Loss.OrderByDescending(l => l.Value).Select(l => new Recognition {
                Tag = l.Key, Probability = l.Value
            });

            return(result);
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            // Create single instance of sample data from first line of dataset for model input
            ModelInput sampleData = new ModelInput()
            {
                Title   = @"Donald Trump Sends Out Embarrassing New Year’s Eve Message; This is Disturbing",
                Text    = @"Donald Trump just couldn t wish all Americans a Happy New Year and leave it at that. Instead, he had to give a shout out to his enemies, haters and  the very dishonest fake news media.  The former reality show star had just one job to do and he couldn t do it. As our Country rapidly grows stronger and smarter, I want to wish all of my friends, supporters, enemies, haters, and even the very dishonest Fake News Media, a Happy and Healthy New Year,  President Angry Pants tweeted.  2018 will be a great year for America! As our Country rapidly grows stronger and smarter, I want to wish all of my friends, supporters, enemies, haters, and even the very dishonest Fake News Media, a Happy and Healthy New Year. 2018 will be a great year for America!  Donald J. Trump (@realDonaldTrump) December 31, 2017Trump s tweet went down about as welll as you d expect.What kind of president sends a New Year s greeting like this despicable, petty, infantile gibberish? Only Trump! His lack of decency won t even allow him to rise above the gutter long enough to wish the American citizens a happy new year!  Bishop Talbert Swan (@TalbertSwan) December 31, 2017no one likes you  Calvin (@calvinstowell) December 31, 2017Your impeachment would make 2018 a great year for America, but I ll also accept regaining control of Congress.  Miranda Yaver (@mirandayaver) December 31, 2017Do you hear yourself talk? When you have to include that many people that hate you you have to wonder? Why do the they all hate me?  Alan Sandoval (@AlanSandoval13) December 31, 2017Who uses the word Haters in a New Years wish??  Marlene (@marlene399) December 31, 2017You can t just say happy new year?  Koren pollitt (@Korencarpenter) December 31, 2017Here s Trump s New Year s Eve tweet from 2016.Happy New Year to all, including to my many enemies and those who have fought me and lost so badly they just don t know what to do. Love!  Donald J. Trump (@realDonaldTrump) December 31, 2016This is nothing new for Trump. He s been doing this for years.Trump has directed messages to his  enemies  and  haters  for New Year s, Easter, Thanksgiving, and the anniversary of 9/11. pic.twitter.com/4FPAe2KypA  Daniel Dale (@ddale8) December 31, 2017Trump s holiday tweets are clearly not presidential.How long did he work at Hallmark before becoming President?  Steven Goodine (@SGoodine) December 31, 2017He s always been like this . . . the only difference is that in the last few years, his filter has been breaking down.  Roy Schulze (@thbthttt) December 31, 2017Who, apart from a teenager uses the term haters?  Wendy (@WendyWhistles) December 31, 2017he s a f*****g 5 year old  Who Knows (@rainyday80) December 31, 2017So, to all the people who voted for this a hole thinking he would change once he got into power, you were wrong! 70-year-old men don t change and now he s a year older.Photo by Andrew Burton/Getty Images.",
                Subject = @"News",
                Date    = @"31-Dec-17",
            };

            // Make a single prediction on the sample data and print results
            ModelOutput predictionResult = ConsumeModel.Predict(sampleData);

            Console.WriteLine("Using model to make single prediction -- Comparing actual Type with predicted Type from sample data...\n\n");
            Console.WriteLine($"Title: {sampleData.Title}");
            Console.WriteLine($"Text: {sampleData.Text}");
            Console.WriteLine($"Subject: {sampleData.Subject}");
            Console.WriteLine($"Date: {sampleData.Date}");
            Console.WriteLine($"\n\nPredicted Type value {predictionResult.Prediction} \nPredicted Type scores: [{String.Join(",", predictionResult.Score)}]\n\n");
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var input = new ModelInput();

            input.Trip_distance     = 10;
            input.Trip_time_in_secs = 1000;

            ModelOutput result = ConsumeModel.Predict(input);

            Console.WriteLine("Tahmin edilen ödenecek tutar => " + result.Score);
            Console.ReadLine();

            Console.Write("Yeni rota uzaklığı giriniz => ");
            input.Trip_distance = Single.Parse(Console.ReadLine());

            Console.Write("Yeni rota zamanınızı giriniz (Saniye) => ");
            input.Trip_time_in_secs = Single.Parse(Console.ReadLine());

            ModelOutput result2 = ConsumeModel.Predict(input);

            Console.WriteLine("Tahmin edilen ödenecek tutar => " + result2.Score);
            Console.ReadLine();
        }
        public string TestIt()
        {
            MLContext mlContext = new MLContext();

            ITransformer mlModel    = mlContext.Model.Load(@"..\GithubLabelMlML.Model\MLModel.zip", out var modelInputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);
            // Use the code below to add input data
            var input = new ModelInput();

            Console.WriteLine("Enter The Title :");
            input.Title       = Title;
            input.Description = Description;
            //Console.WriteLine("Enter The Description :");
            //input.Description = Console.ReadLine();
            // Try model on sample data
            ModelOutput result = predEngine.Predict(input);

            Console.WriteLine("Result Rating=" + result.Prediction);
            //Console.WriteLine("Result=" + result.Score);

            // Console.ReadKey();
            return(result.Prediction.ToString());
        }
Esempio n. 30
0
        public float TestIt()
        {
            MLContext mlContext = new MLContext();

            ITransformer mlModel    = mlContext.Model.Load(@"..\PlayStoreML.Model\MLModel.zip", out var modelInputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);
            // Use the code below to add input data
            var input = new ModelInput();

            Console.WriteLine("Enter The Track Name :");
            input.Track_name  = TrackName;
            input.Prime_genre = Genre;
            //Console.WriteLine("Enter The Description :");
            //input.Description = Console.ReadLine();
            // Try model on sample data
            ModelOutput result = predEngine.Predict(input);

            Console.WriteLine("Result Rating=" + result.Prediction);
            //Console.WriteLine("Result=" + result.Score);

            // Console.ReadKey();
            return(result.Prediction);
        }
Esempio n. 31
0
        public static void ConsumeModel()
        {
            // Load the model
            MLContext mlContext = new MLContext();

            ITransformer mlModel = mlContext.Model.Load("MLModel.zip", out var modelInputSchema);

            var predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            // Use the code below to add input data
            var input = new ModelInput();

            //input.SentimentText = "That is rude";

// vendor_id,
// rate_code,
// passenger count,
// trip time in secs,
// trip distance,
// payment_type,
// fare_amount
            //CMT,3,1,2528,18.1,CSH,71

            input.Rate_code = 3;
            //        input.Passenger_count = 1;
//            input.Trip_time_in_secs = 2528;
//input.Trip_distance = float.Parse("18.1");
            input.Payment_type = "CSH";
//input.Fare_amount = 71;

            // Try model on sample data
            // True is toxic, false is non-toxic
            ModelOutput result = predEngine.Predict(input);

            //Console.WriteLine($"satıcı kimliği: {input.Vendor_id} | Oran Kodu: {input.Rate_code} | Yolcu Sayisi: {input.Passenger_count} | saniye olarak yolculuk süresi: {input.Trip_time_in_secs} | yolculuk mesafesi: {input.Trip_distance} | ödeme şekli: {input.Payment_type} | Hesap toplamı: {input.Fare_amount}");
            Console.WriteLine($"Tahmin: {(Convert.ToBoolean(result.Prediction) ? "Olumlu" : "Olumsuz")} yolcu");
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            // Create single instance of sample data from first line of dataset for model input
            ModelInput sampleData = CreateSingleDataSample(DATA_FILEPATH);

            // Make a single prediction on the sample data and print results
            ModelOutput predictionResult = ConsumeModel.Predict(sampleData);

            Console.WriteLine("Using model to make single prediction -- Comparing actual Class with predicted Class from sample data...\n\n");
            Console.WriteLine($"age: {sampleData.Age}");
            Console.WriteLine($"bp: {sampleData.Bp}");
            Console.WriteLine($"sg: {sampleData.Sg}");
            Console.WriteLine($"al: {sampleData.Al}");
            Console.WriteLine($"su: {sampleData.Su}");
            Console.WriteLine($"rbc: {sampleData.Rbc}");
            Console.WriteLine($"pc: {sampleData.Pc}");
            Console.WriteLine($"pcc: {sampleData.Pcc}");
            Console.WriteLine($"ba: {sampleData.Ba}");
            Console.WriteLine($"bgr: {sampleData.Bgr}");
            Console.WriteLine($"bu: {sampleData.Bu}");
            Console.WriteLine($"sc: {sampleData.Sc}");
            Console.WriteLine($"sod: {sampleData.Sod}");
            Console.WriteLine($"pot: {sampleData.Pot}");
            Console.WriteLine($"hemo: {sampleData.Hemo}");
            Console.WriteLine($"pcv: {sampleData.Pcv}");
            Console.WriteLine($"wbcc: {sampleData.Wbcc}");
            Console.WriteLine($"rbcc: {sampleData.Rbcc}");
            Console.WriteLine($"htn: {sampleData.Htn}");
            Console.WriteLine($"dm: {sampleData.Dm}");
            Console.WriteLine($"cad: {sampleData.Cad}");
            Console.WriteLine($"appet: {sampleData.Appet}");
            Console.WriteLine($"pe: {sampleData.Pe}");
            Console.WriteLine($"ane: {sampleData.Ane}");
            Console.WriteLine($"\n\nActual Class: {sampleData.Class} \nPredicted Class: {predictionResult.Prediction}\n\n");
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            // Training code used by ML.NET CLI and AutoML to generate the model
            Console.WriteLine("=============== Creating model ===============");
            ModelBuilder.CreateModel();
            Console.WriteLine("=============== Model created, hit any key to finish ===============");
            Console.ReadKey();
            ITransformer mlModel    = mlContext.Model.Load(MODEL_FILEPATH, out DataViewSchema inputSchema);
            var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

            Random random = new Random();
            //index = random.Next(1, 1000);
            int y;

            for (int i = 0; i <= 10; i++)
            {
                // Create sample data to do a single prediction with it
                y = random.Next(1, 140);
                ModelInput sampleData = CreateSingleDataSample(mlContext, DATA_FILEPATH, y);

                Console.WriteLine($"Iteration [{i}] for index {y}");
                // Try a single prediction
                ModelOutput predictionResult = predEngine.Predict(sampleData);

                Console.WriteLine($"SepalLength --> Actual value: [{sampleData.SepalLength}]");
                Console.WriteLine($"SepalWidth --> Actual value: [{sampleData.SepalWidth}]");
                Console.WriteLine($"PetalLength --> Actual value: [{sampleData.PetalLength}]");
                Console.WriteLine($"PetalWidth --> Actual value: [{sampleData.PetalWidth}]");
                Console.WriteLine($"Single Prediction --> Actual value: [{sampleData.Label}]");
                Console.WriteLine($"Predicted value: [{predictionResult.Prediction}]");
                Console.WriteLine($"Predicted scores: [{String.Join(",", predictionResult.Score)}]");
            } // of for loop
            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
        /// <summary>
        /// Data input yang dimasukkan dari array 0 - akhir itu nilai reflectance dari wave length: 2501.982414 sampe 1350.724346
        /// </summary>
        /// <param name="DataReflectance"></param>
        public List <ResultPrediction> Predict(string ModelFolder, float[] DataReflectance)
        {
            if (DataReflectance == null || DataReflectance.Length != 154)
            {
                return(null);
            }
            var datas = new List <ResultPrediction>();

            // Create sample data to do a single prediction with it
            ModelInput inputData = PreProcessData(new List <float>(DataReflectance));
            var        fileModel = Directory.GetFiles(ModelFolder, "*.zip");

            foreach (var file in fileModel)
            {
                var          modelName  = Path.GetFileNameWithoutExtension(file);
                ITransformer mlModel    = mlContext.Model.Load(GetAbsolutePath(file), out DataViewSchema inputSchema);
                var          predEngine = mlContext.Model.CreatePredictionEngine <ModelInput, ModelOutput>(mlModel);

                // Try a single prediction
                ModelOutput predictionResult = predEngine.Predict(inputData);

                ConsoleHelper.Print($"Prediction [{modelName}] --> Predicted value: {predictionResult.Score}");
                datas.Add(new ResultPrediction()
                {
                    ElementName = modelName, ElementValue = predictionResult.Score
                });
            }
            for (int i = 0; i < datas.Count; i++)
            {
                var item = datas[i];
                if (float.IsNaN(item.ElementValue))
                {
                    item.ElementValue = -9999;
                }
            }
            return(datas);
        }
Esempio n. 35
0
        private static void Rm_handDataChanged(RealsenseHandler.RsHand.Hand rightHand, RealsenseHandler.RsHand.Hand leftHand)
        {
            ModelInput handInput = new ModelInput();

            try
            {
                if (rightHand != null && rightHand.IsTracked)
                {
                    //float flexion = rightHand.Index.Foldness;
                    //Console.WriteLine(flexion);
                    MapHandRightDataToModelInput(ref rightHand, ref handInput);
                }
                else
                {
                }

                if (leftHand != null && leftHand.IsTracked)
                {
                    MapHandRightDataToModelInput(ref leftHand, ref handInput);
                }
                else
                {
                }

                ModelOutput modelOutput = ConsumeModel.Predict(handInput);
                if (modelOutput.Score.Max() > 0.85)
                {
                    Console.WriteLine($"Predicted Value : {modelOutput.Prediction}, Score : {modelOutput.Score.Max()}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.InnerException);
            }
        }
Esempio n. 36
0
File: Model.cs Progetto: VWille/fund
        protected void InitVariables(ModelOutput mf)
        {
            foreach (var key in _components.Keys)
            {
                var c = _components[key];
                foreach (var v in c.Variables)
                {
                    var dtpes = v.DimensionTypes.ToArray();

                    if (dtpes.Length == 0)
                    {
                        MethodInfo mi = typeof(ModelOutput).GetMethod("AddNonDimensionalVariable", new Type[] { typeof(string), typeof(string) });
                        MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { v.DataType });
                        mi2.Invoke(mf, new string[] { c.Name, v.Name });

                    }
                    else if (dtpes.Length == 1)
                    {
                        MethodInfo mi = typeof(ModelOutput).GetMethod("Add1DimensionalVariable");
                        MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { dtpes[0], v.DataType });
                        mi2.Invoke(mf, new object[] { c.Name, v.Name, !v.StoreOutput });

                    }
                    else if (dtpes.Length == 2)
                    {
                        MethodInfo mi = typeof(ModelOutput).GetMethod("Add2DimensionalVariable");
                        MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { dtpes[0], dtpes[1], v.DataType });
                        mi2.Invoke(mf, new object[] { c.Name, v.Name, !v.StoreOutput });

                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }
        }
Esempio n. 37
0
        public void RunTransitionFunction(Clock clock, object state, ModelOutput mf)
        {
            if (_hasTransitionFunction)
            {
                object c = Activator.CreateInstance(_componentType);

                var method = _componentType.GetMethod("RunTransitionFunction");
                method.Invoke(c, new object[] { clock, state, mf.Dimensions });
            }
        }
Esempio n. 38
0
        public void RunComponent(Clock clock, object state, ModelOutput mf)
        {
            object c = Activator.CreateInstance(_componentType);

            var method = _componentType.GetMethod("Run");
            method.Invoke(c, new object[] { clock, state, mf.Dimensions });

            //c.Run(clock, state, mf.Dimensions);
        }
Esempio n. 39
0
        public void DoOneRun(int RunId, WeightingCombination[] i_weightingCombinations, ParameterValues parameters)
        {
            double i_aggregatedDamage;
            ModelOutput i_output1;

            // Create Output object for run 1, set addmp to 0 so that
            // the extra greenhouse gases are not emitted and then run
            // the model
            i_output1 = new ModelOutput();

            var fundWorkflow = new Esmf.Model.ModelTyped<FundWorkflow>();

            var result1 = fundWorkflow.Run(parameters);

            i_output1.Load(result1);

            for (int i = 0; i < i_weightingCombinations.Length; i++)
            {
                i_weightingCombinations[i].CalculateWeights(i_output1);
                i_aggregatedDamage = i_weightingCombinations[i].AddDamagesUp(i_output1.Damages, _run.YearsToAggregate, _emissionYear);

                WriteAggregateDamage(RunId, i, i_aggregatedDamage, i_weightingCombinations);

            }

            //for (int l = 0; l < i_output1.Damages.Count; l++)
            //{
            //    i_Damage = i_output1.Damages[l];
            //    if ((i_Damage.Year >= _emissionYear.Value) && (i_Damage.Year < _emissionYear.Value + _run.YearsToAggregate))
            //    {
            //        for (int k = 0; k < i_weightingCombinations.Length; k++)
            //            WriteDamage(RunId, i_Damage, k, i_weightingCombinations[k][i_Damage.Year, i_Damage.Region], i_weightingCombinations);
            //    }
            //}
        }
Esempio n. 40
0
        public double[] DoOneRun(int RunId, WeightingCombination[] i_weightingCombinations, ParameterValues parameters)
        {
            ModelOutput i_output2;
            Damages i_marginalDamages;
            double i_aggregatedDamage;
            ModelOutput i_output1;

            // Create Output object for run 1, set addmp to 0 so that
            // the extra greenhouse gases are not emitted and then run
            // the model
            i_output1 = new ModelOutput();

            var f1 = FundModel.GetModel();
            f1["ImpactWaterResources"].Variables["water"].StoreOutput = true;
            f1["ImpactForests"].Variables["forests"].StoreOutput = true;
            f1["ImpactHeating"].Variables["heating"].StoreOutput = true;
            f1["ImpactCooling"].Variables["cooling"].StoreOutput = true;
            f1["ImpactAgriculture"].Variables["agcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true;
            f1["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true;
            f1["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true;
            f1["ImpactBioDiversity"].Variables["species"].StoreOutput = true;
            f1["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true;
            f1["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true;
            f1["SocioEconomic"].Variables["income"].StoreOutput = true;
            f1["Population"].Variables["population"].StoreOutput = true;

            if (AdditionalInitCode != null)
                AdditionalInitCode(f1);

            var result1 = f1.Run(parameters);

            i_output1.Load(result1);

            // Create Output object for run 2, set addmp to 1 so that
            // the extra greenhouse gases for the marginal run are
            // emitted and then run the model
            i_output2 = new ModelOutput();

            var f2 = FundModel.GetModel();
            f2["ImpactWaterResources"].Variables["water"].StoreOutput = true;
            f2["ImpactForests"].Variables["forests"].StoreOutput = true;
            f2["ImpactHeating"].Variables["heating"].StoreOutput = true;
            f2["ImpactCooling"].Variables["cooling"].StoreOutput = true;
            f2["ImpactAgriculture"].Variables["agcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true;
            f2["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true;
            f2["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true;
            f2["ImpactBioDiversity"].Variables["species"].StoreOutput = true;
            f2["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true;
            f2["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true;
            f2["SocioEconomic"].Variables["income"].StoreOutput = true;
            f2["Population"].Variables["population"].StoreOutput = true;

            if (AdditionalInitCode != null)
                AdditionalInitCode(f2);

            f2.AddComponent("marginalemission", typeof(Fund.Components.MarginalEmissionComponent), "emissions");
            f2["marginalemission"].Parameters["emissionperiod"].SetValue(_emissionyear);
            switch (_gas)
            {
                case MarginalGas.C:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "mco2");
                    f2["climateco2cycle"].Parameters["mco2"].Bind("marginalemission", "modemission");
                    break;
                case MarginalGas.CH4:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "globch4");
                    f2["climatech4cycle"].Parameters["globch4"].Bind("marginalemission", "modemission");
                    break;
                case MarginalGas.N2O:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "globn2o");
                    f2["climaten2ocycle"].Parameters["globn2o"].Bind("marginalemission", "modemission");
                    break;
                case MarginalGas.SF6:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "globsf6");
                    f2["climatesf6cycle"].Parameters["globsf6"].Bind("marginalemission", "modemission");
                    break;
                default:
                    throw new NotImplementedException();
            }

            var result2 = f2.Run(parameters);

            i_output2.Load(result2);

            Fund28LegacyWeightingCombinations.GetWeightingCombinationsFromName(this.WeightingCombination, out i_weightingCombinations, _emissionyear);

            // Take out growth effect effect of run 2 by transforming
            // the damage from run 2 into % of GDP of run 2, and then
            // multiplying that with GDP of run 1
            for (int year = 1; year < LegacyConstants.NYear; year++)
            {
                for (int region = 0; region < LegacyConstants.NoReg; region++)
                {
                    for (int sector = 0; sector < LegacyConstants.NoSector; sector++)
                    {
                        i_output2.Damages[year, region, (Sector)sector] = (i_output2.Damages[year, region, (Sector)sector] / i_output2.Incomes[year, region]) * i_output1.Incomes[year, region];
                    }
                }
            }

            // Calculate the marginal damage between run 1 and 2 for each
            // year/region/sector
            i_marginalDamages = Damages.CalculateMarginalDamage(i_output1.Damages, i_output2.Damages);

            double[] i_weightedAggregatedDamages = new double[i_weightingCombinations.Length];

            for (int i = 0; i < i_weightingCombinations.Length; i++)
            {
                i_weightingCombinations[i].CalculateWeights(i_output1);
                i_aggregatedDamage = i_weightingCombinations[i].AddDamagesUp(i_marginalDamages, YearsToAggregate, _emissionyear);

                i_weightedAggregatedDamages[i] = i_aggregatedDamage;

                WriteAggregateDamage(RunId, i, i_aggregatedDamage, i_weightingCombinations);

                // Console.Write(i_weightingCombinations[i].Name + ": ");
                // Console.WriteLine(Convert.ToString(i_aggregatedDamage));
            }

            if (m_YearRegionSectorWeightingSchemeCsv != null)
            {
                foreach (var i_Damage in i_marginalDamages)
                {
                    if ((i_Damage.Year >= _emissionyear.Value) && (i_Damage.Year < _emissionyear.Value + this.YearsToAggregate))
                    {
                        for (int k = 0; k < i_weightingCombinations.Length; k++)
                            WriteMarginalDamage(RunId, i_Damage, k, i_weightingCombinations[k][i_Damage.Year, i_Damage.Region], i_weightingCombinations);
                    }
                }
            }

            return i_weightedAggregatedDamages;
        }
Esempio n. 41
0
 public abstract void CalculateWeights(ModelOutput ModelOutput);
Esempio n. 42
0
 public void CalculateWeights(ModelOutput ModelOutput)
 {
     for (int i = 0; i < m_weightingSchemes.Count; i++)
         m_weightingSchemes[i].CalculateWeights(ModelOutput);
 }
Esempio n. 43
0
        public object ConnectToState(ModelOutput mf, string componentName)
        {
            Type t = GetProxyTypeForStateInterface();
            object connector = Activator.CreateInstance(t);

            IStateObjectConnections soc = (IStateObjectConnections)connector;

            foreach (StateFieldStructure field in _fields)
            {
                if (field.Dimensions.Count == 0)
                {

                    if (field.CanWrite)
                    {
                        soc.AddNonDimensionalField(field.Name, mf.GetNonDimensionalVariableGetter(componentName, field.Name), mf.GetNonDimensionalVariableSetter(componentName, field.Name));
                    }
                    else
                    {
                        soc.AddNonDimensionalField(field.Name, mf.GetNonDimensionalVariableGetter(componentName, field.Name));
                    }
                }
                else
                {
                    soc.AddDimensionalField(field.Name, mf.GetDimensionalField(componentName, field.Name));

                }
            }
            return connector;
        }
Esempio n. 44
0
File: Model.cs Progetto: VWille/fund
        protected void ReCreateStateVariables(ModelOutput mf)
        {
            mf._stateinterfaceOjbect.Clear();

            foreach (var c in Components)
            {
                Esmf.ComponentStructure.StateStructure s = Esmf.ComponentStructure.StateStructure.LoadFromInterface(c.StateInterfaceType);
                MethodInfo mi = s.GetType().GetMethod("ConnectToState");
                MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { c.StateInterfaceType });
                object o = mi2.Invoke(s, new object[] { mf, c.Name });
                mf._stateinterfaceOjbect.Add(c.Name, o);

            }
        }
Esempio n. 45
0
File: Model.cs Progetto: VWille/fund
        protected void RunComponents(ModelOutput mf)
        {
            mf.Clock.Reset();

            var clock = mf.Clock;

            while (!clock.IsDone)
            {
                for (int i = 0; i < _componentsOrder.Count; i++)
                {

                    var c = _components[_componentsOrder[i]];
                    //Console.WriteLine(c.Name);
                    var state = mf._stateinterfaceOjbect[c.Name];
                    c.RunComponent(clock, state, mf);

                }

                clock.Advance();
            }
        }
Esempio n. 46
0
File: Model.cs Progetto: VWille/fund
        // TODO Make flexible
        protected void LoadDimensions(ParameterValues parameters, ModelOutput mf)
        {
            var dimensionsFromParameters = from component in Components
                                           from parameter in component.Parameters
                                           from type in parameter.DimensionTypes
                                           where type != typeof(Timestep)
                                           select type;

            var dimensionsFromVariables = from component in Components
                                          from variable in component.Variables
                                          from type in variable.DimensionTypes
                                          where type != typeof(Timestep)
                                          select type;

            var allDimensionTypes = dimensionsFromParameters.Union(dimensionsFromVariables).Distinct().ToArray();

            foreach (var dimension in allDimensionTypes)
            {
                var parameterValues = (ParameterValue1Dimensional<string>)parameters[dimension.Name];

                int elementCount = parameterValues.Length;

                var dt = mf.Dimensions.GetType();
                var method = dt.GetMethod("Add");
                var typedMethod = method.MakeGenericMethod(new Type[] { dimension });
                object dim = typedMethod.Invoke(mf.Dimensions, new object[] { elementCount });

                var dimSetMethod = dim.GetType().GetMethod("Set");

                for (int i = 0; i < elementCount; i++)
                {
                    var s = parameterValues[i];

                    object dimelement = Activator.CreateInstance(dimension, new object[] { i, dim });
                    dimSetMethod.Invoke(dim, new object[] { i, dimelement, s });
                }
            }

            mf.Clock = new Clock(Timestep.FromSimulationYear(0), Timestep.FromSimulationYear(1049));
        }
Esempio n. 47
0
 public override void CalculateWeights(ModelOutput ModelOutput)
 {
 }
Esempio n. 48
0
File: Model.cs Progetto: VWille/fund
        protected void ConnectLeftoversToParameters(ModelOutput mf, ParameterValues parameters)
        {
            var parametersToFindValueFor = from component in Components
                                           from parameter in component.Parameters
                                           where parameter.Binding is ParameterValueFile
                                           select new
                                           {
                                               ComponentName = component.Name,
                                               ParameterName = parameter.Name,
                                               DimensionTypes = parameter.DimensionTypes,
                                               DataType = parameter.DataType,
                                               DefaultValue = parameter.Binding.DefaultValue,
                                               paer = parameter
                                           };

            var parametersWithManualValues = from component in Components
                                             from parameter in component.Parameters
                                             where parameter.Binding is ParameterValueManualConstant
                                             select new
                                             {
                                                 ComponentName = component.Name,
                                                 ParameterName = parameter.Name,
                                                 DimensionTypes = parameter.DimensionTypes,
                                                 DataType = parameter.DataType,
                                                 Value = ((ParameterValueManualConstant)parameter.Binding).Value,
                                                 paer = parameter
                                             };

            var parametersWithLambdas = from component in Components
                                        from parameter in component.Parameters
                                        where parameter.Binding is ParameterValueManuelLambda
                                        select new
                                        {
                                            ComponentName = component.Name,
                                            ParameterName = parameter.Name,
                                            DimensionTypes = parameter.DimensionTypes,
                                            DataType = parameter.DataType,
                                            Value = ((ParameterValueManuelLambda)parameter.Binding).Lambda,
                                            paer = parameter
                                        };

            var parametersInFileThatAreNotBound = from p in parameters
                                                  let pName = p.Name.ToLowerInvariant()
                                                  where !parametersToFindValueFor.Any(i => pName == i.ParameterName.ToLowerInvariant()) && pName != "region"
                                                  select p.Name;

            if (parametersInFileThatAreNotBound.Count() > 0)
            {
                Console.WriteLine();
                foreach (var p in parametersInFileThatAreNotBound)
                {
                    Console.WriteLine("WARNING: Parameter '{0}' is not used by model", p);
                }
            }

            foreach (var p in parametersWithManualValues)
            {
                mf.AddNonDimensionalVariable(p.ComponentName, p.ParameterName, p.Value);
            }

            foreach (var p in parametersWithLambdas)
            {
                if (p.Value.GetType().GetGenericTypeDefinition() == typeof(Func<,,>))
                {
                    var types = p.Value.GetType().GetGenericArguments();

                    var method = mf.GetType().GetMethod("Add2DimensionalParameterLambda").MakeGenericMethod(types);
                    method.Invoke(mf, new object[] { p.ComponentName, p.ParameterName, p.Value });
                }
                else
                    throw new NotImplementedException();
            }

            foreach (var p in parametersToFindValueFor)
            {
                if (parameters.Contains(p.ParameterName))
                {
                    mf.LoadVariableFromParameter(p.ComponentName, p.ParameterName, parameters, p.DataType, p.DimensionTypes.ToArray());
                }
                else if (p.DefaultValue != null)
                {
                    mf.AddNonDimensionalVariable(p.ComponentName, p.ParameterName, p.DefaultValue);
                }
                else
                    throw new InvalidOperationException();
            }
        }
Esempio n. 49
0
File: Model.cs Progetto: VWille/fund
        protected void ConnectBindings(ModelOutput mf)
        {
            var bindings = from component in Components
                           from parameter in component.Parameters
                           where parameter.Binding is ParameterValueBound
                           select new
                           {
                               TargetComponentName = component.Name,
                               TargetParameterName = parameter.Name,
                               SourceComponentName = ((ParameterValueBound)parameter.Binding).ComponentName,
                               SourceVariableName = ((ParameterValueBound)parameter.Binding).VariableName
                           };

            foreach (var b in bindings)
            {
                mf.ConnectParameterToVariable(b.TargetComponentName, b.TargetParameterName, b.SourceComponentName, b.SourceVariableName);
            }
        }
Esempio n. 50
0
        public double Start()
        {
            int yearsToRun = Math.Min(1049, EmissionYear.Value + YearsToAggregate);

            var f1 = FundModel.GetModel(storeFullVariablesByDefault: false, years: yearsToRun);
            f1["impactwaterresources"].Variables["water"].StoreOutput = true;
            f1["ImpactForests"].Variables["forests"].StoreOutput = true;
            f1["ImpactHeating"].Variables["heating"].StoreOutput = true;
            f1["ImpactCooling"].Variables["cooling"].StoreOutput = true;
            f1["ImpactAgriculture"].Variables["agcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true;
            f1["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true;
            f1["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true;
            f1["ImpactBioDiversity"].Variables["species"].StoreOutput = true;
            f1["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true;
            f1["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true;
            f1["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true;
            f1["socioeconomic"].Variables["income"].StoreOutput = true;
            f1["Population"].Variables["population"].StoreOutput = true;

            if (AdditionalInitMethod != null)
                AdditionalInitMethod(f1);

            var result1 = f1.Run(Parameters);

            var i_output1 = new ModelOutput();
            i_output1.Load(result1, years: yearsToRun);

            var f2 = FundModel.GetModel(storeFullVariablesByDefault: false, years: yearsToRun);
            f2["impactwaterresources"].Variables["water"].StoreOutput = true;
            f2["ImpactForests"].Variables["forests"].StoreOutput = true;
            f2["ImpactHeating"].Variables["heating"].StoreOutput = true;
            f2["ImpactCooling"].Variables["cooling"].StoreOutput = true;
            f2["ImpactAgriculture"].Variables["agcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true;
            f2["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true;
            f2["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true;
            f2["ImpactBioDiversity"].Variables["species"].StoreOutput = true;
            f2["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true;
            f2["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true;
            f2["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true;
            f2["socioeconomic"].Variables["income"].StoreOutput = true;
            f2["Population"].Variables["population"].StoreOutput = true;

            if (AdditionalInitMethod != null)
                AdditionalInitMethod(f2);

            f2.AddComponent("marginalemission", typeof(Fund.Components.MarginalEmissionComponent), "emissions");
            f2["marginalemission"].Parameters["emissionperiod"].SetValue(EmissionYear);
            switch (Gas)
            {
                case MarginalGas.C:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "mco2");
                    f2["climateco2cycle"].Parameters["mco2"].Bind("marginalemission", "modemission");
                    break;
                case MarginalGas.CH4:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "globch4");
                    f2["climatech4cycle"].Parameters["globch4"].Bind("marginalemission", "modemission");
                    break;
                case MarginalGas.N2O:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "globn2o");
                    f2["climaten2ocycle"].Parameters["globn2o"].Bind("marginalemission", "modemission");
                    break;
                case MarginalGas.SF6:
                    f2["marginalemission"].Parameters["emission"].Bind("emissions", "globsf6");
                    f2["climatesf6cycle"].Parameters["globsf6"].Bind("marginalemission", "modemission");
                    break;
                default:
                    throw new NotImplementedException();
            }

            var result2 = f2.Run(Parameters);

            var i_output2 = new ModelOutput();
            i_output2.Load(result2, years: yearsToRun);

            // Take out growth effect effect of run 2 by transforming
            // the damage from run 2 into % of GDP of run 2, and then
            // multiplying that with GDP of run 1
            for (int year = 1; year < LegacyConstants.NYear; year++)
            {
                for (int region = 0; region < LegacyConstants.NoReg; region++)
                {
                    for (int sector = 0; sector < LegacyConstants.NoSector; sector++)
                    {
                        i_output2.Damages[year, region, (Sector)sector] = (i_output2.Damages[year, region, (Sector)sector] / i_output2.Incomes[year, region]) * i_output1.Incomes[year, region];
                    }
                }
            }

            // Calculate the marginal damage between run 1 and 2 for each
            // year/region/sector
            var i_marginalDamages = Damages.CalculateMarginalDamage(i_output1.Damages, i_output2.Damages);

            var weightingcom = new WeightingCombination();
            if (UseEquityWeights)
            {
                weightingcom.Add(new ConstantDiscountrate(Prtp));
                weightingcom.Add(new EquityWeighting(EmissionYear.Value, -1, Eta));
            }
            else
            {
                weightingcom.Add(new RamseyRegionalDiscounting(Prtp, Eta, EmissionYear.Value));
            }

            weightingcom.CalculateWeights(i_output1);
            var i_aggregatedDamage = weightingcom.AddDamagesUp(i_marginalDamages, YearsToAggregate, EmissionYear);

            return i_aggregatedDamage;
        }