Python numpy.swapaxes() Examples

The following are 30 code examples of numpy.swapaxes(). 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 numpy , or try the search function .
Example #1
Source File: test_numeric.py    From recruit with Apache License 2.0 6 votes vote down vote up
def setup(self):
        self.data = [
                # Array scalars
                (np.array(3.), None),
                (np.array(3), 'f8'),
                # 1D arrays
                (np.arange(6, dtype='f4'), None),
                (np.arange(6), 'c16'),
                # 2D C-layout arrays
                (np.arange(6).reshape(2, 3), None),
                (np.arange(6).reshape(3, 2), 'i1'),
                # 2D F-layout arrays
                (np.arange(6).reshape((2, 3), order='F'), None),
                (np.arange(6).reshape((3, 2), order='F'), 'i1'),
                # 3D C-layout arrays
                (np.arange(24).reshape(2, 3, 4), None),
                (np.arange(24).reshape(4, 3, 2), 'f4'),
                # 3D F-layout arrays
                (np.arange(24).reshape((2, 3, 4), order='F'), None),
                (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'),
                # 3D non-C/F-layout arrays
                (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None),
                (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'),
                     ] 
Example #2
Source File: basic.py    From lambda-packs with MIT License 6 votes vote down vote up
def _raw_fft(x, n, axis, direction, overwrite_x, work_function):
    """ Internal auxiliary function for fft, ifft, rfft, irfft."""
    if n is None:
        n = x.shape[axis]
    elif n != x.shape[axis]:
        x, copy_made = _fix_shape(x,n,axis)
        overwrite_x = overwrite_x or copy_made

    if n < 1:
        raise ValueError("Invalid number of FFT data points "
                         "(%d) specified." % n)

    if axis == -1 or axis == len(x.shape)-1:
        r = work_function(x,n,direction,overwrite_x=overwrite_x)
    else:
        x = swapaxes(x, axis, -1)
        r = work_function(x,n,direction,overwrite_x=overwrite_x)
        r = swapaxes(r, axis, -1)
    return r 
Example #3
Source File: nstyle.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def PreprocessContentImage(path, long_edge):
    img = io.imread(path)
    logging.info("load the content image, size = %s", img.shape[:2])
    factor = float(long_edge) / max(img.shape[:2])
    new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
    resized_img = transform.resize(img, new_size)
    sample = np.asarray(resized_img) * 256
    # swap axes to make image from (224, 224, 3) to (3, 224, 224)
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)
    # sub mean
    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    logging.info("resize the content image to %s", new_size)
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
Example #4
Source File: image_segmentaion.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def get_data(img_path):
    """get the (1, 3, h, w) np.array data for the supplied image
                Args:
                    img_path (string): the input image path

                Returns:
                    np.array: image data in a (1, 3, h, w) shape

    """
    mean = np.array([123.68, 116.779, 103.939])  # (R,G,B)
    img = Image.open(img_path)
    img = np.array(img, dtype=np.float32)
    reshaped_mean = mean.reshape(1, 1, 3)
    img = img - reshaped_mean
    img = np.swapaxes(img, 0, 2)
    img = np.swapaxes(img, 1, 2)
    img = np.expand_dims(img, axis=0)
    return img 
Example #5
Source File: stress_gui.py    From fenics-topopt with MIT License 6 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example #6
Source File: stress_gui.py    From fenics-topopt with MIT License 6 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example #7
Source File: mxnet_predict_example.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def PreprocessImage(path, show_img=False):
    # load image
    img = io.imread(path)
    print("Original Image Shape: ", img.shape)
    # we crop image from center
    short_egde = min(img.shape[:2])
    yy = int((img.shape[0] - short_egde) / 2)
    xx = int((img.shape[1] - short_egde) / 2)
    crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
    # resize to 224, 224
    resized_img = transform.resize(crop_img, (224, 224))
    # convert to numpy.ndarray
    sample = np.asarray(resized_img) * 255
    # swap axes to make image from (224, 224, 3) to (3, 224, 224)
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    # sub mean
    return sample

# Get preprocessed batch (single image batch) 
Example #8
Source File: vgg_16_reduced.py    From lambda-deep-learning-demo with Apache License 2.0 6 votes vote down vote up
def vgg_mod(outputs, params, name, data_format, dilation=1):
    w = np.swapaxes(np.swapaxes(np.swapaxes(params[name][0], 0, 3), 1, 2), 0, 1)
    b = params[name][1]
    outputs = tf.layers.conv2d(
            outputs,
        filters=w.shape[3],
        kernel_size=(w.shape[0], w.shape[1]),
        strides=(1, 1),
        padding=("SAME"),
        data_format=data_format,
        dilation_rate=(dilation, dilation),
        kernel_initializer=tf.constant_initializer(w),
        bias_initializer=tf.constant_initializer(b),
        activation=tf.nn.relu,
        name=name)
    return outputs 
Example #9
Source File: competition_model_class.py    From Deep_Learning_Weather_Forecasting with Apache License 2.0 6 votes vote down vote up
def linear_ensemble_strategy(self, pred_mean, pred_var, ruitu_inputs, feature_name,\
                            timestep_to_ensemble=21, alpha=1):
        '''
        This stratergy aims to calculate linear weighted at specific timestep (timestep_to_ensemble) between prediction and ruitu as formula:
                                    (alpha)*pred_mean + (1-alpha)*ruitu_inputs
        pred_mean: (10, 37, 3)
        pred_var: (10, 37, 3)
        ruitu_inputs: (37,10,29). Need Swamp to(10,37,29) FIRSTLY!!
        timestep_to_ensemble: int32 (From 0 to 36)
        '''
        assert 0<= alpha <=1, 'Please ensure 0<= alpha <=1 !'
        assert pred_mean.shape == (10, 37, 3), 'Error! This funtion ONLY works for \
        one data sample with shape (10, 37, 3). Any data shape (None, 10, 37, 3) will leads this error!'
        #pred_std = np.sqrt(np.exp(pred_var))           
        ruitu_inputs = np.swapaxes(ruitu_inputs,0,1)
        print('alpha:',alpha)

        pred_mean[:,timestep_to_ensemble:,self.obs_and_output_feature_index_map[feature_name]] = \
        (alpha)*pred_mean[:,timestep_to_ensemble:,self.obs_and_output_feature_index_map[feature_name]] + \
                                (1-alpha)*ruitu_inputs[:,timestep_to_ensemble:, self.ruitu_feature_index_map[feature_name]]  
        print('Corrected pred_mean shape:', pred_mean.shape)
        
        return pred_mean 
Example #10
Source File: vgg_16_reduced.py    From lambda-deep-learning-demo with Apache License 2.0 6 votes vote down vote up
def vgg_block(outputs, params, name, data_format, num_conv):

    for i in range(num_conv):
        layer_name = name + "_" + str(i + 1)
        w = np.swapaxes(np.swapaxes(np.swapaxes(params[layer_name][0], 0, 3), 1, 2), 0, 1)
        b = params[layer_name][1]
        outputs = tf.layers.conv2d(
                outputs,
    	    filters=w.shape[3],
    	    kernel_size=(w.shape[0], w.shape[1]),
    	    strides=(1, 1),
    	    padding=("SAME"),
    	    data_format=data_format,
    	    kernel_initializer=tf.constant_initializer(w),
    	    bias_initializer=tf.constant_initializer(b),
    	    activation=tf.nn.relu,
    	    name=layer_name)
    return outputs 
Example #11
Source File: plotting.py    From kvae with MIT License 6 votes vote down vote up
def plot_ball_and_alpha(alpha, trajectory, filename, cmap='Blues'):
    f, ax = plt.subplots(nrows=1, ncols=2, figsize=[12, 6])
    collection = construct_ball_trajectory(trajectory, r=1., cmap=cmap)

    x_min, y_min = np.min(trajectory, axis=0)
    x_max, y_max = np.max(trajectory, axis=0)

    ax[0].add_collection(collection)
    ax[0].set_xlim([x_min, x_max])
    ax[0].set_ylim([y_min, y_max])
    # ax[0].set_xticks([])
    # ax[0].set_yticks([])
    ax[0].axis("equal")

    for line in np.swapaxes(alpha, 1, 0):
        ax[1].plot(line, linestyle='-')

    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close() 
Example #12
Source File: movie.py    From kvae with MIT License 6 votes vote down vote up
def save_movies_to_frame(images, filename, cmap='Blues'):
    # Binarize images
    # images[images > 0] = 1.

    # Grid images
    images = np.swapaxes(images, 1, 0)
    images = np.array([combine_multiple_img(image) for image in images])

    # Collect to single image
    image = movie_to_frame(images)

    f = plt.figure(figsize=[12, 12])
    plt.imshow(image, cmap=plt.cm.get_cmap(cmap), interpolation='none', vmin=0, vmax=1)
    plt.axis('image')
    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close(f) 
Example #13
Source File: FirstDerivative.py    From pylops with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _matvec_centered(self, x):
        if not self.reshape:
            x = x.squeeze()
            y = np.zeros(self.N, self.dtype)
            y[1:-1] = (0.5 * x[2:] - 0.5 * x[0:-2]) / self.sampling
            if self.edge:
                y[0] = (x[1] - x[0]) / self.sampling
                y[-1] = (x[-1] - x[-2]) / self.sampling
        else:
            x = np.reshape(x, self.dims)
            if self.dir > 0:  # need to bring the dim. to derive to first dim.
                x = np.swapaxes(x, self.dir, 0)
            y = np.zeros(x.shape, self.dtype)
            y[1:-1] = (0.5 * x[2:] - 0.5 * x[0:-2]) / self.sampling
            if self.edge:
                y[0] = (x[1] - x[0]) / self.sampling
                y[-1] = (x[-1] - x[-2]) / self.sampling
            if self.dir > 0:
                y = np.swapaxes(y, 0, self.dir)
            y = y.ravel()
        return y 
Example #14
Source File: FirstDerivative.py    From pylops with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _rmatvec_forward(self, x):
        if not self.reshape:
            x = x.squeeze()
            y = np.zeros(self.N, self.dtype)
            y[:-1] -= x[:-1] / self.sampling
            y[1:] += x[:-1] / self.sampling
        else:
            x = np.reshape(x, self.dims)
            if self.dir > 0:  # need to bring the dim. to derive to first dim.
                x = np.swapaxes(x, self.dir, 0)
            y = np.zeros(x.shape, self.dtype)
            y[:-1] -= x[:-1] / self.sampling
            y[1:] += x[:-1] / self.sampling
            if self.dir > 0:
                y = np.swapaxes(y, 0, self.dir)
            y = y.ravel()
        return y 
Example #15
Source File: feat_slicing.py    From Attentive-Filtering-Network with MIT License 6 votes vote down vote up
def tensor_cnn_frame(mat, M):
    """Construct a tensor of shape (C x H x W) given an utterance matrix 
    for CNN
    """
    slice_mat = []
    for index in np.arange(len(mat)):
        if index < M:
            to_left = np.tile(mat[index], M).reshape((M,-1))
            rest = mat[index:index+M+1]
            context = np.vstack((to_left, rest))
        elif index >= len(mat)-M:
            to_right = np.tile(mat[index], M).reshape((M,-1))
            rest = mat[index-M:index+1]
            context = np.vstack((rest, to_right))
        else:
            context = mat[index-M:index+M+1]
        slice_mat.append(context)

    slice_mat = np.array(slice_mat)
    slice_mat = np.expand_dims(slice_mat, axis=1)
    slice_mat = np.swapaxes(slice_mat, 2, 3)
    
    return slice_mat 
Example #16
Source File: feat_slicing.py    From Attentive-Filtering-Network with MIT License 6 votes vote down vote up
def tensor_cnngru(mat):
    """Construct an utterance tensor for a given utterance matrix mat
    for CNN+GRU
    """
    mat = np.swapaxes(mat, 0, 1)
    div = int(mat.shape[1]/400)
    if div == 0: # short utt
        tensor_mat = mat
        while True:
            shape = tensor_mat.shape[1]
            if shape + mat.shape[1] < 400:
                tensor_mat = np.hstack((tensor_mat,mat))
            else:
                tensor_mat = np.hstack((tensor_mat,mat[:,:400-shape]))
                break
    elif div == 1: # truncate to 1
        tensor_mat = mat[:,:400]
    else:
        # TO DO: cut into 2
        tensor_mat = mat[:,:400]

    tensor_mat = np.expand_dims(tensor_mat, axis=2)
    print(tensor_mat.shape)
    return tensor_mat 
Example #17
Source File: matrixforwardsim.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def doperation(self, opLabel, flat=False, wrtFilter=None):
        """ Return the derivative of a length-1 (single-gate) sequence """
        dim = self.dim
        gate = self.sos.get_operation(opLabel)
        op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate)

        # Allocate memory for the final result
        num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter)
        flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd')

        _fas(flattened_dprod, [None, gpindices],
             gate.deriv_wrt_params(op_wrtFilter))  # (dim**2, nParams[opLabel])

        if _slct.length(gpindices) > 0:  # works for arrays too
            # Compute the derivative of the entire operation sequence with respect to the
            # gate's parameters and fill appropriate columns of flattened_dprod.
            #gate = self.sos.get_operation[opLabel] UNNEEDED (I think)
            _fas(flattened_dprod, [None, gpindices],
                 gate.deriv_wrt_params(op_wrtFilter))  # (dim**2, nParams in wrtFilter for opLabel)

        if flat:
            return flattened_dprod
        else:
            # axes = (gate_ij, prod_row, prod_col)
            return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) 
