예제 #1
0
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)
예제 #2
0
 def to_modelica(self):
     """Convert the schematic to a valid Modelica file
     :returns: None
     """
     mod = ModelicaSystem("TJunctionSingleDrop.mo", "TJunctionSingleDrop",
                          ["Modelica"])
     return mod.getQuantities()
예제 #3
0
 def make_fmu():
     '''Create an FMU from the Modelica model to use for testing
     '''
     # 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')
     # Convert model to FMU 'BouncingBall.fmu'
     mod.convertMo2Fmu()
예제 #4
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)
예제 #5
0
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)
 def from_modelica(cls, model_info: ModelicaModelInfo):
     if not model_info.location.exists():
         raise ValueError('No such file: ' + str(model_info.location))
     modelica_model = ModelicaSystem(str(model_info.location),
                                     model_info.name, ["Modelica"],
                                     commandLineOptions="--fmiFlags=s:cvode -d=initialization")
     modelica_model.setSimulationOptions(["startTime=0", "stopTime=0"])
     modelica_model.simulate()
     fmu_path = modelica_model.convertMo2Fmu(fmuType='cs')
     if not len(fmu_path):
         raise RuntimeError("Couldn't compile FMU")
     return FmuSource(Path(fmu_path))
예제 #7
0
class TestAROMethods(unittest.TestCase):
    #omc = OMCSessionZMQ();
    #omc.sendExpression("loadModel(Modelica)");
    #omc.sendExpression("loadFile(getInstallationDirectoryPath() + \"../Users/Lucas/Desktop/trackingARO/Vector.mo\")");

    mod = ModelicaSystem("Sattraj.mo", "Sattraj.Satellite")

    # Test of Datefun functions
    def test_curday(self):
        self.assertIsNotNone(curday())

    def test_doy(self):
        # Checks to see if it equals the expected values
        self.assertEqual(doy(2018, 3, 1), 60)
        self.assertEqual(doy(2009, 3, 14), 73)

    def test_dayFraction(self):
        # Checks to see if the two answers are equal to within 7 decimal places
        self.assertAlmostEqual(frcofd(3, 23, 14.444), 0.141139398)
        self.assertAlmostEqual(frcofd(12, 3, 14.12345678901234), 0.502246799)

    def test_ep2dat(self):
        self.assertEqual(ep2dat('8650.28438588'), '1986-02-20 06:49:30.940032')
        self.assertEqual(ep2dat('0850.28438588'), '2008-02-20 06:49:30.940032')

    # Test of Fileio functions

    def test_ReadNoradTLE(self):
        line0 = 'name'
        line1 = '1 20830U 90088A   05053.88610693  .00000015  00000-0  00000-0 0  2777'
        line2 = '2 20830  55.1681 285.7420 0086707 136.1120 224.6824  2.00574691105728'
        Satellite = ReadNoradTLE(line0, line1, line2)
        self.assertEqual(Satellite.eccn, '0086707')
        self.assertEqual(Satellite.incl, '55.1681')
        self.assertEqual(Satellite.meanan, '224.6824')

    def test_ReadStationFile(self):
        Station = ReadStationFile('station.dat')
        self.assertEqual(Station.stnlong, '281.9269597222222')
        self.assertEqual(Station.az_el_lim.elmin, ['9.0', '37.0', '9.0'])
예제 #8
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
예제 #9
0
    * create results file for each run
    * import results file in MATLAB and run analysis.
