示例#1
0
        public static SimulationModel Initialize(this CpuZ80 cpu, byte[] program, byte[] ioSpace = null)
        {
            new InstructionLogger(cpu);

            var model = new SimulationModel();

            model.Cpu      = cpu;
            model.Cpu.Name = "U1";
            model.ClockGen = new SignalGenerator();
            model.ClockGen.Output.ConnectTo(model.Cpu.Clock, "Clock");

            model.Memory      = MemoryTestExtensions.NewRam(program);
            model.Memory.Name = "U2";
            model.Cpu.MemoryRequest.ConnectTo(model.Memory.ChipEnable, "MREQ");
            model.Cpu.Read.ConnectTo(model.Memory.OutputEnable, "RD");
            model.Cpu.Write.ConnectTo(model.Memory.WriteEnable, "WE");
            model.Address = cpu.Address.ConnectTo(model.Memory.Address, "Address");
            model.Data    = cpu.Data.ConnectTo(model.Memory.Data.Slave, "Data");
            new MemoryLogger <BusData16, BusData8>().Attach(model.Memory);

            if (ioSpace != null)
            {
                model.IoSpace      = MemoryTestExtensions.NewRam(ioSpace);
                model.IoSpace.Name = "U3";
                model.Cpu.IoRequest.ConnectTo(model.IoSpace.ChipEnable, "IORQ");
                model.IoSpace.OutputEnable.ConnectTo(model.Cpu.Read.DigitalSignal);
                model.IoSpace.WriteEnable.ConnectTo(model.Cpu.Write.DigitalSignal);
                model.IoSpace.Address.ConnectTo(cpu.Address.Bus);
                model.IoSpace.Data.ConnectTo(cpu.Data.Bus);
                new MemoryLogger <BusData16, BusData8>("IO").Attach(model.IoSpace);
            }

            model.LogicAnalyzer = new LogicAnalyzer();
            model.LogicAnalyzer.Clock.ConnectTo(model.ClockGen.Output.DigitalSignal);
            model.Cpu.MachineCycle1.ConnectTo(model.LogicAnalyzer.AddInput("M1"));
            model.Cpu.Refresh.ConnectTo(model.LogicAnalyzer.AddInput("RFSH"));
            model.LogicAnalyzer.ConnectInput(model.Cpu.MemoryRequest.DigitalSignal);
            if (ioSpace != null)
            {
                model.LogicAnalyzer.ConnectInput(model.Cpu.IoRequest.DigitalSignal);
            }
            model.LogicAnalyzer.ConnectInput(model.Cpu.Read.DigitalSignal);
            model.LogicAnalyzer.ConnectInput(model.Cpu.Write.DigitalSignal);
            model.LogicAnalyzer.ConnectInput(model.Address);
            model.LogicAnalyzer.ConnectInput(model.Data);
            model.LogicAnalyzer.Start();

            return(model);
        }
示例#2
0
        public static void Lab3()
        {
            const double creatorDelay    = 1.0f;
            const double processDelay    = 2.5f;
            const int    processMaxQueue = 5;

            var creator = new Creator(creatorDelay);

            //var process1 = new Process("process1", processDelay, processMaxQueue, 2);
            //var process2 = new Process("process2", processDelay * 3, processMaxQueue, 2);
            //var process3 = new Process("process3", processDelay * 7, processMaxQueue, 1);
            //var process4 = new Process("process4", processDelay * 10, processMaxQueue, 1);

            var process1 = new Process("process1", processDelay, processMaxQueue, 1);
            var process2 = new Process("process2", processDelay, processMaxQueue, 1);
            var process3 = new Process("process3", processDelay, processMaxQueue, 1);
            var process4 = new Process("process4", processDelay, processMaxQueue, 1);

            var despose1 = new Despose("despose1");
            var despose2 = new Despose("despose2");

            var branch1 = new Branch(new List <(Element element, int weight)> {
                (process1, 4), (despose2, 1)
            });
            var branch2 = new Branch(new List <(Element element, int weight)> {
                (process2, 3), (process3, 2)
            });

            creator.nextElement  = branch1;
            process1.nextElement = branch2;
            process2.nextElement = despose1;
            process3.nextElement = process4;
            process4.nextElement = despose2;

            var model = new SimulationModel(new List <Element>
            {
                creator,
                process1,
                process2,
                process3,
                process4,
                despose1,
                despose2
            },
                                            SimulateTime);

            model.Simulate(false);
            model.PrintResultStatistic();
        }
