Ejemplo n.º 1
0
    def test_work_flow_me2(self):
        """Tests the work flow of write_header, write_point, write_finalize."""
        model = Dummy_FMUModelME2([],
                                  "bouncingBall.fmu",
                                  os.path.join(file_path, "files", "FMUs",
                                               "XML", "ME2.0"),
                                  _connect_dll=False)
        model.setup_experiment()
        model.initialize()

        bouncingBall = ResultHandlerFile(model)

        bouncingBall.set_options(model.simulate_options())
        bouncingBall.simulation_start()
        bouncingBall.initialize_complete()
        bouncingBall.integration_point()
        bouncingBall.simulation_end()

        res = ResultDymolaTextual('bouncingBall_result.txt')

        h = res.get_variable_data('h')
        derh = res.get_variable_data('der(h)')
        g = res.get_variable_data('g')

        nose.tools.assert_almost_equal(h.x, 1.000000, 5)
        nose.tools.assert_almost_equal(derh.x, 0.000000, 5)
Ejemplo n.º 2
0
    def test_dymola_export_import(self):
        """
        Test for export and import the result file on Dymola textual format.
        """
        vdp = self.vdp

        # Initialize the mesh
        n_e = 50 # Number of elements 
        hs = N.ones(n_e)*1./n_e # Equidistant points
        n_cp = 3; # Number of collocation points in each element

        # Create an NLP object
        nlp = ipopt.NLPCollocationLagrangePolynomials(vdp,n_e,hs,n_cp)

        # Create an Ipopt NLP object
        nlp_ipopt = ipopt.CollocationOptimizer(nlp)

        # Solve the optimization problem
        nlp_ipopt.opt_coll_ipopt_solve()
       
        # Get the result
        p_opt, traj = nlp.get_result()

        # Write to file
        nlp.export_result_dymola()

        # Load the file we just wrote
        res = ResultDymolaTextual(self.fname[:-len('.jmu')]+'_result.txt')

        # Check that one of the trajectories match.
        assert max(N.abs(traj[:,3]-res.get_variable_data('x1').x))<1e-12

        # Check that the value of the cost function is correct
        assert N.abs(p_opt[0] - 2.2811587) < 1e-5
Ejemplo n.º 3
0
    def test_dymola_export_import(self):
        """
        Test for export and import the result file on Dymola textual format.
        """
        vdp = self.vdp

        # Initialize the mesh
        n_e = 50  # Number of elements
        hs = N.ones(n_e) * 1. / n_e  # Equidistant points
        n_cp = 3
        # Number of collocation points in each element

        # Create an NLP object
        nlp = ipopt.NLPCollocationLagrangePolynomials(vdp, n_e, hs, n_cp)

        # Create an Ipopt NLP object
        nlp_ipopt = ipopt.CollocationOptimizer(nlp)

        # Solve the optimization problem
        nlp_ipopt.opt_coll_ipopt_solve()

        # Get the result
        p_opt, traj = nlp.get_result()

        # Write to file
        nlp.export_result_dymola()

        # Load the file we just wrote
        res = ResultDymolaTextual(self.fname[:-len('.jmu')] + '_result.txt')

        # Check that one of the trajectories match.
        assert max(N.abs(traj[:, 3] - res.get_variable_data('x1').x)) < 1e-12

        # Check that the value of the cost function is correct
        assert N.abs(p_opt[0] - 2.2811587) < 1e-5