"""

import os
import subprocess
import numpy as np
from OMPython import OMCSessionZMQ
from OMPython import ModelicaSystem

#os.environ["OPENMODELICAHOME"] = "/home/avpreetsingh/programfiles/OpenModelica_stable/"
#print(os.environ.get('OPENMODELICAHOME'))
omc = OMCSessionZMQ()

model = "HPF.Test.TransformerAnalysis.TransformerEfficiency"
mod = ModelicaSystem("../../DC-Design/HPF/package.mo", model)

# set resistor values, (decreasing)
# using Pout values from Google drive "Energy Balance - Phase 2 Validation/Loss Model: Transformer (Modelica)"
Pout = np.array([1e-5, 155.49, 295.12, 443.76, 590.64, 752.62, 895.59, 1048.46, \
                 1192.41, 1350.64, 1506.68, 1657.16, 1800.54, 1949.58, 2097.18, \
                 2253.9, 2404.18, 2551.03, 2699.13, 2850.55, 2997.55])
#Pout = np.linspace(1e-5, 3e3, 5)
resistorVals = ((120.0**2) / Pout) * 3
# run simulations
indx = 1
for resistorVal in resistorVals:
    # set resistor values
    mod.setParameters("a_r1.r = " + str(resistorVal))
    mod.setParameters("a_r2.r = " + str(resistorVal))
    mod.setParameters("a_r3.r = " + str(resistorVal))
예제 #10
0
scenarios = np.arange(4, 7)  # running scenarios 1-4
dataSets = np.arange(1, 5)  # datasets 1-4
# simulation options
# default settings result in translation errors
cmdOptions = "--matchingAlgorithm=PFPlusExt --indexReductionMethod=dynamicStateSelection -d=initialization,NLSanalyticJacobian,newInst"

# run simulations
indx = 1
for scenario in scenarios:
    for dataSet in dataSets:

        model = "HPF.Examples.ModelingValidation.Scenario_" + str(scenario) + \
                    "_Data_Set_" + str(scenario) + "_" + str(dataSet)
        print("=============================")
        print("== Scenario ", str(scenario), " DataSet ", str(scenario), ".", \
              str(dataSet), "==")
        print("=============================")

        mod = ModelicaSystem("../../../HPF/package.mo", model, \
                             commandLineOptions = cmdOptions)
        #mod.simulate()
        # simulate
        simRunRes = subprocess.run(["./" + model], stdout=subprocess.PIPE)
        print(simRunRes.stdout)
        # ??? remove executable
        # using python routines
        os.remove(model)
        indx = indx + 1

# cleanup, all except result file
os.system("rm *.json *.c *.h *.o *.makefile *.libs *.xml *.log")
end Simple;''' # модель мовою Modelica 
with open('Simple.mo', 'w') as f: f.write(code) # створити файл моделі
import os, sys
sys.path.insert(0, r"e:\OpenModelica\share\omc\scripts\PythonInterface") # шлях до модулів
from OMPython import OMCSession, ModelicaSystem

# перший спосіб - використання 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)) # створити файл зі значеннями параметрів
예제 #12
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
예제 #13
0
import os
from OMPython import OMCSessionZMQ
from OMPython import ModelicaSystem
os.chdir("output")
omc = OMCSessionZMQ()
model_path=omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/"
mod=ModelicaSystem(model_path + "BouncingBall.mo","BouncingBall",["Modelica"])
#mod.buildModel()
print(mod.getQuantities())
print(mod.simulate()) # (simflags="stopTime=3.0")
mod.setLinearizationOptions(["stopTime=2.0"])
print(mod.linearize())
#outp = mod.linearize() # mod.getOutputs()
#print(outp)
# cmds = [
#   'loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/BouncingBall.mo")',
#   "simulate(BouncingBall, stopTime=3.0)",
#   "plot(h)"
#   ]
# for cmd in cmds:
#   answer = omc.sendExpression(cmd)
#   print("\n{}:\n{}".format(cmd, answer))
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()
예제 #15
0
파일: main.py 프로젝트: naufalrafi/Tracking
# insert error conditions here
# if error, errmsg();
# else

print("Station and Satellites successfully loaded");

# user can take some time to examine the newly created Station and Satellites[i] variables
# these variables are in the form of named tuples, e.g. Sattellites[2].refepoch and Station.stnlat
# these variables are as documented in the procedure section

#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)
예제 #16
0
"""
Created on Sat Oct 19 13:31:58 2019

@author: kdst
"""

from OMPython import ModelicaSystem
from numpy import transpose, ones, linspace

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)