Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modifications using numpy operations, CI #9

Merged
merged 51 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
3e6c03e
trying to implement auto testing
Mar 13, 2024
2f7b624
trying to implement auto testing
Mar 13, 2024
f90e745
trying to implement auto testing
Mar 13, 2024
75e92b2
trying to implement auto testing
Mar 13, 2024
08b668a
implement CI
Mar 14, 2024
269dcb5
implement CI
Mar 14, 2024
65bd967
implement CI
Mar 14, 2024
3faa6eb
implement CI
Mar 14, 2024
e1228b6
implement CI
Mar 14, 2024
09d1aa0
CI implement
Mar 14, 2024
ab3aaf0
testing script added
Mar 14, 2024
4f7f694
implement CI fix
Mar 14, 2024
3f556ba
mpi hang not observed if plt.show() not last line
Mar 14, 2024
21d5b36
plt.show() not hanging with multiproc
Mar 14, 2024
8e0e656
possible memory issue needs to be fixed
Mar 15, 2024
51ae577
testing suite comments removed
Mar 15, 2024
dee84e5
possible memory issue
Mar 15, 2024
20bec60
investigatingmemory usage
Mar 15, 2024
9906551
updated testing suite file
Mar 15, 2024
d773a21
unit tests update v_1
Mar 15, 2024
2da1208
updated Dockerfile to test memory usage
Mar 15, 2024
4882861
updated testing file
Mar 16, 2024
6062ee5
CI attempt
Mar 16, 2024
48857d7
removed mem_prof import
Mar 16, 2024
29c38f2
update test file
Mar 16, 2024
94ab33c
update CI from 4 proc to 2 proc
Mar 16, 2024
f80fc13
testing if CI fails
Mar 16, 2024
cfc422a
testing suite working as expected
Mar 16, 2024
086a453
clean up
Mar 16, 2024
6660458
testing CI v_1
Mar 16, 2024
a6743bd
testing CI v_1
Mar 16, 2024
7637683
testing CI v_1
Mar 16, 2024
dd564d7
testing CI - expected to fail
Mar 16, 2024
c5a8b82
checking CI after minor changes to return values from modelVerify
Mar 16, 2024
0c5567e
changes to testing suite
Mar 16, 2024
c9ea067
removed testing folder from example folder
Mar 16, 2024
894a510
final change _v1
Mar 16, 2024
a3ba6ba
merged changes
Mar 18, 2024
00fb8b2
removed files
Mar 18, 2024
8cacc43
minor fixes, MPI hang for multiproc pact with destructor in PDEProblem
Mar 18, 2024
1c390ab
MPI lag fixed
Mar 18, 2024
551bbbb
removing commented code
Mar 18, 2024
776e6e8
prior del method, jacobi pc
Mar 19, 2024
b76c9ce
need to fix Regularization.py
Mar 19, 2024
7a50535
Update Regularization.py
uvilla Mar 19, 2024
5ffc3f8
Update prior.py
uvilla Mar 19, 2024
f83d5d4
Update model.py
uvilla Mar 19, 2024
dc78353
Update prior.py
uvilla Mar 19, 2024
9a0e8c2
Update Regularization.py
uvilla Mar 19, 2024
c56ec63
regularization prior example added
Mar 19, 2024
bf55be1
clean up
Mar 19, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .github/workflows/CI_testing.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: CI
on:
push:
branches:
- numpy_debug_v2
uvilla marked this conversation as resolved.
Show resolved Hide resolved

defaults:
run:
shell: bash -l {0}
jobs:
style:
runs-on: ubuntu-22.04
container:
image: dolfinx/dolfinx:stable
options: --user 1001 --privileged
name: CI test
steps:
- name: run code
uses: actions/checkout@v2
- name: run serial check
run: |
cd ./hippylibX/test &&
output=$(mpirun -n 1 python3 testing_suite_file.py) &&
uvilla marked this conversation as resolved.
Show resolved Hide resolved
if [[ "$output" == "1" ]]; then
exit 1
fi

- name: run parallel check
run: |
cd ./hippylibX/test &&
output=$(mpirun -n 2 python3 testing_suite_file.py) &&
uvilla marked this conversation as resolved.
Show resolved Hide resolved
if [[ "$output" == "1" ]]; then
exit 1
fi


1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
FROM dolfinx/dolfinx:stable
MAINTAINER Venugopal Ranganathan <[email protected]>
RUN pip install memory_profiler
RUN pip install psutil
35 changes: 22 additions & 13 deletions example/poisson_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@
import os
import dolfinx.fem.petsc


from matplotlib import pyplot as plt

