def choose_variable_and_value_not_found_in_other_initial_values(
        sim_config: SimulationConfiguration,
        component: Component) -> Tuple[str, float]:
    """Chooses a variable and a value from a component that are not found in other initial values"""
    while True:  # Make sure the new initial value is not found in the existing ones
        variable = random.choice(component.fmu.get_parameter_names())
        value = random.random() * 100
        try:
            sim_config.get_initial_value_by_variable(component=component.name,
                                                     variable=variable)
        except TypeError:
            break
    return variable, value
def test_deployment():
    """Test deployment of files for simulation"""
    sim_config = SimulationConfiguration(
        system_structure=PATH_TO_SYSTEM_STRUCTURE_FILE,
        path_to_fmu=PATH_TO_FMU_DIR)
    path_to_deploy = sim_config.prepare_temp_dir_for_simulation()
    assert os.path.isdir(path_to_deploy)

    # Test deploy_files_for_simulation method
    path_to_system_structure = sim_config.deploy_files_for_simulation(
        path_to_deploy=path_to_deploy,
        rel_path_to_system_structure='system_structure')
    assert os.path.isdir(path_to_system_structure)
    assert os.path.join(path_to_deploy,
                        'system_structure') == path_to_system_structure
    assert os.path.isfile(
        os.path.join(path_to_system_structure, 'OspSystemStructure.xml'))
    assert all(
        list(
            map(
                lambda x: os.path.isfile(
                    os.path.join(path_to_deploy,
                                 os.path.basename(x.fmu.fmu_file))),
                sim_config.components)))

    # deploy again and see if the previous directory has been deleted.
    path_to_deploy_again = sim_config.prepare_temp_dir_for_simulation()
    sim_config.deploy_files_for_simulation(path_to_deploy_again)
    assert path_to_deploy != path_to_deploy_again
    assert not os.path.isdir(path_to_deploy)
    assert os.path.isdir(path_to_deploy_again)
def test_get_fmu_rel_path():
    """Testng get_fmu_rel_path method"""
    sim_config = SimulationConfiguration()
    for _ in range(3):
        num_depth = random.randint(0, 5)
        path_to_deploy = 'abc'
        path_to_sys_struct = path_to_deploy
        for _ in range(num_depth):
            path_to_sys_struct = os.path.join(path_to_sys_struct,
                                              get_random_string())
        fmu_rel_path = sim_config.get_fmu_rel_path(path_to_deploy,
                                                   path_to_sys_struct)
        num_depth_calculated = fmu_rel_path.count('../')
        assert num_depth == num_depth_calculated
        fmu_rel_path = sim_config.get_fmu_rel_path(path_to_sys_struct,
                                                   path_to_deploy)
        if len(fmu_rel_path) == 0:
            assert path_to_deploy == path_to_sys_struct
        else:
            assert path_to_sys_struct == os.path.join(
                path_to_deploy,
                reduce(os.path.join,
                       fmu_rel_path.split('/')[:-1]))
def test_initialization():
    with pytest.raises(AssertionError):
        sim_config = SimulationConfiguration(
            system_structure=PATH_TO_SYSTEM_STRUCTURE_FILE)
    sim_config = SimulationConfiguration(
        system_structure=PATH_TO_SYSTEM_STRUCTURE_FILE,
        path_to_fmu=PATH_TO_FMU_DIR)
    system_struct = OspSystemStructure(
        xml_source=PATH_TO_SYSTEM_STRUCTURE_FILE)
    assert sim_config.system_structure.to_xml_str(
    ) == system_struct.to_xml_str()
    assert len(sim_config.components) == len(
        sim_config.system_structure.Simulators)
    num_initial_values = sum(
        map(lambda x: len(x.InitialValues)
            if x.InitialValues else 0, system_struct.Simulators))
    assert len(sim_config.initial_values) == num_initial_values
    with pytest.raises(AssertionError):
        sim_config.scenario = ''
    with pytest.raises(AssertionError):
        sim_config.logging_config = ''
def sim_config_empty() -> SimulationConfiguration:
    """Fixture for pytest"""
    return SimulationConfiguration()
def sim_config_from_xml() -> SimulationConfiguration:
    return SimulationConfiguration(
        system_structure=PATH_TO_SYSTEM_STRUCTURE_FILE,
        path_to_fmu=PATH_TO_FMU_DIR)
