def _lock_target_values(element: _edge_with_target_values,
                        config: configuration):
    element_partial_type = None
    for potential_element_type in ['control-valve', 'compressor']:
        if potential_element_type in element.type:
            element_partial_type = potential_element_type
    if element_partial_type is None:
        raise NetDescriptionError(
            "target values can be locked for edge-types in ['compressor', 'control-valve']!"
        )

    target_values_to_lock = None

    # if 'deactivate_target_values' in config.raw:
    for key, val in config.raw.items():
        if ('deactivate_target_values' in key):
            if (element_partial_type
                    in key) and (target_values_to_lock is None):
                target_values_to_lock = val
            elif (element.name in key):
                target_values_to_lock = val

    if not (target_values_to_lock is None):
        if target_values_to_lock['target_upper_pR'] in [
                "off", "None", None, 0, "0", "deactivate"
        ]:
            element.target_upper_pR = table_lookup(
                [-1.0], [pressure_to_bar(1000.0, 'bar')])
            element.target_upper_pR_locked = True
        if target_values_to_lock['target_lower_pR'] in [
                "off", "None", None, 0, "0", "deactivate"
        ]:
            element.target_lower_pR = table_lookup(
                [-1.0], [pressure_to_bar(0.0, 'bar')])
            element.target_lower_pR_locked = True
        if target_values_to_lock['target_upper_pL'] in [
                "off", "None", None, 0, "0", "deactivate"
        ]:
            element.target_upper_pL = table_lookup(
                [-1.0], [pressure_to_bar(1000.0, 'bar')])
            element.target_upper_pL_locked = True
        if target_values_to_lock['target_lower_pL'] in [
                "off", "None", None, 0, "0", "deactivate"
        ]:
            element.target_lower_pL = table_lookup(
                [-1.0], [pressure_to_bar(0.0, 'bar')])
            element.target_lower_pL_locked = True
        if target_values_to_lock['target_q'] in [
                "off", "None", None, 0, "0", "deactivate"
        ]:
            if element_partial_type == 'control-valve':
                element.target_q = table_lookup(
                    [-1.0], [flow_to_kilogramm_per_second(10000.0, 'kg/s')])
            else:
                element.target_q = table_lookup(
                    [-1.0], [flow_to_kilogramm_per_second(0.0, 'kg/s')])
            element.target_q_locked = True
        if target_values_to_lock['use_bypass_instead_of_active']:
            element.by_io_func = table_lookup([-1.0], [1.0])
            element.by_io_func_locked = True