示例#3
0
        /// <summary>
        /// Get Project, Cost related data from dynamic table Report_x_y, x = Network Id, y = Simulation Id
        /// </summary>
        /// <param name="simulationModel"></param>
        /// <param name="dbContext"></param>
        /// <param name="simulationYears"></param>
        /// <returns></returns>
        public IQueryable <ReportProjectCost> GetReportData(SimulationModel simulationModel, BridgeCareContext dbContext, List <int> simulationYears)
        {
            IQueryable <ReportProjectCost> rawQueryForReportData = null;
            var years         = string.Join(",", simulationYears);
            var listOfBudgets = dbContext.CriteriaDrivenBudgets.Where(y => y.SIMULATIONID == simulationModel.simulationId)
                                .Select(cri => "'" + cri.BUDGET_NAME + "'").ToList();

            var budgets = string.Join(",", listOfBudgets);
            var selectReportStatement = $"SELECT SECTIONID, TREATMENT, COST_, YEARS FROM REPORT_{simulationModel.networkId}_{simulationModel.simulationId} " +
                                        $"WITH (NOLOCK) WHERE BUDGET IN (" + budgets + ") AND YEARS IN (" + years + ")";

            rawQueryForReportData = dbContext.Database.SqlQuery <ReportProjectCost>(selectReportStatement).AsQueryable();

            return(rawQueryForReportData);
        }
示例#4
0
        public void TestInitialize()
        {
            var builder   = CreateModelBuilder(HelloWorldBin);
            var ioAddress = new BusTap(8);

            ioAddress.ConnectTo(builder.Model.Address);
            builder.AddOutputPort(ioAddress, builder.Model.Data, 0x20, "ConsoleOut");

            builder.AddLogicAnalyzer(false);
            builder.Model.LogicAnalyzer.ConnectInput(
                builder.Model.OutputPorts.Values.First().PortEnable.DigitalSignal);
            builder.Model.LogicAnalyzer.Start();

            _model = builder.Model;
        }
示例#5
0
        private static void ApplyAddedRegions(SimulationModel model, ModelResponse diff)
        {
            for (int i = 0; i < diff.AddedRegionsLength; i++)
            {
                Region addedRegion = diff.GetAddedRegions(i);

                Vector3 lower = addedRegion.Position.ToVector3();
                Vector3 size  = addedRegion.Size.ToVector3();

                Vector3 position = lower + size / 2;

                model.Regions[addedRegion.Index] = new RegionModel(addedRegion.Index, addedRegion.Name, addedRegion.Type,
                                                                   position, size);
            }
        }
示例#6
0
        private void ApplyObservers(SimulationModel model, ModelResponse diff)
        {
            for (int i = 0; i < diff.ObserverResultsLength; i++)
            {
                ObserverResult observerData = diff.GetObserverResults(i);

                NeuronId neuronId   = observerData.Observer.NeuronId;
                var      definition = new ObserverDefinition(neuronId.Neuron, neuronId.Region, observerData.Observer.Type);

                model.Observers[definition] = new ObserverData(
                    CopyObserverArrayData(observerData.MetadataLength, (n => observerData.GetMetadata(n))),
                    observerData.GetPlainDataBytes()?.ToArray(),
                    CopyObserverArrayData(observerData.FloatDataLength, (n => observerData.GetFloatData(n))));
            }
        }
示例#7
0
        public SimulationUI(SimulationModel model, bool isNewProject)
        {
            InitializeComponent();
            this.Model = model;
            this.SimulationEventHandler = new SimulationEventHandler(this);
            this.ConnectionCreator      = new ConnectionCreator(this.Model, this.target);

            //this.StartDate.SelectedDate = DateTime.Now;
            //this.StartDate.SelectedDate = DateTime.Now.AddMonths(1);

            if (!isNewProject)
            {
                PrintProject();
            }
        }
示例#8
0
        private void ApplyRemovedRegions(SimulationModel model, ModelResponse diff)
        {
            for (int i = 0; i < diff.RemovedRegionsLength; i++)
            {
                uint regionIndex = diff.GetRemovedRegions(i);

                if (!model.Regions.ContainsKey(regionIndex))
                {
                    Log.Warn("Cannot remove region with index {regionIndex}, region not found", regionIndex);
                    continue;
                }

                model.Regions.Remove(regionIndex);
            }
        }
