from paraview.simple import *
CreateLayout('S11')
pythonView1 = CreateView('PythonView')
# SetActiveView(FindView('RenderView1'))
layout2 = GetLayoutByName("S11")
RemoveLayout(GetLayoutByName("Layout #1"))
#AssignViewToLayout(view=pythonView1, layout=layout2, hint=0)
layout2.AssignView(0, pythonView1)


pythonView1.Script = '''frequency_range = [] #(MHz)
# Click anywhere on the charts
# to update the view

cases = %s

xAxName = "Frequency" #Default x axis title
xAxUnit = "Hz" #Default x axis unit

lineWidth = 0.5 #Plot line thickness
markerSize = 3.0 #Plot point size

legendLoc = "best" #legend location
legendSize = 10 #Font size for legend

threshold = 0.02 #If the relative delta of the data is below this, the y axis is scaled
scaleCoef = 4.0 #By how much the y-axis is scales if data has minute delta.

spRows = 1 #Number of subplot rows
spCols = 1 #Number of subplot columns

import re
import json
import os
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter
from paraview import python_view

masterCaseJson = json.load(open(os.path.join(os.getcwd(), "case.json")))
parametricCasesJson = masterCaseJson["parametric"]["cases"]

caseDir = os.path.join(os.getcwd(), cases[0])
resultDir = os.path.join(caseDir, 'results')
resultData = json.load(open(os.path.join(resultDir, 'resultData.json'), encoding='utf-8'))
globalResultsData = json.load(open(os.path.join(resultDir, 'globalResultsFile.json'), encoding='utf-8'))

def getTimeValues():
    bc = globalResultsData["bcs"][0]["time"]["timeValues"]
    return(bc)

def getBCValues(name, post):
    bcs = globalResultsData["bcs"]
    for bc in bcs:
        if bc["name"] == name:
            for p in bc["postValues"]:
                if p["postName"] == post:
                    return(p["values"])

def getDomainValues(name, post):
    domainList = globalResultsData["domains"]
    for domain in domainList:
        if domain["name"] == name:
            for p in domain["postValues"]:
                if p["postName"] == post:
                    return(p["values"])

def getValues(name, post):
	d = getDomainValues(name, post)
	if d is not None:
		return(d)
	else:
		d = getBCValues(name, post)
		return(d)

def plot(rows, cols, pos, x, y, xUnit, yUnit, title, xlabel, ylabel, leg):
	if ylabel == "Inductance":
		my_new_list = [i / 1000 for i in y]
		y = my_new_list
		new_unit = yUnit[1:]
		yUnit = new_unit

	ax = fig.add_subplot(rows, cols, pos)
	ax.tick_params(axis="both", direction = "in", length = 4, color='#DDDDDD')
	ax.plot(x, y, linewidth=lineWidth, marker="o", markersize=markerSize, label=leg)
	ax.xaxis.set_major_formatter(EngFormatter(unit=xUnit))
	ax.yaxis.set_major_formatter(EngFormatter(unit=yUnit))
	ax.set_title(title, color='#222222', pad=16)
	ax.set_xlabel(xlabel)
	ax.set_ylabel(ylabel)
	ax.grid(color='#DDDDDD', linestyle='-', linewidth=0.5)
	ax.tick_params(axis="both", direction = "in", length = 4, color='#DDDDDD', labelsize=9)
	ax.set_facecolor("#FFFFFF")

	if max(y) == 0:
		delta_rel = 0
	else:
		delta_rel = (max(y) - min(y)) / max(y)
	if 0.00001 < delta_rel < threshold:
		ax.set_ylim([min(y)*(1.0 - delta_rel * scaleCoef), max(y)* (1.0 + delta_rel * scaleCoef)])
	if frequency_range:
		ax.set_xlim([i*10**6 for i in frequency_range])	
	return(ax)

def plotAddLine(ax, yValues, legend):
	ax.plot(x, yValues, linewidth=lineWidth, marker="o", markersize=markerSize, label=legend)
	ax.legend(loc=legendLoc, frameon=False, prop={'size': legendSize})


if resultData['boundariesByType']["physicsMicrowaves"]["uniformPort"]:
	portName = resultData['boundariesByType']["physicsMicrowaves"]["uniformPort"]
else:
	portName = resultData['boundariesByType']["physicsMicrowaves"]["coaxialPort"]




fig = plt.figure()
matplotlib.use #global plot style
plt.style.use('ggplot') #global plot style

is_first_line = True
for subcase in cases:
    for i in parametricCasesJson:
        if i["path"] == subcase:
            name = i["name"]
    if not name:
        raise RuntimeError(f"Subcase name not found for {subcase}")

    subCaseDir = os.path.join(os.getcwd(), subcase)
    subResultDir = os.path.join(subCaseDir, 'results')
    resultData = json.load(open(os.path.join(subResultDir, 'resultData.json'), encoding='utf-8'))
    globalResultsData = json.load(open(os.path.join(subResultDir, 'globalResultsFile.json'), encoding='utf-8'))

    x1 = getTimeValues()
    x = [element * 10**6 for element in x1]
    S11 = getBCValues(portName[0], "S11[dB]")

    if is_first_line:
        ax = plot(spRows, spCols, 1, x, S11, xAxUnit, "dB", "S11", xAxName, " ", name)
        is_first_line = False
    else:
        plotAddLine(ax, S11, name)


fig.tight_layout(pad=0.2, w_pad=-5.5, h_pad=0.0, rect=[-0.06,0.0,0.99,1])

# this gets called by ParaView
def render(view, width, height):
	DPI = fig.get_dpi()
	fig.set_size_inches(width/float(DPI),height/float(DPI))
	return python_view.figure_to_image(fig)

plt.close('all')

''' % (str(subcases))

RenderAllViews()

