#!/usr/bin/env python
# coding: utf-8
# nazvy proměnných jsou v angličtině
# Ale komenty teda ne)
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
#from scipy.special import gamma, factorial
#import numpy as np
##import numpy.ma as ma
#import scipy.stats as stats
#
##import scipy.integrate as integrate
##from scipy.spatial import ConvexHull
##from scipy.spatial import cKDTree
#
#from scipy import spatial
#
##import lukiskon as lk
#import g_models
#import f_models
#
#import whitebox
#
##import itertools
#
## patří to asi do user kódu
## pro zobrazení v interaktivním okně (IPython)
## get_ipython().run_line_magic('matplotlib', 'nbagg')
#
#
#
#
## Estimation of pf given a list of red and green points (Voronoi)
##
#
#def show_shape(patch):
# ax=plt.gca()
# ax.add_patch(patch)
# #plt.axis('scaled')
# plt.show()
#
#def show_shape(patch, ax):
# ax.add_patch(patch)
# #plt.axis('scaled')
# plt.show()
#
#def draw_voronoi(ax, ns):
#
# plt=ax
#
# #%% Draw R-space
# r = 4 # tato r-ko v local namespace, vid?
#
# x = bx.sampled_plan.R[:ns,0]
# y = bx.sampled_plan.R[:ns,1]
#
# mask = bx.failsi[:ns]
#
#
# plt.plot(x[ mask], y[ mask], 'o', c='r' , markersize=1.0)
# plt.plot(x[~mask], y[~mask], 'o', c='g' , markersize=1.0)
#
# #for j, p in enumerate(sampled_plan_R):
# # plt.text(p[0]-0.0, p[1]+0.0, j, ha='right') # label the points
#
# if gm.__class__.__name__ == 'S_ball':
# xbound = np.linspace(-r, +r, 100)
# plt.plot(xbound, +np.sqrt(r**2 - xbound**2), '--', c = 'blue', linewidth = 0.5)
# plt.plot(xbound, -np.sqrt(r**2 - xbound**2), '--', c = 'blue', linewidth = 0.5)
#
#
# if gm.__class__.__name__ == 'Sin2D':
# xbound = np.linspace(-r, +r, 100)
# plt.plot(xbound,- xbound/4 + np.sin(5*xbound) + 6, '--', c = 'blue', linewidth = 0.5)
#
#
#
# tree = cKDTree(bx.sampled_plan.R[:ns])
#
# nis = 1500000
# pf = 0 # inicializace
# ps = 0
#
# points_weigths = np.zeros(len(bx))
# near_neighbors = np.zeros(len(bx))
# # loop over points (need to integrate red regions)
#
#
# # set the minimum distance as the standard deviation of IS densisty
# h_i = [stats.norm(0, 2) for j in range(nvar)] #! dosadit standard deviation pddle chutí
#
#
# # use IS sampling density with center equal to the current "red" point
#
# # select nis = 100 points from IS density and
# # if the point has its nearest neighbor any red point from the sampled_plan,
#
# h_plan = np.zeros((nis, nvar))
# for j in range(nvar):
# h_plan[:, j] = h_i[j].rvs(nis) # realizace váhové funkce náhodné veličiny
#
# # Rozptyl corrected IS
# weights_sim = bx.f.new_sample(h_plan).pdf_R / np.prod([h_i[j].pdf(h_plan[:, j])
# for j in range(nvar)], axis=0) # [f1/h1, ..., fn/hn]
#
#
#
# dd, ii = tree.query(h_plan)
#
# Vor_mask = np.empty(len(ii), dtype=bool)# np.where(ii==i, True, False)
#
# for k in range(len(ii)):
# #points_weigths[ii[k]] = points_weigths[ii[k]] + weights_sim[k] / nis
# #near_neighbors[ii[k]] = near_neighbors[ii[k]] + 1
# Vor_mask[k] = bx.failsi[ii[k]]
#
# pf = np.sum(weights_sim[Vor_mask])/nis
# #print(pf)
#
#
# # rohy. jasně
# #plt.plot(сэрегъёс_R[:,0], сэрегъёс_R[:,1], 'o', c='b' )
#
#
# x_grid = h_plan[:,0]
# y_grid = h_plan[:,1]
#
# marker_vole = matplotlib.markers.MarkerStyle(marker='.', fillstyle='full')
# plt.scatter(x_grid[ Vor_mask], y_grid[ Vor_mask], c='xkcd:pale rose' , s=0.125**2, edgecolors='face', marker=marker_vole, alpha=1 ) #'YlOrRd' cmap='Wistia',
# plt.scatter(x_grid[~Vor_mask], y_grid[~Vor_mask], c='xkcd:light seafoam green', s=0.125**2, edgecolors='face', marker=marker_vole, alpha=1 ) #'YlOrRd' cmap='Wistia',
#
#
# #ax0.plot(x_w[fail_wgP], y_w[fail_wgP], 's', color='xkcd:mango', markersize=1)
# # ax0.plot(x_w[fail_wsP], y_w[fail_wsP], 's', color='xkcd:light seafoam green', markersize=1)
# # ax0.plot(x_w[fail_w1P], y_w[fail_w1P], 's', color='xkcd:pale rose', markersize=1)
# # ax0.plot(x_w[fail_w2P], y_w[fail_w2P], 's', color='xkcd:khaki', markersize=1)
#
#
# #plt.xlim(-8, 8); plt.ylim(-8, 8)
# lim = 6.0
# ax.set_xlim(-lim, lim)
# ax.set_ylim(-lim, lim)
# ax.set_aspect('equal')
# #ax.set_xticks([-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6])
# #ax.set_yticks([-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6])
# ax.set_xticks([-6,-4,-2,0,2,4,6])
# ax.set_yticks([-6,-4,-2,0,2,4,6])
# #plt.axis('equal')
#
#
#
#
#
#
# #pf = np.sum(points_weigths[failsi]*1/near_neighbors[failsi])
# #pf = np.sum(points_weigths[failsi]) #/ nis / len(failure_points_indexes)
#
# print(pf)
#
#
## In[66]:
#
#
#
#
#from scipy.spatial import cKDTree
#
## workaround :D
#from matplotlib.axes._axes import _log as matplotlib_axes_logger
#matplotlib_axes_logger.setLevel("DEBUG")
#
#fig, ([ax1, ax2], [ax3, ax4]) = plt.subplots(nrows=2, ncols=2, figsize=(7, 6), tight_layout=True)
#
#nsim = bx.nsim
#
#draw_voronoi(ax1, int(nsim/8))
#ax1.set_title('n={0}'.format(int(nsim/8)))
#
#draw_voronoi(ax2, int(nsim/4))
#ax2.set_title('n={0}'.format(int(nsim/4)))
#
#draw_voronoi(ax3, int(nsim/2))
#ax3.set_title('n={0}'.format(int(nsim/2)))
#
#draw_voronoi(ax4, nsim)
#ax4.set_title('n={0}'.format(nsim))
##ax1.set_ylabel('U prostor')
##ax3.set_ylabel('R prostor')
##ax1.set_title('Teselace v U prostoru')
##ax2.set_title('Teselace v R prostoru')
#
#
#ax1.set_xlabel('$x_{1}$')
#ax1.set_ylabel('$x_{2}$')
#ax2.set_xlabel('$x_{1}$')
#ax2.set_ylabel('$x_{2}$')
#ax3.set_xlabel('$x_{1}$')
#ax3.set_ylabel('$x_{2}$')
#ax4.set_xlabel('$x_{1}$')
#ax4.set_ylabel('$x_{2}$')
#
##ax1.set_xlim(-8, 8)
##ax1.set_ylim(-8, 8)
##ax1.set_aspect('equal')
#
## plot unit circles for better orientation
#
#for ax in [ax1, ax2, ax3, ax4]:
# circle1 = plt.Circle((0, 0), 1, color='k', linewidth = 0.7, fill=False)
# circle2 = plt.Circle((0, 0), 2, color='k', linewidth = 0.5, fill=False)
# circle3 = plt.Circle((0, 0), 3, color='k', linewidth = 0.4, fill=False)
# circle4 = plt.Circle((0, 0), 4, color='k', linewidth = 0.3, fill=False)
# circle5 = plt.Circle((0, 0), 5, color='k', linewidth = 0.2, fill=False)
# circle6 = plt.Circle((0, 0), 6, color='k', linewidth = 0.1, fill=False)
# show_shape(circle1, ax)
# show_shape(circle2, ax)
# show_shape(circle3, ax)
##show_shape(circle4)
##show_shape(circle5)
##show_shape(circle6)
#
##plt.axis('square')
#
##fig.savefig("2x2_Deloneho_Zprod.png", dpi=300)
##fig.savefig("2x2.eps")
##fig.savefig("2x2.svg")
##fig.savefig("2x2.pdf")
def subplot3D(sample_box, ax3d, space='R'):
Fails = getattr(sample_box.failure_samples, space)
Succeses = getattr(sample_box.success_samples, space)
xyz = [0,1,2]
ax3d.scatter(Fails[:,xyz[0]], Fails[:,xyz[1]], Fails[:,xyz[2]], c='r', marker='.')
ax3d.scatter(Succeses[:,xyz[0]], Succeses[:,xyz[1]], Succeses[:,xyz[2]], c='g', marker='.')
ax3d.set_xlabel('X')
ax3d.set_ylabel('Y')
ax3d.set_zlabel('Z')
def plot3D(sample_box, space='R', filename=''):
if not filename:
filename = 'store/%s_%s_%s'%(sample_box.gm_signature, space, sample_box.nsim)
fig = plt.figure()
ax3d = fig.add_subplot(111, projection='3d')
subplot3D(sample_box, ax3d, space)
try: # jen pro formu zkusíme, vždyť musí funkce formálně něco dělat, žejo?
fig.savefig(filename + ".png")#, dpi=300)
except:
pass # nic se neděje
# vracím plt místo figury, protože nechcem sa trapiť ivent lupem
# return plt insted of just fig to bypass event loop issues
return plt
#
## nikdo mi neuvěří, že by tohle postačílo a nebylo by nutné tohlensto furt úpravovat
#def gp_plot(sample_box, space='R', terminal='png', filename=''):
# if not filename:
# filename = 'store/%s_%s_%s'%(sample_box.gm_signature, space, sample_box.nsim)
# if space in ['Rn', 'GK', 'G']:
# gp.c('set autoscale xy')
# gp.c('set size square')
# gp.c('set zeroaxis')
# elif space in ['P', 'U']:
# gp.c('set xrange [0:1]')
# gp.c('set yrange [0:1]')
# gp.c('set size square')
# #gp.c('set autoscale')
# gp.c('unset zeroaxis')
# else: # R teda?
# gp.c('set size noratio')
# gp.c('set autoscale')
# gp.c('unset zeroaxis')
#
# gp.c('set terminal ' + terminal)
# gp.c('set output "%s.%s"'%(filename, terminal))
# if os.name == 'posix':
# gp.c('set decimalsign locale "POSIX"')
#
# # legenda
# gp.c('unset key')
#
# # se mi zda, že gp bere data v řadcích
# f_name = "%s_failure.dat" % (filename)
# s_name = "%s_success.dat" % (filename)
# gp.s(getattr(sample_box.failure_samples, space).T, f_name)
# gp.s(getattr(sample_box.success_samples, space).T, s_name)
#
#
# # rozkaz, který předaváme gnuplotovi
# gp_plot = 'plot "%s" title "Success points" w p lc rgb "green", "%s" title "Failure points" w p lc rgb "red"' % (s_name, f_name)
#
# # Kružničky chcete?
# # Кружочки ннада?
# if space in ['Rn', 'G']:
# gp.c('set parametric')
# for i in range(5):
# lw = 2 - i*0.3
# gp_plot += ', cos(t)*%s,sin(t)*%s notitle w l lc rgb "black" lw %s'%(i+1, i+1, lw)
#
# # ne všichni majó definované hranice
# try:
# bounds = sample_box.get_2D_boundary()
#
# for i in range(len(bounds)):
# bound = getattr(bounds[i], space).T
# gp.s(bound, "%s_boundary_%s.dat"%(filename, i+1))
# gp_plot += ', "%s_boundary_%s.dat" notitle w l lc rgb "blue"'%(filename, i+1)
# except AttributeError:
# pass
#
# # Plot!
# gp.c(gp_plot)
#
#
#
## nikdo mi neuvěří, že by tohle postačílo a nebylo by nutné tohlensto furt úpravovat
#def plot(data2D, terminal='png', filename=''):
# if not filename:
# filename = 'store/plot_%s'%(len(data2D[0]))
#
# gp.c('set terminal ' + terminal)
# gp.c('set output "%s.%s"'%(filename, terminal))
# if os.name == 'posix':
# gp.c('set decimalsign locale "POSIX"')
#
#
# # se mi zda, že gp bere data v řadcích
# gp.s(data2D, filename+'.dat')
#
# # Plot!
# # rozkaz, který předaváme gnuplotovi
# gp.c('plot "%s.dat" ' % (filename))