Python numpy.isreal() Examples

The following are 30 code examples of numpy.isreal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: table_formatters.py    From PyBloqs with GNU Lesser General Public License v2.1 6 votes vote down vote up
def _modify_dataframe(self, df):
        """Add row to dataframe, containing numbers aggregated with self.operator."""
        if self.total_columns == []:
            columns = df.columns
        else:
            columns = self.total_columns
        if self.operator is not OP_NONE:
            df_calculated = df[columns]
            last_row = self.operator(df_calculated[df_calculated.applymap(np.isreal)])
            last_row = last_row.fillna(0.)
            last_row = last_row.append(pd.Series('', index=df.columns.difference(last_row.index)))
        else:
            last_row = pd.Series('', index=df.columns)
        last_row.name = self.row_name
        # Appending kills index name, save now and restore after appending
        index_name = df.index.name
        df = df.append(last_row)
        df.index.name = index_name
        return df 
Example #2
Source File: ltisys.py    From lambda-packs with MIT License 6 votes vote down vote up
def _order_complex_poles(poles):
    """
    Check we have complex conjugates pairs and reorder P according to YT, ie
    real_poles, complex_i, conjugate complex_i, ....
    The lexicographic sort on the complex poles is added to help the user to
    compare sets of poles.
    """
    ordered_poles = np.sort(poles[np.isreal(poles)])
    im_poles = []
    for p in np.sort(poles[np.imag(poles) < 0]):
        if np.conj(p) in poles:
            im_poles.extend((p, np.conj(p)))

    ordered_poles = np.hstack((ordered_poles, im_poles))

    if poles.shape[0] != len(ordered_poles):
        raise ValueError("Complex poles must come with their conjugates")
    return ordered_poles 
Example #3
Source File: safelife_logger.py    From safelife with Apache License 2.0 6 votes vote down vote up
def log_scalars(self, data, global_step=None, tag=None):
        """
        Log scalar values to tensorboard.

        Parameters
        ----------
        data : dict
            Dictionary of key/value pairs to log to tensorboard.
        tag : str or None

        """
        self.init_logdir()  # init if needed

        if not self.summary_writer:
            return
        tag = "" if tag is None else tag + '/'
        if global_step is None:
            global_step = self.cumulative_stats['training_steps']
        for key, val in data.items():
            if np.isreal(val) and np.isscalar(val):
                self.summary_writer.add_scalar(tag + key, val, global_step)
        self.summary_writer.flush() 
Example #4
Source File: local_transition.py    From pyABC with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def fit(self, X, w):
        if len(X) == 0:
            raise NotEnoughParticles("Fitting not possible.")
        self.X_arr = X.values

        ctree = cKDTree(X)
        _, indices = ctree.query(X, k=min(self.k + 1, X.shape[0]))

        covs, inv_covs, dets = list(zip(*[self._cov_and_inv(n, indices)
                                    for n in range(X.shape[0])]))
        self.covs = np.array(covs)
        self.inv_covs = np.array(inv_covs)
        self.determinants = np.array(dets)

        self.normalization = np.sqrt(
            (2 * np.pi) ** self.X_arr.shape[1] * self.determinants)

        if not np.isreal(self.normalization).all():
            raise Exception("Normalization not real")
        self.normalization = np.real(self.normalization) 
Example #5
Source File: _base.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def _validate_converted_limits(self, limit, convert):
        """
        Raise ValueError if converted limits are non-finite.

        Note that this function also accepts None as a limit argument.

        Returns
        -------
        The limit value after call to convert(), or None if limit is None.

        """
        if limit is not None:
            converted_limit = convert(limit)
            if (isinstance(converted_limit, float) and
                    (not np.isreal(converted_limit) or
                        not np.isfinite(converted_limit))):
                raise ValueError("Axis limits cannot be NaN or Inf")
            return converted_limit 
Example #6
Source File: util.py    From scaper with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_real_number(num):
    '''
    Check if a value is a real scalar by aggregating several numpy checks.

    Parameters
    ----------
    num : any type
        The parameter to check

    Returns
    ------
    check : bool
        True if ```num``` is a real scalar, False otherwise.

    '''

    if (not np.isreal(num) or
            not np.isrealobj(num) or
            not np.isscalar(num)):
        return False
    else:
        return True 
