From 7155205503d57786a8c0530479e9e427e8eb7565 Mon Sep 17 00:00:00 2001
From: David <forenkram@gmx.de>
Date: Mon, 15 Jun 2020 19:25:30 +0200
Subject: [PATCH] set up new TPTP examples

---
 .../TP-TP-layered_soil_with_inner_patch.py    | 804 ++++++++++++------
 .../Archive/TP-TP-2-patch-alterantive.py      | 511 +++++++++++
 ...P-2-patch-nonwetting-zero-on-subdomain1.py | 527 ++++++++++++
 .../Archive/TP-TP-2-patch-test.py             | 528 ++++++++++++
 .../TP-TP-2-patch-different-intrinsic-perm.py | 598 +++++++++++++
 .../TP-TP-2-patch-same-intrinsic-perm.py      | 598 +++++++++++++
 .../TP-TP-2-patch-test.py                     | 494 ++++++-----
 .../TP-TP-2-patch-test-case/run-simulation    |  16 +
 8 files changed, 3611 insertions(+), 465 deletions(-)
 create mode 100755 Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-alterantive.py
 create mode 100755 Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-nonwetting-zero-on-subdomain1.py
 create mode 100755 Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-test.py
 create mode 100755 Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-different-intrinsic-perm.py
 create mode 100755 Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-same-intrinsic-perm.py
 create mode 100755 Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/run-simulation

diff --git a/Two-phase-Two-phase/multi-patch/TP-TP-layered-soil-case-with-inner-patch/TP-TP-layered_soil_with_inner_patch.py b/Two-phase-Two-phase/multi-patch/TP-TP-layered-soil-case-with-inner-patch/TP-TP-layered_soil_with_inner_patch.py
index b46fbab..6f420d5 100755
--- a/Two-phase-Two-phase/multi-patch/TP-TP-layered-soil-case-with-inner-patch/TP-TP-layered_soil_with_inner_patch.py
+++ b/Two-phase-Two-phase/multi-patch/TP-TP-layered-soil-case-with-inner-patch/TP-TP-layered_soil_with_inner_patch.py
@@ -1,50 +1,174 @@
 #!/usr/bin/python3
-"""This program sets up a domain together with a decomposition into subdomains
-modelling layered soil. This is used for our LDD article with tp-tp and tp-r
-coupling.
+"""TP-TP 2 patch soil simulation.
 
