当前位置: 首页>>代码示例>>Python>>正文


Python numpy.isreal方法代码示例

本文整理汇总了Python中numpy.isreal方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.isreal方法的具体用法?Python numpy.isreal怎么用?Python numpy.isreal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.isreal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fit_cubic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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) 
开发者ID:jhrmnn,项目名称:pyberny,代码行数:26,代码来源:Math.py

示例2: _order_complex_poles

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:20,代码来源:ltisys.py

示例3: log_scalars

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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() 
开发者ID:PartnershipOnAI,项目名称:safelife,代码行数:24,代码来源:safelife_logger.py

示例4: test_edge_types

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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])) 
开发者ID:AllenInstitute,项目名称:sonata,代码行数:21,代码来源:test_types.py

示例5: get_fixed_point

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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) 
开发者ID:EPFL-LCN,项目名称:neuronaldynamics-exercises,代码行数:27,代码来源:fitzhugh_nagumo.py

示例6: _modify_dataframe

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:man-group,项目名称:PyBloqs,代码行数:21,代码来源:table_formatters.py

示例7: validate_gibbs_parameters

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:biota,项目名称:sourcetracker2,代码行数:19,代码来源:_sourcetracker.py

示例8: rotation_matrix_zyz_normalized_angle

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:xulabs,项目名称:aitom,代码行数:24,代码来源:ang_loc.py

示例9: vector_step

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:ray-project,项目名称:ray,代码行数:18,代码来源:vector_env.py

示例10: __truediv__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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) 
开发者ID:williamFalcon,项目名称:pytorch-complex-tensor,代码行数:24,代码来源:complex_tensor.py

示例11: __call__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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") 
开发者ID:neherlab,项目名称:treetime,代码行数:23,代码来源:distribution.py

示例12: _set_widget_value

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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() 
开发者ID:lneuhaus,项目名称:pyrpl,代码行数:19,代码来源:attribute_widgets.py

示例13: fit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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) 
开发者ID:ICB-DCM,项目名称:pyABC,代码行数:22,代码来源:local_transition.py

示例14: _validate_converted_limits

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:alvarobartt,项目名称:twitter-stock-recommendation,代码行数:20,代码来源:_base.py

示例15: is_real_number

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isreal [as 别名]
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 
开发者ID:justinsalamon,项目名称:scaper,代码行数:24,代码来源:util.py


注:本文中的numpy.isreal方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。