Example #7
Source File: attribute_widgets.py    From pyrpl with GNU General Public License v3.0 6 votes vote down vote up
def _set_widget_value(self, new_value, transform_magnitude=lambda data :
    20. * np.log10(np.abs(data) + sys.float_info.epsilon)):
        if new_value is None:
            return
        x, y = new_value
        shape = np.shape(y)
        if len(shape) > 2:
            raise ValueError("Data cannot be larger than 2 "
                             "dimensional")
        if len(shape) == 1:
            y = [y]
        self._set_real(np.isreal(y).all())
        for i, values in enumerate(y):
            self._display_curve_index(x, values, i, transform_magnitude=transform_magnitude)
        while (i + 1 < len(self.curves)):  # delete remaining curves
            i += 1
            self.curves[i].hide() 
Example #8
Source File: distribution.py    From treetime with MIT License 6 votes vote down vote up
def __call__(self, x):

        if isinstance(x, Iterable):
            valid_idxs = (x > self._xmin-TINY_NUMBER) & (x < self._xmax+TINY_NUMBER)
            res = np.ones_like (x, dtype=float) * (BIG_NUMBER+self.peak_val)
            tmp_x = np.copy(x[valid_idxs])
            tmp_x[tmp_x<self._xmin+TINY_NUMBER] = self._xmin+TINY_NUMBER
            tmp_x[tmp_x>self._xmax-TINY_NUMBER] = self._xmax-TINY_NUMBER
            res[valid_idxs] = self._peak_val + self._func(tmp_x)
            return res

        elif np.isreal(x):
            if x < self._xmin or x > self._xmax:
                return BIG_NUMBER+self.peak_val
            # x is within interpolation range
            elif self._delta == True:
                return self._peak_val
            else:
                return self._peak_val + self._func(x)
        else:
            raise TypeError("Wrong type: should be float or array") 
Example #9
Source File: ltisys.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def _order_complex_poles(poles):
    """
    Check we have complex conjugates pairs and reorder P according to YT, ie
    real_poles, complex_i, conjugate complex_i, ....
    The lexicographic sort on the complex poles is added to help the user to
    compare sets of poles.
    """
    ordered_poles = np.sort(poles[np.isreal(poles)])
    im_poles = []
    for p in np.sort(poles[np.imag(poles) < 0]):
        if np.conj(p) in poles:
            im_poles.extend((p, np.conj(p)))

    ordered_poles = np.hstack((ordered_poles, im_poles))

    if poles.shape[0] != len(ordered_poles):
        raise ValueError("Complex poles must come with their conjugates")
    return ordered_poles 
Example #10
Source File: vector_env.py    From ray with Apache License 2.0 6 votes vote down vote up
def vector_step(self, actions):
        obs_batch, rew_batch, done_batch, info_batch = [], [], [], []
        for i in range(self.num_envs):
            obs, r, done, info = self.envs[i].step(actions[i])
            if not np.isscalar(r) or not np.isreal(r) or not np.isfinite(r):
                raise ValueError(
                    "Reward should be finite scalar, got {} ({}). "
                    "Actions={}.".format(r, type(r), actions[i]))
            if type(info) is not dict:
                raise ValueError("Info should be a dict, got {} ({})".format(
                    info, type(info)))
            obs_batch.append(obs)
            rew_batch.append(r)
            done_batch.append(done)
            info_batch.append(info)
        return obs_batch, rew_batch, done_batch, info_batch 
