コード例 #1
0
def deploy_turbines(config, nx, ny, friction=21.):
    ''' Generates an array of initial turbine positions with nx x ny turbines homonginuosly distributed over the site with the specified dimensions. '''
    turbine_pos = []
    for x_r in numpy.linspace(
            config.domain.site_x_start + 0.5 * config.params["turbine_x"],
            config.domain.site_x_end - 0.5 * config.params["turbine_y"], nx):
        for y_r in numpy.linspace(
                config.domain.site_y_start + 0.5 * config.params["turbine_x"],
                config.domain.site_y_end - 0.5 * config.params["turbine_y"],
                ny):
            turbine_pos.append((float(x_r), float(y_r)))
    config.set_turbine_pos(turbine_pos, friction)
    info_blue("Deployed " + str(len(turbine_pos)) + " turbines.")
    return turbine_pos
コード例 #2
0
def print_benchmark_report(solver_timings, failed_solvers):
        # Let's analyse the result of the benchmark test:
        solver_timings = sorted(solver_timings.iteritems(), key=operator.itemgetter(1)) 
        failed_solvers = sorted(failed_solvers.iteritems(), key=operator.itemgetter(1)) 

        dolfin.info_blue("***********************************************") 
        dolfin.info_blue("********** Solver benchmark results: **********")
        dolfin.info_blue("***********************************************") 
        for solver, timing in solver_timings:
            dolfin.info_blue("%s: %.6f s" % (solver, timing))
        for solver, reason in failed_solvers:
            dolfin.info_red("%s: %s" % (solver, reason))
コード例 #3
0
def print_benchmark_report(solver_timings, failed_solvers):
    # Let's analyse the result of the benchmark test:
    solver_timings = sorted(solver_timings.iteritems(),
                            key=operator.itemgetter(1))
    failed_solvers = sorted(failed_solvers.iteritems(),
                            key=operator.itemgetter(1))

    dolfin.info_blue("***********************************************")
    dolfin.info_blue("********** Solver benchmark results: **********")
    dolfin.info_blue("***********************************************")
    for solver, timing in solver_timings:
        dolfin.info_blue("%s: %.6f s" % (solver, timing))
    for solver, reason in failed_solvers:
        dolfin.info_red("%s: %s" % (solver, reason))
コード例 #4
0
    def derivative_action(self, dependencies, values, variable, contraction_vector, hermitian):
        expressions.update_expressions(self.frozen_expressions)
        constant.update_constants(self.frozen_constants)

        if not hermitian:
            if self.solver not in caching.pis_fwd_to_tlm:
                dolfin.info_blue("No TLM solver, creating ... ")
                creation_timer = dolfin.Timer("to_adm")
                if contraction_vector.data is not None:
                    tlm_scheme = self.scheme.to_tlm(contraction_vector.data)
                else:
                    tlm_scheme = self.scheme.to_tlm(dolfin.Function(self.fn_space))

                creation_time = creation_timer.stop()
                dolfin.info_red("TLM creation time: %s" % creation_time)

                tlm_solver = dolfin.PointIntegralSolver(tlm_scheme)
                tlm_solver.parameters.update(self.solver.parameters)
                caching.pis_fwd_to_tlm[self.solver] = tlm_solver
            else:
                tlm_solver = caching.pis_fwd_to_tlm[self.solver]
                tlm_scheme = tlm_solver.scheme()
                if contraction_vector.data is not None:
                    tlm_scheme.contraction.assign(contraction_vector.data)
                else:
                    tlm_scheme.contraction.vector().zero()

            coeffs = [x for x in ufl.algorithms.extract_coefficients(tlm_scheme.rhs_form()) if hasattr(x, 'function_space')]
            for (coeff, value) in zip(coeffs, values):
                coeff.assign(value.data)
            tlm_scheme.t().assign(self.time)

            tlm_solver.step(self.dt)

            return adjlinalg.Vector(tlm_scheme.solution())

        else:
            if self.solver not in caching.pis_fwd_to_adj:
                dolfin.info_blue("No ADM solver, creating ... ")
                creation_timer = dolfin.Timer("to_adm")
                if contraction_vector.data is not None:
                    adm_scheme = self.scheme.to_adm(contraction_vector.data)
                else:
                    adm_scheme = self.scheme.to_adm(dolfin.Function(self.fn_space))
                creation_time = creation_timer.stop()
                dolfin.info_red("ADM creation time: %s" % creation_time)

                adm_solver = dolfin.PointIntegralSolver(adm_scheme)
                adm_solver.parameters.update(self.solver.parameters)
                caching.pis_fwd_to_adj[self.solver] = adm_solver
            else:
                adm_solver = caching.pis_fwd_to_adj[self.solver]
                adm_scheme = adm_solver.scheme()
                if contraction_vector.data is not None:
                    adm_scheme.contraction.assign(contraction_vector.data)
                else:
                    adm_scheme.contraction.vector().zero()

            coeffs = [x for x in ufl.algorithms.extract_coefficients(adm_scheme.rhs_form()) if hasattr(x, 'function_space')]
            for (coeff, value) in zip(coeffs, values):
                coeff.assign(value.data)
            adm_scheme.t().assign(self.time)

            adm_solver.step(self.dt)

            return adjlinalg.Vector(adm_scheme.solution())