Exemplo n.º 2
0
def create_inic(net : network_dae, dictInic : Union[List, None] = None,
                deadPressure : float = 50.0, deadPressure_unit : str = 'bar',
                deadFlow : float = 0.0, deadFlow_unit : str = 'kg/s',
                x0 : Union[np.ndarray, None] = None) -> np.ndarray:
    '''
    :param net:
    :param dictInic:
    :param deadPressure: pressure in the dead state [50.0 'bar' is default]
    :param deadPressure_unit:
    :param deadFlow: flow in the dead state [0.0 'kg/s' is default and recommended]
    :param deadFlow_unit:
    :param x0: shape fitting vector to update or None (the latter is default)
    :return:
    '''

    '''
        if no state x0 to update was provided a dead state will be created.
    '''
    deadPressure = pressure_to_bar(deadPressure, deadPressure_unit)
    deadFlow = flow_to_kilogramm_per_second(deadFlow, deadFlow_unit)

    if x0 is None:
        x0 = np.zeros(shape  = (net.dim,))
        for node_types in [net.all_node_types, net.all_hidden_node_types]:
            for node_type in node_types:
                for nodeInstance in net.typeReg[node_type]:
                    x0[nodeInstance.p_press_id] = deadPressure

        for edge_types in [net.all_edge_types, net.all_hidden_edge_types]:
            for edge_type in edge_types:
                for edgeInstance in net.typeReg[edge_type]:
                    x0[edgeInstance.qL_leftFlow_id] = deadFlow
                    x0[edgeInstance.qR_rightFlow_id] = deadFlow
    else:
        if x0.shape[0] != net.dim:
            raise DimensionError("x0 provided doesn't fit dim : {}".format(net.dim))


    '''
        this function can return a dead state if no dictInic is provided. 
        So the following code is executed only if a dictInic was provided
    '''
    if not (dictInic is None):
        # ''' gather norm density '''
        # for dictRow in dictInic:
        #     if dictRow['!'] == '!':
        #         continue
        #
        #     # if dictRow['Object'] == '_SYS' and dictRow['Parameter'] == 'RHO_0':
        #     #     net.gasMix.rho_0 = (float(dictRow['Value']), dictRow['Unit'])

        ''' actually filling out x0 by entries from dictInic (which comes from e.g. a csv) '''
        for dictRow in dictInic:
            if dictRow['!'] == '!':
                continue

            obj   = dictRow['Object']
            param = dictRow['Parameter']
            try:
                val = float(dictRow['Value'])
            except:
                val = dictRow['Value']
            unit  = dictRow['Unit']

            if obj in net.nameReg:
                net_elem_instance : Union[node, base_edge] = net.nameReg[obj]
                if 'node' in net_elem_instance.type:
                    nodeInstance : node = net_elem_instance

                    if param == 'P':
                        x0[nodeInstance.p_press_id] = pressure_to_bar(val, unit)

                elif 'edge' in net_elem_instance.type:
                    edgeInstance : base_edge = net_elem_instance

                    if param == 'M':
                        x0[edgeInstance.qL_leftFlow_id] = flow_to_kilogramm_per_second(val, unit,
                                                                                      density = net.gasMix.rho_0,
                                                                                      density_unit = net.gasMix.rho_0_unit)
                    elif param == 'ML':
                        x0[edgeInstance.qL_leftFlow_id] = flow_to_kilogramm_per_second(val, unit,
                                                                                      density = net.gasMix.rho_0,
                                                                                      density_unit = net.gasMix.rho_0_unit)
                    elif param == 'MR':
                        x0[edgeInstance.qR_rightFlow_id] = flow_to_kilogramm_per_second(val, unit,
                                                                                       density = net.gasMix.rho_0,
                                                                                       density_unit = net.gasMix.rho_0_unit)

        ''' dealing with hidden objects '''
        for edge_type in net.all_hidden_edge_types:
            for edgeInstance in net.typeReg[edge_type]:
                linked_edge : base_edge = net.nameReg[edgeInstance.linked_to]
                if edgeInstance.linked_on == 'left':
                    x0[edgeInstance.qL_leftFlow_id] = x0[linked_edge.qL_leftFlow_id]
                    x0[edgeInstance.qR_rightFlow_id] = x0[linked_edge.qL_leftFlow_id]
                else:
                    x0[edgeInstance.qL_leftFlow_id] = x0[linked_edge.qR_rightFlow_id]
                    x0[edgeInstance.qR_rightFlow_id] = x0[linked_edge.qR_rightFlow_id]

        for node_type in net.all_hidden_node_types:
            for nodeInstance in net.typeReg[node_type]:
                linked_node : node = net.nameReg[nodeInstance.linked_to]
                while hasattr(linked_node, "linked_to"): linked_node = net.nameReg[linked_node.linked_to]
                x0[nodeInstance.p_press_id] = x0[linked_node.p_press_id]

    return x0
