def test_str_rendering(): pdid = ParamDict(a=1, b=2) pdin = ParamDict(a=1, b=3) pdout = ParamDict(a=1, b=4) record = ParamDict(identity=pdid, input=pdin, output=pdout) s = str(record) assert record["identity"] == pdid
def create_default_problem_factories(): problem_factories = [ #lambda refinement_level,dt: LidDrivenCavity(ParamDict(refinement_level=refinement_level, dt=dt, T=2.5, mu=1./1000., rho=1.0)), lambda refinement_level, dt: Poiseuille2D( ParamDict(refinement_level=refinement_level, dt=dt, T=None, num_periods=0.2)), lambda refinement_level, dt: Poiseuille3D( ParamDict(refinement_level=refinement_level, dt=dt, T=None, num_periods=0.2)), lambda refinement_level, dt: Womersley2D( ParamDict(refinement_level=refinement_level, dt=dt, T=None, num_periods=1.0)), lambda refinement_level, dt: Womersley3D( ParamDict(refinement_level=refinement_level, dt=dt, T=None, num_periods=1.0)), lambda refinement_level, dt: Beltrami( ParamDict(refinement_level=refinement_level, dt=dt, T=1.0)), ] return problem_factories
def create_default_scheme_factories(): scheme_factories = [ lambda: IPCS_Naive(), #lambda: Yosida(), lambda: IPCS(ParamDict(theta=1.0)), lambda: IPCS(ParamDict(theta=0.5)), ] return scheme_factories
def test_shallow_copy(): pd1 = ParamDict(a=3, b=4) pd2 = pd1.copy_recursive() pd1.a = 1 pd2.a = 2 pd2.b = 2 pd1.b = 1 assert pd1.a == 1 assert pd1.b == 1 assert pd2.a == 2 assert pd2.b == 2
def test_shallow_replace(): pd1 = ParamDict(a=3, b=4) pd2 = ParamDict(b=14) pd3 = ParamDict(c=15) pd1orig = pd1.copy() pd1.replace_shallow(pd2) assert all(k in pd1 for k in pd1orig) assert all(pd1[k] == pd2[k] for k in pd2) assert all(pd1[k] == pd1orig[k] for k in pd1orig if not k in pd2) with pytest.raises(RuntimeError): pd1.replace_shallow(pd3)
def test_init_by_kwargs(): pd = ParamDict(foo='hei', bar='argh') assert pd.foo == 'hei' assert pd.bar == 'argh' assert pd["foo"] == 'hei' assert pd["bar"] == 'argh' assert len(pd) == 2
def default_params(cls): """ Default parameters are: +----------------------+-----------------------+--------------------------------------------------------------+ |Key | Default value | Description | +======================+=======================+==============================================================+ | casedir | '.' | Case directory - relative path to use for saving | +----------------------+-----------------------+--------------------------------------------------------------+ | extrapolate | True | Constant extrapolation of fields prior to first | | | | update call | +----------------------+-----------------------+--------------------------------------------------------------+ | initial_dt | 1e-5 | Initial timestep. Only used in planning algorithm at first | | | | update call. | +----------------------+-----------------------+--------------------------------------------------------------+ | clean_casedir | False | Clean out case directory prior to update. | +----------------------+-----------------------+--------------------------------------------------------------+ | flush_frequency | 1 | Frequency to flush shelve and txt files (playlog, | | | | metadata and data) | +----------------------+-----------------------+--------------------------------------------------------------+ """ params = ParamDict( casedir=".", extrapolate=True, initial_dt=1e-5, clean_casedir=False, flush_frequency=1, ) return params
def __call__(self, parser, namespace, values, option_string=None): parameterized = {} # Start parsing arguments for arg in values: # Stop parsing if we've reached a new option #if arg[0] == '-': # break #nargs += 1 # Create new key if this is not recognized as a parameter if "=" not in arg: key = arg parameterized[key] = ParamDict() continue # Add parameters param, value = arg.split('=') if value.isdigit(): parameterized[key][param] = int(value) else: try: parameterized[key][param] = float(value) except ValueError: parameterized[key][param] = value # Removed parsed args from parser setattr(namespace, self.dest, parameterized)
def default_params(cls): """ Default parameters are: +----------------------+-----------------------+-------------------------------------------------------------------+ |Key | Default value | Description | +======================+=======================+===================================================================+ | casedir | '.' | Case directory - relative path to read solutions from | +----------------------+-----------------------+-------------------------------------------------------------------+ | restart_times | -1 | float or list of floats to find restart times from. If -1, | | | | restart from last available time. | +----------------------+-----------------------+-------------------------------------------------------------------+ | solution_names | 'default' | Solution names to look for. If 'default', will fetch all | | | | fields stored as SolutionField. | +----------------------+-----------------------+-------------------------------------------------------------------+ | rollback_casedir | False | Rollback case directory by removing all items stored after | | | | largest restart time. This allows for saving data from a | | | | restarted simulation in the same case directory. | +----------------------+-----------------------+-------------------------------------------------------------------+ """ params = ParamDict( casedir='.', restart_times=-1, #restart_timesteps=-1, solution_names="default", rollback_casedir=False, #interpolate=True, #dt=None, ) return params
def _init_postprocessor(self): self.postprocessor._timer = self.timer # Handle restarting or cleaning of fresh casedir if self.params.restart: Restart(self.problem, self.postprocessor, self.params.restart_time, self.params.restart_timestep) self.timer.completed("set up restart") else: # If no restart, remove any existing data coming from cbcflow self.postprocessor.clean_casedir() self.timer.completed("cleaned casedir") # Store parameters params = ParamDict(solver=self.params, problem=self.problem.params, scheme=self.scheme.params, postprocessor=self.postprocessor.params) self.postprocessor.store_params(params) # Store mesh assert hasattr(self.problem, "mesh") and isinstance( self.problem.mesh, Mesh), "Unable to find problem.mesh!" self.postprocessor.store_mesh(self.problem.mesh) self.timer.completed("stored mesh")
def test_add_params_after_init_succeeds_with_dict_notation(): pd = ParamDict() pd["a"] = 1 pd["b"] = 2 assert pd.a == 1 assert pd.b == 2 assert len(pd) == 2
def test_init_from_dict(): d = {'a': 1, 'b': 3.14} pd = ParamDict(d) assert len(pd) == 2 assert pd.a == d['a'] assert pd.b == d['b'] assert pd['a'] == d['a'] assert pd['b'] == d['b']
def test_init_by_sequence(): keys = ('a', 'b', 'c') values = (1, 2, 3) items = tuple(zip(keys, values)) pd = ParamDict(items) assert pd.a == 1 assert pd.b == 2 assert pd.c == 3
def test_recursive_copy(): pdcc1 = ParamDict(cca=30) pdcc2 = ParamDict(ccb=40) pdc1 = ParamDict(a=3, b=4, cc1=pdcc1, cc2=pdcc2) pdc2 = ParamDict(c=5, d=6) pd1 = ParamDict(c1=pdc1, c2=pdc2) pd2 = pd1.copy_recursive() assert pd1.c2.d == 6 assert pd2.c2.d == 6 pd1.c2.d = 7 assert pd1.c2.d == 7 assert pd2.c2.d == 6 pd2.c2.d = 8 assert pd1.c2.d == 7 assert pd2.c2.d == 8 assert pd1.c1.cc2.ccb == 40 assert pd2.c1.cc2.ccb == 40 pd2.c1.cc2.ccb = 50 assert pd1.c1.cc2.ccb == 40 assert pd2.c1.cc2.ccb == 50 pd1.c1.cc2.ccb = 60 assert pd1.c1.cc2.ccb == 60 assert pd2.c1.cc2.ccb == 50
def create_multilevel_pd(): pda1 = ParamDict(a=1) pdb1 = ParamDict(b=2) pdc1 = ParamDict(pa=pda1, pb=pdb1) pda2 = ParamDict(a=3) pdb2 = ParamDict(b=4) pdc2 = ParamDict(pa=pda2, pb=pdb2) pdd = ParamDict(pc1=pdc1, pc2=pdc2) return pdd
def test_iterdeep_shallow_data(): pd = ParamDict() deep = tuple(pd.iterdeep()) assert deep == () pd = ParamDict(a=3, b=4) deep = tuple(pd.iterdeep()) assert deep == (('a', 3), ('b', 4))
def default_params(cls): """ Default parameters are: +------------------------+-----------------------+--------------------------------------------------------------+ |Key | Default value | Description | +========================+=======================+==============================================================+ | check_memory_frequency | 0 | Frequency to report memory usage | +------------------------+-----------------------+--------------------------------------------------------------+ """ params = ParamDict(check_memory_frequency=0, ) return params
def test_shallow_update(): pd1 = ParamDict(a=3, b=4) pd2 = ParamDict(b=14, c=15) pd1orig = pd1.copy() pd1.update_shallow(pd2) assert all(k in pd1 for k in pd1orig) assert all(k in pd1 for k in pd2) assert all(pd1[k] == pd2[k] for k in pd2) assert all(pd1[k] == pd1orig[k] for k in pd1orig if not k in pd2)
def test_shallow_iteration(): keys = ('a', 'b', 'c') values = (1, 2, 3) items = tuple(zip(keys, values)) pd = ParamDict(items) assert tuple(sorted(pd)) == keys assert tuple(sorted(pd.iterkeys())) == keys assert tuple(sorted(pd.keys())) == keys assert tuple(sorted(pd.iteritems())) == items assert tuple(sorted(pd.itervalues())) == values
def test_store_params(casedir): pp = PostProcessor(dict(casedir=casedir)) params = ParamDict(Field=Field.default_params(), PostProcessor=PostProcessor.default_params()) pp.store_params(params) # Read back params params2 = None with open(os.path.join(pp.get_casedir(), "params.pickle"), 'r') as f: params2 = pickle.load(f) assert params2 == params str_params2 = open(os.path.join(pp.get_casedir(), "params.txt"), 'r').read() assert str_params2 == str(params)
def default_params(cls): """Returns the default parameters for a problem. Explanation of parameters: Time parameters: - start_timestep: int, initial time step number - dt: float, time discretization value - T0: float, initial time - T: float, end time - period: float, length of period - num_periods: float, number of periods to run Either T or period and num_period must be set. If T is not set, T=T0+period*num_periods is used. Physical parameters: - mu: float, kinematic viscosity - rho: float, mass density Space discretization parameters: - mesh_file: str, filename to load mesh from (if any) """ params = ParamDict( # Physical parameters: mu=None, rho=None, # Time parameters: start_timestep=0, dt=None, T0=0.0, T=None, period=None, num_periods=None, # Spatial discretization parameters: mesh_file=None, ) return params
def default_params(cls): params = ParamDict( # Discretization parameters u_degree = None, # Require this to be set explicitly by scheme subclass! p_degree = None, # Require this to be set explicitly by scheme subclass! # TODO: These ipcs solvers are scheme specific and should maybe not be here, # however they are used by most of the splitting schemes... # TODO: Split these into separate parameters for solver/preconditioner? solver_u_tent=("gmres", "default"), solver_p_neumann=("gmres", "amg"), solver_p_dirichlet=("gmres", "amg"), solver_p=None, # overrides neumann/dirichlet if given solver_u_corr=("bicgstab", "default"), # Timestepping method # FIXME: Adaptive timestepping still unsupported # adaptive_timestepping=False, ) return params
def default_params(cls): """Returns the default parameters for a problem. Explanation of parameters: - restart: bool, turn restart mode on or off - restart_time: float, time to search for restart data - restart_timestep: int, timestep to search for restart data - check_memory_frequency: int, timestep frequency to check memory consumption - timer_frequency: int, timestep frequency to print more detailed timing - enable_annotation: bool, enable annotation of solve with dolfin-adjoint If restart=True, maximum one of restart_time and restart_timestep can be set. """ params = ParamDict( restart=False, restart_time=-1.0, restart_timestep=-1, timer_frequency=0, check_memory_frequency=0, enable_annotation=False, ) return params
def test_recursive_update(): # Build multilevel test data pdcc1 = ParamDict(cca=30) pdcc2 = ParamDict(ccb=40) pdc1 = ParamDict(a=3, b=4, cc1=pdcc1, cc2=pdcc2) pdc2 = ParamDict(c=5, d=6) pdorig = ParamDict(c1=pdc1, c2=pdc2, v=7) # Build alternative multilevel test data apdcc1 = ParamDict(cca=31) apdcc2 = ParamDict(ccb=41) apdc1 = ParamDict(a=5, b=8, cc1=apdcc1, cc2=apdcc2) apdc2 = ParamDict(c=7, d=9) apdorig = ParamDict(c1=apdc1, c2=apdc2, v=2) assert pdorig != apdorig # Supply a single item pd = pdorig.copy_recursive() assert pd.v == 7 pd.update_recursive(v=9) assert pd.v == 9 pd.update_recursive({'v': 10}) assert pd.v == 10 pd.update_recursive(ParamDict(v=11)) assert pd.v == 11 # Supply multiple items for child pd = pdorig.copy_recursive() assert pd.c1.a == 3 assert pd.c1.b == 4 if 0: pd.update_recursive(c1={'a': 11, 'b': 22}) assert pd.c1.a == 11 assert pd.c1.b == 22 pd.update_recursive(c1=ParamDict(a=13, b=25)) assert pd.c1.a == 13 assert pd.c1.b == 25 # Supply a full multilevel paramdict pd = pdorig.copy_recursive() assert pd == pdorig assert pd != apdorig pd.update_recursive(apdorig) assert pd != pdorig assert pd == apdorig
def __copy__(self): cls = self.__class__ result = cls.__new__(cls) result.__dict__.update(self.__dict__) result.params = ParamDict(self.params) return result
def default_params(cls): """ Default params are: +----------------------+-----------------------+-------------------------------------------------------------------+ |Key | Default value | Description | +======================+=======================+===================================================================+ | start_timestep | -1e16 | Timestep to start computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | end_timestep | 1e16 | Timestep to end computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | stride_timestep | 1 | Number of steps between each computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | start_time | -1e16 | Time to start computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | end_time | 1e16 | Time to end computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | stride_time | 1e-16 | Time between each computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | plot | False | Plot Field after a directly triggered computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | plot_args | {} | Keyword arguments to pass to dolfin.plot. | +----------------------+-----------------------+-------------------------------------------------------------------+ | safe | True | Trigger safe computation. This allows get-calls to this field | | | | outside postprocessor. Set to False to rely on postprocessor | | | | and improve efficiency. | +----------------------+-----------------------+-------------------------------------------------------------------+ | save | False | Save Field after a directly triggered computation | +----------------------+-----------------------+-------------------------------------------------------------------+ | save_as | 'determined by data' | Format(s) to save in. Allowed save formats: | | | | | | | | The default values are: | | | | | | | | - ['hdf5', 'xdmf'] if data is dolfin.Function | | | | - ['txt', 'shelve'] if data is float, int, list, tuple or dict | | | | | +----------------------+-----------------------+-------------------------------------------------------------------+ | rewrite_mesh | False | Rewrite mesh to file at every timestep | +----------------------+-----------------------+-------------------------------------------------------------------+ | expr2function | 'assemble' | How to convert Expression to Function. Allowed values: | | | | | | | | - 'assemble' | | | | - 'project' | | | | - 'interpolate' | +----------------------+-----------------------+-------------------------------------------------------------------+ | finalize | False | Switch whether to finalize if Field. This is especially useful | | | | when a costly computation is only interesting at the end time. | +----------------------+-----------------------+-------------------------------------------------------------------+ """ params = ParamDict( # Configure direct compute requests through timestep counting start_timestep=-1e16, end_timestep=1e16, stride_timestep=1, # Configure direct compute requests through physical time intervals start_time=-1e16, end_time=1e16, stride_time=1e-16, # Trigger and configure action after each direct compute request plot=False, plot_args={}, safe=True, save=False, save_as=cls.default_save_as(), rewrite_mesh=False, #callback = False, # Configure computing expr2function="assemble", #project = False, # This is the safest approach #assemble = True, # This is faster but only works for for DG0 #interpolate = False, # This will be the best when properly implemented in fenics # Finalize field? finalize=False, ) return params
def test_recursive_replace(): # Build multilevel test data pdcc1 = ParamDict(cca=30) pdcc2 = ParamDict(ccb=40) pdc1 = ParamDict(a=3, b=4, cc1=pdcc1, cc2=pdcc2) pdc2 = ParamDict(c=5, d=6) pdorig = ParamDict(c1=pdc1, c2=pdc2, v=7) # Build alternative multilevel test data apdcc1 = ParamDict(cca=31) apdcc2 = ParamDict(ccb=41) apdc1 = ParamDict(a=5, b=8, cc1=apdcc1, cc2=apdcc2) apdc2 = ParamDict(c=7, d=9) apdorig = ParamDict(c1=apdc1, c2=apdc2, v=2) assert pdorig != apdorig # Supply a single item pd = pdorig.copy_recursive() assert pd.v == 7 pd.replace_recursive(v=9) assert pd.v == 9 pd.replace_recursive({'v': 10}) assert pd.v == 10 pd.replace_recursive(ParamDict(v=11)) assert pd.v == 11 # Supply multiple items for child pd = pdorig.copy_recursive() assert pd.c1.a == 3 assert pd.c1.b == 4 if 0: pd.replace_recursive(c1={'a': 11, 'b': 22}) assert pd.c1.a == 11 assert pd.c1.b == 22 pd.replace_recursive(c1=ParamDict(a=13, b=25)) assert pd.c1.a == 13 assert pd.c1.b == 25 # Supply a full multilevel paramdict pd = pdorig.copy_recursive() assert pd == pdorig assert pd != apdorig pd.replace_recursive(apdorig) assert pd != pdorig assert pd == apdorig # Raises for single missing item pd = pdorig.copy_recursive() with pytest.raises(RuntimeError): pd.replace_recursive(v2=13) # Build alternative multilevel test data rpdcc1 = ParamDict(cca2=32) rpdc1 = ParamDict(cc1=rpdcc1) rpdorig = ParamDict(c1=rpdc1) # Raises for item deep in recursive structure pd = pdorig.copy_recursive() with pytest.raises(RuntimeError): pd.replace_recursive(rpdorig)
def test_arg_rendering_parsing(): pdid = ParamDict(a=1, b=2) pdin = ParamDict(a=1, b=3) pdout = ParamDict(a=1, b=4) record = ParamDict(a="foo", b="bar", c=(1, 2, "foo"), identity=pdid, input=pdin, output=pdout) pd_default = ParamDict(a=None, b=None) pd = ParamDict(identity=pd_default, input=pd_default, output=pd_default, c=None, **pd_default) assert pd != record pd.parse_args(record.render_args()) assert pd == record
def test_add_params_after_init_raises_with_attribute_notation(): pd = ParamDict() with pytest.raises(RuntimeError): pd.a = 1