示例#9
0
        public async Task <IHttpActionResult> RunSimulation([FromBody] SimulationModel model)
        {
            var result = await Task.Factory.StartNew(() => repo.RunSimulation(model));

            if (result.IsCompleted)
            {
                repo.SetSimulationLastRunDate(model.SimulationId, db);
            }
            else
            {
                return(InternalServerError(new Exception(result.Result)));
            }

            return(Ok());
        }
示例#10
0
        private void ApplyRemovedSynapses(SimulationModel model, ModelResponse diff)
        {
            for (int i = 0; i < diff.RemovedSynapsesLength; i++)
            {
                var synapse = diff.GetRemovedSynapses(i);

                ProcessSynapse(model, synapse, "remove", (fromRegion, fromNeuron, toRegion, toNeuron) =>
                {
                    var synapseModel = fromNeuron.Outputs[toNeuron.Index];
                    fromNeuron.Outputs.Remove(toNeuron.Index);
                    fromRegion.Synapses.Remove(synapseModel);
                    toNeuron.Inputs.Remove(fromNeuron.Index);
                });
            }
        }
示例#11
0
        private void ProcessConnector(SimulationModel model, uint regionIndex, string connectorName, string actionName, Action <RegionModel> action)
        {
            RegionModel targetRegionModel = model.Regions[regionIndex];

            if (targetRegionModel == null)
            {
                Log.Warn(
                    "Cannot " + actionName + " connector {connectorName}, region with index {regionIndex} was not found",
                    connectorName,
                    regionIndex);
                return;
            }

            action(targetRegionModel);
        }
示例#12
0
        /// <summary>
        /// Bsaic constructor
        /// </summary>
        /// <param name="type">Type of health care control unit</param>
        /// <param name="name">String identifier of control unit</param>
        /// <param name="parentControlUnit">Parent control unit if this is not the root control unit of the control tree</param>
        /// <param name="parentSimulationModel">Parent simulation model</param>
        /// <param name="inputData">Input data for the department</param>
        public ControlUnitHealthCareDepartment(ControlUnitType type,
                                               string name,
                                               ControlUnit parentControlUnit,
                                               SimulationModel parentSimulationModel,
                                               IInputHealthCareDepartment inputData)
            : base(type,
                   name,
                   parentControlUnit,
                   parentSimulationModel)
        {
            _childOrganizationalUnits   = new ControlUnitOrganizationalUnit[] { };
            _organizationalUnitsPerName = new Dictionary <string, ControlUnitOrganizationalUnit>();

            _inputData = inputData;
        } // end of ControlUnitHealthCare
示例#13
0
        public string[] InvestmentData(SimulationModel data)
        {
            var db          = new BridgeCareContext();
            var budgetOrder = db.Investments.Where(_ => _.SIMULATIONID == data.SimulationId)
                              .Select(_ => _.BUDGETORDER)
                              .First();

            if (string.IsNullOrEmpty(budgetOrder))
            {
                throw new Exception("Budget types not found in Investments table for the id : " + data.SimulationId);
            }
            var budgetTypes = budgetOrder.Split(',');

            return(budgetTypes);
        }
        public HttpResponseMessage ExportCommittedProjects([FromBody] SimulationModel model)
        {
            var response        = Request.CreateResponse();
            var userInformation = ESECSecurity.GetUserInformation(Request);

            byte[] byteArray = repo.ExportCommittedProjects(model.simulationId, model.networkId, db, userInformation);
            response.Content = new ByteArrayContent(byteArray);
            response.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "CommittedProjects.xlsx"
            };

            return(response);
            //return Ok(response);
        }
示例#15
0
        public void TestInitialize()
        {
            var builder = CreateModelBuilder(EchoBin);
            //var ioAddress = new BusTap(8);
            //ioAddress.ConnectTo(builder.Model.Address);
            var ioAddress  = builder.Model.Address;
            var outputPort = builder.AddOutputPort(ioAddress, builder.Model.Data, 0x20, "ConsoleOut");
            var inputPort  = builder.AddInputPort(ioAddress, builder.Model.Data, 0x20, "ConsoleIn");

            inputPort.DataBuffer.Write(Encoding.ASCII.GetBytes(Message));

            builder.AddLogicAnalyzer();
            LogExecutionPath(builder.Model);

            _model = builder.Model;
        }