Ejemplo n.º 4
0
 def test_correct_file_after_simulation_failure(self):
     simple_alias = Dummy_FMUModelME2([("x", "y")], "NegatedAlias.fmu", os.path.join(file_path, "files", "FMUs", "XML", "ME2.0"), _connect_dll=False)
     
     def f(*args, **kwargs):
         if simple_alias.time > 0.5:
             raise Exception
         return -simple_alias.continuous_states
     
     simple_alias.get_derivatives = f
     
     opts = simple_alias.simulate_options()
     opts["result_handling"] = "file"
     opts["solver"] = "ExplicitEuler"
     
     successful_simulation = False
     try:
         res = simple_alias.simulate(options=opts)
         successful_simulation = True #The above simulation should fail...
     except:
         pass
     
     if successful_simulation:
         raise Exception
         
     result = ResultDymolaTextual("NegatedAlias_result.txt")
     
     x = result.get_variable_data("x").x
     y = result.get_variable_data("y").x
     
     assert len(x) > 2
     
     for i in range(len(x)):
         nose.tools.assert_equal(x[i], -y[i])
Ejemplo n.º 5
0
 def test_result_no_variable_data(self):
     """
     Test that it is possible to get time data from a result file 
     with no variable data (no data_2 vector).
     """
     res_file = os.path.join(path_to_results, 'no_variables_result.txt')
     res = ResultDymolaTextual(res_file)
     time_traj = res.get_variable_data('time')
     assert N.abs(time_traj.t[-1] - 1.0) < 1e-6
Ejemplo n.º 6
0
 def test_result_dymola_textual_finding_derivative(self):
     """
     Test so that the correct alias derivatives are found.
     """
     res = ResultDymolaTextual(
         os.path.join(path_to_results,
                      "VDP_pack_VDP_Test_result_modified_for_alias.txt"))
     assert res.get_variable_index("vdp.der(x1)") == res.get_variable_index(
         "der(vdp.u)")
Ejemplo n.º 7
0
 def test_result_no_variable_data(self):
     """
     Test that it is possible to get time data from a result file 
     with no variable data (no data_2 vector).
     """
     res_file = os.path.join(path_to_results, 'no_variables_result.txt')
     res = ResultDymolaTextual(res_file)
     time_traj = res.get_variable_data('time')
     assert N.abs(time_traj.t[-1] - 1.0) < 1e-6
Ejemplo n.º 8
0
 def test_result_only_variable_data_txt(self):
     """
     Test that it is possible to get time data from a textual result file 
     with only variable data.
     """
     res_file = os.path.join(path_to_results, 'onlyVars.txt')
     res = ResultDymolaTextual(res_file)
     time_traj = res.get_variable_data('time')
     assert N.abs(time_traj.t[-1] - 1.0) < 1e-6
     time_traj_dym = res.get_variable_data('Time')
     assert N.abs(time_traj_dym.t[-1] - 1.0) < 1e-6 
Ejemplo n.º 9
0
 def test_result_dymola_textual_naming_convention(self):
     """
     Assert that we can read both der(PI.x) and PI.der(x) variables. Also tests
     that we can read u[2, 1] and u[2,1].
     """
     res = ResultDymolaTextual(os.path.join(path_to_results, "VDP_pack_VDP_Test_result_correct.txt"))
     assert res.get_variable_index("vdp.der(x1)") == res.get_variable_index("der(vdp.x1)")
     assert res.get_variable_index("u[2,1]") == res.get_variable_index("u[2, 1]")
     
     res = ResultDymolaTextual(os.path.join(path_to_results, "VDP_pack_VDP_Test_result_incorrect.txt"))
     assert res.get_variable_index("vdp.der(x1)") == res.get_variable_index("der(vdp.x1)")
     assert res.get_variable_index("u[2, 1]") == res.get_variable_index("u[2, 1]")
Ejemplo n.º 10
0
 def test_get_description(self):
     model = Dummy_FMUModelME1([], "CoupledClutches.fmu", os.path.join(file_path, "files", "FMUs", "XML", "ME1.0"), _connect_dll=False)
     model.initialize()
     
     result_writer = ResultHandlerFile(model)
     result_writer.set_options(model.simulate_options())
     result_writer.simulation_start()
     result_writer.initialize_complete()
     result_writer.integration_point()
     result_writer.simulation_end()
     
     res = ResultDymolaTextual('CoupledClutches_result.txt')
     
     assert res.description[res.get_variable_index("J1.phi")] == "Absolute rotation angle of component"
