numpy.nditer

Here are the examples of the python api numpy.nditer taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

185 Examples 7

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_best_order_multi_index_1d():
    # The multi-indices should be correct with any reordering

    a = arange(4)
    # 1D order
    i = nditer(a, ['multi_index'], [['readonly']])
    assert_equal(iter_multi_index(i), [(0,), (1,), (2,), (3,)])
    # 1D reversed order
    i = nditer(a[::-1], ['multi_index'], [['readonly']])
    assert_equal(iter_multi_index(i), [(3,), (2,), (1,), (0,)])

def test_iter_best_order_multi_index_2d():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_best_order_c_index_1d():
    # The C index should be correct with any reordering

    a = arange(4)
    # 1D order
    i = nditer(a, ['c_index'], [['readonly']])
    assert_equal(iter_indices(i), [0, 1, 2, 3])
    # 1D reversed order
    i = nditer(a[::-1], ['c_index'], [['readonly']])
    assert_equal(iter_indices(i), [3, 2, 1, 0])

def test_iter_best_order_c_index_2d():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_best_order_f_index_1d():
    # The Fortran index should be correct with any reordering

    a = arange(4)
    # 1D order
    i = nditer(a, ['f_index'], [['readonly']])
    assert_equal(iter_indices(i), [0, 1, 2, 3])
    # 1D reversed order
    i = nditer(a[::-1], ['f_index'], [['readonly']])
    assert_equal(iter_indices(i), [3, 2, 1, 0])

def test_iter_best_order_f_index_2d():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_slice():
    a, b, c = np.arange(3), np.arange(3), np.arange(3.)
    i = nditer([a, b, c], [], ['readwrite'])
    i[0:2] = (3, 3)
    assert_equal(a, [3, 1, 2])
    assert_equal(b, [3, 1, 2])
    assert_equal(c, [0, 1, 2])
    i[1] = 12
    assert_equal(i[0:2], [3, 12])

def test_iter_nbo_align_contig():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_allocate_output_simple():
    # Check that the iterator will properly allocate outputs

    # Simple case
    a = arange(6)
    i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
                        op_dtypes=[None, np.dtype('f4')])
    assert_equal(i.operands[1].shape, a.shape)
    assert_equal(i.operands[1].dtype, np.dtype('f4'))

def test_iter_allocate_output_buffered_readwrite():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_allocate_output_buffered_readwrite():
    # Allocated output with buffering + delay_bufalloc

    a = arange(6)
    i = nditer([a, None], ['buffered', 'delay_bufalloc'],
                        [['readonly'], ['allocate', 'readwrite']])
    i.operands[1][:] = 1
    i.reset()
    for x in i:
        x[1][...] += x[0][...]
    assert_equal(i.operands[1], a+1)

def test_iter_allocate_output_itorder():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_allocate_output_opaxes():
    # Specifying op_axes should work

    a = arange(24, dtype='i4').reshape(2, 3, 4)
    i = nditer([None, a], [], [['writeonly', 'allocate'], ['readonly']],
                        op_dtypes=[np.dtype('u4'), None],
                        op_axes=[[1, 2, 0], None])
    assert_equal(i.operands[0].shape, (4, 2, 3))
    assert_equal(i.operands[0].strides, (4, 48, 16))
    assert_equal(i.operands[0].dtype, np.dtype('u4'))

def test_iter_allocate_output_types_promotion():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_allocate_output_types_byte_order():
    # Verify the rules for byte order changes

    # When there's just one input, the output type exactly matches
    a = array([3], dtype='u4').newbyteorder()
    i = nditer([a, None], [],
                    [['readonly'], ['writeonly', 'allocate']])
    assert_equal(i.dtypes[0], i.dtypes[1])
    # With two or more inputs, the output type is in native byte order
    i = nditer([a, a, None], [],
                    [['readonly'], ['readonly'], ['writeonly', 'allocate']])
    assert_(i.dtypes[0] != i.dtypes[2])
    assert_equal(i.dtypes[0].newbyteorder('='), i.dtypes[2])

