Python numpy.around() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def get_labels(contours, shape, slices):
    z = [np.around(s.ImagePositionPatient[2], 1) for s in slices]
    pos_r = slices[0].ImagePositionPatient[1]
    spacing_r = slices[0].PixelSpacing[1]
    pos_c = slices[0].ImagePositionPatient[0]
    spacing_c = slices[0].PixelSpacing[0]
    
    label_map = np.zeros(shape, dtype=np.float32)
    for con in contours:
        num = ROI_ORDER.index(con['name']) + 1
        for c in con['contours']:
            nodes = np.array(c).reshape((-1, 3))
            assert np.amax(np.abs(np.diff(nodes[:, 2]))) == 0
            z_index = z.index(np.around(nodes[0, 2], 1))
            r = (nodes[:, 1] - pos_r) / spacing_r
            c = (nodes[:, 0] - pos_c) / spacing_c
            rr, cc = polygon(r, c)
            label_map[z_index, rr, cc] = num
    
    return label_map 

Example 2

def ani_update(arg, ii=[0]):

    i = ii[0]  # don't ask...

    if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
        fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)

    graphic_floor[0].set_data([-floor_lim*np.cos(incline_history[i]) + radius*np.sin(incline_history[i]), floor_lim*np.cos(incline_history[i]) + radius*np.sin(incline_history[i])], [-floor_lim*np.sin(incline_history[i])-radius*np.cos(incline_history[i]), floor_lim*np.sin(incline_history[i])-radius*np.cos(incline_history[i])])
    graphic_wheel.center = (x_history[i], y_history[i])
    graphic_ind[0].set_data([x_history[i], x_history[i] + radius*np.sin(w_history[i])],
                            [y_history[i], y_history[i] + radius*np.cos(w_history[i])])
    graphic_pend[0].set_data([x_history[i], x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2])],
                             [y_history[i], y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2])])
    graphic_dist[0].set_data([x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2]), x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2]) - pscale*p_history[i]*np.cos(q_history[i, 2])],
                             [y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2]), y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2]) - pscale*p_history[i]*np.sin(q_history[i, 2])])

    ii[0] += int(1 / (timestep * framerate))
    if ii[0] >= len(t_arr):
        print("Resetting animation!")
        ii[0] = 0

    return [graphic_floor, graphic_wheel, graphic_ind, graphic_pend, graphic_dist]

# Run animation 

Example 3

def gen_adj_mat(longs, lats, prob_edge=.2,
                        additional_length=lambda: np.random.exponential(20,1)):
    '''Get an adjacency matrix for the cities whose longitudes and latitudes
    are passed. Each entry will either be a number somewhat greater than the
    crow-flies distance between the two cities (with probability prob_edge),
    or math.inf. The matrix will consist of floats, and be symmetric. The
    diagonal will be all zeroes. The "somewhat greater" is controlled by the
    additional_length parameter, a function returning a random amount.'''

    # Generate full nxn Bernoulli's, even though we'll only use the upper
    # triangle.
    edges = np.random.binomial(1, prob_edge, size=(len(longs),len(longs)))
    am = np.zeros((len(longs),len(longs)))
    for i in range(len(longs)):
        for j in range(len(longs)):
            if i==j:
                am[i,i] = 0
            elif i < j:
                if edges[i,j] == 1:
                    am[i,j] = (math.hypot(longs[i]-longs[j],lats[i]-lats[j])
                        + additional_length())
                    am[j,i] = am[i,j]
                else:
                    am[i,j] = am[j,i] = math.inf
    return np.around(am,1) 

Example 4

def bbox_indices(self, bbox, shape, precision=7):
        """
        Return row and column coordinates of a bounding box at a
        given cellsize.

        Parameters
        ----------
        bbox : tuple of floats or ints (length 4)
               bbox of new data.
        shape : tuple of ints (length 2)
                The shape of the 2D array (rows, columns).
        precision : int
                    Precision to use when matching geographic coordinates.
        """
        rows = np.around(np.linspace(bbox[1], bbox[3],
               shape[0], endpoint=False)[::-1], precision)
        cols = np.around(np.linspace(bbox[0], bbox[2],
               shape[1], endpoint=False), precision)
        return rows, cols 

Example 5

