Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected type 'Union[ndarray, Iterable]' warning in Python instruction

I have translated a Matlab function to create an Overcomplete Discrete Cosine Transform matrix to represent 1D signals in such vectorial space, to Python language.

Matlab Function

function D = odctdict(n,L)
%ODCTDICT Overcomplete DCT dictionary.
%  D = ODCTDICT(N,L) returns the overcomplete DCT dictionary of size NxL
%  for signals of length N.
%
%  See also ODCT2DICT, ODCT3DICT, ODCTNDICT.    

D = zeros(n,L);
D(:,1) = 1/sqrt(n);
for k = 2:L
  v = cos((0:n-1)*pi*(k-1)/L)';
  v = v-mean(v);
  D(:,k) = v/norm(v);
end

Python translated function

import numpy as np


def odct1dict(n, l):
    """
    1-D Overcomplete DCT dictionary.

    D = odct1dict(N, L) returns the overcomplete DCT dictionary of size NxL
    for signals of length N.

    :param n: signal size
    :type n: int
    :param l: number of atoms
    :type l: int
    :return: 1-D Overcomplete DCT dictionary NumPy array
    """

    d = np.zeros((n, l))
    d[:, 0] = 1 / np.sqrt(n)

    for k in range(1, l):
        v = np.transpose(np.cos(np.arange(0, n) * np.pi * k * l))
        v = v - np.mean(v)
        d[:, k] = v / np.linalg.norm(v)

    return d

I'm using PyCharm as Python IDE, and this software raises a warning, that I don't understand, in the instruction v = np.transpose(np.cos(np.arange(0, n) * np.pi * k * l)) inside the for loop, specifically for the argument of the np.transpose function, np.cos(np.arange(0, n) * np.pi * k * l).

Expected type 'Union[ndarray, Iterable]', got 'int' instead less...

This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations.

Can you explain this warning for me? And how to correct it? What is the proper way to write such instruction?

like image 945
osjerick Avatar asked Jun 02 '15 14:06

osjerick


1 Answers

I'm guessing that PyCharm does not fully understand numpy. It looks and acts like valid Python:

Using my IDE, Ipython, I can do:

In [84]: n,k,l=3, .4, 1

In [85]: v = np.transpose(np.cos(np.arange(0, n) * np.pi * k * l))

In [86]: v
Out[86]: array([ 1.        ,  0.30901699, -0.80901699])
like image 170
hpaulj Avatar answered Sep 20 '22 13:09

hpaulj