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 = 10.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 = 20
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)

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)


B1_Values_beta05 = b1_Vec(rho1, 0.5, alpha ,Theta_Values)
B1_Values_beta1  = b1_Vec(rho1, 1.0, alpha ,Theta_Values)
B1_Values_beta2  = b1_Vec(rho1, 2.0, alpha ,Theta_Values)
B1_Values_beta10 = b1_Vec(rho1, 10, alpha  ,Theta_Values)
# ---
B2_Values_beta05 = b2_Vec(rho1, 0.5, alpha ,Theta_Values)
B2_Values_beta1  = b2_Vec(rho1, 1.0, alpha ,Theta_Values)
B2_Values_beta2  = b2_Vec(rho1, 2.0, alpha ,Theta_Values)
B2_Values_beta10 = b2_Vec(rho1, 10, alpha  ,Theta_Values)


# print('B1_Values:', B1_Values)
# print('B2_Values:', B2_Values)



# --- Convert to numpy array
# B1_Values = np.array(B1_Values)
# B2_Values  = np.array(B2_Values)
B1_Values_alphaNeg1  = np.array(B1_Values_alphaNeg1)
B1_Values_alphaNeg10  = np.array(B1_Values_alphaNeg10)
B1_Values_alpha2  = np.array(B1_Values_alpha2)
B1_Values_alpha10  = np.array(B1_Values_alpha10)
B2_Values_alphaNeg1  = np.array(B2_Values_alphaNeg1)
B2_Values_alphaNeg10  = np.array(B2_Values_alphaNeg10)
B2_Values_alpha2  = np.array(B2_Values_alpha2)
B2_Values_alpha10  = np.array(B2_Values_alpha10)



B1_Values_beta05= np.array(B1_Values_beta05)
B1_Values_beta1  = np.array(B1_Values_beta1 )
B1_Values_beta2  = np.array(B1_Values_beta2 )
B1_Values_beta10  = np.array(B1_Values_beta10 )
B2_Values_beta05  = np.array(B2_Values_beta05)
B2_Values_beta1  = np.array(B2_Values_beta1)
B2_Values_beta2  = np.array(B2_Values_beta2 )
B2_Values_beta10  = np.array(B2_Values_beta10)
# ---------------- Create Plot -------------------

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


#--- 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"] = "9"
# 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=2,ncols=2,figsize=(width,height)) # more than one plot
fig,ax = plt.subplots(nrows=2,ncols=2, figsize=(width,height)) # more than one plot

# --- set overall Title
# fig.suptitle('Example of a Single Legend Shared Across Multiple Subplots')
# fig.supxlabel(r'common')
# fig.supylabel(r'common')
# 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[0][0].tick_params(axis='x',which='major', direction='out',pad=3)
ax[0][0].tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
ax[0][0].xaxis.set_major_locator(MultipleLocator(0.25))
ax[0][0].xaxis.set_minor_locator(MultipleLocator(0.125))
ax[0][0].yaxis.set_major_locator(MultipleLocator(25))
# ax[0][0].yaxis.set_minor_locator(MultipleLocator(12.5))
# 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][0].grid(True,which='major',axis='both',alpha=0.3)
ax[0][1].grid(True,which='major',axis='both',alpha=0.3)
ax[1][0].grid(True,which='major',axis='both',alpha=0.3)
ax[1][1].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][0].plot(Theta_Values,B1_Values_alphaNeg1 , label=r"$\theta_\rho = -1.0$")
l2 = ax[0][0].plot(Theta_Values,B1_Values_alphaNeg10 , label=r"$\theta_\rho = -10.0$")
l3 = ax[0][0].plot(Theta_Values,B1_Values_alpha2 ,  label=r"$\theta_\rho = 2.0$")
l4 = ax[0][0].plot(Theta_Values,B1_Values_alpha10 , label=r"$\theta_\rho = 10.0$")
ax[0][0].set_xlabel(r"volume fraction $\theta$")
ax[0][0].set_ylabel(r"prestrain $b_1$")
# l1 = ax[0].plot(Theta_Values,B1_Values_beta05 , label=r"$\theta_\mu = -1.0$")
# l2 = ax[0].plot(Theta_Values,B1_Values_beta1 , label=r"$\theta_\mu = -10.0$")
# l3 = ax[0].plot(Theta_Values,B1_Values_beta2 , label=r"$\theta_\mu = 2.0$")
# l4 = ax[0].plot(Theta_Values,B1_Values_beta10 , label=r"$\theta_\mu = 10.0$")
l5 = ax[1][0].plot(Theta_Values,B1_Values_beta05 , label=r"$\theta_\mu = -1.0$")
l6 = ax[1][0].plot(Theta_Values,B1_Values_beta1 , label=r"$\theta_\mu = -10.0$")
l7 = ax[1][0].plot(Theta_Values,B1_Values_beta2 , label=r"$\theta_\mu = 2.0$")
l8 = ax[1][0].plot(Theta_Values,B1_Values_beta10 , label=r"$\theta_\mu = 10.0$")
ax[1][0].set_xlabel(r"volume fraction $\theta$")
ax[1][0].set_ylabel(r"prestrain $b_1$")