def round_(a, decimals=0, out=None):
    """
    Round an array to the given number of decimals.

    Refer to `around` for full documentation.

    See Also
    --------
    around : equivalent function

    """
    try:
        round = a.round
    except AttributeError:
        return _wrapit(a, 'round', decimals, out)
    return round(decimals, out) 

Example 6

def get_cell(self):

        # from fractions import Fraction

        marr = np.array(self._matrix, dtype=np.float64).reshape((3, 3))
        g_arr = self._sites_grid.to_array()
        d = self.depth
        w = self.width
        l = self.length

        arr_bas = marr*np.array([d, w, l], dtype=np.int).reshape((3, 1))
        grid_position = np.array([p for p in CStru._yield_position(d, w, l)])
        frac = np.array([1/d, 1/w, 1/l], dtype=np.float64).reshape((1, 3))
        # round_frac = np.around(frac, decimals=22)
        arr_pos = grid_position * frac
        arr_num = np.array([i for i in g_arr.flat])

        return (arr_bas, arr_pos, arr_num) 

Example 7

def _get_new_id_seq(pos, numbers):
        """
        A helper function to produce the new sequence of the transformed
        structure. Algs is sort the position back to init and use the index
        to sort numbers.
        """
        # transfer the atom position into >=0 and <=1
        pos = np.around(pos, decimals=3)
        func_tofrac = np.vectorize(lambda x: round((x % 1), 3))
        o_pos = func_tofrac(pos)
        # round_o_pos = np.around(o_pos, decimals=3)
        # z, y, x = round_o_pos[:, 2], round_o_pos[:, 1], round_o_pos[:, 0]
        z, y, x = o_pos[:, 2], o_pos[:, 1], o_pos[:, 0]
        inds = np.lexsort((z, y, x))

        return inds 

Example 8

def _get_new_id_seq(pos, numbers):
        """
        A helper function to produce the new sequence of the transformed 
        structure. Algs is sort the position back to init and use the index
        to sort numbers.
        """
        # transfer the atom position into >=0 and <=1
        pos = np.around(pos, decimals=5)
        func_tofrac = np.vectorize(lambda x: round((x % 1), 3))
        o_pos = func_tofrac(pos)
        # round_o_pos = np.around(o_pos, decimals=3)
        # z, y, x = round_o_pos[:, 2], round_o_pos[:, 1], round_o_pos[:, 0]
        z, y, x = o_pos[:, 2], o_pos[:, 1], o_pos[:, 0]
        inds = np.lexsort((z, y, x))

        return inds 

Example 9

def __init__(self, gcell):
        self.lattice = np.around(gcell.lattice, decimals=6)
        self.positions = np.around(gcell.positions, decimals=6)
        self.numbers = gcell.numbers

        atoms_name_list = list(map(lambda x: Specie.to_name(x),
                                   list(self.numbers)))
        d = Counter(atoms_name_list)
        ordered_atoms = OrderedDict(sorted(d.items(),
                                           key=lambda x: Specie(x[0]).Z))
        # remove Ghostatoms
        if 'G' in ordered_atoms:
            del ordered_atoms['G']

        self.comment = ''.join(['{}{}'.format(k, v)
                               for k, v in ordered_atoms.items()]) 

Example 10

def _pnl_pos(self, e, s, a, pnl, inputs):
        '''
        Return the reward based on PnL from the last step marked to the
        mid-price of the instruments traded

        :param e: Environment object. Environment where the agent operates
        :param a: Agent object. the agent that will perform the action
        :param s: dictionary. The inputs from environment to the agent
        :param pnl: float. The current pnl of the agent
        :param inputs: dictionary. The inputs from environment to the agent
        '''
        reward = self._pnl(e, s, a, pnl, inputs)
        s_main = e.s_main_intrument
        if not a.logged_action:
            return reward
        f_penalty = abs(e.agent_states[a][s_main]['Position']) * 0.02
        f_penalty += abs(np.around(a.log_info['duration'])) * 0.30
        return reward - f_penalty 

Example 11

def fixOffset(self, offset, img):
    size = img.shape
    finalImg = np.ndarray(size)
    indices = np.indices((self.videoSize[0],self.videoSize[1])).swapaxes(0,2).swapaxes(0,1)
    indices = np.around(indices, decimals=1)
    indices.shape = (self.videoSize[1] * self.videoSize[0], 2)
    phi = 2 * np.arctan(np.exp(indices[:, 1] / self.videoSize[1])) - 1/2 * np.pi - offset[0]
    lamb = indices[:, 0] - offset[1]
    x = lamb
    y = np.log(np.tan(np.pi / 4 + 1/2 * phi)) * self.videoSize[1]
    finalIdx = np.ndarray((self.videoSize[1] * self.videoSize[0], 2))
    finalIdx = np.around(finalIdx, decimals=1).astype(int)
    finalIdx[:, 1] = y % self.videoSize[1]
    finalIdx[:, 0] = x % self.videoSize[0]
    finalImg[indices[:,1], indices[:,0]] = img[finalIdx[:,1], finalIdx[:,0]]
    return finalImg 

Example 12

def imresizemex(inimg, weights, indices, dim):
    in_shape = inimg.shape
    w_shape = weights.shape
    out_shape = list(in_shape)
    out_shape[dim] = w_shape[0]
    outimg = np.zeros(out_shape)
    if dim == 0:
        for i_img in range(in_shape[1]):
            for i_w in range(w_shape[0]):
                w = weights[i_w, :]
                ind = indices[i_w, :]
                im_slice = inimg[ind, i_img].astype(np.float64)
                outimg[i_w, i_img] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
    elif dim == 1:
        for i_img in range(in_shape[0]):
            for i_w in range(w_shape[0]):
                w = weights[i_w, :]
                ind = indices[i_w, :]
                im_slice = inimg[i_img, ind].astype(np.float64)
                outimg[i_img, i_w] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)        
    if inimg.dtype == np.uint8:
        outimg = np.clip(outimg, 0, 255)
        return np.around(outimg).astype(np.uint8)
    else:
        return outimg 

Example 13

def frac_coord(npixel, kernel_oversampling, p):
    """ Compute whole and fractional parts of coordinates, rounded to
    kernel_oversampling-th fraction of pixel size

    The fractional values are rounded to nearest 1/kernel_oversampling pixel value. At
    fractional values greater than (kernel_oversampling-0.5)/kernel_oversampling coordinates are
    rounded to next integer index.

    :param npixel: Number of pixels in total
    :param kernel_oversampling: Fractional values to round to
    :param p: Coordinate in range [-.5,.5[
    """
    assert numpy.array(p >= -0.5).all() and numpy.array(
        p < 0.5).all(), "Cellsize is too large: uv overflows grid uv= %s" % str(p)
    x = npixel // 2 + p * npixel
    flx = numpy.floor(x + 0.5 / kernel_oversampling)
    fracx = numpy.around((x - flx) * kernel_oversampling)
    return flx.astype(int), fracx.astype(int) 

Example 14

def test_optimized(self):
        """
        Test if optimized works well
        """
        lr = self.logistic_regression

        lr.set_data(self.iris)
        op_theta = lr.optimized()
        self.assertEqual(len(op_theta), 4)

        # check if really minimal, function is monotonic so everywhere around
        # j should be higher
        self.assertLessEqual(
            lr.j(op_theta), lr.j(op_theta + np.array([1, 0, 0, 0])))
        self.assertLessEqual(
            lr.j(op_theta), lr.j(op_theta + np.array([0, 1, 0, 0])))
        self.assertLessEqual(
            lr.j(op_theta), lr.j(op_theta + np.array([0, 0, 1, 0])))
        self.assertLessEqual(
            lr.j(op_theta), lr.j(op_theta + np.array([0, 0, 0, 1]))) 

Example 15

def ani_update(arg, ii=[0]):

    i = ii[0]  # don't ask...

    if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
        fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)

    graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
    graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
    graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))

    ii[0] += int(1 / (dt * framerate))
    if ii[0] >= len(t_arr):
        print("Resetting animation!")
        ii[0] = 0

    return None

# Run animation 

Example 16

def ani_update(arg, ii=[0]):

    i = ii[0]  # don't ask...

    if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
        fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)

    graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
    graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
    graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))

    ii[0] += int(1 / (dt * framerate))
    if ii[0] >= len(t_arr):
        print("Resetting animation!")
        ii[0] = 0

    return None

# Run animation 