コード例 #5
0
def solve(*args, **kwargs):
    ''' This function overwrites the dolfin.solve function but provides additional functionality to benchmark 
        different solver/preconditioner settings. The arguments of equivalent to dolfin.solve except some (optional) additional parameters:
        - benchmark = [True, False]: If True, the problem will be solved with all different solver/precondition combinations and the results reported.
                                     If False, the problem is solved using the default solver settings.
        - solve: An optional function parameter that is called instead of dolfin.solve. This parameter is useful if dolfin.solve is overwritten by a custom solver routine.
        - solver_exclude: A list of solvers that are to be excluded from the benchmark.
        - preconditioner_exclude: A list of preconditioners that are to be excluded from the benchmark.
        - return_best: Option to return the fastest solver result only.

    '''

    # Retrieve the extended benchmark arguments.
    if kwargs.has_key('benchmark'):
        benchmark = kwargs.pop('benchmark')
    else:
        benchmark = False

    if kwargs.has_key('solve'):
        solve = kwargs.pop('solve')
    else:
        solve = dolfin.fem.solving.solve

    if kwargs.has_key('solver_exclude'):
        solver_exclude = kwargs.pop('solver_exclude')
    else:
        solver_exclude = [] 

    if kwargs.has_key('preconditioner_exclude'):
        preconditioner_exclude = kwargs.pop('preconditioner_exclude')
    else:
        preconditioner_exclude = [] 

    if benchmark: 
        dolfin.info_blue("Running solver benchmark...")
        solver_parameters_set = solver_parameters(solver_exclude, preconditioner_exclude)
        solver_timings = {}
        failed_solvers = {}
        ret = None

        # Perform the benchmark
        for parameters in solver_parameters_set:
            solver_failed = False
            # Replace the existing solver setting with the benchmark one's.
            new_args, new_kwargs = replace_solver_settings(args, kwargs, parameters)
##            print "args,", new_args
##            print "kwargs;", new_kwargs

            # Solve the problem
            timer = dolfin.Timer("Solver benchmark")
            timer.start()
            try:
                ret = solve(*new_args)
            except RuntimeError as e:
                if 'diverged' in e.message.lower():
                    failure_reason = 'diverged'
                else:
                    failure_reason = 'unknown'
                pass
            timer.stop()

            #Check to see if the solver returned a zero solution
            if np.all(args[1].array() == 0.0):
                solver_failed = True
                failure_reason = 'Zero Solution'

            # Save the result
            parameters_str = parameters["linear_solver"] + ", " + parameters["preconditioner"]
            if solver_failed:
                if not kwargs.has_key("return_best"):
                    dolfin.info_red(parameters_str + ": solver failed.")
                failed_solvers[parameters_str] = failure_reason 
            else:
               # print parameters_str
                if not kwargs.has_key("return_best"):
                    dolfin.info(parameters_str + ": " + str(timer.value()) + "s.")
                solver_timings[parameters_str] = timer.value() 

        # Print the report
        if kwargs.has_key("return_best"):
            sortedtimings = sorted(solver_timings.iteritems(), key=operator.itemgetter(1))
            ret = {k[0]:solver_timings[k[0]] for k in sortedtimings[:int(kwargs["return_best"])]}
            print_benchmark_report(ret,{})
        else:
            print_benchmark_report(solver_timings, failed_solvers) 

    else:
        ret = solve(*args)
    return ret