def test_iter_allocate_output_types_scalar():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_allocate_output_types_scalar():
    # If the inputs are all scalars, the output should be a scalar

    i = nditer([None, 1, 2.3, np.float32(12), np.complex128(3)], [],
                [['writeonly', 'allocate']] + [['readonly']]*4)
    assert_equal(i.operands[0].dtype, np.dtype('complex128'))
    assert_equal(i.operands[0].ndim, 0)

def test_iter_allocate_output_subtype():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_remove_axis():
    a = arange(24).reshape(2, 3, 4)

    i = nditer(a, ['multi_index'])
    i.remove_axis(1)
    assert_equal([x for x in i], a[:, 0,:].ravel())

    a = a[::-1,:,:]
    i = nditer(a, ['multi_index'])
    i.remove_axis(0)
    assert_equal([x for x in i], a[0,:,:].ravel())

def test_iter_remove_multi_index_inner_loop():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_write_buffering():
    # Test that buffering of writes is working

    # F-order swapped array
    a = np.arange(24).reshape(2, 3, 4).T.newbyteorder().byteswap()
    i = nditer(a, ['buffered'],
                   [['readwrite', 'nbo', 'aligned']],
                   casting='equiv',
                   order='C',
                   buffersize=16)
    x = 0
    while not i.finished:
        i[0] = x
        x += 1
        i.iternext()
    assert_equal(a.ravel(order='C'), np.arange(24))

def test_iter_buffering_delayed_alloc():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_buffered_cast_simple():
    # Test that buffering can handle a simple cast

    a = np.arange(10, dtype='f4')
    i = nditer(a, ['buffered', 'external_loop'],
                   [['readwrite', 'nbo', 'aligned']],
                   casting='same_kind',
                   op_dtypes=[np.dtype('f8')],
                   buffersize=3)
    for v in i:
        v[...] *= 2

    assert_equal(a, 2*np.arange(10, dtype='f4'))

def test_iter_buffered_cast_byteswapped():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_buffering_string():
    # Safe casting disallows shrinking strings
    a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_)
    assert_equal(a.dtype, np.dtype('S4'))
    assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
                  op_dtypes='S2')
    i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6')
    assert_equal(i[0], b'abc')
    assert_equal(i[0].dtype, np.dtype('S6'))

    a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode)
    assert_equal(a.dtype, np.dtype('U4'))
    assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
                    op_dtypes='U2')
    i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6')
    assert_equal(i[0], u'abc')
    assert_equal(i[0].dtype, np.dtype('U6'))

def test_iter_buffering_growinner():

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_buffering_growinner():
    # Test that the inner loop grows when no buffering is needed
    a = np.arange(30)
    i = nditer(a, ['buffered', 'growinner', 'external_loop'],
                           buffersize=5)
    # Should end up with just one inner loop here
    assert_equal(i[0].size, a.size)


@dec.slow