示例#16
0
        public async Task <IHttpActionResult> RunSimulation([FromBody] SimulationModel model)
        {
            UserInformationModel userInformation = ESECSecurity.GetUserInformation(Request);
            var result = await Task.Factory.StartNew(() => SimulationRunMethods[userInformation.Role](model, userInformation));

            if (result.IsCompleted)
            {
                repo.SetSimulationLastRunDate(model.simulationId, db);
            }
            else
            {
                return(InternalServerError(new Exception(result.Result)));
            }

            return(Ok());
        }
示例#17
0
        /// <summary>
        /// Generate Bridge Summary Report for given simulation details.
        /// </summary>
        /// <param name="simulationModel"></param>
        /// <returns></returns>
        public byte[] GenerateExcelReport(SimulationModel simulationModel)
        {
            // Get data
            var simulationId         = simulationModel.SimulationId;
            var simulationYearsModel = commonSummaryReportData.GetSimulationYearsData(simulationId);
            var simulationYears      = simulationYearsModel.Years;
            var simulationYearsCount = simulationYears.Count;
            var dbContext            = new BridgeCareContext();

            using (ExcelPackage excelPackage = new ExcelPackage(new System.IO.FileInfo("SummaryReport.xlsx")))
            {
                // Bridge Data tab
                var bridgeDataModels = new List <BridgeDataModel>();
                var worksheet        = excelPackage.Workbook.Worksheets.Add("Bridge Data");
                var workSummaryModel = summaryReportBridgeData.Fill(worksheet, simulationModel, simulationYears, dbContext);

                // Bridge Work Summary tab
                var bridgeWorkSummaryWorkSheet = excelPackage.Workbook.Worksheets.Add("Bridge Work Summary");
                var chartRowsModel             = bridgeWorkSummary.Fill(bridgeWorkSummaryWorkSheet, workSummaryModel.SimulationDataModels, workSummaryModel.BridgeDataModels, simulationYears, dbContext, simulationId);

                // NHS Condition Bridge Cnt tab
                worksheet = excelPackage.Workbook.Worksheets.Add("NHS Condition Bridge Cnt");
                nhsConditionChart.Fill(worksheet, bridgeWorkSummaryWorkSheet, chartRowsModel.NHSBridgeCountPercentSectionYearsRow, Properties.Resources.NHSConditionByBridgeCountLLCC, simulationYearsCount);

                // NHS Condition DA tab
                worksheet = excelPackage.Workbook.Worksheets.Add("NHS Condition DA");
                nhsConditionChart.Fill(worksheet, bridgeWorkSummaryWorkSheet, chartRowsModel.NHSBridgeDeckAreaPercentSectionYearsRow, Properties.Resources.NHSConditionByDeckAreaLLCC, simulationYearsCount);

                // Condition Bridge Cnt tab
                worksheet = excelPackage.Workbook.Worksheets.Add("Condition Bridge Cnt");
                conditionBridgeCount.Fill(worksheet, bridgeWorkSummaryWorkSheet, chartRowsModel.TotalBridgeCountSectionYearsRow, simulationYearsCount);

                // Condition DA tab
                worksheet = excelPackage.Workbook.Worksheets.Add("Condition DA");
                conditionDeckArea.Fill(worksheet, bridgeWorkSummaryWorkSheet, chartRowsModel.TotalDeckAreaSectionYearsRow, simulationYearsCount);

                // Poor Bridge Cnt tab
                worksheet = excelPackage.Workbook.Worksheets.Add("Poor Bridge Cnt");
                poorBridgeCount.Fill(worksheet, bridgeWorkSummaryWorkSheet, chartRowsModel.TotalPoorBridgesCountSectionYearsRow, simulationYearsCount);

                // Poor Bridge DA tab
                worksheet = excelPackage.Workbook.Worksheets.Add("Poor Bridge DA");
                poorBridgeDeckArea.Fill(worksheet, bridgeWorkSummaryWorkSheet, chartRowsModel.TotalPoorBridgesDeckAreaSectionYearsRow, simulationYearsCount);

                return(excelPackage.GetAsByteArray());
            }
        }
