gel.scripts.forward

The forward model.

For all arguments, run forward --help

Will interact with local file system when run as a command. This includes:

  • Logs what it is doing in file specified by name LOG_FILE
  • Uses a directory results_dir as a super-directory for all forward model results. This directory should be clear of subdirectories except for those created by specifically this program.
  • Creates a .csv file table.csv under results_dir to store a chart of all options used and some result info like runtime.
  • Creates a subdirectory under results_dir according to the options provided.
  • In that subdirectory, stores many .xdmf files.
  • If a subdirectory for a collection of settings already exists, will not proceed forward and quietly skip.
  1"""The forward model.
  2
  3For all arguments, run `forward --help`
  4
  5Will interact with local file system when run as a command. This
  6includes:
  7* Logs what it is doing in file specified by name `LOG_FILE`
  8* Uses a directory `results_dir` as a super-directory for all forward
  9model results. This directory should be clear of subdirectories except
 10for those created by **specifically this program**.
 11* Creates a .csv file `table.csv` under `results_dir` to store a chart
 12of all options used and some result info like runtime.
 13* Creates a subdirectory under `results_dir` according to the options
 14provided.
 15* In that subdirectory, stores many .xdmf files.
 16* If a subdirectory for a collection of settings already exists, will
 17not proceed forward and quietly skip.
 18"""
 19from gel import *
 20import os
 21from sanity_utils import *
 22
 23
 24LOG_FILE = "log.txt"
 25
 26
 27FORWARD_EXP_COLS = [
 28    "Results Dir",
 29    "Cell Name",
 30    "Formulation",
 31    "Modulus Repr",
 32    "Modulus Ratio",
 33    "pc",
 34    "Load Steps",
 35    "Absolute Tolerance",
 36    "Relative Tolerance",
 37    "Traction",
 38    "lower_bound",
 39    "upper_bound",
 40    "Inner Mesh",
 41    "Outer Mesh",
 42    "u_init",
 43    "time"
 44]
 45"""Names of columns in `table.csv`"""
 46
 47
 48def run_experiments(args):
 49    """Sets up logging to relevant files and starts the forward model.
 50
 51    * `args`: `argparse.Namespace` with parsed command arguments
 52
 53    Side-effects: see intro to `gel.scripts.forward`; does all the file
 54    handling except the experiment's subdirectory
 55
 56    Computation: calls `output_single_forward_result`, which handles
 57    the experiment's subdirectory.
 58    """
 59    logger = get_global_logger(LOG_FILE)
 60
 61    # Results
 62    result_csv_path = os.path.join(args.r, "table.csv")
 63    csv = ResultsCSV(result_csv_path, FORWARD_EXP_COLS)
 64
 65    logger.info(f"Detected number of processes: {MPI.comm_world.Get_size()}")
 66
 67    exp_info = (
 68        args.r,
 69        args.c,
 70        args.f,
 71        args.a,
 72        args.k,
 73        args.p,
 74        args.l,
 75        args.tola,
 76        args.tolr,
 77        args.t,
 78        args.b[0],
 79        args.b[1],
 80        args.bci,
 81        args.bco,
 82        args.u_init
 83    )
 84
 85    logger.info(f"Beginning experiment with arguments {exp_info}.")
 86
 87    # Be careful of it already existing
 88    try:
 89        total_time = output_single_forward_result(*exp_info)
 90
 91        # Update DataFrame
 92        csv.add_row(list(exp_info)+[float(total_time)])
 93
 94        # Save into file
 95        csv.save()
 96    except FileExistsError:
 97        logger.info("Found that directory already exists. Skipping...")
 98
 99
100def output_single_forward_result(
101        results_dir,
102        cell_data_dir,
103        formulation,
104        mod_repr,
105        k,
106        pc,
107        load_steps,
108        tola,
109        tolr,
110        traction,
111        lower_bound,
112        upper_bound,
113        bci,
114        bco,
115        u_init
116    ):
117    r"""Runs a single forward model experiment, writes subdirectory and
118    logs progress.
119
120    * `results_dir`: str path to directory to put all results
121    * `cell_data_dir`: str path to directory with geometry information
122    to use, see the constructor to `gel.geometry.Geometry` for required
123    files
124    * `formulation`: str a valid material model formulation, see
125    `gel.mechanics` for options
126    * `mod_repr`: str a valid modulus representation, see
127    `gel.mechanics` for options
128    * `k`: float $\frac{D_1}{c_1}$ ratio
129    * `pc`: str preconditioner to use, see `gel.gel.ForwardSimulation`
130    for more details
131    * `tola`: float the absolute tolerance for Newton-Raphson
132    * `tolr`: float the relative tolerance for Newton-Raphson
133    * `traction`: str filename to traction if using, see
134    `gel.gel.ForwardSimulation` for details
135    * `lower_bound`: float the lower bound for the "beta_tilde"
136    formulation described in `gel.mechanics`
137    * `upper_bound`: float the upper bound for the "beta_tilde"
138    formulation described in `gel.mechanics`
139    * `bci`: str path to .vtk file with inner BC info, see
140    `gel.geometry.Geometry` for details
141    * `bco`: str path to .vtk file with outer BC info, see
142    `gel.geometry.Geometry` for details
143    * `u_init`: str path to full-shape .xdmf file with initial
144    displacements
145
146    Side-effects: writes many files in new subdirectory to
147    `results_dir`, see intro to `gel.scripts.forward`
148
149    Returns: float time it took to run
150    """
151    # Input validation
152    validate_formulation(formulation)
153    validate_mod_repr_field(mod_repr)
154
155    # Get cell name
156    cell_name = read_cell_name(cell_data_dir)
157
158    # Output directory handling
159    output_dir = prepare_experiment_dir(
160        results_dir,
161        cell_name,
162        formulation,
163        mod_repr,
164        k,
165        pc,
166        load_steps,
167        traction,
168        lower_bound,
169        upper_bound,
170        bci,
171        bco,
172        u_init
173    )
174
175    # Setup logging
176    logger, logger_destructor = create_experiment_logger(output_dir)
177
178    #
179    # Experiment
180    #
181    logger.info(f"Beginning experiment in {formulation} formulation.")
182    logger.info(f"Using cell data from {cell_data_dir}, '{cell_name}'")
183    logger.info(f"Using mod_repr field: {mod_repr}")
184    logger.info(f"Using D1/C1: {k}")
185    logger.info(f"Using preconditioner: {pc}")
186    logger.info(f"Abs tolerance: {tola}")
187    logger.info(f"Rel tolerance: {tolr}")
188    logger.info(f"Traction filename: {traction}")
189    logger.info(f"Using load steps: {load_steps}")
190    logger.info(f"Override inner BC: {bci}")
191    logger.info(f"Override outer BC: {bco}")
192    logger.info(f"Initial displacements: {u_init}")
193
194    # Timer start
195    timer = ExperimentTimer()
196    timer.start()
197
198    # run
199    addn_args = {"bci_data" : bci, "bco_data" : bco}
200    formulation_kwargs = dict()
201    if formulation == "beta_tilde":
202        formulation_kwargs["beta_min"] = lower_bound
203        formulation_kwargs["beta_max"] = upper_bound
204
205    sim = ForwardSimulation(
206        "real_cell_gel",
207        k,
208        formulation=formulation,
209        mod_repr_init=mod_repr,
210        vprint=logger.info,
211        data_directory=cell_data_dir,
212        restrict_ctl_dofs_to_veh=False,
213        pc=pc,
214        load_steps=load_steps,
215        tola=tola,
216        tolr=tolr,
217        traction=traction,
218        u_init=u_init,
219        formulation_kwargs=formulation_kwargs,
220        **addn_args
221    )
222    sim.run_forward()
223    kinematics, mod_repr = sim.kinematics, sim.mod_repr
224
225    # Timer end
226    total_time = timer.end()
227    logger.info(f"Took {total_time} seconds to complete")
228
229    # Save
230    geo = kinematics.geo
231    logger.info(f"Saving results to {output_dir}")
232    kinematics_sim = Kinematics(geo, kinematics.u)
233    output_results_paraview(output_dir, kinematics_sim, mod_repr)
234
235    # Tear down logging
236    logger_destructor()
237
238    return total_time
239
240
241def forward():
242    """The function invoked by the command. Parses arguments and passes
243    to `run_experiments`.
244    """
245    parser = get_common_parser(
246        description="Run the forward model for ground-truth"
247        " simulations of test problems"
248    )
249
250    parser.add_argument(
251        "-r",
252        metavar="RESULTS_DIR",
253        default="forward",
254        help="superdirectory in which all solutions are saved"
255    )
256    parser.add_argument(
257        "--tola",
258        type=float,
259        metavar="ABS_TOL",
260        default=1e-10,
261        help="Newton-Rasphon absolute residual tolerance"
262    )
263    parser.add_argument(
264        "--tolr",
265        type=float,
266        metavar="REL_TOL",
267        default=1e-9,
268        help="Newton-Rasphon relative residual tolerance"
269    )
270    parser.add_argument(
271        "-a",
272        metavar="MOD_REPR",
273        default="zero",
274        help="the modulus field to use"
275    )
276    parser.add_argument(
277        "-t",
278        type=str,
279        metavar="TRACTION",
280        default=None,
281        help="full-shape .xdmf file with 1st order Lagrange reference tractions"
282        " 'T' over the whole gel domain, note that values outside cell surface "
283        "are ignored. 'zero' for automatic 0 traction, but suppress cell BC"
284    )
285    args = parser.parse_args()
286
287    run_experiments(args)
288
289
290if __name__ == "__main__":
291    forward()
LOG_FILE = 'log.txt'
FORWARD_EXP_COLS = ['Results Dir', 'Cell Name', 'Formulation', 'Modulus Repr', 'Modulus Ratio', 'pc', 'Load Steps', 'Absolute Tolerance', 'Relative Tolerance', 'Traction', 'lower_bound', 'upper_bound', 'Inner Mesh', 'Outer Mesh', 'u_init', 'time']