sys.path.append( os.environ.get('HIPPYLIBX_BASE_DIR', "../") )

import hippylibX as hpx

def master_print(comm, *args, **kwargs):
Expand Down Expand Up @@ -94,7 +92,7 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
d.x.scatter_forward()

misfit_form = PoissonMisfitForm(d,noise_variance)
misfit = hpx.NonGaussianContinuousMisfit(msh, Vh, misfit_form)
misfit = hpx.NonGaussianContinuousMisfit(Vh, misfit_form)

prior_mean = dlx.fem.Function(Vh_m)
prior_mean.x.array[:] = 0.01
Expand All @@ -108,17 +106,16 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
hpx.parRandom.normal(1.,noise)
prior.sample(noise,m0)

hpx.modelVerify(comm,model,m0,is_quadratic=False,misfit_only=True,verbose=(rank == 0))
hpx.modelVerify(comm,model,m0,is_quadratic=False,misfit_only=False,verbose=(rank == 0))

eps, err_grad, err_H,rel_symm_error = hpx.modelVerify(model,m0,is_quadratic=False,misfit_only=True,verbose=(rank == 0))
uvilla marked this conversation as resolved.
Show resolved Hide resolved

# eps, err_grad, err_H = hpx.modelVerify(comm,model,m0,is_quadratic=False,misfit_only=True,verbose=(rank == 0))
data_misfit_True = {"eps":eps,"err_grad":err_grad, "err_H": err_H, "sym_Hessian_value":rel_symm_error}

# if(rank == 0):
# print(err_grad,'\n')
# print(err_H)
# plt.show()

eps, err_grad, err_H,rel_symm_error = hpx.modelVerify(model,m0,is_quadratic=False,misfit_only=False,verbose=(rank == 0))

data_misfit_False = {"eps":eps,"err_grad":err_grad, "err_H": err_H, "sym_Hessian_value":rel_symm_error}

# # #######################################

prior_mean_copy = prior.generate_parameter(0)
Expand Down Expand Up @@ -151,18 +148,30 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
master_print (comm, "Termination reason: ", solver.termination_reasons[solver.reason])
master_print (comm, "Final gradient norm: ", solver.final_grad_norm)
master_print (comm, "Final cost: ", solver.final_cost)

optimizer_results = {}
if(solver.termination_reasons[solver.reason] == 'Norm of the gradient less than tolerance'):
optimizer_results['optimizer'] = True
else:
optimizer_results['optimizer'] = False

#######################################

final_results = {"data_misfit_True":data_misfit_True,
"data_misfit_False":data_misfit_False,
"optimizer_results":optimizer_results}


return final_results


#######################################

if __name__ == "__main__":
nx = 64
ny = 64
noise_variance = 1e-4
prior_param = {"gamma": 0.1, "delta": 1.}
run_inversion(nx, ny, noise_variance, prior_param)


plt.savefig("poisson_result_FD_Gradient_Hessian_Check")
uvilla marked this conversation as resolved.
Show resolved Hide resolved
plt.show()

34 changes: 25 additions & 9 deletions example/sfsi_toy_gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import os
import dolfinx.fem.petsc


from matplotlib import pyplot as plt

sys.path.append( os.environ.get('HIPPYLIBX_BASE_DIR', "../") )
Expand Down Expand Up @@ -61,7 +60,6 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
comm = MPI.COMM_WORLD
rank = comm.rank
nproc = comm.size

fname = 'meshes/circle.xdmf'
fid = dlx.io.XDMFFile(comm,fname,"r")
msh = fid.read_mesh(name='mesh')
Expand Down Expand Up @@ -110,7 +108,7 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
d.x.scatter_forward()

misfit_form = PACTMisfitForm(d, noise_variance)
misfit = hpx.NonGaussianContinuousMisfit(msh, Vh, misfit_form)
misfit = hpx.NonGaussianContinuousMisfit(Vh, misfit_form)

prior_mean = dlx.fem.Function(Vh_m)
prior_mean.x.array[:] = 0.01
Expand All @@ -124,14 +122,15 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
hpx.parRandom.normal(1.,noise)
prior.sample(noise,m0)

hpx.modelVerify(comm,model,m0,is_quadratic=False,misfit_only=True,verbose=(rank == 0))
hpx.modelVerify(comm,model,m0,is_quadratic=False,misfit_only=False,verbose=(rank == 0))

# if(rank == 0):
# print(err_grad,'\n')
# print(err_H)
# plt.show()
eps, err_grad, err_H,rel_symm_error = hpx.modelVerify(model,m0,is_quadratic=False,misfit_only=True,verbose=(rank == 0))
uvilla marked this conversation as resolved.
Show resolved Hide resolved

