Python numpy.resize() Examples

The following are 30 code examples for showing how to use numpy.resize(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: nstyle.py    License: 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 2
def test_PLinearDropInputs_ShouldDropRightParams(self):
        dropped_index = 0

        # assume input is 2x2x2, 2 layers of 2x2
        input_shape = (2, 2, 2)
        module = pnn.PLinear(8, 10)

        old_num_features = module.in_features
        old_weight = module.weight.data.cpu().numpy()
        resized_old_weight = np.resize(old_weight, (module.out_features, *input_shape))

        module.drop_inputs(input_shape, dropped_index)
        new_shape = module.weight.size()

        # ensure that the chosen index is dropped
        expected_weight = np.resize(np.delete(resized_old_weight, dropped_index, 1), new_shape)
        output = module.weight.data.cpu().numpy()
        self.assertTrue(np.array_equal(output, expected_weight))

        # ensure num features is reduced
        self.assertTrue(module.in_features, old_num_features-1) 
Example 3
Project: DenseMatchingBenchmark   Author: DeepMotionAIResearch   File: load_flow.py    License: MIT License 6 votes vote down vote up
def load_flo(file_path):
    """
    Read .flo file in MiddleBury format
    Code adapted from:
    http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy

    WARNING: this will work on little-endian architectures (eg Intel x86) only!
    Args:
        file_path string: file path(absolute)
    Returns:
        flow (numpy.array): data of image in (Height, Width, 2) layout
    """

    with open(file_path, 'rb') as f:
        magic = np.fromfile(f, np.float32, count=1)
        assert(magic == 202021.25)
        w = int(np.fromfile(f, np.int32, count=1))
        h = int(np.fromfile(f, np.int32, count=1))
        # print('Reading %d x %d flo file\n' % (w, h))
        flow = np.fromfile(f, np.float32, count=2 * w * h)
        # Reshape data into 3D array (columns, rows, bands)
        # The reshape here is for visualization, the original code is (w,h,2)
        flow = np.resize(flow, (h, w, 2))

    return flow 
Example 4
Project: weakalign   Author: ignacio-rocco   File: flow.py    License: MIT License 6 votes vote down vote up
def read_flo_file(filename,verbose=False):
    """
    Read from .flo optical flow file (Middlebury format)
    :param flow_file: name of the flow file
    :return: optical flow data in matrix
    
    adapted from https://github.com/liruoteng/OpticalFlowToolkit/
    
    """
    f = open(filename, 'rb')
    magic = np.fromfile(f, np.float32, count=1)
    data2d = None

    if 202021.25 != magic:
        raise TypeError('Magic number incorrect. Invalid .flo file')
    else:
        w = np.fromfile(f, np.int32, count=1)
        h = np.fromfile(f, np.int32, count=1)
        if verbose:
            print("Reading %d x %d flow file in .flo format" % (h, w))
        data2d = np.fromfile(f, np.float32, count=int(2 * w * h))
        # reshape data into 3D array (columns, rows, channels)
        data2d = np.resize(data2d, (h[0], w[0], 2))
    f.close()
    return data2d 
Example 5
Project: vnpy_crypto   Author: birforce   File: test_boolean.py    License: MIT License 6 votes vote down vote up
def test_broadcast(size, mask, item, box):
    selection = np.resize(mask, size)

    data = np.arange(size, dtype=float)

    # Construct the expected series by taking the source
    # data or item based on the selection
    expected = Series([item if use_item else data[
        i] for i, use_item in enumerate(selection)])

    s = Series(data)
    s[selection] = box(item)
    assert_series_equal(s, expected)

    s = Series(data)
    result = s.where(~selection, box(item))
    assert_series_equal(result, expected)

    s = Series(data)
    result = s.mask(selection, box(item))
    assert_series_equal(result, expected) 
Example 6
Project: conditional-motion-propagation   Author: XiaohangZhan   File: flowlib.py    License: MIT License 6 votes vote down vote up
def read_flo_file(filename, memcached=False):
    """
    Read from Middlebury .flo file
    :param flow_file: name of the flow file
    :return: optical flow data in matrix
    """
    if memcached:
        filename = io.BytesIO(filename)
    f = open(filename, 'rb')
    magic = np.fromfile(f, np.float32, count=1)[0]
    data2d = None

    if 202021.25 != magic:
        print('Magic number incorrect. Invalid .flo file')
    else:
        w = np.fromfile(f, np.int32, count=1)[0]
        h = np.fromfile(f, np.int32, count=1)[0]
        data2d = np.fromfile(f, np.float32, count=2 * w * h)
        # reshape data into 3D array (columns, rows, channels)
        data2d = np.resize(data2d, (h, w, 2))
    f.close()
    return data2d


# fast resample layer 
Example 7
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_pairwise.py    License: MIT License 6 votes vote down vote up
def test_check_preserve_type():
    # Ensures that type float32 is preserved.
    XA = np.resize(np.arange(40), (5, 8)).astype(np.float32)
    XB = np.resize(np.arange(40), (5, 8)).astype(np.float32)

    XA_checked, XB_checked = check_pairwise_arrays(XA, None)
    assert_equal(XA_checked.dtype, np.float32)

    # both float32
    XA_checked, XB_checked = check_pairwise_arrays(XA, XB)
    assert_equal(XA_checked.dtype, np.float32)
    assert_equal(XB_checked.dtype, np.float32)

    # mismatched A
    XA_checked, XB_checked = check_pairwise_arrays(XA.astype(np.float),
                                                   XB)
    assert_equal(XA_checked.dtype, np.float)
    assert_equal(XB_checked.dtype, np.float)

    # mismatched B
    XA_checked, XB_checked = check_pairwise_arrays(XA,
                                                   XB.astype(np.float))
    assert_equal(XA_checked.dtype, np.float)
    assert_equal(XB_checked.dtype, np.float) 
Example 8
Project: swiftnet   Author: orsic   File: flow_utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def readFlow(fn):
    """ Read .flo file in Middlebury format"""
    # Code adapted from:
    # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy

    # WARNING: this will work on little-endian architectures (eg Intel x86) only!
    # print 'fn = %s'%(fn)
    with open(fn, 'rb') as f:
        magic = np.fromfile(f, np.float32, count=1)
        if 202021.25 != magic:
            print('Magic number incorrect. Invalid .flo file')
            return None
        else:
            w = np.fromfile(f, np.int32, count=1)
            h = np.fromfile(f, np.int32, count=1)
            # print 'Reading %d x %d flo file\n' % (w, h)
            data = np.fromfile(f, np.float32, count=2 * int(w) * int(h))
            # Reshape data into 3D array (columns, rows, bands)
            # The reshape here is for visualization, the original code is (w,h,2)
            return np.resize(data, (int(h), int(w), 2)) 
Example 9
Project: mlnd_DeepTesla   Author: omnigeeker   File: run.py    License: GNU General Public License v3.0 6 votes vote down vote up
def img_pre_process(img):
    """
    Processes the image and returns it
    :param img: The image to be processed
    :return: Returns the processed image
    """
    ## Chop off 1/3 from the top and cut bottom 150px(which contains the head of car)
    shape = img.shape
    img = img[int(shape[0]/3):shape[0]-150, 0:shape[1]]
    ## Resize the image
    img = cv2.resize(img, (params.FLAGS.img_w, params.FLAGS.img_h), interpolation=cv2.INTER_AREA)
    ## Return the image sized as a 4D array
    return np.resize(img, (params.FLAGS.img_w, params.FLAGS.img_h, params.FLAGS.img_c))


## Process video 
Example 10
Project: fenics-topopt   Author: zfergus   File: triangulate.py    License: MIT License 5 votes vote down vote up
def mesh_from_img(img):
    nv = (img.shape[0] + 1) * (img.shape[1] + 1)
    nf = img.size * 2

    v_count = 0
    f_count = 0
    V_dict = {}

    V = np.zeros([nv, 2])
    F = np.zeros([nf, 3], dtype=np.int)

    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            val = img[i, j]
            if val == 255.0:
                continue

            v_idx = []
            for v_i in [(i, j), (i + 1, j), (i, j + 1), (i + 1, j + 1)]:
                if v_i in V_dict:
                    v_idx.append(V_dict[v_i])
                else:
                    V_dict[v_i] = v_count
                    V[v_count, :] = np.array((v_i[1], -v_i[0]))
                    v_count += 1
                    v_idx.append(v_count - 1)

            v1, v2, v3, v4 = v_idx

            F[f_count, :] = np.array([v1, v2, v4])
            F[f_count + 1, :] = np.array([v1, v4, v3])
            f_count += 2

    V = np.resize(V, [v_count, 2])
    F = np.resize(F, [f_count, 3])

    return V, F 
Example 11
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: nstyle.py    License: Apache License 2.0 5 votes vote down vote up
def get_args(arglist=None):
    parser = argparse.ArgumentParser(description='neural style')

    parser.add_argument('--model', type=str, default='vgg19',
                        choices = ['vgg'],
                        help = 'the pretrained model to use')
    parser.add_argument('--content-image', type=str, default='input/IMG_4343.jpg',
                        help='the content image')
    parser.add_argument('--style-image', type=str, default='input/starry_night.jpg',
                        help='the style image')
    parser.add_argument('--stop-eps', type=float, default=.005,
                        help='stop if the relative chanage is less than eps')
    parser.add_argument('--content-weight', type=float, default=10,
                        help='the weight for the content image')
    parser.add_argument('--style-weight', type=float, default=1,
                        help='the weight for the style image')
    parser.add_argument('--tv-weight', type=float, default=1e-2,
                        help='the magtitute on TV loss')
    parser.add_argument('--max-num-epochs', type=int, default=1000,
                        help='the maximal number of training epochs')
    parser.add_argument('--max-long-edge', type=int, default=600,
                        help='resize the content image')
    parser.add_argument('--lr', type=float, default=.001,
                        help='the initial learning rate')
    parser.add_argument('--gpu', type=int, default=0,
                        help='which gpu card to use, -1 means using cpu')
    parser.add_argument('--output_dir', type=str, default='output/',
                        help='the output image')
    parser.add_argument('--save-epochs', type=int, default=50,
                        help='save the output every n epochs')
    parser.add_argument('--remove-noise', type=float, default=.02,
                        help='the magtitute to remove noise')
    parser.add_argument('--lr-sched-delay', type=int, default=75,
                        help='how many epochs between decreasing learning rate')
    parser.add_argument('--lr-sched-factor', type=int, default=0.9,
                        help='factor to decrease learning rate on schedule')

    if arglist is None:
        return parser.parse_args()
    else:
        return parser.parse_args(arglist) 
Example 12
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: nstyle.py    License: Apache License 2.0 5 votes vote down vote up
def PreprocessStyleImage(path, shape):
    img = io.imread(path)
    resized_img = transform.resize(img, (shape[2], shape[3]))
    sample = np.asarray(resized_img) * 256
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
Example 13
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: nstyle.py    License: Apache License 2.0 5 votes vote down vote up
def PostprocessImage(img):
    img = np.resize(img, (3, img.shape[2], img.shape[3]))
    img[0, :] += 123.68
    img[1, :] += 116.779
    img[2, :] += 103.939
    img = np.swapaxes(img, 1, 2)
    img = np.swapaxes(img, 0, 2)
    img = np.clip(img, 0, 255)
    return img.astype('uint8') 
Example 14
def PreprocessContentImage(path, short_edge, dshape=None):
    img = io.imread(path)
    #logging.info("load the content image, size = %s", img.shape[:2])
    factor = float(short_edge) / min(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
    if dshape is not None:
        # random crop
        xx = int((sample.shape[0] - dshape[2]))
        yy = int((sample.shape[1] - dshape[3]))
        xstart = random.randint(0, xx)
        ystart = random.randint(0, yy)
        xend = xstart + dshape[2]
        yend = ystart + dshape[3]
        sample = sample[xstart:xend, ystart:yend, :]

    # 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", sample.shape)
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
Example 15
def PostprocessImage(img):
    img = np.resize(img, (3, img.shape[2], img.shape[3]))
    img[0, :] += 123.68
    img[1, :] += 116.779
    img[2, :] += 103.939
    img = np.swapaxes(img, 1, 2)
    img = np.swapaxes(img, 0, 2)
    img = np.clip(img, 0, 255)
    return img.astype('uint8') 
Example 16
Project: DOTA_models   Author: ringringyi   File: controller.py    License: Apache License 2.0 5 votes vote down vote up
def convert_to_batched_episodes(self, episodes, max_length=None):
    """Convert batch-major list of episodes to time-major batch of episodes."""
    lengths = [len(ep[-2]) for ep in episodes]
    max_length = max_length or max(lengths)

    new_episodes = []
    for ep, length in zip(episodes, lengths):
      initial, observations, actions, rewards, terminated = ep
      observations = [np.resize(obs, [max_length + 1] + list(obs.shape)[1:])
                      for obs in observations]
      actions = [np.resize(act, [max_length + 1] + list(act.shape)[1:])
                 for act in actions]
      pads = np.array([0] * length + [1] * (max_length - length))
      rewards = np.resize(rewards, [max_length]) * (1 - pads)
      new_episodes.append([initial, observations, actions, rewards,
                           terminated, pads])

    (initial, observations, actions, rewards,
     terminated, pads) = zip(*new_episodes)
    observations = [np.swapaxes(obs, 0, 1)
                    for obs in zip(*observations)]
    actions = [np.swapaxes(act, 0, 1)
               for act in zip(*actions)]
    rewards = np.transpose(rewards)
    pads = np.transpose(pads)

    return (initial, observations, actions, rewards, terminated, pads) 
Example 17
Project: radiometric_normalization   Author: planetlabs   File: validation_tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_sum_of_rmse(self):
        mask1 = [[0, 1], [0, 0]]
        bands1 = numpy.resize(range(8), (2, 2, 2))
        image1 = gimage.GImage(bands1, mask1, {})

        mask2 = [[0, 0], [1, 0]]
        bands2 = numpy.resize(range(8, 16), (2, 2, 2))
        image2 = gimage.GImage(bands2, mask2, {})
        result = validation.sum_of_rmse(image1, image2)

        expected = 16
        assert result == expected 
Example 18
def resize_arrays(self, new_size, arrays):
        """
        Resize all the arrays to new_size along dimension 0.
        Sometimes we need to initialise a np.zeros() to an arbitrary size
        and then cut it down to out intended new_size.
        """
        logger.debug("Resizing batch_size in structures from %d -> %d",
                    arrays[0].shape[0], new_size)

        for i, array in enumerate(arrays):
            arrays[i] = np.resize(array, (new_size, array.shape[1],
                                          array.shape[2]))
        return arrays 
Example 19
Project: network-slimming   Author: Eric-mingjie   File: channel_selection.py    License: MIT License 5 votes vote down vote up
def forward(self, input_tensor):
        """
        Parameter
        ---------
        input_tensor: (N,C,H,W). It should be the output of BatchNorm2d layer.
        """
        selected_index = np.squeeze(np.argwhere(self.indexes.data.cpu().numpy()))
        if selected_index.size == 1:
            selected_index = np.resize(selected_index, (1,)) 
        output = input_tensor[:, selected_index, :, :]
        return output 
Example 20
Project: reconstructing_faces_from_voices   Author: cmu-mlsp   File: mfcc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def sig2s2mfc(self, sig):
        nfr = int(len(sig) / self.fshift + 1)
        mfcc = numpy.zeros((nfr, self.ncep), 'd')
        fr = 0
        while fr < nfr:
            start = round(fr * self.fshift)
            end = min(len(sig), start + self.wlen)
            frame = sig[start:end]
            if len(frame) < self.wlen:
                frame = numpy.resize(frame,self.wlen)
                frame[self.wlen:] = 0
            mfcc[fr] = self.frame2s2mfc(frame)
            fr = fr + 1
        return mfcc 
Example 21
Project: reconstructing_faces_from_voices   Author: cmu-mlsp   File: mfcc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def sig2logspec(self, sig):
        nfr = int(len(sig) / self.fshift + 1)
        mfcc = numpy.zeros((nfr, self.nfilt), 'd')
        fr = 0
        while fr < nfr:
            start = round(fr * self.fshift)
            end = min(len(sig), start + self.wlen)
            frame = sig[start:end]
            if len(frame) < self.wlen:
                frame = numpy.resize(frame,self.wlen)
                frame[self.wlen:] = 0
            mfcc[fr] = self.frame2logspec(frame)
            fr = fr + 1
        return mfcc 
Example 22
Project: recruit   Author: Frank-qlu   File: mrecords.py    License: Apache License 2.0 5 votes vote down vote up
def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None,
                formats=None, names=None, titles=None,
                byteorder=None, aligned=False,
                mask=nomask, hard_mask=False, fill_value=None, keep_mask=True,
                copy=False,
                **options):

        self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset,
                                strides=strides, formats=formats, names=names,
                                titles=titles, byteorder=byteorder,
                                aligned=aligned,)

        mdtype = ma.make_mask_descr(self.dtype)
        if mask is nomask or not np.size(mask):
            if not keep_mask:
                self._mask = tuple([False] * len(mdtype))
        else:
            mask = np.array(mask, copy=copy)
            if mask.shape != self.shape:
                (nd, nm) = (self.size, mask.size)
                if nm == 1:
                    mask = np.resize(mask, self.shape)
                elif nm == nd:
                    mask = np.reshape(mask, self.shape)
                else:
                    msg = "Mask and data not compatible: data size is %i, " + \
                          "mask size is %i."
                    raise MAError(msg % (nd, nm))
                copy = True
            if not keep_mask:
                self.__setmask__(mask)
                self._sharedmask = True
            else:
                if mask.dtype == mdtype:
                    _mask = mask
                else:
                    _mask = np.array([tuple([m] * len(mdtype)) for m in mask],
                                     dtype=mdtype)
                self._mask = _mask
        return self 
