/// <summary>Performs necessary initialization of the device, like mapping to the equation system.</summary> /// <param name="adapter">The equation system builder.</param> /// <param name="context">Context of current simulation.</param> public override void Initialize(IEquationSystemAdapter adapter, ISimulationContext context) { stamper.Register(adapter, bprimeNode, cprimeNode, eprimeNode); voltageBc.Register(adapter, bprimeNode, cprimeNode); voltageBe.Register(adapter, bprimeNode, eprimeNode); voltageCs.Register(adapter, cprimeNode, Substrate); capacbe.Register(adapter, bprimeNode, eprimeNode); capacbc.Register(adapter, bprimeNode, cprimeNode); capaccs.Register(adapter, cprimeNode, Substrate); chargebe = context.SimulationParameters.IntegrationMethodFactory.CreateInstance(); chargebc = context.SimulationParameters.IntegrationMethodFactory.CreateInstance(); chargecs = context.SimulationParameters.IntegrationMethodFactory.CreateInstance(); gb.Register(adapter, bprimeNode, Base); gc.Register(adapter, cprimeNode, Collector); ge.Register(adapter, eprimeNode, Emitter); vT = PhysicalConstants.Boltzmann * PhysicalConstants.CelsiusToKelvin(Parameters.NominalTemperature) / PhysicalConstants.DevicearyCharge; VoltageBaseEmitter = DeviceHelpers.PnCriticalVoltage(Parameters.SaturationCurrent, vT); }
/// <summary>This method is called each time an equation is solved.</summary> /// <param name="context">Context of current simulation.</param> public override void OnEquationSolution(ISimulationContext context) { foreach (var model in devices) { model.OnEquationSolution(context); } }
/// <summary> /// Applies device impact on the circuit equation system. If behavior of the device is nonlinear, this method is /// called once every Newton-Raphson iteration. /// </summary> /// <param name="context">Context of current simulation.</param> public override void ApplyModelValues(ISimulationContext context) { vt = Parameters.EmissionCoefficient * PhysicalConstants.Boltzmann * PhysicalConstants.CelsiusToKelvin(Parameters.NominalTemperature) / PhysicalConstants.DevicearyCharge; gmin = Parameters.MinimalResistance ?? context.SimulationParameters.MinimalResistance; smallBiasTreshold = -5 * vt; capacitanceTreshold = Parameters.ForwardBiasDepletionCapacitanceCoefficient * Parameters.JunctionPotential; var vd = Voltage - Parameters.SeriesResistance * Current; var(id, geq, cd) = GetModelValues(vd); var ieq = id - geq * vd; // Diode stamper.Stamp(geq, -ieq); // Capacitance var(cieq, cgeq) = IntegrationMethod.GetEquivalents(cd / context.TimeStep); if (initialConditionCapacitor) // initial condition { capacitorStamper.Stamp(0, 0); } else { capacitorStamper.Stamp(cieq, cgeq); } Current = id + ic; Conductance = geq; }
/// <summary> /// Invoke this method before calling Execute(), to initialize the actor /// with details like the device model and message type to simulate. /// </summary> public async Task Init(ISimulationContext simulationContext, string deviceId, DeviceModel deviceModel, IDeviceConnectionActor context) { this.instance.InitOnce(); this.simulationContext = simulationContext; this.deviceModel = deviceModel; this.deviceId = deviceId; this.deviceContext = context; this.actorLogger.Init(deviceId, "Replay"); string fileId = simulationContext.ReplayFileId; try { if (!string.IsNullOrEmpty(fileId)) { var data = await this.replayFileService.GetAsync(fileId); this.file = data.Content; this.fileReader = new StringReader(this.file); this.status = ActorStatus.ReadLine; } } catch (Exception e) { this.log.Error("Failed to read line", () => new { this.deviceId, e }); } this.instance.InitComplete(); }
private ISimulationContext CreateContext(IConfigurationSection algorithmConfig) { //если никакие настройки не указаны - создаем первый попавшийся алгоритм без параметров if (algorithmConfig == null) { return(new SimpleBruteAlgorithm()); } //получим название класса, который нужно создать string className = algorithmConfig.GetValue <string>("class"); if (string.IsNullOrWhiteSpace(className)) { throw new ArgumentException("algorithm class name not specified in 'class' config section"); } Assembly whereToSearch = System.Reflection.Assembly.GetAssembly(typeof(SimpleBruteAlgorithm)); //поищем его в текущей сборке object createdType = whereToSearch.CreateInstance(className); if (createdType == null) { throw new ArgumentException(string.Format("class '{0}' not found in assembly {1}. Loading from a different assembly is currently not supported", className, whereToSearch.FullName)); } //и убедимся, что он реализовывает нужный интерфейс ISimulationContext context = createdType as ISimulationContext; if (context == null) { throw new ArgumentException(string.Format("class '{0}' does not implement necessary interface {1}", className, typeof(ISimulationContext).Name)); } return(context); }
private void HandleOptions(ISimulationContext context, IConfigurationSection algorithmConfig) { IContextWithOptions withOptions = context as IContextWithOptions; if (withOptions == null) { //нет настроек в алгоритме logger.LogDebug("Algorithm doesn't support options "); return; } logger.LogDebug("Algorithm may require options to run."); IConfigurationSection optionsSection = (algorithmConfig != null) ? algorithmConfig.GetSection("options") : null; if (optionsSection == null) { logger.LogWarning("no options specified in config"); return; } //настройки все есть, передаем в алгоритм object options = optionsSection.Get(withOptions.OptionClass); withOptions.SetOptions(options); logger.LogDebug("options passed to algorithm"); }
public override void Initialize(IEquationSystemAdapter adapter, ISimulationContext context) { // get proxies voltage.Register(adapter, Anode, Cathode); currentStamper.Register(adapter, Anode, Cathode); conductanceStamper.Register(adapter, Anode, Cathode); }
/// <summary>Performs necessary initialization of the device, like mapping to the equation system.</summary> /// <param name="adapter">The equation system builder.</param> /// <param name="context">Context of current simulation.</param> public override void Initialize(IEquationSystemAdapter adapter, ISimulationContext context) { stamper.Register(adapter, Anode, Cathode); voltage.Register(adapter, Anode, Cathode); firstDcPoint = true; IntegrationMethod = context.SimulationParameters.IntegrationMethodFactory.CreateInstance(); }
public override bool CanComplete(ISimulationContext context, out long?skipFurtherChecksUntilTimePeriod) { HasCanCompleteBeenCalled = true; skipFurtherChecksUntilTimePeriod = CanCompleteNextTimePeriodResult; return(CanCompleteResult); }
/// <summary> /// Invoke this method before calling Execute(), to initialize the actor /// with details like the device model and message type to simulate. /// Init() should be called only once. /// </summary> public void Init( ISimulationContext simulationContext, string deviceId, DeviceModel deviceModel, IDeviceStateActor deviceStateActor, ConnectionLoopSettings loopSettings) { this.instance.InitOnce(); this.simulationContext = simulationContext; this.deviceModel = deviceModel; this.deviceId = deviceId; this.deviceStateActor = deviceStateActor; this.loopSettings = loopSettings; this.credentialsSetupLogic.Init(this, this.deviceId, this.deviceModel); this.fetchFromRegistryLogic.Init(this, this.deviceId, this.deviceModel); this.registerLogic.Init(this, this.deviceId, this.deviceModel); this.connectLogic.Init(this, this.deviceId, this.deviceModel); this.deregisterLogic.Init(this, this.deviceId, this.deviceModel); this.disconnectLogic.Init(this, this.deviceId, this.deviceModel); this.actorLogger.Init(deviceId, "Connection"); this.status = ActorStatus.ReadyToStart; this.instance.InitComplete(); }
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"); } }
/// <summary> /// Applies device impact on the circuit equation system. If behavior of the device is nonlinear, this method is /// called once every Newton-Raphson iteration. /// </summary> /// <param name="context">Context of current simulation.</param> public override void ApplyModelValues(ISimulationContext context) { foreach (var model in devices) { model.ApplyModelValues(context); } }
public SimulationManager( ISimulationContext simulationContext, IDevicePartitions devicePartitions, IClusterNodes clusterNodes, IDeviceModels deviceModels, IFactory factory, IClusteringConfig clusteringConfig, ILogger logger, IInstance instance, ISimulationStatistics simulationStatistics, ISimulations simulations) { this.simulationContext = simulationContext; this.devicePartitions = devicePartitions; this.clusterNodes = clusterNodes; this.deviceModels = deviceModels; this.simulationStatistics = simulationStatistics; this.factory = factory; this.log = logger; this.instance = instance; this.maxDevicePerNode = clusteringConfig.MaxDevicesPerNode; this.simulations = simulations; this.assignedPartitions = new ConcurrentDictionary <string, DevicesPartition>(); this.nodeCount = 1; this.deviceCount = 0; }
public void Init( ISimulationContext simulationContext, string deviceId, DeviceModel deviceModel, int deviceCounter) { // TODO: will be implemented when SimulationManager is integrated }
public void Init( ISimulationContext simulationContext, string deviceId, DeviceModel deviceModel, IDeviceStateActor deviceStateActor, ConnectionLoopSettings loopSettings) { // TODO: will be implemented when SimulationManager is integrated. }
/// <summary> /// Notifies model class that DC bias for given timepoint is established (i.e after Newton-Raphson iterations /// converged). /// </summary> /// <param name="context">Context of current simulation.</param> public override void OnDcBiasEstablished(ISimulationContext context) { base.OnDcBiasEstablished(context); foreach (var model in devices) { model.OnDcBiasEstablished(context); } }
public void Init(IDeviceConnectionActor context, string deviceId, DeviceModel deviceModel) { this.instance.InitOnce(); this.deviceContext = context; this.simulationContext = context.SimulationContext; this.deviceId = deviceId; this.instance.InitComplete(); }
/// <summary> /// получить пакет "сырых" входных данных из входных файлов /// </summary> public ISimulationContext GetSimulationContext(ConfigParams inputData, IConfigurationSection algorithmConfig = null) { ISimulationContext context = CreateContext(algorithmConfig); context.LoggerFactory = this.loggerFactory; context.InputParams = CreateBundle(inputData); //если в данном классе алгоритма есть настройки, загружаем их HandleOptions(context, algorithmConfig); return(context); }
/// <summary> /// Applies device impact on the circuit equation system. If behavior of the device is nonlinear, this method is /// called once every Newton-Raphson iteration. /// </summary> /// <param name="context">Context of current simulation.</param> public override void ApplyModelValues(ISimulationContext context) { if (firstDcPoint) // initial dc bias { stamper.StampInitialCondition(DefinitionDevice.InitialCurrent); } else { var(veq, req) = IntegrationMethod.GetEquivalents(DefinitionDevice.Inductance / context.TimeStep); stamper.Stamp(-veq, req); } }
/// <summary> /// Notifies model class that DC bias for given timepoint is established (i.e after Newton-Raphson iterations /// converged). /// </summary> /// <param name="context">Context of current simulation.</param> public override void OnDcBiasEstablished(ISimulationContext context) { base.OnDcBiasEstablished(context); ic = capacitorStamper.GetCurrent(); if (Math.Abs(context.TimeStep) < double.Epsilon) // set initial condition for the capacitor { ic = Current; } vc = Voltage; IntegrationMethod.SetState(ic, vc); initialConditionCapacitor = false; // capacitor no longer needs initial condition }
public override void OnEquationSolution(ISimulationContext context) { var newVoltage = voltage.GetValue(); var abstol = context.SimulationParameters.AbsoluteTolerance; var reltol = context.SimulationParameters.RelativeTolerance; // Check if converged if (!MathHelper.InTollerance(newVoltage, Voltage, abstol, reltol)) { context.ReportNotConverged(this); } // update voltage for reading Voltage = newVoltage; }
/// <summary> /// Invoke this method before calling Start(), to initialize the actor /// with details such as the device model and message type to simulate. /// If this method is not called before Run(), the application will /// throw an exception. /// Init() should be called only once, typically after the constructor. /// </summary> public void Init( ISimulationContext simulationContext, string deviceId, DeviceModel deviceModel, int deviceCounter) { this.instance.InitOnce(); this.simulationContext = simulationContext; this.deviceModel = deviceModel; this.deviceId = deviceId; // Distribute actors start over 10 secs this.startDelayMsecs = deviceCounter % START_DISTRIBUTION_WINDOW_MSECS; this.instance.InitComplete(); }
/// <summary> /// Notifies model class that DC bias for given timepoint is established (i.e after Newton-Raphson iterations /// converged). /// </summary> /// <param name="context">Context of current simulation.</param> public override void OnDcBiasEstablished(ISimulationContext context) { base.OnDcBiasEstablished(context); // update capacitances var vbe = voltageBe.GetValue(); chargebe.SetState(vbe * cgeqbe, vbe); var vbc = voltageBc.GetValue(); chargebc.SetState(vbc * cgeqbc, vbc); var vcs = voltageCs.GetValue(); chargecs.SetState(vcs * cgeqcs, vcs); }
public override void ApplyModelValues(ISimulationContext context) { var Is = DefinitionDevice.Param.SaturationCurrent; var Vt = DefinitionDevice.Param.ThermalVoltage; var n = DefinitionDevice.Param.IdealityCoefficient; var Vd = voltage.GetValue(); // calculates current through the diode and it's derivative DeviceHelpers.PnJunction(Is, Vd, Vt * n, out var Id, out var Geq); Current = Id; // stamp the equivalent circuit var Ieq = Id - Geq * Vd; conductanceStamper.Stamp(Geq); currentStamper.Stamp(Ieq); }
/// <summary>Performs necessary initialization of the device, like mapping to the equation system.</summary> /// <param name="adapter">The equation system builder.</param> /// <param name="context">Context of current simulation.</param> public override void Initialize(IEquationSystemAdapter adapter, ISimulationContext context) { stamper.Register(adapter, Anode, Cathode); capacitorStamper.Register(adapter, Anode, Cathode); voltage.Register(adapter, Anode, Cathode); initialConditionCapacitor = true; IntegrationMethod = context.SimulationParameters.IntegrationMethodFactory.CreateInstance(); vt = Parameters.EmissionCoefficient * PhysicalConstants.Boltzmann * PhysicalConstants.CelsiusToKelvin(Parameters.NominalTemperature) / PhysicalConstants.DevicearyCharge; var iS = Parameters.SaturationCurrent; var n = Parameters.EmissionCoefficient; Voltage = DefinitionDevice.VoltageHint ?? 0; }
/// <summary>This method is called each time an equation is solved.</summary> /// <param name="context">Context of current simulation.</param> public override void OnEquationSolution(ISimulationContext context) { var iS = Parameters.SaturationCurrent; var nF = Parameters.ForwardEmissionCoefficient; var nR = Parameters.ReverseEmissionCoefficient; var polarity = Parameters.IsPnp ? -1 : +1; // critical voltages to prevent numerical overflow var vbecrit = DeviceHelpers.PnCriticalVoltage(iS, nF * vT); var vbccrit = DeviceHelpers.PnCriticalVoltage(iS, nR * vT); var vvbe = voltageBe.GetValue() * polarity; var vvbc = voltageBc.GetValue() * polarity; var(vbe, limited) = DeviceHelpers.PnLimitVoltage(vvbe, VoltageBaseEmitter, nF * vT, vbecrit); var(vbc, limited2) = DeviceHelpers.PnLimitVoltage(vvbc, VoltageBaseCollector, nR * vT, vbccrit); // calculate current deltas var delvbe = vbe - VoltageBaseEmitter; var delvbc = vbc - VoltageBaseCollector; var cchat = CurrentCollector + (Transconductance + OutputConductance) * delvbe - (OutputConductance + ConductanceMu) * delvbc; var cbhat = CurrentBase + ConductancePi * delvbe + ConductanceMu * delvbc; var cc = CurrentCollector; var cb = CurrentBase; var reltol = context.SimulationParameters.RelativeTolerance; var abstol = context.SimulationParameters.AbsoluteTolerance; // request another iteration if not converged if (limited || limited2 || !MathHelper.InTollerance(cchat, cc, abstol, reltol) || !MathHelper.InTollerance(cbhat, cb, abstol, reltol)) { context.ReportNotConverged(this); } // update voltages VoltageBaseEmitter = vbe; VoltageBaseCollector = vbc; VoltageCollectorEmitter = vbc - vbe; }
/// <summary>This method is called each time an equation is solved.</summary> /// <param name="context">Context of current simulation.</param> public override void OnEquationSolution(ISimulationContext context) { var vcrit = DeviceHelpers.PnCriticalVoltage(Parameters.SaturationCurrent, vt); var(newvolt, limited) = DeviceHelpers.PnLimitVoltage(voltage.GetValue(), Voltage, vt, vcrit); var dVolt = newvolt - Voltage; var dCurr = Conductance * dVolt; var reltol = context.SimulationParameters.RelativeTolerance; var abstol = context.SimulationParameters.AbsoluteTolerance; if (limited || !MathHelper.InTollerance(Current, Current + dCurr, abstol, reltol)) { context.ReportNotConverged(this); } Voltage = newvolt; }
/// <summary> /// Invoke this method before calling Execute(), to initialize the actor /// with details like the device id. /// </summary> public void Init( ISimulationContext simulationContext, string deviceId, IDeviceStateActor deviceStateActor, IDeviceConnectionActor deviceConnectionActor, PropertiesLoopSettings loopSettings) { this.instance.InitOnce(); this.simulationContext = simulationContext; this.deviceId = deviceId; this.deviceStateActor = deviceStateActor; this.deviceConnectionActor = deviceConnectionActor; this.updatePropertiesLogic.Init(this, this.deviceId); this.actorLogger.Init(deviceId, "Properties"); this.status = ActorStatus.ReadyToStart; this.instance.InitComplete(); }
/// <summary> /// Applies device impact on the circuit equation system. If behavior of the device is nonlinear, this method is /// called once every Newton-Raphson iteration. /// </summary> /// <param name="context">Context of current simulation.</param> public override void ApplyModelValues(ISimulationContext context) { double ieq, geq; if (firtDcPoint) { if (DefinitionDevice.InitialVoltage.HasValue) { ieq = DefinitionDevice.InitialVoltage.Value; geq = 1; } else { ieq = geq = 0; // open circuit } } else { (ieq, geq) = IntegrationMethod.GetEquivalents(DefinitionDevice.Capacity / context.TimeStep); } stamper.Stamp(ieq, geq); }
/// <summary> /// Invoke this method before calling Execute(), to initialize the actor /// with details like the device model and message type to simulate. /// </summary> public void Init( ISimulationContext simulationContext, string deviceId, DeviceModel deviceModel, DeviceModel.DeviceModelMessage message, IDeviceStateActor deviceStateActor, IDeviceConnectionActor context) { this.instance.InitOnce(); this.simulationContext = simulationContext; this.deviceModel = deviceModel; this.Message = message; this.deviceId = deviceId; this.deviceStateActor = deviceStateActor; this.deviceContext = context; this.sendTelemetryLogic.Init(this, this.deviceId, this.deviceModel); this.actorLogger.Init(deviceId, "Telemetry"); this.status = ActorStatus.ReadyToStart; this.instance.InitComplete(); }
public void RunStrategy_IncorrectStrategy_ReturnsFalse(ISimulationContext sut, Mock<ISimulationContext> ctx) { ctx.Setup(x => x.RunStrategy()).Returns(false); sut.Initialize(null, null, null); Assert.False(sut.RunStrategy()); }
public void RunStrategy_CanceledAfterRun_ReturnsFalse(ISimulationContext sut, Mock<ISimulationContext> ctx) { ctx.Setup(x => x.RunStrategy()).Callback(() => Thread.Sleep(60000)).Returns(true); sut.Initialize(null, null, null); Task.Factory.StartNew(() => { Thread.Sleep(1000);(sut as SimulationContextAsyncDecorator).Cancel();}); bool result = sut.RunStrategy(); Assert.False(result); }
public void RunStrategy_CanceledBeforeRun_ReturnsFalse(ISimulationContext sut, Mock<ISimulationContext> ctx) { ctx.Setup(x => x.RunStrategy()).Returns(true); sut.Initialize(null, null, null); (sut as SimulationContextAsyncDecorator).Cancel(); Assert.False(sut.RunStrategy()); }
public void ApplyInteresetRate_IsCalledOnDecorated(ISimulationContext sut, Mock<ISimulationContext> ctx) { sut.ApplyInterestRate(); ctx.Verify(x => x.ApplyInterestRate(), Times.Once()); }
public void RunStrategy_IsCalledOnDecorated(ISimulationContext sut, Mock<ISimulationContext> ctx) { sut.Initialize(null, null, null); sut.RunStrategy(); ctx.Verify(x => x.RunStrategy(), Times.Once()); }
public void EndStep_IsCalledOnDecorated(ISimulationContext sut, Mock<ISimulationContext> ctx) { sut.EndStep(); ctx.Verify(x => x.EndStep(), Times.Once()); }
public void GetLastError_IsCalledOnDecorated(ISimulationContext sut, Mock<ISimulationContext> ctx) { sut.GetLastError(); ctx.Verify(x => x.GetLastError(), Times.Once()); }
public void ProcessPendingTransactions_IsCalledOnDecorated(ISimulationContext sut, Mock<ISimulationContext> ctx) { sut.ProcessPendingTransactions(); ctx.Verify(x => x.ProcessPendingTransactions(), Times.Once()); }
public void Dispose_IsCalledOnDecorated(ISimulationContext sut, Mock<ISimulationContext> ctx) { sut.Dispose(); ctx.Verify(x => x.Dispose(), Times.Once()); }