def set_scenario(net: network_dae, event_dict: dict, config: configuration):
    profile_conf = _profile_configuration('profiles_all', config)
    node_profile_conf = _profile_configuration('profiles_node', config,
                                               profile_conf)
    vlv_profile_conf = _profile_configuration('profiles_common-valve', config,
                                              profile_conf)
    cvlv_profile_conf = _profile_configuration('profiles_control-valve',
                                               config, profile_conf)
    cu_profile_conf = _profile_configuration('profiles_compressor', config,
                                             profile_conf)

    for obj, obj_events in event_dict.items():
        if obj == "_SYS": continue

        try:
            element: base_element = net.nameReg[obj]
        except KeyError:
            raise SceneDescriptionError(
                "did not recognize {} as 'Object' from event_dict!".format(
                    obj))

        obj_profile_conf = None
        for key, val in config.raw.items():
            if ("profiles" in key) and (obj in key):
                obj_profile_conf = _profile_configuration(key, config)

        if 'node' in element.type:
            if obj_profile_conf is None: obj_profile_conf = node_profile_conf

            times = obj_events['t']
            behaviour = obj_events['behaviour'][0]

            element.behaviour = behaviour
            if behaviour == 0:
                pressures = obj_events['pset']
                element.pBoundFunc = table_lookup(times, pressures,
                                                  **obj_profile_conf)
            elif behaviour == 1:
                in_out_flows = obj_events['qInOut']
                element.qBoundFunc = table_lookup(times, in_out_flows,
                                                  **obj_profile_conf)
            else:
                raise SceneDescriptionError(
                    "behaviour couldn't be determined properly from event_dict"
                )

        elif 'common-valve' in element.type:
            if obj_profile_conf is None: obj_profile_conf = vlv_profile_conf

            times = obj_events['t']
            io = obj_events['io']

            element.io_func = table_lookup(times, io, **obj_profile_conf)

        elif ('control-valve' in element.type) or ('compressor'
                                                   in element.type):
            if obj_profile_conf is None:
                if 'control-valve' in element.type:
                    obj_profile_conf = cvlv_profile_conf
                else:  # ==> 'compressor' in element.type
                    obj_profile_conf = cu_profile_conf

            t_io = obj_events['t_io']
            io = obj_events['io']
            element.io_func = table_lookup(t_io, io, **obj_profile_conf)

            t_by_io = obj_events.get('t_by_io', [0.0])
            by_io = obj_events.get('by_io', [1.0])
            element.by_io_func = table_lookup(t_by_io, by_io,
                                              **obj_profile_conf)

            t_target_upper_pR = obj_events.get('t_target_upper_pR', [0.0])
            target_upper_pR = obj_events.get('target_upper_pR',
                                             [pressure_to_bar(1000.0, 'bar')])
            element.target_upper_pR = table_lookup(t_target_upper_pR,
                                                   target_upper_pR,
                                                   **obj_profile_conf)

            t_target_lower_pR = obj_events.get('t_target_lower_pR', [0.0])
            target_lower_pR = obj_events.get('target_lower_pR',
                                             [pressure_to_bar(0.0, 'bar')])
            element.target_lower_pR = table_lookup(t_target_lower_pR,
                                                   target_lower_pR,
                                                   **obj_profile_conf)

            t_target_upper_pL = obj_events.get('t_target_upper_pL', [0.0])
            target_upper_pL = obj_events.get('target_upper_pL',
                                             [pressure_to_bar(1000.0, 'bar')])
            element.target_upper_pL = table_lookup(t_target_upper_pL,
                                                   target_upper_pL,
                                                   **obj_profile_conf)

            t_target_lower_pL = obj_events.get('t_target_lower_pL', [0.0])
            target_lower_pL = obj_events.get('target_lower_pL',
                                             [pressure_to_bar(0.0, 'bar')])
            element.target_lower_pL = table_lookup(t_target_lower_pL,
                                                   target_lower_pL,
                                                   **obj_profile_conf)

            t_target_q = obj_events.get('t_target_q', [0.0])
            target_q = obj_events.get(
                'target_q', [flow_to_kilogramm_per_second(10000.0, 'kg/s')])
            element.target_q = table_lookup(t_target_q, target_q,
                                            **obj_profile_conf)