Example 23
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_copies(self):
        A = np.array([[1, 2], [3, 4]])
        Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
        assert_equal(np.resize(A, (2, 4)), Ar1)

        Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
        assert_equal(np.resize(A, (4, 2)), Ar2)

        Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]])
        assert_equal(np.resize(A, (4, 3)), Ar3) 
Example 24
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_zeroresize(self):
        A = np.array([[1, 2], [3, 4]])
        Ar = np.resize(A, (0,))
        assert_array_equal(Ar, np.array([]))
        assert_equal(A.dtype, Ar.dtype)

        Ar = np.resize(A, (0, 2))
        assert_equal(Ar.shape, (0, 2))

        Ar = np.resize(A, (2, 0))
        assert_equal(Ar.shape, (2, 0)) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_reshape_from_zero(self):
        # See also gh-6740
        A = np.zeros(0, dtype=[('a', np.float32, 1)])
        Ar = np.resize(A, (2, 1))
        assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype))
        assert_equal(A.dtype, Ar.dtype) 
Example 26
Project: usv_sim_lsa   Author: disaster-robotics-proalertas   File: windOpenFoam.py    License: Apache License 2.0 5 votes vote down vote up
def parse_config_file(config_file_name):
	global pkg_path, fieldNames, fieldsVX, fieldsVY, fieldsVZ
	global originX, originY, originZ, cellSizeX, cellSizeY, cellSizeZ
	global sizeX, sizeY, sizeZ, time
	with open(pkg_path+"/"+config_file_name, 'r') as stream:
        	data_loaded = yaml.load(stream)
	print ('--------------------- Loading yaml file ', config_file_name)
	print ('--------------------- data_loaded: ', data_loaded)
	sizeX=data_loaded['size'][0]
	sizeY=data_loaded['size'][1]
	sizeZ=data_loaded['size'][2]
	originX=data_loaded['origin'][0]
	originY=data_loaded['origin'][1]
	originZ=data_loaded['origin'][2]
	cellSizeX=data_loaded['cellsize'][0]
	cellSizeY=data_loaded['cellsize'][1]
	cellSizeZ=data_loaded['cellsize'][2]
	time = data_loaded['time']
	if (time > len(data_loaded['fields'])):
		time = len(data_loaded['fields'])
	print "time: ",time
	print sizeX
	print sizeY
	print sizeZ

	for i in range(0, len(data_loaded['fields'])):
	   fieldNames.append(pkg_path+"/"+data_loaded['fields'][i])
	   fieldsVX.append([])
	   fieldsVY.append([])
	   fieldsVZ.append([])
	   fieldsVX[i]=numpy.resize(fieldsVX[i], (sizeX,sizeY,sizeZ));
	   fieldsVY[i]=numpy.resize(fieldsVY[i], (sizeX,sizeY,sizeZ));
	   fieldsVZ[i]=numpy.resize(fieldsVZ[i], (sizeX,sizeY,sizeZ));

	

	#fields[0] = data_loaded['fields'][0];
	#fields[1] = data_loaded['fields'][1]; 