Example 17

def ani_update(arg, ii=[0]):

    i = ii[0]  # don't ask...

    if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
        fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)

    graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
    graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
    graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))

    ii[0] += int(1 / (dt * framerate))
    if ii[0] >= len(t_arr):
        print("Resetting animation!")
        ii[0] = 0

    return None

# Run animation 

Example 18

def ani_update(arg, ii=[0]):

    i = ii[0]  # don't ask...

    if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
        fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)

    graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
    graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
    graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))

    ii[0] += int(1 / (dt * framerate))
    if ii[0] >= len(t_arr):
        print("Resetting animation!")
        ii[0] = 0

    return None

# Run animation 

Example 19

def update(arg, ii=[0]):

    i = ii[0]  # don't ask...

    if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
        fig3.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)

    link1[0].set_data([0, elb_history[i, 0]], [0, elb_history[i, 1]])
    link2[0].set_data([elb_history[i, 0], x_history[i, 0]], [elb_history[i, 1], x_history[i, 1]])
    end.set_offsets((x_history[i, 0], x_history[i, 1]))
    elb.set_offsets((elb_history[i, 0], elb_history[i, 1]))

    ii[0] += int(1 / (dt * framerate))
    if ii[0] >= len(t_arr):
        print("Resetting animation!")
        ii[0] = 0

    return [link1, link2, end, elb]

# Run animation 

Example 20

def test_encode_texts():
    """ Text encoding is stable.
    """

    TEST_SENTENCES = [u'I love mom\'s cooking',
                      u'I love how you never reply back..',
                      u'I love cruising with my homies',
                      u'I love messing with yo mind!!',
                      u'I love you and now you\'re just gone..',
                      u'This is shit',
                      u'This is the shit']

    maxlen = 30
    batch_size = 32

    with open(VOCAB_PATH, 'r') as f:
        vocabulary = json.load(f)
    st = SentenceTokenizer(vocabulary, maxlen)
    tokenized, _, _ = st.tokenize_sentences(TEST_SENTENCES)

    model = deepmoji_feature_encoding(maxlen, PRETRAINED_PATH)

    encoding = model.predict(tokenized)
    avg_across_sentences = np.around(np.mean(encoding, axis=0)[:5], 3)
    assert np.allclose(avg_across_sentences, np.array([-0.023, 0.021, -0.037, -0.001, -0.005])) 

Example 21

def myImputer(kernel,sample):
    kernelSize = kernel.shape[0];
    vectorSize = sample.shape[3];

    for fIndex in range(0,int(sample.shape[0])):
        for sIndex in range(0,int(sample.shape[1])):
            sslice = sample[fIndex][sIndex]
            #find the index of -1
            [x,y] = np.where(sslice == -1)
            #change -1 to 0
            sslice[sslice == -1] = 0
            if x.size == 0:
                continue
            #broaden the vector 
            tempVectorH = np.zeros([int((kernelSize-1)/2),vectorSize])
            tempVectorV = np.zeros([vectorSize-1+kernelSize,int((kernelSize-1)/2)])
            tempSlice = np.vstack((tempVectorH,sslice,tempVectorH))
            tempSlice = np.hstack((tempVectorV,tempSlice,tempVectorV))
            
            zeroSlice = np.zeros(sslice.shape);
            for k in range(len(x)):
                subSlice = tempSlice[x[k]:x[k]+kernelSize,y[k]:y[k]+kernelSize]
                imputerValue = np.sum(subSlice*kernel)
                zeroSlice[x[k],y[k]] = np.around(imputerValue)
            sslice += zeroSlice.astype("int32") 

Example 22

def round_(a, decimals=0, out=None):
    """
    Round an array to the given number of decimals.

    Refer to `around` for full documentation.

    See Also
    --------
    around : equivalent function

    """
    try:
        round = a.round
    except AttributeError:
        return _wrapit(a, 'round', decimals, out)
    return round(decimals, out) 

Example 23