Names of columns in table.csv

def run_experiments(args):
49def run_experiments(args):
50    """Sets up logging to relevant files and starts the forward model.
51
52    * `args`: `argparse.Namespace` with parsed command arguments
53
54    Side-effects: see intro to `gel.scripts.forward`; does all the file
55    handling except the experiment's subdirectory
56
57    Computation: calls `output_single_forward_result`, which handles
58    the experiment's subdirectory.
59    """
60    logger = get_global_logger(LOG_FILE)
61
62    # Results
63    result_csv_path = os.path.join(args.r, "table.csv")
64    csv = ResultsCSV(result_csv_path, FORWARD_EXP_COLS)
65
66    logger.info(f"Detected number of processes: {MPI.comm_world.Get_size()}")
67
68    exp_info = (
69        args.r,
70        args.c,
71        args.f,
72        args.a,
73        args.k,
74        args.p,
75        args.l,
76        args.tola,
77        args.tolr,
78        args.t,
79        args.b[0],
80        args.b[1],
81        args.bci,
82        args.bco,
83        args.u_init
84    )
85
86    logger.info(f"Beginning experiment with arguments {exp_info}.")
87
88    # Be careful of it already existing
89    try:
90        total_time = output_single_forward_result(*exp_info)
91
92        # Update DataFrame
93        csv.add_row(list(exp_info)+[float(total_time)])
94
95        # Save into file
96        csv.save()
97    except FileExistsError:
98        logger.info("Found that directory already exists. Skipping...")

Sets up logging to relevant files and starts the forward model.

  • args: argparse.Namespace with parsed command arguments

