Exemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                string msg = "This console application is intended to run as a batch file "
                             + " using input files specified in app.json configuration file "
                             + " and writes output to specified file. Details can be found in log and "
                             + " only few messages pass through to the console.\r\n";
                Console.WriteLine(msg);

                Configure();
                logger.LogInformation("starting application");

                //получим контекст моделирования, передавая настройки для входных параметров
                //и для самого алгоритма
                ISimulationContext algorithm = contextFactory.GetSimulationContext(
                    configRoot.GetSection("input").Get <ConfigParams>(),
                    configRoot.GetSection("algorithm")
                    );
                ISimulationResult result = algorithm.Simulate();

                OutputResult(result);
            }
            catch (Exception ex) {
                string msg = string.Format("Exception {0} with message : {1}", ex.GetType(), ex.Message);
                if (logger != null)
                {
                    logger.LogCritical(ex, msg);
                    logger.LogCritical(ex.StackTrace);
                    NLog.LogManager.Flush();
                }
                Console.WriteLine(msg);
                Console.WriteLine("See log for more details");
            }
        }
Exemplo n.º 2
0
 public bool Equals(ISimulationResult other)
 {
     if (other == null)
     {
         return(false);
     }
     return(Key.Equals(other.Key));
 }
 public bool Equals(ISimulationResult other)
 {
     if (other == null)
     {
         return false;
     }
     return Key.Equals(other.Key);
 }
 public static void MyClassInitialize(TestContext testContext)
 {
     Directory.SetCurrentDirectory(testContext.TestDir);
     _testInstance = SimulationRepository.Instance;
     _testResult = new SimulationResult
     {
         Key = CreateKey(),
         Value = Dev2BinaryDataListFactory.CreateDataList()
     };
     _testInstance.Save(_testResult);
 }
Exemplo n.º 5
0
 public static void MyClassInitialize(TestContext testContext)
 {
     Directory.SetCurrentDirectory(testContext.TestDir);
     _testInstance = SimulationRepository.Instance;
     _testResult   = new SimulationResult
     {
         Key   = CreateKey(),
         Value = Dev2BinaryDataListFactory.CreateDataList()
     };
     _testInstance.Save(_testResult);
 }
Exemplo n.º 6
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <returns>
 /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
 /// </returns>
 /// <param name="other">An object to compare with this object.</param>
 public bool Equals(ISimulationResult other)
 {
     if(ReferenceEquals(null, other))
     {
         return false;
     }
     if(ReferenceEquals(this, other))
     {
         return true;
     }
     return Equals(Key, other.Key);
 }
        private static void WriteEquipmentData(ResultWorkSheet currWorkSheet, ISimulationResult simulationResult)
        {
            //запишем данные по загрузке оборудования
            int startRow         = currWorkSheet.currRow;
            int stopRow          = 1;
            int currEquipmentNum = 0;

            foreach (IEquipment eq in simulationResult.TaskByEquipment.Keys)
            {
                int startColumn = currEquipmentNum * currWorkSheet.columnsPerTask;
                //добавим заголовок
                int headerHeight = AddTaskHeader(eq, startRow, startColumn, currWorkSheet);

                int taskNum = 0;
                //заполним данные по всем задачам для этого оборудования
                foreach (var task in simulationResult.TaskByEquipment[eq])
                {
                    currWorkSheet.AdvanceToRow(startRow + taskNum + headerHeight);
                    currWorkSheet.AdvanceToColumn(startColumn);
                    if (currWorkSheet.currRow > stopRow)
                    {
                        stopRow = currWorkSheet.currRow;
                    }
                    currWorkSheet.Write(string.Format("{0}", task.id), WriteOptions.SingleCell);
                    currWorkSheet.Write(string.Format("{0}", task.description), WriteOptions.SingleCell);
                    currWorkSheet.Write(string.Format("{0}", task.startedAt), WriteOptions.SingleCell);
                    currWorkSheet.Write(string.Format("{0}", task.duration), WriteOptions.SingleCell);
                    taskNum++;
                }
                currWorkSheet.NewLine();
                currWorkSheet.AdvanceToColumn(startColumn + 3);
                currWorkSheet.Write(string.Format("sum(indirect(address({0},{2})&\":\"&address({1},{2})))",
                                                  startRow + headerHeight, currWorkSheet.currRow - 1,
                                                  currWorkSheet.currColumn), WriteOptions.Formula);
                currEquipmentNum++;
            }

            //перейдем на последнюю строку, которую заполнили по оборудованию
            stopRow++; //учитываем формулу "всего"
            currWorkSheet.AdvanceToRow(stopRow);

            //для таблички оборудования сделаем красивую автоширину колонки
            //AutoFitColumns() не работает нигде и никак
            //currWorkSheet.worksheet.Cells.AutoFitColumns();

            //уменьшим шрифт таблицы
            currWorkSheet.worksheet.Cells[startRow, 1,
                                          currWorkSheet.currRow, currWorkSheet.worksheet.Dimension.End.Column]
            .Style.Font.Size = 8.0f;
            //вернем красивость заголовку
            currWorkSheet.ApplyStyle(currWorkSheet.worksheet.Row(startRow).Style, WriteStyle.BigHeader);
            currWorkSheet.NewLine();
        }
