Python types.ComplexType() Examples

The following are code examples for showing how to use types.ComplexType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 6 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        self.type_name = 'complex'
        self.check_func = 'PyComplex_Check'
        self.c_type = 'std::complex<double>'
        self.return_type = 'std::complex<double>'
        self.to_c_return = "std::complex<double>(PyComplex_RealAsDouble(py_obj),"\
                                                "PyComplex_ImagAsDouble(py_obj))"
        self.matching_types = [types.ComplexType]

#----------------------------------------------------------------------------
#
# List, Tuple, and Dict converters.
#
# Based on SCXX by Gordon McMillan
#---------------------------------------------------------------------------- 
Example 2
Project: Computable   Author: ktraunmueller   File: c_spec.py    MIT License 6 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        self.type_name = 'complex'
        self.check_func = 'PyComplex_Check'
        self.c_type = 'std::complex<double>'
        self.return_type = 'std::complex<double>'
        self.to_c_return = "std::complex<double>(PyComplex_RealAsDouble(py_obj),"\
                                                "PyComplex_ImagAsDouble(py_obj))"
        self.matching_types = [types.ComplexType]

#----------------------------------------------------------------------------
#
# List, Tuple, and Dict converters.
#
# Based on SCXX by Gordon McMillan
#---------------------------------------------------------------------------- 
Example 3
Project: poker   Author: surgebiswas   File: c_spec.py    MIT License 6 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        self.type_name = 'complex'
        self.check_func = 'PyComplex_Check'
        self.c_type = 'std::complex<double>'
        self.return_type = 'std::complex<double>'
        self.to_c_return = "std::complex<double>(PyComplex_RealAsDouble(py_obj),"\
                                                "PyComplex_ImagAsDouble(py_obj))"
        self.matching_types = [types.ComplexType]

#----------------------------------------------------------------------------
#
# List, Tuple, and Dict converters.
#
# Based on SCXX by Gordon McMillan
#---------------------------------------------------------------------------- 
Example 4
Project: senior-design   Author: james-tate   File: ma.py    GNU General Public License v2.0 6 votes vote down vote up
def default_fill_value (obj):
    "Function to calculate default fill value for an object."
    if isinstance(obj, types.FloatType):
        return default_real_fill_value
    elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType):
        return default_integer_fill_value
    elif isinstance(obj, types.StringType):
        return default_character_fill_value
    elif isinstance(obj, types.ComplexType):
        return default_complex_fill_value
    elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
        x = obj.dtype.char
        if x in typecodes['Float']:
            return default_real_fill_value
        if x in typecodes['Integer']:
            return default_integer_fill_value
        if x in typecodes['Complex']:
            return default_complex_fill_value
        if x in typecodes['Character']:
            return default_character_fill_value
        if x in typecodes['UnsignedInteger']:
            return umath.absolute(default_integer_fill_value)
        return default_object_fill_value
    else:
        return default_object_fill_value 
Example 5
Project: xuemc   Author: skycucumber   File: Utility.py    GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, key):
        NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
        if isinstance(key, NumberTypes):
            return self.list[key]
        return self.data[key] 
Example 6
Project: SUMO_dy_public   Author: DayuanTan   File: classman.py    GNU General Public License v3.0 5 votes vote down vote up
def format_value(self, _id, show_unit=False, show_parentesis=False):
        if show_unit:
            unit = ' ' + self.format_unit(show_parentesis)
        else:
            unit = ''
        # return repr(self[_id])+unit

        #self.min = minval
        #self.max = maxval
        #self.digits_integer = digits_integer
        #self.digits_fraction = digits_fraction
        val = self[_id]
        tt = type(val)

        if tt in (types.LongType, types.IntType):
            return str(val) + unit

        elif tt in (types.FloatType, types.ComplexType):
            if hasattr(attrconf, 'digits_fraction'):
                digits_fraction = self.digits_fraction
            else:
                digits_fraction = 3
            return "%." + str(digits_fraction) + "f" % (val) + unit

        else:
            return str(val) + unit

        # return str(self[_id])+unit 