Example #11
Source File: vector_env.py    From ray with Apache License 2.0 6 votes vote down vote up
def vector_step(self, actions):
        obs_batch, rew_batch, done_batch, info_batch = [], [], [], []
        for i in range(self.num_envs):
            obs, r, done, info = self.envs[i].step(actions[i])
            if not np.isscalar(r) or not np.isreal(r) or not np.isfinite(r):
                raise ValueError(
                    "Reward should be finite scalar, got {} ({}). "
                    "Actions={}.".format(r, type(r), actions[i]))
            if type(info) is not dict:
                raise ValueError("Info should be a dict, got {} ({})".format(
                    info, type(info)))
            obs_batch.append(obs)
            rew_batch.append(r)
            done_batch.append(done)
            info_batch.append(info)
        return obs_batch, rew_batch, done_batch, info_batch 
Example #12
Source File: test_types.py    From sonata with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_edge_types(net):
    edge_types = net.edges.edge_types_table
    assert(edge_types is not None)
    assert(len(edge_types.edge_type_ids) == 11)
    assert(len(edge_types.columns) == 5)
    assert('template' in edge_types.columns)
    assert('delay' in edge_types.columns)
    assert(edge_types.to_dataframe().shape == (11, 5))
    assert(np.isreal(edge_types.column('delay').dtype))

    assert(1 in edge_types)
    edge_type1 = edge_types[1]
    assert(edge_type1['dynamics_params'] == 'instanteneousInh.json')
    assert(edge_type1['delay'] == 2.0)

    # check that row is being cached.
    mem_id = id(edge_type1)
    del edge_type1
    assert (mem_id == id(edge_types[1])) 
Example #13
Source File: ltisys.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _order_complex_poles(poles):
    """
    Check we have complex conjugates pairs and reorder P according to YT, ie
    real_poles, complex_i, conjugate complex_i, ....
    The lexicographic sort on the complex poles is added to help the user to
    compare sets of poles.
    """
    ordered_poles = np.sort(poles[np.isreal(poles)])
    im_poles = []
    for p in np.sort(poles[np.imag(poles) < 0]):
        if np.conj(p) in poles:
            im_poles.extend((p, np.conj(p)))

    ordered_poles = np.hstack((ordered_poles, im_poles))

    if poles.shape[0] != len(ordered_poles):
        raise ValueError("Complex poles must come with their conjugates")
    return ordered_poles 
Example #14
Source File: ang_loc.py    From aitom with GNU General Public License v3.0 6 votes vote down vote up
def rotation_matrix_zyz_normalized_angle(rm):

    assert(all(N.isreal(rm.flatten())));     assert(rm.shape == (3,3));

    cos_theta = rm[2, 2]
    if N.abs(cos_theta) > 1.0:
        # warning(sprintf('cos_theta %g', cos_theta));
        cos_theta = N.sign(cos_theta);

    theta = N.arctan2(N.sqrt(1.0 - (cos_theta*cos_theta) ), cos_theta);

    if N.abs(cos_theta) < (1.0 - (1e-10)) :          # use a small epslon to increase numerical stability when abs(cos_theta) is very close to 1!!!!
        phi = N.arctan2(rm[2,1], rm[2,0]);
        psi_t = N.arctan2(rm[1,2], -rm[0,2]);
    else:
        theta = 0.0
        phi = 0.0
        psi_t = N.arctan2(rm[0,1], rm[1,1])

    ang = N.array([phi, theta, psi_t], dtype=N.float)

    return ang 
Example #15
Source File: _sourcetracker.py    From sourcetracker2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validate_gibbs_parameters(alpha1, alpha2, beta, restarts,
                              draws_per_restart, burnin, delay):
    '''Return `True` if params numerically acceptable. See `gibbs` for docs.'''
    real_vals = [alpha1, alpha2, beta]
    int_vals = [restarts, draws_per_restart, burnin, delay]
    # Check everything is real.
    if all(np.isreal(val) for val in real_vals + int_vals):
        # Check that integer values are some type of int.
        int_check = all(isinstance(val, (int, np.int32, np.int64)) for val in
                        int_vals)
        # All integer values must be > 0.
        pos_int = all(val > 0 for val in int_vals)
        # All real values must be non-negative.
        non_neg = all(val >= 0 for val in real_vals)
        return int_check and pos_int and non_neg and real_vals
    else:  # Failed to be all numeric values.
        False 
