Ejemplo n.º 1
0
    def _simul_coloring(prob):
        if options.outfile is None:
            outfile = sys.stdout
        else:
            outfile = open(options.outfile, 'w')
        if prob.model._use_derivatives:
            Problem._post_setup_func = None  # avoid recursive loop

            with profiling('coloring_profile.out'
                           ) if options.profile else do_nothing_context():
                color_info = get_simul_meta(
                    prob,
                    repeats=options.num_jacs,
                    tol=options.tolerance,
                    show_jac=options.show_jac,
                    include_sparsity=not options.no_sparsity,
                    setup=False,
                    run_model=True,
                    stream=outfile)

            if sys.stdout.isatty():
                simul_coloring_summary(color_info, stream=sys.stdout)
        else:
            print(
                "Derivatives are turned off.  Cannot compute simul coloring.")
        exit()
Ejemplo n.º 2
0
    def _simul_coloring(prob):
        if options.outfile is None:
            outfile = sys.stdout
        else:
            outfile = open(options.outfile, 'w')
        if prob.model._use_derivatives:
            Problem._post_setup_func = None  # avoid recursive loop

            with profiling('coloring_profile.out') if options.profile else do_nothing_context():
                color_info = get_simul_meta(prob,
                                            repeats=options.num_jacs, tol=options.tolerance,
                                            show_jac=options.show_jac,
                                            include_sparsity=not options.no_sparsity,
                                            setup=False, run_model=True,
                                            stream=outfile)

            if sys.stdout.isatty():
                simul_coloring_summary(color_info, stream=sys.stdout)
        else:
            print("Derivatives are turned off.  Cannot compute simul coloring.")
        exit()
Ejemplo n.º 3
0
    def _inverse(self):
        """
        Return the inverse Jacobian.

        This is only used by the Broyden solver when calculating a full model Jacobian. Since it
        is only done for a single RHS, no need for LU.

        Returns
        -------
        ndarray
            Inverse Jacobian.
        """
        system = self._system
        iproc = system.comm.rank
        nproc = system.comm.size

        if self._assembled_jac is not None:

            with multi_proc_exception_check(
                    system.comm) if nproc > 1 else do_nothing_context():

                if nproc == 1:
                    matrix = self._assembled_jac._int_mtx._matrix
                else:
                    matrix = self._assembled_jac._int_mtx._get_assembled_matrix(
                        system)
                    if self._owned_size_totals is None:
                        self._owned_size_totals = np.sum(system._owned_sizes,
                                                         axis=1)

                if matrix is None:
                    # This happens if we're not rank 0
                    sz = np.sum(system._owned_sizes)
                    inv_jac = np.zeros((sz, sz))

                # Dense and Sparse matrices have their own inverse method.
                elif isinstance(matrix, np.ndarray):
                    # Detect singularities and warn user.
                    with warnings.catch_warnings():
                        if self.options['err_on_singular']:
                            warnings.simplefilter('error', RuntimeWarning)
                        try:
                            inv_jac = scipy.linalg.inv(matrix)
                        except RuntimeWarning as err:
                            raise RuntimeError(
                                format_singular_error(err, system, matrix))

                        # NaN in matrix.
                        except ValueError as err:
                            raise RuntimeError(format_nan_error(
                                system, matrix))

                elif isinstance(matrix, csc_matrix):
                    try:
                        inv_jac = scipy.sparse.linalg.inv(matrix)
                    except RuntimeError as err:
                        if 'exactly singular' in str(err):
                            raise RuntimeError(
                                format_singular_csc_error(system, matrix))
                        else:
                            reraise(*sys.exc_info())
                else:
                    raise RuntimeError(
                        "Direct solver not implemented for matrix type %s"
                        " in %s." % (type(matrix), system.msginfo))

        else:
            mtx = self._build_mtx()

            # During inversion detect singularities and warn user.
            with warnings.catch_warnings():

                if self.options['err_on_singular']:
                    warnings.simplefilter('error', RuntimeWarning)

                try:
                    inv_jac = scipy.linalg.inv(mtx)

                except RuntimeWarning as err:
                    raise RuntimeError(format_singular_error(err, system, mtx))

                # NaN in matrix.
                except ValueError as err:
                    raise RuntimeError(format_nan_error(system, mtx))

        return inv_jac
Ejemplo n.º 4
0
    def _linearize(self):
        """
        Perform factorization.
        """
        system = self._system
        nproc = system.comm.size

        if self._assembled_jac is not None:

            with multi_proc_exception_check(
                    system.comm) if nproc > 1 else do_nothing_context():
                if nproc == 1:
                    matrix = self._assembled_jac._int_mtx._matrix
                else:
                    matrix = self._assembled_jac._int_mtx._get_assembled_matrix(
                        system)
                    if self._owned_size_totals is None:
                        self._owned_size_totals = np.sum(system._owned_sizes,
                                                         axis=1)

                if matrix is None:
                    # this happens if we're not rank 0
                    self._lu = self._lup = None
                    self._nodup_size = np.sum(system._owned_sizes)

                # Perform dense or sparse lu factorization.
                elif isinstance(matrix, csc_matrix):
                    try:
                        self._lu = scipy.sparse.linalg.splu(matrix)
                        self._nodup_size = matrix.shape[1]
                    except RuntimeError as err:
                        if 'exactly singular' in str(err):
                            raise RuntimeError(
                                format_singular_csc_error(system, matrix))
                        else:
                            reraise(*sys.exc_info())

                elif isinstance(matrix, np.ndarray):  # dense
                    # During LU decomposition, detect singularities and warn user.
                    with warnings.catch_warnings():
                        if self.options['err_on_singular']:
                            warnings.simplefilter('error', RuntimeWarning)
                        try:
                            self._lup = scipy.linalg.lu_factor(matrix)
                            self._nodup_size = matrix.shape[1]
                        except RuntimeWarning as err:
                            raise RuntimeError(
                                format_singular_error(err, system, matrix))

                        # NaN in matrix.
                        except ValueError as err:
                            raise RuntimeError(format_nan_error(
                                system, matrix))

                # Note: calling scipy.sparse.linalg.splu on a COO actually transposes
                # the matrix during conversion to csc prior to LU decomp, so we can't use COO.
                else:
                    raise RuntimeError(
                        "Direct solver not implemented for matrix type %s"
                        " in %s." %
                        (type(self._assembled_jac._int_mtx), system.msginfo))
        else:
            if nproc > 1:
                raise RuntimeError(
                    "DirectSolvers without an assembled jacobian are not supported "
                    "when running under MPI if comm.size > 1.")

            mtx = self._build_mtx()
            self._nodup_size = mtx.shape[1]

            # During LU decomposition, detect singularities and warn user.
            with warnings.catch_warnings():

                if self.options['err_on_singular']:
                    warnings.simplefilter('error', RuntimeWarning)

                try:
                    self._lup = scipy.linalg.lu_factor(mtx)

                except RuntimeWarning as err:
                    raise RuntimeError(format_singular_error(err, system, mtx))

                # NaN in matrix.
                except ValueError as err:
                    raise RuntimeError(format_nan_error(system, mtx))