Skip to content

Commit

Permalink
save, quicker runs
Browse files Browse the repository at this point in the history
  • Loading branch information
csafta committed Mar 16, 2023
1 parent 3b58db6 commit 2631bd4
Show file tree
Hide file tree
Showing 6 changed files with 820 additions and 592 deletions.
5 changes: 2 additions & 3 deletions examples/kle_ex1/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ SET(copy_SRC_FILES
)

SET(copy_DAT_FILES
data/cali_grid.dat
data/cali_tria.dat
data/kl_prep_grid.py
data/cali.dat
)

SET(copy_SCRIPT_FILES
Expand Down Expand Up @@ -110,7 +110,6 @@ INSTALL(FILES ${copy_DAT_FILES}
DESTINATION examples/kle_ex1/data
)


# Copy over README file too
INSTALL(FILES README
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
Expand Down
188 changes: 188 additions & 0 deletions examples/kle_ex1/data/kl_prep_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
#!/usr/bin/env python
#=====================================================================================
#
# The UQ Toolkit (UQTk) version @UQTKVERSION@
# Copyright (@UQTKYEAR@) NTESS
# https://www.sandia.gov/UQToolkit/
# https://github.com/sandialabs/UQTk
#
# Copyright @UQTKYEAR@ National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government
# retains certain rights in this software.
#
# This file is part of The UQ Toolkit (UQTk)
#
# UQTk is open source software: you can redistribute it and/or modify
# it under the terms of BSD 3-Clause License
#
# UQTk is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# BSD 3 Clause License for more details.
#
# You should have received a copy of the BSD 3 Clause License
# along with UQTk. If not, see https://choosealicense.com/licenses/bsd-3-clause/.
#
# Questions? Contact the UQTk Developers at <[email protected]>
# Sandia National Laboratories, Livermore, CA, USA
#=====================================================================================
import argparse
import matplotlib.pyplot as plt
import matplotlib.tri as tri
from matplotlib.lines import Line2D
import numpy as np
import math

THRSMALL = 1.e-6

def trArea(t0, t1, t2):
'''
Area of a 2D triangle
'''
return abs(t0[0]*(t1[1]-t2[1])+t1[0]*(t2[1]-t0[1])+t2[0]*(t0[1]-t1[1]))/2.0

def checkPtInside(borders,x,y):
nm=len(x);
umask=np.zeros(nm)
for i in range(nm):
b=y[i]-x[i];
nint = 0;
for brd in borders:
xc=brd[:,0];
yc=brd[:,1];
for j in range(xc.shape[0]-1):
if abs(xc[j]-xc[j+1]) < 1.0e-30:
yi=xc[j]+b;
if (xc[j]<=x[i]) & ((yi-yc[j])*(yi-yc[j+1])<=0.0):
nint = nint+1;
else:
a1=(yc[j+1]-yc[j]) / (xc[j+1]-xc[j]);
b1=yc[j]-a1*xc[j];
xi=(b1-b)/(1.0-a1);
if (xi<=x[i]) & ((xi-xc[j])*(xi-xc[j+1])<=0.0):
nint = nint+1;
if ( nint%2 == 0 ):
umask[i]=1;
return umask;


def check_Point_In_Region(borders, x, y):
b = y - x
for region in borders:
nint = 0
xc = region[:,0]
yc = region[:,1]
for j in range(xc.shape[0]-1):
if abs(xc[j]-xc[j+1]) < 1.0e-30:
yi = xc[j] + b
if (xc[j] <= x) & ((yi-yc[j]) * (yi-yc[j+1]) <= 0.0):
nint = nint+1
else:
a1 = (yc[j+1]-yc[j]) / (xc[j+1]-xc[j])
b1 = yc[j]-a1*xc[j]
xi = (b1-b) / (1.0-a1)
if (xi<=x) & ((xi-xc[j])*(xi-xc[j+1])<=0.0):
nint = nint+1
if ( nint%2 == 1 ):
return True
return False

def gen_samples_region(regions, npoints, seed = 2020):
'''
Generate samples inside a set of regions
'''

xmin,xmax = min([bnd[:,0].min() for bnd in regions]), max([bnd[:,0].max() for bnd in regions])
ymin,ymax = min([bnd[:,1].min() for bnd in regions]), max([bnd[:,1].max() for bnd in regions])

np.random.seed(seed)
i = 0
xy = np.zeros((npoints,2))
while i<npoints:
x = np.random.uniform(xmin,xmax)
y = np.random.uniform(ymin,ymax)
if check_Point_In_Region(regions, x, y):
xy[i] = np.array([x,y])
i=i+1

for region in regions:
xy = np.vstack((xy,region))

return xy


def main():

# Parse aeguments
parser = argparse.ArgumentParser(prog='kl_prep',
description='Generate triangulation over a generic area')
parser.add_argument('-r','--regions', dest='regions', nargs='+', type=str, help='''list of regions''')
parser.add_argument('-n','--npoints', dest='npoints', type=int, default = 256, help='''num. points''')
parser.add_argument('-o','--output', dest='output', type=str, default = '', help='''output''')
parser.add_argument('-s','--seed', dest='seed', type=int, default = 2020, help='''num. points''')
args = parser.parse_args()

print('Regions:', args.regions)
print('No. of samples:', args.npoints)
print('Output arguments:', args.output)

# read boundaries
borders = []
for i in args.regions:
borders.append(np.genfromtxt(i+'.dat'))

# generate samples
xy = gen_samples_region(borders, args.npoints, seed = args.seed)

# Create triangulation
triang = tri.Triangulation(xy[:,0],xy[:,1])
xmid = xy[triang.triangles,0].mean(axis=1)
ymid = xy[triang.triangles,1].mean(axis=1)

# Mask off unwanted triangles
mask = np.zeros(triang.triangles.shape[0])
for ii, t in enumerate(triang.triangles):
if not check_Point_In_Region(borders, xmid[ii], ymid[ii]):
mask[ii] = 1

triang.set_mask(mask)
triangles_valid = triang.get_masked_triangles()

np.savetxt('cali_grid'+args.output+'.dat', xy, fmt='%.10e %.10e', delimiter=' ', newline='\n')
np.savetxt('cali_tria'+args.output+'.dat', triangles_valid, fmt='%d %d %d', delimiter=' ', newline='\n')

# plot samples and triangles
fig1 = plt.figure(figsize=[8,7])
fig2 = plt.figure(figsize=[8,7])
ax1 = fig1.add_axes([0.12,0.12,0.85,0.85])
ax2 = fig2.add_axes([0.12,0.12,0.85,0.85])

ax1.scatter(xy[:,0], xy[:,1], s=6)
for k in range(len(triangles_valid)):
x1, x2, x3 = xy[triangles_valid[k,:], 0]
y1, y2, y3 = xy[triangles_valid[k,:], 1]
aaa = ax2.add_line(Line2D([x1,x2],[y1,y2]))
aaa = ax2.add_line(Line2D([x2,x3],[y2,y3]))
aaa = ax2.add_line(Line2D([x3,x1],[y3,y1]))

for brd in borders:
ax1.plot(brd[:,0], brd[:,1], 'r', lw=3)
ax2.plot(brd[:,0], brd[:,1], 'r', lw=3)

for ax in [ax1, ax2]:
ax.set_aspect('equal')
ax.set_xlabel("longitude", fontsize=18)
ax.set_ylabel("latitude",fontsize=18)
for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks():
tick.label.set_fontsize(14)

fig1.savefig('cali_pts'+args.output+'.pdf')
fig2.savefig('cali_tri'+args.output+'.pdf')
plt.close(fig1)
plt.close(fig2)
#plt.show()


if __name__ == "__main__":
main()

57 changes: 39 additions & 18 deletions examples/kle_ex1/kl_2D.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
#define GTYPE "cl0L"
#define AFAC 0.5
#define BFAC 1.1
#define NX 65
#define NY 65
#define NX 33
#define NY 33
#define DLEN 1.0

#define COVTYPE "SqExp"
Expand Down Expand Up @@ -163,13 +163,13 @@ int main(int argc, char *argv[])
cout << " - Standard deviation: " << sigma<< endl<<flush;
cout << " - Number of KL modes: " << nkl << endl<<flush;
if ( cflag )
cout<<" - Will generate covariance of type "<<cov_type<<endl<<flush;
cout<<" - Generate covariance of type "<<cov_type<<endl<<flush;
else
cout << " - Will generate covariance from "<<nspl<<" samples" << endl<<flush;
if ( xflag )
cout<<" - Will read grid from file: "<<xfile<<endl<<flush;
cout << " - Generate covariance from "<<nspl<<" samples" << endl<<flush;
if ( xflag )
cout<<" - Read grid from file: "<<xfile<<endl<<flush;
else
cout << " - Will create grid with "<<nx<<"x"<<ny<<" points" << endl<<flush;
cout << " - Create grid with "<<nx<<"x"<<ny<<" points" << endl<<flush;

/* read grid from file or generate uniform grid on [0,1] */
if ( xflag ) {
Expand Down Expand Up @@ -198,9 +198,6 @@ int main(int argc, char *argv[])
for ( int j = 0; j < nxy; j++)
cov(i,j)=genCovAnl2D(xygrid,i,j,clen,sigma,cov_type);
}
// else {
// read_datafile(cov,"cov.dat");
// }
else {

double dfac=1.0e-11;
Expand All @@ -209,42 +206,65 @@ int main(int argc, char *argv[])
while ( ( tryagain ) && ( dfac < 1.e-6 ) ) {
tryagain = false ;
for ( int i = 0; i < nxy; i++)
for ( int j = 0; j < nxy; j++)
cov(i,j)=genCovAnl2D(xygrid,i,j,clen,sigma,string("SqExp"));
for ( int j = 0; j < nxy; j++) {
cov(i,j) = genCovAnl2D(xygrid,i,j,clen,sigma,string("SqExp"));
//cov(j,i) = cov(i,j);
}
for ( int i = 0; i < nxy; i++)
cov(i,i) += dfac;
//write_datafile( cov, "cov.dat" );

/* Generate samples */
cout << " - Cholesky decomposition" << endl<<flush;

char *lu = (char *) "L";
int info ;
FTN_NAME(dpotrf)( lu, &nxy, cov.GetArrayPointer(), &nxy, &info );

/* Check the success in Cholesky factorization */
if ( info != 0 ) {

cout<<"Error in Cholesky factorization, info=" << info << endl << flush ;;
cout << "Error in Cholesky factorization, info=" << info << endl << flush ;;
dfac = dfac * 10.0 ;
tryagain = true ;
cout<<" will try again with diagonal factor" << dfac << endl << flush ;;
cout << " will try again with diagonal factor" << dfac << endl << flush ;;

} /* done if Cholesky factorization fails */
}
dsfmt_t rnstate ;
int rseed=20120828;
dsfmt_init_gen_rand(&rnstate, (uint32_t) rseed );

float progress = 0.0;
int barWidth = 70;
cout << " - Generate samples" << endl<<flush;
Array1D<double> randSamples(nxy,0.0);
ySamples.Resize(nxy,nspl,0.0);
ySamples.Resize(nxy, nspl, 0.0);
for ( int j = 0; j < nspl; j++) {

if (float(j) / nspl > progress+0.01) {

cout << " [";
int pos = barWidth * progress;
for (int ii = 0; ii< barWidth; ++ii) {
if (ii < pos) cout << "=";
else if (ii == pos) cout << ">";
else cout << " ";
}
cout << "] " << int(progress * 100.0) << " %\r";
cout << flush;
progress += 0.01;
}

for (int i = 0 ; i < nxy ; i++ )
randSamples(i) = dsfmt_genrand_nrv(&rnstate);
for ( int i = 0; i < nxy; i++ ) {
ySamples(i,j)=0.0;
for ( int k = 0; k < i+1; k++)
ySamples(i,j) += (cov.GetArrayPointer())[i+k*nxy]*randSamples(k);
ySamples(i,j) += (cov.GetArrayPointer())[i+k*nxy] * randSamples(k);
}
}
cout << endl << flush;
if (sflag) write_datafile( ySamples, "samples.dat" );

/* Compute samples mean */
Expand All @@ -254,6 +274,7 @@ int main(int argc, char *argv[])
write_datafile_1d( mean, "mean.dat" );

/* Compute covariance matrix */
cout << " --> Compute covariance matrix from samples " << endl;

/* 1. subtract the mean from samples */
for ( int j = 0 ; j < nspl ; j++)
Expand All @@ -265,8 +286,8 @@ int main(int argc, char *argv[])
for ( int j = i; j < nxy; j++ ) {

double dsum=0.0;
for(int k = 0; k < nspl; k++ )
dsum += ySamples(i,k)*ySamples(j,k);
for (int k = 0; k < nspl; k++ )
dsum += ySamples(i,k) * ySamples(j,k);

cov(i,j) = dsum/( (double) nspl );
}
Expand Down
Loading

0 comments on commit 2631bd4

Please sign in to comment.