Example #18
Source File: np_conserved.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def iswapaxes(self, axis1, axis2):
        """Similar as ``np.swapaxes``; in place."""
        axis1 = self.get_leg_index(axis1)
        axis2 = self.get_leg_index(axis2)
        if axis1 == axis2:
            return self  # nothing to do
        swap = np.arange(self.rank, dtype=np.intp)
        swap[axis1], swap[axis2] = axis2, axis1
        legs = self.legs
        legs[axis1], legs[axis2] = legs[axis2], legs[axis1]
        labels = self._labels
        labels[axis1], labels[axis2] = labels[axis2], labels[axis1]
        self._set_shape()
        self._qdata = self._qdata[:, swap]
        self._qdata_sorted = False
        self._data = [t.swapaxes(axis1, axis2) for t in self._data]
        return self 
Example #19
Source File: FirstDerivative.py    From pylops with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _rmatvec_backward(self, x):
        if not self.reshape:
            x = x.squeeze()
            y = np.zeros(self.N, self.dtype)
            y[:-1] -= x[1:] / self.sampling
            y[1:] += x[1:] / self.sampling
        else:
            x = np.reshape(x, self.dims)
            if self.dir > 0:  # need to bring the dim. to derive to first dim.
                x = np.swapaxes(x, self.dir, 0)
            y = np.zeros(x.shape, self.dtype)
            y[:-1] -= x[1:] / self.sampling
            y[1:] += x[1:] / self.sampling
            if self.dir > 0:
                y = np.swapaxes(y, 0, self.dir)
            y = y.ravel()
        return y 