def prepare_basemap(min_lat, min_lon, max_lat, max_lon, delta_lat, delta_lon):
    """
    
    :param min_lat: float 
    :param min_lon: float
    :param max_lat: float
    :param max_lon: float
    :param delta_lat: float
    :param delta_lon: float
    :return: A Basemap instance
    """
    m = Basemap(projection='cyl', llcrnrlat=min_lat, urcrnrlat=max_lat, urcrnrlon=max_lon,
                llcrnrlon=min_lon, resolution='l')
    m.drawcountries()
    m.drawcoastlines()
    m.drawparallels(np.arange(np.around(min_lat, 1), np.around(max_lat, 1), -round(delta_lat) / 5.0),
                    labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(np.around(min_lon, 1), np.around(max_lon, 1), -round(delta_lon) / 5.0),
                    labels=[0, 0, 0, 1])
    return m 

Example 24

def svimg(totarr):
	#print it out:
	x,y=totarr.shape
	vl = np.around(totarr.flatten(),5)#round to 5 digits
	xx = np.repeat(np.arange(x),x)+1
	yy = np.tile(np.arange(y),y)+1
	big =np.column_stack((xx,yy,vl))
	np.savetxt("noisyimage.txt",big,fmt=('%4.1f','%4.1f','%10.5f'))
	##Add this if you want to
	##read it out to make sure it works
	##Otherwise slows down routine.
	#row,col,data=np.loadtxt("noisyimage.txt",unpack=True)
	#rsize = int(max(row))
	#csize = int(max(col))
	#data=np.array(data).reshape(rsize,csize)
#	plt.imshow(data, interpolation='None',cmap=plt.cm.Greys_r) 

Example 25

def contour_edges(a):
    import matplotlib.pyplot as plt
    a = checkma(a)
    #Contour nodata value
    levels = [a.fill_value]
    #kw = {'antialiased':True, 'colors':'r', 'linestyles':'-'}
    kw = {'antialiased':True}
    #Generate contours around nodata
    cs = plt.contour(a.filled(), levels, **kw)
    #This returns a list of numpy arrays
    #allpts = np.vstack(cs.allsegs[0])
    #Extract paths
    p = cs.collections[0].get_paths()
    #Sort by number of vertices in each path
    p_len = [i.vertices.shape[0] for i in p]
    p_sort = [x for (y,x) in sorted(zip(p_len,p), reverse=True)]    
    #cp = p[0].make_compound_path(*p)
    return p_sort

#Brute force search for edges of valid data 

Example 26

def save_goal_image(self, traj):
        rounded = np.around(traj.score, decimals=2)
        best_score = np.min(rounded)
        for i in range(traj.score.shape[0]):
            if rounded[i] == best_score:
                first_best_index = i
                break

        print 'best_score', best_score
        print 'allscores', traj.score
        print 'goal index: ', first_best_index

        goalimage = traj._sample_images[first_best_index]
        # goalstate = traj.X_Xdot_full[i]
        img = Image.fromarray(goalimage)

        cPickle.dump([], open(self._hyperparams['save_goal_image'] + '.pkl', 'wb'))
        img.save(self._hyperparams['save_goal_image'] + '.png',) 

Example 27

def evaluate_checkpoints(self, filename):
        # Load image
        with open(UPLOAD_FOLDER + '/' + filename, 'rb') as f:
            image_string = f.read()

        # Session
        with tf.Session() as sess:
            # Restore variables values
            self.saver.restore(sess, './models/'+self.loaded_model_name+'/model.ckpt')

            prob_values = sess.run(self.probs, feed_dict={
                self.input_image_string: image_string
                })

            pred_idx = prob_values[0].argsort()[-5:][::-1]
            pred_class = self.classes[pred_idx - 1] # from 1001 to 1000 classes
            pred_score = np.around(100*prob_values[0][pred_idx], decimals=2) # two decimals

            return list(pred_class), list(pred_score) 

Example 28

def evaluate_frozen(self, filename):
        # Load image
        with open(UPLOAD_FOLDER + '/' + filename, 'rb') as f:
            image_string = f.read()

        # Session
        with tf.Session() as sess:
            prob_values = sess.run(self.probs, feed_dict={
                self.input_image_string: image_string
                })

            pred_idx = prob_values[0].argsort()[-5:][::-1]
            pred_class = self.classes[pred_idx - 1] # from 1001 to 1000 classes
            pred_score = np.around(100*prob_values[0][pred_idx], decimals=2) # two decimals

            return list(pred_class), list(pred_score) 

Example 29

