예제 #1
0
    def plot_errors(self,
                    concs,
                    init_concs,
                    varied_data,
                    varied,
                    axes=None,
                    compositions=True,
                    Q=True,
                    subplot_kwargs=None):
        if axes is None:
            import matplotlib.pyplot as plt
            if subplot_kwargs is None:
                subplot_kwargs = dict(xscale='log')
            fig, axes = plt.subplots(1,
                                     2,
                                     figsize=(10, 4),
                                     subplot_kw=subplot_kwargs)
        varied_idx = self.as_substance_index(varied)
        ls, c = '- -- : -.'.split(), 'krgbcmy'
        all_inits = np.tile(self.as_per_substance_array(init_concs),
                            (len(varied_data), 1))
        all_inits[:, varied_idx] = varied_data
        if compositions:
            cmp_nrs, m1, m2 = self.composition_conservation(concs, all_inits)
            for cidx, (cmp_nr, a1, a2) in enumerate(zip(cmp_nrs, m1, m2)):
                axes[0].plot(concs[:, varied_idx],
                             a1 - a2,
                             label='Comp ' + str(cmp_nr),
                             ls=ls[cidx % len(ls)],
                             c=c[cidx % len(c)])
                axes[1].plot(concs[:, varied_idx], (a1 - a2) / np.abs(a2),
                             label='Comp ' + str(cmp_nr),
                             ls=ls[cidx % len(ls)],
                             c=c[cidx % len(c)])

        if Q:
            # TODO: handle precipitate phases in plotting Q error
            qs = self.equilibrium_quotients(concs)
            ks = [rxn.param for rxn in self.rxns]
            for idx, (q, k) in enumerate(zip(qs, ks)):
                axes[0].plot(concs[:, varied_idx],
                             q - k,
                             label='K R:' + str(idx),
                             ls=ls[(idx + cidx) % len(ls)],
                             c=c[(idx + cidx) % len(c)])
                axes[1].plot(concs[:, varied_idx], (q - k) / k,
                             label='K R:' + str(idx),
                             ls=ls[(idx + cidx) % len(ls)],
                             c=c[(idx + cidx) % len(c)])

        from pyneqsys.plotting import mpl_outside_legend
        mpl_outside_legend(axes[0])
        mpl_outside_legend(axes[1])
        axes[0].set_title("Absolute errors")
        axes[1].set_title("Relative errors")
예제 #2
0
파일: equilibria.py 프로젝트: bjodah/chempy
    def plot_errors(self, concs, init_concs, varied_data, varied, axes=None,
                    compositions=True, Q=True, subplot_kwargs=None):
        if axes is None:
            import matplotlib.pyplot as plt
            if subplot_kwargs is None:
                subplot_kwargs = dict(xscale='log')
            fig, axes = plt.subplots(1, 2, figsize=(10, 4),
                                     subplot_kw=subplot_kwargs)
        varied_idx = self.as_substance_index(varied)
        ls, c = '- -- : -.'.split(), 'krgbcmy'
        all_inits = np.tile(self.as_per_substance_array(init_concs),
                            (len(varied_data), 1))
        all_inits[:, varied_idx] = varied_data
        if compositions:
            cmp_nrs, m1, m2 = self.composition_conservation(concs, all_inits)
            for cidx, (cmp_nr, a1, a2) in enumerate(zip(cmp_nrs, m1, m2)):
                axes[0].plot(concs[:, varied_idx],
                             a1-a2, label='Comp ' + str(cmp_nr),
                             ls=ls[cidx % len(ls)], c=c[cidx % len(c)])
                axes[1].plot(concs[:, varied_idx],
                             (a1-a2)/np.abs(a2), label='Comp ' + str(cmp_nr),
                             ls=ls[cidx % len(ls)], c=c[cidx % len(c)])

        if Q:
            # TODO: handle precipitate phases in plotting Q error
            qs = self.equilibrium_quotients(concs)
            ks = [rxn.param for rxn in self.rxns]
            for idx, (q, k) in enumerate(zip(qs, ks)):
                axes[0].plot(concs[:, varied_idx],
                             q-k, label='K R:' + str(idx),
                             ls=ls[(idx+cidx) % len(ls)],
                             c=c[(idx+cidx) % len(c)])
                axes[1].plot(concs[:, varied_idx],
                             (q-k)/k, label='K R:' + str(idx),
                             ls=ls[(idx+cidx) % len(ls)],
                             c=c[(idx+cidx) % len(c)])

        from pyneqsys.plotting import mpl_outside_legend
        mpl_outside_legend(axes[0])
        mpl_outside_legend(axes[1])
        axes[0].set_title("Absolute errors")
        axes[1].set_title("Relative errors")
예제 #3
0
    def roots(
        self,
        init_concs,
        varied_data,
        varied,
        x0=None,
        NumSys=NumSysLog,
        plot_kwargs=None,
        neqsys_type="chained_conditional",
        **kwargs
    ):
        """
        Parameters
        ----------
        init_concs : array or dict
        varied_data : array
        varied_idx : int or str
        x0 : array
        NumSys : _NumSys subclass
            See :class:`NumSysLin`, :class:`NumSysLog`, etc.
        plot_kwargs : dict
            See py:meth:`pyneqsys.NeqSys.solve`. Two additional keys
            are intercepted here:
                latex_names: bool (default: False)
                conc_unit_str: str (default: 'M')
        neqsys_type : str
            what method to use for NeqSys construction (get_neqsys_*)
        \\*\\*kwargs :
            Keyword argumetns passed on to py:meth:`pyneqsys.NeqSys.solve_series`.

        """
        _plot = plot_kwargs is not None
        if _plot:
            latex_names = plot_kwargs.pop("latex_names", False)
            conc_unit_str = plot_kwargs.pop("conc_unit_str", "M")
            if "ax" not in plot_kwargs:
                plot_kwargs["ax"] = self._get_default_plot_ax()

        init_concs = self.as_per_substance_array(init_concs)
        neqsys = self.get_neqsys(
            neqsys_type,
            NumSys=NumSys,
            rref_equil=kwargs.pop("rref_equil", False),
            rref_preserv=kwargs.pop("rref_preserv", False),
            precipitates=kwargs.pop("precipitates", None),
        )
        if x0 is None:
            x0 = init_concs

        if _plot:
            cb = neqsys.solve_and_plot_series
            if "plot_kwargs" not in kwargs:
                kwargs["plot_kwargs"] = plot_kwargs
            if "labels" not in kwargs["plot_kwargs"]:
                kwargs["plot_kwargs"]["labels"] = self.substance_labels(latex_names)
            if "substances" in plot_kwargs:
                if "indices" in plot_kwargs:
                    raise ValueError("Now I am confused..")
                kwargs["plot_kwargs"]["indices"] = map(
                    self.as_substance_index, plot_kwargs.pop("substances")
                )
                print(kwargs["plot_kwargs"]["indices"])
        else:
            cb = neqsys.solve_series

        params = np.concatenate((init_concs, self.eq_constants()))
        xvecs, info_dicts = cb(
            x0,
            params,
            varied_data,
            self.as_substance_index(varied),
            propagate=False,
            **kwargs
        )
        sanity = [self._result_is_sane(init_concs, x) for x in xvecs]

        if _plot:
            import matplotlib.pyplot as plt
            from pyneqsys.plotting import mpl_outside_legend

            mpl_outside_legend(plt.gca())
            varied_subst = self.substances[varied]
            xlbl = (
                "$[" + varied_subst.latex_name + "]_0$"
                if latex_names
                else str(varied_subst)
            )
            plt.gca().set_xlabel(xlbl + " / " + conc_unit_str)
            plt.gca().set_ylabel("Concentration / " + conc_unit_str)

        return xvecs, info_dicts, sanity