# Labels to use in the legend for each line
# line_labels = [r"$\theta_\rho = -1.0$", r"$\theta_\rho = -10.0$", r"$\theta_\rho = 2.0$", r"$\theta_\rho = 10.0$"]
line_labels = [r"$\theta_\rho = -1.0$", r"$\theta_\rho = -10.0$", r"$\theta_\rho = 2.0$", r"$\theta_\rho = 10.0$",
r"$\theta_\mu = -1.0$", r"$\theta_\mu = -10.0$", r"$\theta_\mu = 2.0$",r"$\theta_\mu = 10.0$" ]

ax[0][1].plot(Theta_Values,B2_Values_alphaNeg1 , label=r"$\theta_\rho = -1.0$")
ax[0][1].plot(Theta_Values,B2_Values_alphaNeg10 , label=r"$\theta_\rho = -10.0$")
ax[0][1].plot(Theta_Values,B2_Values_alpha2 , label=r"$\theta_\rho = 2.0$")
ax[0][1].plot(Theta_Values,B2_Values_alpha10 , label=r"$\theta_\rho = 10.0$")
ax[0][1].set_xlabel(r"volume fraction $\theta$")
ax[0][1].set_ylabel(r"prestrain $b_2$")
# ---------------
ax[1][1].plot(Theta_Values,B2_Values_beta05 , label=r"$\theta_\mu = -1.0$")
ax[1][1].plot(Theta_Values,B2_Values_beta1 ,  label=r"$\theta_\mu = -10.0$")
ax[1][1].plot(Theta_Values,B2_Values_beta2 ,  label=r"$\theta_\mu = 2.0$")
ax[1][1].plot(Theta_Values,B2_Values_beta10 , label=r"$\theta_\mu = 10.0$")
ax[1][1].set_xlabel(r"volume fraction $\theta$")
ax[1][1].set_ylabel(r"prestrain $b_2$")

plt.subplots_adjust(wspace=0.2, hspace=0)
plt.tight_layout()
# ax.plot(Theta_Values,B2_Values_alphaNeg1 )
# ax.plot(Theta_Values,B2_Values_alphaNeg10 )
# ax.plot(Theta_Values,B2_Values_alpha2 )
# ax.plot(Theta_Values,B2_Values_alpha10 )


# plt.figure()

# f,ax=plt.subplots(1)

# plt.title(r''+ yName + '-Plot')
# plt.plot(X_Values, Y_Values,linewidth=2, '.k')
# plt.plot(X_Values, Y_Values,'.k',markersize=1)
# plt.plot(X_Values, Y_Values,'.',markersize=0.8)

# plt.plot(X_Values, Y_Values)

# ax.plot([[0],X_Values[-1]], [Y_Values[0],Y_Values[-1]])



# Gamma = '0'
# ax.plot([x_plotValues[0],x_plotValues[1]], [y_plotValues[0],y_plotValues[1]] , 'b')
#
# ax.plot([x_plotValues[1],x_plotValues[3]], [y_plotValues[2],y_plotValues[3]] , 'b')
#
# ax.plot(x_rest, y_rest, 'b')


# Gamma between

# x jump values (gamma 0): [0.13606060606060608, 0.21090909090909093]

# ax.plot([[0,jump_xValues[0]], [0, 0]] , 'b')
# ax.plot([jump_xValues[0],xmin], [y_plotValues[2],y_plotValues[2]] , 'b')

# ax.plot([[0,0.13606060606060608], [0, 0]] , 'b')
# ax.plot([[0.13606060606060608,xmin], [(math.pi/2),(math.pi/2)]], 'b')

# jump_xValues[0]



# --- leave out jumps:
# ax.scatter(X_Values, Y_Values)







# ax.plot(X_Values[X_Values>0.136], Y_Values[X_Values>0.136])
# ax.plot(X_Values[X_Values<0.135], Y_Values[X_Values<0.135])
# ax.scatter(X_Values, Y_Values)
# ax.plot(X_Values, Y_Values)

# plt.plot(x_plotValues, y_plotValues,'.')
# plt.scatter(X_Values, Y_Values, alpha=0.3)
# plt.scatter(X_Values, Y_Values)
# plt.plot(X_Values, Y_Values,'.')
# plt.plot([X_Values[0],X_Values[-1]], [Y_Values[0],Y_Values[-1]])
# plt.axis([0, 6, 0, 20])

# ax.set_xlabel(r"volume fraction $\theta$", size=11)
# ax.set_ylabel(r"angle $\angle$",  size=11)


# plt.ylabel('$\kappa$')

# ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
# ax.yaxis.set_major_locator(ticker.MultipleLocator(base=0.1))





# -- SETUP LEGEND
# ax.legend(prop={'size': 11})
# ax[0].legend()
# ax[1].legend(
# loc='upper left',
# bbox_to_anchor=(1,1))

# Create the legend
# handles, labels = ax.get_legend_handles_labels()

fig.legend([l1, l2, l3, l4, l5, l6 ,l7 ,l8],     # 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)
plt.subplots_adjust(right=0.8)

# ------------------ 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-Prestrain-Theta.pdf')




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

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

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


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