Ejemplo n.º 11
0
    def test_get_description_unicode(self):
        model = Dummy_FMUModelME1([], "Description.fmu", os.path.join(file_path, "files", "FMUs", "XML", "ME1.0"), _connect_dll=False)
        model.initialize()
        
        result_writer = ResultHandlerFile(model)
        result_writer.set_options(model.simulate_options())
        result_writer.simulation_start()
        result_writer.initialize_complete()
        result_writer.integration_point()
        result_writer.simulation_end()
        
        res = ResultDymolaTextual('Description_result.txt')
        desc = res.description[res.get_variable_index("x")] 

        assert desc == u"Test symbols '' ‘’"
Ejemplo n.º 12
0
 def test_description_not_stored(self):
     model = Dummy_FMUModelME1([], "CoupledClutches.fmu", os.path.join(file_path, "files", "FMUs", "XML", "ME1.0"), _connect_dll=False)
     model.initialize()
     
     opts = model.simulate_options()
     opts["result_store_variable_description"] = False
     
     result_writer = ResultHandlerFile(model)
     result_writer.set_options(opts)
     result_writer.simulation_start()
     result_writer.initialize_complete()
     result_writer.integration_point()
     result_writer.simulation_end()
     
     res = ResultDymolaTextual('CoupledClutches_result.txt')
     
     assert res.description[res.get_variable_index("J1.phi")] == "", "Description is not empty, " + res.description[res.get_variable_index("J1.phi")]
Ejemplo n.º 13
0
    def test_work_flow(self):
        """Tests the work flow of write_header, write_point, write_finalize."""

        bouncingBall = fmi_ResultHandlerFile(self._bounce)

        bouncingBall.set_options(self._bounce.simulate_options())
        bouncingBall.simulation_start()
        bouncingBall.initialize_complete()
        bouncingBall.integration_point()
        bouncingBall.simulation_end()

        res = ResultDymolaTextual('bouncingBall_result.txt')

        h = res.get_variable_data('h')
        derh = res.get_variable_data('der(h)')
        g = res.get_variable_data('g')

        nose.tools.assert_almost_equal(h.x, 1.000000, 5)
        nose.tools.assert_almost_equal(derh.x, 0.000000, 5)
Ejemplo n.º 14
0
    def test_work_flow(self):
        """Tests the work flow of write_header, write_point, write_finalize."""
        
        
        bouncingBall = fmi_ResultHandlerFile(self._bounce)
        
        bouncingBall.set_options(self._bounce.simulate_options())
        bouncingBall.simulation_start()
        bouncingBall.initialize_complete()
        bouncingBall.integration_point()
        bouncingBall.simulation_end()
        
        res = ResultDymolaTextual('bouncingBall_result.txt')
        
        h = res.get_variable_data('h')
        derh = res.get_variable_data('der(h)')
        g = res.get_variable_data('g')

        nose.tools.assert_almost_equal(h.x, 1.000000, 5)
        nose.tools.assert_almost_equal(derh.x, 0.000000, 5)
Ejemplo n.º 15
0
 def get_result(self):
     """ 
     Write result to file, load result data and create an FMICSResult 
     object.
     
     Returns::
     
         The FMICSResult object.
     """
     # load result file
     res = ResultDymolaTextual(self.result_file_name)
     # create and return result object
     return FMIResult(self.model, self.result_file_name, None, res,
                      self.options)
Ejemplo n.º 16
0
 def get_result(self):
     """ 
     Write result to file, load result data and create an AssimuloSimResult 
     object.
     
     Returns::
     
         The AssimuloSimResult object.
     """
     if not self.simulator.continuous_output:
         write_data(self.simulator,self.write_scaled_result, self.result_file_name)
     # load result file
     res = ResultDymolaTextual(self.result_file_name)
     # create and return result object
     return AssimuloSimResult(self.model, self.result_file_name, self.simulator, 
         res, self.options)