Example #16
Source File: complex_tensor.py    From pytorch-complex-tensor with MIT License 6 votes vote down vote up
def __truediv__(self, other):
        real = self.real.clone()
        imag = self.imag.clone()

        # given a real tensor
        if isinstance(other, torch.Tensor) and type(other) is not ComplexTensor:
            raise NotImplementedError

        # given a complex tensor
        elif type(other) is ComplexTensor:
            raise NotImplementedError

        # given a real scalar
        elif np.isreal(other):
            real = real / other
            imag = imag / other

        # given a complex scalar
        else:
            raise NotImplementedError

        return self.__graph_copy__(real, imag) 
Example #17
Source File: fitzhugh_nagumo.py    From neuronaldynamics-exercises with GNU General Public License v2.0 6 votes vote down vote up
def get_fixed_point(I=0., eps=0.1, a=2.0):
    """Computes the fixed point of the FitzHugh Nagumo model
    as a function of the input current I.

    We solve the 3rd order poylnomial equation:
    v**3 + V + a - I0 = 0

    Args:
        I: Constant input [mV]
        eps: Inverse time constant of the recovery variable w [1/ms]
        a: Offset of the w-nullcline [mV]

    Returns:
        tuple: (v_fp, w_fp) fixed point of the equations
    """

    # Use poly1d function from numpy to compute the
    # roots of 3rd order polynomial
    P = np.poly1d([1, 0, 1, (a - I)], variable="x")

    # take only the real root
    v_fp = np.real(P.r[np.isreal(P.r)])[0]
    w_fp = 2. * v_fp + a

    return (v_fp, w_fp) 
Example #18
Source File: Math.py    From pyberny with Mozilla Public License 2.0 6 votes vote down vote up
def fit_cubic(y0, y1, g0, g1):
    """Fit cubic polynomial to function values and derivatives at x = 0, 1.

    Returns position and function value of minimum if fit succeeds. Fit does
    not succeeds if

    1. polynomial doesn't have extrema or
    2. maximum is from (0,1) or
    3. maximum is closer to 0.5 than minimum
    """
    a = 2 * (y0 - y1) + g0 + g1
    b = -3 * (y0 - y1) - 2 * g0 - g1
    p = np.array([a, b, g0, y0])
    r = np.roots(np.polyder(p))
    if not np.isreal(r).all():
        return None, None
    r = sorted(x.real for x in r)
    if p[0] > 0:
        maxim, minim = r
    else:
        minim, maxim = r
    if 0 < maxim < 1 and abs(minim - 0.5) > abs(maxim - 0.5):
        return None, None
    return minim, np.polyval(p, minim) 
Example #19
Source File: table_formatters.py    From PyBloqs with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _modify_dataframe(self, df):
        """Add row to dataframe, containing numbers aggregated with self.operator."""
        if self.total_rows == []:
            rows = df.index.tolist()
        else:
            rows = self.total_rows
        if self.operator is not OP_NONE:
            new_column = self.operator(df[df.applymap(np.isreal)], axis=1)
            new_column = new_column.fillna(0.)
            new_column[~new_column.index.isin(rows)] = ''
        else:
            new_column = pd.Series('', index=df.index)
        df_mod = df.copy()
        df_mod[self.column_name] = new_column
        return df_mod 
Example #20
Source File: filter_design.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _nearest_real_complex_idx(fro, to, which):
    """Get the next closest real or complex element based on distance"""
    assert which in ('real', 'complex')
    order = np.argsort(np.abs(fro - to))
    mask = np.isreal(fro[order])
    if which == 'complex':
        mask = ~mask
    return order[np.where(mask)[0][0]] 
