def run_ModelicaSystem():
    '''Create a ``ModelicaSystem`` object which provides functions to
    load, configure and simulate a model. Plotting is done with Python.

    For this example, we run the simulations for different heights 'h' from
    where the bouncing ball is dropped.
    '''

    # Setup the Modelica session and load the module
    omc = OMCSessionZMQ()
    model_path = (omc.sendExpression('getInstallationDirectoryPath()')
                  + '/share/doc/omc/testmodels/')
    mod = ModelicaSystem(model_path + 'BouncingBall.mo', 'BouncingBall')
    # Set some simulation options
    mod.setSimulationOptions(stepSize=.05, stopTime=2.0)

    # Print some useful information
    quant = pd.DataFrame(mod.getQuantities())
    print(quant)

    # Modify and run simulations
    for h_start in [1, 2, 3]:
        mod.setContinuous(h=h_start)  # `h` is a `continuous` variable
        mod.simulate()
        time, h = mod.getSolutions('time', 'h')

        plt.plot(time, h, label='h_start = {0} m'.format(h_start))

    plt.legend()
    plt.xlabel(r'time $t$ in [s]')
    plt.ylabel(r'height $h$ in [m]')
    plt.show(block=False)
Beispiel #2
0
    def simulate(self, ds_test: TestDataSet):

        omc = OMCSessionZMQ()
        # path = inspect.getfile(omc.__class__)

        mod = ModelicaSystem(sep.join([self.path_model, "package.mo"]),
                             "Steps.Test.TestPCHXMeshram", ["Modelica 3.2.1"])
        # options for simulation - steady state simulation, no iteration required, so set numberOfIntervals = 2
        mod.setSimulationOptions('stepSize  = 0.2')

        for test in ds_test:
            cfg = test.cfg
            print('prepare to simulate:' + cfg.full_name)
            mod.setParameters(test.gen_sim_param())

            mod.simulate()

            print('simulation {0} done, retrieving result'.format(
                cfg.full_name))
            result = test.result

            # collect data in solutions
            for sol_key in result:
                sol = mod.getSolutions(sol_key)
                if not sol is None:
                    result.set_result(sol_key, sol)
                else:
                    print("solution with key = {0} not exsits".format(sol_key))

            # result.update_cal_columns()

        print('all simulation(s) done, save result next')

        self.save_results(ds_test)
Beispiel #3
0
def run_ModelicaSystem():
    """Create a ``ModelicaSystem`` object and run the simulation."""
    # Create a subdirectory for the simulation
    sim_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           'sim_'+sys.platform)  # separate windows and linux

    # Define some paths
    file = os.path.abspath(
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     '../modelica/Q100_DistrictModel/package.mo'))
    model = 'Q100_DistrictModel.FMUs.FMU_PhyModel'
    input_path = os.path.join(os.path.dirname(os.path.abspath(file)), 'input/')

    # Change to a simulation directory
    if os.path.exists(sim_dir) is False:
        os.mkdir(sim_dir)
    os.chdir(sim_dir)

    # Setup the Modelica session and load the module, use "new frontend"
    mod = ModelicaSystem(fileName=file.replace("\\", "/"),
                         modelName=model,
                         commandLineOptions='-d=newInst')

    # Adapt the path of all the input files
    # cmd = '''setComponentModifierValue(
    #          Q100_DistrictModel.Simulations.SIM_RI_Schema,
    #          inputData.Pfad,
    #          $Code(="{}"))'''.format(input_path.replace("\\", "/"))
    # mod.sendExpression(cmd)

    # Rebuild the model afterwards, for the changes to take effect
    mod.buildModel()

    try:
        mod.setSimulationOptions(["stopTime=86400", "stepSize=900"])
    except Exception:
        mod.setSimulationOptions(stopTime=86400, stepSize=900)

    # Run simulations
    mod.simulate()

    solution_list = ['time', 'heatStorageVariablePorts_central.Heat_loss']
    solution_data = mod.getSolutions(solution_list)

    # Create DataFrame from results
    data = pd.DataFrame(data=solution_data.T, columns=solution_list)
    print(data)

    # Evaluate some variable just to see if the simulation finished:
    condition = data['heatStorageVariablePorts_central.Heat_loss'].mean() < 0
    return condition
def run_ModelicaSystem():
    """Create a ``ModelicaSystem`` object and run a simulation.

    For this example, we run the simulations for different heights 'h' from
    where the bouncing ball is dropped. Plotting is done with Python.

    """
    # Setup the Modelica session and load the module
    omc = OMCSessionZMQ()
    model_path = (omc.sendExpression('getInstallationDirectoryPath()') +
                  '/share/doc/omc/testmodels/')
    mod = ModelicaSystem(model_path + 'BouncingBall.mo',
                         'BouncingBall',
                         commandLineOptions='-d=newInst')

    # Set some simulation options
    stepSize = 0.05
    stopTime = 2.0

    text = ["stepSize={}".format(stepSize), "stopTime={}".format(stopTime)]
    mod.setSimulationOptions(text)

    # Print some useful information
    quantities = pd.DataFrame(mod.getQuantities())
    print(quantities)

    # Modify and run simulations
    for h_start in [1, 2, 3]:
        # `h` is a `continuous` variable
        mod.setContinuous("h={}".format(h_start))
        mod.simulate()  # Run the actual simulation

        solution_list = ['time', 'h']
        solution_data = mod.getSolutions(solution_list)  # read solutions
        df = pd.DataFrame(data=solution_data.T, columns=solution_list)

        plt.plot(df.time, df.h, label='h_start = {0} m'.format(h_start))

    plt.legend()
    plt.xlabel(r'time $t$ in [s]')
    plt.ylabel(r'height $h$ in [m]')
    plt.show(block=False)