예제 #4
0
    def roots(self, init_concs, varied_data, varied, x0=None,
              NumSys=NumSysLog, plot_kwargs=None,
              neqsys_type='chained_conditional', **kwargs):
        """
        Parameters
        ----------
        init_concs : array or dict
        varied_data : array
        varied_idx : int or str
        x0 : array
        NumSys : _NumSys subclass
            See :class:`NumSysLin`, :class:`NumSysLog`, etc.
        plot_kwargs : dict
            See py:meth:`pyneqsys.NeqSys.solve`. Two additional keys
            are intercepted here:
                latex_names: bool (default: False)
                conc_unit_str: str (default: 'M')
        neqsys_type : str
            what method to use for NeqSys construction (get_neqsys_*)
        \*\*kwargs :
            kwargs passed on to py:meth:`pyneqsys.NeqSys.solve_series`

        """
        _plot = plot_kwargs is not None
        if _plot:
            latex_names = plot_kwargs.pop('latex_names', False)
            conc_unit_str = plot_kwargs.pop('conc_unit_str', 'M')
            if 'ax' not in plot_kwargs:
                plot_kwargs['ax'] = self._get_default_plot_ax()

        init_concs = self.as_per_substance_array(init_concs)
        neqsys = self.get_neqsys(
            neqsys_type, init_concs, NumSys=NumSys,
            rref_equil=kwargs.pop('rref_equil', False),
            rref_preserv=kwargs.pop('rref_preserv', False),
            precipitates=kwargs.pop('precipitates', None))
        if x0 is None:
            x0 = init_concs

        if _plot:
            cb = neqsys.solve_and_plot_series
            if 'plot_kwargs' not in kwargs:
                kwargs['plot_kwargs'] = {}
            if 'labels' not in kwargs['plot_kwargs']:
                kwargs['plot_kwargs']['labels'] = (
                    self.substance_labels(latex_names))
            if 'substances' in plot_kwargs:
                if 'indices' in plot_kwargs:
                    raise ValueError("Now I am confused..")
                kwargs['plot_kwargs']['indices'] = map(
                    self.as_substance_index, plot_kwargs.pop('substances'))
                print(kwargs['plot_kwargs']['indices'])
        else:
            cb = neqsys.solve_series

        params = np.concatenate((init_concs, self.eq_constants()))
        xvecs, info_dicts = cb(
            x0, params, varied_data, self.as_substance_index(varied),
            propagate=False, **kwargs)
        sanity = [self._result_is_sane(init_concs, x) for x in xvecs]

        if _plot:
            import matplotlib.pyplot as plt
            from pyneqsys.plotting import mpl_outside_legend
            mpl_outside_legend(plt.gca())
            varied_subst = self.substances[varied]
            xlbl = ('$[' + varied_subst.latex_name + ']_0$' if latex_names
                    else str(varied_subst))
            plt.gca().set_xlabel(xlbl + ' / ' + conc_unit_str)
            plt.gca().set_ylabel('Concentration / ' + conc_unit_str)

        return xvecs, info_dicts, sanity
예제 #5
0
파일: equilibria.py 프로젝트: bjodah/chempy
    def roots(self, init_concs, varied_data, varied, x0=None,
              NumSys=NumSysLog, plot_kwargs=None,
              neqsys_type='chained_conditional', **kwargs):
        """
        Parameters
        ----------
        init_concs : array or dict
        varied_data : array
        varied_idx : int or str
        x0 : array
        NumSys : _NumSys subclass
            See :class:`NumSysLin`, :class:`NumSysLog`, etc.
        plot_kwargs : dict
            See py:meth:`pyneqsys.NeqSys.solve`. Two additional keys
            are intercepted here:
                latex_names: bool (default: False)
                conc_unit_str: str (default: 'M')
        neqsys_type : str
            what method to use for NeqSys construction (get_neqsys_*)
        \\*\\*kwargs :
            Keyword argumetns passed on to py:meth:`pyneqsys.NeqSys.solve_series`.

        """
        _plot = plot_kwargs is not None
        if _plot:
            latex_names = plot_kwargs.pop('latex_names', False)
            conc_unit_str = plot_kwargs.pop('conc_unit_str', 'M')
            if 'ax' not in plot_kwargs:
                plot_kwargs['ax'] = self._get_default_plot_ax()

        init_concs = self.as_per_substance_array(init_concs)
        neqsys = self.get_neqsys(
            neqsys_type, NumSys=NumSys,
            rref_equil=kwargs.pop('rref_equil', False),
            rref_preserv=kwargs.pop('rref_preserv', False),
            precipitates=kwargs.pop('precipitates', None))
        if x0 is None:
            x0 = init_concs

        if _plot:
            cb = neqsys.solve_and_plot_series
            if 'plot_kwargs' not in kwargs:
                kwargs['plot_kwargs'] = plot_kwargs
            if 'labels' not in kwargs['plot_kwargs']:
                kwargs['plot_kwargs']['labels'] = (
                    self.substance_labels(latex_names))
            if 'substances' in plot_kwargs:
                if 'indices' in plot_kwargs:
                    raise ValueError("Now I am confused..")
                kwargs['plot_kwargs']['indices'] = map(
                    self.as_substance_index, plot_kwargs.pop('substances'))
                print(kwargs['plot_kwargs']['indices'])
        else:
            cb = neqsys.solve_series

        params = np.concatenate((init_concs, self.eq_constants()))
        xvecs, info_dicts = cb(
            x0, params, varied_data, self.as_substance_index(varied),
            propagate=False, **kwargs)
        sanity = [self._result_is_sane(init_concs, x) for x in xvecs]

        if _plot:
            import matplotlib.pyplot as plt
            from pyneqsys.plotting import mpl_outside_legend
            mpl_outside_legend(plt.gca())
            varied_subst = self.substances[varied]
            xlbl = ('$[' + varied_subst.latex_name + ']_0$' if latex_names
                    else str(varied_subst))
            plt.gca().set_xlabel(xlbl + ' / ' + conc_unit_str)
            plt.gca().set_ylabel('Concentration / ' + conc_unit_str)

        return xvecs, info_dicts, sanity