Example 7
Project: neurotools   Author: michaelerule   File: closure.py    GNU General Public License v3.0 5 votes vote down vote up
def is_probably_safe(x):
    '''
    Objects are probably "safe" (unlikly to change) if they are
    -- immutable
    -- functions
    -- modules
    Obviously, the latter two may change, but in practice it is likely
    ok. Still, risky!
    '''
    if is_immutable(x): return True
    if sys.version_info > (3,):
        probably_fine = (\
            types.LambdaType,
            types.BuiltinMethodType,
            types.BuiltinFunctionType,
            types.FunctionType,
            types.ModuleType,
            types.MethodType)
    else:
        probably_fine = (\
            types.LambdaType,
            types.InstanceType,
            types.NoneType,
            types.NotImplementedType,
            types.TypeType,
            types.UnicodeType,
            types.ComplexType,
            types.ClassType,
            types.BuiltinMethodType,
            types.BuiltinFunctionType,
            types.FunctionType,
            types.ModuleType,
            types.MethodType)

    if type(x) in probably_fine: return True
    if hasattr(x,'__call__'): return True
    return False 
Example 8
Project: pyx   Author: pyx-project   File: mathutils.py    GNU General Public License v2.0 4 votes vote down vote up
def realpolyroots(*cs):
    r"""returns the roots of a polynom with given coefficients

    polynomial with coefficients given in cs:
      0 = \sum_i  cs[i] * x^(len(cs)-i-1)
    """
    if not cs:
        return [0]
    try:
        f = 1.0/cs[0]
        cs = [f*c for c in cs[1:]]
    except ArithmeticError:
        return realpolyroots(*cs[1:])
    else:
        n = len(cs)
        if n == 0:
            return []
        elif n == 1:
            return [-cs[0]]
        elif n == 2:
            return _realroots_quadratic(*cs)
        elif n == 3:
            return _realroots_cubic(*cs)
        elif n == 4:
            return _realroots_quartic(*cs)
        else:
            raise RuntimeError("realpolyroots solver currently limited to polynoms up to the power of 4")


# def realpolyroots_eigenvalue(*cs):
#     # as realpolyroots but using an equivalent eigenvalue problem
#     # (this code is currently used for functional tests only)
#     if not _has_numeric:
#         raise RuntimeError("realpolyroots_eigenvalue depends on Numeric")
#     if not cs:
#         return [0]
#     try:
#         f = 1.0/cs[0]
#         cs = [f*c for c in cs[1:]]
#     except ArithmeticError:
#         return realpolyroots_eigenvalue(*cs[1:])
#     else:
#         if not cs:
#             return []
#         n = len(cs)
#         a = Numeric.zeros((n, n), Numeric.Float)
#         for i in range(n-1):
#             a[i+1][i] = 1
#         for i in range(n):
#             a[0][i] = -cs[i]
#         rs = []
#         for r in LinearAlgebra.eigenvalues(a):
#             if type(r) == types.ComplexType:
#                 if not r.imag:
#                     rs.append(r.real)
#             else:
#                 rs.append(r)
#         return rs
# 
Example 9
Project: SUMO_dy_public   Author: DayuanTan   File: objpanel.py    GNU General Public License v3.0 4 votes vote down vote up
def SetValue(self, row, col, value):
        """
        Transfer of cell value to object.
        """
        id, attrconf = self.get_id_attrconf(row, col)
        if attrconf != None:
            if attrconf.is_writable():
                # print 'SetValue(%d, %d, "%s").\n' % (row, col, value)

                # print '    attrconf',id,attrconf.attrname, attrconf.is_writable(),hasattr(attrconf,'choices')
                # attr=self.attrs[col]
                tt = type(attrconf.get_default())
                if hasattr(attrconf, 'choices'):
                    # print '
                    # type(attrconf.choices)',type(attrconf.choices),type(attrconf.choices)
                    # in (OrderedDict, types.DictionaryType)
                    # (types.ListType, types.TupleType):
                    if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
                        # print '  set choices[value]',attrconf.choices[value]
                        if attrconf.choices.has_key(value):
                            attrconf[id] = attrconf.choices[value]
                        else:
                            attrconf[id] = value

                    else:
                        # print '  set value',value
                        attrconf[id] = value

                if (tt in (types.BooleanType, types.FloatType, types.IntType, types.LongType, types.StringType, types.UnicodeType, types.ComplexType)):
                    # set only values of types that are allowed for the grid
                    # TODO: this grid types data must be organized more central
                    attrconf[id] = value
                else:
                    # TODO: for other types, like color or arrays, this must be
                    # done beforehand
                    print 'WARNING in SetValue: cannot write to this type:', tt
            else:
                # readonly
                pass
                # print 'SetValue(%d, %d, "%s") read only.\n' % (row, col,
                # value)

#--------------------------------------------------
    # Some optional methods

    # Called when the grid needs to display labels 
Example 10
Project: SUMO_dy_public   Author: DayuanTan   File: results.py    GNU General Public License v3.0 4 votes vote down vote up
def import_sumoxml(self, filepath, attrconfigs):
        element = 'tripinfo'
        # print 'import_sumoxml',element
        #id_type = 'edge',
        #reader = 'interval',

        ids_raw, results, interval = read_interval2(
            filepath, element, attrconfigs)

        # this procedure is necessary to create new result ids only
        # for trips that are not yet in the database
        n = len(ids_raw)
        # print '  n',n
        ind_range = np.arange(n, dtype=np.int32)
        ids = np.zeros(n, dtype=np.int32)
        for i in ind_range:
            id_trip = int(ids_raw[i])
            if self.ids_trip.has_index(id_trip):
                ids[i] = self.ids_trip.get_id_from_index(id_trip)
            else:
                ids[i] = self.add_row(ids_trip=id_trip)

        for attrconfig in attrconfigs:
            attrname = attrconfig.attrname
            default = attrconfig.get_default()
            if type(default) in (types.IntType, types.LongType):
                conversion = 'i'  # int
                values_attr = np.zeros(n, int)
            elif type(default) in (types.FloatType, types.ComplexType):
                conversion = 'f'  # float
                values_attr = np.zeros(n, float)
            else:
                conversion = 's'  # str
                values_attr = np.zeros(n, obj)

            # this is a tricky way to read the data stored in
            # dictionarie into array tructures as used in results
            # problem is that not all dictionaries have all ids
            for i in ind_range:
                val = results[attrname].get(ids_raw[i], default)

                if conversion == 'i':
                    val = int(val)
                else:
                    values_attr[i] = val
                # print '   attrname',attrname,conversion,val,type(val)
                values_attr[i] = val

            # print '  attrname',attrname
            # print '  ids',type(ids),ids
            # print '  values_attr',type(values_attr),values_attr
            attrconfig.set(ids, values_attr) 
Example 11
Project: OpenRAM   Author: VLSIDA   File: mathutils.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def realpolyroots(*cs):
    """returns the roots of a polynom with given coefficients

    polynomial with coefficients given in cs:
      0 = \sum_i  cs[i] * x^(len(cs)-i-1)
    """
    if not cs:
        return [0]
    try:
        f = 1.0/cs[0]
        cs = [f*c for c in cs[1:]]
    except ArithmeticError:
        return realpolyroots(*cs[1:])
    else:
        n = len(cs)
        if n == 0:
            return []
        elif n == 1:
            return [-cs[0]]
        elif n == 2:
            return _realroots_quadratic(*cs)
        elif n == 3:
            return _realroots_cubic(*cs)
        elif n == 4:
            return _realroots_quartic(*cs)
        else:
            raise RuntimeError("realpolyroots solver currently limited to polynoms up to the power of 4")


# def realpolyroots_eigenvalue(*cs):
#     # as realpolyroots but using an equivalent eigenvalue problem
#     # (this code is currently used for functional tests only)
#     if not _has_numeric:
#         raise RuntimeError("realpolyroots_eigenvalue depends on Numeric")
#     if not cs:
#         return [0]
#     try:
#         f = 1.0/cs[0]
#         cs = [f*c for c in cs[1:]]
#     except ArithmeticError:
#         return realpolyroots_eigenvalue(*cs[1:])
#     else:
#         if not cs:
#             return []
#         n = len(cs)
#         a = Numeric.zeros((n, n), Numeric.Float)
#         for i in range(n-1):
#             a[i+1][i] = 1
#         for i in range(n):
#             a[0][i] = -cs[i]
#         rs = []
#         for r in LinearAlgebra.eigenvalues(a):
#             if type(r) == types.ComplexType:
#                 if not r.imag:
#                     rs.append(r.real)
#             else:
#                 rs.append(r)
#         return rs
#