コード例 #6
0
 def info_blue(self, message, values, log_keys, time=None):
     info_blue(message % values)
     self._log_data(values, log_keys, time)
コード例 #7
0
ファイル: gen_plots.py プロジェクト: BijanZarif/CBC.Solve
RUNTIMEPATH = "runtimedata.py"
CONVPLOTPATH = "../tests/test_analytic_plot.py"


if __name__ == "__main__":
    #Allow for a user defined start and stop point
    if len(sys.argv) > 1:
        start = sys.argv[1]
        stop = sys.argv[2]

    for elem_order in elem_orders:
        for bctype in bctypes:
            for argument in arguments:
                
                case = "%s %s %s %s %s"%(argument,elem_order,bctype,start,stop)
                info_blue("Generating data for %s"%case)
                info_blue("")
                
                #Plot the runtimedata
                for i in range(int(start),int(stop) + 1):
                    datapath = "../results/convergence/%sdegree%s/%sdata/refinement%i"%(bctype,elem_order,argument,i)    
                    try:
                        os.system("python %s %s"%(RUNTIMEPATH,datapath))
                        info_blue("Runtime data generated!")
                    except:
                        info_blue("Error, couldn't generate the runtimedata of %s"%datapath)
                #Plot the convergence data
                try:
                    os.system("python %s %s"%(CONVPLOTPATH,case))
                    info_blue("Plot data generated!")
                    info_blue("")
コード例 #8
0
def solve(*args, **kwargs):
    ''' This function overwrites the dolfin.solve function but provides additional functionality to benchmark 
        different solver/preconditioner settings. The arguments of equivalent to dolfin.solve except some (optional) additional parameters:
        - benchmark = [True, False]: If True, the problem will be solved with all different solver/precondition combinations and the results reported.
                                     If False, the problem is solved using the default solver settings.
        - solve: An optional function parameter that is called instead of dolfin.solve. This parameter is useful if dolfin.solve is overwritten by a custom solver routine.
        - solver_exclude: A list of solvers that are to be excluded from the benchmark.
        - preconditioner_exclude: A list of preconditioners that are to be excluded from the benchmark.
        - return_best: Option to return the fastest solver result only.

    '''

    # Retrieve the extended benchmark arguments.
    if kwargs.has_key('benchmark'):
        benchmark = kwargs.pop('benchmark')
    else:
        benchmark = False

    if kwargs.has_key('solve'):
        solve = kwargs.pop('solve')
    else:
        solve = dolfin.fem.solving.solve

    if kwargs.has_key('solver_exclude'):
        solver_exclude = kwargs.pop('solver_exclude')
    else:
        solver_exclude = []

    if kwargs.has_key('preconditioner_exclude'):
        preconditioner_exclude = kwargs.pop('preconditioner_exclude')
    else:
        preconditioner_exclude = []

    if benchmark:
        dolfin.info_blue("Running solver benchmark...")
        solver_parameters_set = solver_parameters(solver_exclude,
                                                  preconditioner_exclude)
        solver_timings = {}
        failed_solvers = {}
        ret = None

        # Perform the benchmark
        for parameters in solver_parameters_set:
            solver_failed = False
            # Replace the existing solver setting with the benchmark one's.
            new_args, new_kwargs = replace_solver_settings(
                args, kwargs, parameters)
            ##            print "args,", new_args
            ##            print "kwargs;", new_kwargs

            # Solve the problem
            timer = dolfin.Timer("Solver benchmark")
            timer.start()
            try:
                ret = solve(*new_args)
            except RuntimeError as e:
                if 'diverged' in e.message.lower():
                    failure_reason = 'diverged'
                else:
                    failure_reason = 'unknown'
                pass
            timer.stop()

            #Check to see if the solver returned a zero solution
            if np.all(args[1].array() == 0.0):
                solver_failed = True
                failure_reason = 'Zero Solution'

            # Save the result
            parameters_str = parameters["linear_solver"] + ", " + parameters[
                "preconditioner"]
            if solver_failed:
                if not kwargs.has_key("return_best"):
                    dolfin.info_red(parameters_str + ": solver failed.")
                failed_solvers[parameters_str] = failure_reason
            else:
                # print parameters_str
                if not kwargs.has_key("return_best"):
                    dolfin.info(parameters_str + ": " + str(timer.value()) +
                                "s.")
                solver_timings[parameters_str] = timer.value()

        # Print the report
        if kwargs.has_key("return_best"):
            sortedtimings = sorted(solver_timings.iteritems(),
                                   key=operator.itemgetter(1))
            ret = {
                k[0]: solver_timings[k[0]]
                for k in sortedtimings[:int(kwargs["return_best"])]
            }
            print_benchmark_report(ret, {})
        else:
            print_benchmark_report(solver_timings, failed_solvers)

    else:
        ret = solve(*args)
    return ret