3 Source : test_nditer.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_iter_no_broadcast():
    # Test that the no_broadcast flag works
    a = np.arange(24).reshape(2, 3, 4)
    b = np.arange(6).reshape(2, 3, 1)
    c = np.arange(12).reshape(3, 4)

    nditer([a, b, c], [],
           [['readonly', 'no_broadcast'],
            ['readonly'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                  [['readonly'], ['readonly', 'no_broadcast'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                  [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])


class TestIterNested(object):

3 Source : test_nditer.py
with MIT License
from alvarobartt

def test_iter_slice():
    a, b, c = np.arange(3), np.arange(3), np.arange(3.)
    i = nditer([a, b, c], [], ['readwrite'])
    with i:
        i[0:2] = (3, 3)
        assert_equal(a, [3, 1, 2])
        assert_equal(b, [3, 1, 2])
        assert_equal(c, [0, 1, 2])
        i[1] = 12
        assert_equal(i[0:2], [3, 12])

def test_iter_assign_mapping():

3 Source : test_nditer.py
with MIT License
from alvarobartt

def test_iter_allocate_output_buffered_readwrite():
    # Allocated output with buffering + delay_bufalloc

    a = arange(6)
    i = nditer([a, None], ['buffered', 'delay_bufalloc'],
                        [['readonly'], ['allocate', 'readwrite']])
    with i:
        i.operands[1][:] = 1
        i.reset()
        for x in i:
            x[1][...] += x[0][...]
        assert_equal(i.operands[1], a+1)

def test_iter_allocate_output_itorder():

3 Source : test_nditer.py
with MIT License
from alvarobartt

def test_iter_write_buffering():
    # Test that buffering of writes is working

    # F-order swapped array
    a = np.arange(24).reshape(2, 3, 4).T.newbyteorder().byteswap()
    i = nditer(a, ['buffered'],
                   [['readwrite', 'nbo', 'aligned']],
                   casting='equiv',
                   order='C',
                   buffersize=16)
    x = 0
    with i:
        while not i.finished:
            i[0] = x
            x += 1
            i.iternext()
    assert_equal(a.ravel(order='C'), np.arange(24))

def test_iter_buffering_delayed_alloc():

3 Source : test_nditer.py
with MIT License
from alvarobartt

def test_iter_buffered_cast_simple():
    # Test that buffering can handle a simple cast

    a = np.arange(10, dtype='f4')
    i = nditer(a, ['buffered', 'external_loop'],
                   [['readwrite', 'nbo', 'aligned']],
                   casting='same_kind',
                   op_dtypes=[np.dtype('f8')],
                   buffersize=3)
    with i:
        for v in i:
            v[...] *= 2

    assert_equal(a, 2*np.arange(10, dtype='f4'))

def test_iter_buffered_cast_byteswapped():

3 Source : test_nditer.py
with MIT License
from alvarobartt

def test_iter_buffering_growinner():
    # Test that the inner loop grows when no buffering is needed
    a = np.arange(30)
    i = nditer(a, ['buffered', 'growinner', 'external_loop'],
                           buffersize=5)
    # Should end up with just one inner loop here
    assert_equal(i[0].size, a.size)


@pytest.mark.slow

3 Source : utils.py
with Apache License 2.0
from criteo-research

def compute_2i_regularization_id(prods, num_products):
    """Compute the ID for the regularization for the 2i approach"""

    reg_ids = []
    # Loop through batch and compute if the product ID is greater than the number of products
    for x in np.nditer(prods):
        if x >= num_products:
            reg_ids.append(x)
        elif x   <   num_products:
            reg_ids.append(x + num_products) # Add number of products to create the 2i representation 

    return np.asarray(reg_ids)

def compute_treatment_or_control(prods, num_products):

3 Source : utils.py
with Apache License 2.0
from criteo-research

def compute_treatment_or_control(prods, num_products):
    """Compute if product is in treatment or control"""
    # Return the control product places and treatment places as 1's in a binary matrix.
    ids = []
    for x in np.nditer(prods):
        # Greater than the number of products
        if x >= num_products:
            ids.append(0)
        elif x   <   num_products:
            ids.append(1)
    # create the binary mask and return 
    return np.asarray(ids), np.logical_not(np.asarray(ids)).astype(int)

def compute_bootstraps_2i(sess, model, test_user_batch, test_product_batch, test_label_batch, test_logits, ap_mse_loss, ap_log_loss):

3 Source : test_nditer.py
with Apache License 2.0
from dashanji

def test_iter_buffering_string():
    # Safe casting disallows shrinking strings
    a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_)
    assert_equal(a.dtype, np.dtype('S4'))
    assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
                  op_dtypes='S2')
    i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6')
    assert_equal(i[0], b'abc')
    assert_equal(i[0].dtype, np.dtype('S6'))

    a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode_)
    assert_equal(a.dtype, np.dtype('U4'))
    assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
                    op_dtypes='U2')
    i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6')
    assert_equal(i[0], u'abc')
    assert_equal(i[0].dtype, np.dtype('U6'))

