Пример #1
0
 def __str__(self):
     if self._strings['rhs_wrt_time'] is not None:
         _outstr = r"u'(t,\phi(t))=%s" % self._strings['rhs_wrt_time']
     else:
         _outstr = r"%s" % class_name(self)
     _outstr += r", DOFs={:s}".format(self.dim)
     return _outstr
Пример #2
0
    def __init__(self, *args, **kwargs):
        """
        Parameters
        ----------
        exact_function : :py:class:`callable`
            *(optional)*
            If given initializes the problem with the exact solution function.
        """
        assert_is_instance(
            self,
            IProblem,
            descriptor="Problem needs to be a IProblem first: NOT %s" % class_name(self),
            checking_obj=self,
        )
        self._exact_function = None
        if "exact_function" in kwargs:
            self.exact_function = kwargs["exact_function"]

        self._strings["exact"] = None
        if "strings" in kwargs:
            if "exact" in kwargs["strings"]:
                assert_is_instance(
                    kwargs["strings"]["exact"],
                    str,
                    descriptor="String representation of Exact Function",
                    checking_obj=self,
                )
                self._strings["exact"] = kwargs["strings"]["exact"]
Пример #3
0
 def definalize(self):
     if self._finalized:
         self._solution = self.solution.__class__()
         self._finalized = False
         self.reset_to_start()
     else:
         LOG.debug("This {} wasn't finalized.".format(class_name(self)))
Пример #4
0
 def finalize(self):
     assert_condition(not self.finalized, RuntimeError,
                      message="This {} is already done.".format(class_name(self)),
                      checking_obj=self)
     self._solution = self.finest_level.solution
     self._current_index = 0
     self._finalized = True
Пример #5
0
 def __eq__(self, other):
     assert_condition(isinstance(other, self.__class__), TypeError,
                      message="Can not compare {} with {}".format(self.__class__, class_name(other)),
                      checking_obj=self)
     return (
         self.numeric_type == other.numeric_type
         and np.array_equal(self.value, other.value)
     )
Пример #6
0
 def print_lines_for_log(self):
     _lines = {
         'Type': class_name(self)
     }
     if self._nodes is not None:
         _lines['Nodes'] = self._nodes.print_lines_for_log()
     if self._weights_function is not None:
         _lines['Weight Function'] = self._weights_function.print_lines_for_log()
     return _lines
Пример #7
0
 def __lt__(self, other):
     assert_is_instance(other, StepSolutionData,
                        message="Can not compare StepSolutionData with {}".format(class_name(other)),
                        checking_obj=self)
     return (
         self.dim == other.dim
         and self.numeric_type == other.numeric_type
         and self.time_point < other.time_point
     )
Пример #8
0
 def __contains__(self, item):
     assert_condition(
         isinstance(item, StepSolutionData),
         TypeError,
         message="Item must be a StepSolutionData: NOT {}".format(class_name(item)),
         checking_obj=self,
     )
     for elem in self._data:
         if elem == item:
             return True
     return False
Пример #9
0
 def __eq__(self, other):
     assert_is_instance(other, StepSolutionData,
                        message="Can not compare StepSolutionData with {}".format(class_name(other)),
                        checking_obj=self)
     return (
         self.time_point == other.time_point
         and self.dim == other.dim
         and self.numeric_type == other.numeric_type
         and np.array_equal(self.value, other.value)
         and self.error == other.error
         and self.residual == other.residual
     )
Пример #10
0
    def finalize(self):
        """Finalizes the whole solver state.

        This copies the :py:class:`.TrajectorySolutionData` objects from the :py:class:`.IIterationState` instances of
        this sequence to the main :py:class:`.IterativeSolution` object and finalizes it.
        """
        assert_condition(not self.finalized, RuntimeError,
                         message="This {} is already done.".format(class_name(self)),
                         checking_obj=self)
        for _iter in self:
            self.solution.add_solution(_iter.solution)
        # self.solution.finalize()
        self._current_index = 0