Side-effects: see intro to gel.scripts.forward; does all the file handling except the experiment's subdirectory

Computation: calls output_single_forward_result, which handles the experiment's subdirectory.

def output_single_forward_result( results_dir, cell_data_dir, formulation, mod_repr, k, pc, load_steps, tola, tolr, traction, lower_bound, upper_bound, bci, bco, u_init):
101def output_single_forward_result(
102        results_dir,
103        cell_data_dir,
104        formulation,
105        mod_repr,
106        k,
107        pc,
108        load_steps,
109        tola,
110        tolr,
111        traction,
112        lower_bound,
113        upper_bound,
114        bci,
115        bco,
116        u_init
117    ):
118    r"""Runs a single forward model experiment, writes subdirectory and
119    logs progress.
120
121    * `results_dir`: str path to directory to put all results
122    * `cell_data_dir`: str path to directory with geometry information
123    to use, see the constructor to `gel.geometry.Geometry` for required
124    files
125    * `formulation`: str a valid material model formulation, see
126    `gel.mechanics` for options
127    * `mod_repr`: str a valid modulus representation, see
128    `gel.mechanics` for options
129    * `k`: float $\frac{D_1}{c_1}$ ratio
130    * `pc`: str preconditioner to use, see `gel.gel.ForwardSimulation`
131    for more details
132    * `tola`: float the absolute tolerance for Newton-Raphson
133    * `tolr`: float the relative tolerance for Newton-Raphson
134    * `traction`: str filename to traction if using, see
135    `gel.gel.ForwardSimulation` for details
136    * `lower_bound`: float the lower bound for the "beta_tilde"
137    formulation described in `gel.mechanics`
138    * `upper_bound`: float the upper bound for the "beta_tilde"
139    formulation described in `gel.mechanics`
140    * `bci`: str path to .vtk file with inner BC info, see
141    `gel.geometry.Geometry` for details
142    * `bco`: str path to .vtk file with outer BC info, see
143    `gel.geometry.Geometry` for details
144    * `u_init`: str path to full-shape .xdmf file with initial
145    displacements
146
147    Side-effects: writes many files in new subdirectory to
148    `results_dir`, see intro to `gel.scripts.forward`
149
150    Returns: float time it took to run
151    """
152    # Input validation
153    validate_formulation(formulation)
154    validate_mod_repr_field(mod_repr)
155
156    # Get cell name
157    cell_name = read_cell_name(cell_data_dir)
158
159    # Output directory handling
160    output_dir = prepare_experiment_dir(
161        results_dir,
162        cell_name,
163        formulation,
164        mod_repr,
165        k,
166        pc,
167        load_steps,
168        traction,
169        lower_bound,
170        upper_bound,
171        bci,
172        bco,
173        u_init
174    )
175
176    # Setup logging
177    logger, logger_destructor = create_experiment_logger(output_dir)
178
179    #
180    # Experiment
181    #
182    logger.info(f"Beginning experiment in {formulation} formulation.")
183    logger.info(f"Using cell data from {cell_data_dir}, '{cell_name}'")
184    logger.info(f"Using mod_repr field: {mod_repr}")
185    logger.info(f"Using D1/C1: {k}")
186    logger.info(f"Using preconditioner: {pc}")
187    logger.info(f"Abs tolerance: {tola}")
188    logger.info(f"Rel tolerance: {tolr}")
189    logger.info(f"Traction filename: {traction}")
190    logger.info(f"Using load steps: {load_steps}")
191    logger.info(f"Override inner BC: {bci}")
192    logger.info(f"Override outer BC: {bco}")
193    logger.info(f"Initial displacements: {u_init}")
194
195    # Timer start
196    timer = ExperimentTimer()
197    timer.start()
198
199    # run
200    addn_args = {"bci_data" : bci, "bco_data" : bco}
201    formulation_kwargs = dict()
202    if formulation == "beta_tilde":
203        formulation_kwargs["beta_min"] = lower_bound
204        formulation_kwargs["beta_max"] = upper_bound
205
206    sim = ForwardSimulation(
207        "real_cell_gel",
208        k,
209        formulation=formulation,
210        mod_repr_init=mod_repr,
211        vprint=logger.info,
212        data_directory=cell_data_dir,
213        restrict_ctl_dofs_to_veh=False,
214        pc=pc,
215        load_steps=load_steps,
216        tola=tola,
217        tolr=tolr,
218        traction=traction,
219        u_init=u_init,
220        formulation_kwargs=formulation_kwargs,
221        **addn_args
222    )
223    sim.run_forward()
224    kinematics, mod_repr = sim.kinematics, sim.mod_repr
225
226    # Timer end
227    total_time = timer.end()
228    logger.info(f"Took {total_time} seconds to complete")
229
230    # Save
231    geo = kinematics.geo
232    logger.info(f"Saving results to {output_dir}")
233    kinematics_sim = Kinematics(geo, kinematics.u)
234    output_results_paraview(output_dir, kinematics_sim, mod_repr)
235
236    # Tear down logging
237    logger_destructor()
238
239    return total_time

