Python math.floor() Examples

The following are 30 code examples of math.floor(). 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 math , or try the search function .
Example #1
Source File: GXDLMSExtendedRegister.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def getValue(self, settings, e):
        if e.index == 1:
            return _GXCommon.logicalNameToBytes(self.logicalName)
        if e.index == 2:
            return self.value
        if e.index == 3:
            data = GXByteBuffer()
            data.setUInt8(DataType.STRUCTURE)
            data.setUInt8(2)
            _GXCommon.setData(settings, data, DataType.INT8, math.floor(math.log(self.scaler, 10)))
            _GXCommon.setData(settings, data, DataType.ENUM, int(self.unit))
            return data.array()
        if e.index == 4:
            return self.status
        if e.index == 5:
            return self.captureTime
        e.error = ErrorCode.READ_WRITE_DENIED
        return None

    #
    #      Set value of given attribute.
    # 
Example #2
Source File: sand.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name, width, height, model_nm=None, props=None):
        super().__init__(name, width, height, torus=False,
                         model_nm=model_nm, postact=True, props=props)

        self.center_agent = None
        self.set_var_color('0', disp.BLACK)
        self.set_var_color('1', disp.MAGENTA)
        self.set_var_color('2', disp.BLUE)
        self.set_var_color('3', disp.CYAN)
        self.set_var_color('4', disp.RED)
        self.set_var_color('5', disp.YELLOW)
        self.set_var_color('6', disp.GREEN)
        center_x = floor(self.width // 2)
        center_y = floor(self.height // 2)
        print("center = %i, %i" % (center_x, center_y))

        for cell in self:
            (x, y) = cell.coords
            agent = SandAgent("Grainy", "Hold sand", cell)
            self.add_agent(agent, position=False)
            if x == center_x and y == center_y:
                self.center_agent = agent 
Example #3
Source File: fractions.py    From jawfish with MIT License 6 votes vote down vote up
def __round__(self, ndigits=None):
        """Will be round(self, ndigits) in 3.0.

        Rounds half toward even.
        """
        if ndigits is None:
            floor, remainder = divmod(self.numerator, self.denominator)
            if remainder * 2 < self.denominator:
                return floor
            elif remainder * 2 > self.denominator:
                return floor + 1
            # Deal with the half case:
            elif floor % 2 == 0:
                return floor
            else:
                return floor + 1
        shift = 10**abs(ndigits)
        # See _operator_fallbacks.forward to check that the results of
        # these operations will always be Fraction and therefore have
        # round().
        if ndigits > 0:
            return Fraction(round(self * shift), shift)
        else:
            return Fraction(round(self / shift) * shift) 
Example #4
Source File: demo.py    From unicorn-hat-hd with MIT License 6 votes vote down vote up
def checker(x, y, step):
    x -= (u_width / 2)
    y -= (u_height / 2)
    angle = (step / 10.0)
    s = math.sin(angle)
    c = math.cos(angle)
    xs = x * c - y * s
    ys = x * s + y * c
    xs -= math.sin(step / 200.0) * 40.0
    ys -= math.cos(step / 200.0) * 40.0
    scale = step % 20
    scale /= 20
    scale = (math.sin(step / 50.0) / 8.0) + 0.25
    xs *= scale
    ys *= scale
    xo = abs(xs) - int(abs(xs))
    yo = abs(ys) - int(abs(ys))
    v = 0 if (math.floor(xs) + math.floor(ys)) % 2 else 1 if xo > .1 and yo > .1 else .5
    r, g, b = hue_to_rgb[step % 255]
    return (r * (v * 255), g * (v * 255), b * (v * 255))


# weeee waaaah 
Example #5
Source File: GXDLMSRegister.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def getValue(self, settings, e):
        if e.index == 1:
            return _GXCommon.logicalNameToBytes(self.logicalName)
        if e.index == 2:
            return self.value
        if e.index == 3:
            data = GXByteBuffer()
            data.setUInt8(DataType.STRUCTURE)
            data.setUInt8(2)
            _GXCommon.setData(settings, data, DataType.INT8, math.floor(math.log(self.scaler, 10)))
            _GXCommon.setData(settings, data, DataType.ENUM, int(self.unit))
            return data.array()
        e.error = ErrorCode.READ_WRITE_DENIED
        return None

    #
    # Set value of given attribute.
    #
    #pylint: disable=broad-except 
Example #6
Source File: senet.py    From argus-freesound with MIT License 6 votes vote down vote up
def __init__(self, inplanes, planes, groups, reduction, stride=1,
                 downsample=None, base_width=4):
        super(SEResNeXtBottleneck, self).__init__()
        width = math.floor(planes * (base_width / 64)) * groups
        self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False,
                               stride=1)
        self.bn1 = nn.BatchNorm2d(width)
        self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,
                               padding=1, groups=groups, bias=False)
        self.bn2 = nn.BatchNorm2d(width)
        self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.se_module = SEModule(planes * 4, reduction=reduction)
        self.downsample = downsample
        self.stride = stride 