Example #20
Source File: SecondDerivative.py    From pylops with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _matvec(self, x):
        if not self.reshape:
            x = x.squeeze()
            y = np.zeros(self.N, self.dtype)
            y[1:-1] = (x[2:] - 2*x[1:-1] + x[0:-2]) / self.sampling**2
            if self.edge:
                y[0] = (x[0] - 2*x[1] + x[2]) / self.sampling**2
                y[-1] = (x[-3] - 2*x[-2] + x[-1]) / self.sampling**2
        else:
            x = np.reshape(x, self.dims)
            if self.dir > 0:  # need to bring the dim. to derive to first dim.
                x = np.swapaxes(x, self.dir, 0)
            y = np.zeros(x.shape, self.dtype)
            y[1:-1] = (x[2:] - 2*x[1:-1] + x[0:-2])/self.sampling**2
            if self.edge:
                y[0] = (x[0] - 2*x[1] + x[2]) / self.sampling ** 2
                y[-1] = (x[-3] - 2*x[-2] + x[-1]) / self.sampling ** 2
            if self.dir > 0:
                y = np.swapaxes(y, 0, self.dir)
            y = y.ravel()
        return y 
Example #21
Source File: predict.py    From cloudless with Apache License 2.0 5 votes vote down vote up
def _load_validation_data(validation_leveldb, width, height):
    """
    Loads all of our validation data from our leveldb database, producing unrolled numpy input
    vectors ready to test along with their correct, expected target values.
    """

    print "\tLoading validation data..."
    input_vectors = []
    expected_targets = []

    db = plyvel.DB(validation_leveldb)
    for key, value in db:
        datum = Datum()
        datum.ParseFromString(value)

        data = np.fromstring(datum.data, dtype=np.uint8)
        data = np.reshape(data, (3, height, width))
        # Move the color channel to the end to match what Caffe wants.
        data = np.swapaxes(data, 0, 2) # Swap channel with width.
        data = np.swapaxes(data, 0, 1) # Swap width with height, to yield final h x w x channel.

        input_vectors.append(data)
        expected_targets.append(datum.label)

    db.close()

    print "\t\tValidation data has %d images" % len(input_vectors)

    return {
        "input_vectors": np.asarray(input_vectors),
        "expected_targets": np.asarray(expected_targets)
    } 