def histo_plot(figure,X,color,xlabel="",ylabel="",cumul=False,bar=True,n_points=400,smooth_factor=0.1,spline_order=3,linewidth=3,alpha=1.0,label=""):
    if '%' in xlabel:
        magnitude = 100
        X_values = np.array(np.minimum(np.around(X),n_points+1),int)
    else:
        # magnitude = np.power(10,np.around(4*np.log10(X.mean()))/4+0.5)
        magnitude = np.power(10,np.around(4*np.log10(np.nanmean(X)+np.nanstd(X)+1e-7))/4+1)
        magnitude = np.around(magnitude,int(-np.log10(magnitude))+1)
        # print magnitude
        #magnitude = X.mean()+5.0*X.std()
        X_values = np.array(np.minimum(np.around(n_points*X[True-np.isnan(X)]/magnitude),n_points+1),int)
    X_histo = np.zeros(n_points+1,float)
    for x in np.linspace(0,n_points,n_points+1):
        X_histo[x] = nd.sum(np.ones_like(X_values,float),X_values,index=x)
        if '%' in ylabel:
            X_histo[x] /= X_values.size/100.0
        if cumul:
            X_histo[x] += X_histo[x-1]

    if bar:
        bar_plot(figure,np.linspace(0,magnitude,n_points+1),X_histo,np.array([1,1,1]),color,xlabel,ylabel,label=label)
    else:
        smooth_plot(figure,np.linspace(0,magnitude,n_points+1),X_histo,color,color,xlabel,ylabel,n_points=n_points,smooth_factor=smooth_factor,spline_order=spline_order,linewidth=linewidth,alpha=alpha,label=label) 

Example 30

def make_pivots(start, stop, pivots_per_year=12, precision=2):
    """Makes an array of pivots (i.e., timepoints) between the given start and stop
    by the given pivots per year. The generated pivots are floating point values
    that are then rounded to the requested decimal precision.

    >>> list(make_pivots(2000.0, 2001.0, 5))
    [2000.0, 2000.25, 2000.5, 2000.75, 2001.0]
    """
    # Calculate number of pivots (i.e., months) in the requested interval.
    number_of_pivots = np.ceil((stop - start) * pivots_per_year)

    # Build an evenly-spaced closed interval (including the start and stop
    # points) based on the calculated number of pivots.
    return np.around(
        np.linspace(start, stop, number_of_pivots),
        precision
    ) 

Example 31

def test_dayofwk(self):
        "Test computation of dayofwk in the 365_day calendar."

        converter = self.converters["noleap"]

        # Pick the date corresponding to the Julian day of 1.0 to test
        # the transision from positive to negative Julian days.
        julian_day = converter.date2num(datetimex(-4712, 1, 2, 12))

        old_date = converter.num2date(julian_day)
        for delta_year in range(1, 101): # 100 years cover several 7-year cycles
            date = converter.num2date(julian_day - delta_year * 365)

            # test that the day of the week changes by one every year (except
            # for wrapping around every 7 years, of course)
            if date.dayofwk == 6:
                self.assertEqual(old_date.dayofwk, 0)
            else:
                self.assertEqual(old_date.dayofwk - date.dayofwk, 1)

            old_date = date 

Example 32

def test_reindex_nearest(self):
        s = Series(np.arange(10, dtype='int64'))
        target = [0.1, 0.9, 1.5, 2.0]
        actual = s.reindex(target, method='nearest')
        expected = Series(np.around(target).astype('int64'), target)
        assert_series_equal(expected, actual)

        actual = s.reindex_like(actual, method='nearest')
        assert_series_equal(expected, actual)

        actual = s.reindex_like(actual, method='nearest', tolerance=1)
        assert_series_equal(expected, actual)

        actual = s.reindex(target, method='nearest', tolerance=0.2)
        expected = Series([0, 1, np.nan, 2], target)
        assert_series_equal(expected, actual) 

Example 33

def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 

Example 34

def ylimit(self, value):
        """Upper and lower limit of current plot.
        Permanent limits are stored in yScaleSteps, which can be changed by user using range box.

        This is the only function through which plots can be updated.
        """
        if value[0] == value[1]:
            return

        if not self.hiCmapAxis.doNotPlot:
            self._ylimit = [ value[0], value[1] ]

            # Setting yticks based on ylimits, only change yticks when y-limits are changed
            ydiff = value[0] - value[1]
            yticks = np.linspace(self.ylimit[0], self.ylimit[1], 100)

            # Set tick label according to precision
            self.yticksDecimals = gmlib.util.locate_significant_digit_after_decimal(ydiff)
            if self.yticksDecimals > 3:
                self.yticksFormatStyle = 'sci'
                self.yticks = np.around(yticks, decimals=self.yticksDecimals+1)
            else:
                self.yticks = np.around(yticks, decimals=self.yticksDecimals+1)

            self.updatePlot() 

Example 35

def project_radii(radii, spacing, r_min, r_max):
    """ Projects given radii to values between r_min and r_max; good spacing ~ 1000 """

    radii_norm = radii / np.max(radii)  # Normalize radii

    # Determine min and max of array and generate spacing
    radii_to_proj = np.around(np.linspace(np.min(radii_norm), np.max(radii_norm), spacing), 3)
    values_to_proj = np.around(np.linspace(r_min, r_max, spacing), 3)

    # Determine respective array positions
    pos = np.array([np.argmin(np.abs(radii_to_proj -
                                     radii_norm[entry])) for entry in range(len(radii_norm))], dtype=np.int)

    # Determine new radii
    return np.take(values_to_proj, pos)


###############################################################################
# HUNGARIAN (MUNKRES) ALGORITHM - TAKEN FROM SCIPY
############################################################################### 

Example 36

def round_(a, decimals=0, out=None):
    """
    Round an array to the given number of decimals.

    Refer to `around` for full documentation.

    See Also
    --------
    around : equivalent function

    """
    try:
        round = a.round
    except AttributeError:
        return _wrapit(a, 'round', decimals, out)
    return round(decimals, out) 

Example 37

def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 

Example 38

def ha2Fa3d(ha,N):
	#usage: Fa=ha2Fa3d(ha,N);
	#produces the analysis polyphase folding matrix Fa with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15
	print "ha2Pa3d:"
	Pa=ha2Pa3d(ha,N);
	print "polmatmult DCT:"
	Fa=polmatmult(Pa,DCToMatrix(N))
        #round zeroth polyphase component to 7 decimals after point:
        Fa=np.around(Fa,8)

	return Fa 

Example 39

def hs2Fs3d(hs,N):
	#usage: Fs=hs2Fs3d(hs,N);
	#produces the synthesis polyphase folding matrix Fs with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15

	Ps=hs2Ps3d(hs,N);
	Fs=polmatmult(DCToMatrix(N),Ps)
        #round zeroth polyphase component to 7 decimals after point:
        Fs=np.around(Fs,8)

	return Fs 

Example 40

def ha2Fa3d(ha,N):
	#usage: Fa=ha2Fa3d(ha,N);
	#produces the analysis polyphase folding matrix Fa with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15
	print "ha2Pa3d:"
	Pa=ha2Pa3d(ha,N);
	print "polmatmult DCT:"
	Fa=polmatmult(Pa,DCToMatrix(N))
        #round zeroth polyphase component to 7 decimals after point:
        Fa=np.around(Fa,8)

	return Fa 

Example 41

def hs2Fs3d(hs,N):
	#usage: Fs=hs2Fs3d(hs,N);
	#produces the synthesis polyphase folding matrix Fs with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15

	Ps=hs2Ps3d(hs,N);
	Fs=polmatmult(DCToMatrix(N),Ps)
        #round zeroth polyphase component to 7 decimals after point:
        Fs=np.around(Fs,8)

	return Fs 

Example 42

def ha2Fa3d(ha,N):
	#usage: Fa=ha2Fa3d(ha,N);
	#produces the analysis polyphase folding matrix Fa with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15
	print "ha2Pa3d:"
	Pa=ha2Pa3d(ha,N);
	print "polmatmult DCT:"
	Fa=polmatmult(Pa,DCToMatrix(N))
        #round zeroth polyphase component to 7 decimals after point:
        Fa=np.around(Fa,8)

	return Fa 

Example 43