コード例 #9
0
        def derivative_action(self, dependencies, values, variable, contraction_vector, hermitian):
            expressions.update_expressions(self.frozen_expressions)
            constant.update_constants(self.frozen_constants)

            if not hermitian:
                if self.solver not in caching.pis_fwd_to_tlm:
                    dolfin.info_blue("No TLM solver, creating ... ")
                    creation_timer = dolfin.Timer("to_adm")
                    if contraction_vector.data is not None:
                        tlm_scheme = self.scheme.to_tlm(contraction_vector.data)
                    else:
                        tlm_scheme = self.scheme.to_tlm(dolfin.Function(self.fn_space))

                    creation_time = creation_timer.stop()
                    dolfin.info_red("TLM creation time: %s" % creation_time)

                    tlm_solver = dolfin.PointIntegralSolver(tlm_scheme)
                    tlm_solver.parameters.update(self.solver.parameters)
                    caching.pis_fwd_to_tlm[self.solver] = tlm_solver
                else:
                    tlm_solver = caching.pis_fwd_to_tlm[self.solver]
                    tlm_scheme = tlm_solver.scheme()
                    if contraction_vector.data is not None:
                        tlm_scheme.contraction.assign(contraction_vector.data)
                    else:
                        tlm_scheme.contraction.vector().zero()

                coeffs = [
                    x
                    for x in ufl.algorithms.extract_coefficients(tlm_scheme.rhs_form())
                    if hasattr(x, "function_space")
                ]
                for (coeff, value) in zip(coeffs, values):
                    coeff.assign(value.data)
                tlm_scheme.t().assign(self.time)

                tlm_solver.step(self.dt)

                return adjlinalg.Vector(tlm_scheme.solution())

            else:
                if self.solver not in caching.pis_fwd_to_adj:
                    dolfin.info_blue("No ADM solver, creating ... ")
                    creation_timer = dolfin.Timer("to_adm")
                    if contraction_vector.data is not None:
                        adm_scheme = self.scheme.to_adm(contraction_vector.data)
                    else:
                        adm_scheme = self.scheme.to_adm(dolfin.Function(self.fn_space))
                    creation_time = creation_timer.stop()
                    dolfin.info_red("ADM creation time: %s" % creation_time)

                    adm_solver = dolfin.PointIntegralSolver(adm_scheme)
                    adm_solver.parameters.update(self.solver.parameters)
                    caching.pis_fwd_to_adj[self.solver] = adm_solver
                else:
                    adm_solver = caching.pis_fwd_to_adj[self.solver]
                    adm_scheme = adm_solver.scheme()
                    if contraction_vector.data is not None:
                        adm_scheme.contraction.assign(contraction_vector.data)
                    else:
                        adm_scheme.contraction.vector().zero()

                coeffs = [
                    x
                    for x in ufl.algorithms.extract_coefficients(adm_scheme.rhs_form())
                    if hasattr(x, "function_space")
                ]
                for (coeff, value) in zip(coeffs, values):
                    coeff.assign(value.data)
                adm_scheme.t().assign(self.time)

                adm_solver.step(self.dt)

                return adjlinalg.Vector(adm_scheme.solution())
