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

Names of columns in table.csv

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

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

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