Exemplo n.º 8
0
        public SimulationResponse(ISimulationResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            ExecutionDate = result.ExecutionDate;
            NumberOfGames = result.NumberOfGames;
            SwitchDoor    = result.SwitchDoor;
            WinPercentage = result.WinPercentage;
        }
Exemplo n.º 9
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <returns>
 /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
 /// </returns>
 /// <param name="other">An object to compare with this object.</param>
 public bool Equals(ISimulationResult other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(Equals(Key, other.Key));
 }
Exemplo n.º 10
0
 public void DeleteWithInvalidItem_Expected_ItemCountIsSame()
 {
     lock (l)
     {
         SimulationRepository thisInstance = _testInstance;
         int               expected        = thisInstance.Count;
         ISimulationKey    theKey          = CreateKey();
         ISimulationResult item            = CreateResult(theKey);
         string            id1             = theKey.ActivityID;
         string            id2             = theKey.ScenarioID;
         string            id3             = theKey.WorkflowID;
         Assert.AreEqual(expected, thisInstance.Count, "Fail 1");
         thisInstance.Delete(item); // Problem over here!
         Assert.AreEqual(expected, thisInstance.Count, "Fail 2");
     }
 }
        /// <summary>
        /// записать результаты моделирования в файл Excel
        /// </summary>
        public static void ToExcel(this ISimulationResult simulationResult, string filename)
        {
            if (File.Exists(filename))  //всегда создаем новый файл результатов
            {
                File.Delete(filename);
            }

            FileInfo excelFile = new FileInfo(filename);

            //в пути могут быть пока еще не созданные каталоги, создадим их
            Directory.CreateDirectory(excelFile.DirectoryName);

            using (ExcelPackage package = new ExcelPackage(excelFile)) {
                ResultWorkSheet currWorkSheet = new ResultWorkSheet();
                //"План загрузки оборудования" - слишком много для названия листа :=)
                currWorkSheet.worksheet = package.Workbook.Worksheets.Add("План загрузки");

                currWorkSheet.currRow = 1;

                if (simulationResult.HasErrors)  //были ошибки, просто вернем их список
                {
                    WriteErrors(currWorkSheet, simulationResult.Errors);
                    package.Save();
                    return;
                }
                //запишем данные по оборудованию
                currWorkSheet.startingColumn   = 2; //для красивости немного отступим
                currWorkSheet.singleColumnSize = 1;
                WriteEquipmentData(currWorkSheet, simulationResult);
                currWorkSheet.startingColumn = 1;
                currWorkSheet.NewLine();

                //запишем  метрики
                currWorkSheet.singleColumnSize = 4; //для метрик нужно побольше места
                WriteMetrics(currWorkSheet, simulationResult.Metrics);
                currWorkSheet.NewLine();

                //запишем все примечания
                foreach (string str in simulationResult.Footnotes)
                {
                    currWorkSheet.Write(str, WriteOptions.FullWidth);
                }
                package.Save();
            }
        }
Exemplo n.º 12
0
 private void CheckInitializationAndInputData(ISimulationResult simulationResult)
 {
     if ((LoggerFactory == null) || (InputParams == null))
     {
         simulationResult.Errors.Add(new ValidationResult("Modelling context not initialized. Can't contnue"));
         return;
     }
     logger = LoggerFactory.CreateLogger(this.GetType());
     InputParams.Validate();
     if (!InputParams.isValid)
     {
         foreach (var err in InputParams.ValidationResults)
         {
             logger.LogError(string.Format("input validation : {0}", err.ErrorMessage));
         }
         //входные данные некорректны или не согласованы или еще какая беда с ними
         List <ValidationResult> result = new List <ValidationResult>(InputParams.ValidationResults);
         result.Insert(0, new ValidationResult("input data is not valid or incorrect"));
         simulationResult.Errors = result;
         return;
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// вывести результат в консоль и в файл excel,
        /// если это указано в опциях
        /// </summary>
        /// <param name="result"></param>
        private static void OutputResult(ISimulationResult result)
        {
            Console.WriteLine();
            //выведем на консоль результаты
            foreach (string str in result.ToText())
            {
                Console.WriteLine(str);
                logger.LogInformation(str);
            }

            //проверим, указан ли файл для вывода в Excel
            logger.LogInformation("Creating Excel output file");
            FileParam excelFile = configRoot.GetSection("output").Get <FileParam>();

            if (FileParam.IsEmpty(excelFile))
            {
                string msg = "Excel output file not specified in config file and thus won't be generated";
                logger.LogWarning(msg);
                Console.WriteLine(msg);
                return;
            }
            result.ToExcel(excelFile.fileName);
            logger.LogInformation("Excel output file created");
        }
Exemplo n.º 14
0
        private ISimulationResult ToggleDistribution(DistributionInput distributionInput, DistributionType distributionType)
        {
            ISimulationResult distributions = null;

            switch (distributionType)
            {
            case DistributionType.Uniform:
                distributions = new Uniform().GetDistribution(distributionInput.Delegate,
                                                              distributionInput.Iteration, distributionInput.UncertaintyArray);
                break;

            case DistributionType.Triangular:
                distributions = new Triangular().GetDistribution(distributionInput.Delegate,
                                                                 distributionInput.Iteration, distributionInput.UncertaintyArray);
                break;

            case DistributionType.Normal:
                break;

            case DistributionType.Log_Normal:
                break;
            }
            return(distributions);
        }