コード例 #10
0
    def __init__(self, turbine, flow):
        # add radius to model params
        if model_parameters is None:
            model_parameters = {"radius": turbine_radius}
        else:
            model_parameters.update({"radius": turbine_radius})
        # check if gradient required
        if "compute_gradient" in model_parameters:
            compute_gradient = model_parameters["compute_gradient"]
        else:
            compute_gradient = True
        # check if a wake and wake gradients are provided
        if "wake" in model_parameters:
            if "wake_gradients" in model_parameters:
                gradients = model_parameters["wake_gradients"]
            else:
                gradients = None
            self.wake = ADDolfinExpression(model_parameters["wake"],
                                           compute_gradient=compute_gradient,
                                           gradients=gradients)
        # compute wake and gradients
        else:
            # mimic a SteadyConfiguration but change a few things along the way
            config = otf.DefaultConfiguration()
            config.params['steady_state'] = True
            config.params[
                'initial_condition'] = otf.ConstantFlowInitialCondition(config)
            config.params['include_advection'] = True
            config.params['include_diffusion'] = True
            config.params['diffusion_coef'] = 3.0
            config.params['quadratic_friction'] = True
            config.params['newton_solver'] = True
            config.params['friction'] = dolfin.Constant(0.0025)
            config.params['theta'] = 1.0
            config.params["dump_period"] = 0

            xmin, ymin = -100, -200
            xsize, ysize = 1000, 400
            xcells, ycells = 400, 160
            mesh = dolfin.RectangleMesh(xmin, ymin, xmin + xsize, ymin + ysize,
                                        xcells, ycells)

            V, H = config.finite_element(mesh)
            config.function_space = dolfin.MixedFunctionSpace([V, H])
            config.turbine_function_space = dolfin.FunctionSpace(mesh, 'CG', 2)

            class Domain(object):
                """
                Domain object used for setting boundary conditions etc later on
                """
                def __init__(self, mesh):
                    class InFlow(dolfin.SubDomain):
                        def inside(self, x, on_boundary):
                            return dolfin.near(x[0], -100)

                    class OutFlow(dolfin.SubDomain):
                        def inside(self, x, on_boundary):
                            return dolfin.near(x[0], 900)

                    inflow = InFlow()
                    outflow = OutFlow()

                    self.mesh = mesh
                    self.boundaries = dolfin.FacetFunction("size_t", mesh)
                    self.boundaries.set_all(0)
                    inflow.mark(self.boundaries, 1)
                    outflow.mark(self.boundaries, 2)

                    self.ds = dolfin.Measure('ds')[self.boundaries]

            config.domain = Domain(mesh)
            config.set_domain(config.domain, warning=False)

            # Boundary conditions
            bc = otf.DirichletBCSet(config)
            bc.add_constant_flow(1, 1.0 + 1e-10)
            bc.add_zero_eta(2)
            config.params['bctype'] = 'strong_dirichlet'
            config.params['strong_bc'] = bc
            config.params['free_slip_on_sides'] = True

            # Optimisation settings
            config.params['functional_final_time_only'] = True
            config.params['automatic_scaling'] = False

            # Turbine settings
            config.params['turbine_pos'] = []
            config.params['turbine_friction'] = []
            config.params['turbine_x'] = turbine_radius * 2
            config.params['turbine_y'] = turbine_radius * 2
            config.params['controls'] = ['turbine_pos']

            # Finally set some DOLFIN optimisation flags
            dolfin.parameters['form_compiler']['cpp_optimize'] = True
            dolfin.parameters['form_compiler']['cpp_optimize_flags'] = '-O3'
            dolfin.parameters['form_compiler']['optimize'] = True

            # place a turbine with default friction
            turbine = [(0., 0.)]
            config.set_turbine_pos(turbine)

            # solve the shallow water equations
            rf = otf.ReducedFunctional(config, plot=False)
            dolfin.info_blue("Generating the wake model...")
            rf.j(rf.initial_control())
            # get state
            state = rf.last_state
            V = dolfin.VectorFunctionSpace(config.function_space.mesh(),
                                           "CG",
                                           2,
                                           dim=2)
            u_out = dolfin.TrialFunction(V)
            v_out = dolfin.TestFunction(V)
            M_out = dolfin_adjoint.assemble(
                dolfin.inner(v_out, u_out) * dolfin.dx)
            out_state = dolfin.Function(V)
            rhs = dolfin_adjoint.assemble(
                dolfin.inner(v_out,
                             state.split()[0]) * dolfin.dx)
            dolfin_adjoint.solve(M_out,
                                 out_state.vector(),
                                 rhs,
                                 "cg",
                                 "sor",
                                 annotate=False)
            dolfin.info_green("Wake model generated.")
            self.wake = ADDolfinExpression(out_state.split()[0],
                                           compute_gradient)

        super(ApproximateShallowWater,
              self).__init__("ApproximateShallowWater", flow_field,
                             model_parameters)