# перший спосіб - використання OMCSession:
omc = OMCSession()
omc.sendExpression('loadFile("Simple.mo")')
omc.sendExpression('setParameterValue(Simple, a, 2)')
omc.sendExpression('simulate(Simple)')
omc.sendExpression('plot(x)')
print omc.sendExpression('val(x , 1.0)') # результат x(time=1.0)

# або більш зручний спосіб:
mod=ModelicaSystem("Simple.mo","Simple")
print mod.getParameters()
mod.setParameters(a=2)
mod.setSimulationOptions(stopTime=2.0)
mod.simulate()
print mod.getSolutions('time','x') # результати як масиви

# або компілювати модель і симулювати без OMPython:
omc.sendExpression('buildModel(Simple)') # компілювати
os.environ["PATH"] += os.pathsep + r"e:\OpenModelica\bin" # шлях до dll
param='''outputFormat=csv
stopTime=2
a={}
''' # значення параметрів
for i,p in enumerate([1, 2, 3]): # для кожного значення
    with open('override%d.txt'%i, 'w') as f: f.write(param.format(p)) # створити файл зі значеннями параметрів
    os.system(r'Simple.exe -overrideFile=override%d.txt -r=Simple_%d.csv'%(i,i)) # симуляція
"""
    7.38908993012
    {'a': 1.0}
    (array([0., 0.002, 0.004, ..., 1.998, 2., 2.]), array([1., 1.00400801, 1.0080321, ..., 54.38076352, 54.59872293, 54.59872293]))
Beispiel #6
0
def run_ModelicaSystem(fileName,
                       modelName,
                       solutions,
                       stepSize=1,
                       stopTime=60,
                       parameters=dict(),
                       list_models=[],
                       make_FMU=False,
                       HP_dict=dict()):
    """Run the simulation with OpenModelica.

    Create a ``ModelicaSystem`` object which provides functions to
    load, configure and simulate a model.

    Args:
        fileName (str): Name (including path) of a *.mo file with the model

        modelName (str): Name of the model

        solutions (dict): Dict of all solutions (column names) to load
        from the results

        stepSize (int): Simulation step in seconds

        stopTime (int): Simulation lenth in seconds

        parameters (dict): Key, value pairs handed to ``setParameters()``

        list_models (list): List of file paths to additional *.mo that need
        to be loaded

        make_FMU (boolean): Should we create an FMU from the model?

        HP_dict (dict): Dict with settings for replacing the simulated heatpump

    Returns:
        data (DataFrame): Pandas DataFrame with the requested ``solutions``

    .. note::
        OMPython changed the input style for ``setSimulationOptions()``,
        ``setParameters()``, etc. dramatically after v3.1.2.
        As of 2019-12-04 this script requires the latest version from
        https://github.com/OpenModelica/OMPython

    """
    from OMPython import ModelicaSystem  # import only if necessary

    # If we want to simulate with some other than the default heatpump,
    # we have to include the record database for that heatpump.
    # For this, we need to load the *.mo file of that database into
    # the ModelicaSystem, via the argument ``lmodel``.
    if HP_dict.get('path', False):
        # Add to the list of additionally loaded modules
        list_models.append(HP_dict['path'].replace("\\", "/"))

    # Setup the Modelica session and load the module
    mod = ModelicaSystem(fileName=fileName,
                         modelName=modelName,
                         lmodel=list_models)

    if HP_dict.get('replace_expressions', False):
        # This part is tricky! If we want to change the heat pump that is
        # used in the simulation, we cannot simply use setParameters(),
        # because we are replacing the reference to a "record".
        # Instead we have to modify the component value directly...
        for expression in HP_dict['replace_expressions']:
            answer = mod.sendExpression(expression)
            logger.debug(expression)
            logger.debug(answer)
        # ... and re-build the model afterwards, for the changes to take effect
        mod.buildModel()

    # Set some simulation options (valid until v3.1.2)
#    mod.setSimulationOptions(stepSize=stepSize, stopTime=stopTime)

# Attention! For the current master branch of OMPython, we need the
# following style (https://github.com/OpenModelica/OMPython)
    text = ["stepSize={}".format(stepSize), "stopTime={}".format(stopTime)]
    mod.setSimulationOptions(text)  # current master branch of OMPython

    # Print some useful information
    quantities = pd.DataFrame(mod.getQuantities())

    # Use this code snippet to find out of which kind (parameter, continuous)
    # a given quantity is:
    search_str = None
    if search_str is not None:
        mask = [search_str in quantity for quantity in quantities['name']]
        logger.debug('Results for "{}":'.format(search_str))
        if logger.isEnabledFor(logging.DEBUG):
            print(quantities[mask].to_string())

    # Set simulation parameters
    text = ["{}={}".format(key, value) for (key, value) in parameters.items()]
    mod.setParameters(text)  # current master branch of OMPython
    #    mod.setParameters(**parameters)  # Until v3.1.2

    # Run simulations
    mod.simulate()

    # Get list of simulation variables for which results are available
    solution_vars = mod.getSolutions()

    # List required evaluation values:
    solution_list = ['time']
    for items in solutions.values():
        for item in items:
            if item not in solution_vars:
                logger.error('Skipping requested column "{}", since it'
                             ' is not among the solutions'.format(item))
            else:
                solution_list.append(item)

    # Read the results from your harddrive (this can take quite a long time)
    solution_data = mod.getSolutions(solution_list)

    # Create DataFrame from results
    data = pd.DataFrame(data=solution_data.T, columns=solution_list)

    if make_FMU:
        # Convert model to FMU 'modelName.fmu' in the current working directory
        mod.convertMo2Fmu()

        # Alternative: Try to produce Windows and Linux FMU at the same time
        # The platforms argument does not seem to have an effect


#        platforms = '{"x86_64-linux-gnu", "x86_64-w64-mingw32"}'
#        expr = ('buildModelFMU({}, version="2.0", fmuType="me_cs",'
#                'platforms={})'.format(modelName, platforms))
#        mod.getconn.sendExpression(expr)

    return data
from OMPython import ModelicaSystem

#Input Model
mod=ModelicaSystem(ModelPath,ClassName) #2 arguments
#mod=ModelicaSystem(ModelPath, ClassName, ["Modelica"]) #3 arguments 
#mod=ModelicaSystem(ModelPath, ClassName, commandLineOptions="-d=newInst") #4 arguments

#Outputs
Quantities = mod.getQuantities()
SimOptions = mod.getSimulationOptions()
if RunSimulation == True:
    mod.simulate()
    Solutions = list(mod.getSolutions())
else:
    Solutions = mod.getSolutions()
Beispiel #8
0
#anykey();


#Using OpenModelica models
mod1 = ModelicaSystem("SatTrak.mo", "SatTrak.FINAL", ["Modelica"])

mod1.setParameters(M0=Satellites[0].meanan, N0=Satellites[0].meanmo, eccn=Satellites[0].eccn, Ndot2=Satellites[0].ndot, 
                   Nddot6=Satellites[0].nddot6, raan0=Satellites[0].raan, argper0=Satellites[0].argper, incl=Satellites[0].incl, 
                   tstart=((Satellites[0].refepoch - timestart)*3600*24), stn_long=Station.stnlong, 
                   stn_lat=Station.stnlat, stn_elev=Station.stnalt, d0 = 7060, h0 = hh)
                   #,azspeedmax = 3.0, elspeedmax = 3.0)
mod1.setSimulationOptions(startTime=0., stopTime=18000., stepSize=720.)
mod1.simulate()


timemo = mod1.getSolutions("time")
posmo = np.transpose([mod1.getSolutions("p_sat_ECF[1]"), mod1.getSolutions("p_sat_ECF[2]"), mod1.getSolutions("p_sat_ECF[3]")])
velmo = np.transpose([mod1.getSolutions("v_sat_ECF[1]"), mod1.getSolutions("v_sat_ECF[2]"), mod1.getSolutions("v_sat_ECF[3]")])
        
STKout("periftry.e", "EPHEMecf.txt", timemo, posmo, velmo)

#AOS,LOS, POINTING 
azim = mod1.getSolutions("Azimuth")
elev = mod1.getSolutions("Elevation")
dazdt = mod1.getSolutions("dazdt")
deldt = mod1.getSolutions("deldt")

npts = len(azim)

time = []
sataz = []
Beispiel #9
0
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
degree_sign = u'\N{DEGREE SIGN}'

#line1 = ones(370)

mod = ModelicaSystem("ProjectWaterHeater.mo",
                     "ProjectWaterHeater.SimSlicedWaterHeater1")
#mod.setInputs(["Ti=27", "Vd=13", "up=0.5", "uv=0.5", 'Inversed="False"'])

mod.setSimulationOptions(["startTime=0", "stopTime=3600", "stepSize=10"])

mod.simulate()

t = transpose(mod.getSolutions(["time"]))
N = mod.getSolutions("N")
#tarr = range(int(N[0,0]))
#for i in range(int(N[0,0])):
#    Tarr(i) = "T[" + str(i) + "]"

T = mod.getSolutions(["T"])
'''
T = transpose(T)
line1 = ones(len(T))

line = linspace(0,1.5,len(T[1]))
fig = plt.figure(figsize=(12 , 6))
ax = Axes3D(fig)
ax.axis([3600,0,0,1.5])
ax.set_title("Inversed intial temperature and heater is turned on at t=1500s",fontsize=15)