data_misfit_True = {"eps":eps,"err_grad":err_grad, "err_H": err_H, "sym_Hessian_value":rel_symm_error}

eps, err_grad, err_H,rel_symm_error = hpx.modelVerify(model,m0,is_quadratic=False,misfit_only=False,verbose=(rank == 0))

data_misfit_False = {"eps":eps,"err_grad":err_grad, "err_H": err_H, "sym_Hessian_value":rel_symm_error}

# #######################################

prior_mean_copy = prior.generate_parameter(0)
Expand Down Expand Up @@ -166,6 +165,21 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
master_print (comm, "Final gradient norm: ", solver.final_grad_norm)
master_print (comm, "Final cost: ", solver.final_cost)


optimizer_results = {}
if(solver.termination_reasons[solver.reason] == 'Norm of the gradient less than tolerance'):
optimizer_results['optimizer'] = True
else:
optimizer_results['optimizer'] = False


final_results = {"data_misfit_True":data_misfit_True,
"data_misfit_False":data_misfit_False,
"optimizer_results":optimizer_results}

return final_results


#######################################

if __name__ == "__main__":
Expand All @@ -174,5 +188,7 @@ def run_inversion(nx : int, ny : int, noise_variance : float, prior_param : dict
noise_variance = 1e-6
prior_param = {"gamma": 0.05, "delta": 1.}
uvilla marked this conversation as resolved.
Show resolved Hide resolved
run_inversion(nx, ny, noise_variance, prior_param)
plt.savefig("qpact_result_FD_Gradient_Hessian_Check")
uvilla marked this conversation as resolved.
Show resolved Hide resolved
plt.show()


36 changes: 36 additions & 0 deletions example/testing_folder/test_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import numpy as np
uvilla marked this conversation as resolved.
Show resolved Hide resolved
import pickle

with open('outputs.pickle', 'rb') as f:
data = pickle.load(f)

xvals = data["xvals"]
arr_1 = data['arr_1']
arr_2 = data['arr_2']
value = data['sym_Hessian_value']

if(value > 1e-10):
print("1")
exit

#values from arr_1
relevant_values_1, relevant_values_2 = arr_1[10:], arr_2[10:]

x = xvals[10:]

data = relevant_values_1
y = data
coefficients = np.polyfit(np.log(x), np.log(y), 1)
slope_1 = coefficients[0]

data = relevant_values_2
y = data
coefficients = np.polyfit(np.log(x), np.log(y), 1)
slope_2 = coefficients[0]


if(np.abs(slope_1 - 1) > 1e-1 or np.abs(slope_2 - 1) > 1e-1):
print("1")
exit

print("0")
1 change: 0 additions & 1 deletion hippylibX/algorithms/NewtonCG.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,6 @@ def _solve_ls(self,x):
gradnorm_ini = gradnorm
tol = max(abs_tol, gradnorm_ini*rel_tol)

# print(tol)

# check if solution is reached
if (gradnorm < tol) and (self.it > 0):
Expand Down
2 changes: 1 addition & 1 deletion hippylibX/algorithms/linSolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

uvilla marked this conversation as resolved.
Show resolved Hide resolved

#I don't use either of the following 2 functions for now,
# currently just using this in the _createLUSolver method in
# currently just using the following: in the _createLUSolver method in
# the PDEVariationalProblem class in modeling/PDEProblem.py file

# def _createLUSolver(self):
Expand Down
12 changes: 10 additions & 2 deletions hippylibX/modeling/PDEProblem.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,19 @@ def setLinearizationPoint(self,x : list, gauss_newton_approx) -> None:
self.solver_adj_inc.setOperators(self.At)

if gauss_newton_approx:
if(self.Wuu is not None):
uvilla marked this conversation as resolved.
Show resolved Hide resolved
self.Wuu.destroy()

uvilla marked this conversation as resolved.
Show resolved Hide resolved
self.Wuu = None

if(self.Wmu is not None):
self.Wmu.destroy()
uvilla marked this conversation as resolved.
Show resolved Hide resolved
self.Wmu = None

if(self.Wmm is not None):
self.Wmm.destroy()
self.Wmm = None

else:

if self.Wuu is None:
Expand All @@ -265,8 +275,6 @@ def setLinearizationPoint(self,x : list, gauss_newton_approx) -> None:
self.Wmu = self.Wum.copy()
self.Wmu.transpose()

# print(self.Wum.isTranspose(self.Wmu)) #True

if self.Wmm is None:
self.Wmm = dlx.fem.petsc.create_matrix(dlx.fem.form(ufl.derivative(g_form[PARAMETER],x_fun[PARAMETER],x_fun_trial[PARAMETER])))

Expand Down
37 changes: 3 additions & 34 deletions hippylibX/modeling/Regularization.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,69 +8,38 @@
import numpy as np

class VariationalRegularization:
def __init__(self, mesh, Vh, functional_handler, isQuadratic=False):
def __init__(self, Vh, functional_handler, isQuadratic=False):
self.Vh = Vh #Function space of the parameter.
self.functional_handler = functional_handler #a function or a functor that takes as input m (as dl.Function) and evaluate the regularization functional
self.isQuadratic = isQuadratic #Whether the functional is a quadratic form (i.e. the Hessian is constant) or not (the Hessian dependes on m
self.mesh = mesh #to allreduce over the entire mesh in the cost function

self.xfun = dlx.fem.Function(self.Vh)

# def cost(self, m):
# 1. Cast the petsc4py vector m to a dlx.Function mfun
# 2. Compute the cost by calling assemble on self.functional_handler(mfun)
# 3. Return the value of the cost (Make sure to call a AllReduce for parallel computations

def cost(self,m):
# mfun = vector2Function(m,self.Vh)

def cost(self,m):
updateFromVector(self.xfun, m)
mfun = self.xfun

loc_cost = self.functional_handler(mfun)
glb_cost_proc = dlx.fem.assemble_scalar(dlx.fem.form(loc_cost))
return self.mesh.comm.allreduce(glb_cost_proc, op=MPI.SUM )
return self.Vh[STATE].mesh.comm.allreduce(glb_cost_proc, op=MPI.SUM )


# def grad(self, m, out):
# 1. Cast the petsc4py vector m to a dlx.Function mfun
# 2. call symbolic differentation of self.functional_handler(mfun) wrt mfun
# 3. call assemble, update ghosts, and store the result in out

def grad(self, x : dlx.la.Vector, out: dlx.la.Vector) -> None:
# mfun = vector2Function(x,self.Vh)

updateFromVector(self.xfun, x)
mfun = self.xfun


L = dlx.fem.form(ufl.derivative(self.functional_handler(mfun),mfun,ufl.TestFunction(self.Vh)))

out.array[:] = 0.
tmp_out = dlx.la.create_petsc_vector_wrap(out)
tmp_out.ghostUpdate(addv=petsc4py.PETSc.InsertMode.ADD_VALUES, mode=petsc4py.PETSc.ScatterMode.REVERSE)
tmp_out.destroy()

# def setLinearizationPoint(self, m):
# 1. Cast the petsc4py vector m to a dlx.Function mfun
# 2. call symbolic differentiation (twice) to get the second variation of self.functional_handler(mfun) wrt mfun
# 3. assemble the Hessian operator (it's a sparse matrix!) in the attribute self.R
# 4. set up a linearsolver self.Rsolver that uses CG as Krylov method, gamg as preconditioner and self.R as operator

def setLinearizationPoint(self, m, rel_tol=1e-12, max_iter=1000):
# mfun = vector2Function(m,self.Vh)

updateFromVector(self.xfun, m)
mfun = self.xfun

L = ufl.derivative(ufl.derivative(self.functional_handler(mfun),mfun), mfun)
self.R = dlx.fem.petsc.assemble_matrix(dlx.fem.form(L))
self.R.assemble()

#for Rsolver:
#have to call _BilaplacianRsolver(self.Asolver,self.M)
#so have to construct self.Asolver, self.M first

self.Rsolver = petsc4py.PETSc.KSP().create()
self.Rsolver.getPC().setType(petsc4py.PETSc.PC.Type.GAMG)
self.Rsolver.setType(petsc4py.PETSc.KSP.Type.CG)
Expand Down
6 changes: 2 additions & 4 deletions hippylibX/modeling/misfit.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
import numpy as np

class NonGaussianContinuousMisfit(object):
def __init__(self, mesh : dlx.mesh.Mesh, Vh : list, form):
#mesh needed for comm.allreduce in cost function
self.mesh = mesh
def __init__(self,Vh : list, form):
self.Vh = Vh
self.form = form

Expand All @@ -28,7 +26,7 @@ def cost(self,x : list) -> float:

loc_cost = self.form(u_fun,m_fun)
glb_cost_proc = dlx.fem.assemble_scalar(dlx.fem.form(loc_cost))
return self.mesh.comm.allreduce(glb_cost_proc, op=MPI.SUM )
return self.Vh[hpx.STATE].mesh.comm.allreduce(glb_cost_proc, op=MPI.SUM )

def grad(self, i : int, x : list, out: dlx.la.Vector) -> dlx.la.Vector:

Expand Down
Loading
Loading