def test_run():

    simulation_end_time = 10 + random.random() * 90

    sim_config = SimulationConfiguration(
        system_structure=PATH_TO_SYSTEM_STRUCTURE_FILE,
        path_to_fmu=PATH_TO_FMU_DIR,
    )

    scenario = OSPScenario(name='test_scenario', end=0.5 * simulation_end_time)

    scenario.add_event(
        OSPEvent(time=0.5 * scenario.end,
                 model=sim_config.components[0].name,
                 variable=random.choice(
                     sim_config.components[0].fmu.parameters).get('name'),
                 action=OSPEvent.OVERRIDE,
                 value=random.random() * 10))
    sim_config.scenario = scenario

    assert type(scenario.events[0].variable) is str

    sim_config.logging_config = OspLoggingConfiguration(simulators=list(
        map(
            lambda comp: OspSimulatorForLogging(
                name=comp.name,
                variables=[
                    OspVariableForLogging(name=variable.get('name'))
                    for variable in random.choices(comp.fmu.outputs, k=4)
                ]), sim_config.components)))

    output = sim_config.run_simulation(
        duration=simulation_end_time,
        rel_path_to_sys_struct="system_structure",
        logging_level=LoggingLevel.info)
    assert os.path.isdir(output.output_file_path)
    path_to_scenario_file = os.path.join(output.output_file_path,
                                         scenario.get_file_name())
    assert os.path.isfile(path_to_scenario_file)
    path_to_logging_config_file = os.path.join(output.output_file_path,
                                               'LogConfig.xml')
    assert os.path.isfile(path_to_logging_config_file)
    output_files = [
        file_name for file_name in os.listdir(output.output_file_path)
        if file_name.endswith('.csv')
    ]
    assert len(output_files) == len(sim_config.logging_config.simulators)
    assert len(output.result) == len(sim_config.logging_config.simulators)
    assert simulation_end_time == pytest.approx(
        output.result[sim_config.components[0].name]['Time'].values[-1],
        rel=1e-3)

    print(output.result)

    # Test if the time step option is effective
    sim_config.set_base_step_size(0.02)
    output = sim_config.run_simulation(
        duration=simulation_end_time,
        rel_path_to_sys_struct="system_structure",
        logging_level=LoggingLevel.info)
    if len(output.error) > 0:
        raise SimulationError(
            f'An error or errors occured during the simulation: {output.error}'
        )
    assert np.all(
        np.round(
            np.diff(output.result[sim_config.components[0].name]
                    ['Time'].values), 3) == 0.02)
def test_simulation_configurtion_add_delete_connection():
    """Testing adding/deleting connection for SimulationConfiguration"""
    sim_config = SimulationConfiguration()
    component_names = ['chassis.fmu', 'wheel.fmu', 'ground.fmu']
    for comp in component_names:
        sim_config.add_component(fmu=FMU(os.path.join(PATH_TO_FMU_DIR, comp)),
                                 name=os.path.splitext(comp)[0])
    # Test adding a proper connection
    [source_comp, target_comp] = random.sample(sim_config.components, k=2)
    source_endpoint = OspVariableEndpoint(
        simulator=source_comp.name,
        name=random.choice(source_comp.fmu.get_output_names()))
    target_endpont = OspVariableEndpoint(
        simulator=target_comp.name,
        name=random.choice(target_comp.fmu.get_input_names()))
    var_connection = sim_config.add_connection(source_endpoint,
                                               target_endpont,
                                               group=False)
    number_connections_after = len(
        sim_config.system_structure.Connections.VariableConnection)
    assert var_connection in sim_config.system_structure.Connections.VariableConnection
    assert number_connections_after == 1

    # Test adding the same connection
    with pytest.raises(TypeError):
        sim_config.add_connection(source_endpoint, target_endpont, group=False)

    # Test adding a variable group connection
    var_group1 = OspLinearMechanicalPortType(
        name='contact_to_wheel',
        Force=OspForceType(name='linear_force',
                           Variable=[OspVariableType(ref='p.e')]),
        LinearVelocity=OspLinearVelocityType(
            name='linear_velocity', Variable=[OspVariableType(ref='p.f')]))
    var_group2 = OspLinearMechanicalPortType(
        name='contact_to_chassis',
        Force=OspForceType(name='linear_force',
                           Variable=[OspVariableType(ref='p1.e')]),
        LinearVelocity=OspLinearVelocityType(
            name='linear_velocity', Variable=[OspVariableType(ref='p1.f')]))
    sim_config.components[0].fmu.add_variable_group(var_group1)
    sim_config.components[1].fmu.add_variable_group(var_group2)
    var_group_connection = sim_config.add_connection(
        source=OspVariableEndpoint(simulator='chassis',
                                   name='contact_to_wheel'),
        target=OspVariableEndpoint(simulator='wheel',
                                   name='contact_to_chassis'),
        group=True)
    assert len(
        sim_config.system_structure.Connections.VariableGroupConnection) == 1

    # Test adding a signal connection
    sim_config.add_function(function_name='linear_transform',
                            function_type=FunctionType.LinearTransformation,
                            factor=1.5,
                            offset=0.0)
    var_endpoint = OspVariableEndpoint(simulator='chassis', name='p.e')
    sig_endpoint = OspSignalEndpoint(function='linear_transform', name='in')
    sig_connection = sim_config.add_connection(source=var_endpoint,
                                               target=sig_endpoint,
                                               group=False)
    assert len(sim_config.system_structure.Connections.SignalConnection) == 1

    # Test deleting a signal connection
    sim_config.delete_connection(endpoint1=sig_connection.Signal,
                                 endpoint2=sig_connection.Variable)
    assert sim_config.system_structure.Connections.SignalConnection is None

    # Test deleting a variable group connection
    sim_config.delete_connection(
        endpoint1=var_group_connection.VariableGroup[0],
        endpoint2=var_group_connection.VariableGroup[1])
    assert sim_config.system_structure.Connections.VariableGroupConnection is None

    # Test deleting a variable connection
    sim_config.delete_connection(endpoint1=var_connection.Variable[0],
                                 endpoint2=var_connection.Variable[1])
    assert sim_config.system_structure.Connections is None
