:- module(_,_).
:- use_package(clpr).

%----------------------------------------
% - RLC Analog Circuits

% We represent complex numbers as a pair
% c( <Real_part>, <Imaginary_part> )

% ** Complex number addition

c_add(c(Re1,Im1), c(Re2,Im2), c(Re12,Im12)) :- 
	Re12 .=. Re1+Re2,
	Im12 .=. Im1+Im2.

% ** Complex number multiplication

c_mult(c(Re1, Im1), c(Re2, Im2), c(Re3, Im3)) :-
      Re3 .=. Re1 * Re2 - Im1 * Im2,
      Im3 .=. Re1 * Im2 + Re2 * Im1.

% ** Describing the relation of voltage (V), current (Y),
%    and frequency (W) in resistors, inductors, and
%    capacitors.

circuit(resistor(R), V, I, _W) :- 
    c_mult(I, c(R, 0), V).

circuit(inductor(L), V, I, W) :- 
    Im .=. W * L,
    c_mult(I, c(0, Im), V).

circuit(capacitor(C), V, I, W) :- 
    Im .=. -1 / (W * C),
    c_mult(I, c(0, Im), V).

% ** Describing the relation of voltage (V), current (Y),
%    and frequency (W) when circuits connected in series or
%    in parallel.      
%    We put these after the components, so that synthesis
%    is directed.

% When connecting in parallel, the voltage is the same, the
% currents are added.
circuit(parallel(N1, N2), V, I, W) :-
       c_add(I1, I2, I),
       circuit(N1, V, I1, W),
       circuit(N2, V, I2, W).

% When connecting in series the current is the same, the
% voltages are added.
circuit(series(N1, N2), V, I, W) :-
       c_add(V1, V2, V),
       circuit(N1, V1, I, W),
       circuit(N2, V2, I, W).

/* Calculating the C and R values needed in the given circuit
   to get the given voltage and current at the given frequency:  

?- circuit(parallel(inductor(0.073),
           series(capacitor(C), resistor(R))), 
           c(4.5, 0), c(0.65, 0), 2400).

*/