Пример #11
0
    def proceed(self):
        """Proceed :py:attr:`.current` to the next state in the sequence

        Raises
        ------
        RuntimeError
            if this sequence has already been finalized via :py:meth:`.IStateIterator.finalize`
        """
        assert_condition(not self.finalized, RuntimeError,
                         message="This {} is already done.".format(class_name(self)),
                         checking_obj=self)
        if self.next_index is not None:
            self._current_index += 1
        else:
            raise StopIteration("No further states available.")
Пример #12
0
    def finalize(self):
        """Finalize this sequence of states

        This copies the solution data from all containing states to its own solution object and finalizes it.
        As well, the :py:attr:`.current_index` is reset to zero.

        Raises
        ------
        RuntimeError
            if this state has already been finalized
        """
        assert_condition(not self.finalized, RuntimeError,
                         message="This {} is already done.".format(class_name(self)),
                         checking_obj=self)
        for _state in self:
            self.solution.add_solution_data(deepcopy(_state.solution))
        self.solution.finalize()
        self._current_index = 0
        self._finalized = True
Пример #13
0
    def run(self, core, **kwargs):
        """Applies this solver.

        Parameters
        ----------
        solution_type : :py:class:`tuple` of two :py:class:`class`
            Tuple of two classes specifying the solution type and underlying solution storage data type.
            The first item must be a class derived off :py:class:`.ISolution` and the second a class derived
            off :py:class:`.ISolutionData`.

        Returns
        -------
        solution : :py:class:`.ISolution`
            The solution of the problem.
        """
        assert_condition(issubclass(core, ISolverCore),
                         ValueError, message="The given solver core class must be valid: NOT {:s}"
                                             .format(class_name(core)),
                         checking_obj=self)
        self._core = core()
Пример #14
0
    def finalize(self):
        """Finalizes this iteration and copies solutions

        The solutions of all steps of all time steps are copied to this sequence's :py:class:`.TrajectorySolutionData`
        and is finalized afterwards.

        The remaining behaviour is the same as the overridden method.

        See Also
        --------
        :py:meth:`.IStateIterator.finalize` : overridden method
        """
        assert_condition(not self.finalized, RuntimeError,
                         message="This {} is already done.".format(class_name(self)),
                         checking_obj=self)
        for _time_step in self:
            for _step in _time_step:
                self.solution.add_solution_data(deepcopy(_step.solution))
        self.solution.finalize()
        self._current_index = 0
        self._finalized = True
Пример #15
0
    def direct_implicit(self, *args, **kwargs):
        """Direct Implicit Formula for :math:`u'(t, \\phi_t) &= \\lambda u(t, \\phi_t)`
        """
        assert_is_instance(self.lmbda, complex,
                           message="Direct implicit formula only valid for imaginay lambda: NOT %s"
                                   % class_name(self.lmbda),
                           checking_obj=self)

        assert_named_argument('phis_of_time', kwargs, checking_obj=self)
        assert_named_argument('delta_node', kwargs, checking_obj=self)
        assert_named_argument('integral', kwargs, checking_obj=self)

        _phis = kwargs["phis_of_time"]
        assert_is_instance(_phis, list, message="Direct implicit formula needs multiple phis.", checking_obj=self)
        assert_condition(len(_phis) == 3, ValueError, message="Need exactly three different phis.", checking_obj=self)

        # _phis[0] : previous iteration -> previous step
        # _phis[1] : previous iteration -> current step
        # _phis[2] : current iteration -> previous step

        _dn = kwargs["delta_node"]
        # TODO: make this numerics check more advanced (better warning for critical numerics)
        assert_condition(_dn * self.lmbda.real != 1.0,
                         ArithmeticError, "Direct implicit formula for lambda={:f} and dn={:f} not valid. "
                                          .format(self.lmbda, _dn) + "Try implicit solver.",
                         self)
        _int = kwargs["integral"]

        if 'core' in kwargs and isinstance(kwargs['core'], ImplicitSdcCore):
            return (_phis[2] - _dn * self.lmbda * _phis[1] + _int) / (1 - self.lmbda * _dn)
        else:
            return \
                (_phis[2]
                 + _dn * (complex(0, self.lmbda.imag) * (_phis[2] - _phis[0]) - self.lmbda.real * _phis[1])
                 + _int) \
                / (1 - self.lmbda.real * _dn)
