def TestChemostatSimple(): print "=== BEGIN: TestChemostatSimple ===" # Settings simulate = True #True - run simulation; False - plot an old results # Initialize simulation parameters solverParams = AttributeDict({'tFinal': 10., 'tPrint': 0.1}) # Initialize model parameters modelParams = AttributeDict({ 'updateProgress': lambda x, y: x, #:TRICKY: not used, 'm': 3.0, 'K': 3.7, 'S_in': 2.2, 'X_in': 0.0, 'gamma': 0.6, 'D_vals': np.array([[100, 1], [200, 0.5], [1e6, 1.1]]), 'S0': 0.0, 'X0': 0.5 }) # Create the model chemostat = ChemostatSimple(modelParams, initDataStorage=simulate) # Run simulation or load old results if (simulate == True): chemostat.prepareSimulation() chemostat.run(solverParams) else: chemostat.loadResult(simIndex=1) # Export to csv file chemostat.resultStorage.exportToCsv(fileName=csvFileName) # Plot results chemostat.plotHDFResults() print "=== END: TestChemostatSimple ==="
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.fluid = params.fluid self.fState = CP.FluidState(self.fluid) self.port1 = DMS.FluidPort('C', self.fState)
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.condModel = params.condModel self.port1 = DMS.ThermalPort('R') self.port2 = DMS.ThermalPort('R')
def create(self, heatExch=None, **kwargs): if heatExch == None: heatExch = AttributeDict(kwargs) #===== Create the gmsh script =====# # Geometry object IDs self.pointId = 1 self.circleArcId = 1 self.circleId = 1 #loop line self.planeSurfaceId = 1 # Initialize gmsh script self.sMesh = StringIO() # Add the outer block circle self.addCircle2D(radius=heatExch.blockGeom.diameter / 2.0, cellSize=heatExch.externalChannelGeom.cellSize, radialPosition=0, angularPosition=0, name="OuterBoundary") # Add the Primary channels self.addChannelGroup(heatExch.primaryChannelsGeom) self.addChannelGroup(heatExch.secondaryChannelsGeom) # Add the cross section surface self.addSurface(beginId=1, endId=self.circleId, name="CrossSection") # Get the gmsh script gmshScript = self.sMesh.getvalue() self.sMesh.close() #===== Generate the mesh =====# self.mesh = FP.Gmsh2D(gmshScript)
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.hConv = params.hConv #convectin coefficient self.A = params.A #convection area self.fluidPort = DMS.FluidPort('R') self.wallPort = DMS.ThermalPort('R')
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.fluid = params.fluid self.fState = CP.FluidState(self.fluid) self.TOutModel = lambda obj: params.TOut self.mDot = params.mDot self.flow = DMS.FluidFlow(mDot=self.mDot) self.port1 = DMS.FluidPort('R', self.flow)
def run(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) # Remember the final time self.tFinal = params.tFinal # Run simulation self.simSolver.simulate(tfinal=params.tFinal, ncp=np.floor(params.tFinal / params.tPrint)) self.resultStorage.finalizeResult()
def __init__(self, params = None, **kwargs): if params == None: params = AttributeDict(kwargs) self.V = params.V if (isinstance(params.fluid, CP.Fluid)): self.fluid = params.fluid else: self.fluid = CP.Fluid(params.fluid) self.fState = CP.FluidState(self.fluid) self.fluidPort = DMS.DynamicCPort(DMS.FluidPort, state = self.fState)
def run(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.solverParams = params # Set the simulation parameters self.dde.set_sim_params(tfinal=self.solverParams.tFinal, AbsTol=params.absTol, RelTol=params.relTol, dtmax=None) # Run the simulator self.dde.run()
def __init__(self, params=None, **kwargs): super(ChemostatSimple, self).__init__(**kwargs) if params == None: params = AttributeDict(kwargs) # Initialize update progress function self.updateProgress = params.updateProgress # Initialize parameters self.m = params.m self.K = params.K self.S_in = params.S_in self.X_in = params.X_in self.gamma = params.gamma self.D_vals = params.D_vals # Create state vector and derivative vector stateVarNames = ['S', 'X'] self.y = NamedStateVector(stateVarNames) self.yRes = NamedStateVector(stateVarNames) self.yDot = NamedStateVector(stateVarNames) # Initialize data storage self.resultStorage = ResultStorage(filePath=dataStorageFilePath, datasetPath=dataStorageDatasetPath) if (kwargs.get('initDataStorage', True)): self.resultStorage.initializeWriting(varList=['t'] + stateVarNames + ['D'], chunkSize=1e4) # Register time event (changed of D) D_val = self.D_vals[0] self.D = D_val[1] tChangedD = D_val[0] for i in range(len(self.D_vals) - 1): self.D_val = self.D_vals[i + 1] self.timeEventRegistry.add( ChemostatSimpleTimeEvent(t=tChangedD, newValue_D=self.D_val[1])) tChangedD += self.D_val[0] # Set initial values of the states self.y.S = params.S0 self.y.X = params.X0 # Set all the initial state values self.y0 = self.y.get(copy=True) # Set the initial flags self.sw0 = [True]
def setState(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.sourceType = params.sourceType if (self.sourceType == self.TP): self.T = params.T self.p = params.p elif (self.sourceType == self.PQ): self.p = params.p self.q = params.q elif (self.sourceType == self.TQ): self.T = params.T self.q = params.q
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.fluid = params.fluid #fluid self.etaS = params.etaS #isentropic efficiency self.fQ = params.fQ #fraction of heat loss to ambient self.V = params.V #displacement volume self.n = 0.0 #number of revolutions per second self.fStateOut = CP.FluidState(self.fluid) self.flow = DMS.FluidFlow() self.portOut = DMS.FluidPort('R', self.flow) self.portIn = DMS.FluidPort('R', -self.flow)
def addChannelGroup(self, channelGroup=None, **kwargs): if channelGroup == None: channelGroup = AttributeDict(kwargs) if (channelGroup.number <= 0): return offsetAngle = 2 * np.pi / channelGroup.number for i in range(int(channelGroup.number)): self.addCircle2D( radius=channelGroup.externalDiameter / 2., cellSize=channelGroup.cellSize, radialPosition=channelGroup.radialPosition, angularPosition=channelGroup.startingAngle + i * offsetAngle, name="{0}_{1}".format(channelGroup.channelName, i + 1), )
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.fluid = params.fluid self.fStateIn = CP.FluidState(self.fluid) self.fStateOut = CP.FluidState(self.fluid) self.fStateDown = CP.FluidState(self.fluid) self.fStateTmp = CP.FluidState(self.fluid) self.flowOut = DMS.FluidFlow() self.heatOut = DMS.HeatFlow() self.portIn = DMS.FluidPort('C', self.fStateDown) self.portOut = DMS.FluidPort('R', self.flowOut) self.thermalPort = DMS.ThermalPort('R', self.heatOut)
def TestChemostatDDE(): print "=== BEGIN: TestChemostatDDE ===" # Initialize simulation parameters solverParams = AttributeDict({ 'tFinal': 500., 'tPrint': 0.1, 'absTol': 1e-16, 'relTol': 1e-16, }) # Initialize model parameters class ModelParams( ): #:TRICKY: here it is also possible to use AttributeDict instead of class ModelParams k1 = 10.53 k2 = 28.6 k3 = 1074. s1_in = 7.5 s2_in = 75. a = 0.5 m1 = 1.2 m2 = 0.74 k_s1 = 7.1 k_s2 = 9.28 k_I = 16. D = 0.1 tau1 = 2 tau2 = 7 s1_hist_vals = 2. x1_hist_vals = 0.1 s2_hist_vals = 10. x2_hist_vals = 0.05 modelParams = ModelParams() chemostat = ChemostatDDE2(modelParams) chemostat.run(solverParams) chemostat.plotResults() #chemostat.plotX1X2() #chemostat.plotS1S2() #chemostat.plotS1X1() #chemostat.plotS2X2() print "=== END: TestChemostatDDE ==="
def __init__(self, params=None, **kwargs): """ #params.reactions = [reactionEquation, rateConstants] #params.species = [speciesVariable, initialValue] """ super(BiochemicalReactions, self).__init__(**kwargs) if params == None: params = AttributeDict(kwargs) # Initialize update progress function self.updateProgress = params.updateProgress # Get the species variables Xs = [X1, X2, ..., Xn] and their initial values self.Xs = np.empty(len(params.species), dtype=(np.str_, 256)) self.X0s = np.zeros(len(params.species)) for i, itSpecies in enumerate(params.species): self.Xs[i] = itSpecies[0] self.X0s[i] = itSpecies[1] # Get the reactions = [[left Xs, right Xs, k, ss, rs, f], ...], where: # left Xs - the species variables of reactants (i.e. the species variables of the left parts of the reactions) # rigth Xs - the species variables of products (i.e. the species variables of the right parts of the reactions) # k - the rate constant of the reaction # ss - the stoichiometric coefficients of reactants (e.g. [0,1,1,0,...,1]) # rs - the stoichiometric coefficients of products (e.g. [1,0,...,0]) # f - the fluxs (e.g. k*X2*X3*...*Xn) self.reactions = self.readReactions(params.reactions, self.Xs) #for reaction in self.reactions: print reaction # Create a vector with state variable names stateVarNames = list(self.Xs) # Initialize data storage self.resultStorage = ResultStorage(filePath=dataStorageFilePath, datasetPath=dataStorageDatasetPath) if (kwargs.get('initDataStorage', True)): self.resultStorage.initializeWriting(varList=['t'] + stateVarNames, chunkSize=1e4) # Set the initial state values self.y0 = self.X0s # Set the initial flags self.sw0 = [True]
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.state = params.initialState self.pTankInit = params.pTankInit self.inputs = self.Inputs() self.outputs = self.Outputs() self.parameters = self.Parameters(params) # :TRICKY: change the initial state of the controler if (self.pTankInit >= self.parameters.pMax and self.state == self.FUELING): self.state = self.EXTRACTION if (self.pTankInit <= self.parameters.pMin and self.state == self.EXTRACTION): self.state = self.FUELING self.executeEntryActions()
def run(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.solverParams = params # Initialize results self.initResults() # Run the main simulation mainSimStepIndex = -1 mainSimTimeRange = np.arange(0, self.solverParams.tFinal, self.solverParams.mainSimStep) for tMainSim in mainSimTimeRange: mainSimStepIndex += 1 # Run the current secondary simulation self.runSecSim(tMainSim) # Write secondary simulation results self.writeResultsSecSim(mainSimStepIndex)
def prepareSimulation(self, params=None): if params == None: params = AttributeDict({ 'absTol': 1e-6, 'relTol': 1e-6, }) #Define an explicit solver simSolver = CVode(self) #Create a CVode solver #Sets the parameters #simSolver.verbosity = LOUD simSolver.report_continuously = True simSolver.iter = 'Newton' #Default 'FixedPoint' simSolver.discr = 'BDF' #Default 'Adams' #simSolver.discr = 'Adams' simSolver.atol = [params.absTol] #Default 1e-6 simSolver.rtol = params.relTol #Default 1e-6 simSolver.problem_info['step_events'] = True # activates step events #simSolver.maxh = 1.0 simSolver.store_event_points = True self.simSolver = simSolver
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.params = params # Define the specific growth rates (in 'C' source code) self.support_c_code = """ double mu1(double s, double m, double k) { return (m*s)/(k + s); } double mu2(double s, double m, double k, double k_I) { return (m*s)/(k + s + (s/k_I)*(s/k_I)); } """ # Define the equations self.eqns = { 's1': 'D*(s1_in - s1) - k1*mu1(s1, m1, k_s1)*x1', 'x1': 'exp(-a*D*tau1)*mu1(s1(t-tau1), m1, k_s1)*x1(t-tau1) - a*D*x1', 's2': 'D*(s2_in - s2) + k2*mu1(s1, m1, k_s1)*x1 - k3*mu2(s2, m2, k_s2, k_I)*x2', 'x2': 'exp(-a*D*tau2)*mu2(s2(t-tau2), m2, k_s2, k_I)*x2(t-tau2) - a*D*x2' } # Initialize tauMax self.tauMax = np.max([ self.params.tau1, self.params.tau2 ]) + 1 #:TRICKY: give the solver more historical data # Compute equilibrium point self.equilibriumPoint = self.computeEquilibriumPoint() if plotEqulibriumValuesAtTheEnd: print "equilibrium point (s1, x1, s2, x2) = ", self.equilibriumPoint
def TestChemostatDDE(): print "=== BEGIN: TestChemostatDDE ===" # Initialize simulation parameters solverParams = AttributeDict({ 'tFinal': 5000.0, 'tPrint': 0.1, 'absTol': 1e-16, 'relTol': 1e-16, 'mainSimStep': 10. }) # Initialize model parameters class ModelParams( ): #:TRICKY: here it is also possible to use AttributeDict instead of class ModelParams k1 = 10.53 k2 = 28.6 k3 = 1074. k4 = 100. s1_in = 7.5 s2_in = 75. a = 0.5 m1 = 1.2 m2 = 0.74 k_s1 = 7.1 k_s2 = 9.28 k_I = 16. D = 0.1 tau1 = 2 tau2 = 7 s1_hist_vals = 2. x1_hist_vals = 0.1 s2_hist_vals = 10. x2_hist_vals = 0.05 DsQs_DMin = 0.0 DsQs_DMax = 1.0 DsQs_Step = 0.01 ESA_DMin = 0.22 ESA_DMax = 0.33 ESA_eps = 0.001 ESA_h = 0.025 ESA_eps_z = 0.01 modelParams = ModelParams() chemostat = ChemostatDDE2_ESA(modelParams) runESA = 0 if runESA: #run extremum seeking algorithm chemostat.runESA(solverParams) resESA = chemostat.getResultsESA() if resESA['QMaxIsFound']: print "QMax is found: (DMax, QMax) = (", resESA[ 'DMax'], ",", resESA['QMax'], ")." else: print "QMax is not found." chemostat.plotAllResults() chemostat.plotDsQs() else: #run simulation #chemostat.run(solverParams) #chemostat.plotAllResults() #chemostat.plotResults() #chemostat.plotX1X2() #chemostat.plotS1S2() #chemostat.plotS1X1() #chemostat.plotS2X2() chemostat.plotDsQs() print "=== END: TestChemostatDDE ==="
def create(params=None, **kwargs): if params == None: params = AttributeDict(kwargs) if params.cooler.workingState == 0: params.cooler.epsilon = 0. tankModel = TankModel( updateProgress=params.updateProgress, initDataStorage=True, controller=TankController( initialState=params.controller.initialState, pTankInit=params.tank.pInit, tWaitBeforeExtraction=params.controller.tWaitBeforeExtraction, tWaitBeforeFueling=params.controller.tWaitBeforeFueling, pMin=params.controller.pMin, pMax=params.controller.pMax, mDotExtr=params.controller.mDotExtr, hConvTankWaiting=params.tank.hConvInternalWaiting, hConvTankExtraction=params.tank.hConvInternalExtraction, hConvTankFueling=params.tank.hConvInternalFueling, nCompressor=params.controller.nCompressor, ), fuelingSource=AttributeDict( fluid=params.fluid, sourceType=params.fuelingSource.sourceType, T=params.fuelingSource.T, p=params.fuelingSource.p, q=params.fuelingSource.q, ), compressor=AttributeDict( fluid=params.fluid, etaS=params.compressor.etaS, fQ=params.compressor.fQ, V=params.compressor.V, ), cooler=AttributeDict( fluid=params.fluid, epsilon=params.cooler.epsilon, ), coolerTemperatureSource=AttributeDict(T=params.cooler.TCooler, ), tank=AttributeDict( fluid=params.fluid, V=params.tank.volume, TInit=params.tank.TInit, pInit=params.tank.pInit, ), tankInternalConvection=AttributeDict( A=params.tank.wallArea, hConv=100., #TRICKY: unused parameter ), liner=AttributeDict( material=params.tank.linerMaterial, thickness=params.tank.linerThickness, conductionArea=params.tank.wallArea, port1Type='C', port2Type='C', numMassSegments=2, TInit=params.tank.TInit, ), composite=AttributeDict(material=params.tank.compositeMaterial, thickness=params.tank.compositeThickness, conductionArea=params.tank.wallArea, port1Type='R', port2Type='C', numMassSegments=4, TInit=params.tank.TInit), tankExternalConvection=AttributeDict( A=params.tank.wallArea, hConv=params.tank.hConvExternal, ), ambientSource=AttributeDict( fluid=params.ambientFluid, sourceType=DM.FluidStateSource.TP, T=params.TAmbient, p=1.e5, ), extractionSink=AttributeDict( fluid=params.fluid, mDot=0.0, #TRICKY: unused parameter TOut=params.TAmbient, #TRICKY: unused parameter ), ) return tankModel
def __init__(self, params=None, **kwargs): super(TankModel, self).__init__(**kwargs) if params == None: params = AttributeDict(kwargs) # Initialize update progress function self.updateProgress = params.updateProgress # Create state vector and derivative vector stateVarNames = [ 'WRealCompressor', 'TTank', 'rhoTank', 'TLiner_1', 'TLiner_2', 'TComp_1', 'TComp_2', 'TComp_3', 'TComp_4' ] self.y = NamedStateVector(stateVarNames) self.yRes = NamedStateVector(stateVarNames) self.yDot = NamedStateVector(stateVarNames) # Initialize storage self.resultStorage = DMC.ResultStorage( filePath=dataStorageFilePath, datasetPath=dataStorageDatasetPath) if (kwargs.get('initDataStorage', True)): self.resultStorage.initializeWriting( varList=['t'] + stateVarNames + [ 'pTank', 'mTank', 'TCompressorOut', 'TCoolerOut', 'QDotCooler', 'QDotComp', 'mDotFueling' ], chunkSize=10000) # Fueling source self.fuelingSource = DM.FluidStateSource(params.fuelingSource) self.fuelingSource.initState(params.fuelingSource) # Compressor self.compressor = DM.Compressor(params.compressor) # Connect the compressor to the fluid source self.compressor.portIn.connect(self.fuelingSource.port1) # Cooler self.cooler = DM.FluidHeater(params.cooler) self.cooler.setEffectivnessModel(epsilon=params.cooler.epsilon) # Connect the cooler to the compressor self.cooler.portIn.connect(self.compressor.portOut) # Connect the cooler to the heater (i.e. temperature source) self.coolerTemperatureSource = DMS.ThermalPort( 'C', DMS.ThermalState(T=params.coolerTemperatureSource.T)) self.cooler.thermalPort.connect(self.coolerTemperatureSource) # Tank chamber self.tank = DM.FluidChamber(params.tank) self.tank.initialize(params.tank.TInit, params.tank.pInit) # Connect the tank to the cooler self.tank.fluidPort.connect(self.cooler.portOut) # Extraction sink self.extractionSink = DM.FlowSource(params.extractionSink) # Connect the extraction sink with the tank self.extractionSink.port1.connect(self.tank.fluidPort) # Tank convection component self.tankInternalConvection = DM.ConvectionHeatTransfer( params.tankInternalConvection) # Connect to the fluid in the tank self.tankInternalConvection.fluidPort.connect(self.tank.fluidPort) # Tank (Liner) self.liner = DM.SolidConductiveBody(params.liner) # Connect to the tank convection component self.tankInternalConvection.wallPort.connect(self.liner.port1) # Tank (composite) self.composite = DM.SolidConductiveBody(params.composite) # Connect the liner to the composite self.composite.port1.connect(self.liner.port2) # Ambient fluid component self.ambientSource = DM.FluidStateSource(params.ambientSource) self.ambientSource.initState(params.ambientSource) # Composite convection component self.tankExternalConvection = DM.ConvectionHeatTransfer( params.tankExternalConvection) # Connect the composite convection to the ambient fluid self.tankExternalConvection.fluidPort.connect(self.ambientSource.port1) # Connect the composite convection to the composite self.tankExternalConvection.wallPort.connect(self.composite.port2) # Controller self.controller = params.controller # Initialize the state variables self.y.WRealCompressor = 0. # [W] self.y.TLiner_1 = self.liner.T[0] self.y.TLiner_2 = self.liner.T[1] self.y.TComp_1 = self.composite.T[0] self.y.TComp_2 = self.composite.T[1] self.y.TComp_3 = self.composite.T[2] self.y.TComp_4 = self.composite.T[3] self.y.TTank = self.tank.fState.T self.y.rhoTank = self.tank.fState.rho # Set all the initial state values self.y0 = self.y.get(copy=True) # Set the initial flags self.sw0 = [True]
def testTankModel(): print "=== BEGIN: testTankModel ===" # Settings simulate = True #True - run simulation; False - plot an old results # Create the model tankModel = TankModelFactory.create( updateProgress=lambda x, y: x, #:TRICKY: not used fluid=CP.Fluid('ParaHydrogen'), ambientFluid=CP.Fluid('Air'), TAmbient=288.15, controller=AttributeDict( #initialState = TC.FUELING, initialState=TC.EXTRACTION, tWaitBeforeExtraction=150., tWaitBeforeFueling=150., pMin=20e5, pMax=300e5, mDotExtr=30 / 3600., nCompressor=0.53 * 1.44, ), fuelingSource=AttributeDict( sourceType=DM.FluidStateSource.PQ, T=15, #:TRICKY: unused p=2.7e5, q=0., ), compressor=AttributeDict( etaS=0.9, fQ=0., V=0.5e-3, ), cooler=AttributeDict( workingState=1., epsilon=1.0, TCooler=200, ), tank=AttributeDict( wallArea=1.8, volume=0.1, TInit=300., pInit=20e5, linerMaterial='Aluminium6061', linerThickness=0.004, compositeMaterial='CarbonFiberComposite', compositeThickness=0.0105, hConvExternal=100., hConvInternalWaiting=10., hConvInternalExtraction=20., hConvInternalFueling=100., ), ) # Run simulation or load old results if (simulate): tankModel.prepareSimulation() tankModel.run(tFinal=2000., tPrint=1.0) else: tankModel.loadResult(simIndex=1) # Export to csv file #tankModel.resultStorage.exportToCsv(fileName = csvFileName) # Plot results tankModel.plotHDFResults() print "=== END: testTankModel ==="
def runESA(self, solverParams=None, **kwargs): if solverParams == None: solverParams = AttributeDict(kwargs) self.solverParams = solverParams # Define helpful function def printStep(tMainSim, nextStep, D): print "\nAt time ", tMainSim, " do ", nextStep, " with D = ", D return # Initialize results self.initResults() # Initialize ESA variables QMaxIsFound = False eps = self.params.ESA_eps eps_z = self.params.ESA_eps_z h = self.params.ESA_h sigma = 1.0 # Stage I D0 = None Q0 = None D1 = None Q1 = None D2 = None Q2 = None D_minus = None D_plus = None # Stage II lmbd = (np.sqrt(5) - 1) / 2. dlt1 = None dlt2 = None dlt3 = None D0_minus = None D0_plus = None D1_minus = None D1_plus = None D_p0 = None Q_p0 = None D_q0 = None Q_q0 = None D_p1 = None Q_p1 = None D_q1 = None Q_q1 = None # Do Step I.0 of ESA self.params.D = (self.params.ESA_DMax + self.params.ESA_DMin) / 2. nextStep = 'Step I.0' # Run the main simulation D_prevStep = None mainSimStepIndex = -1 mainSimTimeRange = np.arange(0, self.solverParams.tFinal, self.solverParams.mainSimStep) for tMainSim in mainSimTimeRange: mainSimStepIndex += 1 # Run the secondary simulation self.runSecSim(tMainSim) # Write secondary simulation results and compute Qs self.writeResultsSecSim(mainSimStepIndex) # Check for stabilization of the system if (QMaxIsFound): continue # Compute equilibrium and current point if (D_prevStep is None) or (D_prevStep != self.params.D): D_prevStep = self.params.D eqPnt = self.computeEquilibriumPoint() #[_s1_eqPnt, _x1_eqPnt, s2_eqPnt, x2_eqPnt] = eqPnt #Q_eqPnt = self.computeQ(s2_eqPnt, x2_eqPnt) currPnt = self.currPnt [_s1_currPnt, _x1_currPnt, s2_currPnt, x2_currPnt] = currPnt Q_currPnt = self.computeQ(s2_currPnt, x2_currPnt) # Check for the equilibrium point if ( self.distance(eqPnt, currPnt) > eps_z ): #:TODO:(?) compare distance between previous point and currPnt (not between eqPnt and currPnt) # The equilibrium point is not reached continue # Do a step of ESA (i.e. the equilibrium point is reached) doStep = True if nextStep == 'Step I.0' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D0 = self.params.D Q0 = Q_currPnt # Go to nextStep = 'Step I.1' sigma = 1 self.params.D = D0 + sigma * h if nextStep == 'Step I.1' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D1 = self.params.D Q1 = Q_currPnt if Q1 > Q0: # Go to nextStep = 'Step I.3' h = 2 * h self.params.D = D1 + sigma * h else: # Go to nextStep = 'Step I.2' sigma = -1.0 self.params.D = D0 - sigma * h if nextStep == 'Step I.2' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D1 = self.params.D Q1 = Q_currPnt if Q1 > Q0: # Go to nextStep = 'Step I.3' h = 2 * h self.params.D = D1 + sigma * h else: h = h / 2. if h <= eps / 2.: # Go to nextStep = 'Step III' self.params.D = D0 else: # Go to nextStep = 'Step I.1' sigma = 1 self.params.D = D0 + sigma * h if nextStep == 'Step I.3' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D2 = self.params.D Q2 = Q_currPnt if Q2 <= Q1: D_minus = D0 D_plus = D2 # Go to nextStep = 'Step II' doStep = True else: D0 = D1 Q0 = Q1 D1 = D2 Q1 = Q2 # Go to nextStep = 'Step I.3' h = 2 * h self.params.D = D1 + sigma * h if nextStep == 'Step II' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D0_minus = D_minus D0_plus = D_plus print "Step II [D-, D+] = [", D0_minus, ", ", D0_plus, "]" dlt1 = D0_plus - D0_minus # Go to nextStep = 'Step II.0' doStep = True if nextStep == 'Step II.0' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False dlt2 = (1 - lmbd) * dlt1 D_p0 = D0_minus + dlt2 D_q0 = D0_plus - dlt2 # Go to nextStep = 'Step II.1.p0' self.params.D = D_p0 if nextStep == 'Step II.1.p0' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D_p0 = self.params.D Q_p0 = Q_currPnt # Go to nextStep = 'Step II.1.q0' self.params.D = D_q0 if nextStep == 'Step II.1.q0' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D_q0 = self.params.D Q_q0 = Q_currPnt # Go to nextStep = 'Step II.2' doStep = True if nextStep == 'Step II.2' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False dlt3 = D_q0 - D_p0 if Q_p0 > Q_q0: D1_minus = D0_minus D1_plus = D_q0 D_p1 = D1_minus + dlt3 D_q1 = D_p0 Q_q1 = Q_p0 #:TODO:(?) missing in pdf if Q_p0 <= Q_q0: D1_minus = D_p0 D1_plus = D0_plus D_p1 = D_q0 Q_p1 = Q_q0 #:TODO:(?) missing in pdf D_q1 = D1_plus - dlt3 dlt1 = D1_plus - D1_minus # Go to nextStep = 'Step II.3' doStep = True if nextStep == 'Step II.3' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False print "Step II.3 [D1-, D1+] = [", D1_minus, ", ", D1_plus, "]" if dlt1 <= eps: # Go to nextStep = 'Step III' self.params.D = (D1_minus + D1_plus) / 2. else: # if dlt1 > eps: if D_p1 >= D_q1: D0_minus = D1_minus D0_plus = D1_plus # Go to nextStep = 'Step II.0' doStep = True else: # if D_p1 < D_q1: if Q_p0 > Q_q0: # Go to nextStep = 'Step II.3.p1' self.params.D = D_p1 else: # if Q_p0 >= Q_q0: # Go to nextStep = 'Step II.3.q1' self.params.D = D_q1 if nextStep == 'Step II.3.p1' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D_p1 = self.params.D Q_p1 = Q_currPnt # Go to nextStep = 'Step II.3.1' doStep = True if nextStep == 'Step II.3.q1' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D_q1 = self.params.D Q_q1 = Q_currPnt # Go to nextStep = 'Step II.3.1' doStep = True if nextStep == 'Step II.3.1' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False D_p0 = D_p1 D_q0 = D_q1 D0_minus = D1_minus D0_plus = D1_plus Q_p0 = Q_p1 Q_q0 = Q_q1 # Go to nextStep = 'Step II.2' doStep = True if nextStep == 'Step III' and doStep: printStep(tMainSim, nextStep, self.params.D) doStep = False QMaxIsFound = True # Set the ESA result self.ResESA_QMaxIsFound = QMaxIsFound self.ResESA_QMax = Q_currPnt self.ResESA_DMax = self.params.D #:TRICKY: limit the current seeking D value if self.params.D < self.params.ESA_DMin: self.params.D = self.params.ESA_DMin if self.params.D > self.params.ESA_DMax: self.params.D = self.params.ESA_DMax
def initState(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) self.setState(params) self.compute()
def __init__(self, params = None, **kwargs): if params == None: params = AttributeDict(kwargs) self.params = params #Calculate the equilibrium point def mu1(s, m, k): return (m*s)/(k + s) def mu2(s, m, k, k_I): return (m*s)/(k + s + (s/k_I)*(s/k_I)) def eq_s1(s1, *args): (_k1, _k2, _k3, _s1_in, _s2_in, a, m1, _m2, k_s1, _k_s2, _k_I, D, _tau1, _tau2) = args return a*D - mu1(s1, m1, k_s1) def eq_s2(s2, *args): (_k1, _k2, _k3, _s1_in, _s2_in, a, _m1, m2, _k_s1, k_s2, k_I, D, _tau1, _tau2) = args return a*D - mu2(s2, m2, k_s2, k_I) eqs_args = ( params.k1, params.k2, params.k3, params.s1_in, params.s2_in, params.a, params.m1, params.m2, params.k_s1, params.k_s2, params.k_I, params.D, params.tau1, params.tau2) s1_eqpnt = fsolve(eq_s1, 1.0, args = eqs_args)[0] x1_eqpnt = (params.s1_in - s1_eqpnt)/(params.a*params.k1) if x1_eqpnt < 0: s1_eqpnt = params.s1_in x1_eqpnt = 0.0 s2_eqpnt_sol, _info, ier, _msg = fsolve(eq_s2, 1.0, args = eqs_args, full_output = True) if ier != 1 or s2_eqpnt_sol[0] < 0: x2_eqpnt = 0.0 s2_eqpnt = params.s2_in + params.k2*mu1(s1_eqpnt, params.m1, params.k_s1) * x1_eqpnt / params.D else: s2_eqpnt = s2_eqpnt_sol[0] x2_eqpnt = ((params.s2_in - s2_eqpnt)*params.D + params.k2*mu1(s1_eqpnt, params.m1, params.k_s1)*x1_eqpnt) \ / (params.k3 * mu2(s2_eqpnt, params.m2, params.k_s2, params.k_I)) self.equilibriumPoint = [s1_eqpnt, x1_eqpnt, s2_eqpnt, x2_eqpnt] if plotEqulibriumValuesAtTheEnd: print "equilibrium point (s1, x1, s2, x2) = ", self.equilibriumPoint # Define the specific growth rates (in 'C' source code) support_c_code = """ double mu1(double s, double m, double k) { return (m*s)/(k + s); } double mu2(double s, double m, double k, double k_I) { return (m*s)/(k + s + (s/k_I)*(s/k_I)); } """ # Define the equations eqns = { 's1': 'D*(s1_in - s1) - k1*mu1(s1, m1, k_s1)*x1', 'x1': 'mu1(s1(t-tau1), m1, k_s1)*x1(t-tau1) - a*D*x1', 's2': 'D*(s2_in - s2) + k2*mu1(s1, m1, k_s1)*x1 - k3*mu2(s2, m2, k_s2, k_I)*x2', 'x2': 'mu2(s2(t-tau2), m2, k_s2, k_I)*x2(t-tau2) - a*D*x2' } # Define the parameters eqns_params = { 'k1' : params.k1, 'k2' : params.k2, 'k3' : params.k3, 's1_in' : params.s1_in, 's2_in' : params.s2_in, 'a' : params.a, 'm1' : params.m1, 'm2' : params.m2, 'k_s1' : params.k_s1, 'k_s2' : params.k_s2, 'k_I' : params.k_I, 'D' : params.D, 'tau1' : params.tau1, 'tau2' : params.tau2, } # Initialize the solver self.dde = dde23(eqns=eqns, params=eqns_params, supportcode=support_c_code) # Set the initial conditions (i.e. set the history of the state variables) histfunc = { 's1': lambda t: params.s1_hist_vals, 'x1': lambda t: params.x1_hist_vals, 's2': lambda t: params.s2_hist_vals, 'x2': lambda t: params.x2_hist_vals } self.dde.hist_from_funcs(histfunc, 10.) #:TRICKY: 10. is 'nn' - sample in the interval
def TestADM1H2CH4Bioreactor(): print "=== BEGIN: TestADM1H2CH4Bioreactor ===" # Settings simulate = True #True - run simulation; False - plot an old results # Initialize simulation parameters solverParams = AttributeDict({ 'tFinal': 50., 'tPrint': .1, 'absTol': 1e-9, 'relTol': 1e-7, }) # Initialize model parameters # Validation of prameters #f_su_li + f_fa_li <= 1.0 #f_ch_xc + f_pr_xc + f_li_xc + [f_xI_xc + f_sI_xc] = 1.0 #[f_bu_su + f_pro_su] + f_ac_su + f_h2_su = 1.0 #[f_va_aa + f_bu_aa + f_pro_aa] + f_ac_aa + f_h2_aa = 1.0 #Y_xx < = 1.0 class ModelParamsRH2: #Stoichiometric parameter values f_ch_xc = 0.2 #- f_pr_xc = 0.2 #- f_li_xc = 0.3 #- f_su_li = 0.05 #- f_fa_li = 0.90 #- f_ac_su = 0.41 #- f_ac_aa = 0.4 #- Y_suaa = 0.1 #- Y_fa = 0.06 #- #Biochemical parameter values k_dis = 0.5 #1/day k_hyd_ch = 10.0 #1/day k_hyd_pr = 10.0 #1/day k_hyd_li = 10.0 #1/day k_m_suaa = 30.0 #1/day K_S_suaa = 0.5 #g/L k_m_fa = 6.0 #1/day K_S_fa = 0.4 #g/L #kLa_h2 = 200 #1/day Y_h2_su = 1.0 #- Y_h2_aa = 1.0 #- Y_h2_fa = 1.0 #- # Controller - D = q/V D_liq_arr = np.array([[10., 1.], [20., 2.]]) #[day, 1/day] (liquid) modelParamsRH2 = ModelParamsRH2() class ModelConcentrsRH2: # Input concentrations S_su_in = 0 * 0.01 #gCOD/L S_aa_in = 0 * 0.001 #gCOD/L S_fa_in = 0 * 0.001 #gCOD/L S_ac_in = 0 * 0.001 #gCOD/L X_c_in = 2.0 #gCOD/L X_ch_in = 5.0 #gCOD/L X_pr_in = 20.0 #gCOD/L X_li_in = 5.0 #gCOD/L X_suaa_in = 0 * 0.01 #g/L X_fa_in = 0 * 0.01 #g/L # Initial values of state variables S_su_0 = 0.01 #gCOD/L S_aa_0 = 0.001 #gCOD/L S_fa_0 = 0.001 #gCOD/L S_ac_0 = 0.001 #gCOD/L X_c_0 = 2.0 #gCOD/L X_ch_0 = 5.0 #gCOD/L X_pr_0 = 20.0 #gCOD/L X_li_0 = 5.0 #gCOD/L X_suaa_0 = 0.01 #g/L X_fa_0 = 0.01 #g/L modelConcentrsRH2 = ModelConcentrsRH2() webModel = AttributeDict({ 'updateProgress': lambda x, y: x, #:TRICKY: not used, }) class ModelParamsRCH4: #Stoichiometric parameter values Y_ac = 0.05 #- #Biochemical parameter values k_m_ac = 8.0 #1/day K_S_ac = 0.15 #g/L Y_ch4_ac = 1.0 #- # Physical parameters V_liq_RCH4_del_V_liq_RH2 = 5. modelParamsRCH4 = ModelParamsRCH4() class ModelConcentrsRCH4: # Input concentrations X_ac_in = 0 * 0.01 #g/L # Initial values of state variables S_ac_0 = 0.2 #gCOD/L X_ac_0 = 0.76 #g/L modelConcentrsRCH4 = ModelConcentrsRCH4() # Create the model bioreactor = ADM1H2CH4Bioreactors(webModel=webModel, paramsRH2=modelParamsRH2, concentrsRH2=modelConcentrsRH2, paramsRCH4=modelParamsRCH4, concentrsRCH4=modelConcentrsRCH4, initDataStorage=simulate) # Run simulation or load old results if (simulate == True): bioreactor.prepareSimulation(solverParams) bioreactor.run(solverParams) else: bioreactor.loadResult(simIndex=1) # Export to csv file bioreactor.resultStorage.exportToCsv(fileName=csvFileName) # Plot results bioreactor.plotHDFResults() print "=== END: TestADM1H2Bioreactor ==="
def __init__(self, params=None, **kwargs): if params == None: params = AttributeDict(kwargs) # Set the material if (isinstance(params.material, basestring)): self.material = Solids[params.material] elif (isinstance(params.material, dict)): self.material = params.material # Thermal conductivity params if ('thermalCond_T' in self.material): self.thermCondModel = Interpolator1D( xValues=self.material['thermalCond_T']['T'], yValues=self.material['thermalCond_T']['cond']) else: raise ValueError( "The material '{}' does not define a thermal conductivity params" .format(self.material.name)) # Heat capacity params if ('heatCapacity_T' in self.material): self.cpModel = Interpolator1D( xValues=self.material['heatCapacity_T']['T'], yValues=self.material['heatCapacity_T']['cp']) else: raise ValueError( "The material '{}' does not define a thermal conductivity params" .format(self.material.name)) # Mass if hasattr(params, 'mass'): self.mass = params.mass else: rho = self.material['refValues']['density'] V = params.thickness * params.conductionArea self.mass = rho * V self.numMassSegments = params.numMassSegments self.segmentMass = self.mass / self.numMassSegments self.cp = np.zeros(self.numMassSegments) self.T = np.ones(self.numMassSegments) * params.TInit self.TDot = np.zeros(self.numMassSegments) # Conductions and end handling self.thickness = params.thickness self.numConductiveSegments = self.numMassSegments - 1 if (params.port1Type in ['C', 'R']): if (params.port1Type == 'R'): self.numConductiveSegments += 1 else: raise ValueError( "port1Type must be 'R' or 'C', value given is '{}'".format( params.port1Type)) if (params.port2Type in ['C', 'R']): if (params.port2Type == 'R'): self.numConductiveSegments += 1 else: raise ValueError( "port2Type must be 'R' or 'C', value given is '{}'".format( params.port2Type)) if (self.numConductiveSegments > 0): self.segmentThickness = self.thickness / self.numConductiveSegments self.conductionArea = params.conductionArea self.cond = np.zeros(self.numConductiveSegments) self.QDot = np.zeros(self.numConductiveSegments) # Set up the port valriables if (params.port1Type == 'C'): self.port1 = DMS.ThermalPort(params.port1Type, DMS.ThermalState()) else: self.port1 = DMS.ThermalPort(params.port1Type) if (params.port2Type == 'C'): self.port2 = DMS.ThermalPort(params.port2Type, DMS.ThermalState()) else: self.port2 = DMS.ThermalPort(params.port2Type)
def TestBiochemicalReactions(): print "=== BEGIN: TestBiochemicalReactions ===" # Settings simulate = True #True - run simulation; False - plot an old results # Initialize simulation parameters solverParams = AttributeDict({ 'tFinal': 20., 'tPrint': 0.01, }) # Initialize model parameters dt = np.dtype([('reactionEquation', np.str_, 256), ('rateConstants', np.str_, 256)]) reactions = np.array([ ("E + S = ES", "2., 1."), ("ES -> E + P", "1.5"), ], dtype=dt) dt_vars = np.dtype([('speciesVariable', np.str_, 256), ('initialValue', np.float64, (1))]) species = np.array([ ('E', 4.), ('S', 8.), ('ES', 0.0), ('P', 0.0), ], dtype=dt_vars) modelParams = AttributeDict({ 'updateProgress': lambda x, y: x, #:TRICKY: not used, 'reactions': reactions, 'species': species, }) # Create the model model = BiochemicalReactions(modelParams) print model.getODEsTxt() fig = plt.figure() ax = fig.add_subplot(111) model.plotODEsTxt(ax) # Run simulation or load old results if (simulate == True): model.prepareSimulation() model.run(solverParams) else: model.loadResult(simIndex=1) # Export to csv file #model.resultStorage.exportToCsv(fileName = csvFileName) # Plot results fig = plt.figure() ax = fig.add_subplot(111) model.plotHDFResults(ax) print "=== END: TestBiochemicalReactions ==="