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 + b, hvor y = 1/cv, og x = alpha, hvor a og b er funnet ved regresjon

    if cv > 15:
        b=	-0.065857766
        a=	0.611373745

    elif cv > 2.2: 
        b=	-0.202321017
        a=	1.299528059
      
    elif cv > 1:
        b=	-0.093754908
        a=	1.102433653

    elif cv > .5:
        b=	0.100672358
        a=	0.910570158

    elif cv > .23:
        b=	0.296233664
        a=	0.815995658

    else:
        b=	0.426187437
        a=	0.788942982
    alpha0 = (1/cv-b)/a
    y2 = 1/cvWeibull(alpha0*1.025)
    y1 = 1/cvWeibull(alpha0*.975)
    a = (y2-y1)/(alpha0*.05)
    b = y2-a*alpha0*1.025
    alpha0 = (1/cv-b)/a
    return alpha0


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))
