:- module(autobuild_engine_interaction, 
    [
    check_relation_consistency_in_state/2,
    check_relation_consistency/1
    ]).

/** <module> Interaction with simulation engine : Automatic model building

@author Jochem Liem

 * Automatic model building algorithm
 * Inspired by Hylke Buisman's algorithm

*/

%%	check_relation_consistency(+StateID, +Relations) is det.
% 	This function checks the consistency of a set of relations 
% 	(inequalities, causal relations and operators) with the values
% 	of a specific state.
%
% 	Relations is a list of par_relations 
check_relation_consistency_in_state(StateID, Relations):-
    % Create an empty Class Input Output (Cio) structure (internal garp representation) 
    engine:cio_empty(CioEmpty),

    % Get the parameters (quantities + quantity spaces) and parameter values (values),
    % of a specific state 
    engine:state(StateID, Smd),      
    engine:smd_slots2(Smd, _, _, P, V, _R, _, _),

    /* CHEAT ADD ALL INEQUALITIES */
    get_inequalities_from_smd(Smd, Inequalities),
    merge(Inequalities, Relations, NewRelations),
    %NewRelations = Relations,

    % Add the parameters, parameter values and the relations to the Cio and do both inequality reasoning and influence
    % resolution.
    engine:add_givens([P, V, par_relations(NewRelations)], CioEmpty, Cout),
    engine:resolve_influence_proportional(Cout, _Cout2, [], [], _SecondOrderDerivatives, _AmbiguousDerivatives).


%% check_relation_consistency(+Relations:list)
%  Checks the consistency of a set of relations (inequalities, causal relations, and operators) with all the states in
%  the state graph.
check_relation_consistency(Relations) :-
    get_all_states(StateIDs),
    forall(
	member(StateID, StateIDs),
	check_relation_consistency_in_state(StateID, Relations)
    ).