Example #7
Source File: noduleCADEvaluationLUNA16.py    From DeepLung with GNU General Public License v3.0 6 votes vote down vote up
def compute_mean_ci(interp_sens, confidence = 0.95):
    sens_mean = np.zeros((interp_sens.shape[1]),dtype = 'float32')
    sens_lb   = np.zeros((interp_sens.shape[1]),dtype = 'float32')
    sens_up   = np.zeros((interp_sens.shape[1]),dtype = 'float32')
    
    Pz = (1.0-confidence)/2.0
    print(interp_sens.shape)
    for i in range(interp_sens.shape[1]):
        # get sorted vector
        vec = interp_sens[:,i]
        vec.sort()

        sens_mean[i] = np.average(vec)
        sens_lb[i] = vec[int(math.floor(Pz*len(vec)))]
        sens_up[i] = vec[int(math.floor((1.0-Pz)*len(vec)))]

    return sens_mean,sens_lb,sens_up 
Example #8
Source File: utils.py    From TVQAplus with MIT License 6 votes vote down vote up
def get_bbox_target_single_box(single_box, spatial_dim=7, img_w=640., img_h=360., thd=0.5):
    """
    :param single_box: a single box
    :param spatial_dim:
    :param img_w:
    :param img_h:
    :param thd: round thd
    :return:
    """
    top = single_box["top"]
    left = single_box["left"]
    bottom = top + single_box["height"]
    right = left + single_box["width"]

    # map to 224x224 to 7x7
    top = int(math.floor((top * spatial_dim) / img_h + thd))
    bottom = int(math.ceil((bottom * spatial_dim) / img_h - thd))
    left = int(math.floor((left * spatial_dim) / img_w + thd))
    right = int(math.ceil((right * spatial_dim) / img_w - thd))
    gt_att_map = np.zeros([spatial_dim, spatial_dim]).astype(np.float32)
    gt_att_map[top: bottom+1, left:right+1] = 1
    # print(top, bottom, left, right)
    return gt_att_map 
Example #9
Source File: editor.py    From sixcells with GNU General Public License v3.0 6 votes vote down vote up
def _place(self, p, kind=Cell.unknown):
        if not self.preview:
            self.preview = Cell()
            self.preview.kind = kind
            self.preview.setOpacity(0.4)
            self.addItem(self.preview)
        x, y = convert_pos(p.x(), p.y())
        x = round(x)
        for yy in [round(y), int(math.floor(y - 1e-4)), int(math.ceil(y + 1e-4))]:
            self.preview.coord = (x, yy)
            if not any(isinstance(it, Cell) for it in self.preview.overlapping):
                break
        else:
            self.preview.coord = (round(x), round(y))
        self.preview.upd()
        self.preview._text.setText('') 
Example #10
Source File: HalvesRainbow.py    From BiblioPixelAnimations with MIT License 6 votes vote down vote up
def step(self, amt=1):
        center = float(self._maxLed) / 2
        center_floor = math.floor(center)
        center_ceil = math.ceil(center)

        if self._centerOut:
            self.layout.fill(
                self.palette(self._step), int(center_floor - self._current), int(center_floor - self._current))
            self.layout.fill(
                self.palette(self._step), int(center_ceil + self._current), int(center_ceil + self._current))
        else:
            self.layout.fill(
                self.palette(self._step), int(self._current), int(self._current))
            self.layout.fill(
                self.palette(self._step), int(self._maxLed - self._current), int(self._maxLed - self._current))

        self._step += amt + self._rainbowInc

        if self._current == center_floor:
            self._current = self._minLed
        else:
            self._current += amt 
Example #11
Source File: utils.py    From progressive_growing_of_GANs with MIT License 6 votes vote down vote up
def grid_batch_images(self, images):
        n, h, w, c = images.shape
        a = int(math.floor(np.sqrt(n)))
        # images = (((images - images.min()) * 255) / (images.max() - images.min())).astype(np.uint8)
        images = images.astype(np.uint8)
        images_in_square = np.reshape(images[:a * a], (a, a, h, w, c))
        new_img = np.zeros((h * a, w * a, c), dtype=np.uint8)
        for col_i, col_images in enumerate(images_in_square):
            for row_i, image in enumerate(col_images):
                new_img[col_i * h: (1 + col_i) * h, row_i * w: (1 + row_i) * w] = image
        resolution = self.cfg.resolution
        if self.cfg.resolution != h:
            scale = resolution / h
            new_img = cv2.resize(new_img, None, fx=scale, fy=scale,
                                 interpolation=cv2.INTER_NEAREST)
        return new_img 
