#-----------------------------------------------------------
# Risoluzione in diversi modi di un semplice circuito
# (figura circ_fig_2_12.png, lezione nr. 33 per SMIA)
# GdA, maggio 2023
#---------------------------------------------------------- 

pausa <- function() { cat ("\n >> press Enter to continue\n"); scan() }

# Nota: simboli rinominati rispetto alla fig. circ_fig_2_12.png
# R0, R1, R2 -> R1, R2, r3
# I0, I1, I2 -> I1, I2, I3        

f  <- 12 # V
R1 <- 10 # Ohm
R2 <- 50 # Ohm
R3 <- 15 # Ohm
R <- c(R1,R2,R3) # le mettiamo, per comodità, anche in un vettore

#------------------------------------------------
# soluzione mediante riduzione a serie/parallelo
cat(" Soluzione mediante riduzione e parallelo e serie:\n") 
Rp <- R2*R3/(R2+R3)
Rt <- R1 + Rp

I1 <- f / Rt
I2 <- I1 * R3 / (R2+R3)
I3 <- I1 * R2 / (R2+R3)
cat(sprintf("(I1, I2, I3):  (%.3f,  %.3f,  %.3f) A\n", I1, I2, I3)) 

V1 <- I1*R1
Vp <- I1*Rp
cat(sprintf("(f, V1, Vp):  (%.3f,  %.3f,  %.3f) V\n", f, V1, Vp))
pausa()

#-------------------------------------------------
# soluzione 'matriciale'
# Equazioni possibili (inclusa la 'e', a vista equivalente alla 'd' )
#  a)  f - R1*I1 - R2*I2 = 0    ->   R1*I1 + R2*I2 +   0   = f 
#  b)  f - R1*I1 - R3*I3 = 0    ->   R1*I1 +   0   + R3*I3 = f
#  c)      R2*I2 - R3*I3 = 0    ->     0   + R2*I2 - R3*I3 = 0
#  d)        I1 - I2 -I3 = 0    ->    1*I1 -  1*I2 -  1*I3 = 0 
#  e)       -I1 + I2 +I3 = 0    ->  - 1*I1 +  1*I2 +  1*I3 = 0 

# 1: (a,b,c)
cat("\n\n 1) \n") 
M <- rbind(c(R1, R2, 0),
           c(R1, 0, R3),
           c(0, R2, -R3))
print(M)
detM <- det(M)
cat(sprintf(" determinante: %.3e \n -> matrice singolare\n", detM))
pausa()

# 2: (a,c,d) 
cat("\n\n 2) \n") 
M <- rbind(c(R1, R2, 0),
           c( 0, R2, -R3),
           c(1, -1, -1))
print(M)
detM <- det(M)
cat(sprintf(" determinante: %.3e\n Inversa:\n", detM))
iM <- solve(M)  # inversa di M
print(iM)
b <- c(f, 0, 0)   # vettore dei termini noti
cat(" vettore dei termini noti:\n")
print(b)
I <- as.vector(iM%*%b)
cat(" correnti (A):\n")
print(I)
V <- R*I
cat(" tensioni (V):\n")
print(V)
pausa()

# 3: (a,b,d) 
cat("\n\n 3) \n") 
M <- rbind(c(R1, R2, 0),
           c(R1, 0, R3),
           c(1, -1, -1))
print(M)
detM <- det(M)
cat(sprintf(" determinante: %.3e\n Inversa:\n", detM))
iM <- solve(M)  # inversa di M
print(iM)
cat(" vettore dei termini noti:\n")
b <- c(f, f, 0)   # vettore dei termini noti
print(b)
I <- as.vector(iM%*%b)
cat(" correnti (A):\n")
print(I)
V <- R*I
cat(" tensioni (V):\n")
print(V)