コード例 #11
0
ファイル: gen_plots.py プロジェクト: bonh/CBC.Solve
CONVPLOTPATH = "../tests/test_analytic_plot.py"

if __name__ == "__main__":
    #Allow for a user defined start and stop point
    if len(sys.argv) > 1:
        start = sys.argv[1]
        stop = sys.argv[2]

    for elem_order in elem_orders:
        for bctype in bctypes:
            for argument in arguments:

                case = "%s %s %s %s %s" % (argument, elem_order, bctype, start,
                                           stop)
                info_blue("Generating data for %s" % case)
                info_blue("")

                #Plot the runtimedata
                for i in range(int(start), int(stop) + 1):
                    datapath = "../results/convergence/%sdegree%s/%sdata/refinement%i" % (
                        bctype, elem_order, argument, i)
                    try:
                        os.system("python %s %s" % (RUNTIMEPATH, datapath))
                        info_blue("Runtime data generated!")
                    except:
                        info_blue(
                            "Error, couldn't generate the runtimedata of %s" %
                            datapath)
                #Plot the convergence data
                try:
                    os.system("python %s %s" % (CONVPLOTPATH, case))
コード例 #12
0
def solve(*args, **kwargs):
    ''' This function overwrites the dolfin.solve function but provides additional functionality to benchmark 
        different solver/preconditioner settings. The arguments of equivalent to dolfin.solve except some (optional) additional parameters:
        - benchmark = [True, False]: If True, the problem will be solved with all different solver/precondition combinations and the results reported.
                                     If False, the problem is solved using the default solver settings.
        - solve: An optional function parameter that is called instead of dolfin.solve. This parameter is useful if dolfin.solve is overwritten by a custom solver routine.
        - solver_exclude: A list of solvers that are to be excluded from the benchmark.
        - preconditioner_exclude: A list of preconditioners that are to be excluded from the benchmark.

    '''

    # Retrieve the extended benchmark arguments.
    if kwargs.has_key('benchmark'):
        benchmark = kwargs.pop('benchmark')
    else:
        benchmark = False

    if kwargs.has_key('solve'):
        solve = kwargs.pop('solve')
    else:
        solve = dolfin.fem.solving.solve

    if kwargs.has_key('solver_exclude'):
        solver_exclude = kwargs.pop('solver_exclude')
    else:
        solver_exclude = []

    if kwargs.has_key('preconditioner_exclude'):
        preconditioner_exclude = kwargs.pop('preconditioner_exclude')
    else:
        preconditioner_exclude = []

    if benchmark:
        dolfin.info_blue("Running solver benchmark...")
        solver_parameters_set = solver_parameters(solver_exclude,
                                                  preconditioner_exclude)
        solver_timings = {}
        failed_solvers = {}
        ret = None

        # Perform the benchmark
        for parameters in solver_parameters_set:
            solver_failed = False
            # Replace the existing solver setting with the benchmark one's.
            new_args, new_kwargs = replace_solver_settings(
                args, kwargs, parameters)

            # Solve the problem
            timer = dolfin.Timer("Solver benchmark")
            timer.start()
            try:
                ret = solve(*new_args, **new_kwargs)
            except RuntimeError as e:
                solver_failed = True
                if 'diverged' in e.message.lower():
                    failure_reason = 'diverged'
                else:
                    failure_reason = 'unknown'
                    from IPython.Shell import IPShellEmbed
                    ipshell = IPShellEmbed()
                    ipshell()
                pass
            timer.stop()

            # Save the result
            parameters_str = parameters["linear_solver"] + ", " + parameters[
                "preconditioner"]
            if solver_failed:
                dolfin.info_red(parameters_str + ": solver failed.")
                failed_solvers[parameters_str] = failure_reason
            else:
                dolfin.info(parameters_str + ": " + str(timer.value()) + "s.")
                solver_timings[parameters_str] = timer.value()

        # Print the report
        print_benchmark_report(solver_timings, failed_solvers)

    else:
        ret = solve(*args, **kwargs)
    return ret