Example #21
Source File: element.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_axis_limits(self, axis, view, subplots, ranges):
        """
        Compute extents for current view and apply as axis limits
        """
        # Extents
        extents = self.get_extents(view, ranges)
        if not extents or self.overlaid:
            axis.autoscale_view(scalex=True, scaley=True)
            return

        valid_lim = lambda c: util.isnumeric(c) and not np.isnan(c)
        coords = [coord if np.isreal(coord) or isinstance(coord, np.datetime64) else np.NaN for coord in extents]
        coords = [date2num(util.dt64_to_dt(c)) if isinstance(c, np.datetime64) else c
                  for c in coords]
        if self.projection == '3d' or len(extents) == 6:
            l, b, zmin, r, t, zmax = coords
            if self.invert_zaxis or any(p.invert_zaxis for p in subplots):
                zmin, zmax = zmax, zmin
            if zmin != zmax:
                if valid_lim(zmin):
                    axis.set_zlim(bottom=zmin)
                if valid_lim(zmax):
                    axis.set_zlim(top=zmax)
        else:
            l, b, r, t = coords

        if self.invert_axes:
            l, b, r, t = b, l, t, r

        invertx = self.invert_xaxis or any(p.invert_xaxis for p in subplots)
        xlim, scalex = self._compute_limits(l, r, self.logx, invertx, 'left', 'right')
        inverty = self.invert_yaxis or any(p.invert_yaxis for p in subplots)
        ylim, scaley =  self._compute_limits(b, t, self.logy, inverty, 'bottom', 'top')
        if xlim:
            axis.set_xlim(**xlim)
        if ylim:
            axis.set_ylim(**ylim)
        axis.autoscale_view(scalex=scalex, scaley=scaley) 
Example #22
Source File: attribute_widgets.py    From pyrpl with GNU General Public License v3.0 5 votes vote down vote up
def _set_widget_value(self, new_value):
        x, y, name = self.get_xy_data(new_value)
        if x is not None:
            if not np.isreal(y).all():
                self.curve.setData(x, self._magnitude(y))
                self.curve_phase.setData(x, self._phase(y))
                self.plot_item_phase.show()
                self.plot_item.setTitle(name + " - Magnitude (dB)")
            else:
                self.curve.setData(x, np.real(y))
                self.plot_item_phase.hide()
                self.plot_item.setTitle(name) 
Example #23
Source File: operator_spaces_test.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def test_hilbert_schmidt_inner_product_is_conjugate_symmetric(
        m1, m2, expect_real):
    v1 = cirq.hilbert_schmidt_inner_product(m1, m2)
    v2 = cirq.hilbert_schmidt_inner_product(m2, m1)
    assert v1 == v2.conjugate()

    assert np.isreal(v1) == expect_real
    if not expect_real:
        assert v1 != v2 
Example #24
Source File: ulog.py    From px4tools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _smallest_positive_real_root(roots, min_val=0, max_val=1e6):
    """
    Find smallest positive real root in list
    """
    res = np.nan
    if len(roots) > 0:
        cond = np.logical_and(
            np.isreal(roots),
            np.real(roots) > min_val)
        posreal = sorted(np.real(roots[cond]))
        if len(posreal) > 0:
            res = posreal[0]
    if not np.isfinite(res) or res < min_val or res > max_val:
        res = np.nan
    return res 