示例#18
0
        protected void RunTest(SimulationModel model, ushort endAddress = EndOfProgram)
        {
            bool stop = false;

            model.Cpu.InstructionExecuted += (s, e) => {
                stop = e.Opcode.Address == endAddress ||
                       model.Cpu.Halt.Level == Zim80.DigitalLevel.Low;
            };

            model.ClockGen.SquareWave((c) => stop);

            if (model.LogicAnalyzer != null)
            {
                model.LogicAnalyzer.Stop();
                Console.WriteLine(model.LogicAnalyzer.ToWaveJson());
            }
        }
        /// <summary>
        /// Runs a single simulation with passed parameters and tests it
        /// </summary>
        /// <param name="clusterId">Id of the cluster used in simulation</param>
        /// <param name="mapId">Id of the map used in simulation</param>
        /// <param name="vehicleIds">Ids of the vehicles used in simulation</param>
        /// <param name="interactive">Ids of the vehicles used in simulation</param>
        /// <returns>IEnumerator</returns>
        private IEnumerator RunSimulation(long clusterId, long mapId, long[] vehicleIds, bool interactive)
        {
            var vehicles = new ConnectionModel[vehicleIds.Length];

            for (var i = 0; i < vehicleIds.Length; i++)
            {
                var vehicleId = vehicleIds[i];
                vehicles[i] = new ConnectionModel()
                {
                    Connection = "",
                    Id         = 0,
                    Vehicle    = vehicleId,
                    Simulation = 0
                };
            }

            var simulationModel = new SimulationModel()
            {
                Cluster        = clusterId,
                Headless       = false,
                Interactive    = interactive,
                Vehicles       = vehicles,
                Map            = mapId,
                ApiOnly        = false,
                UsePedestrians = true,
                UseTraffic     = true
            };

            yield return(RunSimulation(simulationModel));

            yield return(WaitForClients());

            yield return(new WaitForSecondsRealtime(1.0f));

            if (interactive)
            {
                SimulatorManager.Instance.UIManager.PauseButtonOnClick();
            }
            yield return(PerformPingsTests(10));

            Loader.StopAsync();
            while (Loader.Instance.CurrentSimulation != null)
            {
                yield return(null);
            }
        }
示例#20
0
        private void ApplyRepositionedRegions(SimulationModel model, ModelResponse diff)
        {
            for (int i = 0; i < diff.RepositionedRegionsLength; i++)
            {
                Region repositionedRegion = diff.GetRepositionedRegions(i);

                RegionModel regionModel;
                if (!model.Regions.TryGetModel(repositionedRegion.Index, out regionModel))
                {
                    Log.Warn("Could not reposition region {region}, not found", repositionedRegion.Index);
                    continue;
                }

                regionModel.Position = repositionedRegion.Position.ToVector3();
                regionModel.Size     = repositionedRegion.Size.ToVector3();
            }
        }
示例#21
0
        } // end of ActionsAfterFinishingSimulationRun

        #endregion

        #region NonVisualizationLoop

        public void NonVisualizationLoop()
        {
            DateTime originalTimerTime = CurrentTime;

            while (BackgroundWorkerNonVisualization.CancellationPending == false &&
                   !SimulationModel.StopSimulation(CurrentTime))
            {
                DateTime newTime;
                bool     modelRunning = SimulationEngine.RunSingleStepSimulationModel(_currentTime, out newTime);

                if (modelRunning)
                {
                    BackgroundWorkerNonVisualization.ReportProgress(SimulationEngine.SimulationModel.GetSimulationProgress(newTime));
                    _currentTime = newTime;
                } // end if
            }     // end while
        }         // end of
示例#22
0
 public void SetSimulationModel(SimulationModel value)
 {
     lock (monitor) {
         SimulationModel oldValue = simModel;
         if (value != oldValue)
         {
             simModel = value;
             if (oldValue != null)
             {
                 oldValue.SimulationModelModifiedEvent -= SimulationUpdated;
             }
             if (value != null)
             {
                 value.SimulationModelModifiedEvent += SimulationUpdated;
             }
         }
     }
 }
示例#23
0
        public void Start()
        {
            Stop();

            m_requestModelEvent = new AutoResetEvent(false);
            m_modelReadEvent    = new AutoResetEvent(false);

            m_cancellation = new CancellationTokenSource();

            m_getFullModel = true;
            Task task = RepeatGetModelAsync(m_cancellation);

            m_currentModel  = new SimulationModel();
            m_previousModel = new SimulationModel();

            // The empty model is what we have at the beginning.
            m_isNewModelReady = true;
        }