Пример #16
0
 def __str__(self):
     return "{:s}: {}".format(class_name(self), self._data)
Пример #17
0
 def __str__(self):
     _states = [state.__str__() for state in self._states]
     return "{}({}, solution={}, _states={})".format(class_name(self), self._element_type.__name__,
                                                     self.solution.__str__(), _states.__str__())
Пример #18
0
 def print_lines_for_log(self):
     _lines = {
         'Type': class_name(self)
     }
     return _lines
Пример #19
0
 def __str__(self):
     return "{}(solution={})".format(class_name(self), self.solution)
Пример #20
0
 def __ne__(self, other):
     assert_is_instance(other, StepSolutionData,
                        message="Can not compare StepSolutionData with {}".format(class_name(other)),
                        checking_obj=self)
     return not self.__eq__(other)
Пример #21
0
    def transform(self, interval):
        """Transforms computed integration nodes to fit a new given interval.

        Based on the old interval the computed integration nodes are transformed fitting the newly given interval using
        standard linear interval scaling.
        In case no interval was previously given, the standard interval of the used nodes method, e.g. :math:`[-1, 1]`
        for Gauss-Lobatto, is used.

        Parameters
        ----------
        interval : :py:class:`numpy.ndarray(size=2)`
            New interval to transform nodes onto.

        Raises
        ------
        ValueError
            If the standard interval is not suited for transformation, i.e. it is not a :py:class:`numpy.ndarray` of
            size 2 and not positive.

        Notes
        -----
        It may be this transformation is numerically inconvenient because of the loss of significance.
        """
        assert_is_instance(interval, np.ndarray, descriptor="Interval", checking_obj=self)
        assert_condition(interval.size == 2,
                         ValueError,
                         message="Intervals must be of size 2: {} ({:s})".format(interval, class_name(interval)),
                         checking_obj=self)
        assert_condition(interval[0] < interval[1],
                         ValueError,
                         message="Interval must be positive: {:.2f} > {:.2f}".format(interval[0], interval[1]),
                         checking_obj=self)
        _old_interval = self.interval
        self._interval = interval
        self._nodes = (self.nodes - _old_interval[0]) * (interval[1] - interval[0]) / \
                      (_old_interval[1] - _old_interval[0]) + interval[0]
        assert_condition(self._nodes[0] - self._interval[0] <= 1e-16 and self._nodes[-1] - self._interval[1] <= 1e-16,
                         RuntimeError,
                         message="Newly computed nodes do not match new interval: {} NOT IN {}"
                                 .format(self._nodes, self._interval),
                         checking_obj=self)
        LOG.debug("Nodes: %s" % self._nodes.tolist())
Пример #22
0
 def __ne__(self, other):
     assert_condition(isinstance(other, self.__class__), TypeError,
                      message="Can not compare {} with {}".format(self.__class__, class_name(other)),
                      checking_obj=self)
     return not self.__eq__(other)
Пример #23
0
 def __init__(self, *args, **kwargs):
     assert_is_instance(self, IProblem, descriptor="Problem needs to be a IProblem first: NOT %s" % class_name(self),
                        checking_obj=self)
     self.validate_time_interval(start=kwargs.get('time_start', 0.0), end=kwargs.get('time_end', 1.0))
     self._time_start = kwargs.get('time_start', 0.0)
     self._time_end = kwargs.get('time_end', 1.0)
Пример #24
0
 def print_lines_for_log(self):
     _lines = {
         'Type': class_name(self),
         'Number Nodes': "%d" % self.num_nodes
     }
     return _lines