def ha2Fa3d(ha,N):
	#usage: Fa=ha2Fa3d(ha,N);
	#produces the analysis polyphase folding matrix Fa with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15

	Pa=ha2Pa3d(ha,N);
	Fa=polmatmult(Pa,DCToMatrix(N))
        #round zeroth polyphase component to 7 decimals after point:
        Fa=np.around(Fa,8)

	return Fa 

Example 44

def hs2Fs3d(hs,N):
	#usage: Fs=hs2Fs3d(hs,N);
	#produces the synthesis polyphase folding matrix Fs with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15

	Ps=hs2Ps3d(hs,N);
	Fs=polmatmult(DCToMatrix(N),Ps)
        #round zeroth polyphase component to 7 decimals after point:
        Fs=np.around(Fs,8)

	return Fs 

Example 45

def ha2Fa3d(ha,N):
	#usage: Fa=ha2Fa3d(ha,N);
	#produces the analysis polyphase folding matrix Fa with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15
	print "ha2Pa3d:"
	Pa=ha2Pa3d(ha,N);
	print "polmatmult DCT:"
	Fa=polmatmult(Pa,DCToMatrix(N))
        #round zeroth polyphase component to 7 decimals after point:
        Fa=np.around(Fa,8)

	return Fa 

Example 46

def hs2Fs3d(hs,N):
	#usage: Fs=hs2Fs3d(hs,N);
	#produces the synthesis polyphase folding matrix Fs with all polyphase components
	#in 3D matrix representation
	#from a basband filter ha with
	#a cosine modulation
	#N: Blocklength
	#Gerald Schuller
	#[email protected]
	#Dec-2-15

	Ps=hs2Ps3d(hs,N);
	Fs=polmatmult(DCToMatrix(N),Ps)
        #round zeroth polyphase component to 7 decimals after point:
        Fs=np.around(Fs,8)

	return Fs 

Example 47

def qreport(self, header="State", state=None, visualize=False):
		# This is only a simulator function for debugging. it CANNOT be done on a real Quantum Computer.
		if state == None:
			state = self.sys_state
		print
		print header
		for i in range(len(state)):
			if self.disp_zeros or np.absolute(state[i]) > self.maxerr:
				barlen = 20
				barstr = ""
				if self.visualize or visualize:
					barstr = "	x"
					amp = np.absolute(state[i].item(0))*barlen
					intamp = int(amp)
					if amp > self.maxerr:
						barstr = "	|"
						for b in range(barlen):
							if b <= intamp:
								barstr = barstr+"*"
							else:
								barstr = barstr + "."
				ststr = ("{:0"+str(self.nqbits)+"b}    ").format(i)
				ampstr = "{:.8f}".format(np.around(state[i].item(0),8))
				print ststr + ampstr + barstr 

Example 48

def genLandmarkMap(landmarks, shape=[39, 39]):
    '''Generate landmark map according to landmarks.
    Input params:
    landmarks: K x 2 float 
    shape: H x W
    Output:
    landmarkMap: H x W x K binary map. For each H x W
    map, there's only one location nearest to the landmark
    location filled with 1, else 0.'''

    landmarks = landmarks.reshape((-1, 2))
    landmarkMap = np.zeros(shape + [len(landmarks)])
    for (i, landmark) in enumerate(landmarks):
        x = int(np.around(landmark[0] * shape[1]))
        y = int(np.around(landmark[1] * shape[0]))
        landmarkMap[y, x, i] = 1
    return landmarkMap 

Example 49

def round_(a, decimals=0, out=None):
    """
    Round an array to the given number of decimals.

    Refer to `around` for full documentation.

    See Also
    --------
    around : equivalent function

    """
    try:
        round = a.round
    except AttributeError:
        return _wrapit(a, 'round', decimals, out)
    return round(decimals, out) 

Example 50

def show(img, name = "output.png"):
    """
    Show MNSIT digits in the console.
    """
    np.save(name, img)
    fig = np.around((img + 0.5)*255)
    fig = fig.astype(np.uint8).squeeze()
    pic = Image.fromarray(fig)
    # pic.resize((512,512), resample=PIL.Image.BICUBIC)
    pic.save(name)
    remap = "  .*#"+"#"*100
    img = (img.flatten()+.5)*3
    if len(img) != 784: return
    print("START")
    for i in range(28):
        print("".join([remap[int(round(x))] for x in img[i*28:i*28+28]])) 
点赞