def main(): import os import sys generation_params = CUDACodeGenerator.default_parameters() params = ParameterDict( list_timings=Param( False, description="If true timings for reading " "and evaluating the model is listed.", ), system_headers=Param( True, description="If true system " "headers needed to compile moudle is " "included.", ), output=Param("", description="Specify output file name"), **dict((name, param) for name, param in list(generation_params.items()) if name not in ["class_code"]), ) params.parse_args(usage="usage: %prog FILE [options]") # sys.argv[2:]) if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") file_name = sys.argv[1] gotran2cuda(file_name, params)
def test_optstr(self): base0, base1, p = default_params(sp) self.assertEqual( p.optstr(), " --a.abla sin --a.abli 123 --b.bblal 987 " "--b.bling akjh --other 0.1239 --something_very_long 3", ) p.parse_args(["--a.abla", "cos", "--b.bling", "smada"]) self.assertEqual(p.a.abla, "cos") self.assertEqual(p.b.bling, "smada") with self.assertRaises(ValueError) as cm: p.parse_args(["--other", "-1"]) self.assertEqual( six.text_type(cm.exception), ("Trying to set 'other' while parsing " + "command line, but Illegal value 'other': -1.0 " + b"\xe2\x88\x89 (0, 10]".decode("utf-8")), ) p = ParameterDict(list=[1, 2, 3, 4, 5]) p.parse_args(["--list", "-1", "1", "2"]) self.assertEqual(p.list, [-1, 1, 2])
def main(): generation_params = parameters.generation.copy() params = ParameterDict( list_timings=Param( False, description="If true timings for reading " "and evaluating the model is listed.", ), output=Param("", description="Specify output file name"), import_inside_functions=Param( False, description="Perform imports inside functions", ), namespace=OptionParam( "math", ["math", "np", "numpy", "ufl"], description="The math namespace of the generated code", ), **generation_params, ) params.parse_args(usage="usage: %prog FILE [options]") # sys.argv[2:]) if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") file_name = sys.argv[1] gotran2py(file_name, params)
def main(): params = ParameterDict(flat_view=Param( True, description="List all objects in a flat view"), ) params.parse_args(usage="usage: %prog FILE [options]") if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") file_name = sys.argv[1] gotranprobe(file_name, params)
def main(): params = ParameterDict(output=Param( "", description="Specify output file name"), **DOLFINCodeGenerator.default_parameters()) params.parse_args(usage="usage: %prog FILE [options]") # sys.argv[2:]) if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") file_name = sys.argv[1] gotran2dolfin(file_name, params)
def default_parameters(): default_params = parameters.generation.code.copy() state_repr = dict.__getitem__(default_params.states, "representation") param_repr = dict.__getitem__(default_params.parameters, "representation") return ParameterDict(state_repr=state_repr, param_repr=param_repr, )
def default_parameters(): # Start with a modified subset of the global parameters default_params = CUDACodeGenerator.default_parameters().copy() return ParameterDict( code=default_params.code, solvers=default_params.solvers, solver=OptionParam( "explicit_euler", list(default_params.solvers.keys()), description="Default solver type", ), block_size=ScalarParam( 256, ge=1, description="Number of threads per CUDA block", ), ode_substeps=ScalarParam( 1, ge=1, description="Number of ODE steps to compute per " "forward function call", ), nvcc=Param("nvcc", description="Command to run nvcc compiler"), gpu_arch=TypelessParam( None, description="The name of the class of nVidia GPU " "architectures for which the CUDA input must " "be compiled", ), gpu_code=TypelessParam( None, description="The names of nVidia GPUs to generate code " "for", ), keep_cuda_code=Param( False, description="If true, CUDA compiler output is kept, and a" "line indicating its location in the file " "system is printed for debugging purposes", ), cuda_cache_dir=TypelessParam( None, description="Directory for compiler caching. Has a " "sensible per-user default. If False, caching " "is disabled.", ), # no_extern_c=Param( # False, # description=""), # cuda_include_dirs=Param( # [""], # description="Additional CUDA include directories"), nvcc_options=Param([""], description="Additional nvcc options"), )
def main(): params = _default_latex_params() params = ParameterDict( sympy_contraction=Param( True, description="If True sympy contraction" " will be used, turning (V-3)/2 into V/2-3/2", ), **params, ) params.parse_args(usage="usage: %prog FILE [options]") if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") filename = sys.argv[1] gotran2latex(filename, params)
def main(): import os import sys params = ParameterDict( components=Param( [""], description="List all components that will be " "exported.", ), name=Param("", description="Specify name of exported ODE."), ) params.parse_args(usage="usage: %prog FILE [options]") if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") file_name = sys.argv[1] gotranexport(file_name, params)
def main(): generation_params = MatlabCodeGenerator.default_parameters() params = ParameterDict( list_timings=Param( False, description="If true timings for reading " "and evaluating the model is listed.", ), output=Param("", description="Specify output file name"), **generation_params, ) params.parse_args(usage="usage: %prog FILE [options]") # sys.argv[2:]) if len(sys.argv) < 2: raise RuntimeError("Expected a single gotran file argument") if not os.path.isfile(sys.argv[1]): raise IOError("Expected the argument to be a file") file_name = sys.argv[1] gotran2matlab(file_name, params)
def default_params(sp=True): params = dict( something_very_long="3", other=ScalarParam(0.1239, le=10, gt=0), a=default_a(), b=default_b(), const=ConstParam(3), ) base0, base1 = None, None if sp: base0 = ScalarParam(5, gt=0, name="base0") base1 = ScalarParam(0.5, gt=0, name="base1") params["zlave"] = base0.sym * base1.sym return base0, base1, ParameterDict(**params)
def default_parameters(): default_params = parameters.generation.code.copy() state_repr = dict.__getitem__(default_params.states, "representation") body_repr = dict.__getitem__(default_params.body, "representation") use_cse = dict.__getitem__(default_params.body, "use_cse") optimize_exprs = dict.__getitem__(default_params.body, "optimize_exprs") return ParameterDict(state_repr=state_repr.copy(), body_repr=body_repr.copy(), use_cse=use_cse.copy(), optimize_exprs=optimize_exprs.copy(), generate_jacobian = Param(\ False, description="Generate analytic jacobian "\ "when integrating."),\ generate_lu_factorization = Param(\ False, description="Generate analytic lu" \ "factorization of jacobian when integrating."),\ generate_forward_backward_subst = Param(\ False, description="Generate analytic forward" \ "backward substituion of factorized jacobian when "\ "integrating."),\ )
def default_a(): return ParameterDict(abla="sin", abli=123)
def _default_params(exclude=None): exclude = exclude or [] check_arg(exclude, list, itemtypes=str) # Add not implemented parameters to excludes exclude += ["max_terms", "parameter_contraction", "use_variables"] # Build a dict with allowed parameters params = {} if "use_state_names" not in exclude: # Use state names in code (compared to array with indices) params["use_state_names"] = Param( True, description="Use state names in code " "(compared to array with indices)", ) if "use_parameter_names" not in exclude: # Use parameter names in code (compared to array with indices) params["use_parameter_names"] = Param( True, description="Use parameter names " "in code (compared to array with indices)", ) if "keep_intermediates" not in exclude: # Keep all intermediates params["keep_intermediates"] = Param( True, description="Keep intermediates in code", ) if "use_variables" not in exclude: # If True, code for altering variables are created # FIXME: Not used params["use_variables"] = Param( False, description="If True, code for altering variables are created", ) if "parameter_contraction" not in exclude: # Find sub expressions of only parameters and create a dummy parameter # FIXME: Not used params["parameter_contraction"] = Param( False, description="Find sub expressions of only parameters " "and create a dummy parameter", ) if "parameter_numerals" not in exclude: # Exchange all parameters with their initial numerical values params["parameter_numerals"] = Param( False, description="Exchange all parameters with their initial" " numerical values", ) if "max_terms" not in exclude: # Split terms with more than max_terms into several evaluations # FIXME: Not used params["max_terms"] = ScalarParam( 5, ge=2, description="Split terms with more than max_terms " "into several evaluations", ) if "use_cse" not in exclude: # Use sympy common sub expression simplifications, # only when keep_intermediates is false params["use_cse"] = Param( False, description="Use sympy common sub expression " "simplifications, only when keep_intermediates is false", ) if "generate_jacobian" not in exclude: # Generate code for the computation of the jacobian params["generate_jacobian"] = Param( True, description="Generate code for the computation of the jacobian", ) if "transposed_jacobian" not in exclude: # Generate code for the computation of the jacobian params["transposed_jacobian"] = Param( False, description="The Jacobian is transposed", ) if "generate_lu_factorization" not in exclude: # Generate code for the factorization of the jacobian params["generate_lu_factorization"] = Param( True, description="Generate code for the factorization of the jacobian", ) if "generate_forward_backward_subst" not in exclude: # Generate code for the forward backward substitution code params["generate_forward_backward_subst"] = Param( True, description= "Generate code for the forward backward substitution code", ) if "generate_linearized_evaluation" not in exclude: # Generate code for linearized evaluation # For sympy versions lower than 0.7.2 linearized computation does not work default_linearized_evaluation = _current_sympy_version > _V("0.7.2") params["generate_linearized_evaluation"] = Param( default_linearized_evaluation, description="Generate code for linearized evaluation", ) # Return the ParameterDict return ParameterDict(**params)
def _default_latex_params(): """ Initializes default parameters. """ params = dict() # Specify output file params["output"] = Param("", description="Specify LaTeX output file") # Set number of columns per page # FIXME: ScalarParam might cause parse_args() to crash due to non-ASCII # symbols. # params["page_columns"] = ScalarParam( # 1, ge=1, description="Set number of columns per page in " # "LaTeX document") params["page_columns"] = Param( 1, description="Set number of columns per page in " "LaTeX document", ) # Set equation font size # FIXME: ScalarParam might cause parse_args() to crash due to non-ASCII # symbols. # params["font_size"] = ScalarParam( # 10, ge=1, description="Set global font size for LaTeX document") params["font_size"] = Param( 10.0, description="Set global font size for LaTeX document", ) # Set font size for mathematical expressions. # FIXME: ScalarParam might cause parse_args() to crash due to non-ASCII # symbols. # params["math_font_size"] = ScalarParam( # 1, ge=1, description="Set font size for mathematical " # "expressions in LaTeX document. Uses global font size if left " # "blank") params["math_font_size"] = Param( 0.0, description="Set font size for mathematical expressions in " "LaTeX document. Uses global font size if left blank", ) # Toggle bold equation labels params["bold_equation_labels"] = Param( True, description="Give equation labels a bold typeface in " "LaTeX document", ) # If set to False, does not generate the preamble params["preamble"] = Param( True, description="If set to False, LaTeX document will be " "be generated without the preamble", ) # If set to true, sets document to a landscape page layout params["landscape"] = Param( False, description="Set LaTeX document to landscape layout", ) # Latex separator between factors in products params["mul_symbol"] = Param( "dot", description="Multiplication symbol for Sympy LatexPrinter", ) # Flag to enable page numbers params["page_numbers"] = Param(True, description="Enable page numbers") # Flag to disable state table (currently unused) # params["no_state_descriptions"] = Param( # False, description="Disable table column for state descriptions") # Flag to disable parameter table (currently unused) # params["no_parameter_descriptions"] = Param( # False, description="Disable table column for parameter descriptions") # Set headline types for States, Parameters and Components params["section_type"] = Param( "section", description="Section type (e.g. 'section', 'subsection')", ) # Set page margins params["margins"] = Param( "", description="Set page margins (e.g. '0.75in'). Uses LaTeX " "defaults if left blank", ) # Set column seperator distance params["columnsep"] = Param( "", description="Set column separator distance (e.g. '0.25cm'). " "Uses LaTeX default if left blank", ) # Set column separator line width params["columnseprule"] = Param( "", description="Set column separator line width (e.g. '0.2pt'). " "Uses LaTeX default if left blank", ) # Flag to let the code generator attempt automatically converting # state and parameter names in descriptions to math-mode params["auto_format_description"] = Param( False, description="Automatically format state and parameter " "descriptions", ) # Flag to toggle numbering style for equations. params["equation_subnumbering"] = Param( True, description="Use component-wise equation subnumbering", ) params["parameter_description_cell_style"] = Param( "l", description="Set description cell type for the parameter table. " "Use 'X' for long descriptions, or 'p{5cm}' to set a fixed 5 cm", ) params["state_description_cell_style"] = Param( "l", description="Set description cell type for the state table. " "Use 'X' for long descriptions, or 'p{5cm}' to set a fixed 5 cm", ) # Return the ParameterDict return ParameterDict(**params)
def main(): import os import sys body_params = parameters.generation.code.body.copy() code_params = ParameterDict( language=OptionParam("C", ["Python", "C"]), body_repr=dict.__getitem__(body_params, "representation"), use_cse=dict.__getitem__(body_params, "use_cse"), optimize_exprs=dict.__getitem__(body_params, "optimize_exprs"), generate_jacobian=Param( False, description="Generate and use analytic " "jacobian when integrating.", ), ) steady_state = ParameterDict( solve=Param( False, description="If true scipy.optimize.root is used " "to find a steady state for a given parameters.", ), method=OptionParam( "hybr", [ "hybr", "lm", "broyden1", "broyden2", "anderson", "linearmixing", "diagbroyden", "excitingmixing", "krylov", ], ), tol=ScalarParam(1e-5, description="Tolerance for root finding algorithm."), ) solver = OptionParam( "scipy", ["scipy"] + list(parameters.generation.solvers.keys()), description="The solver that will be used to " "integrate the ODE.", ) params = ParameterDict( solver=solver, steady_state=steady_state, parameters=Param([""], description="Set parameter of model"), init_conditions=Param([""], description="Set initial condition of model"), tstop=ScalarParam(100.0, gt=0, description="Time for stopping simulation"), dt=ScalarParam(0.1, gt=0, description="Timestep for plotting."), plot_y=Param(["V"], description="States or monitored to plot on the y axis."), plot_x=Param( "time", description="Values used for the x axis. Can be time " "and any valid plot_y variable.", ), model_arguments=Param([""], description="Set model arguments of the model"), code=code_params, save_results=Param( False, description="If True the results will be " "saved to a 'results.csv' file.", ), basename=Param( "results", description="The basename of the results " "file if the 'save_results' options is True.", ), ) params.parse_args(usage="usage: %prog FILE [options]") if len(sys.argv) < 2: error("Expected a single gotran file argument.") if not os.path.isfile(sys.argv[1]): error("Expected the argument to be a file.", exception=IOError) file_name = sys.argv[1] gotranrun(file_name, params)
parameters = ParameterDict( # Generation parameters generation=ParameterDict( class_code=Param( False, description="If true methods are contained " "inside a class", ), # Code generation parameters code=ParameterDict( # Float precision float_precision=OptionParam( "double", ["double", "single"], description="Float precision in generated " "code.", ), # Parameter for default argument order default_arguments=OptionParam( "stp", ["tsp", "stp", "spt", "ts", "st"], description="Default input argument order: " "s=states, p=parameters, t=time", ), # Parameter for the time parameter name time=ParameterDict(name=Param("t", description="Name of time argument")), # Parameter for the time step parameter name dt=ParameterDict( name=Param("dt", description="Name of time step argument"), ), # Number of nodes for solvers n_nodes=ScalarParam(0, ge=0, description="Number of nodes for simulation"), # Parameters for code generation of arrays array=ParameterDict( index_format=OptionParam( "[]", ["[]", "{}", "()"], description="The format of index notations.", ), index_offset=ScalarParam( 0, ge=0, description="A global offset to all indexed variables.", ), flatten=Param( True, description="If true multidimensional arrays will be " "flattened. jac[2,3] -> jac[27] if the shape of jac " "is (12,12)", ), ), # Parameters for code generation of parameters parameters=ParameterDict( field_parameters=Param( [""], description="A list of parameter names " "which should be treated as field parameters. " "Only available for CUDA backends.", ), representation=OptionParam( "named", ["named", "array", "numerals"], description="Controls how parameters are " "represented in the code. As named variables," " as an indexed array or as the default " "numeral values given in the gotran model.", ), array_name=Param( "parameters", description="The name of the array " "representing the parameters.", ), field_array_name=Param( "field_parameters", description="The name of the array " "representing the field parameters.", ), add_offset=Param( False, description="If true an offset will be " "added to the index of each parameter", ), add_field_offset=Param( False, description="If true an offset will be " "added to the index of each field parameter", ), ), # Parameters for code generation of states states=ParameterDict( field_states=Param( [""], description="A list of state names " "which should be treated as field states. " "Not available for all backends...", ), representation=OptionParam( "named", ["named", "array"], description="Controls how states are " "represented in the code. As named variables," " or as an indexed array.", ), array_name=Param( "states", description="The name of the array " "representing the states.", ), add_offset=Param( False, description="If true an offset will be " "added to the index of each state", ), ), # Parameters for code generation of body expressions body=ParameterDict( use_cse=Param( False, description="If true will the body be " "optimized using SymPy common sub expression " "extraction.", ), use_enum=Param( False, description="If true use enumeration" "data types instead of indexing.", ), in_signature=Param( False, description="If true the body argument " "will be included in the signature.", ), representation=OptionParam( "named", ["named", "array", "reused_array"], description="Controls how body variables are " "represented in the code. As named variables," "as an indexed array or as indexed array with " "reuse of unused array elements.", ), array_name=Param( "body", description="The name of the array " "representing the body.", ), optimize_exprs=OptionParam( "none", ["none", "numerals", "numerals_symbols"], description="Remove body expressions as " "intermediates, which contains only a " "numeral or numerals and a symbol.", ), ), ), # Parameters for automatic generation of specific functions functions=ParameterDict( rhs=ParameterDict( generate=Param( True, description="Generate code for the " "evaluation of the right hand side evaluation.", ), function_name=Param( "rhs", description="The name of " "the generated function.", ), result_name=Param( "values", description="The name of " "the result argument.", ), ), monitored=ParameterDict( generate=Param( True, description="Generate code for the " "evaluation of monitored intermediates.", ), function_name=Param( "monitor", description="The name of " "the generated function.", ), result_name=Param( "monitored", description="The name of " "the result argument.", ), ), jacobian=ParameterDict( generate=Param( False, description="Generate code for the " "evaluation of the jacobian of the right hand " "side.", ), function_name=Param( "compute_jacobian", description="The name " "of the generated function.", ), result_name=Param( "jac", description="The name of " "the result argument.", ), ), lu_factorization=ParameterDict( generate=Param( False, description="Generate code for " "symbolicly factorize the jacobian.", ), function_name=Param( "lu_factorize", description="The name " "of the generated function.", ), ), forward_backward_subst=ParameterDict( generate=Param( False, description="Generate code for the " "symbolic forward backward substitution of the " "jacobian.", ), function_name=Param( "forward_backward_subst", description="The name of the generated " "function.", ), residual_name=Param( "F", description="The name of " "the residual argument.", ), result_name=Param( "dx", description="The name of " "the incriment argument.", ), ), componentwise_rhs_evaluation=ParameterDict( generate=Param( False, description="If true, generate code for " "computing componentwise evaluation of the rhs.", ), function_name=Param( "componentwise_rhs", description="The name of the generated " "function.", ), ), linearized_rhs_evaluation=ParameterDict( generate=Param( False, description="If true, generate code for " "computing linearized evaluation of linear rhs " "terms.", ), function_name=Param( "linearized_rhs", description="The name of the generated " "function.", ), include_rhs=Param( False, description="If True the rhs will be " "included as a result argument.", ), only_linear=Param( True, description="If True only linearized " "expressions for the linear derivatives will " "be generated.", ), result_names=Param( ["linearized", "rhs"], description="The name of " "the two results arguments.", ), ), ), # Parameters for automatic generation of lists/arrays of names for states and parameters lists=ParameterDict( parameter_names=ParameterDict( generate=Param(False, description="Generate list of parameter names"), name=Param("parameter_names", description="Name of list variable"), ), state_names=ParameterDict( generate=Param(False, description="Generate list of state names"), name=Param("state_names", description="Name of list variable"), ), ), # Parameters for automatic generation of specific solver functions solvers=ParameterDict( explicit_euler=ParameterDict( generate=Param( False, description="If true, generate code for " "solving an ODE using explicit Euler method.", ), function_name=Param( "forward_explicit_euler", description="The name of the generated " "function.", ), ), rush_larsen=ParameterDict( generate=Param( False, description="If true, generate code for " "solving an ODE using Rush Larsen method.", ), function_name=Param( "forward_rush_larsen", description="The name of the generated " "function.", ), delta=ScalarParam( 1e-8, gt=0, lt=1.0, description="Value to " "safeguard the evaluation of the rush larsen " "step.", ), ), generalized_rush_larsen=ParameterDict( generate=Param( False, description="If true, generate code for " "solving an ODE using generalized Rush Larsen method.", ), function_name=Param( "forward_generalized_rush_larsen", description="The name of the generated " "function.", ), delta=ScalarParam( 1e-8, gt=0, lt=1.0, description="Value to " "safeguard the evaluation of the rush larsen " "step.", ), ), hybrid_generalized_rush_larsen=ParameterDict( generate=Param( False, description="If true, generate code for " "solving an ODE using a hybrid generalized Rush Larsen method.", ), function_name=Param( "forward_hybrid_generalized_rush_larsen", description="The name of the generated " "function.", ), delta=ScalarParam( 1e-8, gt=0, lt=1.0, description="Value to " "safeguard the evaluation of the rush larsen " "step.", ), stiff_states=Param( "", name="stiff_states", description="List of names of state variables that should " "be solved with the GRL1 scheme that has better stability" "than explicit Euler", ), ), simplified_implicit_euler=ParameterDict( generate=Param( False, description="If true, generate code for " "solving an ODE using Rush Larsen method.", ), function_name=Param( "forward_simplified_implicit_euler", description="The name of the generated " "function.", ), numeric_jacobian=Param( False, description="Use numeric " "calculated diagonal jacobian.", ), ), ), ), # Parameters for different input input=ParameterDict( # Parameters for CellML input cellml=ParameterDict( change_state_names=Param( [], description="A list of state names " "which should be changed to not interfere " "with for example a parameter name.", ), grouping=OptionParam( "encapsulation", ["encapsulation", "containment"], description="Determines what type of grouping " "should be used when the cellml model is parsed.", ), use_sympy_integers=Param( False, description="If yes dedicated sympy " "integers will be used instead of the " "integers 0-10. This will turn 1/2 into a " "sympy rational instead of the float 0.5.", ), strip_parent_name=Param( True, description="If True strip the name from " "the child component it contains the name of the " "parent component.", ), ), ), )
def default_b(): return ParameterDict( bblal=987, bling=OptionParam("akjh", ["akjh", "bla", "jada", "smada"]), )