Ejemplo n.º 17
0
    def test_result_dymola_textual_naming_convention(self):
        """
        Assert that we can read both der(PI.x) and PI.der(x) variables. Also tests
        that we can read u[2, 1] and u[2,1].
        """
        res = ResultDymolaTextual(
            os.path.join(path_to_results,
                         "VDP_pack_VDP_Test_result_correct.txt"))
        assert res.get_variable_index("vdp.der(x1)") == res.get_variable_index(
            "der(vdp.x1)")
        assert res.get_variable_index("u[2,1]") == res.get_variable_index(
            "u[2, 1]")

        res = ResultDymolaTextual(
            os.path.join(path_to_results,
                         "VDP_pack_VDP_Test_result_incorrect.txt"))
        assert res.get_variable_index("vdp.der(x1)") == res.get_variable_index(
            "der(vdp.x1)")
        assert res.get_variable_index("u[2, 1]") == res.get_variable_index(
            "u[2, 1]")
Ejemplo n.º 18
0
varArr = np.zeros((len(variables[0]), 3), dtype=np.object)
varArr[:, 0] = np.arange(len(variables[0]))
varArr[:, 1] = variables[0]
varArr[:, 2] = variables[1]

np.savetxt(fileName + '_variables.txt', varArr, fmt='%s', delimiter='\t\t')

## Get variables in JModelica pylab

# load existing result file
from pyfmi.common.io import ResultDymolaTextual
# initialize
dataAllx = list()
dataAllt = list()
maxLen = 0  # record the longest sequence length
resData = ResultDymolaTextual(fileName + '.txt')
for i in range(len(variables[0]) - 1):
    data = resData.get_variable_data(variables[0][i])
    dataAllx.append(data.x)
    dataAllt.append(data.t)
    maxLen = len(data.x) if len(data.x) > maxLen else maxLen

## Save all data to csv file (This is not recommended)

# # initialize output array
# dataArr = np.zeros((maxLen+1,2*(len(variables[0,:])-1)),dtype = np.object) # Set dtype beforehand, conversion later causes error for large arrays
# # header
# header = list()
# # fill in data and pad with NAN for empty entries, (var_time|var_value)
# for i in range(len(variables[0])-1):
#     dataArr[1:,2*i] = np.pad(dataAllt[i],(0,maxLen-len(dataAllt[i])),mode='constant',constant_values=np.nan)
Ejemplo n.º 19
0
##

model_name = 'MyMedia.TwoTankTest'
# If the package is not in library form, then must assign the mo file instead of the directory
mo_file1 = 'C:\Users\James\OneDrive\Documents\Berkeley\HVAC\Modelica\Test\MyMedia.mo'
# If the package is in library form, then must assign the root directory
mo_file2 = 'C:\Users\James\Desktop\Buildings 4.0.0'
mo_files = mo_file1 + ',' + mo_file2

fmu = compile_fmu(model_name, mo_files)

##
# load existing result file
from pyfmi.common.io import ResultDymolaTextual

res = ResultDymolaTextual("MyResult.txt")

var = res.get_variable_data("MyVariable")

var.x  #Trajectory
var.t  #Corresponding time vector

# Example:
res = ResultDymolaTextual('TestSys_HVACv3a_weather_result.txt')
var = res.get_variable_data('ahu1.fanOA.m_flow')
print(var.x)

##
# Set compiler log level to 'info'
compile_fmu('myModel', 'myModels.mo', compiler_log_level='info')
'''
Ejemplo n.º 20
0
 def test_result_dymola_textual_finding_derivative(self):
     """
     Test so that the correct alias derivatives are found.
     """
     res = ResultDymolaTextual(os.path.join(path_to_results, "VDP_pack_VDP_Test_result_modified_for_alias.txt"))
     assert res.get_variable_index("vdp.der(x1)") == res.get_variable_index("der(vdp.u)")