Runs a single forward model experiment, writes subdirectory and logs progress.

  • results_dir: str path to directory to put all results
  • cell_data_dir: str path to directory with geometry information to use, see the constructor to gel.geometry.Geometry for required files
  • formulation: str a valid material model formulation, see gel.mechanics for options
  • mod_repr: str a valid modulus representation, see gel.mechanics for options
  • k: float $\frac{D_1}{c_1}$ ratio
  • pc: str preconditioner to use, see gel.gel.ForwardSimulation for more details
  • tola: float the absolute tolerance for Newton-Raphson
  • tolr: float the relative tolerance for Newton-Raphson
  • traction: str filename to traction if using, see gel.gel.ForwardSimulation for details
  • lower_bound: float the lower bound for the "beta_tilde" formulation described in gel.mechanics
  • upper_bound: float the upper bound for the "beta_tilde" formulation described in gel.mechanics
  • bci: str path to .vtk file with inner BC info, see gel.geometry.Geometry for details
  • bco: str path to .vtk file with outer BC info, see gel.geometry.Geometry for details
  • u_init: str path to full-shape .xdmf file with initial displacements

Side-effects: writes many files in new subdirectory to results_dir, see intro to gel.scripts.forward

Returns: float time it took to run

def forward():
242def forward():
243    """The function invoked by the command. Parses arguments and passes
244    to `run_experiments`.
245    """
246    parser = get_common_parser(
247        description="Run the forward model for ground-truth"
248        " simulations of test problems"
249    )
250
251    parser.add_argument(
252        "-r",
253        metavar="RESULTS_DIR",
254        default="forward",
255        help="superdirectory in which all solutions are saved"
256    )
257    parser.add_argument(
258        "--tola",
259        type=float,
260        metavar="ABS_TOL",
261        default=1e-10,
262        help="Newton-Rasphon absolute residual tolerance"
263    )
264    parser.add_argument(
265        "--tolr",
266        type=float,
267        metavar="REL_TOL",
268        default=1e-9,
269        help="Newton-Rasphon relative residual tolerance"
270    )
271    parser.add_argument(
272        "-a",
273        metavar="MOD_REPR",
274        default="zero",
275        help="the modulus field to use"
276    )
277    parser.add_argument(
278        "-t",
279        type=str,
280        metavar="TRACTION",
281        default=None,
282        help="full-shape .xdmf file with 1st order Lagrange reference tractions"
283        " 'T' over the whole gel domain, note that values outside cell surface "
284        "are ignored. 'zero' for automatic 0 traction, but suppress cell BC"
285    )
286    args = parser.parse_args()
287
288    run_experiments(args)

The function invoked by the command. Parses arguments and passes to run_experiments.