Example #25
Source File: delayseq.py    From piradar with GNU Affero General Public License v3.0 5 votes vote down vote up
def delayseq(x, delay_sec: float, fs: int):
    """
    x: input 1-D signal
    delay_sec: amount to shift signal [seconds]
    fs: sampling frequency [Hz]

    xs: time-shifted signal
    """

    assert x.ndim == 1, "only 1-D signals for now"

    delay_samples = delay_sec * fs
    delay_int = round(delay_samples)

    nfft = nextpow2(x.size + delay_int)

    fbins = 2 * pi * ifftshift((arange(nfft) - nfft // 2)) / nfft

    X = fft(x, nfft)
    Xs = ifft(X * exp(-1j * delay_samples * fbins))

    if isreal(x[0]):
        Xs = Xs.real

    xs = zeros_like(x)
    xs[delay_int:] = Xs[delay_int : x.size]

    return xs 
Example #26
Source File: interval.py    From highway-env with MIT License 5 votes vote down vote up
def update_coordinates_frame(self, a0: np.ndarray) -> None:
        """
        Ensure that the dynamics matrix A0 is Metzler.

        If not, design a coordinate transformation and apply it to the model and state interval.
        :param a0: the dynamics matrix A0
        """
        self.coordinates = None
        # Rotation
        if not is_metzler(a0):
            eig_v, transformation = np.linalg.eig(a0)
            if np.isreal(eig_v).all():
                try:
                    self.coordinates = (transformation, np.linalg.inv(transformation))
                except LinAlgError:
                    pass
            if not self.coordinates:
                print("Non Metzler A0 with eigenvalues: ", eig_v)
        else:
            self.coordinates = (np.eye(a0.shape[0]), np.eye(a0.shape[0]))

        # Forward coordinates change of states and models
        self.a0 = self.change_coordinates(self.a0, matrix=True)
        self.da = self.change_coordinates(self.da, matrix=True)
        self.b = self.change_coordinates(self.b, offset=False)
        self.x_i_t = np.array(self.change_coordinates([x for x in self.x_i])) 
Example #27
Source File: table_formatters.py    From PyBloqs with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _modify_dataframe(self, df):
        """Create single index dataframe inserting grouping rows for higher levels."""
        if self.total_columns == []:
            columns = df.columns
        else:
            columns = self.total_columns

        flat_row_list = []
        n_ix_levels = len(df.index.levels)

        # For each row compare index tuple to previous one and see if it changed on any level.
        previous_tuple = [''] * n_ix_levels
        for level_k, index_tuple in enumerate(df.index):
            for level_i, sub_index in enumerate(index_tuple):
                if index_tuple[:level_i + 1] != previous_tuple[:level_i + 1]:
                    if level_i == n_ix_levels - 1:
                        # If we are on lowest level, add entire row to flat_df
                        data_rows = df.iloc[[level_k], :].copy()
                    else:
                        # If we are on higher level, add row filled with operator on lower level data
                        if self.operator is OP_NONE:
                            # For operator None fill row with empty string for each column
                            data_rows = pd.DataFrame('', columns=df.columns, index=[sub_index])
                        else:
                            df_subset = df.loc[index_tuple[:level_i + 1]]
                            data_rows = self.operator(df_subset[df_subset.applymap(np.isreal)]).to_frame().T
                            data_rows = data_rows.fillna(0.)
                            data_rows.loc[:, ~data_rows.columns.isin(columns)] = ''
                    n_rows = len(data_rows)
                    data_rows.index = [sub_index] * n_rows
                    data_rows.loc[:, ORG_ROW_NAMES] = pd.Series([index_tuple[:level_i + 1]], index=data_rows.index)
                    flat_row_list.append(data_rows)
                    # Need to address index_level with i instead of sub_index, because sub_index can repeat many times.
                    self.index_level += [level_i] * n_rows
            previous_tuple = index_tuple
        flat_df = pd.concat(flat_row_list)
        flat_df.index.name = ''
        return flat_df 
Example #28
Source File: test_mlab.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_cohere():
    N = 1024
    np.random.seed(19680801)
    x = np.random.randn(N)
    # phase offset
    y = np.roll(x, 20)
    # high-freq roll-off
    y = np.convolve(y, np.ones(20) / 20., mode='same')
    cohsq, f = mlab.cohere(x, y, NFFT=256, Fs=2, noverlap=128)
    assert_allclose(np.mean(cohsq), 0.837, atol=1.e-3)
    assert np.isreal(np.mean(cohsq)) 
Example #29
Source File: util.py    From scaper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_real_array(array):
    '''
    Check if a value is a list or array of real scalars by aggregating several
    numpy checks.

    Parameters
    ----------
    array: any type
        The parameter to check

    Returns
    ------
    check : bool
        True if ```array``` is a list or array of a real scalars, False
        otherwise.

    '''

    if not (type(array) is list or type(array) is np.ndarray):
        return False
    else:
        if (not np.all([np.isreal(x) for x in array]) or
                not np.isrealobj(array) or
                not np.asarray(list(map(np.isscalar, array))).all()):
            return False
        else:
            return True 
Example #30
Source File: test_quantity_non_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_isreal(self):
        self.check(np.isreal)
        assert not np.isreal([1. + 1j]*u.m)