import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
from HelperFunctions import *
from ClassifyMin import *

import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd



def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]


def find_nearestIdx(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return idx



# TODO
# - Fallunterscheidung (Speedup) falls gesuchter value mu_gamma = q3
# - Also Add option to plot Minimization Output


# ----- Setup Paths -----
# InputFile  = "/inputs/cellsolver.parset"
# OutputFile = "/outputs/output.txt"

InputFile  = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"

# path = os.getcwd()
# InputFilePath = os.getcwd()+InputFile
# OutputFilePath = os.getcwd()+OutputFile
# --------- Run  from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)

#---------------------------------------------------------------

print('---- Input parameters: -----')

mu1 = 1.0
# mu1 = 10.0
# lambda1 = 10.0
rho1 = 1.0
alpha = 2.0
beta = 5.0
theta = 1.0/4.0

lambda1 = 0.0
# gamma = 1.0/4.0

gamma = 'infinity'  #Elliptic Setting
# gamma = '0'       #Hyperbolic Setting
# gamma = 0.5


print('mu1: ', mu1)
print('rho1: ', rho1)
print('alpha: ', alpha)
print('beta: ', beta)
print('theta: ', theta)
print('gamma:', gamma)
print('----------------------------')


# --- define Interval of x-va1ues:
xmin = 0.0
xmax = 1.0


numPoints = 200
Theta_Values = np.linspace(xmin, xmax, num=numPoints)
print('Theta_Values:', Theta_Values)






B1_Values = []
B2_Values = []

b1 = prestrain_b1(rho1, beta, alpha,theta)
b2 = prestrain_b2(rho1, beta, alpha,theta)

b1_Vec = np.vectorize(prestrain_b1)
b2_Vec = np.vectorize(prestrain_b2)

harmonicMeanVec = np.vectorize(harmonicMean)
arithmeticMeanVec = np.vectorize(arithmeticMean)

Theta_Values = np.array(Theta_Values)

# B1_Values_alphaNeg1 = b1_Vec(rho1, beta, -1.0,Theta_Values)
# B1_Values_alphaNeg10 = b1_Vec(rho1, beta, -10.0,Theta_Values)
# B1_Values_alpha2= b1_Vec(rho1, beta, 2.0 ,Theta_Values)
# B1_Values_alpha10= b1_Vec(rho1, beta, 10.0 ,Theta_Values)
# # B2_Values = b2_Vec(rho1, beta, alpha,Theta_Values)
# B2_Values_alphaNeg1 = b2_Vec(rho1, beta, -1.0,Theta_Values)
# B2_Values_alphaNeg10 = b2_Vec(rho1, beta, -10.0,Theta_Values)
# B2_Values_alpha2= b2_Vec(rho1, beta, 2.0 ,Theta_Values)
# B2_Values_alpha10= b2_Vec(rho1, beta, 10.0 ,Theta_Values)

Q1_Values_beta05  = (1.0/6.0)*harmonicMeanVec(mu1, 0.5, Theta_Values)

Q1_Values_beta1  = (1.0/6.0)*harmonicMeanVec(mu1, 1.0, Theta_Values)
Q1_Values_beta2  = (1.0/6.0)*harmonicMeanVec(mu1, 2.0, Theta_Values)
Q1_Values_beta5  = (1.0/6.0)*harmonicMeanVec(mu1, 5.0, Theta_Values)
Q1_Values_beta10 = (1.0/6.0)*harmonicMeanVec(mu1, 10.0, Theta_Values)

Q2_Values_beta05  = (1.0/6.0)*arithmeticMeanVec(mu1, 0.5, Theta_Values)

Q2_Values_beta1  = (1.0/6.0)*arithmeticMeanVec(mu1, 1.0, Theta_Values)
Q2_Values_beta2  = (1.0/6.0)*arithmeticMeanVec(mu1, 2.0, Theta_Values)
Q2_Values_beta5  = (1.0/6.0)*arithmeticMeanVec(mu1, 5.0, Theta_Values)
Q2_Values_beta10 = (1.0/6.0)*arithmeticMeanVec(mu1, 10.0, Theta_Values)

print("Q1_Values_beta1 ", Q1_Values_beta1 )

# --- Convert to numpy array
# B1_Values = np.array(B1_Values)
# B2_Values  = np.array(B2_Values)
Q1_Values_beta05 = np.array(Q1_Values_beta05 )

Q1_Values_beta1  = np.array(Q1_Values_beta1 )
Q1_Values_beta2  = np.array(Q1_Values_beta2 )
Q1_Values_beta5  = np.array(Q1_Values_beta5 )
Q1_Values_beta10 = np.array(Q1_Values_beta10 )

Q2_Values_beta05 = np.array(Q2_Values_beta05 )

Q2_Values_beta1  = np.array(Q2_Values_beta1 )
Q2_Values_beta2  = np.array(Q2_Values_beta2 )
Q2_Values_beta5  = np.array(Q2_Values_beta5 )
Q2_Values_beta10 = np.array(Q2_Values_beta10 )

# ---------------- Create Plot -------------------

#--- change plot style:  SEABORN
# plt.style.use("seaborn-paper")

# plt.style.use("seaborn-darkgrid")
# plt.style.use("seaborn-whitegrid")
plt.style.use("seaborn")
# plt.style.use("seaborn-paper")
# plt.style.use('ggplot')
# plt.rcParams["font.family"] = "Avenir"
# plt.rcParams["font.size"] = 16

# plt.style.use("seaborn-darkgrid")
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "10"
# mpl.rcParams['xtick.labelsize'] = 16mpl.rcParams['xtick.major.size'] = 2.5
# mpl.rcParams['xtick.bottom'] = True
# mpl.rcParams['ticks'] = True
mpl.rcParams['xtick.bottom'] = True
mpl.rcParams['xtick.major.size'] = 3
mpl.rcParams['xtick.minor.size'] = 1.5
mpl.rcParams['xtick.major.width'] = 0.75
mpl.rcParams['ytick.left'] = True
mpl.rcParams['ytick.major.size'] = 3
mpl.rcParams['ytick.minor.size'] = 1.5
mpl.rcParams['ytick.major.width'] = 0.75

mpl.rcParams.update({'font.size': 10})
mpl.rcParams['axes.labelpad'] = 3.0

#--- Adjust gobal matplotlib variables
# mpl.rcParams['pdf.fonttype'] = 42
# mpl.rcParams['ps.fonttype'] = 42
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "10"
# plt.rcParams.update({'font.size': 22})
# mpl.rcParams["font.size"] = "11"
# mpl.rcParams['axes.grid'] = True

# plt.rc('font', family='serif', serif='Times')
# plt.rc('font', family='serif')
# # plt.rc('text', usetex=True)  #also works...
# plt.rc('xtick', labelsize=8)
# plt.rc('ytick', labelsize=8)
# plt.rc('axes', labelsize=8)





#---- Scale Figure apropriately to fit tex-File Width
# width = 452.9679

# width as measured in inkscape
# width = 6.28 *0.5
width = 6.28

height = width / 1.618
height = width / 2.5
#setup canvas first
fig = plt.figure()      #main
# fig, ax = plt.subplots()
# fig, (ax, ax2) = plt.subplots(ncols=2)
fig,ax = plt.subplots(nrows=1,ncols=3,figsize=(width,height)) # more than one plot


# --- set overall Title
# fig.suptitle('Example of a Single Legend Shared Across Multiple Subplots')

# fig.subplots_adjust(left=.15, bottom=.16, right=.99, top=.97)  #TEST


# TEST
# mpl.rcParams['figure.figsize'] = (width+0.1,height+0.1)
# fig = plt.figure(figsize=(width+0.1,height+0.1))


# mpl.rcParams['figure.figsize'] = (width,height)
# fig = plt.figure(figsize=(10,6)) # default is [6.4,4.8] 6.4 is the width, 4.8 is the height
# fig = plt.figure(figsize=(width,height)) # default is [6.4,4.8] 6.4 is the width, 4.8 is the height
# fig = plt.figure(figsize=set_size(width))
# fig = plt.subplots(1, 1, figsize=set_size(width))

# --- To create a figure half the width of your document:#
# fig = plt.figure(figsize=set_size(width, fraction=0.5))



#--- You must select the correct size of the plot in advance
# fig.set_size_inches(3.54,3.54)


# ---- TODO ?:
# ax[0] = plt.axes((0.15,0.18,0.8,0.8))


# ax.tick_params(axis='x',which='major', direction='out',pad=3)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# a=ax.yaxis.get_major_locator()
# b=ax.yaxis.get_major_formatter()
# c = ax.get_xticks()
# d = ax.get_xticklabels()
# print('xticks:',c)
# print('xticklabels:',d)

ax[0].grid(True,which='major',axis='both',alpha=0.3)
ax[1].grid(True,which='major',axis='both',alpha=0.3)
ax[2].grid(True,which='major',axis='both',alpha=0.3)
# ax.plot(Theta_Values,B1_Values , 'royalblue')
# ax.plot(Theta_Values,B2_Values , 'royalblue')

# l1 = ax[0].plot(Theta_Values,Q1_Values_beta05 , label=r"$\theta_\mu = 0.5$")
l2 = ax[0].plot(Theta_Values,Q1_Values_beta1 , label=r"$\theta_\mu = 1.0$")
l3 = ax[0].plot(Theta_Values,Q1_Values_beta2 , label=r"$\theta_\mu = 2.0$")
l4 = ax[0].plot(Theta_Values,Q1_Values_beta5 , label=r"$\theta_\mu = 5.0$")
l5 = ax[0].plot(Theta_Values,Q1_Values_beta10 , label=r"$\theta_\mu = 10.0$", color='orange')

# ax[0].set_xlabel(r"volume fraction $\theta$")
ax[0].set_xlabel(r"$\theta$",fontsize=10)
# ax[0]ax[2].set_title(r" $q_1/q_2$").set_ylabel(r" $q_1$")

# ax[0].set_title(r" $q_1$",fontsize=10)
ax[0].set_ylabel(r" $q_1$",rotation=0, fontsize=10, labelpad=8)


ax[0].xaxis.set_major_locator(MultipleLocator(0.25))
# Labels to use in the legend for each line
# line_labels = [r"$\theta_\mu  = 1.0$", r"$\theta_\mu  = 2.0$",  r"$\theta_\mu  = 5.0$", r"$\theta_\mu  = 10.0$"]
line_labels = [r"$\theta_\mu  = 1$", r"$\theta_\mu  = 2$",  r"$\theta_\mu  = 5$", r"$\theta_\mu  = 10$"]
# line_labels = [r"$\theta_\mu  = 0.5$",r"$\theta_\mu  = 1.0$", r"$\theta_\mu  = 2.0$",  r"$\theta_\mu  = 5.0$", r"$\theta_\mu  = 10.0$"]

# ax[1].plot(Theta_Values,Q2_Values_beta05  , label=r"$\theta_\rho = 0.5$")
ax[1].plot(Theta_Values,Q2_Values_beta1  , label=r"$\theta_\rho = 1.0$")
ax[1].plot(Theta_Values,Q2_Values_beta2  , label=r"$\theta_\rho = 2.0$")
ax[1].plot(Theta_Values,Q2_Values_beta5  , label=r"$\theta_\rho = 5.0$")
ax[1].plot(Theta_Values,Q2_Values_beta10 , label=r"$\theta_\rho = 10.0$",color='orange')

# ax[1].set_xlabel(r"volume fraction $\theta$")
ax[1].set_xlabel(r"$\theta$",fontsize=10)

ax[1].set_ylabel(r" $q_2$",rotation=0, fontsize=10, labelpad=8)
# ax[1].set_title(r" $q_2$",fontsize=10)

ax[1].xaxis.set_major_locator(MultipleLocator(0.25))
# ax[1].xaxis.set_minor_locator(MultipleLocator(0.05))


# ax[2].plot(Theta_Values,Q1_Values_beta05/Q2_Values_beta05  , label=r"$\theta_\rho = 0.5$",zorder=5)

ax[2].plot(Theta_Values,Q1_Values_beta1/Q2_Values_beta1  , label=r"$\theta_\rho = 1.0$")
ax[2].plot(Theta_Values,Q1_Values_beta2/Q2_Values_beta2  , label=r"$\theta_\rho = 2.0$")
ax[2].plot(Theta_Values,Q1_Values_beta5/Q2_Values_beta5  , label=r"$\theta_\rho = 5.0$")
ax[2].plot(Theta_Values,Q1_Values_beta10/Q2_Values_beta10 , label=r"$\theta_\rho = 10.0$", color='orange')

# ax[2].set_xlabel(r"volume fraction $\theta$")
ax[2].set_xlabel(r"$\theta$",fontsize=10)
# ax[2].set_ylabel(r" $q_1/q_2$")

# ax[2].set_ylabel(r" $q_1/q_2$",rotation=0, fontsize=10, labelpad=8)
ax[2].set_ylabel(r" $\frac{q_1}{q_2}$",rotation=0, fontsize=10, labelpad=8)
# ax[2].set_title(r" $q_1/q_2$",fontsize=10)
ax[2].xaxis.set_major_locator(MultipleLocator(0.25))




# plt.subplots_adjust(wspace=0.4, hspace=0.25)
# plt.subplots_adjust(hspace=0.15, wspace=0.25)
plt.subplots_adjust(hspace=0.1)
plt.subplots_adjust(wspace=0.8)
plt.tight_layout()



## LEGEND TO THE RIGHT
# legend = fig.legend([l2, l3, l4, l5],     # The line objects
#            labels=line_labels,   # The labels for each line
#            loc="center right",   # Position of legend
#            # borderaxespad=0.05    # Small spacing around legend box
#
#            borderaxespad=0.15,    # Small spacing around legend box
#            frameon=True
#            # title="Legend Title"  # Title for the legend
#            )

# plt.subplots_adjust(right=0.83) # if Legend to the Right!!




## PUT LEGEND ON BOTTOM /TOP
legend = fig.legend([l2, l3, l4, l5],     # The line objects
           labels=line_labels,   # The labels for each line
           loc="lower left",   # Position of legend
           # bbox_to_anchor=[1.0, 0.55],
           # bbox_to_anchor=[0.1, 1.0], # TOP
           bbox_to_anchor=[0.15, -0.07], # BOTTOM
           borderaxespad=0.15,    # Small spacing around legend box
           frameon=True,
           ncol = 4

           # title="Legend Title"  # Title for the legend
           )

frame = legend.get_frame()
frame.set_edgecolor('gray')


# fig.legend([l1, l2, l3, l4,l5],     # The line objects
#            labels=line_labels,   # The labels for each line
#            loc="center right",   # Position of legend
#            borderaxespad=0.15    # Small spacing around legend box
#            # title="Legend Title"  # Title for the legend
#            )

# Adjust the scaling factor to fit your legend text completely outside the plot
# (smaller value results in more space being made for the legend)





# ------------------ SAVE FIGURE
# tikzplotlib.save("TesTout.tex")
# plt.close()
# mpl.rcParams.update(mpl.rcParamsDefault)

# plt.savefig("graph.pdf",
#             #This is simple recomendation for publication plots
#             dpi=1000,
#             # Plot will be occupy a maximum of available space
#             bbox_inches='tight',
#             )
# plt.savefig("graph.pdf")




fig.set_size_inches(width, height)
# fig.savefig('Plot-q1q2-Theta.pdf')
fig.savefig('Plot-q1q2-Theta.pdf',dpi=300,bbox_extra_artists=(legend,),
            bbox_inches='tight')



# tikz_save('someplot.tex', figureheight='5cm', figurewidth='9cm')

# tikz_save('fig.tikz',
#            figureheight = '\\figureheight',
#            figurewidth = '\\figurewidth')

# ----------------------------------------


plt.show()
# #---------------------------------------------------------------