Example #12
Source File: parameters.py    From python-panavatar with MIT License 6 votes vote down vote up
def _get_octave(seed, coord):
    x = coord.real
    y = coord.imag

    cellx = math.floor(x)
    celly = math.floor(y)

    value00 = _perlin_random(seed, cellx, celly)
    value10 = _perlin_random(seed, cellx + 1, celly)
    value01 = _perlin_random(seed, cellx, celly + 1)
    value11 = _perlin_random(seed, cellx + 1, celly + 1)

    offsetx = x % 1.0
    offsety = y % 1.0

    value0 = offsetx * value10 + (1 - offsetx) * value00
    value1 = offsetx * value11 + (1 - offsetx) * value01

    result = offsety * value1 + (1 - offsety) * value0

    return result * INV_MAX_VALUE 
Example #13
Source File: parameters.py    From python-panavatar with MIT License 6 votes vote down vote up
def __init__(self, seed, octaves=None, detail=None,
                 min_value=0, max_value=1, size=1.0):

        if not octaves:
            octaves = max(1, int(math.floor(math.log(size / detail, 2))))

        scales = [.5 ** o for o in range(octaves)]
        inv_total_scale = 1.0 / sum(scales)

        self.min_value = min_value
        self.max_value = max_value
        self.inv_size = 1.0 / size

        self.octaves = [
            (inv_total_scale * scale,
             1.0 / (inv_total_scale * scale),
             (seed ^ o * 541) & 0x3FFFFFFF)
            for (o, scale)
            in enumerate(scales)] 
Example #14
Source File: node.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mouseMoveEvent(self, event):
        if self.__dragging:
            newPos = self.mapToScene(event.pos())

            graph = self.getGraph()
            if graph.getSnapToGrid() is True:
                gridSize = graph.getGridSize()

                newNodePos = newPos - self._mouseDelta

                snapPosX = math.floor(newNodePos.x() / gridSize) * gridSize;
                snapPosY = math.floor(newNodePos.y() / gridSize) * gridSize;
                snapPos = QtCore.QPointF(snapPosX, snapPosY)

                newPosOffset = snapPos - newNodePos

                newPos = newPos + newPosOffset

            delta = newPos - self._lastDragPoint
            self.__graph.moveSelectedNodes(delta)
            self._lastDragPoint = newPos
            self._nodesMoved = True
        else:
            super(Node, self).mouseMoveEvent(event) 
Example #15
Source File: stats.py    From simon with MIT License 5 votes vote down vote up
def bytes2human(n):
    # Credits to /u/cyberspacecowboy on reddit
    # https://www.reddit.com/r/Python/comments/5xukpd/-/dem5k12/
    symbols = (' B', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB', ' EiB', ' ZiB',
               ' YiB')
    i = math.floor(math.log(abs(n)+1, 2) / 10)
    return '%.1f%s' % (n/2**(i*10), symbols[int(i)]) 
Example #16
Source File: fractions.py    From jawfish with MIT License 5 votes vote down vote up
def __floor__(a):
        """Will be math.floor(a) in 3.0."""
        return a.numerator // a.denominator 
Example #17
Source File: pwnpass.py    From password_pwncheck with MIT License 5 votes vote down vote up
def find(self,string):
        if self.debug:
            print(("   * searchfile: find: filepath=%s"%(self.filepath)))
        string = string.strip()
        if len(string) != self.nows_linesize:
            return None
        startrow = floor(self.filerows/2)
        startjump = int(self.filerows/4)
        ret = self._find(string,startrow,startjump)
        if ret == None:
            return ret
        return int(ret)+1
        #return int(self._find(string,startrow,startjump))+1 
Example #18
Source File: combined.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _append_ngram (self, size, train_sents, verbose=False, cutoff_value=0.001):
        cutoff = math.floor(len(train_sents)*cutoff_value)
        self._tagger.append( Ngram(size, cutoff=cutoff, backoff=self._tagger[-1]) )
        self._tagger[-1].train([train_sents], verbose) 