-Along with the subdomains and the mesh domain markers are set upself.
-The resulting mesh is saved into files for later use.
+This program sets up an LDD simulation
 """
 
-#!/usr/bin/python3
 import dolfin as df
-import mshr
-import numpy as np
 import sympy as sym
-import typing as tp
 import functools as ft
-import domainPatch as dp
 import LDDsimulation as ldd
 import helpers as hlp
+import datetime
+import os
+import pandas as pd
 
 # init sympy session
 sym.init_printing()
 
-use_case = "TP-TP-layered-soil-with-inner-patch"
-solver_tol = 1E-6
-
-############ GRID #######################ΓΌ
-mesh_resolution = 30
+# PREREQUISITS  ###############################################################
+# check if output directory "./output" exists. This will be used in
+# the generation of the output string.
+if not os.path.exists('./output'):
+    os.mkdir('./output')
+    print("Directory ", './output',  " created ")
+else:
+    print("Directory ", './output',  " already exists. Will use as output \
+    directory")
+
+date = datetime.datetime.now()
+datestr = date.strftime("%Y-%m-%d")
+
+# Name of the usecase that will be printed during simulation.
+use_case = "TP-TP-layered-soil-inner-patch-realistic"
+# The name of this very file. Needed for creating log output.
+thisfile = "TP-TP-layered_soil_with_inner_patch.py"
+
+# GENERAL SOLVER CONFIG  ######################################################
+# maximal iteration per timestep
+max_iter_num = 300
+FEM_Lagrange_degree = 1
+
+# GRID AND MESH STUDY SPECIFICATIONS  #########################################
+mesh_study = False
+resolutions = {
+                # 1: 1e-6,
+                # 2: 1e-6,
+                # 4: 1e-6,
+                # 8: 1e-6,
+                16: 5e-6,
+                # 32: 5e-6,
+                # 64: 2e-6,
+                # 128: 1e-6,
+                # 256: 1e-6,
+                }
+
+# starttimes gives a list of starttimes to run the simulation from.
+# The list is looped over and a simulation is run with t_0 as initial time
+#  for each element t_0 in starttimes.
+starttimes = [0.0]
 timestep_size = 0.001
-number_of_timesteps = 1500
-# decide how many timesteps you want analysed. Analysed means, that we write out
-# subsequent errors of the L-iteration within the timestep.
-number_of_timesteps_to_analyse = 10
-starttime = 0
+number_of_timesteps = 10
+
+# LDD scheme parameters  ######################################################
+Lw1 = 0.25  # /timestep_size
+Lnw1 = Lw1
+
+Lw2 = 0.25  # /timestep_size
+Lnw2 = Lw2
+
+Lw3 = 0.05  # /timestep_size
+Lnw3 = Lw3
+
+Lw4 = 0.05  # /timestep_size
+Lnw4 = Lw4
+
+Lw5 = 0.05  # /timestep_size
+Lnw5 = Lw5
+
+Lw6 = 0.05  # /timestep_size
+Lnw6 = Lw6
+
+lambda12_w = 40
+lambda12_nw = 40
+
+lambda23_w = 40
+lambda23_nw = 40
+
+lambda24_w = 40
+lambda24_nw= 40
+
+lambda25_w= 40
+lambda25_nw= 40
+
+lambda34_w = 40
+lambda34_nw = 40
+
+lambda36_w = 40
+lambda36_nw = 40
 
-Lw = 0.25  #/timestep_size
-Lnw=Lw
+lambda45_w = 40
+lambda45_nw = 40
 
-lambda_w = 41
-lambda_nw = 41
+lambda46_w = 40
+lambda46_nw = 40
+
+lambda56_w = 40
+lambda56_nw = 40
 
 include_gravity = True
-debugflag = False
+debugflag = True
 analyse_condition = False
 
-output_string = "./output/test-after-bugfix-nondirichlet_number_of_timesteps{}_".format(number_of_timesteps)
+# I/O CONFIG  #################################################################
+# when number_of_timesteps is high, it might take a long time to write all
+# timesteps to disk. Therefore, you can choose to only write data of every
+# plot_timestep_every timestep to disk.
+plot_timestep_every = 4
+# Decide how many timesteps you want analysed. Analysed means, that
+# subsequent errors of the L-iteration within the timestep are written out.
+number_of_timesteps_to_analyse = 5
+
+# fine grained control over data to be written to disk in the mesh study case
+# as well as for a regular simuation for a fixed grid.
+if mesh_study:
+    write_to_file = {
+        # output the relative errornorm (integration in space) w.r.t. an exact
+        # solution for each timestep into a csv file.
+        'space_errornorms': True,
+        # save the mesh and marker functions to disk
+        'meshes_and_markers': True,
+        # save xdmf/h5 data for each LDD iteration for timesteps determined by
+        # number_of_timesteps_to_analyse. I/O intensive!
+        'L_iterations_per_timestep': False,
+        # save solution to xdmf/h5.
+        'solutions': True,
+        # save absolute differences w.r.t an exact solution to xdmf/h5 file
+        # to monitor where on the domains errors happen
+        'absolute_differences': True,
+        # analyise condition numbers for timesteps determined by
+        # number_of_timesteps_to_analyse and save them over time to csv.
+        'condition_numbers': analyse_condition,
+        # output subsequent iteration errors measured in L^2  to csv for
+        # timesteps determined by number_of_timesteps_to_analyse.
+        # Usefull to monitor convergence of the acutal LDD solver.
+        'subsequent_errors': True
+    }
+else:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': True,
+        'absolute_differences': True,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': True
+    }
+
+# OUTPUT FILE STRING  #########################################################
+if mesh_study:
+    output_string = "./output/{}-{}_timesteps{}_P{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree
+        )
+else:
+    for tol in resolutions.values():
+        solver_tol = tol
+    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol
+        )
 
+
+# DOMAIN AND INTERFACE  #######################################################
 # global domain
 subdomain0_vertices = [df.Point(-1.0,-1.0), #
                         df.Point(1.0,-1.0),#
@@ -101,48 +225,6 @@ interface45_vertices = [interface56_vertices[0],
                         interface25_vertices[0]
                         ]
 
-# # subdomain1.
-# subdomain1_vertices = [interface12_vertices[0],
-#                         interface12_vertices[1],
-#                         interface12_vertices[2],
-#                         interface12_vertices[3],
-#                         interface12_vertices[4], # southern boundary, 12 interface
-#                         subdomain0_vertices[2], # eastern boundary, outer boundary
-#                         subdomain0_vertices[3]] # northern boundary, outer on_boundary
-#
-# # vertex coordinates of the outer boundaries. If it can not be specified as a
-# # polygon, use an entry per boundary polygon. This information is used for defining
-# # the Dirichlet boundary conditions. If a domain is completely internal, the
-# # dictionary entry should be 0: None
-# subdomain1_outer_boundary_verts = {
-#     0: [interface12_vertices[4], #
-#         subdomain0_vertices[2], # eastern boundary, outer boundary
-#         subdomain0_vertices[3],
-#         interface12_vertices[0]]
-# }
-#
-
-
-# #subdomain1
-# subdomain2_vertices = [interface23_vertices[0],
-#                         interface23_vertices[1],
-#                         interface23_vertices[2],
-#                         interface23_vertices[3],
-#                         interface23_vertices[4],
-#                         interface23_vertices[5], # southern boundary, 23 interface
-#                         subdomain1_vertices[4], # eastern boundary, outer boundary
-#                         subdomain1_vertices[3],
-#                         subdomain1_vertices[2],
-#                         subdomain1_vertices[1],
-#                         subdomain1_vertices[0] ] # northern boundary, 12 interface
-#
-# subdomain2_outer_boundary_verts = {
-#     0: [interface23_vertices[5],
-#         subdomain1_vertices[4]],
-#     1: [subdomain1_vertices[0],
-#         interface23_vertices[0]]
-# }
-#
 
 # interface_vertices introduces a global numbering of interfaces.
 interface_def_points = [interface12_vertices,
@@ -155,6 +237,7 @@ interface_def_points = [interface12_vertices,
                         interface46_vertices,
                         interface56_vertices,
                         ]
+
 adjacent_subdomains = [[1,2],
                        [2,3],
                        [2,4],
@@ -171,17 +254,18 @@ subdomain1_vertices = [interface12_vertices[0],
                         interface12_vertices[1],
                         interface12_vertices[2],
                         interface12_vertices[3],
-                        interface12_vertices[4], # southern boundary, 12 interface
-                        subdomain0_vertices[2], # eastern boundary, outer boundary
-                        subdomain0_vertices[3]] # northern boundary, outer on_boundary
+                        interface12_vertices[4],  # southern boundary, 12 interface
+                        subdomain0_vertices[2],  # eastern boundary, outer boundary
+                        subdomain0_vertices[3]]  # northern boundary, outer on_boundary
 
 # vertex coordinates of the outer boundaries. If it can not be specified as a
-# polygon, use an entry per boundary polygon. This information is used for defining
+# polygon, use an entry per boundary polygon.
+# This information is used for defining
 # the Dirichlet boundary conditions. If a domain is completely internal, the
 # dictionary entry should be 0: None
 subdomain1_outer_boundary_verts = {
-    0: [subdomain1_vertices[4], #
-        subdomain1_vertices[5], # eastern boundary, outer boundary
+    0: [subdomain1_vertices[4],
+        subdomain1_vertices[5],  # eastern boundary, outer boundary
         subdomain1_vertices[6],
         subdomain1_vertices[0]]
 }
@@ -191,12 +275,12 @@ subdomain2_vertices = [interface23_vertices[0],
                         interface23_vertices[1],
                         interface23_vertices[2],
                         interface24_vertices[1],
-                        interface25_vertices[1], # southern boundary, 23 interface
-                        subdomain1_vertices[4], # eastern boundary, outer boundary
+                        interface25_vertices[1],  # southern boundary, 23 interface
+                        subdomain1_vertices[4],  # eastern boundary, outer boundary
                         subdomain1_vertices[3],
                         subdomain1_vertices[2],
                         subdomain1_vertices[1],
-                        subdomain1_vertices[0] ] # northern boundary, 12 interface
+                        subdomain1_vertices[0] ]  # northern boundary, 12 interface
 
 subdomain2_outer_boundary_verts = {
     0: [subdomain2_vertices[9],
@@ -288,6 +372,7 @@ outer_boundary_def_points = {
     6: subdomain6_outer_boundary_verts
 }
 
+# MODEL CONFIGURATION #########################################################
 
 isRichards = {
     1: False,
@@ -298,45 +383,37 @@ isRichards = {
     6: False
     }
 
-# isRichards = {
-#     1: True,
-#     2: True,
-#     3: True,
-#     4: True,
-#     5: True,
-#     6: True
-#     }
 
 # Dict of the form: { subdom_num : viscosity }
 viscosity = {
-    1: {'wetting' :1,
+    1: {'wetting' :1.0,
          'nonwetting': 1/50},
-    2: {'wetting' :1,
+    2: {'wetting' :1.0,
          'nonwetting': 1/50},
-    3: {'wetting' :1,
+    3: {'wetting' :1.0,
          'nonwetting': 1/50},
-    4: {'wetting' :1,
+    4: {'wetting' :1.0,
          'nonwetting': 1/50},
-    5: {'wetting' :1,
+    5: {'wetting' :1.0,
          'nonwetting': 1/50},
-    6: {'wetting' :1,
+    6: {'wetting' :1.0,
          'nonwetting': 1/50},
 }
 
 # Dict of the form: { subdom_num : density }
 densities = {
-    1: {'wetting': 1,  #997
-         'nonwetting': 1},  #1},  #1.225},
-    2: {'wetting': 1,  #997
-         'nonwetting': 1},  #1.225},
-    3: {'wetting': 1,  #997
-         'nonwetting': 1},  #1.225},
-    4: {'wetting': 1,  #997
-         'nonwetting': 1},  #1.225}
-    5: {'wetting': 1,  #997
-         'nonwetting': 1},  #1.225},
-    6: {'wetting': 1,  #997
-         'nonwetting': 1}  #1.225}
+    1: {'wetting': 997.0,  #997
+         'nonwetting': 1.225},  #1},  #1.225},
+    2: {'wetting': 997.0,  #997
+         'nonwetting': 1.225},  #1.225},
+    3: {'wetting': 997.0,  #997
+         'nonwetting': 1.225},  #1.225},
+    4: {'wetting': 997.0,  #997
+         'nonwetting': 1.225},  #1.225}
+    5: {'wetting': 997.0,  #997
+         'nonwetting': 1.225},  #1.225},
+    6: {'wetting': 997.0,  #997
+         'nonwetting': 1.225}  #1.225}
 }
 
 gravity_acceleration = 9.81
@@ -344,124 +421,286 @@ gravity_acceleration = 9.81
 # https://www.geotechdata.info/parameter/soil-porosity.html
 # Dict of the form: { subdom_num : porosity }
 porosity = {
-    1: 1,  #0.2,  # Clayey gravels, clayey sandy gravels
-    2: 1,  #0.22, # Silty gravels, silty sandy gravels
-    3: 1,  #0.37, # Clayey sands
-    4: 1,  #0.2 # Silty or sandy clay
-    5: 1,  #
-    6: 1,  #
+    1: 0.2,  #0.2,  # Clayey gravels, clayey sandy gravels
+    2: 0.2,  #0.22, # Silty gravels, silty sandy gravels
+    3: 0.2,  #0.37, # Clayey sands
+    4: 0.2,  #0.2 # Silty or sandy clay
+    5: 0.2,  #
+    6: 0.2,  #
 }
 
 # subdom_num : subdomain L for L-scheme
 L = {
-    1: {'wetting' :Lw,
-         'nonwetting': Lnw},
-    2: {'wetting' :Lw,
-         'nonwetting': Lnw},
-    3: {'wetting' :Lw,
-         'nonwetting': Lnw},
-    4: {'wetting' :Lw,
-         'nonwetting': Lnw},
-    5: {'wetting' :Lw,
-         'nonwetting': Lnw},
-    6: {'wetting' :Lw,
-         'nonwetting': Lnw}
+    1: {'wetting' :Lw1,
+         'nonwetting': Lnw1},
+    2: {'wetting' :Lw2,
+         'nonwetting': Lnw2},
+    3: {'wetting' :Lw3,
+         'nonwetting': Lnw3},
+    4: {'wetting' :Lw4,
+         'nonwetting': Lnw4},
+    5: {'wetting' :Lw5,
+         'nonwetting': Lnw5},
+    6: {'wetting' :Lw6,
+         'nonwetting': Lnw6}
 }
 
-# subdom_num : lambda parameter for the L-scheme
+
+# interface_num : lambda parameter for the L-scheme on that interface.
+# Note that interfaces are numbered starting from 0, because
+# adjacent_subdomains is a list and not a dict. Historic fuckup, I know
+# We have defined above as interfaces
+# # interface_vertices introduces a global numbering of interfaces.
+# interface_def_points = [interface12_vertices,
+#                         interface23_vertices,
+#                         interface24_vertices,
+#                         interface25_vertices,
+#                         interface34_vertices,
+#                         interface36_vertices,
+#                         interface45_vertices,
+#                         interface46_vertices,
+#                         interface56_vertices,
+#                         ]
 lambda_param = {
-    1: {'wetting': lambda_w,
-         'nonwetting': lambda_nw},#
-    2: {'wetting': lambda_w,
-         'nonwetting': lambda_nw},#
-    3: {'wetting': lambda_w,
-         'nonwetting': lambda_nw},#
-    4: {'wetting': lambda_w,
-         'nonwetting': lambda_nw},#
-    5: {'wetting': lambda_w,
-         'nonwetting': lambda_nw},#
-    6: {'wetting': lambda_w,
-         'nonwetting': lambda_nw},#
+    0: {'wetting': lambda12_w,
+         'nonwetting': lambda12_nw},#
+    1: {'wetting': lambda23_w,
+         'nonwetting': lambda23_nw},#
+    2: {'wetting': lambda24_w,
+         'nonwetting': lambda24_nw},#
+    3: {'wetting': lambda25_w,
+         'nonwetting': lambda25_nw},#
+    4: {'wetting': lambda34_w,
+         'nonwetting': lambda34_nw},#
+    5: {'wetting': lambda36_w,
+         'nonwetting': lambda36_nw},#
+    6: {'wetting': lambda45_w,
+         'nonwetting': lambda45_nw},#
+    7: {'wetting': lambda46_w,
+         'nonwetting': lambda46_nw},#
+    8: {'wetting': lambda56_w,
+         'nonwetting': lambda56_nw},#
+}
+
+
+# after Lewis, see pdf file
+intrinsic_permeability = {
+    1: 0.01,  # sand
+    2: 0.01,  # sand, there is a range
+    3: 0.01,  #10e-2,  # clay has a range
+    4: 0.01,  #10e-3
+    5: 0.01,  #10e-2,  # clay has a range
+    6: 0.01,  #10e-3
 }
 
 
-## relative permeabilty functions on subdomain 1
+# relative permeabilty functions on subdomain 1
 def rel_perm1w(s):
     # relative permeabilty wetting on subdomain1
-    return s**2
+    return intrinsic_permeability[1]*s**2
 
 
 def rel_perm1nw(s):
     # relative permeabilty nonwetting on subdomain1
-    return (1-s)**2
+    return intrinsic_permeability[1]*(1-s)**2
 
 
-## relative permeabilty functions on subdomain 2
+# relative permeabilty functions on subdomain 2
 def rel_perm2w(s):
     # relative permeabilty wetting on subdomain2
-    return s**3
+    return intrinsic_permeability[2]*s**2
 
 
 def rel_perm2nw(s):
-    # relative permeabilty nonwetting on subdosym.cos(0.8*t - (0.8*x + 1/7*y))main2
-    return (1-s)**3
+    # relative permeabilty nonwetting on subdomain2
+    return intrinsic_permeability[2]*(1-s)**2
+
+
+# relative permeabilty functions on subdomain 3
+def rel_perm3w(s):
+    # relative permeabilty wetting on subdomain3
+    return intrinsic_permeability[3]*s**3
+
+
+def rel_perm3nw(s):
+    # relative permeabilty nonwetting on subdomain3
+    return intrinsic_permeability[3]*(1-s)**3
+
+
+# relative permeabilty functions on subdomain 4
+def rel_perm4w(s):
+    # relative permeabilty wetting on subdomain4
+    return intrinsic_permeability[4]*s**3
+
+
+def rel_perm4nw(s):
+    # relative permeabilty nonwetting on subdomain4
+    return intrinsic_permeability[4]*(1-s)**3
+
+
+# relative permeabilty functions on subdomain 5
+def rel_perm5w(s):
+    # relative permeabilty wetting on subdomain5
+    return intrinsic_permeability[5]*s**3
+
+
+def rel_perm5nw(s):
+    # relative permeabilty nonwetting on subdomain5
+    return intrinsic_permeability[5]*(1-s)**3
+
+
+# relative permeabilty functions on subdomain 6
+def rel_perm6w(s):
+    # relative permeabilty wetting on subdomain6
+    return intrinsic_permeability[6]*s**3
+
+
+def rel_perm6nw(s):
+    # relative permeabilty nonwetting on subdomain6
+    return intrinsic_permeability[6]*(1-s)**3
 
 
 _rel_perm1w = ft.partial(rel_perm1w)
 _rel_perm1nw = ft.partial(rel_perm1nw)
+
 _rel_perm2w = ft.partial(rel_perm2w)
 _rel_perm2nw = ft.partial(rel_perm2nw)
 
+_rel_perm3w = ft.partial(rel_perm3w)
+_rel_perm3nw = ft.partial(rel_perm3nw)
+
+_rel_perm4w = ft.partial(rel_perm4w)
+_rel_perm4nw = ft.partial(rel_perm4nw)
+
+_rel_perm5w = ft.partial(rel_perm5w)
+_rel_perm5nw = ft.partial(rel_perm5nw)
+
+_rel_perm6w = ft.partial(rel_perm6w)
+_rel_perm6nw = ft.partial(rel_perm6nw)
+
 subdomain1_rel_perm = {
-    'wetting': _rel_perm1w,#
+    'wetting': _rel_perm1w,
     'nonwetting': _rel_perm1nw
 }
 
 subdomain2_rel_perm = {
-    'wetting': _rel_perm2w,#
+    'wetting': _rel_perm2w,
     'nonwetting': _rel_perm2nw
 }
 
-# _rel_perm3 = ft.partial(rel_perm2)
-# subdomain3_rel_perm = subdomain2_rel_perm.copy()
-#
-# _rel_perm4 = ft.partial(rel_perm1)
-# subdomain4_rel_perm = subdomain1_rel_perm.copy()
+subdomain3_rel_perm = {
+    'wetting': _rel_perm3w,
+    'nonwetting': _rel_perm3nw
+}
+
+subdomain4_rel_perm = {
+    'wetting': _rel_perm4w,
+    'nonwetting': _rel_perm4nw
+}
+
+subdomain5_rel_perm = {
+    'wetting': _rel_perm5w,
+    'nonwetting': _rel_perm5nw
+}
+
+subdomain6_rel_perm = {
+    'wetting': _rel_perm6w,
+    'nonwetting': _rel_perm6nw
+}
 
 # dictionary of relative permeabilties on all domains.
 relative_permeability = {
     1: subdomain1_rel_perm,
-    2: subdomain1_rel_perm,
-    3: subdomain2_rel_perm,
-    4: subdomain2_rel_perm,
-    5: subdomain2_rel_perm,
-    6: subdomain2_rel_perm,
+    2: subdomain2_rel_perm,
+    3: subdomain3_rel_perm,
+    4: subdomain4_rel_perm,
+    5: subdomain5_rel_perm,
+    6: subdomain6_rel_perm
 }
 
+
 # definition of the derivatives of the relative permeabilities
 # relative permeabilty functions on subdomain 1
 def rel_perm1w_prime(s):
     # relative permeabilty on subdomain1
-    return 2*s
+    return intrinsic_permeability[1]*2*s
+
 
 def rel_perm1nw_prime(s):
     # relative permeabilty on subdomain1
-    return -2*(1-s)
+    return -1*intrinsic_permeability[1]*2*(1-s)
+
 
-# definition of the derivatives of the relative permeabilities
-# relative permeabilty functions on subdomain 1
 def rel_perm2w_prime(s):
-    # relative permeabilty on subdomain1
-    return 3*s**2
+    # relative permeabilty on subdomain2
+    return intrinsic_permeability[2]*2*s
+
 
 def rel_perm2nw_prime(s):
-    # relative permeabilty on subdomain1
-    return -3*(1-s)**2
+    # relative permeabilty on subdomain2
+    return -1*intrinsic_permeability[2]*2*(1-s)
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 3
+def rel_perm3w_prime(s):
+    # relative permeabilty on subdomain3
+    return intrinsic_permeability[3]*3*s**2
+
+
+def rel_perm3nw_prime(s):
+    # relative permeabilty on subdomain3
+    return -1*intrinsic_permeability[3]*3*(1-s)**2
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 4
+def rel_perm4w_prime(s):
+    # relative permeabilty on subdomain4
+    return intrinsic_permeability[4]*3*s**2
+
+
+def rel_perm4nw_prime(s):
+    # relative permeabilty on subdomain4
+    return -1*intrinsic_permeability[4]*3*(1-s)**2
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 5
+def rel_perm5w_prime(s):
+    # relative permeabilty on subdomain5
+    return intrinsic_permeability[5]*3*s**2
+
+
+def rel_perm5nw_prime(s):
+    # relative permeabilty on subdomain5
+    return -1*intrinsic_permeability[5]*3*(1-s)**2
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 6
+def rel_perm6w_prime(s):
+    # relative permeabilty on subdomain6
+    return intrinsic_permeability[6]*3*s**2
+
+
+def rel_perm6nw_prime(s):
+    # relative permeabilty on subdomain6
+    return -1*intrinsic_permeability[6]*3*(1-s)**2
+
 
 _rel_perm1w_prime = ft.partial(rel_perm1w_prime)
 _rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
 _rel_perm2w_prime = ft.partial(rel_perm2w_prime)
 _rel_perm2nw_prime = ft.partial(rel_perm2nw_prime)
+_rel_perm3w_prime = ft.partial(rel_perm3w_prime)
+_rel_perm3nw_prime = ft.partial(rel_perm3nw_prime)
+_rel_perm4w_prime = ft.partial(rel_perm4w_prime)
+_rel_perm4nw_prime = ft.partial(rel_perm4nw_prime)
+_rel_perm5w_prime = ft.partial(rel_perm5w_prime)
+_rel_perm5nw_prime = ft.partial(rel_perm5nw_prime)
+_rel_perm6w_prime = ft.partial(rel_perm6w_prime)
+_rel_perm6nw_prime = ft.partial(rel_perm6nw_prime)
 
 subdomain1_rel_perm_prime = {
     'wetting': _rel_perm1w_prime,
@@ -474,22 +713,46 @@ subdomain2_rel_perm_prime = {
     'nonwetting': _rel_perm2nw_prime
 }
 
+subdomain3_rel_perm_prime = {
+    'wetting': _rel_perm3w_prime,
+    'nonwetting': _rel_perm3nw_prime
+}
+
+
+subdomain4_rel_perm_prime = {
+    'wetting': _rel_perm4w_prime,
+    'nonwetting': _rel_perm4nw_prime
+}
+
+subdomain5_rel_perm_prime = {
+    'wetting': _rel_perm5w_prime,
+    'nonwetting': _rel_perm5nw_prime
+}
+
+subdomain6_rel_perm_prime = {
+    'wetting': _rel_perm6w_prime,
+    'nonwetting': _rel_perm6nw_prime
+}
+
+
 # dictionary of relative permeabilties on all domains.
 ka_prime = {
     1: subdomain1_rel_perm_prime,
-    2: subdomain1_rel_perm_prime,
-    3: subdomain2_rel_perm_prime,
-    4: subdomain2_rel_perm_prime,
-    5: subdomain2_rel_perm_prime,
-    6: subdomain2_rel_perm_prime,
+    2: subdomain2_rel_perm_prime,
+    3: subdomain3_rel_perm_prime,
+    4: subdomain4_rel_perm_prime,
+    5: subdomain5_rel_perm_prime,
+    6: subdomain6_rel_perm_prime,
 }
 
 
 
-# S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
-# we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
-# this function needs to be monotonically decreasing in the capillary pressure pc.
-# since in the richards case pc=-pw, this becomes as a function of pw a mono
+# S-pc-relation ship. We use the van Genuchten approach, i.e.
+# pc = 1/alpha*(S^{-1/m} -1)^1/n, where we set alpha = 0, assume
+# m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# this function needs to be monotonically decreasing in the capillary pressure
+# pc.
+# Since in the richards case pc=-pw, this becomes as a function of pw a mono
 # tonically INCREASING function like in our Richards-Richards paper. However
 # since we unify the treatment in the code for Richards and two-phase, we need
 # the same requierment
@@ -511,11 +774,7 @@ ka_prime = {
 # def saturation_sym_prime(pc, n_index, alpha):
 #     # inverse capillary pressure-saturation-relationship
 #     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
-#
-# derivative of S-pc relationship with respect to pc. This is needed for the
-# construction of a analytic solution.
-
-#
+##
 # # note that the conditional definition of S-pc in the nonsymbolic part will be
 # # incorporated in the construction of the exact solution below.
 # S_pc_sym = {
@@ -554,6 +813,7 @@ def saturation_sym(pc, n_index):
     # inverse capillary pressure-saturation-relationship
     return 1/((1 + pc)**(1/(n_index + 1)))
 
+
 def saturation_sym_prime(pc, n_index):
     # inverse capillary pressure-saturation-relationship
     return -1/((n_index+1)*(1 + pc)**((n_index+2)/(n_index+1)))
@@ -587,60 +847,42 @@ sat_pressure_relationship = {
 }
 
 
-#############################################
+###############################################################################
 # Manufacture source expressions with sympy #
-#############################################
+###############################################################################
 x, y = sym.symbols('x[0], x[1]')  # needed by UFL
 t = sym.symbols('t', positive=True)
 
 
 p_e_sym = {
-    1: {'wetting': -5.0 - (1.0 + t*t)*(1.0 + x*x + y*y),
+        1: {'wetting': -6.0 - (1.0 + t*t)*(1.0 + x*x + y*y),
         'nonwetting': (-1 -t*(1.1 + y + x**2)) },
-    2: {'wetting': -5.0 - (1.0 + t*t)*(1.0 + x*x + y*y),
+    2: {'wetting': -6.0 - (1.0 + t*t)*(1.0 + x*x + y*y),
         'nonwetting': (-1 -t*(1.1 + y + x**2)) },
-    3: {'wetting': (-5.0 - (1.0 + t*t)*(1.0 + x*x)),
-        'nonwetting': (-1 -t*(1 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
-    4: {'wetting': (-5.0 - (1.0 + t*t)*(1.0 + x*x)),
-        'nonwetting': (-1 -t*(1 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
-    5: {'wetting': (-5.0 - (1.0 + t*t)*(1.0 + x*x)),
-        'nonwetting': (-1 -t*(1 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
-    6: {'wetting': (-5.0 - (1.0 + t*t)*(1.0 + x*x)),
-        'nonwetting': (-1 -t*(1 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
-    # 2: {'wetting': 1.0 - (1.0 + t*t)*(10.0 + x*x + (y-5.0)*(y-5.0)),
-    #     'nonwetting': - 2 - t*(1 + (y-5.0) + x**2)**2 -sym.sqrt(2+t**2)*(1 + (y-5.0))},
-    # 3: {'wetting': 1.0 - (1.0 + t*t)*(10.0 + x*x + (y-5.0)*(y-5.0)*3*sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)),
-    #     'nonwetting': - 2 - t*(1 + x**2)**2 -sym.sqrt(2+t**2)},
-    # 4: {'wetting': 1.0 - (1.0 + t*t)*(10.0 + x*x + (y-5.0)*(y-5.0)*3*sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)),
-    #     'nonwetting': - 2 - t*(1 + x**2)**2 -sym.sqrt(2+t**2)}
+    3: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),
+        'nonwetting': (-1 -t*(1.0 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
+    4: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),
+        'nonwetting': (-1 -t*(1.0 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
+    5: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),
+        'nonwetting': (-1 -t*(1.0 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
+    6: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),
+        'nonwetting': (-1 -t*(1.0 + x**2) - sym.sqrt(2+t**2)*(1+y)*y**2) },
+    # 2: {'wetting': 1.0 - (1.0 + t*t)*(10.0 + x*x + (y-6.0)*(y-6.0)),
+    #     'nonwetting': - 2 - t*(1.0 + (y-6.0) + x**2)**2 -sym.sqrt(2+t**2)*(1.0 + (y-6.0))},
+    # 3: {'wetting': 1.0 - (1.0 + t*t)*(10.0 + x*x + (y-6.0)*(y-6.0)*3*sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)),
+    #     'nonwetting': - 2 - t*(1.0 + x**2)**2 -sym.sqrt(2+t**2)},
+    # 4: {'wetting': 1.0 - (1.0 + t*t)*(10.0 + x*x + (y-6.0)*(y-6.0)*3*sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)),
+    #     'nonwetting': - 2 - t*(1.0 + x**2)**2 -sym.sqrt(2+t**2)}
 }
 
-# pc_e_sym = {
-#     1: p_e_sym[1]['nonwetting'] - p_e_sym[1]['wetting'],
-#     2: p_e_sym[2]['nonwetting'] - p_e_sym[2]['wetting'],
-#     3: p_e_sym[3]['nonwetting'] - p_e_sym[3]['wetting'],
-#     4: p_e_sym[4]['nonwetting'] - p_e_sym[4]['wetting'],
-#     5: p_e_sym[5]['nonwetting'] - p_e_sym[5]['wetting'],
-#     6: p_e_sym[5]['nonwetting'] - p_e_sym[6]['wetting']
-# }
-
-# pc_e_sym = {
-#     1: -p_e_sym[1]['wetting'],
-#     2: -p_e_sym[2]['wetting'],
-#     3: -p_e_sym[3]['wetting'],
-#     4: -p_e_sym[4]['wetting'],
-#     5: -p_e_sym[5]['wetting'],
-#     6: -p_e_sym[6]['wetting']
-# }
-
 
 pc_e_sym = dict()
 for subdomain, isR in isRichards.items():
     if isR:
-        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting']})
+        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting'].copy()})
     else:
-        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting']
-                                        - p_e_sym[subdomain]['wetting']})
+        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting'].copy()
+                                        - p_e_sym[subdomain]['wetting'].copy()})
 
 
 symbols = {"x": x,
@@ -667,6 +909,7 @@ source_expression = exact_solution_example['source']
 exact_solution = exact_solution_example['exact_solution']
 initial_condition = exact_solution_example['initial_condition']
 
+# BOUNDARY CONDITIONS #########################################################
 # Dictionary of dirichlet boundary conditions.
 dirichletBC = dict()
 # similarly to the outer boundary dictionary, if a patch has no outer boundary
@@ -683,7 +926,7 @@ dirichletBC = dict()
 
 # subdomain index: {outer boudary part index: {phase: expression}}
 for subdomain in isRichards.keys():
-    # if subdomain has no outer boundary, outer_boundary_def_points[subdomain] is None
+    # subdomain can have no outer boundary
     if outer_boundary_def_points[subdomain] is None:
         dirichletBC.update({subdomain: None})
     else:
@@ -695,42 +938,97 @@ for subdomain in isRichards.keys():
                 {outer_boundary_ind: exact_solution[subdomain]}
                 )
 
-write_to_file = {
-    'meshes_and_markers': True,
-    'L_iterations': True
-}
 
-# initialise LDD simulation class
-simulation = ldd.LDDsimulation(tol=1E-14, debug=debugflag, LDDsolver_tol=solver_tol)
-simulation.set_parameters(use_case = use_case,
-                          output_dir=output_string,
-                          subdomain_def_points=subdomain_def_points,
-                          isRichards=isRichards,
-                          interface_def_points=interface_def_points,
-                          outer_boundary_def_points=outer_boundary_def_points,
-                          adjacent_subdomains=adjacent_subdomains,
-                          mesh_resolution=mesh_resolution,
-                          viscosity=viscosity,
-                          porosity=porosity,
-                          L=L,
-                          lambda_param=lambda_param,
-                          relative_permeability=relative_permeability,
-                          saturation=sat_pressure_relationship,
-                          starttime=starttime,
-                          number_of_timesteps=number_of_timesteps,
-                          number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
-                          timestep_size=timestep_size,
-                          sources=source_expression,
-                          initial_conditions=initial_condition,
-                          dirichletBC_expression_strings=dirichletBC,
-                          exact_solution=exact_solution,
-                          densities=densities,
-                          include_gravity=include_gravity,
-                          write2file=write_to_file,
-                          )
-
-simulation.initialise()
-# print(simulation.__dict__)
-simulation.run(analyse_condition=analyse_condition)
-# simulation.LDDsolver(time=0, debug=True, analyse_timestep=True)
-# df.info(parameters, True)
+# LOG FILE OUTPUT #############################################################
+# read this file and print it to std out. This way the simulation can produce a
+# log file with ./TP-R-layered_soil.py | tee simulation.log
+f = open(thisfile, 'r')
+print(f.read())
+f.close()
+
+
+# RUN #########################################################################
+for starttime in starttimes:
+    for mesh_resolution, solver_tol in resolutions.items():
+        # initialise LDD simulation class
+        simulation = ldd.LDDsimulation(
+            tol=1E-14,
+            LDDsolver_tol=solver_tol,
+            debug=debugflag,
+            max_iter_num=max_iter_num,
+            FEM_Lagrange_degree=FEM_Lagrange_degree,
+            mesh_study=mesh_study
+            )
+
+        simulation.set_parameters(
+            use_case=use_case,
+            output_dir=output_string,
+            subdomain_def_points=subdomain_def_points,
+            isRichards=isRichards,
+            interface_def_points=interface_def_points,
+            outer_boundary_def_points=outer_boundary_def_points,
+            adjacent_subdomains=adjacent_subdomains,
+            mesh_resolution=mesh_resolution,
+            viscosity=viscosity,
+            porosity=porosity,
+            L=L,
+            lambda_param=lambda_param,
+            relative_permeability=relative_permeability,
+            saturation=sat_pressure_relationship,
+            starttime=starttime,
+            number_of_timesteps=number_of_timesteps,
+            number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+            plot_timestep_every=plot_timestep_every,
+            timestep_size=timestep_size,
+            sources=source_expression,
+            initial_conditions=initial_condition,
+            dirichletBC_expression_strings=dirichletBC,
+            exact_solution=exact_solution,
+            densities=densities,
+            include_gravity=include_gravity,
+            gravity_acceleration=gravity_acceleration,
+            write2file=write_to_file,
+            )
+
+        simulation.initialise()
+        output_dir = simulation.output_dir
+        # simulation.write_exact_solution_to_xdmf()
+        output = simulation.run(analyse_condition=analyse_condition)
+        for subdomain_index, subdomain_output in output.items():
+            mesh_h = subdomain_output['mesh_size']
+            for phase, error_dict in subdomain_output['errornorm'].items():
+                filename = output_dir \
+                    + "subdomain{}".format(subdomain_index)\
+                    + "-space-time-errornorm-{}-phase.csv".format(phase)
+                # for errortype, errornorm in error_dict.items():
+
+                # eocfile = open("eoc_filename", "a")
+                # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
+                # eocfile.close()
+                # if subdomain.isRichards:mesh_h
+                data_dict = {
+                    'mesh_parameter': mesh_resolution,
+                    'mesh_h': mesh_h,
+                }
+                for norm_type, errornorm in error_dict.items():
+                    data_dict.update(
+                        {norm_type: errornorm}
+                    )
+                errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+                # check if file exists
+                if os.path.isfile(filename) is True:
+                    with open(filename, 'a') as f:
+                        errors.to_csv(
+                            f,
+                            header=False,
+                            sep='\t',
+                            encoding='utf-8',
+                            index=False
+                            )
+                else:
+                    errors.to_csv(
+                        filename,
+                        sep='\t',
+                        encoding='utf-8',
+                        index=False
+                        )
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-alterantive.py b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-alterantive.py
new file mode 100755
index 0000000..1df40d9
--- /dev/null
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-alterantive.py
@@ -0,0 +1,511 @@
+#!/usr/bin/python3
+import dolfin as df
+import mshr
+import numpy as np
+import sympy as sym
+import typing as tp
+import domainPatch as dp
+import LDDsimulation as ldd
+import functools as ft
+import helpers as hlp
+import datetime
+import os
+import pandas as pd
+
+date = datetime.datetime.now()
+datestr = date.strftime("%Y-%m-%d")
+#import ufl as ufl
+
+# init sympy session
+sym.init_printing()
+
+use_case = "TP-TP-2-patch-alternative"
+solver_tol = 5E-7
+max_iter_num = 10
+FEM_Lagrange_degree = 1
+mesh_study = False
+resolutions = [20]
+
+############ GRID #######################
+# mesh_resolution = 20
+timestep_size = 0.0001
+number_of_timesteps = 50
+# smallest possible number is 1
+plot_timestep_every = 5
+# decide how many timesteps you want analysed. Analysed means, that we write out
+# subsequent errors of the L-iteration within the timestep.
+number_of_timesteps_to_analyse = 0
+starttime = 0.0
+
+Lw = 0.25 #/timestep_size
+Lnw=Lw
+
+lambda_w = 40
+lambda_nw = 40
+
+include_gravity = False
+debugflag = False
+analyse_condition = False
+
+output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}_".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol)
+
+# toggle what should be written to files
+if mesh_study:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': False,
+        'absolute_differences': False,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': False
+    }
+else:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': True,
+        'absolute_differences': True,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': True
+    }
+
+##### Domain and Interface ####
+# global simulation domain domain
+sub_domain0_vertices = [df.Point(-1.0,-1.0), #
+                        df.Point(1.0,-1.0),#
+                        df.Point(1.0,1.0),#
+                        df.Point(-1.0,1.0)]
+# interface between subdomain1 and subdomain2
+interface12_vertices = [df.Point(-1.0, 0.0),
+                        df.Point(1.0, 0.0) ]
+# subdomain1.
+sub_domain1_vertices = [interface12_vertices[0],
+                        interface12_vertices[1],
+                        sub_domain0_vertices[2],
+                        sub_domain0_vertices[3] ]
+
+# vertex coordinates of the outer boundaries. If it can not be specified as a
+# polygon, use an entry per boundary polygon. This information is used for defining
+# the Dirichlet boundary conditions. If a domain is completely internal, the
+# dictionary entry should be 0: None
+subdomain1_outer_boundary_verts = {
+    0: [interface12_vertices[1],
+        sub_domain0_vertices[2],
+        sub_domain0_vertices[3], #
+        interface12_vertices[0]]
+}
+# subdomain2
+sub_domain2_vertices = [sub_domain0_vertices[0],
+                        sub_domain0_vertices[1],
+                        interface12_vertices[1],
+                        interface12_vertices[0] ]
+
+subdomain2_outer_boundary_verts = {
+    0: [interface12_vertices[0], #
+        sub_domain0_vertices[0],
+        sub_domain0_vertices[1],
+        interface12_vertices[1]]
+}
+# subdomain2_outer_boundary_verts = {
+#     0: [interface12_vertices[0], df.Point(0.0,0.0)],#
+#     1: [df.Point(0.0,0.0), df.Point(1.0,0.0)], #
+#     2: [df.Point(1.0,0.0), interface12_vertices[1]]
+# }
+# subdomain2_outer_boundary_verts = {
+#     0: None
+# }
+
+# list of subdomains given by the boundary polygon vertices.
+# Subdomains are given as a list of dolfin points forming
+# a closed polygon, such that mshr.Polygon(subdomain_def_points[i]) can be used
+# to create the subdomain. subdomain_def_points[0] contains the
+# vertices of the global simulation domain and subdomain_def_points[i] contains the
+# vertices of the subdomain i.
+subdomain_def_points = [sub_domain0_vertices,#
+                      sub_domain1_vertices,#
+                      sub_domain2_vertices]
+# in the below list, index 0 corresponds to the 12 interface which has index 1
+interface_def_points = [interface12_vertices]
+
+# if a subdomain has no outer boundary write None instead, i.e.
+# i: None
+# if i is the index of the inner subdomain.
+outer_boundary_def_points = {
+    # subdomain number
+    1 : subdomain1_outer_boundary_verts,
+    2 : subdomain2_outer_boundary_verts
+}
+
+# adjacent_subdomains[i] contains the indices of the subdomains sharing the
+# interface i (i.e. given by interface_def_points[i]).
+adjacent_subdomains = [[1,2]]
+isRichards = {
+    1: False, #
+    2: False
+    }
+
+
+viscosity = {#
+# subdom_num : viscosity
+    1 : {'wetting' :1,
+         'nonwetting': 1}, #
+    2 : {'wetting' :1,
+         'nonwetting': 1}
+}
+
+porosity = {#
+# subdom_num : porosity
+    1 : 1,#
+    2 : 1
+}
+
+# Dict of the form: { subdom_num : density }
+densities = {
+    1: {'wetting': 1,  #997,
+        'nonwetting': 1}, #1225},
+    2: {'wetting': 1,  #997,
+        'nonwetting': 1}, #1225},
+}
+
+gravity_acceleration = 9.81
+
+L = {#
+# subdom_num : subdomain L for L-scheme
+    1 : {'wetting' :Lw,
+         'nonwetting': Lnw},#
+    2 : {'wetting' :Lw,
+         'nonwetting': Lnw}
+}
+
+lambda_param = {#
+# subdom_num : lambda parameter for the L-scheme
+    1 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw},#
+    2 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw}
+}
+
+## relative permeabilty functions on subdomain 1
+def rel_perm1w(s):
+    # relative permeabilty wetting on subdomain1
+    return s**2
+
+def rel_perm1nw(s):
+    # relative permeabilty nonwetting on subdomain1
+    return (1-s)**2
+
+_rel_perm1w = ft.partial(rel_perm1w)
+_rel_perm1nw = ft.partial(rel_perm1nw)
+
+subdomain1_rel_perm = {
+    'wetting': _rel_perm1w,#
+    'nonwetting': _rel_perm1nw
+}
+## relative permeabilty functions on subdomain 2
+def rel_perm2w(s):
+    # relative permeabilty wetting on subdomain2
+    return s**3
+def rel_perm2nw(s):
+    # relative permeabilty nonwetting on subdosym.cos(0.8*t - (0.8*x + 1/7*y))main2
+    return (1-s)**3
+
+_rel_perm2w = ft.partial(rel_perm2w)
+_rel_perm2nw = ft.partial(rel_perm2nw)
+
+subdomain2_rel_perm = {
+    'wetting': _rel_perm2w,#
+    'nonwetting': _rel_perm2nw
+}
+
+## dictionary of relative permeabilties on all domains.
+relative_permeability = {#
+    1: subdomain1_rel_perm,
+    2: subdomain2_rel_perm
+}
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm1w_prime(s):
+    # relative permeabilty on subdomain1
+    return 2*s
+
+def rel_perm1nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -2*(1-s)
+
+# # definition of the derivatives of the relative permeabilities
+# # relative permeabilty functions on subdomain 1
+def rel_perm2w_prime(s):
+    # relative permeabilty on subdomain1
+    return 3*s**2
+
+def rel_perm2nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -3*(1-s)**2
+
+_rel_perm1w_prime = ft.partial(rel_perm1w_prime)
+_rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
+_rel_perm2w_prime = ft.partial(rel_perm2w_prime)
+_rel_perm2nw_prime = ft.partial(rel_perm2nw_prime)
+
+subdomain1_rel_perm_prime = {
+    'wetting': _rel_perm1w_prime,
+    'nonwetting': _rel_perm1nw_prime
+}
+
+
+subdomain2_rel_perm_prime = {
+    'wetting': _rel_perm2w_prime,
+    'nonwetting': _rel_perm2nw_prime
+}
+
+# dictionary of relative permeabilties on all domains.
+ka_prime = {
+    1: subdomain1_rel_perm_prime,
+    2: subdomain2_rel_perm_prime,
+}
+
+
+
+def saturation(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return df.conditional(pc > 0, 1/((1 + pc)**(1/(index + 1))), 1)
+
+
+def saturation_sym(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return 1/((1 + pc)**(1/(index + 1)))
+
+
+# derivative of S-pc relationship with respect to pc. This is needed for the
+# construction of a analytic solution.
+def saturation_sym_prime(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return -1/((index+1)*(1 + pc)**((index+2)/(index+1)))
+
+
+# note that the conditional definition of S-pc in the nonsymbolic part will be
+# incorporated in the construction of the exact solution below.
+S_pc_sym = {
+    1: ft.partial(saturation_sym, index=1),
+    2: ft.partial(saturation_sym, index=2),
+    # 3: ft.partial(saturation_sym, index=2),
+    # 4: ft.partial(saturation_sym, index=1)
+}
+
+S_pc_sym_prime = {
+    1: ft.partial(saturation_sym_prime, index=1),
+    2: ft.partial(saturation_sym_prime, index=2),
+    # 3: ft.partial(saturation_sym_prime, index=2),
+    # 4: ft.partial(saturation_sym_prime, index=1)
+}
+
+sat_pressure_relationship = {
+    1: ft.partial(saturation, index=1),
+    2: ft.partial(saturation, index=2),
+    # 3: ft.partial(saturation, index=2),
+    # 4: ft.partial(saturation, index=1)
+}
+
+#
+# def saturation(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
+#
+# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
+# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# def saturation_sym(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     #df.conditional(pc > 0,
+#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
+#
+#
+# # derivative of S-pc relationship with respect to pc. This is needed for the
+# # construction of a analytic solution.
+# def saturation_sym_prime(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
+#
+# # note that the conditional definition of S-pc in the nonsymbolic part will be
+# # incorporated in the construction of the exact solution below.
+# S_pc_sym = {
+#     1: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation_sym, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation_sym, n_index=3, alpha=0.001)
+# }
+#
+# S_pc_sym_prime = {
+#     1: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation_sym_prime, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001)
+# }
+#
+# sat_pressure_relationship = {
+#     1: ft.partial(saturation, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation, n_index=3, alpha=0.001)
+# }
+#
+
+
+#############################################
+# Manufacture source expressions with sympy #
+#############################################
+x, y = sym.symbols('x[0], x[1]')  # needed by UFL
+t = sym.symbols('t', positive=True)
+
+p_e_sym = {
+    1: {'wetting': -7 - (1+t*t)*(1 + x*x + y*y),
+        'nonwetting': -2 -t*(1 + y + x**2)},
+    2: {'wetting': -7.0 - (1.0 + t*t)*(1.0 + x*x),
+        'nonwetting': -2 -t*(1 + x**2)**2 - sym.sqrt(2+t**2)*(1+y)**2*x**2*y**2},
+}
+
+pc_e_sym = dict()
+for subdomain, isR in isRichards.items():
+    if isR:
+        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting'].copy()})
+    else:
+        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting'].copy()
+                                        - p_e_sym[subdomain]['wetting'].copy()})
+
+
+symbols = {"x": x,
+           "y": y,
+           "t": t}
+# turn above symbolic code into exact solution for dolphin and
+# construct the rhs that matches the above exact solution.
+exact_solution_example = hlp.generate_exact_solution_expressions(
+                        symbols=symbols,
+                        isRichards=isRichards,
+                        symbolic_pressure=p_e_sym,
+                        symbolic_capillary_pressure=pc_e_sym,
+                        saturation_pressure_relationship=S_pc_sym,
+                        saturation_pressure_relationship_prime=S_pc_sym_prime,
+                        viscosity=viscosity,
+                        porosity=porosity,
+                        relative_permeability=relative_permeability,
+                        relative_permeability_prime=ka_prime,
+                        densities=densities,
+                        gravity_acceleration=gravity_acceleration,
+                        include_gravity=include_gravity,
+                        )
+source_expression = exact_solution_example['source']
+exact_solution = exact_solution_example['exact_solution']
+initial_condition = exact_solution_example['initial_condition']
+
+# Dictionary of dirichlet boundary conditions.
+dirichletBC = dict()
+# similarly to the outer boundary dictionary, if a patch has no outer boundary
+# None should be written instead of an expression.
+# This is a bit of a brainfuck:
+# dirichletBC[ind] gives a dictionary of the outer boundaries of subdomain ind.
+# Since a domain patch can have several disjoint outer boundary parts, the
+# expressions need to get an enumaration index which starts at 0.
+# So dirichletBC[ind][j] is the dictionary of outer dirichlet conditions of
+# subdomain ind and boundary part j.
+# Finally, dirichletBC[ind][j]['wetting'] and dirichletBC[ind][j]['nonwetting']
+# return the actual expression needed for the dirichlet condition for both
+# phases if present.
+
+# subdomain index: {outer boudary part index: {phase: expression}}
+for subdomain in isRichards.keys():
+    # if subdomain has no outer boundary, outer_boundary_def_points[subdomain] is None
+    if outer_boundary_def_points[subdomain] is None:
+        dirichletBC.update({subdomain: None})
+    else:
+        dirichletBC.update({subdomain: dict()})
+        # set the dirichlet conditions to be the same code as exact solution on
+        # the subdomain.
+        for outer_boundary_ind in outer_boundary_def_points[subdomain].keys():
+            dirichletBC[subdomain].update(
+                {outer_boundary_ind: exact_solution[subdomain]}
+                )
+
+
+# def saturation(pressure, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pressure < 0, 1/((1 - pressure)**(1/(subdomain_index + 1))), 1)
+#
+# sa
+
+for mesh_resolution in resolutions:
+    # initialise LDD simulation class
+    simulation = ldd.LDDsimulation(
+        tol=1E-14,
+        LDDsolver_tol=solver_tol,
+        debug=debugflag,
+        max_iter_num=max_iter_num,
+        FEM_Lagrange_degree=FEM_Lagrange_degree,
+        mesh_study=mesh_study
+        )
+
+    simulation.set_parameters(use_case=use_case,
+                              output_dir=output_string,
+                              subdomain_def_points=subdomain_def_points,
+                              isRichards=isRichards,
+                              interface_def_points=interface_def_points,
+                              outer_boundary_def_points=outer_boundary_def_points,
+                              adjacent_subdomains=adjacent_subdomains,
+                              mesh_resolution=mesh_resolution,
+                              viscosity=viscosity,
+                              porosity=porosity,
+                              L=L,
+                              lambda_param=lambda_param,
+                              relative_permeability=relative_permeability,
+                              saturation=sat_pressure_relationship,
+                              starttime=starttime,
+                              number_of_timesteps=number_of_timesteps,
+                              number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+                              plot_timestep_every=plot_timestep_every,
+                              timestep_size=timestep_size,
+                              sources=source_expression,
+                              initial_conditions=initial_condition,
+                              dirichletBC_expression_strings=dirichletBC,
+                              exact_solution=exact_solution,
+                              densities=densities,
+                              include_gravity=include_gravity,
+                              write2file=write_to_file,
+                              )
+
+    simulation.initialise()
+    output_dir = simulation.output_dir
+    # simulation.write_exact_solution_to_xdmf()
+    output = simulation.run(analyse_condition=analyse_condition)
+    for subdomain_index, subdomain_output in output.items():
+        mesh_h = subdomain_output['mesh_size']
+        for phase, different_errornorms in subdomain_output['errornorm'].items():
+            filename = output_dir + "subdomain{}-space-time-errornorm-{}-phase.csv".format(subdomain_index, phase)
+            # for errortype, errornorm in different_errornorms.items():
+
+                # eocfile = open("eoc_filename", "a")
+                # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
+                # eocfile.close()
+                # if subdomain.isRichards:mesh_h
+            data_dict = {
+                'mesh_parameter': mesh_resolution,
+                'mesh_h': mesh_h,
+            }
+            for error_type, errornorms in different_errornorms.items():
+                data_dict.update(
+                    {error_type: errornorms}
+                )
+            errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+            # check if file exists
+            if os.path.isfile(filename) == True:
+                with open(filename, 'a') as f:
+                    errors.to_csv(f, header=False, sep='\t', encoding='utf-8', index=False)
+            else:
+                errors.to_csv(filename, sep='\t', encoding='utf-8', index=False)
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-nonwetting-zero-on-subdomain1.py b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-nonwetting-zero-on-subdomain1.py
new file mode 100755
index 0000000..de6c451
--- /dev/null
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-nonwetting-zero-on-subdomain1.py
@@ -0,0 +1,527 @@
+#!/usr/bin/python3
+import dolfin as df
+import mshr
+import numpy as np
+import sympy as sym
+import typing as tp
+import domainPatch as dp
+import LDDsimulation as ldd
+import functools as ft
+import helpers as hlp
+import datetime
+import os
+import pandas as pd
+
+date = datetime.datetime.now()
+datestr = date.strftime("%Y-%m-%d")
+#import ufl as ufl
+
+# init sympy session
+sym.init_printing()
+
+use_case = "TP-TP-2-patch-nonwetting-zero-on-subdomain1"
+# solver_tol = 5E-7
+max_iter_num = 1000
+FEM_Lagrange_degree = 1
+mesh_study = False
+resolutions = {
+                # 1: 1e-7,  # h=2
+                # 2: 2e-5,  # h=1.1180
+                # 4: 1e-6,  # h=0.5590
+                # 8: 1e-6,  # h=0.2814
+                # 16: 5e-7, # h=0.1412
+                32: 5e-7,
+                # 64: 5e-7,
+                # 128: 5e-7
+                }
+
+
+############ GRID #######################
+# mesh_resolution = 20
+timestep_size = 0.005
+number_of_timesteps = 250
+plot_timestep_every = 1
+# decide how many timesteps you want analysed. Analysed means, that we write out
+# subsequent errors of the L-iteration within the timestep.
+number_of_timesteps_to_analyse = 5
+starttime = 0.0
+
+Lw = 0.05 #/timestep_size
+Lnw=Lw
+
+lambda_w = 40
+lambda_nw = 40
+include_gravity = False
+debugflag = False
+analyse_condition = True
+
+if mesh_study:
+    output_string = "./output/{}-{}_timesteps{}_P{}".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree)
+else:
+    for tol in resolutions.values():
+        solver_tol = tol
+    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol)
+
+
+# toggle what should be written to files
+if mesh_study:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': False,
+        'absolute_differences': False,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': False
+    }
+else:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': True,
+        'absolute_differences': True,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': True
+    }
+
+##### Domain and Interface ####
+# global simulation domain domain
+sub_domain0_vertices = [df.Point(-1.0,-1.0), #
+                        df.Point(1.0,-1.0),#
+                        df.Point(1.0,1.0),#
+                        df.Point(-1.0,1.0)]
+# interface between subdomain1 and subdomain2
+interface12_vertices = [df.Point(-1.0, 0.0),
+                        df.Point(1.0, 0.0) ]
+# subdomain1.
+sub_domain1_vertices = [interface12_vertices[0],
+                        interface12_vertices[1],
+                        sub_domain0_vertices[2],
+                        sub_domain0_vertices[3] ]
+
+# vertex coordinates of the outer boundaries. If it can not be specified as a
+# polygon, use an entry per boundary polygon. This information is used for defining
+# the Dirichlet boundary conditions. If a domain is completely internal, the
+# dictionary entry should be 0: None
+subdomain1_outer_boundary_verts = {
+    0: [interface12_vertices[1],
+        sub_domain0_vertices[2],
+        sub_domain0_vertices[3], #
+        interface12_vertices[0]]
+}
+# subdomain2
+sub_domain2_vertices = [sub_domain0_vertices[0],
+                        sub_domain0_vertices[1],
+                        interface12_vertices[1],
+                        interface12_vertices[0] ]
+
+subdomain2_outer_boundary_verts = {
+    0: [interface12_vertices[0], #
+        sub_domain0_vertices[0],
+        sub_domain0_vertices[1],
+        interface12_vertices[1]]
+}
+# subdomain2_outer_boundary_verts = {
+#     0: [interface12_vertices[0], df.Point(0.0,0.0)],#
+#     1: [df.Point(0.0,0.0), df.Point(1.0,0.0)], #
+#     2: [df.Point(1.0,0.0), interface12_vertices[1]]
+# }
+# subdomain2_outer_boundary_verts = {
+#     0: None
+# }
+
+# list of subdomains given by the boundary polygon vertices.
+# Subdomains are given as a list of dolfin points forming
+# a closed polygon, such that mshr.Polygon(subdomain_def_points[i]) can be used
+# to create the subdomain. subdomain_def_points[0] contains the
+# vertices of the global simulation domain and subdomain_def_points[i] contains the
+# vertices of the subdomain i.
+subdomain_def_points = [sub_domain0_vertices,#
+                      sub_domain1_vertices,#
+                      sub_domain2_vertices]
+# in the below list, index 0 corresponds to the 12 interface which has index 1
+interface_def_points = [interface12_vertices]
+
+# if a subdomain has no outer boundary write None instead, i.e.
+# i: None
+# if i is the index of the inner subdomain.
+outer_boundary_def_points = {
+    # subdomain number
+    1 : subdomain1_outer_boundary_verts,
+    2 : subdomain2_outer_boundary_verts
+}
+
+# adjacent_subdomains[i] contains the indices of the subdomains sharing the
+# interface i (i.e. given by interface_def_points[i]).
+adjacent_subdomains = [[1,2]]
+isRichards = {
+    1: False, #
+    2: False
+    }
+
+
+viscosity = {#
+# subdom_num : viscosity
+    1 : {'wetting' :1,
+         'nonwetting': 1}, #
+    2 : {'wetting' :1,
+         'nonwetting': 1}
+}
+
+porosity = {#
+# subdom_num : porosity
+    1 : 1,#
+    2 : 1
+}
+
+# Dict of the form: { subdom_num : density }
+densities = {
+    1: {'wetting': 1,  #997,
+        'nonwetting': 1}, #1225},
+    2: {'wetting': 1,  #997,
+        'nonwetting': 1}, #1225},
+}
+
+gravity_acceleration = 9.81
+
+L = {#
+# subdom_num : subdomain L for L-scheme
+    1 : {'wetting' :Lw,
+         'nonwetting': Lnw},#
+    2 : {'wetting' :Lw,
+         'nonwetting': Lnw}
+}
+
+
+lambda_param = {#
+# subdom_num : lambda parameter for the L-scheme
+    1 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw},#
+    2 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw}
+}
+
+## relative permeabilty functions on subdomain 1
+def rel_perm1w(s):
+    # relative permeabilty wetting on subdomain1
+    return s**2
+
+def rel_perm1nw(s):
+    # relative permeabilty nonwetting on subdomain1
+    return (1-s)**2
+
+_rel_perm1w = ft.partial(rel_perm1w)
+_rel_perm1nw = ft.partial(rel_perm1nw)
+
+subdomain1_rel_perm = {
+    'wetting': _rel_perm1w,#
+    'nonwetting': _rel_perm1nw
+}
+## relative permeabilty functions on subdomain 2
+def rel_perm2w(s):
+    # relative permeabilty wetting on subdomain2
+    return s**3
+def rel_perm2nw(s):
+    # relative permeabilty nonwetting on subdosym.cos(0.8*t - (0.8*x + 1/7*y))main2
+    return (1-s)**3
+
+_rel_perm2w = ft.partial(rel_perm2w)
+_rel_perm2nw = ft.partial(rel_perm2nw)
+
+subdomain2_rel_perm = {
+    'wetting': _rel_perm2w,#
+    'nonwetting': _rel_perm2nw
+}
+
+## dictionary of relative permeabilties on all domains.
+relative_permeability = {#
+    1: subdomain1_rel_perm,
+    2: subdomain2_rel_perm
+}
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm1w_prime(s):
+    # relative permeabilty on subdomain1
+    return 2*s
+
+def rel_perm1nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -2*(1-s)
+
+# # definition of the derivatives of the relative permeabilities
+# # relative permeabilty functions on subdomain 1
+def rel_perm2w_prime(s):
+    # relative permeabilty on subdomain1
+    return 3*s**2
+
+def rel_perm2nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -3*(1-s)**2
+
+_rel_perm1w_prime = ft.partial(rel_perm1w_prime)
+_rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
+_rel_perm2w_prime = ft.partial(rel_perm2w_prime)
+_rel_perm2nw_prime = ft.partial(rel_perm2nw_prime)
+
+subdomain1_rel_perm_prime = {
+    'wetting': _rel_perm1w_prime,
+    'nonwetting': _rel_perm1nw_prime
+}
+
+
+subdomain2_rel_perm_prime = {
+    'wetting': _rel_perm2w_prime,
+    'nonwetting': _rel_perm2nw_prime
+}
+
+# dictionary of relative permeabilties on all domains.
+ka_prime = {
+    1: subdomain1_rel_perm_prime,
+    2: subdomain2_rel_perm_prime,
+}
+
+
+
+def saturation(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return df.conditional(pc > 0, 1/((1 + pc)**(1/(index + 1))), 1)
+
+
+def saturation_sym(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return 1/((1 + pc)**(1/(index + 1)))
+
+
+# derivative of S-pc relationship with respect to pc. This is needed for the
+# construction of a analytic solution.
+def saturation_sym_prime(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return -1/((index+1)*(1 + pc)**((index+2)/(index+1)))
+
+
+# note that the conditional definition of S-pc in the nonsymbolic part will be
+# incorporated in the construction of the exact solution below.
+S_pc_sym = {
+    1: ft.partial(saturation_sym, index=1),
+    2: ft.partial(saturation_sym, index=2),
+    # 3: ft.partial(saturation_sym, index=2),
+    # 4: ft.partial(saturation_sym, index=1)
+}
+
+S_pc_sym_prime = {
+    1: ft.partial(saturation_sym_prime, index=1),
+    2: ft.partial(saturation_sym_prime, index=2),
+    # 3: ft.partial(saturation_sym_prime, index=2),
+    # 4: ft.partial(saturation_sym_prime, index=1)
+}
+
+sat_pressure_relationship = {
+    1: ft.partial(saturation, index=1),
+    2: ft.partial(saturation, index=2),
+    # 3: ft.partial(saturation, index=2),
+    # 4: ft.partial(saturation, index=1)
+}
+
+#
+# def saturation(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
+#
+# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
+# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# def saturation_sym(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     #df.conditional(pc > 0,
+#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
+#
+#
+# # derivative of S-pc relationship with respect to pc. This is needed for the
+# # construction of a analytic solution.
+# def saturation_sym_prime(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
+#
+# # note that the conditional definition of S-pc in the nonsymbolic part will be
+# # incorporated in the construction of the exact solution below.
+# S_pc_sym = {
+#     1: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation_sym, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation_sym, n_index=3, alpha=0.001)
+# }
+#
+# S_pc_sym_prime = {
+#     1: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation_sym_prime, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001)
+# }
+#
+# sat_pressure_relationship = {
+#     1: ft.partial(saturation, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation, n_index=3, alpha=0.001)
+# }
+#
+
+
+#############################################
+# Manufacture source expressions with sympy #
+#############################################
+x, y = sym.symbols('x[0], x[1]')  # needed by UFL
+t = sym.symbols('t', positive=True)
+
+p_e_sym = {
+    1: {'wetting': (-5.0 - (1.0 + t*t)*(1.0 + x*x + y*y)),  #*cutoff,
+        'nonwetting': 0.0*t},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+    2: {'wetting': (-5.0 - (1.0 + t*t)*(1.0 + x*x + y*y)),  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2,
+        'nonwetting': (-1-t*(1.1+y + x**2))*y**3},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+}
+
+
+pc_e_sym = dict()
+for subdomain, isR in isRichards.items():
+    if isR:
+        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting'].copy()})
+    else:
+        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting'].copy()
+                                        - p_e_sym[subdomain]['wetting'].copy()})
+
+
+symbols = {"x": x,
+           "y": y,
+           "t": t}
+# turn above symbolic code into exact solution for dolphin and
+# construct the rhs that matches the above exact solution.
+exact_solution_example = hlp.generate_exact_solution_expressions(
+                        symbols=symbols,
+                        isRichards=isRichards,
+                        symbolic_pressure=p_e_sym,
+                        symbolic_capillary_pressure=pc_e_sym,
+                        saturation_pressure_relationship=S_pc_sym,
+                        saturation_pressure_relationship_prime=S_pc_sym_prime,
+                        viscosity=viscosity,
+                        porosity=porosity,
+                        relative_permeability=relative_permeability,
+                        relative_permeability_prime=ka_prime,
+                        densities=densities,
+                        gravity_acceleration=gravity_acceleration,
+                        include_gravity=include_gravity,
+                        )
+source_expression = exact_solution_example['source']
+exact_solution = exact_solution_example['exact_solution']
+initial_condition = exact_solution_example['initial_condition']
+
+# Dictionary of dirichlet boundary conditions.
+dirichletBC = dict()
+# similarly to the outer boundary dictionary, if a patch has no outer boundary
+# None should be written instead of an expression.
+# This is a bit of a brainfuck:
+# dirichletBC[ind] gives a dictionary of the outer boundaries of subdomain ind.
+# Since a domain patch can have several disjoint outer boundary parts, the
+# expressions need to get an enumaration index which starts at 0.
+# So dirichletBC[ind][j] is the dictionary of outer dirichlet conditions of
+# subdomain ind and boundary part j.
+# Finally, dirichletBC[ind][j]['wetting'] and dirichletBC[ind][j]['nonwetting']
+# return the actual expression needed for the dirichlet condition for both
+# phases if present.
+
+# subdomain index: {outer boudary part index: {phase: expression}}
+for subdomain in isRichards.keys():
+    # if subdomain has no outer boundary, outer_boundary_def_points[subdomain] is None
+    if outer_boundary_def_points[subdomain] is None:
+        dirichletBC.update({subdomain: None})
+    else:
+        dirichletBC.update({subdomain: dict()})
+        # set the dirichlet conditions to be the same code as exact solution on
+        # the subdomain.
+        for outer_boundary_ind in outer_boundary_def_points[subdomain].keys():
+            dirichletBC[subdomain].update(
+                {outer_boundary_ind: exact_solution[subdomain]}
+                )
+
+
+# def saturation(pressure, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pressure < 0, 1/((1 - pressure)**(1/(subdomain_index + 1))), 1)
+#
+# sa
+
+for mesh_resolution, solver_tol in resolutions.items():
+    # initialise LDD simulation class
+    simulation = ldd.LDDsimulation(
+        tol=1E-14,
+        LDDsolver_tol=solver_tol,
+        debug=debugflag,
+        max_iter_num=max_iter_num,
+        FEM_Lagrange_degree=FEM_Lagrange_degree,
+        mesh_study=mesh_study
+        )
+
+    simulation.set_parameters(use_case=use_case,
+                              output_dir=output_string,
+                              subdomain_def_points=subdomain_def_points,
+                              isRichards=isRichards,
+                              interface_def_points=interface_def_points,
+                              outer_boundary_def_points=outer_boundary_def_points,
+                              adjacent_subdomains=adjacent_subdomains,
+                              mesh_resolution=mesh_resolution,
+                              viscosity=viscosity,
+                              porosity=porosity,
+                              L=L,
+                              lambda_param=lambda_param,
+                              relative_permeability=relative_permeability,
+                              saturation=sat_pressure_relationship,
+                              starttime=starttime,
+                              number_of_timesteps=number_of_timesteps,
+                              number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+                              plot_timestep_every=plot_timestep_every,
+                              timestep_size=timestep_size,
+                              sources=source_expression,
+                              initial_conditions=initial_condition,
+                              dirichletBC_expression_strings=dirichletBC,
+                              exact_solution=exact_solution,
+                              densities=densities,
+                              include_gravity=include_gravity,
+                              write2file=write_to_file,
+                              )
+
+    simulation.initialise()
+    output_dir = simulation.output_dir
+    # simulation.write_exact_solution_to_xdmf()
+    output = simulation.run(analyse_condition=analyse_condition)
+    for subdomain_index, subdomain_output in output.items():
+        mesh_h = subdomain_output['mesh_size']
+        for phase, different_errornorms in subdomain_output['errornorm'].items():
+            filename = output_dir + "subdomain{}-space-time-errornorm-{}-phase.csv".format(subdomain_index, phase)
+            # for errortype, errornorm in different_errornorms.items():
+
+                # eocfile = open("eoc_filename", "a")
+                # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
+                # eocfile.close()
+                # if subdomain.isRichards:mesh_h
+            data_dict = {
+                'mesh_parameter': mesh_resolution,
+                'mesh_h': mesh_h,
+            }
+            for error_type, errornorms in different_errornorms.items():
+                data_dict.update(
+                    {error_type: errornorms}
+                )
+            errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+            # check if file exists
+            if os.path.isfile(filename) == True:
+                with open(filename, 'a') as f:
+                    errors.to_csv(f, header=False, sep='\t', encoding='utf-8', index=False)
+            else:
+                errors.to_csv(filename, sep='\t', encoding='utf-8', index=False)
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-test.py b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-test.py
new file mode 100755
index 0000000..d892719
--- /dev/null
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/Archive/TP-TP-2-patch-test.py
@@ -0,0 +1,528 @@
+#!/usr/bin/python3
+import dolfin as df
+import mshr
+import numpy as np
+import sympy as sym
+import typing as tp
+import domainPatch as dp
+import LDDsimulation as ldd
+import functools as ft
+import helpers as hlp
+import datetime
+import os
+import pandas as pd
+
+date = datetime.datetime.now()
+datestr = date.strftime("%Y-%m-%d")
+#import ufl as ufl
+
+# init sympy session
+sym.init_printing()
+
+use_case = "TP-TP-2-patch"
+# solver_tol = 5E-7
+max_iter_num = 1000
+FEM_Lagrange_degree = 1
+mesh_study = False
+resolutions = {
+                # 1: 1e-7,  # h=2
+                # 2: 2e-5,  # h=1.1180
+                # 4: 1e-6,  # h=0.5590
+                # 8: 1e-6,  # h=0.2814
+                # 16: 5e-7, # h=0.1412
+                32: 1e-6,
+                # 64: 5e-7,
+                # 128: 5e-7
+                }
+
+
+############ GRID #######################
+# mesh_resolution = 20
+timestep_size = 0.001
+number_of_timesteps = 1500
+plot_timestep_every = 5
+# decide how many timesteps you want analysed. Analysed means, that we write out
+# subsequent errors of the L-iteration within the timestep.
+number_of_timesteps_to_analyse = 5
+starttime = 0.0
+
+Lw = 0.05 #/timestep_size
+Lnw=Lw
+
+lambda_w = 4
+lambda_nw = 4
+
+include_gravity = True
+debugflag = False
+analyse_condition = True
+
+if mesh_study:
+    output_string = "./output/{}-{}_timesteps{}_P{}".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree)
+else:
+    for tol in resolutions.values():
+        solver_tol = tol
+    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol)
+
+
+# toggle what should be written to files
+if mesh_study:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': False,
+        'absolute_differences': False,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': False
+    }
+else:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': True,
+        'absolute_differences': True,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': True
+    }
+
+##### Domain and Interface ####
+# global simulation domain domain
+sub_domain0_vertices = [df.Point(-1.0,-1.0), #
+                        df.Point(1.0,-1.0),#
+                        df.Point(1.0,1.0),#
+                        df.Point(-1.0,1.0)]
+# interface between subdomain1 and subdomain2
+interface12_vertices = [df.Point(-1.0, 0.0),
+                        df.Point(1.0, 0.0) ]
+# subdomain1.
+sub_domain1_vertices = [interface12_vertices[0],
+                        interface12_vertices[1],
+                        sub_domain0_vertices[2],
+                        sub_domain0_vertices[3] ]
+
+# vertex coordinates of the outer boundaries. If it can not be specified as a
+# polygon, use an entry per boundary polygon. This information is used for defining
+# the Dirichlet boundary conditions. If a domain is completely internal, the
+# dictionary entry should be 0: None
+subdomain1_outer_boundary_verts = {
+    0: [interface12_vertices[1],
+        sub_domain0_vertices[2],
+        sub_domain0_vertices[3], #
+        interface12_vertices[0]]
+}
+# subdomain2
+sub_domain2_vertices = [sub_domain0_vertices[0],
+                        sub_domain0_vertices[1],
+                        interface12_vertices[1],
+                        interface12_vertices[0] ]
+
+subdomain2_outer_boundary_verts = {
+    0: [interface12_vertices[0], #
+        sub_domain0_vertices[0],
+        sub_domain0_vertices[1],
+        interface12_vertices[1]]
+}
+# subdomain2_outer_boundary_verts = {
+#     0: [interface12_vertices[0], df.Point(0.0,0.0)],#
+#     1: [df.Point(0.0,0.0), df.Point(1.0,0.0)], #
+#     2: [df.Point(1.0,0.0), interface12_vertices[1]]
+# }
+# subdomain2_outer_boundary_verts = {
+#     0: None
+# }
+
+# list of subdomains given by the boundary polygon vertices.
+# Subdomains are given as a list of dolfin points forming
+# a closed polygon, such that mshr.Polygon(subdomain_def_points[i]) can be used
+# to create the subdomain. subdomain_def_points[0] contains the
+# vertices of the global simulation domain and subdomain_def_points[i] contains the
+# vertices of the subdomain i.
+subdomain_def_points = [sub_domain0_vertices,#
+                      sub_domain1_vertices,#
+                      sub_domain2_vertices]
+# in the below list, index 0 corresponds to the 12 interface which has index 1
+interface_def_points = [interface12_vertices]
+
+# if a subdomain has no outer boundary write None instead, i.e.
+# i: None
+# if i is the index of the inner subdomain.
+outer_boundary_def_points = {
+    # subdomain number
+    1 : subdomain1_outer_boundary_verts,
+    2 : subdomain2_outer_boundary_verts
+}
+
+# adjacent_subdomains[i] contains the indices of the subdomains sharing the
+# interface i (i.e. given by interface_def_points[i]).
+adjacent_subdomains = [[1,2]]
+isRichards = {
+    1: False, #
+    2: False
+    }
+
+
+viscosity = {#
+# subdom_num : viscosity
+    1 : {'wetting' :1,
+         'nonwetting': 1}, #
+    2 : {'wetting' :1,
+         'nonwetting': 1}
+}
+
+porosity = {#
+# subdom_num : porosity
+    1 : 1,#
+    2 : 1
+}
+
+# Dict of the form: { subdom_num : density }
+densities = {
+    1: {'wetting': 1,  #997,
+        'nonwetting': 1}, #1225},
+    2: {'wetting': 1,  #997,
+        'nonwetting': 1}, #1225},
+}
+
+gravity_acceleration = 1#9.81
+
+L = {#
+# subdom_num : subdomain L for L-scheme
+    1 : {'wetting' :Lw,
+         'nonwetting': Lnw},#
+    2 : {'wetting' :Lw,
+         'nonwetting': Lnw}
+}
+
+
+lambda_param = {#
+# subdom_num : lambda parameter for the L-scheme
+    1 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw},#
+    2 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw}
+}
+
+## relative permeabilty functions on subdomain 1
+def rel_perm1w(s):
+    # relative permeabilty wetting on subdomain1
+    return s**2
+
+def rel_perm1nw(s):
+    # relative permeabilty nonwetting on subdomain1
+    return (1-s)**2
+
+_rel_perm1w = ft.partial(rel_perm1w)
+_rel_perm1nw = ft.partial(rel_perm1nw)
+
+subdomain1_rel_perm = {
+    'wetting': _rel_perm1w,#
+    'nonwetting': _rel_perm1nw
+}
+## relative permeabilty functions on subdomain 2
+def rel_perm2w(s):
+    # relative permeabilty wetting on subdomain2
+    return s**3
+def rel_perm2nw(s):
+    # relative permeabilty nonwetting on subdosym.cos(0.8*t - (0.8*x + 1/7*y))main2
+    return (1-s)**3
+
+_rel_perm2w = ft.partial(rel_perm2w)
+_rel_perm2nw = ft.partial(rel_perm2nw)
+
+subdomain2_rel_perm = {
+    'wetting': _rel_perm2w,#
+    'nonwetting': _rel_perm2nw
+}
+
+## dictionary of relative permeabilties on all domains.
+relative_permeability = {#
+    1: subdomain1_rel_perm,
+    2: subdomain2_rel_perm
+}
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm1w_prime(s):
+    # relative permeabilty on subdomain1
+    return 2*s
+
+def rel_perm1nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -2*(1-s)
+
+# # definition of the derivatives of the relative permeabilities
+# # relative permeabilty functions on subdomain 1
+def rel_perm2w_prime(s):
+    # relative permeabilty on subdomain1
+    return 3*s**2
+
+def rel_perm2nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -3*(1-s)**2
+
+_rel_perm1w_prime = ft.partial(rel_perm1w_prime)
+_rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
+_rel_perm2w_prime = ft.partial(rel_perm2w_prime)
+_rel_perm2nw_prime = ft.partial(rel_perm2nw_prime)
+
+subdomain1_rel_perm_prime = {
+    'wetting': _rel_perm1w_prime,
+    'nonwetting': _rel_perm1nw_prime
+}
+
+
+subdomain2_rel_perm_prime = {
+    'wetting': _rel_perm2w_prime,
+    'nonwetting': _rel_perm2nw_prime
+}
+
+# dictionary of relative permeabilties on all domains.
+ka_prime = {
+    1: subdomain1_rel_perm_prime,
+    2: subdomain2_rel_perm_prime,
+}
+
+
+
+def saturation(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return df.conditional(pc > 0, 1/((1 + pc)**(1/(index + 1))), 1)
+
+
+def saturation_sym(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return 1/((1 + pc)**(1/(index + 1)))
+
+
+# derivative of S-pc relationship with respect to pc. This is needed for the
+# construction of a analytic solution.
+def saturation_sym_prime(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return -1/((index+1)*(1 + pc)**((index+2)/(index+1)))
+
+
+# note that the conditional definition of S-pc in the nonsymbolic part will be
+# incorporated in the construction of the exact solution below.
+S_pc_sym = {
+    1: ft.partial(saturation_sym, index=1),
+    2: ft.partial(saturation_sym, index=2),
+    # 3: ft.partial(saturation_sym, index=2),
+    # 4: ft.partial(saturation_sym, index=1)
+}
+
+S_pc_sym_prime = {
+    1: ft.partial(saturation_sym_prime, index=1),
+    2: ft.partial(saturation_sym_prime, index=2),
+    # 3: ft.partial(saturation_sym_prime, index=2),
+    # 4: ft.partial(saturation_sym_prime, index=1)
+}
+
+sat_pressure_relationship = {
+    1: ft.partial(saturation, index=1),
+    2: ft.partial(saturation, index=2),
+    # 3: ft.partial(saturation, index=2),
+    # 4: ft.partial(saturation, index=1)
+}
+
+#
+# def saturation(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
+#
+# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
+# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# def saturation_sym(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     #df.conditional(pc > 0,
+#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
+#
+#
+# # derivative of S-pc relationship with respect to pc. This is needed for the
+# # construction of a analytic solution.
+# def saturation_sym_prime(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
+#
+# # note that the conditional definition of S-pc in the nonsymbolic part will be
+# # incorporated in the construction of the exact solution below.
+# S_pc_sym = {
+#     1: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation_sym, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation_sym, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation_sym, n_index=3, alpha=0.001)
+# }
+#
+# S_pc_sym_prime = {
+#     1: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation_sym_prime, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001)
+# }
+#
+# sat_pressure_relationship = {
+#     1: ft.partial(saturation, n_index=3, alpha=0.001),
+#     2: ft.partial(saturation, n_index=6, alpha=0.001),
+#     # 3: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 4: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 5: ft.partial(saturation, n_index=3, alpha=0.001),
+#     # 6: ft.partial(saturation, n_index=3, alpha=0.001)
+# }
+#
+
+
+#############################################
+# Manufacture source expressions with sympy #
+#############################################
+x, y = sym.symbols('x[0], x[1]')  # needed by UFL
+t = sym.symbols('t', positive=True)
+
+p_e_sym = {
+    1: {'wetting': (-6 - (1+t*t)*(1 + x*x + y*y)),  #*cutoff,
+        'nonwetting': (-1 -t*(1.1+ y*y))},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+    2: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2,
+        'nonwetting': (-1 -t*(1.1 + y*y) - sym.sin((x*y-0.5*t)*y**2)**2)},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+}
+
+
+pc_e_sym = dict()
+for subdomain, isR in isRichards.items():
+    if isR:
+        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting'].copy()})
+    else:
+        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting'].copy()
+                                        - p_e_sym[subdomain]['wetting'].copy()})
+
+
+symbols = {"x": x,
+           "y": y,
+           "t": t}
+# turn above symbolic code into exact solution for dolphin and
+# construct the rhs that matches the above exact solution.
+exact_solution_example = hlp.generate_exact_solution_expressions(
+                        symbols=symbols,
+                        isRichards=isRichards,
+                        symbolic_pressure=p_e_sym,
+                        symbolic_capillary_pressure=pc_e_sym,
+                        saturation_pressure_relationship=S_pc_sym,
+                        saturation_pressure_relationship_prime=S_pc_sym_prime,
+                        viscosity=viscosity,
+                        porosity=porosity,
+                        relative_permeability=relative_permeability,
+                        relative_permeability_prime=ka_prime,
+                        densities=densities,
+                        gravity_acceleration=gravity_acceleration,
+                        include_gravity=include_gravity,
+                        )
+source_expression = exact_solution_example['source']
+exact_solution = exact_solution_example['exact_solution']
+initial_condition = exact_solution_example['initial_condition']
+
+# Dictionary of dirichlet boundary conditions.
+dirichletBC = dict()
+# similarly to the outer boundary dictionary, if a patch has no outer boundary
+# None should be written instead of an expression.
+# This is a bit of a brainfuck:
+# dirichletBC[ind] gives a dictionary of the outer boundaries of subdomain ind.
+# Since a domain patch can have several disjoint outer boundary parts, the
+# expressions need to get an enumaration index which starts at 0.
+# So dirichletBC[ind][j] is the dictionary of outer dirichlet conditions of
+# subdomain ind and boundary part j.
+# Finally, dirichletBC[ind][j]['wetting'] and dirichletBC[ind][j]['nonwetting']
+# return the actual expression needed for the dirichlet condition for both
+# phases if present.
+
+# subdomain index: {outer boudary part index: {phase: expression}}
+for subdomain in isRichards.keys():
+    # if subdomain has no outer boundary, outer_boundary_def_points[subdomain] is None
+    if outer_boundary_def_points[subdomain] is None:
+        dirichletBC.update({subdomain: None})
+    else:
+        dirichletBC.update({subdomain: dict()})
+        # set the dirichlet conditions to be the same code as exact solution on
+        # the subdomain.
+        for outer_boundary_ind in outer_boundary_def_points[subdomain].keys():
+            dirichletBC[subdomain].update(
+                {outer_boundary_ind: exact_solution[subdomain]}
+                )
+
+
+# def saturation(pressure, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pressure < 0, 1/((1 - pressure)**(1/(subdomain_index + 1))), 1)
+#
+# sa
+
+for mesh_resolution, solver_tol in resolutions.items():
+    # initialise LDD simulation class
+    simulation = ldd.LDDsimulation(
+        tol=1E-14,
+        LDDsolver_tol=solver_tol,
+        debug=debugflag,
+        max_iter_num=max_iter_num,
+        FEM_Lagrange_degree=FEM_Lagrange_degree,
+        mesh_study=mesh_study
+        )
+
+    simulation.set_parameters(use_case=use_case,
+                              output_dir=output_string,
+                              subdomain_def_points=subdomain_def_points,
+                              isRichards=isRichards,
+                              interface_def_points=interface_def_points,
+                              outer_boundary_def_points=outer_boundary_def_points,
+                              adjacent_subdomains=adjacent_subdomains,
+                              mesh_resolution=mesh_resolution,
+                              viscosity=viscosity,
+                              porosity=porosity,
+                              L=L,
+                              lambda_param=lambda_param,
+                              relative_permeability=relative_permeability,
+                              saturation=sat_pressure_relationship,
+                              starttime=starttime,
+                              number_of_timesteps=number_of_timesteps,
+                              number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+                              plot_timestep_every=plot_timestep_every,
+                              timestep_size=timestep_size,
+                              sources=source_expression,
+                              initial_conditions=initial_condition,
+                              dirichletBC_expression_strings=dirichletBC,
+                              exact_solution=exact_solution,
+                              densities=densities,
+                              include_gravity=include_gravity,
+                              write2file=write_to_file,
+                              )
+
+    simulation.initialise()
+    output_dir = simulation.output_dir
+    # simulation.write_exact_solution_to_xdmf()
+    output = simulation.run(analyse_condition=analyse_condition)
+    for subdomain_index, subdomain_output in output.items():
+        mesh_h = subdomain_output['mesh_size']
+        for phase, different_errornorms in subdomain_output['errornorm'].items():
+            filename = output_dir + "subdomain{}-space-time-errornorm-{}-phase.csv".format(subdomain_index, phase)
+            # for errortype, errornorm in different_errornorms.items():
+
+                # eocfile = open("eoc_filename", "a")
+                # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
+                # eocfile.close()
+                # if subdomain.isRichards:mesh_h
+            data_dict = {
+                'mesh_parameter': mesh_resolution,
+                'mesh_h': mesh_h,
+            }
+            for error_type, errornorms in different_errornorms.items():
+                data_dict.update(
+                    {error_type: errornorms}
+                )
+            errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+            # check if file exists
+            if os.path.isfile(filename) == True:
+                with open(filename, 'a') as f:
+                    errors.to_csv(f, header=False, sep='\t', encoding='utf-8', index=False)
+            else:
+                errors.to_csv(filename, sep='\t', encoding='utf-8', index=False)
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-different-intrinsic-perm.py b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-different-intrinsic-perm.py
new file mode 100755
index 0000000..0daba08
--- /dev/null
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-different-intrinsic-perm.py
@@ -0,0 +1,598 @@
+#!/usr/bin/python3
+"""TP-TP 2 patch soil simulation.
+
+This program sets up an LDD simulation
+"""
+
+import dolfin as df
+import sympy as sym
+import functools as ft
+import LDDsimulation as ldd
+import helpers as hlp
+import datetime
+import os
+import pandas as pd
+
+# init sympy session
+sym.init_printing()
+
+# PREREQUISITS  ###############################################################
+# check if output directory "./output" exists. This will be used in
+# the generation of the output string.
+if not os.path.exists('./output'):
+    os.mkdir('./output')
+    print("Directory ", './output',  " created ")
+else:
+    print("Directory ", './output',  " already exists. Will use as output \
+    directory")
+
+date = datetime.datetime.now()
+datestr = date.strftime("%Y-%m-%d")
+
+# Name of the usecase that will be printed during simulation.
+use_case = "TP-TP-2P-realistic-different-intrinsic-perm"
+# The name of this very file. Needed for creating log output.
+thisfile = "TP-TP-2-patch-different-intrinsic-perm.py"
+
+# GENERAL SOLVER CONFIG  ######################################################
+# maximal iteration per timestep
+max_iter_num = 300
+FEM_Lagrange_degree = 1
+
+# GRID AND MESH STUDY SPECIFICATIONS  #########################################
+mesh_study = False
+resolutions = {
+                # 1: 1e-6,
+                # 2: 1e-6,
+                # 4: 1e-6,
+                # 8: 1e-6,
+                # 16: 5e-6,
+                32: 3e-6,
+                # 64: 2e-6,
+                # 128: 1e-6,
+                # 256: 1e-6,
+                }
+
+# starttimes gives a list of starttimes to run the simulation from.
+# The list is looped over and a simulation is run with t_0 as initial time
+#  for each element t_0 in starttimes.
+starttimes = [0.0]
+timestep_size = 0.001
+number_of_timesteps = 1000
+
+# LDD scheme parameters  ######################################################
+Lw1 = 0.25 #/timestep_size
+Lnw1= 0.25
+
+Lw2 = 0.25 #/timestep_size
+Lnw2= 0.25
+
+lambda_w = 4
+lambda_nw = 4
+
+include_gravity = True
+debugflag = False
+analyse_condition = False
+
+# I/O CONFIG  #################################################################
+# when number_of_timesteps is high, it might take a long time to write all
+# timesteps to disk. Therefore, you can choose to only write data of every
+# plot_timestep_every timestep to disk.
+plot_timestep_every = 4
+# Decide how many timesteps you want analysed. Analysed means, that
+# subsequent errors of the L-iteration within the timestep are written out.
+number_of_timesteps_to_analyse = 5
+
+# fine grained control over data to be written to disk in the mesh study case
+# as well as for a regular simuation for a fixed grid.
+if mesh_study:
+    write_to_file = {
+        # output the relative errornorm (integration in space) w.r.t. an exact
+        # solution for each timestep into a csv file.
+        'space_errornorms': True,
+        # save the mesh and marker functions to disk
+        'meshes_and_markers': True,
+        # save xdmf/h5 data for each LDD iteration for timesteps determined by
+        # number_of_timesteps_to_analyse. I/O intensive!
+        'L_iterations_per_timestep': False,
+        # save solution to xdmf/h5.
+        'solutions': True,
+        # save absolute differences w.r.t an exact solution to xdmf/h5 file
+        # to monitor where on the domains errors happen
+        'absolute_differences': True,
+        # analyise condition numbers for timesteps determined by
+        # number_of_timesteps_to_analyse and save them over time to csv.
+        'condition_numbers': analyse_condition,
+        # output subsequent iteration errors measured in L^2  to csv for
+        # timesteps determined by number_of_timesteps_to_analyse.
+        # Usefull to monitor convergence of the acutal LDD solver.
+        'subsequent_errors': True
+    }
+else:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': True,
+        'absolute_differences': True,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': True
+    }
+
+# OUTPUT FILE STRING  #########################################################
+if mesh_study:
+    output_string = "./output/{}-{}_timesteps{}_P{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree
+        )
+else:
+    for tol in resolutions.values():
+        solver_tol = tol
+    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol
+        )
+
+
+# DOMAIN AND INTERFACE  #######################################################
+# global simulation domain domain
+sub_domain0_vertices = [df.Point(-1.0, -1.0),
+                        df.Point(1.0, -1.0),
+                        df.Point(1.0, 1.0),
+                        df.Point(-1.0, 1.0)]
+# interface between subdomain1 and subdomain2
+interface12_vertices = [df.Point(-1.0, 0.0),
+                        df.Point(1.0, 0.0) ]
+# subdomain1.
+sub_domain1_vertices = [interface12_vertices[0],
+                        interface12_vertices[1],
+                        sub_domain0_vertices[2],
+                        sub_domain0_vertices[3]]
+
+# vertex coordinates of the outer boundaries. If it can not be specified as a
+# polygon, use an entry per boundary polygon. This information is used for defining
+# the Dirichlet boundary conditions. If a domain is completely internal, the
+# dictionary entry should be 0: None
+subdomain1_outer_boundary_verts = {
+    0: [interface12_vertices[1], #
+        sub_domain0_vertices[2],
+        sub_domain0_vertices[3], #
+        interface12_vertices[0]]
+}
+# subdomain2
+sub_domain2_vertices = [sub_domain0_vertices[0],
+                        sub_domain0_vertices[1],
+                        interface12_vertices[1],
+                        interface12_vertices[0] ]
+
+subdomain2_outer_boundary_verts = {
+    0: [interface12_vertices[0], #
+        sub_domain0_vertices[0],
+        sub_domain0_vertices[1],
+        interface12_vertices[1]]
+}
+
+# list of subdomains given by the boundary polygon vertices.
+# Subdomains are given as a list of dolfin points forming
+# a closed polygon, such that mshr.Polygon(subdomain_def_points[i]) can be used
+# to create the subdomain. subdomain_def_points[0] contains the
+# vertices of the global simulation domain and subdomain_def_points[i] contains the
+# vertices of the subdomain i.
+subdomain_def_points = [sub_domain0_vertices,#
+                      sub_domain1_vertices,#
+                      sub_domain2_vertices]
+# in the below list, index 0 corresponds to the 12 interface which has index 1
+interface_def_points = [interface12_vertices]
+
+# if a subdomain has no outer boundary write None instead, i.e.
+# i: None
+# if i is the index of the inner subdomain.
+outer_boundary_def_points = {
+    # subdomain number
+    1 : subdomain1_outer_boundary_verts,
+    2 : subdomain2_outer_boundary_verts
+}
+
+# adjacent_subdomains[i] contains the indices of the subdomains sharing the
+# interface i (i.e. given by interface_def_points[i]).
+adjacent_subdomains = [[1,2]]
+
+
+# MODEL CONFIGURATION #########################################################
+isRichards = {
+    1: False, #
+    2: False
+    }
+
+
+viscosity = {#
+# subdom_num : viscosity
+    1: {'wetting' :1.0,
+         'nonwetting': 1/50}, #
+    2: {'wetting' :1.0,
+         'nonwetting': 1/50}
+}
+
+porosity = {#
+# subdom_num : porosity
+    1: 0.22,#
+    2: 0.22
+}
+
+# Dict of the form: { subdom_num : density }
+densities = {
+    1: {'wetting': 997.0,
+        'nonwetting': 1.225},
+    2: {'wetting': 997.0,
+        'nonwetting': 1.225}
+}
+
+gravity_acceleration = 9.81
+
+L = {#
+# subdom_num : subdomain L for L-scheme
+    1 : {'wetting' :Lw1,
+         'nonwetting': Lnw1},#
+    2 : {'wetting' :Lw2,
+         'nonwetting': Lnw2}
+}
+
+
+lambda_param = {#
+# subdom_num : lambda parameter for the L-scheme
+    0 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw},#
+}
+
+intrinsic_permeability = {
+    1: 0.1,
+    2: 0.01,
+}
+
+
+## relative permeabilty functions on subdomain 1
+def rel_perm1w(s):
+    # relative permeabilty wetting on subdomain1
+    return intrinsic_permeability[1]*s**2
+
+def rel_perm1nw(s):
+    # relative permeabilty nonwetting on subdomain1
+    return intrinsic_permeability[1]*(1-s)**2
+
+_rel_perm1w = ft.partial(rel_perm1w)
+_rel_perm1nw = ft.partial(rel_perm1nw)
+
+subdomain1_rel_perm = {
+    'wetting': _rel_perm1w,#
+    'nonwetting': _rel_perm1nw
+}
+## relative permeabilty functions on subdomain 2
+def rel_perm2w(s):
+    # relative permeabilty wetting on subdomain2
+    return intrinsic_permeability[2]*s**3
+def rel_perm2nw(s):
+    # relative permeabilty nonwetting on subdomain2
+    return intrinsic_permeability[2]*(1-s)**3
+
+_rel_perm2w = ft.partial(rel_perm2w)
+_rel_perm2nw = ft.partial(rel_perm2nw)
+
+subdomain2_rel_perm = {
+    'wetting': _rel_perm2w,#
+    'nonwetting': _rel_perm2nw
+}
+
+## dictionary of relative permeabilties on all domains.
+relative_permeability = {#
+    1: subdomain1_rel_perm,
+    2: subdomain2_rel_perm
+}
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm1w_prime(s):
+    # relative permeabilty on subdomain1
+    return intrinsic_permeability[1]*2*s
+
+def rel_perm1nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -1*intrinsic_permeability[1]*2*(1-s)
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm2w_prime(s):
+    # relative permeabilty on subdomain2
+    return intrinsic_permeability[2]*3*s**2
+
+def rel_perm2nw_prime(s):
+    # relative permeabilty on subdomain2
+    return -3*intrinsic_permeability[2]*(1-s)**2
+
+_rel_perm1w_prime = ft.partial(rel_perm1w_prime)
+_rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
+_rel_perm2w_prime = ft.partial(rel_perm2w_prime)
+_rel_perm2nw_prime = ft.partial(rel_perm2nw_prime)
+
+subdomain1_rel_perm_prime = {
+    'wetting': _rel_perm1w_prime,
+    'nonwetting': _rel_perm1nw_prime
+}
+
+
+subdomain2_rel_perm_prime = {
+    'wetting': _rel_perm2w_prime,
+    'nonwetting': _rel_perm2nw_prime
+}
+
+# dictionary of relative permeabilties on all domains.
+ka_prime = {
+    1: subdomain1_rel_perm_prime,
+    2: subdomain2_rel_perm_prime,
+}
+
+
+# def saturation1(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + pc)**(1/(subdomain_index + 1))), 1)
+#
+# def saturation2(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
+#
+# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
+# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# def saturation1_sym(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return 1/((1 + pc)**(1/(subdomain_index + 1)))
+#
+#
+# def saturation2_sym(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     #df.conditional(pc > 0,
+#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
+#
+#
+# # derivative of S-pc relationship with respect to pc. This is needed for the
+# # construction of a analytic solution.
+# def saturation1_sym_prime(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(1/(subdomain_index + 1))*(1 + pc)**((-subdomain_index - 2)/(subdomain_index + 1))
+#
+#
+# def saturation2_sym_prime(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
+#
+# # note that the conditional definition of S-pc in the nonsymbolic part will be
+# # incorporated in the construction of the exact solution below.
+# S_pc_sym = {
+#     1: ft.partial(saturation1_sym, subdomain_index = 1),
+#     2: ft.partial(saturation2_sym, n_index=3, alpha=0.001),
+# }
+#
+# S_pc_sym_prime = {
+#     1: ft.partial(saturation1_sym_prime, subdomain_index = 1),
+#     2: ft.partial(saturation2_sym_prime, n_index=3, alpha=0.001),
+# }
+#
+# sat_pressure_relationship = {
+#     1: ft.partial(saturation1, subdomain_index = 1),#,
+#     2: ft.partial(saturation2, n_index=3, alpha=0.001),
+# }
+
+def saturation(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return df.conditional(pc > 0, 1/((1 + pc)**(1/(index + 1))), 1)
+
+
+def saturation_sym(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return 1/((1 + pc)**(1/(index + 1)))
+
+
+# derivative of S-pc relationship with respect to pc. This is needed for the
+# construction of a analytic solution.
+def saturation_sym_prime(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return -1/((index+1)*(1 + pc)**((index+2)/(index+1)))
+
+
+# note that the conditional definition of S-pc in the nonsymbolic part will be
+# incorporated in the construction of the exact solution below.
+S_pc_sym = {
+    1: ft.partial(saturation_sym, index=1),
+    2: ft.partial(saturation_sym, index=2),
+    # 3: ft.partial(saturation_sym, index=2),
+    # 4: ft.partial(saturation_sym, index=1)
+}
+
+S_pc_sym_prime = {
+    1: ft.partial(saturation_sym_prime, index=1),
+    2: ft.partial(saturation_sym_prime, index=2),
+    # 3: ft.partial(saturation_sym_prime, index=2),
+    # 4: ft.partial(saturation_sym_prime, index=1)
+}
+
+sat_pressure_relationship = {
+    1: ft.partial(saturation, index=1),
+    2: ft.partial(saturation, index=2),
+    # 3: ft.partial(saturation, index=2),
+    # 4: ft.partial(saturation, index=1)
+}
+
+
+###############################################################################
+# Manufacture source expressions with sympy #
+###############################################################################
+x, y = sym.symbols('x[0], x[1]')  # needed by UFL
+t = sym.symbols('t', positive=True)
+
+# p_e_sym = {
+#     1: {'wetting': (-7.0 - (1.0 + t*t)*(1.0 + x*x + y*y))}, #*(1-x)**2*(1+x)**2*(1-y)**2},
+#     2: {'wetting': (-7.0 - (1.0 + t*t)*(1.0 + x*x)), #*(1-x)**2*(1+x)**2*(1+y)**2,
+#         'nonwetting': (-2-t*(1.1+y + x**2))*y**2}, #*(1-x)**2*(1+x)**2*(1+y)**2},
+# } #-y*y*(sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)) - t*t*x*(0.5-y)*y*(1-x)
+
+p_e_sym = {
+    1: {'wetting': (-6 - (1+t*t)*(1 + x*x + y*y)),  #*cutoff,
+        'nonwetting': (-1 -t*(1.1+ y*y))},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+    2: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2,
+        'nonwetting': (-1 -t*(1.1 + y*y) - sym.sin((x*y-0.5*t)*y**2)**2)},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+}
+
+
+pc_e_sym = dict()
+for subdomain, isR in isRichards.items():
+    if isR:
+        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting'].copy()})
+    else:
+        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting'].copy()
+                                        - p_e_sym[subdomain]['wetting'].copy()})
+
+
+symbols = {"x": x,
+           "y": y,
+           "t": t}
+# turn above symbolic code into exact solution for dolphin and
+# construct the rhs that matches the above exact solution.
+exact_solution_example = hlp.generate_exact_solution_expressions(
+                        symbols=symbols,
+                        isRichards=isRichards,
+                        symbolic_pressure=p_e_sym,
+                        symbolic_capillary_pressure=pc_e_sym,
+                        saturation_pressure_relationship=S_pc_sym,
+                        saturation_pressure_relationship_prime=S_pc_sym_prime,
+                        viscosity=viscosity,
+                        porosity=porosity,
+                        relative_permeability=relative_permeability,
+                        relative_permeability_prime=ka_prime,
+                        densities=densities,
+                        gravity_acceleration=gravity_acceleration,
+                        include_gravity=include_gravity,
+                        )
+source_expression = exact_solution_example['source']
+exact_solution = exact_solution_example['exact_solution']
+initial_condition = exact_solution_example['initial_condition']
+
+# BOUNDARY CONDITIONS #########################################################
+# Dictionary of dirichlet boundary conditions.
+dirichletBC = dict()
+# similarly to the outer boundary dictionary, if a patch has no outer boundary
+# None should be written instead of an expression.
+# This is a bit of a brainfuck:
+# dirichletBC[ind] gives a dictionary of the outer boundaries of subdomain ind.
+# Since a domain patch can have several disjoint outer boundary parts, the
+# expressions need to get an enumaration index which starts at 0.
+# So dirichletBC[ind][j] is the dictionary of outer dirichlet conditions of
+# subdomain ind and boundary part j.
+# Finally, dirichletBC[ind][j]['wetting'] and dirichletBC[ind][j]['nonwetting']
+# return the actual expression needed for the dirichlet condition for both
+# phases if present.
+
+# subdomain index: {outer boudary part index: {phase: expression}}
+for subdomain in isRichards.keys():
+    # subdomain can have no outer boundary
+    if outer_boundary_def_points[subdomain] is None:
+        dirichletBC.update({subdomain: None})
+    else:
+        dirichletBC.update({subdomain: dict()})
+        # set the dirichlet conditions to be the same code as exact solution on
+        # the subdomain.
+        for outer_boundary_ind in outer_boundary_def_points[subdomain].keys():
+            dirichletBC[subdomain].update(
+                {outer_boundary_ind: exact_solution[subdomain]}
+                )
+
+
+# LOG FILE OUTPUT #############################################################
+# read this file and print it to std out. This way the simulation can produce a
+# log file with ./TP-R-layered_soil.py | tee simulation.log
+f = open(thisfile, 'r')
+print(f.read())
+f.close()
+
+
+# RUN #########################################################################
+for starttime in starttimes:
+    for mesh_resolution, solver_tol in resolutions.items():
+        # initialise LDD simulation class
+        simulation = ldd.LDDsimulation(
+            tol=1E-14,
+            LDDsolver_tol=solver_tol,
+            debug=debugflag,
+            max_iter_num=max_iter_num,
+            FEM_Lagrange_degree=FEM_Lagrange_degree,
+            mesh_study=mesh_study
+            )
+
+        simulation.set_parameters(
+            use_case=use_case,
+            output_dir=output_string,
+            subdomain_def_points=subdomain_def_points,
+            isRichards=isRichards,
+            interface_def_points=interface_def_points,
+            outer_boundary_def_points=outer_boundary_def_points,
+            adjacent_subdomains=adjacent_subdomains,
+            mesh_resolution=mesh_resolution,
+            viscosity=viscosity,
+            porosity=porosity,
+            L=L,
+            lambda_param=lambda_param,
+            relative_permeability=relative_permeability,
+            saturation=sat_pressure_relationship,
+            starttime=starttime,
+            number_of_timesteps=number_of_timesteps,
+            number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+            plot_timestep_every=plot_timestep_every,
+            timestep_size=timestep_size,
+            sources=source_expression,
+            initial_conditions=initial_condition,
+            dirichletBC_expression_strings=dirichletBC,
+            exact_solution=exact_solution,
+            densities=densities,
+            include_gravity=include_gravity,
+            gravity_acceleration=gravity_acceleration,
+            write2file=write_to_file,
+            )
+
+        simulation.initialise()
+        output_dir = simulation.output_dir
+        # simulation.write_exact_solution_to_xdmf()
+        output = simulation.run(analyse_condition=analyse_condition)
+        for subdomain_index, subdomain_output in output.items():
+            mesh_h = subdomain_output['mesh_size']
+            for phase, error_dict in subdomain_output['errornorm'].items():
+                filename = output_dir \
+                    + "subdomain{}".format(subdomain_index)\
+                    + "-space-time-errornorm-{}-phase.csv".format(phase)
+                # for errortype, errornorm in error_dict.items():
+
+                # eocfile = open("eoc_filename", "a")
+                # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
+                # eocfile.close()
+                # if subdomain.isRichards:mesh_h
+                data_dict = {
+                    'mesh_parameter': mesh_resolution,
+                    'mesh_h': mesh_h,
+                }
+                for norm_type, errornorm in error_dict.items():
+                    data_dict.update(
+                        {norm_type: errornorm}
+                    )
+                errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+                # check if file exists
+                if os.path.isfile(filename) is True:
+                    with open(filename, 'a') as f:
+                        errors.to_csv(
+                            f,
+                            header=False,
+                            sep='\t',
+                            encoding='utf-8',
+                            index=False
+                            )
+                else:
+                    errors.to_csv(
+                        filename,
+                        sep='\t',
+                        encoding='utf-8',
+                        index=False
+                        )
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-same-intrinsic-perm.py b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-same-intrinsic-perm.py
new file mode 100755
index 0000000..9c10e94
--- /dev/null
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-same-intrinsic-perm.py
@@ -0,0 +1,598 @@
+#!/usr/bin/python3
+"""TP-TP 2 patch soil simulation.
+
+This program sets up an LDD simulation
+"""
+
+import dolfin as df
+import sympy as sym
+import functools as ft
+import LDDsimulation as ldd
+import helpers as hlp
+import datetime
+import os
+import pandas as pd
+
+# init sympy session
+sym.init_printing()
+
+# PREREQUISITS  ###############################################################
+# check if output directory "./output" exists. This will be used in
+# the generation of the output string.
+if not os.path.exists('./output'):
+    os.mkdir('./output')
+    print("Directory ", './output',  " created ")
+else:
+    print("Directory ", './output',  " already exists. Will use as output \
+    directory")
+
+date = datetime.datetime.now()
+datestr = date.strftime("%Y-%m-%d")
+
+# Name of the usecase that will be printed during simulation.
+use_case = "TP-TP-2P-realistic-same-intrinsic-perm"
+# The name of this very file. Needed for creating log output.
+thisfile = "TP-TP-2-patch-same-intrinsic-perm.py"
+
+# GENERAL SOLVER CONFIG  ######################################################
+# maximal iteration per timestep
+max_iter_num = 300
+FEM_Lagrange_degree = 1
+
+# GRID AND MESH STUDY SPECIFICATIONS  #########################################
+mesh_study = False
+resolutions = {
+                # 1: 1e-6,
+                # 2: 1e-6,
+                # 4: 1e-6,
+                # 8: 1e-6,
+                # 16: 5e-6,
+                32: 3e-6,
+                # 64: 2e-6,
+                # 128: 1e-6,
+                # 256: 1e-6,
+                }
+
+# starttimes gives a list of starttimes to run the simulation from.
+# The list is looped over and a simulation is run with t_0 as initial time
+#  for each element t_0 in starttimes.
+starttimes = [0.0]
+timestep_size = 0.001
+number_of_timesteps = 1000
+
+# LDD scheme parameters  ######################################################
+Lw1 = 0.25 #/timestep_size
+Lnw1= 0.25
+
+Lw2 = 0.25 #/timestep_size
+Lnw2= 0.25
+
+lambda_w = 4
+lambda_nw = 4
+
+include_gravity = True
+debugflag = False
+analyse_condition = False
+
+# I/O CONFIG  #################################################################
+# when number_of_timesteps is high, it might take a long time to write all
+# timesteps to disk. Therefore, you can choose to only write data of every
+# plot_timestep_every timestep to disk.
+plot_timestep_every = 4
+# Decide how many timesteps you want analysed. Analysed means, that
+# subsequent errors of the L-iteration within the timestep are written out.
+number_of_timesteps_to_analyse = 5
+
+# fine grained control over data to be written to disk in the mesh study case
+# as well as for a regular simuation for a fixed grid.
+if mesh_study:
+    write_to_file = {
+        # output the relative errornorm (integration in space) w.r.t. an exact
+        # solution for each timestep into a csv file.
+        'space_errornorms': True,
+        # save the mesh and marker functions to disk
+        'meshes_and_markers': True,
+        # save xdmf/h5 data for each LDD iteration for timesteps determined by
+        # number_of_timesteps_to_analyse. I/O intensive!
+        'L_iterations_per_timestep': False,
+        # save solution to xdmf/h5.
+        'solutions': True,
+        # save absolute differences w.r.t an exact solution to xdmf/h5 file
+        # to monitor where on the domains errors happen
+        'absolute_differences': True,
+        # analyise condition numbers for timesteps determined by
+        # number_of_timesteps_to_analyse and save them over time to csv.
+        'condition_numbers': analyse_condition,
+        # output subsequent iteration errors measured in L^2  to csv for
+        # timesteps determined by number_of_timesteps_to_analyse.
+        # Usefull to monitor convergence of the acutal LDD solver.
+        'subsequent_errors': True
+    }
+else:
+    write_to_file = {
+        'space_errornorms': True,
+        'meshes_and_markers': True,
+        'L_iterations_per_timestep': False,
+        'solutions': True,
+        'absolute_differences': True,
+        'condition_numbers': analyse_condition,
+        'subsequent_errors': True
+    }
+
+# OUTPUT FILE STRING  #########################################################
+if mesh_study:
+    output_string = "./output/{}-{}_timesteps{}_P{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree
+        )
+else:
+    for tol in resolutions.values():
+        solver_tol = tol
+    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol
+        )
+
+
+# DOMAIN AND INTERFACE  #######################################################
+# global simulation domain domain
+sub_domain0_vertices = [df.Point(-1.0, -1.0),
+                        df.Point(1.0, -1.0),
+                        df.Point(1.0, 1.0),
+                        df.Point(-1.0, 1.0)]
+# interface between subdomain1 and subdomain2
+interface12_vertices = [df.Point(-1.0, 0.0),
+                        df.Point(1.0, 0.0) ]
+# subdomain1.
+sub_domain1_vertices = [interface12_vertices[0],
+                        interface12_vertices[1],
+                        sub_domain0_vertices[2],
+                        sub_domain0_vertices[3]]
+
+# vertex coordinates of the outer boundaries. If it can not be specified as a
+# polygon, use an entry per boundary polygon. This information is used for defining
+# the Dirichlet boundary conditions. If a domain is completely internal, the
+# dictionary entry should be 0: None
+subdomain1_outer_boundary_verts = {
+    0: [interface12_vertices[1], #
+        sub_domain0_vertices[2],
+        sub_domain0_vertices[3], #
+        interface12_vertices[0]]
+}
+# subdomain2
+sub_domain2_vertices = [sub_domain0_vertices[0],
+                        sub_domain0_vertices[1],
+                        interface12_vertices[1],
+                        interface12_vertices[0] ]
+
+subdomain2_outer_boundary_verts = {
+    0: [interface12_vertices[0], #
+        sub_domain0_vertices[0],
+        sub_domain0_vertices[1],
+        interface12_vertices[1]]
+}
+
+# list of subdomains given by the boundary polygon vertices.
+# Subdomains are given as a list of dolfin points forming
+# a closed polygon, such that mshr.Polygon(subdomain_def_points[i]) can be used
+# to create the subdomain. subdomain_def_points[0] contains the
+# vertices of the global simulation domain and subdomain_def_points[i] contains the
+# vertices of the subdomain i.
+subdomain_def_points = [sub_domain0_vertices,#
+                      sub_domain1_vertices,#
+                      sub_domain2_vertices]
+# in the below list, index 0 corresponds to the 12 interface which has index 1
+interface_def_points = [interface12_vertices]
+
+# if a subdomain has no outer boundary write None instead, i.e.
+# i: None
+# if i is the index of the inner subdomain.
+outer_boundary_def_points = {
+    # subdomain number
+    1 : subdomain1_outer_boundary_verts,
+    2 : subdomain2_outer_boundary_verts
+}
+
+# adjacent_subdomains[i] contains the indices of the subdomains sharing the
+# interface i (i.e. given by interface_def_points[i]).
+adjacent_subdomains = [[1,2]]
+
+
+# MODEL CONFIGURATION #########################################################
+isRichards = {
+    1: False, #
+    2: False
+    }
+
+
+viscosity = {#
+# subdom_num : viscosity
+    1: {'wetting' :1.0,
+         'nonwetting': 1/50}, #
+    2: {'wetting' :1.0,
+         'nonwetting': 1/50}
+}
+
+porosity = {#
+# subdom_num : porosity
+    1: 0.22,#
+    2: 0.22
+}
+
+# Dict of the form: { subdom_num : density }
+densities = {
+    1: {'wetting': 997.0,
+        'nonwetting': 1.225},
+    2: {'wetting': 997.0,
+        'nonwetting': 1.225}
+}
+
+gravity_acceleration = 9.81
+
+L = {#
+# subdom_num : subdomain L for L-scheme
+    1 : {'wetting' :Lw1,
+         'nonwetting': Lnw1},#
+    2 : {'wetting' :Lw2,
+         'nonwetting': Lnw2}
+}
+
+
+lambda_param = {#
+# subdom_num : lambda parameter for the L-scheme
+    0 : {'wetting' :lambda_w,
+         'nonwetting': lambda_nw},#
+}
+
+intrinsic_permeability = {
+    1: 0.1,
+    2: 0.1,
+}
+
+
+## relative permeabilty functions on subdomain 1
+def rel_perm1w(s):
+    # relative permeabilty wetting on subdomain1
+    return intrinsic_permeability[1]*s**2
+
+def rel_perm1nw(s):
+    # relative permeabilty nonwetting on subdomain1
+    return intrinsic_permeability[1]*(1-s)**2
+
+_rel_perm1w = ft.partial(rel_perm1w)
+_rel_perm1nw = ft.partial(rel_perm1nw)
+
+subdomain1_rel_perm = {
+    'wetting': _rel_perm1w,#
+    'nonwetting': _rel_perm1nw
+}
+## relative permeabilty functions on subdomain 2
+def rel_perm2w(s):
+    # relative permeabilty wetting on subdomain2
+    return intrinsic_permeability[2]*s**3
+def rel_perm2nw(s):
+    # relative permeabilty nonwetting on subdomain2
+    return intrinsic_permeability[2]*(1-s)**3
+
+_rel_perm2w = ft.partial(rel_perm2w)
+_rel_perm2nw = ft.partial(rel_perm2nw)
+
+subdomain2_rel_perm = {
+    'wetting': _rel_perm2w,#
+    'nonwetting': _rel_perm2nw
+}
+
+## dictionary of relative permeabilties on all domains.
+relative_permeability = {#
+    1: subdomain1_rel_perm,
+    2: subdomain2_rel_perm
+}
+
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm1w_prime(s):
+    # relative permeabilty on subdomain1
+    return intrinsic_permeability[1]*2*s
+
+def rel_perm1nw_prime(s):
+    # relative permeabilty on subdomain1
+    return -1*intrinsic_permeability[1]*2*(1-s)
+
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
+def rel_perm2w_prime(s):
+    # relative permeabilty on subdomain2
+    return intrinsic_permeability[2]*3*s**2
+
+def rel_perm2nw_prime(s):
+    # relative permeabilty on subdomain2
+    return -3*intrinsic_permeability[2]*(1-s)**2
+
+_rel_perm1w_prime = ft.partial(rel_perm1w_prime)
+_rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
+_rel_perm2w_prime = ft.partial(rel_perm2w_prime)
+_rel_perm2nw_prime = ft.partial(rel_perm2nw_prime)
+
+subdomain1_rel_perm_prime = {
+    'wetting': _rel_perm1w_prime,
+    'nonwetting': _rel_perm1nw_prime
+}
+
+
+subdomain2_rel_perm_prime = {
+    'wetting': _rel_perm2w_prime,
+    'nonwetting': _rel_perm2nw_prime
+}
+
+# dictionary of relative permeabilties on all domains.
+ka_prime = {
+    1: subdomain1_rel_perm_prime,
+    2: subdomain2_rel_perm_prime,
+}
+
+
+# def saturation1(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + pc)**(1/(subdomain_index + 1))), 1)
+#
+# def saturation2(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
+#
+# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
+# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# def saturation1_sym(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return 1/((1 + pc)**(1/(subdomain_index + 1)))
+#
+#
+# def saturation2_sym(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     #df.conditional(pc > 0,
+#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
+#
+#
+# # derivative of S-pc relationship with respect to pc. This is needed for the
+# # construction of a analytic solution.
+# def saturation1_sym_prime(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(1/(subdomain_index + 1))*(1 + pc)**((-subdomain_index - 2)/(subdomain_index + 1))
+#
+#
+# def saturation2_sym_prime(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
+#
+# # note that the conditional definition of S-pc in the nonsymbolic part will be
+# # incorporated in the construction of the exact solution below.
+# S_pc_sym = {
+#     1: ft.partial(saturation1_sym, subdomain_index = 1),
+#     2: ft.partial(saturation2_sym, n_index=3, alpha=0.001),
+# }
+#
+# S_pc_sym_prime = {
+#     1: ft.partial(saturation1_sym_prime, subdomain_index = 1),
+#     2: ft.partial(saturation2_sym_prime, n_index=3, alpha=0.001),
+# }
+#
+# sat_pressure_relationship = {
+#     1: ft.partial(saturation1, subdomain_index = 1),#,
+#     2: ft.partial(saturation2, n_index=3, alpha=0.001),
+# }
+
+def saturation(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return df.conditional(pc > 0, 1/((1 + pc)**(1/(index + 1))), 1)
+
+
+def saturation_sym(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return 1/((1 + pc)**(1/(index + 1)))
+
+
+# derivative of S-pc relationship with respect to pc. This is needed for the
+# construction of a analytic solution.
+def saturation_sym_prime(pc, index):
+    # inverse capillary pressure-saturation-relationship
+    return -1/((index+1)*(1 + pc)**((index+2)/(index+1)))
+
+
+# note that the conditional definition of S-pc in the nonsymbolic part will be
+# incorporated in the construction of the exact solution below.
+S_pc_sym = {
+    1: ft.partial(saturation_sym, index=1),
+    2: ft.partial(saturation_sym, index=2),
+    # 3: ft.partial(saturation_sym, index=2),
+    # 4: ft.partial(saturation_sym, index=1)
+}
+
+S_pc_sym_prime = {
+    1: ft.partial(saturation_sym_prime, index=1),
+    2: ft.partial(saturation_sym_prime, index=2),
+    # 3: ft.partial(saturation_sym_prime, index=2),
+    # 4: ft.partial(saturation_sym_prime, index=1)
+}
+
+sat_pressure_relationship = {
+    1: ft.partial(saturation, index=1),
+    2: ft.partial(saturation, index=2),
+    # 3: ft.partial(saturation, index=2),
+    # 4: ft.partial(saturation, index=1)
+}
+
+
+###############################################################################
+# Manufacture source expressions with sympy #
+###############################################################################
+x, y = sym.symbols('x[0], x[1]')  # needed by UFL
+t = sym.symbols('t', positive=True)
+
+# p_e_sym = {
+#     1: {'wetting': (-7.0 - (1.0 + t*t)*(1.0 + x*x + y*y))}, #*(1-x)**2*(1+x)**2*(1-y)**2},
+#     2: {'wetting': (-7.0 - (1.0 + t*t)*(1.0 + x*x)), #*(1-x)**2*(1+x)**2*(1+y)**2,
+#         'nonwetting': (-2-t*(1.1+y + x**2))*y**2}, #*(1-x)**2*(1+x)**2*(1+y)**2},
+# } #-y*y*(sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)) - t*t*x*(0.5-y)*y*(1-x)
+
+p_e_sym = {
+    1: {'wetting': (-6 - (1+t*t)*(1 + x*x + y*y)),  #*cutoff,
+        'nonwetting': (-1 -t*(1.1+ y*y))},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+    2: {'wetting': (-6.0 - (1.0 + t*t)*(1.0 + x*x)),  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2,
+        'nonwetting': (-1 -t*(1.1 + y*y) - sym.sin((x*y-0.5*t)*y**2)**2)},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
+}
+
+
+pc_e_sym = dict()
+for subdomain, isR in isRichards.items():
+    if isR:
+        pc_e_sym.update({subdomain: -p_e_sym[subdomain]['wetting'].copy()})
+    else:
+        pc_e_sym.update({subdomain: p_e_sym[subdomain]['nonwetting'].copy()
+                                        - p_e_sym[subdomain]['wetting'].copy()})
+
+
+symbols = {"x": x,
+           "y": y,
+           "t": t}
+# turn above symbolic code into exact solution for dolphin and
+# construct the rhs that matches the above exact solution.
+exact_solution_example = hlp.generate_exact_solution_expressions(
+                        symbols=symbols,
+                        isRichards=isRichards,
+                        symbolic_pressure=p_e_sym,
+                        symbolic_capillary_pressure=pc_e_sym,
+                        saturation_pressure_relationship=S_pc_sym,
+                        saturation_pressure_relationship_prime=S_pc_sym_prime,
+                        viscosity=viscosity,
+                        porosity=porosity,
+                        relative_permeability=relative_permeability,
+                        relative_permeability_prime=ka_prime,
+                        densities=densities,
+                        gravity_acceleration=gravity_acceleration,
+                        include_gravity=include_gravity,
+                        )
+source_expression = exact_solution_example['source']
+exact_solution = exact_solution_example['exact_solution']
+initial_condition = exact_solution_example['initial_condition']
+
+# BOUNDARY CONDITIONS #########################################################
+# Dictionary of dirichlet boundary conditions.
+dirichletBC = dict()
+# similarly to the outer boundary dictionary, if a patch has no outer boundary
+# None should be written instead of an expression.
+# This is a bit of a brainfuck:
+# dirichletBC[ind] gives a dictionary of the outer boundaries of subdomain ind.
+# Since a domain patch can have several disjoint outer boundary parts, the
+# expressions need to get an enumaration index which starts at 0.
+# So dirichletBC[ind][j] is the dictionary of outer dirichlet conditions of
+# subdomain ind and boundary part j.
+# Finally, dirichletBC[ind][j]['wetting'] and dirichletBC[ind][j]['nonwetting']
+# return the actual expression needed for the dirichlet condition for both
+# phases if present.
+
+# subdomain index: {outer boudary part index: {phase: expression}}
+for subdomain in isRichards.keys():
+    # subdomain can have no outer boundary
+    if outer_boundary_def_points[subdomain] is None:
+        dirichletBC.update({subdomain: None})
+    else:
+        dirichletBC.update({subdomain: dict()})
+        # set the dirichlet conditions to be the same code as exact solution on
+        # the subdomain.
+        for outer_boundary_ind in outer_boundary_def_points[subdomain].keys():
+            dirichletBC[subdomain].update(
+                {outer_boundary_ind: exact_solution[subdomain]}
+                )
+
+
+# LOG FILE OUTPUT #############################################################
+# read this file and print it to std out. This way the simulation can produce a
+# log file with ./TP-R-layered_soil.py | tee simulation.log
+f = open(thisfile, 'r')
+print(f.read())
+f.close()
+
+
+# RUN #########################################################################
+for starttime in starttimes:
+    for mesh_resolution, solver_tol in resolutions.items():
+        # initialise LDD simulation class
+        simulation = ldd.LDDsimulation(
+            tol=1E-14,
+            LDDsolver_tol=solver_tol,
+            debug=debugflag,
+            max_iter_num=max_iter_num,
+            FEM_Lagrange_degree=FEM_Lagrange_degree,
+            mesh_study=mesh_study
+            )
+
+        simulation.set_parameters(
+            use_case=use_case,
+            output_dir=output_string,
+            subdomain_def_points=subdomain_def_points,
+            isRichards=isRichards,
+            interface_def_points=interface_def_points,
+            outer_boundary_def_points=outer_boundary_def_points,
+            adjacent_subdomains=adjacent_subdomains,
+            mesh_resolution=mesh_resolution,
+            viscosity=viscosity,
+            porosity=porosity,
+            L=L,
+            lambda_param=lambda_param,
+            relative_permeability=relative_permeability,
+            saturation=sat_pressure_relationship,
+            starttime=starttime,
+            number_of_timesteps=number_of_timesteps,
+            number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+            plot_timestep_every=plot_timestep_every,
+            timestep_size=timestep_size,
+            sources=source_expression,
+            initial_conditions=initial_condition,
+            dirichletBC_expression_strings=dirichletBC,
+            exact_solution=exact_solution,
+            densities=densities,
+            include_gravity=include_gravity,
+            gravity_acceleration=gravity_acceleration,
+            write2file=write_to_file,
+            )
+
+        simulation.initialise()
+        output_dir = simulation.output_dir
+        # simulation.write_exact_solution_to_xdmf()
+        output = simulation.run(analyse_condition=analyse_condition)
+        for subdomain_index, subdomain_output in output.items():
+            mesh_h = subdomain_output['mesh_size']
+            for phase, error_dict in subdomain_output['errornorm'].items():
+                filename = output_dir \
+                    + "subdomain{}".format(subdomain_index)\
+                    + "-space-time-errornorm-{}-phase.csv".format(phase)
+                # for errortype, errornorm in error_dict.items():
+
+                # eocfile = open("eoc_filename", "a")
+                # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
+                # eocfile.close()
+                # if subdomain.isRichards:mesh_h
+                data_dict = {
+                    'mesh_parameter': mesh_resolution,
+                    'mesh_h': mesh_h,
+                }
+                for norm_type, errornorm in error_dict.items():
+                    data_dict.update(
+                        {norm_type: errornorm}
+                    )
+                errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+                # check if file exists
+                if os.path.isfile(filename) is True:
+                    with open(filename, 'a') as f:
+                        errors.to_csv(
+                            f,
+                            header=False,
+                            sep='\t',
+                            encoding='utf-8',
+                            index=False
+                            )
+                else:
+                    errors.to_csv(
+                        filename,
+                        sep='\t',
+                        encoding='utf-8',
+                        index=False
+                        )
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-test.py b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-test.py
index d892719..c084d57 100755
--- a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-test.py
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/TP-TP-2-patch-test.py
@@ -1,79 +1,112 @@
 #!/usr/bin/python3
+"""TP-TP 2 patch soil simulation.
+
+This program sets up an LDD simulation
+"""
+
 import dolfin as df
-import mshr
-import numpy as np
 import sympy as sym
-import typing as tp
-import domainPatch as dp
-import LDDsimulation as ldd
 import functools as ft
+import LDDsimulation as ldd
 import helpers as hlp
 import datetime
 import os
 import pandas as pd
 
+# init sympy session
+sym.init_printing()
+
+# PREREQUISITS  ###############################################################
+# check if output directory "./output" exists. This will be used in
+# the generation of the output string.
+if not os.path.exists('./output'):
+    os.mkdir('./output')
+    print("Directory ", './output',  " created ")
+else:
+    print("Directory ", './output',  " already exists. Will use as output \
+    directory")
+
 date = datetime.datetime.now()
 datestr = date.strftime("%Y-%m-%d")
-#import ufl as ufl
 
-# init sympy session
-sym.init_printing()
+# Name of the usecase that will be printed during simulation.
+use_case = "TP-TP-2P-realistic"
+# The name of this very file. Needed for creating log output.
+thisfile = "TP-TP-2-patch-test.py"
 
-use_case = "TP-TP-2-patch"
-# solver_tol = 5E-7
-max_iter_num = 1000
+# GENERAL SOLVER CONFIG  ######################################################
+# maximal iteration per timestep
+max_iter_num = 300
 FEM_Lagrange_degree = 1
+
+# GRID AND MESH STUDY SPECIFICATIONS  #########################################
 mesh_study = False
 resolutions = {
-                # 1: 1e-7,  # h=2
-                # 2: 2e-5,  # h=1.1180
-                # 4: 1e-6,  # h=0.5590
-                # 8: 1e-6,  # h=0.2814
-                # 16: 5e-7, # h=0.1412
-                32: 1e-6,
-                # 64: 5e-7,
-                # 128: 5e-7
+                # 1: 1e-6,
+                # 2: 1e-6,
+                # 4: 1e-6,
+                # 8: 1e-6,
+                # 16: 5e-6,
+                32: 5e-6,
+                # 64: 2e-6,
+                # 128: 1e-6,
+                # 256: 1e-6,
                 }
 
-
-############ GRID #######################
-# mesh_resolution = 20
+# starttimes gives a list of starttimes to run the simulation from.
+# The list is looped over and a simulation is run with t_0 as initial time
+#  for each element t_0 in starttimes.
+starttimes = [0.0]
 timestep_size = 0.001
-number_of_timesteps = 1500
-plot_timestep_every = 5
-# decide how many timesteps you want analysed. Analysed means, that we write out
-# subsequent errors of the L-iteration within the timestep.
-number_of_timesteps_to_analyse = 5
-starttime = 0.0
+number_of_timesteps = 10
+
+# LDD scheme parameters  ######################################################
+Lw1 = 0.25 #/timestep_size
+Lnw1= 0.25
 
-Lw = 0.05 #/timestep_size
-Lnw=Lw
+Lw2 = 0.25 #/timestep_size
+Lnw2= 0.25
 
 lambda_w = 4
 lambda_nw = 4
 
-include_gravity = True
-debugflag = False
-analyse_condition = True
-
-if mesh_study:
-    output_string = "./output/{}-{}_timesteps{}_P{}".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree)
-else:
-    for tol in resolutions.values():
-        solver_tol = tol
-    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol)
-
+include_gravity = False
+debugflag = True
+analyse_condition = False
+
+# I/O CONFIG  #################################################################
+# when number_of_timesteps is high, it might take a long time to write all
+# timesteps to disk. Therefore, you can choose to only write data of every
+# plot_timestep_every timestep to disk.
+plot_timestep_every = 4
+# Decide how many timesteps you want analysed. Analysed means, that
+# subsequent errors of the L-iteration within the timestep are written out.
+number_of_timesteps_to_analyse = 5
 
-# toggle what should be written to files
+# fine grained control over data to be written to disk in the mesh study case
+# as well as for a regular simuation for a fixed grid.
 if mesh_study:
     write_to_file = {
+        # output the relative errornorm (integration in space) w.r.t. an exact
+        # solution for each timestep into a csv file.
         'space_errornorms': True,
+        # save the mesh and marker functions to disk
         'meshes_and_markers': True,
+        # save xdmf/h5 data for each LDD iteration for timesteps determined by
+        # number_of_timesteps_to_analyse. I/O intensive!
         'L_iterations_per_timestep': False,
-        'solutions': False,
-        'absolute_differences': False,
+        # save solution to xdmf/h5.
+        'solutions': True,
+        # save absolute differences w.r.t an exact solution to xdmf/h5 file
+        # to monitor where on the domains errors happen
+        'absolute_differences': True,
+        # analyise condition numbers for timesteps determined by
+        # number_of_timesteps_to_analyse and save them over time to csv.
         'condition_numbers': analyse_condition,
-        'subsequent_errors': False
+        # output subsequent iteration errors measured in L^2  to csv for
+        # timesteps determined by number_of_timesteps_to_analyse.
+        # Usefull to monitor convergence of the acutal LDD solver.
+        'subsequent_errors': True
     }
 else:
     write_to_file = {
@@ -86,12 +119,25 @@ else:
         'subsequent_errors': True
     }
 
-##### Domain and Interface ####
+# OUTPUT FILE STRING  #########################################################
+if mesh_study:
+    output_string = "./output/{}-{}_timesteps{}_P{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree
+        )
+else:
+    for tol in resolutions.values():
+        solver_tol = tol
+    output_string = "./output/{}-{}_timesteps{}_P{}_solver_tol{}".format(
+        datestr, use_case, number_of_timesteps, FEM_Lagrange_degree, solver_tol
+        )
+
+
+# DOMAIN AND INTERFACE  #######################################################
 # global simulation domain domain
-sub_domain0_vertices = [df.Point(-1.0,-1.0), #
-                        df.Point(1.0,-1.0),#
-                        df.Point(1.0,1.0),#
-                        df.Point(-1.0,1.0)]
+sub_domain0_vertices = [df.Point(-1.0, -1.0),
+                        df.Point(1.0, -1.0),
+                        df.Point(1.0, 1.0),
+                        df.Point(-1.0, 1.0)]
 # interface between subdomain1 and subdomain2
 interface12_vertices = [df.Point(-1.0, 0.0),
                         df.Point(1.0, 0.0) ]
@@ -99,14 +145,14 @@ interface12_vertices = [df.Point(-1.0, 0.0),
 sub_domain1_vertices = [interface12_vertices[0],
                         interface12_vertices[1],
                         sub_domain0_vertices[2],
-                        sub_domain0_vertices[3] ]
+                        sub_domain0_vertices[3]]
 
 # vertex coordinates of the outer boundaries. If it can not be specified as a
 # polygon, use an entry per boundary polygon. This information is used for defining
 # the Dirichlet boundary conditions. If a domain is completely internal, the
 # dictionary entry should be 0: None
 subdomain1_outer_boundary_verts = {
-    0: [interface12_vertices[1],
+    0: [interface12_vertices[1], #
         sub_domain0_vertices[2],
         sub_domain0_vertices[3], #
         interface12_vertices[0]]
@@ -123,14 +169,6 @@ subdomain2_outer_boundary_verts = {
         sub_domain0_vertices[1],
         interface12_vertices[1]]
 }
-# subdomain2_outer_boundary_verts = {
-#     0: [interface12_vertices[0], df.Point(0.0,0.0)],#
-#     1: [df.Point(0.0,0.0), df.Point(1.0,0.0)], #
-#     2: [df.Point(1.0,0.0), interface12_vertices[1]]
-# }
-# subdomain2_outer_boundary_verts = {
-#     0: None
-# }
 
 # list of subdomains given by the boundary polygon vertices.
 # Subdomains are given as a list of dolfin points forming
@@ -156,6 +194,9 @@ outer_boundary_def_points = {
 # adjacent_subdomains[i] contains the indices of the subdomains sharing the
 # interface i (i.e. given by interface_def_points[i]).
 adjacent_subdomains = [[1,2]]
+
+
+# MODEL CONFIGURATION #########################################################
 isRichards = {
     1: False, #
     2: False
@@ -164,53 +205,57 @@ isRichards = {
 
 viscosity = {#
 # subdom_num : viscosity
-    1 : {'wetting' :1,
-         'nonwetting': 1}, #
-    2 : {'wetting' :1,
-         'nonwetting': 1}
+    1: {'wetting' :1,
+         'nonwetting': 1/50}, #
+    2: {'wetting' :1,
+         'nonwetting': 1/50}
 }
 
 porosity = {#
 # subdom_num : porosity
-    1 : 1,#
-    2 : 1
+    1: 0.22,#
+    2: 0.22
 }
 
 # Dict of the form: { subdom_num : density }
 densities = {
-    1: {'wetting': 1,  #997,
-        'nonwetting': 1}, #1225},
-    2: {'wetting': 1,  #997,
-        'nonwetting': 1}, #1225},
+    1: {'wetting': 997,
+        'nonwetting': 1.225},
+    2: {'wetting': 997,
+        'nonwetting': 1.225}
 }
 
-gravity_acceleration = 1#9.81
+gravity_acceleration = 9.81
 
 L = {#
 # subdom_num : subdomain L for L-scheme
-    1 : {'wetting' :Lw,
-         'nonwetting': Lnw},#
-    2 : {'wetting' :Lw,
-         'nonwetting': Lnw}
+    1 : {'wetting' :Lw1,
+         'nonwetting': Lnw1},#
+    2 : {'wetting' :Lw2,
+         'nonwetting': Lnw2}
 }
 
 
 lambda_param = {#
 # subdom_num : lambda parameter for the L-scheme
-    1 : {'wetting' :lambda_w,
+    0 : {'wetting' :lambda_w,
          'nonwetting': lambda_nw},#
-    2 : {'wetting' :lambda_w,
-         'nonwetting': lambda_nw}
 }
 
+intrinsic_permeability = {
+    1: 0.1,
+    2: 0.1,
+}
+
+
 ## relative permeabilty functions on subdomain 1
 def rel_perm1w(s):
     # relative permeabilty wetting on subdomain1
-    return s**2
+    return intrinsic_permeability[1]*s**2
 
 def rel_perm1nw(s):
     # relative permeabilty nonwetting on subdomain1
-    return (1-s)**2
+    return intrinsic_permeability[1]*(1-s)**2
 
 _rel_perm1w = ft.partial(rel_perm1w)
 _rel_perm1nw = ft.partial(rel_perm1nw)
@@ -222,10 +267,10 @@ subdomain1_rel_perm = {
 ## relative permeabilty functions on subdomain 2
 def rel_perm2w(s):
     # relative permeabilty wetting on subdomain2
-    return s**3
+    return intrinsic_permeability[2]*s**3
 def rel_perm2nw(s):
-    # relative permeabilty nonwetting on subdosym.cos(0.8*t - (0.8*x + 1/7*y))main2
-    return (1-s)**3
+    # relative permeabilty nonwetting on subdomain2
+    return intrinsic_permeability[2]*(1-s)**3
 
 _rel_perm2w = ft.partial(rel_perm2w)
 _rel_perm2nw = ft.partial(rel_perm2nw)
@@ -246,21 +291,21 @@ relative_permeability = {#
 # relative permeabilty functions on subdomain 1
 def rel_perm1w_prime(s):
     # relative permeabilty on subdomain1
-    return 2*s
+    return intrinsic_permeability[1]*2*s
 
 def rel_perm1nw_prime(s):
     # relative permeabilty on subdomain1
-    return -2*(1-s)
+    return -1*intrinsic_permeability[1]*2*(1-s)
 
-# # definition of the derivatives of the relative permeabilities
-# # relative permeabilty functions on subdomain 1
+# definition of the derivatives of the relative permeabilities
+# relative permeabilty functions on subdomain 1
 def rel_perm2w_prime(s):
-    # relative permeabilty on subdomain1
-    return 3*s**2
+    # relative permeabilty on subdomain2
+    return intrinsic_permeability[2]*3*s**2
 
 def rel_perm2nw_prime(s):
-    # relative permeabilty on subdomain1
-    return -3*(1-s)**2
+    # relative permeabilty on subdomain2
+    return -3*intrinsic_permeability[2]*(1-s)**2
 
 _rel_perm1w_prime = ft.partial(rel_perm1w_prime)
 _rel_perm1nw_prime = ft.partial(rel_perm1nw_prime)
@@ -285,6 +330,54 @@ ka_prime = {
 }
 
 
+# def saturation1(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + pc)**(1/(subdomain_index + 1))), 1)
+#
+# def saturation2(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
+#
+# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
+# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
+# def saturation1_sym(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return 1/((1 + pc)**(1/(subdomain_index + 1)))
+#
+#
+# def saturation2_sym(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     #df.conditional(pc > 0,
+#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
+#
+#
+# # derivative of S-pc relationship with respect to pc. This is needed for the
+# # construction of a analytic solution.
+# def saturation1_sym_prime(pc, subdomain_index):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(1/(subdomain_index + 1))*(1 + pc)**((-subdomain_index - 2)/(subdomain_index + 1))
+#
+#
+# def saturation2_sym_prime(pc, n_index, alpha):
+#     # inverse capillary pressure-saturation-relationship
+#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
+#
+# # note that the conditional definition of S-pc in the nonsymbolic part will be
+# # incorporated in the construction of the exact solution below.
+# S_pc_sym = {
+#     1: ft.partial(saturation1_sym, subdomain_index = 1),
+#     2: ft.partial(saturation2_sym, n_index=3, alpha=0.001),
+# }
+#
+# S_pc_sym_prime = {
+#     1: ft.partial(saturation1_sym_prime, subdomain_index = 1),
+#     2: ft.partial(saturation2_sym_prime, n_index=3, alpha=0.001),
+# }
+#
+# sat_pressure_relationship = {
+#     1: ft.partial(saturation1, subdomain_index = 1),#,
+#     2: ft.partial(saturation2, n_index=3, alpha=0.001),
+# }
 
 def saturation(pc, index):
     # inverse capillary pressure-saturation-relationship
@@ -326,62 +419,19 @@ sat_pressure_relationship = {
     # 4: ft.partial(saturation, index=1)
 }
 
-#
-# def saturation(pc, n_index, alpha):
-#     # inverse capillary pressure-saturation-relationship
-#     return df.conditional(pc > 0, 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index)), 1)
-#
-# # S-pc-relation ship. We use the van Genuchten approach, i.e. pc = 1/alpha*(S^{-1/m} -1)^1/n, where
-# # we set alpha = 0, assume m = 1-1/n (see Helmig) and assume that residual saturation is Sw
-# def saturation_sym(pc, n_index, alpha):
-#     # inverse capillary pressure-saturation-relationship
-#     #df.conditional(pc > 0,
-#     return 1/((1 + (alpha*pc)**n_index)**((n_index - 1)/n_index))
-#
-#
-# # derivative of S-pc relationship with respect to pc. This is needed for the
-# # construction of a analytic solution.
-# def saturation_sym_prime(pc, n_index, alpha):
-#     # inverse capillary pressure-saturation-relationship
-#     return -(alpha*(n_index - 1)*(alpha*pc)**(n_index - 1)) / ( (1 + (alpha*pc)**n_index)**((2*n_index - 1)/n_index) )
-#
-# # note that the conditional definition of S-pc in the nonsymbolic part will be
-# # incorporated in the construction of the exact solution below.
-# S_pc_sym = {
-#     1: ft.partial(saturation_sym, n_index=3, alpha=0.001),
-#     2: ft.partial(saturation_sym, n_index=6, alpha=0.001),
-#     # 3: ft.partial(saturation_sym, n_index=3, alpha=0.001),
-#     # 4: ft.partial(saturation_sym, n_index=3, alpha=0.001),
-#     # 5: ft.partial(saturation_sym, n_index=3, alpha=0.001),
-#     # 6: ft.partial(saturation_sym, n_index=3, alpha=0.001)
-# }
-#
-# S_pc_sym_prime = {
-#     1: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
-#     2: ft.partial(saturation_sym_prime, n_index=6, alpha=0.001),
-#     # 3: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
-#     # 4: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
-#     # 5: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001),
-#     # 6: ft.partial(saturation_sym_prime, n_index=3, alpha=0.001)
-# }
-#
-# sat_pressure_relationship = {
-#     1: ft.partial(saturation, n_index=3, alpha=0.001),
-#     2: ft.partial(saturation, n_index=6, alpha=0.001),
-#     # 3: ft.partial(saturation, n_index=3, alpha=0.001),
-#     # 4: ft.partial(saturation, n_index=3, alpha=0.001),
-#     # 5: ft.partial(saturation, n_index=3, alpha=0.001),
-#     # 6: ft.partial(saturation, n_index=3, alpha=0.001)
-# }
-#
-
 
-#############################################
+###############################################################################
 # Manufacture source expressions with sympy #
-#############################################
+###############################################################################
 x, y = sym.symbols('x[0], x[1]')  # needed by UFL
 t = sym.symbols('t', positive=True)
 
+# p_e_sym = {
+#     1: {'wetting': (-7.0 - (1.0 + t*t)*(1.0 + x*x + y*y))}, #*(1-x)**2*(1+x)**2*(1-y)**2},
+#     2: {'wetting': (-7.0 - (1.0 + t*t)*(1.0 + x*x)), #*(1-x)**2*(1+x)**2*(1+y)**2,
+#         'nonwetting': (-2-t*(1.1+y + x**2))*y**2}, #*(1-x)**2*(1+x)**2*(1+y)**2},
+# } #-y*y*(sym.sin(-2*t+2*x)*sym.sin(1/2*y-1.2*t)) - t*t*x*(0.5-y)*y*(1-x)
+
 p_e_sym = {
     1: {'wetting': (-6 - (1+t*t)*(1 + x*x + y*y)),  #*cutoff,
         'nonwetting': (-1 -t*(1.1+ y*y))},  #*(sym.sin((1+y)/2*sym.pi)*sym.sin((1+x)/2*sym.pi))**2},
@@ -423,6 +473,7 @@ source_expression = exact_solution_example['source']
 exact_solution = exact_solution_example['exact_solution']
 initial_condition = exact_solution_example['initial_condition']
 
+# BOUNDARY CONDITIONS #########################################################
 # Dictionary of dirichlet boundary conditions.
 dirichletBC = dict()
 # similarly to the outer boundary dictionary, if a patch has no outer boundary
@@ -439,7 +490,7 @@ dirichletBC = dict()
 
 # subdomain index: {outer boudary part index: {phase: expression}}
 for subdomain in isRichards.keys():
-    # if subdomain has no outer boundary, outer_boundary_def_points[subdomain] is None
+    # subdomain can have no outer boundary
     if outer_boundary_def_points[subdomain] is None:
         dirichletBC.update({subdomain: None})
     else:
@@ -452,77 +503,96 @@ for subdomain in isRichards.keys():
                 )
 
 
-# def saturation(pressure, subdomain_index):
-#     # inverse capillary pressure-saturation-relationship
-#     return df.conditional(pressure < 0, 1/((1 - pressure)**(1/(subdomain_index + 1))), 1)
-#
-# sa
-
-for mesh_resolution, solver_tol in resolutions.items():
-    # initialise LDD simulation class
-    simulation = ldd.LDDsimulation(
-        tol=1E-14,
-        LDDsolver_tol=solver_tol,
-        debug=debugflag,
-        max_iter_num=max_iter_num,
-        FEM_Lagrange_degree=FEM_Lagrange_degree,
-        mesh_study=mesh_study
-        )
-
-    simulation.set_parameters(use_case=use_case,
-                              output_dir=output_string,
-                              subdomain_def_points=subdomain_def_points,
-                              isRichards=isRichards,
-                              interface_def_points=interface_def_points,
-                              outer_boundary_def_points=outer_boundary_def_points,
-                              adjacent_subdomains=adjacent_subdomains,
-                              mesh_resolution=mesh_resolution,
-                              viscosity=viscosity,
-                              porosity=porosity,
-                              L=L,
-                              lambda_param=lambda_param,
-                              relative_permeability=relative_permeability,
-                              saturation=sat_pressure_relationship,
-                              starttime=starttime,
-                              number_of_timesteps=number_of_timesteps,
-                              number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
-                              plot_timestep_every=plot_timestep_every,
-                              timestep_size=timestep_size,
-                              sources=source_expression,
-                              initial_conditions=initial_condition,
-                              dirichletBC_expression_strings=dirichletBC,
-                              exact_solution=exact_solution,
-                              densities=densities,
-                              include_gravity=include_gravity,
-                              write2file=write_to_file,
-                              )
-
-    simulation.initialise()
-    output_dir = simulation.output_dir
-    # simulation.write_exact_solution_to_xdmf()
-    output = simulation.run(analyse_condition=analyse_condition)
-    for subdomain_index, subdomain_output in output.items():
-        mesh_h = subdomain_output['mesh_size']
-        for phase, different_errornorms in subdomain_output['errornorm'].items():
-            filename = output_dir + "subdomain{}-space-time-errornorm-{}-phase.csv".format(subdomain_index, phase)
-            # for errortype, errornorm in different_errornorms.items():
+# LOG FILE OUTPUT #############################################################
+# read this file and print it to std out. This way the simulation can produce a
+# log file with ./TP-R-layered_soil.py | tee simulation.log
+f = open(thisfile, 'r')
+print(f.read())
+f.close()
+
+
+# RUN #########################################################################
+for starttime in starttimes:
+    for mesh_resolution, solver_tol in resolutions.items():
+        # initialise LDD simulation class
+        simulation = ldd.LDDsimulation(
+            tol=1E-14,
+            LDDsolver_tol=solver_tol,
+            debug=debugflag,
+            max_iter_num=max_iter_num,
+            FEM_Lagrange_degree=FEM_Lagrange_degree,
+            mesh_study=mesh_study
+            )
+
+        simulation.set_parameters(
+            use_case=use_case,
+            output_dir=output_string,
+            subdomain_def_points=subdomain_def_points,
+            isRichards=isRichards,
+            interface_def_points=interface_def_points,
+            outer_boundary_def_points=outer_boundary_def_points,
+            adjacent_subdomains=adjacent_subdomains,
+            mesh_resolution=mesh_resolution,
+            viscosity=viscosity,
+            porosity=porosity,
+            L=L,
+            lambda_param=lambda_param,
+            relative_permeability=relative_permeability,
+            saturation=sat_pressure_relationship,
+            starttime=starttime,
+            number_of_timesteps=number_of_timesteps,
+            number_of_timesteps_to_analyse=number_of_timesteps_to_analyse,
+            plot_timestep_every=plot_timestep_every,
+            timestep_size=timestep_size,
+            sources=source_expression,
+            initial_conditions=initial_condition,
+            dirichletBC_expression_strings=dirichletBC,
+            exact_solution=exact_solution,
+            densities=densities,
+            include_gravity=include_gravity,
+            gravity_acceleration=gravity_acceleration,
+            write2file=write_to_file,
+            )
+
+        simulation.initialise()
+        output_dir = simulation.output_dir
+        # simulation.write_exact_solution_to_xdmf()
+        output = simulation.run(analyse_condition=analyse_condition)
+        for subdomain_index, subdomain_output in output.items():
+            mesh_h = subdomain_output['mesh_size']
+            for phase, error_dict in subdomain_output['errornorm'].items():
+                filename = output_dir \
+                    + "subdomain{}".format(subdomain_index)\
+                    + "-space-time-errornorm-{}-phase.csv".format(phase)
+                # for errortype, errornorm in error_dict.items():
 
                 # eocfile = open("eoc_filename", "a")
                 # eocfile.write( str(mesh_h) + " " + str(errornorm) + "\n" )
                 # eocfile.close()
                 # if subdomain.isRichards:mesh_h
-            data_dict = {
-                'mesh_parameter': mesh_resolution,
-                'mesh_h': mesh_h,
-            }
-            for error_type, errornorms in different_errornorms.items():
-                data_dict.update(
-                    {error_type: errornorms}
-                )
-            errors = pd.DataFrame(data_dict, index=[mesh_resolution])
-            # check if file exists
-            if os.path.isfile(filename) == True:
-                with open(filename, 'a') as f:
-                    errors.to_csv(f, header=False, sep='\t', encoding='utf-8', index=False)
-            else:
-                errors.to_csv(filename, sep='\t', encoding='utf-8', index=False)
+                data_dict = {
+                    'mesh_parameter': mesh_resolution,
+                    'mesh_h': mesh_h,
+                }
+                for norm_type, errornorm in error_dict.items():
+                    data_dict.update(
+                        {norm_type: errornorm}
+                    )
+                errors = pd.DataFrame(data_dict, index=[mesh_resolution])
+                # check if file exists
+                if os.path.isfile(filename) is True:
+                    with open(filename, 'a') as f:
+                        errors.to_csv(
+                            f,
+                            header=False,
+                            sep='\t',
+                            encoding='utf-8',
+                            index=False
+                            )
+                else:
+                    errors.to_csv(
+                        filename,
+                        sep='\t',
+                        encoding='utf-8',
+                        index=False
+                        )
diff --git a/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/run-simulation b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/run-simulation
new file mode 100755
index 0000000..0eb4975
--- /dev/null
+++ b/Two-phase-Two-phase/two-patch/TP-TP-2-patch-test-case/run-simulation
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+[ $# -eq 0 ] && { echo "Usage: $0 simulation_file [logfile_name]"; exit 1; }
+
+SIMULATION_FILE=$1
+SIMULATION=${SIMULATION_FILE%.py}
+LOGFILE_DEFAULT="$SIMULATION.log"
+
+DATE=$(date -I)
+LOGFILE=${2:-$DATE-$LOGFILE_DEFAULT}
+
+GREETING="Simulation $SIMULATION is run on $DATE by $USER"
+
+echo $GREETING
+echo "running $SIMULATION_FILE | tee $LOGFILE"
+./$SIMULATION_FILE | tee $LOGFILE
-- 
GitLab