示例#24
0
        //--------------------------------------------------------------------------------------------------
        // Constructor
        //--------------------------------------------------------------------------------------------------

        #region Constructor

        /// <summary>
        /// Constructor that sets string representations for entities for logging purposes
        /// </summary>
        /// <param name="parentSimulationModel">Simulation model that is executed</param>
        public BaseLoggingEngine(SimulationModel parentSimulationModel)
        {
            _parentSimulationModel = parentSimulationModel;
            _simulationResult      = new List <SimulationState>();

            _defaultEntityStringReps = new Dictionary <Type, string>();

            _defaultEntityStringReps.Add(typeof(EntityDoctor), "EntityDoctor");
            _defaultEntityStringReps.Add(typeof(EntityPatient), "EntityPatient");
            _defaultEntityStringReps.Add(typeof(EntityNurse), "EntityNurse");
            _defaultEntityStringReps.Add(typeof(EntityTreatmentFacility), "EntitiyTreatmentFacility");
            _defaultEntityStringReps.Add(typeof(EntityWaitingArea), "EntityWaitingArea");
            _defaultEntityStringReps.Add(typeof(EntityMultiplePatientTreatmentFacility), "EntityMultiplePatientTreatmentFacility");
            _defaultEntityStringReps.Add(typeof(EntityWaitingListSchedule), "EntityWaitingListSchedule");
            _defaultEntityStringReps.Add(typeof(EntityPath), "EntityPath");
            //_defaultEntityStringReps.Add(typeof(EntityBreastCancerPatient), "EntityBreastCancerPatient");
            _defaultEntityStringReps.Add(typeof(EntitySingleBookingModelWaitingList), "EntitySingleBookingModelWaitingList");
        } // end of BaseLoggingEngine
示例#25
0
        }     // end of StopSimulation

        #endregion

        #region PlaySimulationTick

        public void PlaySimulationTick(object sender, EventArgs e)
        {
            // security call in case the timer ticks bfore
            // it disabled by stop simulation
            if (!VisualizationEnabled)
            {
                return;
            }

            DateTime timeOfCall;

            if (TickCallIsSimulationCall)
            {
                timeOfCall = CurrentTime;

                DateTime newTime;
                bool     modelRunning = SimulationEngine.RunSingleStepSimulationModel(CurrentTime, out newTime);

                // in case end of model is reached the simulation is stopped
                if (!modelRunning)
                {
                    StopSimulation(false);
                    return;
                } // end if

                SimulationDisplayClock.SetDateTime(CurrentTime);
                SimulationModel.SimulationDrawingEngine.CreateModelVisualization(CurrentTime, SimulationModel, SimulationEngine.CurrentlyTriggeredEvents);
                ProgressBarSimulationProgress.Value = SimulationModel.GetSimulationProgress(CurrentTime);

                _nextSimulationTime = newTime;
                _currentTime        = newTime;
            }
            else
            {
                timeOfCall = NextTimerTime;

                SimulationDisplayClock.SetDateTime(NextTimerTime);
                SimulationModel.SimulationDrawingEngine.CreateModelVisualization(NextTimerTime, SimulationModel, new List <Event>());
                ProgressBarSimulationProgress.Value = SimulationModel.GetSimulationProgress(CurrentTime);
                _nextTimerTime += ConstantTimerStep;
            } // end if

            SimulationTimer.Interval = TimeSpan.FromMilliseconds(Math.Max((int)(((NextTime - timeOfCall).Ticks / ConstantTimerStep.Ticks) * SimulationSpeed), 1));
        } // end of PlaySimulationTick
        public SimulationModel Get(Project project)
        {
            SimulationModel  model            = new SimulationModel();
            SupplierBroker   supplierBroker   = new SupplierBroker();
            ShopBroker       shopBroker       = new ShopBroker();
            BuyerBroker      buyerBroker      = new BuyerBroker();
            ConnectionBroker connectionBroker = new ConnectionBroker();

            model.Project = project;

            using (IDbConnection connection = new ConnectionProvider().GetConnection(true))
            {
                model.Buyers      = buyerBroker.GetAllFromProject(connection, model.Project.Id).ToList();
                model.Shops       = shopBroker.GetAllFromProject(connection, model.Project.Id).ToList();
                model.Suppliers   = supplierBroker.GetAllFromProject(connection, model.Project.Id).ToList();
                model.Connections = connectionBroker.GetAllFromProject(connection, model.Project.Id).ToList();
            }

            foreach (Connection conn in model.Connections)
            {
                switch (conn.ConnectionType)
                {
                case DataModel.EnumTypes.ConnectionTypes.ShopToBuyer:
                    conn.ActorA = model.Shops.Find(x => x.Id == conn.ActorAId);
                    conn.ActorB = model.Buyers.Find(x => x.Id == conn.ActorBId);
                    break;

                case DataModel.EnumTypes.ConnectionTypes.ShopToShop:
                    conn.ActorA = model.Shops.Find(x => x.Id == conn.ActorAId);
                    conn.ActorB = model.Shops.Find(x => x.Id == conn.ActorBId);
                    break;

                case DataModel.EnumTypes.ConnectionTypes.SupplierToShop:
                    conn.ActorA = model.Suppliers.Find(x => x.Id == conn.ActorAId);
                    conn.ActorB = model.Shops.Find(x => x.Id == conn.ActorBId);
                    break;

                default:
                    break;
                }
            }

            return(model);
        }