コード例 #13
0
ファイル: helpers.py プロジェクト: pefarrell/OpenTidalFarm
def info_blue(*args, **kwargs):
    if MPI.process_number() == 0:
        dolfin.info_blue(*args, **kwargs)
コード例 #14
0
ファイル: helpers.py プロジェクト: dmculley/OpenTidalFarm
def info_blue(*args, **kwargs):
    if MPI.process_number() == 0:
        dolfin.info_blue(*args, **kwargs)
コード例 #15
0
ファイル: helpers.py プロジェクト: khairy/OpenTidalFarm
def info_blue(*args, **kwargs):
    if get_rank() == 0:
        dolfin.info_blue(*args, **kwargs)
コード例 #16
0
def solve(*args, **kwargs):
    ''' This function overwrites the dolfin.solve function but provides additional functionality to benchmark
        different solver/preconditioner settings. The arguments of equivalent to dolfin.solve except some (optional) additional parameters:
        - benchmark = [True, False]: If True, the problem will be solved with all different solver/precondition combinations and the results reported.
                                     If False, the problem is solved using the default solver settings.
        - solve: An optional function parameter that is called instead of dolfin.solve. This parameter is useful if dolfin.solve is overwritten by a custom solver routine.
        - solver_exclude: A list of solvers that are to be excluded from the benchmark.
        - preconditioner_exclude: A list of preconditioners that are to be excluded from the benchmark.

    '''

    # Retrieve the extended benchmark arguments.
    if 'benchmark' in kwargs:
        benchmark = kwargs.pop('benchmark')
    else:
        benchmark = False

    if 'solve' in kwargs:
        solve = kwargs.pop('solve')
    else:
        solve = dolfin.fem.solving.solve

    if 'solver_exclude' in kwargs:
        solver_exclude = kwargs.pop('solver_exclude')
    else:
        solver_exclude = []

    if 'preconditioner_exclude' in kwargs:
        preconditioner_exclude = kwargs.pop('preconditioner_exclude')
    else:
        preconditioner_exclude = []

    if benchmark:
        dolfin.info_blue("Running solver benchmark...")
        solver_parameters_set = solver_parameters(solver_exclude, preconditioner_exclude)
        solver_timings = {}
        failed_solvers = {}
        ret = None

        # Perform the benchmark
        for parameters in solver_parameters_set:
            solver_failed = False
            # Replace the existing solver setting with the benchmark one's.
            new_args, new_kwargs = replace_solver_settings(args, kwargs, parameters)

            # Solve the problem
            timer = dolfin.Timer("Solver benchmark")
            timer.start()
            try:
                ret = solve(*new_args, **new_kwargs)
            except RuntimeError as e:
                solver_failed = True
                if 'diverged' in e.message.lower():
                    failure_reason = 'diverged'
                else:
                    failure_reason = 'unknown'
                    from IPython.Shell import IPShellEmbed
                    ipshell = IPShellEmbed()
                    ipshell()
                pass
            timer.stop()

            # Save the result
            parameters_str = parameters["linear_solver"] + ", " + parameters["preconditioner"]
            if solver_failed:
                dolfin.info_red(parameters_str + ": solver failed.")
                failed_solvers[parameters_str] = failure_reason
            else:
                dolfin.info(parameters_str + ": " + str(timer.value()) + "s.")
                solver_timings[parameters_str] = timer.value()

        # Print the report
        print_benchmark_report(solver_timings, failed_solvers)

    else:
        ret = solve(*args, **kwargs)
    return ret