Example #22
Source File: plot_dict_batch.py    From UnsupervisedGeometryAwareRepresentationLearning with GNU General Public License v3.0 5 votes vote down vote up
def tensor_imshow_normalized(ax, img, mean=None, stdDev=None, im_plot_handle=None, x_label=None, clip=True):
    npimg = img.numpy()
    npimg = np.swapaxes(npimg, 0, 2)
    npimg = np.swapaxes(npimg, 0, 1)

    if mean is None:
        mean = (0.0, 0.0, 0.0)
    mean = np.array(mean)
    if stdDev is None:
        stdDev = np.array([1.0, 1.0, 1.0])
    stdDev = np.array(stdDev)

    npimg = npimg * stdDev + mean  # unnormalize
    
    if clip:
        npimg = np.clip(npimg, 0, 1)

    if im_plot_handle is not None:
        im_plot_handle.set_array(npimg)
    else:
        im_plot_handle = ax.imshow(npimg)
        
    ax.tick_params(
        axis='x',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        bottom='off',      # ticks along the bottom edge are off
        top='off',         # ticks along the top edge are off
        labelbottom='off') # labels along the bottom edge are off
    # when plotting 2D keypoints on top, this ensures that it only plots on the image region
    ax.set_ylim([img.size()[1],0])

    if x_label is not None:
        plt.xlabel(x_label)   

    return im_plot_handle 
Example #23
Source File: image_testing.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def setImage(self, image=None, **kwds):
        if image is not None and self.__transpose is True:
            image = np.swapaxes(image, 0, 1)
        return ImageItem.setImage(self, image, **kwds) 
Example #24
Source File: atlas.py    From ibllib with MIT License 5 votes vote down vote up
def AllenAtlas(res_um=25, par=None):
    """
    Instantiates an atlas.BrainAtlas corresponding to the Allen CCF at the given resolution
    using the IBL Bregma and coordinate system
    :param res_um: 25 or 50 um
    :return: atlas.BrainAtlas
    """
    if par is None:
        # Bregma indices for the 10um Allen Brain Atlas, mlapdv
        pdefault = {
            'PATH_ATLAS': '/datadisk/BrainAtlas/ATLASES/Allen/',
            'FILE_REGIONS': str(Path(__file__).parent.joinpath('allen_structure_tree.csv')),
            'INDICES_BREGMA': list(np.array([1140 - (570 + 3.9), 540, 0 + 33.2]))
        }
        par = params.read('ibl_histology', default=pdefault)
        if not Path(par.PATH_ATLAS).exists():
            raise NotImplementedError("Atlas doesn't exist ! Mock option not implemented yet")
            # TODO: mock atlas to get only the coordinate framework
            pass
        params.write('ibl_histology', par)
    else:
        par = Bunch(par)
    # file_image = Path(path_atlas).joinpath(f'ara_nissl_{res_um}.nrrd')
    file_image = Path(par.PATH_ATLAS).joinpath(f'average_template_{res_um}.nrrd')
    file_label = Path(par.PATH_ATLAS).joinpath(f'annotation_{res_um}.nrrd')
    image, header = nrrd.read(file_image, index_order='C')  # dv, ml, ap
    image = np.swapaxes(np.swapaxes(image, 2, 0), 1, 2)  # image[iap, iml, idv]
    label, header = nrrd.read(file_label, index_order='C')  # dv, ml, ap
    label = np.swapaxes(np.swapaxes(label, 2, 0), 1, 2)  # label[iap, iml, idv]
    # resulting volumes origin: x right, y front, z top
    df_regions = pd.read_csv(par.FILE_REGIONS)
    regions = BrainRegions(id=df_regions.id.values,
                           name=df_regions.name.values,
                           acronym=df_regions.acronym.values)
    xyz2dims = np.array([1, 0, 2])
    dims2xyz = np.array([1, 0, 2])
    dxyz = res_um * 1e-6 * np.array([-1, -1, -1])
    ibregma = (np.array(par.INDICES_BREGMA) * 10 / res_um)
    return BrainAtlas(image, label, regions, dxyz, ibregma, dims2xyz=dims2xyz, xyz2dims=xyz2dims) 