示例#27
0
        public void ShowNewProjectDialog()
        {
            var w = new NewProjectWindow();

            if (w.ShowDialog() == true)
            {
                Project project = w.Project;
                if (project != null)
                {
                    Model = new SimulationModel(project);
                    SimulationUI ui = new SimulationUI(Model, true);
                    ui.InitializeComponent();
                    simulationUI.Content = ui;
                    SetTitle(project.Name);
                    MnuSave.IsEnabled   = true;
                    MnuSaveAs.IsEnabled = true;
                }
            }
        }
示例#28
0
        protected void RunTest(SimulationModel model, params ushort[] endAddresses)
        {
            var stopList = new List <ushort>(endAddresses);

            bool stop = false;

            model.Cpu.InstructionExecuted += (s, e) => {
                stop = stopList.Contains(e.Opcode.Address) ||
                       model.Cpu.Halt.Level == DigitalLevel.Low;
            };

            model.ClockGen.SquareWave((c) => stop);

            if (model.LogicAnalyzer != null)
            {
                model.LogicAnalyzer.Stop();
                Console.WriteLine(model.LogicAnalyzer.ToWaveJson());
            }
        }
示例#29
0
        public Simulations(Dictionary <string, string> megagridAddressDictionary, Digest digest)
        {
            foreach (KeyValuePair <string, string> kvp in megagridAddressDictionary)
            {
                if (!simulations.ContainsKey(kvp.Value.Trim()))
                {
                    SimulationModel simModel = new SimulationModel();

                    CompiledCode code  = digest.FindByName(kvp.Value);
                    Grid         grid  = Pivot.ToGrid(new Code(code.minimalCode));
                    RectList     rects = Pivot.ToRects(grid);
                    simModel.grid = grid;
                    RasterLib.RasterApi.BuildCircuit(rects, true);
                    simModel.rects = rects;
                    simModel.Build();
                    simulations.Add(kvp.Value.Trim(), simModel);
                }
            }
        }
示例#30
0
文件: Target.cs 项目: radtek/iAM
        internal void Fill(ExcelWorksheet targetReport, SimulationModel model, int[] totalYears)
        {
            var targetResults = repo.GetTarget(model, totalYears, db);

            if (targetResults.Targets.Rows.Count > 0)
            {
                targetReport.Cells[2, 3, targetResults.Targets.Rows.Count + 1, targetResults.Targets.Columns.Count]
                .Style.Fill.PatternType = ExcelFillStyle.Solid;
                targetReport.Cells[2, 3, targetResults.Targets.Rows.Count + 1, targetResults.Targets.Columns.Count]
                .Style.Fill.BackgroundColor.SetColor(Color.LightCoral);
            }

            foreach (var(row, column) in targetResults.Address.Cells)
            {
                targetReport.Cells[row, column + 1].Style.Fill.BackgroundColor.SetColor(Color.LightGreen);
            }
            targetReport.Cells.LoadFromDataTable(targetResults.Targets, true);
            targetReport.Cells.AutoFitColumns();
        }