def calculate_gains(elementModel, saveDir): global FMUMODEL global inputGain global displayGain if not autoScale: inputGain = inputGain displayGain = displayGain else: rmoveSteps = int(rmoveTime/stepTime) maxMove = 0 for frameNum in range(len(r_hist) - rmoveSteps): currentMove = abs(r_hist[frameNum + rmoveSteps] - r_hist[frameNum]) maxMove = max([maxMove, currentMove]) displayGain = pixelDist/maxMove # maximum distance reference signal can move in rmoveTime [sec] is pixelDist resultsFile = os.path.join(saveDir, elementModel.replace('.', '_') + '_step_results.txt') fmuOpts = fmi.set_fmu_options(False, resultsFile, stepTime, solverName='CVode') fmuInput = numpy.transpose(numpy.vstack(([0,ymoveTime], [1,1]))) # step input (FMUMODEL, fmuResults) = fmi.simulate_fmu(FMUMODEL, fmuOpts, 0, ymoveTime, controlInput=(['u'], fmuInput)) ymoveDist = fmuResults['y'][-1] # distance moved by controlled element when step input is applied for ymoveTime unitDist = pixelDist/displayGain inputGain = unitDist/ymoveDist # controlled element can move unitDist [scaled pixels] in time ymoveTime [sec] # Reset and reinitialize the controlled element FMU (otherwise the controlled element starts with a nonzero initial condition) FMUMODEL.reset() FMUMODEL.initialize()
def update_cursor_position(frameIn): global FMUMODEL global u_hist global y_hist currentFrame = frameIn nextFrame = currentFrame + 1 # Get input signal t_input = t_hist[currentFrame:nextFrame] u_input = u_hist[currentFrame:nextFrame][0] + w_hist[currentFrame:nextFrame][0] fmuInput = numpy.transpose(numpy.vstack((t_input, u_input))) # Simulate the model response to input (FMUMODEL, fmuResults) = fmi.simulate_fmu(FMUMODEL, fmuOpts, t_hist[currentFrame], t_hist[nextFrame], controlInput=(['u'], fmuInput)) # Extract simulation results y_hist[nextFrame] = fmuResults['y'][-1]
def generate_fmu_signal(modelicaModel, modelicaFile, t_hist, paramDict, fmuMaxh, saveDir, odeSolver, printVerbose=False): assert t_hist[0] == 0, "Time values must start at t=0." fmuName = os.path.join(os.environ['MANTRA_TEMP'], modelicaModel.replace('.', '_')+'.fmu') logFile = os.path.join(saveDir, modelicaModel.replace('.', '_') + '_log.txt') resultFile = os.path.join(saveDir, modelicaModel.replace('.', '_') + '_results.txt') if not os.path.isfile(fmuName): fmuName = fmi.compile_fmu_openmodelica(modelicaModel, modelicaFile, saveDir, printVerbose=printVerbose) FMUMODEL = fmi.load_fmu_pyfmi(fmuName, logFile, printVerbose=printVerbose) # Overwrite default parameter values for oneKey in paramDict.keys(): FMUMODEL.set(oneKey, paramDict[oneKey]) fmuOpts = fmi.set_fmu_options(False, resultFile, fmuMaxh, solverName=odeSolver) FMUMODEL.initialize() (FMUMODEL, fmuResults) = fmi.simulate_fmu(FMUMODEL, fmuOpts, 0, t_hist[-1], printVerbose=printVerbose) t_sig = fmuResults['time'] y_sig = fmuResults['y'] signalOut = numpy.interp(t_hist, t_sig, y_sig) return signalOut