Example #25
Source File: np_conserved.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def iscale_axis(self, s, axis=-1):
        """Scale with varying values along an axis; in place.

        Rescale to ``new_self[i1, ..., i_axis, ...] = s[i_axis] * self[i1, ..., i_axis, ...]``.

        Parameters
        ----------
        s : 1D array, len=self.shape[axis]
            The vector with which the axis should be scaled.
        axis : str|int
            The leg label or index for the axis which should be scaled.

        See also
        --------
        iproject : can be used to discard indices for which s is zero.
        """
        axis = self.get_leg_index(axis)
        s = np.asarray(s)
        if s.shape != (self.shape[axis], ):
            raise ValueError("s has wrong shape: " + str(s.shape) + " instead of " +
                             str(self.shape[axis]))
        self.dtype = np.find_common_type([self.dtype], [s.dtype])
        leg = self.legs[axis]
        if axis != self.rank - 1:
            self._data = [
                np.swapaxes(np.swapaxes(t, axis, -1) * s[leg.get_slice(qi)], axis, -1)
                for qi, t in zip(self._qdata[:, axis], self._data)
            ]
        else:  # optimize: no need to swap axes, if axis is -1.
            self._data = [
                t * s[leg.get_slice(qi)]  # (it's slightly faster for large arrays)
                for qi, t in zip(self._qdata[:, axis], self._data)
            ]
        return self 
Example #26
Source File: test_np_conserved.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def test_npc_Array_transpose():
    a = random_Array((20, 15, 10), chinfo)
    aflat = a.to_ndarray()
    for tr in [None, [2, 1, 0], (1, 2, 0), (0, 2, 1)]:
        atr = a.transpose(tr)
        atr.test_sanity()
        npt.assert_equal(atr.to_ndarray(), aflat.transpose(tr))
    ax1, ax2 = -1, 0
    a.iswapaxes(ax1, ax2)
    npt.assert_equal(a.to_ndarray(), aflat.swapaxes(ax1, ax2)) 
Example #27
Source File: test_np_conserved.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def test_npc_addition_transpose():
    # addition with labels and transposed axes
    a1 = np.random.random([3, 3, 4])
    a2 = np.swapaxes(a1, 0, 1)
    t1 = npc.Array.from_ndarray_trivial(a1, labels=['a', 'b', 'c'])
    t2 = npc.Array.from_ndarray_trivial(a2, labels=['b', 'a', 'c'])
    # TODO: for now warning
    with pytest.warns(FutureWarning):
        diff = npc.norm(t1 - t2)
    # TODO: when the behaviour is changed do
    #  diff = npc.norm(t1 - t2)
    #  assert diff < 1.e-10 
Example #28
Source File: test_core_execute.py    From mars with Apache License 2.0 5 votes vote down vote up
def testViewDataOnSwapaxes(self):
        data = np.random.rand(10, 20)
        a = tensor(data, chunk_size=6)
        b = swapaxes(a, 1, 0)
        a[1] = 10

        npa = data.copy()
        npb = np.swapaxes(npa, 1, 0)
        npa[1] = 10

        np.testing.assert_array_equal(b.execute(), npb)
        np.testing.assert_array_equal(a.execute(), npa) 
Example #29
Source File: CausalIntegration.py    From pylops with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _rmatvec(self, x):
        if self.reshape:
            x = np.reshape(x, self.dims)
        if self.dir != -1:
            x = np.swapaxes(x, self.dir, -1)
        xflip = np.flip(x, axis=-1)
        if self.halfcurrent:
            y = self.sampling * (np.cumsum(xflip, axis=-1) - xflip/2.)
        else:
            y = self.sampling * np.cumsum(xflip, axis=-1)
        y = np.flip(y, axis=-1)

        if self.dir != -1:
            y = np.swapaxes(y, -1, self.dir)
        return y.ravel() 
Example #30
Source File: stress_gui.py    From fenics-topopt with MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet)