Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert a list of Quantity object into an array of Quantity object #183

Open
xiki-tempula opened this issue Apr 16, 2021 · 2 comments
Open

Comments

@xiki-tempula
Copy link

I wonder if it is possible to have a function to convert a list of Quantity into an array of Quantity object?

>>> import numpy as np
>>> import quantities as pq
>>> a = 1 * pq.e
>>> a
array(1.) * e
>>> b = [a, a]
>>> b
[array(1.) * e, array(1.) * e]
>>> np.array(b)
array([1., 1.])

So I wonder if there could be a function

>>> pq.array(b)
array([1., 1.]) * e
@twmr
Copy link
Contributor

twmr commented May 22, 2021

I'm using the following function for this use-case (the name of it could be improved, though)

def quantitylistrescale(seq, unit=None):
    """Convert list of quantities to a rescaled quantity array

    Examples
    --------

    >>> import quantities as pq
    >>> a = 3 * pq.m; b = 2.5 * pq.mm
    >>> quantitylistrescale([a, b], 'cm')
    array([3.0e+02, 2.5e-01]) * cm

    If no ``unit`` is given, the elements will be rescaled to the unit of the
    first quantity.

    >>> quantitylistrescale([a, b])
    array([3.0e+00, 2.5e-03]) * m

    >>> quantitylistrescale([])
    Traceback (most recent call last):
        ...
    StopIteration
    >>> quantitylistrescale([3 * pq.m, 4 * pq.V])
    Traceback (most recent call last):
        ...
    ValueError: Unable to convert between units of "V" and "m"

    """
    assert all(isinstance(item, pq.Quantity) for item in seq), (
        f"{seq} contains objects which are not of type pq.Quantity")

    if unit is None:
        first = next(iter(seq))
        unit = first.dimensionality.string

    rescaled_seq = [item.rescale(unit).magnitude for item in seq]

    return pq.Quantity(rescaled_seq, unit)

@xiki-tempula
Copy link
Author

xiki-tempula commented May 23, 2021

I'm using a similar function (without type checking as I know what is in the array) but I felt that it might be good to have it in the package, like pq.array().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants