Ejemplo n.º 1
0
    def __init__(self, left, right, op):
        from .data import ComponentID

        self._left = left
        self._right = right
        self._op = op

        from_ = []
        if isinstance(left, ComponentID):
            from_.append(left)
        elif isinstance(left, ComponentLink):
            from_.extend(left.get_from_ids())
        elif not operator.isNumberType(left):
            raise TypeError("Cannot create BinaryComponentLink using %s" %
                            left)

        if isinstance(right, ComponentID):
            from_.append(right)
        elif isinstance(right, ComponentLink):
            from_.extend(right.get_from_ids())
        elif not operator.isNumberType(right):
            raise TypeError("Cannot create BinaryComponentLink using %s" %
                            right)

        to = ComponentID("")
        null = lambda *args: None
        super(BinaryComponentLink, self).__init__(from_, to, null)
Ejemplo n.º 2
0
    def _writeRecord(self, record):
        if not self.isInitialized(): return

        vals = []

        for colname in self.labels:
            val = record.data.get(colname)
            if (not val is None) and (operator.isNumberType(val) and (type(val) in [int, float, long])):
                vals.append(val)
            elif (not val is None) and (operator.isNumberType(val)):
                valsmca = []
                for i in range(0, len(val)):
                    valsmca.append(val[i])
                sufix = "1D"
                if self.array.endswith(sufix):
                    valsmca = numpy.array(valsmca)
                    self.sps.putdatarow(self.program, self.array, record.recordno, valsmca)

        sufix = "0D"
        if self.array.endswith(sufix):
            vals = numpy.array(vals)
            self.sps.putdatarow(self.program, self.array, record.recordno, vals)

        self.nopts += 1

        env = {   'nopts' : self.nopts,
                   'peak' : 111,
                'peakpos' : 34,
                   'fwhm' : 12.3,
                'fwhmpos' : 45,
                    'com' : 23 }

        self.putAllEnv(env)
Ejemplo n.º 3
0
Archivo: shelx.py Proyecto: wojdyr/coot
    def do_gui(disagreeable_restraints_list, interesting_list):
        #print "BL DEBUG:: DR: ", disagreeable_restraints_list

        dis_res_button_list = []
        for dr_list in disagreeable_restraints_list:

            restraint_type = dr_list[4]
            drl_dict = {"BUMP": 0, "DANG": 0, "FLAT": 0, "SIMU": 1, "ISOR": 1}
            if (drl_dict.has_key(restraint_type)):
                drl_index = drl_dict[restraint_type]
            else:
                drl_index = 0
            atom_parts = make_atom_parts(dr_list[5][drl_index])
            stats_string = "not sure what?"
            n2 = dr_list[2]
            n3 = dr_list[3]
            if (operator.isNumberType(n2) and operator.isNumberType(n3)
                    and (n2 <> 0)):
                z = n3 / abs(n2)
                stats_string = " " + str(n2) + " [Z=" + str(z) + "]"
            else:
                stats_string = ""
            if (drl_index == 0):
                rt = restraint_type + " "
            else:
                rt = restraint_type + " " + dr_list[5][0]
            button_label = "Disagreeable Restraint " + rt + " " + atom_parts[0] + " " + \
                           str(atom_parts[1]) + " " + atom_parts[3] + stats_string
            interesting_thing = [button_label, imol] + atom_parts
            dis_res_button_list.append(interesting_thing)

        gui_interesting_list(interesting_list + dis_res_button_list)
Ejemplo n.º 4
0
def get_cuts(cuts):
    """ Convert `cuts` argument to vector_double type.

    Argument can be None, a number or a sequence of numbers. If None, there is
    only one cut at 0.5. If `cuts` is a number, function returns a vector_double
    with that number as a single element. If its a sequence, that sequence will
    be converted to vector_double type.

    Parameters
    ----------
    cuts : None, number or sequence of numbers
        Cut values

    Returns
    -------
    cuts : vector_double
        Cut values.

    Raises
    ------
    TypeError
        If `cuts` is not None, a number or a sequence of numbers.

    """
    if cuts is None:
        return sfr.vector_double([0.5])
    elif op.isSequenceType(cuts) and np.array([op.isNumberType(a) for a in cuts]).all():
        return sfr.vector_double(cuts)
    elif op.isNumberType(cuts):
        return sfr.vector_double([cuts])
    else:
        raise TypeError("'cuts' must be either None, a number or a " + "sequence of numbers.")
Ejemplo n.º 5
0
 def test_isNumberType(self):
     self.failUnlessRaises(TypeError, operator.isNumberType)
     self.failUnless(operator.isNumberType(8))
     self.failUnless(operator.isNumberType(8j))
     self.failUnless(operator.isNumberType(8L))
     self.failUnless(operator.isNumberType(8.3))
     self.failIf(operator.isNumberType(dir()))
Ejemplo n.º 6
0
    def __init__(self, left, right, op):
        from .data import ComponentID

        self._left = left
        self._right = right
        self._op = op

        from_ = []
        if isinstance(left, ComponentID):
            from_.append(left)
        elif isinstance(left, ComponentLink):
            from_.extend(left.get_from_ids())
        elif not operator.isNumberType(left):
            raise TypeError("Cannot create BinaryComponentLink using %s" %
                            left)

        if isinstance(right, ComponentID):
            from_.append(right)
        elif isinstance(right, ComponentLink):
            from_.extend(right.get_from_ids())
        elif not operator.isNumberType(right):
            raise TypeError("Cannot create BinaryComponentLink using %s" %
                            right)

        to = ComponentID("")
        null = lambda *args: None
        super(BinaryComponentLink, self).__init__(from_, to, null)
Ejemplo n.º 7
0
    def do_gui(disagreeable_restraints_list, interesting_list):
	#print "BL DEBUG:: DR: ", disagreeable_restraints_list

	dis_res_button_list = []
	for dr_list in disagreeable_restraints_list:

            restraint_type = dr_list[4]
            drl_dict = {"BUMP": 0, "DANG": 0, "FLAT": 0,
                        "SIMU": 1, "ISOR": 1}
            if (drl_dict.has_key(restraint_type)):
                drl_index = drl_dict[restraint_type]
            else:
                drl_index = 0
            atom_parts = make_atom_parts(dr_list[5][drl_index])
            stats_string = "not sure what?"
            n2 = dr_list[2]
            n3 = dr_list[3]
            if (operator.isNumberType(n2) and operator.isNumberType(n3) and (n2 <> 0)):
                z = n3 / abs(n2)
                stats_string = " " + str(n2) + " [Z=" + str(z) +"]"
            else:
                stats_string = ""
            if (drl_index == 0):
                rt = restraint_type + " "
            else:
                rt = restraint_type + " " + dr_list[5][0]
            button_label = "Disagreeable Restraint " + rt + " " + atom_parts[0] + " " + \
                           str(atom_parts[1]) + " " + atom_parts[3] + stats_string
            interesting_thing = [button_label, imol] + atom_parts
            dis_res_button_list.append(interesting_thing)

	gui_interesting_list(interesting_list + dis_res_button_list)
 def test_isNumberType(self):
     self.failUnlessRaises(TypeError, operator.isNumberType)
     self.failUnless(operator.isNumberType(8))
     self.failUnless(operator.isNumberType(8j))
     self.failUnless(operator.isNumberType(8))
     self.failUnless(operator.isNumberType(8.3))
     self.failIf(operator.isNumberType(dir()))
Ejemplo n.º 9
0
    def __setitem__(self, index, W):
        """
        Speed-up if x is a sparse matrix.
        TODO: checks (first remove the data).
        TODO: once we've got this working in all cases, should we submit to scipy?
        """
        try:
            i, j = index
        except (ValueError, TypeError):
            raise IndexError, "invalid index"

        if isinstance(i, slice) and isinstance(j, slice) and\
               (i.step is None) and (j.step is None) and\
               (isinstance(W, sparse.lil_matrix) or isinstance(W, numpy.ndarray)):
            rows = self.rows[i]
            datas = self.data[i]
            j0 = j.start
            if isinstance(W, sparse.lil_matrix):
                for row, data, rowW, dataW in izip(rows, datas, W.rows,
                                                   W.data):
                    jj = bisect.bisect(row, j0)  # Find the insertion point
                    row[jj:jj] = [j0 + k for k in rowW]
                    data[jj:jj] = dataW
            elif isinstance(W, ndarray):
                nq = W.shape[1]
                for row, data, rowW in izip(rows, datas, W):
                    jj = bisect.bisect(row, j0)  # Find the insertion point
                    row[jj:jj] = range(j0, j0 + nq)
                    data[jj:jj] = rowW
        elif isinstance(i, int) and isinstance(j,
                                               (list, tuple, numpy.ndarray)):
            if len(j) == 0:
                return
            row = dict(izip(self.rows[i], self.data[i]))
            try:
                row.update(dict(izip(j, W)))
            except TypeError:
                row.update(dict(izip(j, itertools.repeat(W))))
            items = row.items()
            items.sort()
            row, data = izip(*items)
            self.rows[i] = list(row)
            self.data[i] = list(data)
        elif isinstance(i, slice) and isinstance(j, int) and isSequenceType(W):
            # This corrects a bug in scipy sparse matrix as of version 0.7.0, but
            # it is not efficient!
            for w, k in izip(W, xrange(*i.indices(self.shape[0]))):
                sparse.lil_matrix.__setitem__(self, (k, j), w)
        elif isinstance(i, int) and isinstance(
                j, slice) and (isNumberType(W) and not isSequenceType(W)):
            # this fixes a bug in scipy 0.7.1
            sparse.lil_matrix.__setitem__(
                self, index, [W] * len(xrange(*j.indices(self.shape[1]))))
        elif isinstance(i, slice) and isinstance(j, slice) and isNumberType(W):
            n = len(xrange(*i.indices(self.shape[0])))
            m = len(xrange(*j.indices(self.shape[1])))
            sparse.lil_matrix.__setitem__(self, index, W * numpy.ones((n, m)))
        else:
            sparse.lil_matrix.__setitem__(self, index, W)
Ejemplo n.º 10
0
 def compute(self, data, view=None):
     l = self._left
     r = self._right
     if not operator.isNumberType(self._left):
         l = data[self._left, view]
     if not operator.isNumberType(self._right):
         r = data[self._right, view]
     return self._op(l, r)
Ejemplo n.º 11
0
 def compute(self, data, view=None):
     l = self._left
     r = self._right
     if not operator.isNumberType(self._left):
         l = data[self._left, view]
     if not operator.isNumberType(self._right):
         r = data[self._right, view]
     return self._op(l, r)
Ejemplo n.º 12
0
    def __setitem__(self, index, W):
        """
        Speed-up if x is a sparse matrix.
        TODO: checks (first remove the data).
        TODO: once we've got this working in all cases, should we submit to scipy?
        """
        try:
            i, j = index
        except (ValueError, TypeError):
            raise IndexError, "invalid index"

        if isinstance(i, slice) and isinstance(j, slice) and\
               (i.step is None) and (j.step is None) and\
               (isinstance(W, sparse.lil_matrix) or isinstance(W, numpy.ndarray)):
            rows = self.rows[i]
            datas = self.data[i]
            j0 = j.start
            if isinstance(W, sparse.lil_matrix):
                for row, data, rowW, dataW in izip(rows, datas, W.rows, W.data):
                    jj = bisect.bisect(row, j0) # Find the insertion point
                    row[jj:jj] = [j0 + k for k in rowW]
                    data[jj:jj] = dataW
            elif isinstance(W, ndarray):
                nq = W.shape[1]
                for row, data, rowW in izip(rows, datas, W):
                    jj = bisect.bisect(row, j0) # Find the insertion point
                    row[jj:jj] = range(j0, j0 + nq)
                    data[jj:jj] = rowW
        elif isinstance(i, int) and isinstance(j, (list, tuple, numpy.ndarray)):
            if len(j) == 0:
                return
            row = dict(izip(self.rows[i], self.data[i]))
            try:
                row.update(dict(izip(j, W)))
            except TypeError:
                row.update(dict(izip(j, itertools.repeat(W))))
            items = row.items()
            items.sort()
            row, data = izip(*items)
            self.rows[i] = list(row)
            self.data[i] = list(data)
        elif isinstance(i, slice) and isinstance(j, int) and isSequenceType(W):
            # This corrects a bug in scipy sparse matrix as of version 0.7.0, but
            # it is not efficient!
            for w, k in izip(W, xrange(*i.indices(self.shape[0]))):
                sparse.lil_matrix.__setitem__(self, (k, j), w)
        elif isinstance(i, int) and isinstance(j, slice) and (isNumberType(W) and not isSequenceType(W)):
            # this fixes a bug in scipy 0.7.1
            sparse.lil_matrix.__setitem__(self, index, [W] * len(xrange(*j.indices(self.shape[1]))))
        elif isinstance(i, slice) and isinstance(j, slice) and isNumberType(W):
            n = len(xrange(*i.indices(self.shape[0])))
            m = len(xrange(*j.indices(self.shape[1])))
            sparse.lil_matrix.__setitem__(self, index, W * numpy.ones((n, m)))
        else:
            sparse.lil_matrix.__setitem__(self, index, W)
Ejemplo n.º 13
0
    def to_mask(self, data, view=None):
        from .data import ComponentID
        left = self._left
        if not operator.isNumberType(self._left):
            left = data[self._left, view]

        right = self._right
        if not operator.isNumberType(self._right):
            right = data[self._right, view]

        return self._operator(left, right)
Ejemplo n.º 14
0
 def update_progress_bar(progress_bar):
     if file_name_for_progress_bar:
         curl_info = curl_progress_info(file_name_for_progress_bar)
         if curl_info:
             v1 = curl_info['content-length-download']
             v2 = curl_info['size-download']                        
             if operator.isNumberType(v1):
                 if operator.isNumberType(v2):
                     f = v2 / v1
                     #print "count %s, active_count %s, f: %s" %(count, active_count, f)
                     progress_bar.set_fraction(f)
Ejemplo n.º 15
0
    def to_mask(self, view=None):
        from .data import ComponentID
        left = self._left
        if not operator.isNumberType(self._left):
            left = self.parent.data[self._left, view]

        right = self._right
        if not operator.isNumberType(self._right):
            right = self.parent.data[self._right, view]

        return self._operator(left, right)
Ejemplo n.º 16
0
def _load_anat(anat_img=MNI152TEMPLATE, dim=False, black_bg='auto'):
    """ Internal function used to load anatomy, for optional diming
    """
    vmin = None
    vmax = None
    if anat_img is not False and anat_img is not None:
        if anat_img is MNI152TEMPLATE:
            anat_img.load()
            # We special-case the 'canonical anat', as we don't need
            # to do a few transforms to it.
            vmin = 0
            vmax = anat_img.vmax
            if black_bg == 'auto':
                black_bg = False
        else:
            anat_img = _utils.check_niimg(anat_img, ensure_3d=True)
            if dim or black_bg == 'auto':
                # We need to inspect the values of the image
                data = anat_img.get_data()
                vmin = data.min()
                vmax = data.max()
            if black_bg == 'auto':
                # Guess if the background is rather black or light based on
                # the values of voxels near the border
                border_size = 2
                border_data = np.concatenate([
                        data[:border_size, :, :].ravel(),
                        data[-border_size:, :, :].ravel(),
                        data[:, :border_size, :].ravel(),
                        data[:, -border_size:, :].ravel(),
                        data[:, :, :border_size].ravel(),
                        data[:, :, -border_size:].ravel(),
                    ])
                background = np.median(border_data)
                if background > .5 * (vmin + vmax):
                    black_bg = False
                else:
                    black_bg = True
        if dim:
            vmean = .5 * (vmin + vmax)
            ptp = .5 * (vmax - vmin)
            if black_bg:
                if not operator.isNumberType(dim):
                    dim = .8
                vmax = vmean + (1 + dim) * ptp
            else:
                if not operator.isNumberType(dim):
                    dim = .6
                vmin = vmean - (1 + dim) * ptp
    if black_bg == 'auto':
        # No anatomy given: no need to turn black_bg on
        black_bg = False
    return anat_img, black_bg, vmin, vmax
Ejemplo n.º 17
0
    def test_isXxxType_more(self):
        import operator

        assert not operator.isSequenceType(list)
        assert not operator.isSequenceType(dict)
        assert not operator.isSequenceType({})
        assert not operator.isMappingType(list)
        assert not operator.isMappingType(dict)
        assert not operator.isMappingType([])
        assert not operator.isMappingType(())
        assert not operator.isNumberType(int)
        assert not operator.isNumberType(float)
Ejemplo n.º 18
0
    def test_isXxxType_more(self):
        import operator

        assert not operator.isSequenceType(list)
        assert not operator.isSequenceType(dict)
        assert not operator.isSequenceType({})
        assert not operator.isMappingType(list)
        assert not operator.isMappingType(dict)
        assert not operator.isMappingType([])
        assert not operator.isMappingType(())
        assert not operator.isNumberType(int)
        assert not operator.isNumberType(float)
Ejemplo n.º 19
0
def _load_anat(anat_img=MNI152TEMPLATE, dim=False, black_bg='auto'):
    """ Internal function used to load anatomy, for optional diming
    """
    vmin = None
    vmax = None
    if anat_img is not False and anat_img is not None:
        if anat_img is MNI152TEMPLATE:
            anat_img.load()
            # We special-case the 'canonical anat', as we don't need
            # to do a few transforms to it.
            vmin = 0
            vmax = anat_img.vmax
            if black_bg == 'auto':
                black_bg = False
        else:
            anat_img = _utils.check_niimg(anat_img, ensure_3d=True)
            if dim or black_bg == 'auto':
                # We need to inspect the values of the image
                data = anat_img.get_data()
                vmin = data.min()
                vmax = data.max()
            if black_bg == 'auto':
                # Guess if the background is rather black or light based on
                # the values of voxels near the border
                border_size = 2
                border_data = np.concatenate([
                        data[:border_size, :, :].ravel(),
                        data[-border_size:, :, :].ravel(),
                        data[:, :border_size, :].ravel(),
                        data[:, -border_size:, :].ravel(),
                        data[:, :, :border_size].ravel(),
                        data[:, :, -border_size:].ravel(),
                    ])
                background = np.median(border_data)
                if background > .5 * (vmin + vmax):
                    black_bg = False
                else:
                    black_bg = True
        if dim:
            vmean = .5 * (vmin + vmax)
            ptp = .5 * (vmax - vmin)
            if black_bg:
                if not operator.isNumberType(dim):
                    dim = .8
                vmax = vmean + (1 + dim) * ptp
            else:
                if not operator.isNumberType(dim):
                    dim = .6
                vmin = vmean - (1 + dim) * ptp
    if black_bg == 'auto':
        # No anatomy given: no need to turn black_bg on
        black_bg = False
    return anat_img, black_bg, vmin, vmax
Ejemplo n.º 20
0
 def getDataMembers(self, obj, objName, tab = " "):
   import operator
   if operator.isNumberType(obj):
     #print "Attribute name = ", objName, ", value = ", obj
     print(tab, objName, " = ", obj)
   else:
     objType = type(obj)
     # If Object is a method, replace obj with the result of the method
     if objType.__name__ == 'MethodProxy':
       try:
         obj = obj()
         objType = type(obj)
       # Exception is thrown for functions that take arguments. We
       # ignore them for the moment. It may be that there are two
       # methods, one providing access to individual values, and
       # another giving a whole vector of values.
       except:
         pass
       if operator.isNumberType(obj):
         print("obj type = ",objType.__name__)
         #print "Attribute name = ", objName, ", value = ", obj
         print(tab, objName, " = ", obj)
         return
     print("obj type =",objType.__name__)
     # Is this a vector?
     isVector = False
     if objType.__name__.find('vector') == 0:
       isVector = True
     elif hasattr(obj,'begin') and hasattr(obj,'end') and hasattr(obj,'size'):
       isVector = True
     # If a vector, loop over elements and print each one out
     if isVector:
       i = 0
       newTab = tab + " "
       for o in obj:
         self.getDataMembers(o, objName + '_' + str(i), newTab)
         i += 1
     # Assume a complex type, loop over attributes and print them out
     else:
       attrNames = dir(obj)
       #print ("found attributes:",attrNames)
       newTab = tab + " "
       for attrName in attrNames:
         # Select attributes that begin with m_ or get
         if attrName.find("m_") == 0 or attrName.find("get") == 0:
           try:
             attr = getattr(obj, attrName)
           except:
             print("Could not get attr", attrName)
           self.getDataMembers(attr, attrName, newTab)
Ejemplo n.º 21
0
 def __rpow__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return Vec2(None, (ox**vx, oy**vy))
Ejemplo n.º 22
0
 def __mul__(self, val):
     if not operator.isNumberType(val):
         raise TypeError
     
     return AffineTransform( self.obj,
                             self.a * val,
                             self.b * val   )
Ejemplo n.º 23
0
def check_sampling(sampling, n):
    if sampling is None:
        sampling = 1.0
    if operator.isNumberType(sampling):
        sampling = SplitSampling(n, evaluation_fraction=sampling)

    return sampling
Ejemplo n.º 24
0
 def _readline(self, line):
     """
     Convert the pseudocode into a list of commands.
     The block associated with the command is stored as the second element
     in a tuple, e.g., (#forward, 16)
     """
     # debug_output(line, self.tw.running_sugar)
     res = []
     while line:
         token = line.pop(0)
         bindex = None
         if isinstance(token, tuple):
             (token, bindex) = token
         if isNumberType(token):
             res.append(token)
         elif token.isdigit():
             res.append(float(token))
         elif token[0] == '-' and token[1:].isdigit():
             res.append(-float(token[1:]))
         elif token[0] == '"':
             res.append(token[1:])
         elif token[0:2] == "#s":
             res.append(token[2:])
         elif token == '[':
             res.append(self._readline(line))
         elif token == ']':
             return res
         elif bindex is None or not isinstance(bindex, int):
             res.append(self._intern(token))
         else:
             res.append((self._intern(token), bindex))
     return res
Ejemplo n.º 25
0
 def __rpow__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return Vec2(None, (ox ** vx, oy ** vy))
Ejemplo n.º 26
0
 def __rmod__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return ox * vy - oy * vx
Ejemplo n.º 27
0
    def __imul__(self, val):
        if not operator.isNumberType(val):
            raise TypeError

        self.a *= val
        self.b *= val
        return self
Ejemplo n.º 28
0
 def __rpow__(self, other):
     vx, vy, vz = self.__vec3__
     if isNumberType(other):
         ox = oy = oz = other
     else:
         ox, oy, oz = getattr(other, "__vec3__", other)
     return Vec3((ox**vx, oy**vy, oz**vz), _InternalCall)
Ejemplo n.º 29
0
def isfloat(f):
    if not operator.isNumberType(f):
        return 0
    if f % 1:
        return 1
    else:
        return 0
def check_sampling(sampling, n):
    if sampling is None:
        sampling = 1.0
    if operator.isNumberType(sampling):
        sampling = SplitSampling(n, evaluation_fraction=sampling)

    return sampling
Ejemplo n.º 31
0
 def __div__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return Vec2(None, (vx / ox, vy / oy))
Ejemplo n.º 32
0
    def __imul__(self, val):
        if not operator.isNumberType(val):
            raise TypeError

        self.a *= val
        self.b *= val
        return self
Ejemplo n.º 33
0
def isNumeric(obj):
    """
    Returns True if an object is a number type, otherwise returns False.

    :rtype: bool
    """
    return operator.isNumberType(obj)
Ejemplo n.º 34
0
 def __pow__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         return Vec2(None, (vx * other, vy * other))
     else:
         ox, oy = getattr(other, "__vec2__", other)
         return Vec2(None, (vx**ox, vy**oy))
Ejemplo n.º 35
0
 def __pow__(self, other):
     vx, vy, vz = self.__vec3__
     if isNumberType(other):
         return Vec3((vx * other, vy * other), _InternalCall)
     else:
         ox, oy = getattr(other, "__vec2__", other)
         return Vec3((vx**ox, vy**oy, vz**oz), _InternalCall)
Ejemplo n.º 36
0
 def __rmod__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return ox * vy - oy * vx
Ejemplo n.º 37
0
 def getFlatHeader(self):
     r = {}
     for k, v in sorted(self.header.iteritems(), key=itemgetter(0)):
         if isinstance(v, dict):
             for k1, v1 in sorted(v.iteritems(), key=itemgetter(0)):
                 if isinstance(v1, dict):
                     for k2, v2 in sorted(v1.iteritems(),
                                          key=itemgetter(0)):
                         r[k2.upper()] = v2 if isNumberType(v2) else str(
                             v2).upper().strip()
                 else:
                     r[k1.upper()] = v1 if isNumberType(v1) else str(
                         v1).upper().strip()
         else:
             r[k.upper()] = v if isNumberType(v) else str(v).upper().strip()
     return r
Ejemplo n.º 38
0
def check_cv(cv, X=None, y=None, classifier=False):
    """Creates a valid and usable cv generator

    Parameters
    ===========
    cv: an integer, a cv generator instance, or None
        The input specifying which cv generator to use. It can be an 
        integer, in which case it is the number of folds in a KFold,
        None, in which case 3 fold is used, or another object, that
        will then be used as a cv generator.
    X: 2D ndarray
        the data the cross-val object will be applied on
    y: 1D ndarray
        the target variable for a supervised learning problem
    classifier: boolean optional
        whether the task is a classification task, in which case 
        stratified KFold will be used.
    """
    if cv is None:
        cv = 3
    if operator.isNumberType(cv):
        is_sparse = hasattr(X, 'tocsr')
        if classifier:
            cv = StratifiedKFold(y, cv, indices=is_sparse)
        else:
            if not is_sparse:
                n_samples = len(X)
            else:
                n_samples = X.shape[0]
            cv = KFold(n_samples, cv, indices=is_sparse)
    return cv
Ejemplo n.º 39
0
def _check_input_times(times):

    issequence = False
    if isSequenceType(times):
        ## Here assume sequence contains
        ## elements of same type.
        test_tm = times[0]
        issequence = True
    else:
        test_tm = times

    if not issequence:
        times = [times]

    if isinstance(test_tm, datetime.datetime):
        tticks = map(ticks, times)
        tticks = array(tticks, float)
    elif isNumberType(test_tm):
        tticks = array(times, float)
    else:
        raise TypeError("Second input for interpolation functions" \
        " must be list/array of number or datatime, or single" \
        " number or datetime")

    return tticks
Ejemplo n.º 40
0
 def __mul__(self, other):
     vx, vy, vz = self.__vec3__
     if isNumberType(other):
         ox = oy = oz = other
     else:
         ox, oy, oz = getattr(other, "__vec3__", other)
     return Vec3((vx * ox, vy * oy, vz * oz), _InternalCall)
Ejemplo n.º 41
0
 def _readline(self, line):
     """
     Convert the pseudocode into a list of commands.
     The block associated with the command is stored as the second element
     in a tuple, e.g., (#forward, 16)
     """
     # debug_output(line, self.tw.running_sugar)
     res = []
     while line:
         token = line.pop(0)
         bindex = None
         if isinstance(token, tuple):
             (token, bindex) = token
         if isNumberType(token):
             res.append(token)
         elif token.isdigit():
             res.append(float(token))
         elif token[0] == '-' and token[1:].isdigit():
             res.append(-float(token[1:]))
         elif token[0] == '"':
             res.append(token[1:])
         elif token[0:2] == "#s":
             res.append(token[2:])
         elif token == '[':
             res.append(self._readline(line))
         elif token == ']':
             return res
         elif bindex is None or not isinstance(bindex, int):
             res.append(self._intern(token))
         else:
             res.append((self._intern(token), bindex))
     return res
Ejemplo n.º 42
0
 def __add__(self, other):
     # Order of testing is important!
     if isinstance(other, numpy.ndarray):
         # If adding sparse and dense, result is dense
         # rv = SparseVector( max( self.n, other.shape[0] ), {} )
         rv = numpy.zeros(max(self.n, other.shape[0]), "d")
         for k in range(other.shape[0]):
             rv[k] = other[k]
         for k in self.values.keys():
             rv[k] += self[k]
         return rv
     elif isSparseVector(other):
         rv = SparseVector(max(self.n, other.n), {})
         for k in self.values.keys():
             rv[k] += self[k]
         for k in other.values.keys():
             rv[k] += other[k]
         return rv
     elif operator.isNumberType(other):
         rv = SparseVector(self.n, {})
         for k in self.values.keys():
             rv[k] = self[k] + other
         return rv
     else:
         raise TypeError, "Cannot add with SparseVector"
Ejemplo n.º 43
0
 def __add__(self, val):
     if not operator.isNumberType(val):
         raise TypeError, type(val)
     
     return AffineTransform( self.obj,
                             self.a,
                             self.b + val   )
Ejemplo n.º 44
0
 def __floordiv__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = oz = other
     else:
         ox, oy, oz = getattr(other, "__vec3__", other)
     return Vec3((vx // ox, vy // oy, vz // oz), _InternalCall)
Ejemplo n.º 45
0
 def __rmod__(self, other):
     vx, vy, vz = self.__vec3__
     if isNumberType(other):
         ox = oy = oz = other
     else:
         ox, oy, oz = getattr(other, "__vec3__", other)
     return Vec3(vy * oz - vz * oy, vz * ox - vx * oz, vx * oy - vy * ox)
Ejemplo n.º 46
0
 def __rsub__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = oz = other
     else:
         ox, oy, oz = getattr(other, "__vec3__", other)
     return Vec2((ox - vx, oy - vy, oz - vz), _InternalCall)
Ejemplo n.º 47
0
def check_cv(cv, n):
    if cv is None:
        cv = 3
    if operator.isNumberType(cv):
        cv = KFold(n, cv, indices=True)

    return cv
Ejemplo n.º 48
0
def isfloat(f):
    if not operator.isNumberType(f):
        return 0
    if f % 1:
        return 1
    else:
        return 0
Ejemplo n.º 49
0
 def __rfloordiv__(self, other):
     vx, vy, vz = self.__vec3__
     if isNumberType(other):
         ox = oy = oz = other
     else:
         ox, oy, oz = getattr(other, "__vec3__", other)
     return Vec3((ox // vx, oy // vy, oz // vz), _InternalCall)
Ejemplo n.º 50
0
        def ok_button_event(*args):
            global pending_install_in_place
            import operator

            # only start when ok button is pressed
            gobject.timeout_add(500, idle_func) # update every 500ms is god enough?!
            if not operator.isNumberType(revision):
                info_dialog("Failed to communicate with server")
            else:
                # BL says:: check if we have a download available already?! (from before)
                if (version_string in get_latest_pending_version()):
                    # installer already here (win only?!)
                    pending_install_in_place = True
                else:
                    # download
                    ok_button.set_sensitive(False)
                    #align.show()
                    progress_bar.show()
                    cancel_button.show()
                    def threaded_func():
                        global pending_install_in_place
                        ret = run_download_binary_curl(revision, version_string,
                                                       pending_install_in_place_func,
                                                       set_file_name_func,
                                                       progress_bar,
                                                       use_curl)

                        if ((not ret) and
                            (not pending_install_in_place == "cancelled")):
                            print "run_download_binary_curl failed"
                            pending_install_in_place = "fail"

                    run_python_thread(threaded_func, [])
Ejemplo n.º 51
0
def check_cv(cv, X=None, y=None, classifier=False):
    """Input checker utility for building a CV in a user friendly way.

    Parameters
    ===========
    cv: an integer, a cv generator instance, or None
        The input specifying which cv generator to use. It can be an
        integer, in which case it is the number of folds in a KFold,
        None, in which case 3 fold is used, or another object, that
        will then be used as a cv generator.

    X: 2D ndarray
        the data the cross-val object will be applied on

    y: 1D ndarray
        the target variable for a supervised learning problem

    classifier: boolean optional
        whether the task is a classification task, in which case
        stratified KFold will be used.
    """
    if cv is None:
        cv = 3
    if operator.isNumberType(cv):
        is_sparse = hasattr(X, 'tocsr')
        if classifier:
            cv = StratifiedKFold(y, cv, indices=is_sparse)
        else:
            if not is_sparse:
                n_samples = len(X)
            else:
                n_samples = X.shape[0]
            cv = KFold(n_samples, cv, indices=is_sparse)
    return cv
Ejemplo n.º 52
0
 def __add__(self, other):
     # Order of testing is important!
     if isinstance(other, numpy.ndarray):
         # If adding sparse and dense, result is dense
         #rv = SparseVector( max( self.n, other.shape[0] ), {} )
         rv = numpy.zeros(max(self.n, other.shape[0]), 'd')
         for k in range(other.shape[0]):
             rv[k] = other[k]
         for k in self.values.keys():
             rv[k] += self[k]
         return rv
     elif isSparseVector(other):
         rv = SparseVector(max(self.n, other.n), {})
         for k in self.values.keys():
             rv[k] += self[k]
         for k in other.values.keys():
             rv[k] += other[k]
         return rv
     elif operator.isNumberType(other):
         rv = SparseVector(self.n, {})
         for k in self.values.keys():
             rv[k] = self[k] + other
         return rv
     else:
         raise TypeError, "Cannot add with SparseVector"
Ejemplo n.º 53
0
 def __div__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return Vec2(None, (vx / ox, vy / oy))
Ejemplo n.º 54
0
def isNumeric(obj):
    """
    Returns True if an object is a number type, otherwise returns False.

    :rtype: bool
    """
    return operator.isNumberType(obj)
Ejemplo n.º 55
0
 def __rfloordiv__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return Vec2(None, (ox // vx, oy // vy))
Ejemplo n.º 56
0
 def __pow__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         return Vec2(None, (vx * other, vy * other))
     else:
         ox, oy = getattr(other, "__vec2__", other)
         return Vec2(None, (vx ** ox, vy ** oy))
Ejemplo n.º 57
0
 def __rfloordiv__(self, other):
     vx, vy = self.__vec2__
     if isNumberType(other):
         ox = oy = other
     else:
         ox, oy = getattr(other, "__vec2__", other)
     return Vec2(None, (ox // vx, oy // vy))
Ejemplo n.º 58
0
 def validate(self, object, name, value):
     if value is None:
         return value
     elif operator.isNumberType(value):
         # Local import to avoid explicit dependency.
         import numpy
         value = numpy.atleast_1d(value)
     return super(ArrayNumberOrNone, self).validate(object, name, value)
Ejemplo n.º 59
0
def _getscaleoffset(expr):
    stub = ["stub"]
    data = expr(_E(stub)).data
    try:
        (a, b, c) = data # simplified syntax
        if (a is stub and b == "__mul__" and isNumberType(c)):
            return c, 0.0
        if (a is stub and b == "__add__" and isNumberType(c)):
            return 1.0, c
    except TypeError: pass
    try:
        ((a, b, c), d, e) = data # full syntax
        if (a is stub and b == "__mul__" and isNumberType(c) and
            d == "__add__" and isNumberType(e)):
            return c, e
    except TypeError: pass
    raise ValueError("illegal expression")
Ejemplo n.º 60
0
def chpri(search="", sortby=[], limit=None, priority=None):
    """Change priority of matching jobs.  priority= specifies the new priority."""
    if priority is None:
        raise TractorQueryError("chpri(): priority must be specified")
    if not operator.isNumberType(priority):
        raise TractorQueryError("chpri(): priority is not numeric")
    jids = _jidsForArgs(search, sortby, limit)
    ModuleEngineClient.setJobPriority(jids, priority)