首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python 3中执行pint数量的numpy矩阵乘法?

如何在python 3中执行pint数量的numpy矩阵乘法?
EN

Stack Overflow用户
提问于 2019-03-28 22:04:58
回答 1查看 532关注 0票数 1

我想将一个(3, 3) np.matrix乘以一个包含pint数量信息的(3,1) np.matrix

下面的代码可以工作:

代码语言:javascript
复制
import numpy as np
x = np.mat([[1,0,0],[0,1,0],[0,0,1]])
y = np.mat([[1],[0],[0]])
x * y
代码语言:javascript
复制
>>> x * y
matrix([[1],
        [0],
        [0]])

这段代码会产生一个错误:

代码语言:javascript
复制
import numpy as np
import pint
ureg = pint.UnitRegistry()
x = np.mat([[1,0,0],[0,1,0],[0,0,1]])
y = np.mat([[1],[0],[0]]) * ureg("m")
x * y

错误是:

代码语言:javascript
复制
>>> x * y
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    x * y
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 900, in __mul__
    return self._mul_div(other, operator.mul)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 75, in wrapped
    result = f(self, *args, **kwargs)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 60, in wrapped
    result = f(self, *args, **kwargs)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 866, in _mul_div
    magnitude = magnitude_op(self._magnitude, other_magnitude)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/numpy/matrixlib/defmatrix.py", line 215, in __mul__
    return N.dot(self, asmatrix(other))
ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0)

如果我使用np.dot(),我会得到一个结果,但单元已被剥离

代码语言:javascript
复制
>>> np.dot(x, y)
~/.virtualenvs/py3env/lib/python3.7/site-packages/pint/q
uantity.py:1377: UnitStrippedWarning: The unit of the quantity is stripped
.
  warnings.warn("The unit of the quantity is stripped.", UnitStrippedWarni
ng)
matrix([[1],
        [0],
        [0]])

这是预期的行为吗?我应该能够对pint数量使用NumPy矩阵数学吗?有没有办法做到这一点?

我使用的是Python3.7 Numpy == 1.15.2品脱== 0.9

EN

回答 1

Stack Overflow用户

发布于 2019-03-30 04:20:36

正如hpaulj所指出的,品脱数量类将订单切换为y*x。

这是因为pint不会为正确的multiply rmul创建单独的函数,而是使用__rmul__ = __mul__

有几种方法可以解决这个问题

解决方案1

我能够通过修改pint/quantity.py来修复这个问题,让它拥有一个独立的。

代码语言:javascript
复制
    def __mul__(self, other):
        return self._mul_div(other, operator.mul)

    def __rmul__(self, other):
        return self._mul_div(other, operator.mul, rmul=True)

    # __rmul__ = __mul__

并通过两个更改将self._mul_div更改为可选地交换self和other:

代码语言:javascript
复制
    @check_implemented
    @ireduce_dimensions
    def _mul_div(self, other, magnitude_op, units_op=None, rmul=False):
        """Perform multiplication or division operation and return the result.

        :param other: object to be multiplied/divided with self
        :type other: Quantity or any type accepted by :func:`_to_magnitude`
        :param magnitude_op: operator function to perform on the magnitudes
            (e.g. operator.mul)
        :type magnitude_op: function
        :param units_op: operator function to perform on the units; if None,
            *magnitude_op* is used
        :type units_op: function or None
        :param rmul: for self.__rmul__ which means the multiplication is 
        happening like:         other * self  
        rather than the normal: self. * other
        """
        print(F"self is {self} other is {other}")
        if units_op is None:
            units_op = magnitude_op

        offset_units_self = self._get_non_multiplicative_units()
        no_offset_units_self = len(offset_units_self)

        if not self._check(other):

            if not self._ok_for_muldiv(no_offset_units_self):
                raise OffsetUnitCalculusError(self._units,
                                              getattr(other, 'units', ''))
            if len(offset_units_self) == 1:
                if (self._units[offset_units_self[0]] != 1
                        or magnitude_op not in [operator.mul, operator.imul]):
                    raise OffsetUnitCalculusError(self._units,
                                                  getattr(other, 'units', ''))
            try:
                other_magnitude = _to_magnitude(other, self.force_ndarray)
            except TypeError:
                return NotImplemented

            # ++++++++++++++++++++++++++++++++++++++++++++++++
            # +++++++++++++++ Change 1 +++++++++++++++++++++++
            # ++++++++++++++++++++++++++++++++++++++++++++++++
            # magnitude = magnitude_op(self._magnitude, other_magnitude)
            op_params = (other_magnitude, self._magnitude) if rmul else (self._magnitude, other_magnitude)
            magnitude = magnitude_op(*op_params)
            # ++++++++++++++++++++++++++++++++++++++++++++++++
            # +++++++++++++++ End Change 1  ++++++++++++++++++
            # ++++++++++++++++++++++++++++++++++++++++++++++++
            units = units_op(self._units, UnitsContainer())

            return self.__class__(magnitude, units)

        if isinstance(other, self._REGISTRY.Unit):
            other = 1.0 * other

        new_self = self

        if not self._ok_for_muldiv(no_offset_units_self):
            raise OffsetUnitCalculusError(self._units, other._units)
        elif no_offset_units_self == 1 and len(self._units) == 1:
            new_self = self.to_root_units()

        no_offset_units_other = len(other._get_non_multiplicative_units())

        if not other._ok_for_muldiv(no_offset_units_other):
            raise OffsetUnitCalculusError(self._units, other._units)
        elif no_offset_units_other == 1 and len(other._units) == 1:
            other = other.to_root_units

        # ++++++++++++++++++++++++++++++++++++++++++++++++
        # +++++++++++++++ Change 2 +++++++++++++++++++++++
        # ++++++++++++++++++++++++++++++++++++++++++++++++
        # magnitude = magnitude_op(new_self._magnitude, other._magnitude)
        op_params = (other._magnitude, new_self._magnitude) if rmul else (new_self._magnitude, other._magnitude)
        magnitude = magnitude_op(*op_params)
        # ++++++++++++++++++++++++++++++++++++++++++++++++
        # +++++++++++++++ End Change 2  ++++++++++++++++++
        # ++++++++++++++++++++++++++++++++++++++++++++++++
        units = units_op(new_self._units, other._units)

        return self.__class__(magnitude, units)

解决方案2

如果你使x是一个无量纲的品脱数量,那么乘法是按正确的顺序给出的。

代码语言:javascript
复制
import numpy as np
import pint
ureg = pint.UnitRegistry()
x = np.mat([[1,0,0],[0,1,0],[0,0,1]]) *ureg("")
y = np.mat([[1],[0],[0]]) * ureg("m")
>>> x * y
<Quantity([[1]
 [0]
 [0]], 'meter')>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55399560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档