import math
import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize
NA=-1
def cvWeibull(alpha ): # SD(X)/E(X), follows from the formulas for expectation and variance in Weibull
   return math.sqrt( math.gamma(1 + 2 / alpha) / (math.gamma(1 + 1 / alpha) ** 2) - 1)





def alphaWeibull(cv): # Find alpha in Weibull based on cv
    # Bruker y = a*x^2 + b*x+c, hvor y = 1/cv, og x = alpha, hvor a b, og c er funnet ved regresjon

    if cv > 15:
        a = 4.5879
        b = - 0.765
        c = 0.0329
    elif cv > 2.2: 
        a = 0.1484
        b = 1.1956
        c = - 0.1855        
    elif cv > 1:
        a = -0.2491
        b = 1.4761
        c= - 0.2277
    elif cv > .5:
        a = -0.0651
        b = 1.1059
        c = - 0.0394        
    elif cv > .23:
        a = -0.0091
        b =  0.8798
        c =  0.1927
    else:
        a = -0.0091
        b = 0.8798
        c = 0.1927
    if a > 0:
       sign = 1
    else:
       sign = -1
    print(a,b,c)   
    c -= 1/cv
    discriminant = (b**2) - (4*a*c)
    print(discriminant)
    return  (-b - sign*math.sqrt(discriminant)) / (2 * a)

print(alphaWeibull(.39                ))
print(1/0)
'''
for cv in np.arange(.1,10,.4):
   print (cv,cvWeibull(alphaWeibull(cv)))
'''
def Q0integrand(t,tau,alpha,lmbda): # 1/tau * Pr(PF<(tau-t) = Prob of "F" if "P" occurs t-time units after last inspection  
   
   return (1-math.exp(-((lmbda*(tau-t))**alpha)))/tau
                      
def Q0(tau,ePF,sdPF):
   global alpha # Use a global variable to avoid calculating alpha each time, i.e., calculate only if is alpha not specified  
   if alpha == NA:
      alpha = alphaWeibull(sdPF/ePF)
   lmbda = math.gamma(1+1/alpha)/ePF   
   I, err = quad(Q0integrand, 0, tau, args=(tau,alpha,lmbda))   
   return I

def C_tau(tau,f_P,ePF,sdPF,c_I,c_F,c_R):
   tau = tau[0]
   return c_I/tau + f_P*c_F*Q0(tau,ePF,sdPF) + f_P*c_R*(1-Q0(tau,ePF,sdPF))

alpha = NA               # Global variable not initialized
C_I = 500                # Cost of inspection
C_PM = 7000	         # Not used
C_CM = 35000	         # Cost of corrective maintenance
C_EP = 500	         # Expected punctuality/production loss cost
C_ES = 25000	         # Expected safety cost
C_F = C_CM + C_EP + C_ES # Total failure cost   
MTTF = 175               # Mean time to failure
ePF = 10                 # Expected PF-interval
f_P = 1/(MTTF-ePF)       # Rate of potential failures
sdPF = 3                 # Standard deviation of PF-interval
tau0 = ePF/3             # Initial guess for tau 

result = minimize(C_tau, tau0, args = (f_P,ePF,sdPF,C_I,C_F,C_PM))
tau = result.x[0]

print("\nOptimal tau (1000 km) = %.3f " % tau,"\nC(tau) = %.3f" %result.fun )
print("Probability of failure|potential failure = %.4f" % Q0(tau,ePF,sdPF))
inspectionCost = C_I/tau
failureCost = f_P*C_F*Q0(tau,ePF,sdPF)
renewalCost = f_P*C_PM*(1-Q0(tau,ePF,sdPF))
print("Inspection cost = %.3f" % inspectionCost)
print("Renewal cost = %.3f" % renewalCost)
print("Failure cost = %.3f" % failureCost )


#print(alphaWeibull2(10,3),alphaWeibull(10,3))