def test_iter_buffering_growinner():

3 Source : test_nditer.py
with Apache License 2.0
from dashanji

def test_iter_no_broadcast():
    # Test that the no_broadcast flag works
    a = np.arange(24).reshape(2, 3, 4)
    b = np.arange(6).reshape(2, 3, 1)
    c = np.arange(12).reshape(3, 4)

    nditer([a, b, c], [],
           [['readonly', 'no_broadcast'],
            ['readonly'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                  [['readonly'], ['readonly', 'no_broadcast'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                  [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])


class TestIterNested:

3 Source : metrics.py
with BSD 3-Clause "New" or "Revised" License
from deep500

    def end(self, outputs: Dict[str, np.ndarray]):
        out = outputs[self._label]
        for outclass in np.nditer(out):
            self.hist[outclass] += 1

    def measure(self, *unused) -> List[int]:

3 Source : selection.py
with BSD 3-Clause "New" or "Revised" License
from FeatureLabs

def _edge_maker(adj, thresh):
    '''Make all edges at a given threshold. Prerequisite
    to make the associated graph.
    '''
    it = np.nditer(adj, flags=['multi_index'])
    edges = []
    for val in it:
        if val   <  = thresh:
            edges.append(it.multi_index)
    return edges


def find_connected_components(vertices, edges):

3 Source : varlib.py
with MIT License
from GeoStat-Framework

    def __iter__(self):
        """Iterate over Observations."""
        if self.state == "transient":
            self.__it = np.nditer(self.time, flags=["multi_index"])
        else:
            self.__itfinished = False
        return self

    def __next__(self):

3 Source : formats.py
with BSD 3-Clause "New" or "Revised" License
from holzschu

    def value(self):
        iterator = np.nditer([self.jd1, self.jd2, None],
                             flags=['refs_ok', 'zerosize_ok'],
                             op_dtypes=[None, None, object])

        for jd1, jd2, out in iterator:
            jd1_, jd2_ = day_frac(jd1, jd2)
            out[...] = datetime.timedelta(days=jd1_,
                                          microseconds=jd2_*86400*1e6)

        return self.mask_if_needed(iterator.operands[-1])


def _validate_jd_for_storage(jd):

3 Source : magnetic_time.py
with MIT License
from igp-gravity

    def reference(cls, times, lats_ngp, lons_ngp):
        times = asarray(times)
        lats_ngp = asarray(lats_ngp)
        lons_ngp = asarray(lons_ngp)
        results = empty(times.shape)
        iterator = nditer(
            [times, lats_ngp, lons_ngp, results],
            op_flags=[
                ['readonly'], ['readonly'], ['readonly'], ['writeonly'],
            ],
        )
        for time, lat_ngp, lon_ngp, result in iterator:
            result[...] = cls.ref_mjd2000_to_magnetic_universal_time(
                time, lat_ngp, lon_ngp
            )
        return results

    @staticmethod

3 Source : dpnpimpl.py
with Apache License 2.0
from IntelPython

def _check_finite_matrix(a):
    for v in np.nditer(a):
        if not np.isfinite(v.item()):
            raise np.linalg.LinAlgError("Array must not contain infs or NaNs.")


@register_jitable

3 Source : calibrate_mupots_intrinsics.py
with MIT License
from isarandi

def main():
    if 'DATA_ROOT' not in os.environ:
        print('Set the DATA_ROOT environment variable to the parent dir of the mupots directory.')
        sys.exit(1)
    intrinsics_per_sequence = {}
    for i_seq in range(1, 21):
        anno_path = f'{os.environ["DATA_ROOT"]}/mupots/TS{i_seq}/annot.mat'
        anno = scipy.io.loadmat(anno_path, struct_as_record=False, squeeze_me=True)['annotations']
        points2d = np.concatenate([x.annot2.T for x in np.nditer(anno) if x.isValidFrame])
        points3d = np.concatenate([x.annot3.T for x in np.nditer(anno) if x.isValidFrame])
        intrinsics_per_sequence[f'TS{i_seq}'] = estimate_intrinsic_matrix(points2d, points3d)

    with open(f'{os.environ["DATA_ROOT"]}/mupots/camera_intrinsics.json', 'w') as file:
        return json.dump(intrinsics_per_sequence, file)


def estimate_intrinsic_matrix(points2d, points3d):

3 Source : mscore.py
with GNU General Public License v3.0
from isjerryxiao

    def __do_i_win(self):
        unopened = 0
        mines_opened = 0
        for x in np.nditer(self.map):
            if x   <  = 8:
                unopened += 1
            elif x in (19, DEAD):
                mines_opened += 1
        if mines_opened == self.mines:
            return True
        elif unopened == 0:
            return True
        else:
            return False
    def __open(self, row, col, automatic=False):

3 Source : box_finder.py
with MIT License
from j-towns

def box_finder_generic(arr, look_for, switch_to):
  warn("Falling back on slow box finder for array with ndim > 6")
  it = np.nditer(arr, flags=['multi_index'])
  for k in it:
    if k == look_for:
      starts = it.multi_index
      arr[starts] = switch_to
      sizes = arr.ndim * [1]
      for d in range(arr.ndim):
        box_iter = test_boxes(starts, sizes, d)
        test_box = next(box_iter)
        while (starts[d] + sizes[d]   <   arr.shape[d]
               and np.all(arr[test_box] == look_for)):
          arr[test_box] = switch_to
          sizes[d] = sizes[d] + 1
          test_box = next(box_iter)
      yield starts, sizes

def box_finder0(arr, look_for, switch_to):

3 Source : test_nditer.py
with MIT License
from ktraunmueller

def test_iter_allocate_output_opaxes():
    # Specifing op_axes should work

    a = arange(24, dtype='i4').reshape(2, 3, 4)
    i = nditer([None, a], [], [['writeonly', 'allocate'], ['readonly']],
                        op_dtypes=[np.dtype('u4'), None],
                        op_axes=[[1, 2, 0], None]);
    assert_equal(i.operands[0].shape, (4, 2, 3))
    assert_equal(i.operands[0].strides, (4, 48, 16))
    assert_equal(i.operands[0].dtype, np.dtype('u4'))

def test_iter_allocate_output_types_promotion():

3 Source : test_nditer.py
with MIT License
from ktraunmueller

def test_iter_allocate_output_types_byte_order():
    # Verify the rules for byte order changes

    # When there's just one input, the output type exactly matches
    a = array([3], dtype='u4').newbyteorder()
    i = nditer([a, None], [],
                    [['readonly'], ['writeonly', 'allocate']])
    assert_equal(i.dtypes[0], i.dtypes[1]);
    # With two or more inputs, the output type is in native byte order
    i = nditer([a, a, None], [],
                    [['readonly'], ['readonly'], ['writeonly', 'allocate']])
    assert_(i.dtypes[0] != i.dtypes[2]);
    assert_equal(i.dtypes[0].newbyteorder('='), i.dtypes[2])

def test_iter_allocate_output_types_scalar():

3 Source : test_nditer.py
with MIT License
from ktraunmueller

def test_iter_buffering_string():
    # Safe casting disallows shrinking strings
    a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_)
    assert_equal(a.dtype, np.dtype('S4'));
    assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
                    op_dtypes='S2')
    i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6')
    assert_equal(i[0], asbytes('abc'))
    assert_equal(i[0].dtype, np.dtype('S6'))

    a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode)
    assert_equal(a.dtype, np.dtype('U4'));
    assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
                    op_dtypes='U2')
    i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6')
    assert_equal(i[0], sixu('abc'))
    assert_equal(i[0].dtype, np.dtype('U6'))

def test_iter_buffering_growinner():

3 Source : test_nditer.py
with MIT License
from ktraunmueller

def test_iter_no_broadcast():
    # Test that the no_broadcast flag works
    a = np.arange(24).reshape(2, 3, 4)
    b = np.arange(6).reshape(2, 3, 1)
    c = np.arange(12).reshape(3, 4)

    i = nditer([a, b, c], [],
                    [['readonly', 'no_broadcast'], ['readonly'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                    [['readonly'], ['readonly', 'no_broadcast'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                    [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])

def test_iter_nested_iters_basic():

3 Source : data_utils.py
with Apache License 2.0
from ludwig-ai

def save_array(data_fp, array):
    with open_file(data_fp, "w") as output_file:
        for x in np.nditer(array):
            output_file.write(str(x) + "\n")


# TODO(shreya): Confirm types of args
def load_pretrained_embeddings(embeddings_path: str, vocab: List[str]) -> np.ndarray:

3 Source : benchmark_data.py
with Apache License 2.0
from nasa

def write_stacks(test_agraph_list):
    filename = '../bingocpp/app/test-agraph-stacks.csv'
    with open(filename, mode='w+') as stack_file:
        stack_file_writer = csv.writer(stack_file, delimiter=',')
        for agraph in test_agraph_list:
            stack = []
            for row in agraph._command_array:
                for i in np.nditer(row):
                    stack.append(i)
            stack_file_writer.writerow(stack)
    stack_file.close()


def write_constants(test_agraph_list):

3 Source : gerador.py
with MIT License
from NatanaelAntonioli

def get_max_min(tipo, espaco, teto_ou_piso):
    if tipo == 'min':
        retornar = 99999999
        for x in np.nditer(espaco):
            if teto_ou_piso   <   x  <  retornar:
                retornar = x

    else:
        retornar = 0
        for x in np.nditer(espaco):
            if retornar  <  x  <  teto_ou_piso:
                retornar = x

    return retornar


def get_distancia(lat1, lon1, lat2, lon2):

3 Source : interference.py
with GNU General Public License v3.0
from NJUOCR

    def interfere(self, img):
        # todo 增加噪点
        # white_noise
        w_rate = self.rate
        w_range = (self.max_val, self.max_val)
        # np.nditer: numpy array自带的迭代器 参考网址:https://www.jianshu.com/p/f2bd63766204
        # 按顺序遍历会出现噪点扎堆的请看
        for x in np.nditer(img, op_flags=['readwrite']):
            if rd.random()   <   w_rate:
                x[...] = rd.randint(*w_range)
        return img, None


class RandomResize(Interference):

3 Source : test_nditer.py
with Apache License 2.0
from pierreant

def test_iter_no_broadcast():
    # Test that the no_broadcast flag works
    a = np.arange(24).reshape(2, 3, 4)
    b = np.arange(6).reshape(2, 3, 1)
    c = np.arange(12).reshape(3, 4)

    nditer([a, b, c], [],
           [['readonly', 'no_broadcast'],
            ['readonly'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                  [['readonly'], ['readonly', 'no_broadcast'], ['readonly']])
    assert_raises(ValueError, nditer, [a, b, c], [],
                  [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])

def test_iter_nested_iters_basic():

3 Source : c3objs.py
with Apache License 2.0
from q-optimize

    def __str__(self):
        val = self.numpy()
        ret = ""
        for entry in np.nditer(val):
            if self.unit != "undefined":
                ret += num3str(entry) + self.unit + " "
            else:
                ret += num3str(entry, use_prefix=False) + " "
        return ret

    def subtract(self, val):

3 Source : pca_utils.py
with BSD 3-Clause "New" or "Revised" License
from RoboticsClubIITJ

def gammaln(a):
    b = []
    for i in np.nditer(a):
        b.append(gamma(i))
    b = np.array(b).reshape(a.shape)
    b = np.log(np.absolute(b))
    return b


def assess_dimension(spectrum, rank, n_samples):

3 Source : framecode.py
with BSD 3-Clause "New" or "Revised" License
from spcl

    def generate_constants(self, sdfg: SDFG, callsite_stream: CodeIOStream):
        # Write constants
        for cstname, (csttype, cstval) in sdfg.constants_prop.items():
            if isinstance(csttype, data.Array):
                const_str = "constexpr " + csttype.dtype.ctype + \
                    " " + cstname + "[" + str(cstval.size) + "] = {"
                it = np.nditer(cstval, order='C')
                for i in range(cstval.size - 1):
                    const_str += str(it[0]) + ", "
                    it.iternext()
                const_str += str(it[0]) + "};\n"
                callsite_stream.write(const_str, sdfg)
            else:
                callsite_stream.write("constexpr %s %s = %s;\n" % (csttype.dtype.ctype, cstname, sym2cpp(cstval)), sdfg)

    def generate_fileheader(self, sdfg: SDFG, global_stream: CodeIOStream, backend: str = 'frame'):

3 Source : ReplaceDenormals.py
with MIT License
from UltronAI

def ReplaceDenormals(net):
    for name, param in net.named_parameters():
        np_arr = param.data.numpy()
        for x in np.nditer(np_arr, op_flags=['readwrite']):
            if abs(x)   <   1e-30:
                x[...] = 1e-30
        param.data = torch.from_numpy(np_arr)

3 Source : minisom.py
with Apache License 2.0
from victorca25

    def _activate(self, x):
        """Updates matrix activation_map, in this matrix
           the element i,j is the response of the neuron i,j to x."""
        s = subtract(x, self._weights)  # x - w
        it = nditer(self._activation_map, flags=['multi_index'])
        while not it.finished:
            # || x - w ||
            self._activation_map[it.multi_index] = fast_norm(s[it.multi_index])
            it.iternext()

    def activate(self, x):

3 Source : minisom.py
with Apache License 2.0
from victorca25

    def random_weights_init(self, data):
        """Initializes the weights of the SOM
        picking random samples from data."""
        self._check_input_len(data)
        it = nditer(self._activation_map, flags=['multi_index'])
        while not it.finished:
            rand_i = self._random_generator.randint(len(data))
            self._weights[it.multi_index] = data[rand_i]
            norm = fast_norm(self._weights[it.multi_index])
            self._weights[it.multi_index] = self._weights[it.multi_index]
            it.iternext()

    def pca_weights_init(self, data):

3 Source : minisom.py
with Apache License 2.0
from victorca25

    def distance_map(self):
        """Returns the distance map of the weights.
        Each cell is the normalised sum of the distances between
        a neuron and its neighbours."""
        um = zeros((self._weights.shape[0], self._weights.shape[1]))
        it = nditer(um, flags=['multi_index'])
        while not it.finished:
            for ii in range(it.multi_index[0]-1, it.multi_index[0]+2):
                for jj in range(it.multi_index[1]-1, it.multi_index[1]+2):
                    if (ii >= 0 and ii   <   self._weights.shape[0] and
                            jj >= 0 and jj  <  self._weights.shape[1]):
                        w_1 = self._weights[ii, jj, :]
                        w_2 = self._weights[it.multi_index]
                        um[it.multi_index] += fast_norm(w_1-w_2)
            it.iternext()
        um = um/um.max()
        return um

    def activation_response(self, data):

3 Source : _property_array.py
with MIT License
from yoelcortes

    def __setitem__(self, key, value):
        items = self.base[key]
        if isa(items, ndarray):
            for i, v in np.nditer((items, value), flags=('refs_ok', 'zerosize_ok')):
                i.item().value = v 
        else:
            items.value = value
    
    def __add__(self, other):

See More Examples