iam-git / WellMet (public) (License: MIT) (since 2021-08-31) (hash sha1)
WellMet is pure Python framework for spatial structural reliability analysis. Or, more specifically, for "failure probability estimation and detection of failure surfaces by adaptive sequential decomposition of the design domain".

/mplot.py (1f6dd06a036fdc4ba6a7e6d61ac0b84e8ad3a4c1) (10489 bytes) (mode 100644) (type blob)

#!/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))


Mode Type Size Ref File
100644 blob 17849 203f064cce20b8609acab94c05532dbd06f77342 IS_stat.py
100644 blob 6 0916b75b752887809bac2330f3de246c42c245cd __init__.py
100644 blob 73746 db9cde38f6b1faa58bec875f056843900e4a2e26 blackbox.py
100644 blob 11243 10c424c2ce5e8cdd0da97a5aba74c54d1ca71e0d candybox.py
100644 blob 47075 3ad01c91c9781b03caf9d0365932c12eb1ccec5c estimation.py
100644 blob 19727 e5853e8cf897aa0ec37fa78bfdb96e91e248a90c f_models.py
100644 blob 31025 70bab60405bfe783a2f7a9f2c41b7c1629d3d474 g_models.py
100644 blob 41574 da5e578b81d9e14a42a4e89f9a4b609b96f17c84 gl_plot.py
100644 blob 2718 5d721d117448dbb96c554ea8f0e4651ffe9ac457 gp_plot.py
100644 blob 29393 96162a5d181b8307507ba2f44bafe984aa939163 lukiskon.py
100644 blob 10489 1f6dd06a036fdc4ba6a7e6d61ac0b84e8ad3a4c1 mplot.py
100644 blob 978 058034342d48b36604acee0d7fdee7be27ce2d68 plot.py
100644 blob 2807 1feb1d43e90e027f35bbd0a6730ab18501cef63a plotly_plot.py
100644 blob 86766 29b6cec674c3910073af358f14d2540be07c1210 qt_plot.py
100644 blob 6304 7fc6ac75e415df43af5b7aa9d6d1848aa5d0963d reader.py
100644 blob 4284 a0e0b4e593204ff6254f23a67652804db07800a6 samplebox.py
100644 blob 5553 bac994ae58f1df80c7f8b3f33955af5402f5a4f3 sball.py
100644 blob 5622 363efd38a88ba680b89aa500f1190ecff191fa52 simplex.py
100644 blob 21623 281aef80556b8d22842b8659f6f0b7dab0ad71af whitebox.py
Hints:
Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://rocketgit.com/user/iam-git/WellMet

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@ssh.rocketgit.com/user/iam-git/WellMet

Clone this repository using git:
git clone git://git.rocketgit.com/user/iam-git/WellMet

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a merge request:
... clone the repository ...
... make some changes and some commits ...
git push origin main