예제 #9
0
pulse_signal_fmu = FMU(PATH_TO_FMU_PULSE)  # For heat source
constant_signal_fmu = FMU(PATH_TO_CONSTANT)  # For ambient temperature

# Examine each FMU
for fmu in [
        control_volume_fmu, wall_heat_transfer_fmu, pulse_signal_fmu,
        constant_signal_fmu
]:
    print('------------------------------')
    print(f'{fmu.name}')
    print(f'  input: {fmu.get_input_names()}')
    print(f'  output: {fmu.get_output_names()}')
    print(f'  parameters: {fmu.get_parameter_names()}')

# Create an simulation configuration instance with empty system configuration
sim_config = SimulationConfiguration()

# Now we will add components
sim_config.add_component(name='ControlVolume1', fmu=control_volume_fmu)
sim_config.add_component(name='ControlVolume2', fmu=control_volume_fmu)
sim_config.add_component(name='WallHeatTransfer', fmu=wall_heat_transfer_fmu)
sim_config.add_component(name='HeatLossCV1', fmu=wall_heat_transfer_fmu)
sim_config.add_component(name='HeatLossCV2', fmu=wall_heat_transfer_fmu)
sim_config.add_component(name='HeatSource', fmu=pulse_signal_fmu)
sim_config.add_component(name='AmbientCondition', fmu=constant_signal_fmu)

# Now we add connections
sim_config.add_connection(  # Heat source dQ to control volume 1
    source=OspVariableEndpoint(simulator='HeatSource', name='output'),
    target=OspVariableEndpoint(simulator='ControlVolume1', name='p_in.dQ'),
    group=False)
예제 #10
0
chassis_fmu = FMU(PATH_TO_CHASSIS)
wheel_fmu = FMU(PATH_TO_WHEEL)
ground_fmu = FMU(PATH_TO_GROUND)

# Inspecting the FMUs
for fmu in [chassis_fmu, wheel_fmu, ground_fmu]:
    print('---------------')
    print(fmu.name)
    print(f'  inputs: {fmu.get_input_names()}')
    print(f'  outputs: {fmu.get_output_names()}')
    print(f'  variable_groups: {fmu.get_variable_group_names()}')
    print(f'  parameters: {fmu.get_parameter_names()}')
    print(f'  others: {fmu.get_other_variable_names()}')

# Create a simulation setup with a empty system inside
sim_config = SimulationConfiguration()

# Add components to the system
sim_config.add_component(name='chassis', fmu=chassis_fmu)
sim_config.add_component(name='wheel', fmu=wheel_fmu)
sim_config.add_component(name='ground', fmu=ground_fmu)

# Add connections between components
sim_config.add_connection(source=OspVariableEndpoint(
    simulator='chassis', name='linear mechanical port'),
                          target=OspVariableEndpoint(simulator='wheel',
                                                     name='chassis port'),
                          group=True)
sim_config.add_connection(source=OspVariableEndpoint(simulator='wheel',
                                                     name='ground port'),
                          target=OspVariableEndpoint(