def parse_scene_csv(net: network_dae, in_event_list: List[Dict[str,
                                                               str]]) -> dict:
    '''
        :param net:
        :param in_event_list:
        :return:
    '''

    out_event_dict = {}

    out_event_dict['_SYS'] = {}
    out_event_dict['_SYS']['CHECKPOINT'] = []
    out_event_dict['_SYS']['ENDOFSIMULATION'] = None
    out_event_dict['_SYS']['DT'] = None

    for dictRow in in_event_list:
        if dictRow['!'] == '!':
            continue

        # if dictRow['Object'] == '_SYS' and dictRow['Parameter'] == 'RHO_0':
        #     rho_0 = net.gasMix.rho_0
        #     net.gasMix.rho_0 = (float(dictRow['Value']), dictRow['Unit'])
        #     if rho_0 != net.gasMix.rho_0:
        #         raise SceneDescriptionError("net {} already had an unequal norm density!".format(str(net)))

    for dictRow in in_event_list:
        if dictRow['!'] == '!':
            continue

        obj = dictRow['Object']
        param = dictRow['Parameter']
        try:
            val = float(dictRow['Value'])
        except ValueError:
            val = dictRow['Value']
        unit = dictRow['Unit']
        if dictRow['Time'] != '':
            time = _convert_time_str_2_float(dictRow['Time'])

        if obj == '_SYS':
            if param == 'DT':
                out_event_dict[obj][param] = relative_time_to_sec(val, unit)
            if param == 'CHECKPOINT':
                out_event_dict[obj][param].append(time)
            elif param == 'ENDOFSIMULATION':
                if out_event_dict[obj][param] is None:
                    out_event_dict[obj][param] = time
                else:
                    raise SceneDescriptionError(
                        "'ENDOFSIMULATION' appeared twice!")
        else:
            try:
                element: base_element = net.nameReg[obj]
            except KeyError:
                raise SceneDescriptionError(
                    "did not recognize {} as 'Object'from event_list!".format(
                        obj))

            if "node" in element.type:
                if param == 'Q':
                    if (obj in out_event_dict) and ('pset'
                                                    in out_event_dict[obj]):
                        raise SceneDescriptionError(
                            '{} can either be a p_node xor q_node!'.format(
                                str(element)))

                    q_in_out = flow_to_kilogramm_per_second(
                        val,
                        unit,
                        density=net.gasMix.rho_0,
                        density_unit=net.gasMix.rho_0_unit)
                    _append_events(obj, out_event_dict, {
                        't': time,
                        'qInOut': q_in_out,
                        'behaviour': 1
                    })

                elif param == 'P':
                    if (obj in out_event_dict) and ('qInOut'
                                                    in out_event_dict[obj]):
                        raise SceneDescriptionError(
                            '{} can either be a p_node xor q_node!'.format(
                                str(element)))

                    _append_events(
                        obj, out_event_dict, {
                            't': time,
                            'pset': pressure_to_bar(val, unit),
                            'behaviour': 0
                        })

            elif ("common-valve" in element.type) and (param in ['ON', 'OFF']):
                _append_events(obj, out_event_dict, {
                    't': time,
                    'io': 1.0 if param != 'OFF' else 0.0
                })

            elif ("compressor" in element.type) or ("control-valve"
                                                    in element.type):
                if param == 'OFF':
                    _append_events(obj, out_event_dict, {
                        't_io': time,
                        'io': 0.0
                    })
                    _append_events(obj, out_event_dict, {
                        't_by_io': time,
                        'by_io': 0.0
                    })
                elif param == 'BP':  # i.e. 'BYPASS'
                    _append_events(obj, out_event_dict, {
                        't_io': time,
                        'io': 1.0
                    })
                    _append_events(obj, out_event_dict, {
                        't_by_io': time,
                        'by_io': 1.0
                    })
                elif (param == 'CONF') and (val == 'FREE'):
                    _append_events(obj, out_event_dict, {
                        't_io': time,
                        'io': 1.0
                    })
                    _append_events(obj, out_event_dict, {
                        't_by_io': time,
                        'by_io': 0.0
                    })

                elif param == 'TARGET_UPPER_PR':
                    _append_events(
                        obj, out_event_dict, {
                            't_target_upper_pR': time,
                            'target_upper_pR': max(0.0,
                                                   pressure_to_bar(val, unit))
                        })
                elif param == 'TARGET_LOWER_PR':
                    _append_events(
                        obj, out_event_dict, {
                            't_target_lower_pR': time,
                            'target_lower_pR': max(0.0,
                                                   pressure_to_bar(val, unit))
                        })
                elif param == 'TARGET_UPPER_PL':
                    _append_events(
                        obj, out_event_dict, {
                            't_target_upper_pL': time,
                            'target_upper_pL': max(0.0,
                                                   pressure_to_bar(val, unit))
                        })
                elif param == 'TARGET_LOWER_PL':
                    _append_events(
                        obj, out_event_dict, {
                            't_target_lower_pL': time,
                            'target_lower_pL': max(0.0,
                                                   pressure_to_bar(val, unit))
                        })
                elif param == 'TARGET_Q':
                    _append_events(
                        obj, out_event_dict, {
                            't_target_q':
                            time,
                            'target_q':
                            max(
                                0.0,
                                flow_to_kilogramm_per_second(
                                    val,
                                    unit,
                                    density=net.gasMix.rho_0,
                                    density_unit=net.gasMix.rho_0_unit))
                        })

    if out_event_dict['_SYS']['ENDOFSIMULATION'] is None:
        raise SceneDescriptionError(
            "There was no 'ENDOFSIMULATION' in in_event_list!")

    return out_event_dict
 def pc(self, pc_tuple : Tuple[float, str]):
     self._pc = pressure_to_bar(*pc_tuple)
     self.pc_unit = validate_unit('bar', 'pressure')