Example #19
Source File: TensorFlowInterface.py    From IntroToDeepLearning with MIT License 5 votes vote down vote up
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	W = layer.output
	wp = W.eval(feed_dict=feed_dict);
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
		fields = np.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = np.rollaxis(wp,3,0)
		features, channels, iy,ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(np.hstack(fields2[i:i+perColumn]))

	tiled = np.vstack(tiled)
	if figOffset is not None:
		mpl.figure(figOffset); mpl.clf();

	mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar(); 
Example #20
Source File: TensorFlowInterface.py    From IntroToDeepLearning with MIT License 5 votes vote down vote up
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
	# Receptive Fields Summary
	W = layer.W
	wp = W.eval().transpose();
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
	else:			# Convolutional layer already has shape
		features, channels, iy, ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	fieldsN = min(fields.shape[0],maxFields)
	perRow = int(math.floor(math.sqrt(fieldsN)))
	perColumn = int(math.ceil(fieldsN/float(perRow)))

	fig = mpl.figure(figName); mpl.clf()

	# Using image grid
	from mpl_toolkits.axes_grid1 import ImageGrid
	grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
	for i in range(0,fieldsN):
		im = grid[i].imshow(fields[i],cmap=cmap);

	grid.cbar_axes[0].colorbar(im)
	mpl.title('%s Receptive Fields' % layer.name)

	# old way
	# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	# tiled = []
	# for i in range(0,perColumn*perRow,perColumn):
	# 	tiled.append(np.hstack(fields2[i:i+perColumn]))
	#
	# tiled = np.vstack(tiled)
	# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
	mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar() 
Example #21
Source File: TensorFlowInterface.py    From IntroToDeepLearning with MIT License 5 votes vote down vote up
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	try:
		W = layer.output
	except:
		W = layer
	wp = W.eval(feed_dict=feed_dict);
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
		fields = np.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = np.rollaxis(wp,3,0)
		features, channels, iy,ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(np.hstack(fields2[i:i+perColumn]))

	tiled = np.vstack(tiled)
	if figOffset is not None:
		mpl.figure(figOffset); mpl.clf(); 

	mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar(); 
Example #22
Source File: TensorFlowInterface.py    From IntroToDeepLearning with MIT License 5 votes vote down vote up
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
	# Receptive Fields Summary
	try:
		W = layer.W
	except:
		W = layer
	wp = W.eval().transpose();
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)	
	else:			# Convolutional layer already has shape
		features, channels, iy, ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

	fig = mpl.figure(figOffset); mpl.clf()
	
	# Using image grid
	from mpl_toolkits.axes_grid1 import ImageGrid
	grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
	for i in range(0,np.shape(fields)[0]):
		im = grid[i].imshow(fields[i],cmap=cmap); 

	grid.cbar_axes[0].colorbar(im)
	mpl.title('%s Receptive Fields' % layer.name)
	
	# old way
	# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	# tiled = []
	# for i in range(0,perColumn*perRow,perColumn):
	# 	tiled.append(np.hstack(fields2[i:i+perColumn]))
	# 
	# tiled = np.vstack(tiled)
	# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
	mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar() 
Example #23
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def get_maximum_length(self, cap):
		full = int(math.floor(cap / 8))*7
		remn = int(math.floor(((cap % 8)/8.0)*7))
		return full + remn 
Example #24
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def get_maximum_length(self, cap):
		return int(math.floor(cap/2)) 
Example #25
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def get_maximum_length(self, cap):
		full = int(math.floor(cap / 8))*5
		remn = int(math.floor(((cap % 8)/8.0)*5))
		return full + remn 
Example #26
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def get_maximum_length(self, cap):
		full = int(math.floor(cap / 4))*3
		remn = int(math.floor(((cap % 4)/4.0)*3))
		return full + remn 
Example #27
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def get_maximum_length(self, cap):
		full = int(math.floor(cap / 4))*3
		remn = int(math.floor(((cap % 4)/4.0)*3))
		return full + remn 
Example #28
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def get_maximum_length(self, cap):
		full = int(math.floor(cap / 4))*3
		remn = int(math.floor(((cap % 4)/4.0)*3))
		return full + remn 
Example #29
Source File: fractions.py    From jawfish with MIT License 5 votes vote down vote up
def __rfloordiv__(b, a):
        """a // b"""
        return math.floor(a / b) 
Example #30
Source File: mutators.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def alter_data(self, incident):
        for x in range(0, math.floor(len(incident) * self.percent)):
            field_to_drop = random.choice(list(incident.keys()))
            if field_to_drop not in self.do_not_mutate and incident[field_to_drop] is not None:
                incident[field_to_drop] = ''.join(random.choice((str.upper, str.lower))(x) for x in incident[field_to_drop])
        return incident