Example 27
Project: benchmarks   Author: tensorflow   File: test_util.py    License: Apache License 2.0 5 votes vote down vote up
def get_fake_var_update_inputs():
  """Returns fake input 1x1 images to use in variable update tests."""
  # BenchmarkCNN divides by 127.5 then subtracts 1.0 from the images, so after
  # that, the images will be -1., 0., 1., ..., 14.
  return np.resize(127.5 * np.array(range(16)), (16, 1, 1, 1)) 
Example 28
Project: formulas   Author: vinci1it2000   File: __init__.py    License: European Union Public License 1.1 5 votes vote down vote up
def collapse(self, shape):
        if self._collapse_value is not None and \
                tuple(shape) == (1, 1) != self.shape:
            return self._collapse_value
        return np.resize(self, shape) 
Example 29
Project: lambda-packs   Author: ryfeus   File: mrecords.py    License: MIT License 5 votes vote down vote up
def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None,
                formats=None, names=None, titles=None,
                byteorder=None, aligned=False,
                mask=nomask, hard_mask=False, fill_value=None, keep_mask=True,
                copy=False,
                **options):

        self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset,
                                strides=strides, formats=formats, names=names,
                                titles=titles, byteorder=byteorder,
                                aligned=aligned,)

        mdtype = ma.make_mask_descr(self.dtype)
        if mask is nomask or not np.size(mask):
            if not keep_mask:
                self._mask = tuple([False] * len(mdtype))
        else:
            mask = np.array(mask, copy=copy)
            if mask.shape != self.shape:
                (nd, nm) = (self.size, mask.size)
                if nm == 1:
                    mask = np.resize(mask, self.shape)
                elif nm == nd:
                    mask = np.reshape(mask, self.shape)
                else:
                    msg = "Mask and data not compatible: data size is %i, " + \
                          "mask size is %i."
                    raise MAError(msg % (nd, nm))
                copy = True
            if not keep_mask:
                self.__setmask__(mask)
                self._sharedmask = True
            else:
                if mask.dtype == mdtype:
                    _mask = mask
                else:
                    _mask = np.array([tuple([m] * len(mdtype)) for m in mask],
                                     dtype=mdtype)
                self._mask = _mask
        return self 
Example 30
Project: lambda-packs   Author: ryfeus   File: fitpack2.py    License: MIT License 5 votes vote down vote up
def _reset_nest(self, data, nest=None):
        n = data[10]
        if nest is None:
            k,m = data[5],len(data[0])
            nest = m+k+1  # this is the maximum bound for nest
        else:
            if not n <= nest:
                raise ValueError("`nest` can only be increased")
        t, c, fpint, nrdata = [np.resize(data[j], nest) for j in [8,9,11,12]]

        args = data[:8] + (t,c,n,fpint,nrdata,data[13])
        data = dfitpack.fpcurf1(*args)
        return data