Python numpy.set_printoptions() Examples

The following are 30 code examples of numpy.set_printoptions(). 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: conftest.py    From astropy-healpix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_configure(config):

    if ASTROPY_HEADER:

        config.option.astropy_header = True

        PYTEST_HEADER_MODULES.pop('h5py', None)
        PYTEST_HEADER_MODULES.pop('Pandas', None)
        PYTEST_HEADER_MODULES['Astropy'] = 'astropy'
        PYTEST_HEADER_MODULES['healpy'] = 'healpy'

        from . import __version__
        packagename = os.path.basename(os.path.dirname(__file__))
        TESTED_VERSIONS[packagename] = __version__

    # Set the Numpy print style to a fixed version to make doctest outputs
    # reproducible.
    try:
        np.set_printoptions(legacy='1.13')
    except TypeError:
        # On older versions of Numpy, the unrecognized 'legacy' option will
        # raise a TypeError.
        pass 
Example #2
Source File: test_arrayprint.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_float_spacing(self):
        x = np.array([1., 2., 3.])
        y = np.array([1., 2., -10.])
        z = np.array([100., 2., -1.])
        w = np.array([-100., 2., 1.])

        assert_equal(repr(x), 'array([1., 2., 3.])')
        assert_equal(repr(y), 'array([  1.,   2., -10.])')
        assert_equal(repr(np.array(y[0])), 'array(1.)')
        assert_equal(repr(np.array(y[-1])), 'array(-10.)')
        assert_equal(repr(z), 'array([100.,   2.,  -1.])')
        assert_equal(repr(w), 'array([-100.,    2.,    1.])')

        assert_equal(repr(np.array([np.nan, np.inf])), 'array([nan, inf])')
        assert_equal(repr(np.array([np.nan, -np.inf])), 'array([ nan, -inf])')

        x = np.array([np.inf, 100000, 1.1234])
        y = np.array([np.inf, 100000, -1.1234])
        z = np.array([np.inf, 1.1234, -1e120])
        np.set_printoptions(precision=2)
        assert_equal(repr(x), 'array([     inf, 1.00e+05, 1.12e+00])')
        assert_equal(repr(y), 'array([      inf,  1.00e+05, -1.12e+00])')
        assert_equal(repr(z), 'array([       inf,  1.12e+000, -1.00e+120])') 
Example #3
Source File: test_core.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #4
Source File: test_utils.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def assert_almost_equal(a, b, rtol=None, atol=None, names=('a', 'b'), equal_nan=False):
    """Test that two numpy arrays are almost equal. Raise exception message if not.

    Parameters
    ----------
    a : np.ndarray
    b : np.ndarray
    threshold : None or float
        The checking threshold. Default threshold will be used if set to ``None``.
    """
    rtol = get_rtol(rtol)
    atol = get_atol(atol)
    if almost_equal(a, b, rtol, atol, equal_nan=equal_nan):
        return
    index, rel = find_max_violation(a, b, rtol, atol)
    np.set_printoptions(threshold=4, suppress=True)
    msg = npt.build_err_msg([a, b],
                            err_msg="Error %f exceeds tolerance rtol=%f, atol=%f. "
                                    " Location of maximum error:%s, a=%f, b=%f"
                            % (rel, rtol, atol, str(index), a[index], b[index]),
                            names=names)
    raise AssertionError(msg) 
Example #5
Source File: test_core.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #6
Source File: molecule.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_hash(self):
        """
        Returns the hash of the molecule.
        """

        m = hashlib.sha1()
        concat = ""

        np.set_printoptions(precision=16)
        for field in self.hash_fields:
            data = getattr(self, field)
            if field == "geometry":
                data = float_prep(data, GEOMETRY_NOISE)
            elif field == "fragment_charges":
                data = float_prep(data, CHARGE_NOISE)
            elif field == "molecular_charge":
                data = float_prep(data, CHARGE_NOISE)
            elif field == "masses":
                data = float_prep(data, MASS_NOISE)

            concat += json.dumps(data, default=lambda x: x.ravel().tolist())

        m.update(concat.encode("utf-8"))
        return m.hexdigest() 
Example #7
Source File: test_arrayprint.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_formatter_reset(self):
        x = np.arange(3)
        np.set_printoptions(formatter={'all':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])")
        np.set_printoptions(formatter={'int':None})
        assert_equal(repr(x), "array([0, 1, 2])")

        np.set_printoptions(formatter={'all':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])")
        np.set_printoptions(formatter={'all':None})
        assert_equal(repr(x), "array([0, 1, 2])")

        np.set_printoptions(formatter={'int':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])")
        np.set_printoptions(formatter={'int_kind':None})
        assert_equal(repr(x), "array([0, 1, 2])")

        x = np.arange(3.)
        np.set_printoptions(formatter={'float':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1.0, 0.0, 1.0])")
        np.set_printoptions(formatter={'float_kind':None})
        assert_equal(repr(x), "array([0., 1., 2.])") 
Example #8
Source File: test_arrayprint.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_linewidth_str(self):
        a = np.full(18, fill_value=2)
        np.set_printoptions(linewidth=18)
        assert_equal(
            str(a),
            textwrap.dedent("""\
            [2 2 2 2 2 2 2 2
             2 2 2 2 2 2 2 2
             2 2]""")
        )
        np.set_printoptions(linewidth=18, legacy='1.13')
        assert_equal(
            str(a),
            textwrap.dedent("""\
            [2 2 2 2 2 2 2 2 2
             2 2 2 2 2 2 2 2 2]""")
        ) 
Example #9
Source File: network.py    From Training-Neural-Networks-for-Event-Based-End-to-End-Robot-Control with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
		# NEST options
		np.set_printoptions(precision=1)
		nest.set_verbosity('M_WARNING')
		nest.ResetKernel()
		nest.SetKernelStatus({"local_num_threads" : 1, "resolution" : p.time_resolution})
		# Create Poisson neurons
		self.spike_generators = nest.Create("poisson_generator", p.resolution[0]*p.resolution[1], params=p.poisson_params)
		self.neuron_pre = nest.Create("parrot_neuron", p.resolution[0]*p.resolution[1])
		# Create motor IAF neurons
		self.neuron_post = nest.Create("iaf_psc_alpha", 2, params=p.iaf_params)
		# Create Output spike detector
		self.spike_detector = nest.Create("spike_detector", 2, params={"withtime": True})
		# Create R-STDP synapses
		self.syn_dict = {"model": "stdp_dopamine_synapse",
						"weight": {"distribution": "uniform", "low": p.w0_min, "high": p.w0_max}}
		self.vt = nest.Create("volume_transmitter")
		nest.SetDefaults("stdp_dopamine_synapse", {"vt": self.vt[0], "tau_c": p.tau_c, "tau_n": p.tau_n, "Wmin": p.w_min, "Wmax": p.w_max, "A_plus": p.A_plus, "A_minus": p.A_minus})
		nest.Connect(self.spike_generators, self.neuron_pre, "one_to_one")
		nest.Connect(self.neuron_pre, self.neuron_post, "all_to_all", syn_spec=self.syn_dict)
		nest.Connect(self.neuron_post, self.spike_detector, "one_to_one")
		# Create connection handles for left and right motor neuron
		self.conn_l = nest.GetConnections(target=[self.neuron_post[0]])
		self.conn_r = nest.GetConnections(target=[self.neuron_post[1]]) 
Example #10
Source File: test_arrayprint.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_formatter_reset(self):
        x = np.arange(3)
        np.set_printoptions(formatter={'all':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])")
        np.set_printoptions(formatter={'int':None})
        assert_equal(repr(x), "array([0, 1, 2])")

        np.set_printoptions(formatter={'all':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])")
        np.set_printoptions(formatter={'all':None})
        assert_equal(repr(x), "array([0, 1, 2])")

        np.set_printoptions(formatter={'int':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])")
        np.set_printoptions(formatter={'int_kind':None})
        assert_equal(repr(x), "array([0, 1, 2])")

        x = np.arange(3.)
        np.set_printoptions(formatter={'float':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1.0, 0.0, 1.0])")
        np.set_printoptions(formatter={'float_kind':None})
        assert_equal(repr(x), "array([ 0.,  1.,  2.])") 
Example #11
Source File: build_the_maze.py    From hazymaze with Apache License 2.0 5 votes vote down vote up
def is_valid(self):
        # If it has less than 2 entrances, it's invalid
        if len(self.entrances) < 2:
            print(f'{len(self.entrances)} found, requires at least 2')
            return False

        # If finding path from entrance to exit gives an error or there is no path, it's invalid
        path = self.test_path()
        if len(path) < 2:
            print('No path found from entrance to exit. Bad map?')
            return False
        else:
            for prevcase, case in zip(path, path[1:]):
                py, px = self.real_position(prevcase.position[0], prevcase.position[1])
                y, x = self.real_position(case.position[0], case.position[1])
                if None in (py, px, y, x):
                    np.set_printoptions(threshold=np.inf)
                    print(self.maze_array)
                    print(f'''Positions of some of the cases in the path
                    from entrance to exit seem incorrect. Bad map?
                    prevcase: {(prevcase.position[0], prevcase.position[1])}
                    case: {(case.position[0], case.position[1])}
                    py, px, y, x: {(py, px, y, x)}''')

                    return False

        return True 
Example #12
Source File: compute_stats.py    From lingvo with Apache License 2.0 5 votes vote down vote up
def _PrintMeanVar(self):
    m, v = self._ComputeMeanVar()
    original = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    tf.logging.info('== Mean/variance.')
    tf.logging.info('mean = %s', m)
    tf.logging.info('var = %s', v)
    np.set_printoptions(**original) 
Example #13
Source File: build_the_maze.py    From hazymaze with Apache License 2.0 5 votes vote down vote up
def build_maze(self, items, key=None):
        game = Master.instance()

        # Making a binary maze (1 is wall 0 is walkable)
        self.build_basic_maze()
        self.build_items(items)

        # Turn out binary maze into a string
        # Save it in a dictionary that points to the finished maze (self.case_array)
        # So if we are trying to build the same maze, we don't have to recreate it
        np.set_printoptions(threshold=np.inf)
        binary_maze_string = np.array2string(self.maze_array)

        if binary_maze_string in game.built_mazes.keys():
            self.case_array, self.entrances, self.items = game.built_mazes[binary_maze_string]
        else:
            self.compress_maze(items)
            game.built_mazes[binary_maze_string] = (self.case_array, self.entrances, self.items)

        if key is not None:
            if key == ord('q'):
                print(binary_maze_string)
                for e in self.entrances:
                    print(self.real_position(e[0], e[1]))
                print(self.entrances)
                print(self.items) 
Example #14
Source File: dch.py    From DeepHash with MIT License 5 votes vote down vote up
def __init__(self, config):
        # Initialize setting
        print("initializing")
        np.set_printoptions(precision=4)

        with tf.name_scope('stage'):
            # 0 for training, 1 for validation
            self.stage = tf.placeholder_with_default(tf.constant(0), [])
        for k, v in vars(config).items():
            setattr(self, k, v)
        self.file_name = 'lr_{}_cqlambda_{}_gamma_{}_dataset_{}'.format(
            self.lr,
            self.q_lambda,
            self.gamma,
            self.dataset)
        self.save_file = os.path.join(self.save_dir, self.file_name + '.npy')

        # Setup session
        print("launching session")
        configProto = tf.ConfigProto()
        configProto.gpu_options.allow_growth = True
        configProto.allow_soft_placement = True
        self.sess = tf.Session(config=configProto)

        # Create variables and placeholders
        self.img = tf.placeholder(tf.float32, [None, 256, 256, 3])
        self.img_label = tf.placeholder(tf.float32, [None, self.label_dim])
        self.img_last_layer, self.deep_param_img, self.train_layers, self.train_last_layer = self.load_model()

        self.global_step = tf.Variable(0, trainable=False)
        self.train_op = self.apply_loss_function(self.global_step)
        self.sess.run(tf.global_variables_initializer())
        return 
Example #15
Source File: analysis.py    From LipReading with MIT License 5 votes vote down vote up
def get_confusion_matrix(encoder, decoding_step, data_loader, device, char2idx, num_epochs):
    class_names = ['a', 'e', 'i', 'y', 'o', 'u', 'w',
                   'b', 'p', 'm',
                   'f', 'v',
                   't', 'd', 'n', 's', 'z', 'l', 'r',
                   'j',
                   'k', 'q', 'c', 'g', 'x',
                   'h']

    class_names_set = set(class_names)

    y_test, y_pred = get_data(encoder, decoding_step, data_loader, device, char2idx)
    filtered_y_test = []
    filtered_y_pred = []
    idx2char = {val: key for key, val in char2idx.items()}
    for test, pred in zip([idx2char[x] for x in y_test], [idx2char[x] for x in y_pred]):
        if test in class_names_set and pred in class_names_set:
            filtered_y_test.append(test)
            filtered_y_pred.append(pred)

    # Compute confusion matrix
    cnf_matrix = confusion_matrix(filtered_y_test, filtered_y_pred, labels=class_names)
    np.set_printoptions(precision=2)

    # Plot non-normalized confusion matrix
    plt.figure(figsize=(10,10), dpi=100)
    plot_confusion_matrix(cnf_matrix, classes=class_names,
                        title='Confusion matrix, without normalization')
    plt.savefig('{}{}'.format(int(num_epochs), '_confusion_matrix.png'))

    # Plot normalized confusion matrix
    plt.figure(figsize=(10,10), dpi=100)
    plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
                        title='Normalized confusion matrix')
    plt.savefig('{}{}'.format(int(num_epochs), '_norm_confusion_matrix.png')) 
Example #16
Source File: common.py    From vedaseg with Apache License 2.0 5 votes vote down vote up
def get_root_logger(log_level=logging.INFO):
    logger = logging.getLogger()
    np.set_printoptions(precision=4)
    if not logger.hasHandlers():
        logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
                            level=log_level)
    return logger 
Example #17
Source File: test_arrayprint.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_formatter(self):
        x = np.arange(3)
        np.set_printoptions(formatter={'all':lambda x: str(x-1)})
        assert_equal(repr(x), "array([-1, 0, 1])") 
Example #18
Source File: noseclasses.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def afterContext(self):
        numpy.set_printoptions(**print_state)

    # Ignore NumPy-specific build files that shouldn't be searched for tests 
Example #19
Source File: arrayprint.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def get_printoptions():
    """
    Return the current print options.

    Returns
    -------
    print_opts : dict
        Dictionary of current print options with keys

          - precision : int
          - threshold : int
          - edgeitems : int
          - linewidth : int
          - suppress : bool
          - nanstr : str
          - infstr : str
          - formatter : dict of callables
          - sign : str

        For a full description of these options, see `set_printoptions`.

    See Also
    --------
    set_printoptions, set_string_function

    """
    return _format_options.copy() 
Example #20
Source File: arrayprint.py    From lambda-packs with MIT License 5 votes vote down vote up
def get_printoptions():
    """
    Return the current print options.

    Returns
    -------
    print_opts : dict
        Dictionary of current print options with keys

          - precision : int
          - threshold : int
          - edgeitems : int
          - linewidth : int
          - suppress : bool
          - nanstr : str
          - infstr : str
          - formatter : dict of callables
          - sign : str

        For a full description of these options, see `set_printoptions`.

    See Also
    --------
    set_printoptions, set_string_function

    """
    return _format_options.copy() 
Example #21
Source File: test_compare_activations.py    From bert-for-tf2 with MIT License 5 votes vote down vote up
def test_compare(self):

        model_dir = tempfile.TemporaryDirectory().name
        os.makedirs(model_dir)
        save_path = MiniBertFactory.create_mini_bert_weights(model_dir)
        tokenizer = bert_tokenization.FullTokenizer(vocab_file=os.path.join(model_dir, "vocab.txt"), do_lower_case=True)

        # prepare input
        max_seq_len  = 16
        input_str    = "hello, bert!"
        input_tokens = tokenizer.tokenize(input_str)
        input_tokens = ["[CLS]"] + input_tokens + ["[SEP]"]
        input_ids    = tokenizer.convert_tokens_to_ids(input_tokens)
        input_ids      = input_ids             + [0]*(max_seq_len - len(input_tokens))
        input_mask     = [0]*len(input_tokens) + [0]*(max_seq_len - len(input_tokens)) # FIXME: input_mask broken - chane to [1]*
        token_type_ids = [0]*len(input_tokens) + [0]*(max_seq_len - len(input_tokens))

        input_ids      = np.array([input_ids], dtype=np.int32)
        input_mask     = np.array([input_mask], dtype=np.int32)
        token_type_ids = np.array([token_type_ids], dtype=np.int32)

        print("   tokens:", input_tokens)
        print("input_ids:{}/{}:{}".format(len(input_tokens), max_seq_len, input_ids), input_ids.shape, token_type_ids)

        bert_1_seq_out = CompareBertActivationsTest.predict_on_stock_model(model_dir, input_ids, input_mask, token_type_ids)
        bert_2_seq_out = CompareBertActivationsTest.predict_on_keras_model(model_dir, input_ids, input_mask, token_type_ids)

        np.set_printoptions(precision=9, threshold=20, linewidth=200, sign="+", floatmode="fixed")

        print("stock bert res", bert_1_seq_out.shape)
        print("keras bert res", bert_2_seq_out.shape)

        print("stock bert res:\n {}".format(bert_1_seq_out[0, :2, :10]), bert_1_seq_out.dtype)
        print("keras bert_res:\n {}".format(bert_2_seq_out[0, :2, :10]), bert_2_seq_out.dtype)

        abs_diff = np.abs(bert_1_seq_out - bert_2_seq_out).flatten()
        print("abs diff:", np.max(abs_diff), np.argmax(abs_diff))
        self.assertTrue(np.allclose(bert_1_seq_out, bert_2_seq_out, atol=1e-6)) 
Example #22
Source File: test_compare_pretrained.py    From bert-for-tf2 with MIT License 5 votes vote down vote up
def test_direct_keras_to_stock_compare(self):
        from tests.ext.modeling import BertModel, BertConfig, get_assignment_map_from_checkpoint

        bert_config = BertConfig.from_json_file(self.bert_config_file)
        tokenizer = FullTokenizer(vocab_file=os.path.join(self.bert_ckpt_dir, "vocab.txt"))

        # prepare input
        max_seq_len  = 6
        input_str    = "Hello, Bert!"
        input_tokens = tokenizer.tokenize(input_str)
        input_tokens = ["[CLS]"] + input_tokens + ["[SEP]"]
        input_ids    = tokenizer.convert_tokens_to_ids(input_tokens)
        input_ids      = input_ids             + [0]*(max_seq_len - len(input_tokens))
        input_mask     = [1]*len(input_tokens) + [0]*(max_seq_len - len(input_tokens))
        token_type_ids = [0]*len(input_tokens) + [0]*(max_seq_len - len(input_tokens))

        input_ids      = np.array([input_ids], dtype=np.int32)
        input_mask     = np.array([input_mask], dtype=np.int32)
        token_type_ids = np.array([token_type_ids], dtype=np.int32)

        print("   tokens:", input_tokens)
        print("input_ids:{}/{}:{}".format(len(input_tokens), max_seq_len, input_ids), input_ids.shape, token_type_ids)

        s_res = self.predict_on_stock_model(input_ids, input_mask, token_type_ids)
        k_res = self.predict_on_keras_model(input_ids, input_mask, token_type_ids)

        np.set_printoptions(precision=9, threshold=20, linewidth=200, sign="+", floatmode="fixed")
        print("s_res", s_res.shape)
        print("k_res", k_res.shape)

        print("s_res:\n {}".format(s_res[0, :2, :10]), s_res.dtype)
        print("k_res:\n {}".format(k_res[0, :2, :10]), k_res.dtype)

        adiff = np.abs(s_res-k_res).flatten()
        print("diff:", np.max(adiff), np.argmax(adiff))
        self.assertTrue(np.allclose(s_res, k_res, atol=1e-6)) 
Example #23
Source File: layer_test.py    From FastMaskRCNN with Apache License 2.0 5 votes vote down vote up
def test(self):
        with tf.Session() as sess:
            boxes = np.random.randint(0, 50, [self.N, 2])
            s = np.random.randint(20, 30, [self.N, 2])
            boxes = np.hstack((boxes, boxes + s)).astype(np.float32)

            scores = np.random.rand(self.N, 1).astype(np.float32)
            boxes, scores, batch_inds= \
                    sample_rpn_outputs(boxes, scores, is_training=False,) 
            self.boxes = boxes.eval()
            self.scores = scores.eval()
            bs = np.hstack((self.boxes, self.scores))
            np.set_printoptions(precision=3, suppress=True)
            print (bs) 
Example #24
Source File: layer_test.py    From FastFPN with Apache License 2.0 5 votes vote down vote up
def test(self):
        with tf.Session() as sess:
            boxes = np.random.randint(0, 50, [self.N, 2])
            s = np.random.randint(20, 30, [self.N, 2])
            boxes = np.hstack((boxes, boxes + s)).astype(np.float32)

            scores = np.random.rand(self.N, 1).astype(np.float32)
            boxes, scores, batch_inds= \
                    sample_rpn_outputs(boxes, scores, is_training=False,) 
            self.boxes = boxes.eval()
            self.scores = scores.eval()
            bs = np.hstack((self.boxes, self.scores))
            np.set_printoptions(precision=3, suppress=True)
            print (bs) 
Example #25
Source File: test_transformers.py    From deepchem with MIT License 5 votes vote down vote up
def test_X_normalization_transformer(self):
    """Tests normalization transformer."""
    solubility_dataset = dc.data.tests.load_solubility_data()
    normalization_transformer = dc.trans.NormalizationTransformer(
        transform_X=True, dataset=solubility_dataset)
    X, y, w, ids = (solubility_dataset.X, solubility_dataset.y,
                    solubility_dataset.w, solubility_dataset.ids)
    solubility_dataset = normalization_transformer.transform(solubility_dataset)
    X_t, y_t, w_t, ids_t = (solubility_dataset.X, solubility_dataset.y,
                            solubility_dataset.w, solubility_dataset.ids)
    # Check ids are unchanged.
    for id_elt, id_t_elt in zip(ids, ids_t):
      assert id_elt == id_t_elt
    # Check y is unchanged since this is a X transformer
    np.testing.assert_allclose(y, y_t)
    # Check w is unchanged since this is a y transformer
    np.testing.assert_allclose(w, w_t)
    # Check that X_t has zero mean, unit std.
    # np.set_printoptions(threshold='nan')
    mean = X_t.mean(axis=0)
    assert np.amax(np.abs(mean - np.zeros_like(mean))) < 1e-7
    orig_std_array = X.std(axis=0)
    std_array = X_t.std(axis=0)
    # Entries with zero std are not normalized
    for orig_std, std in zip(orig_std_array, std_array):
      if not np.isclose(orig_std, 0):
        assert np.isclose(std, 1)

    # TODO(rbharath): Untransform doesn't work properly for binary feature
    # vectors. Need to figure out what's wrong here. (low priority)
    ## Check that untransform does the right thing.
    # np.testing.assert_allclose(normalization_transformer.untransform(X_t), X) 
Example #26
Source File: utilities_geometry.py    From pytim with GNU General Public License v3.0 5 votes vote down vote up
def EulerRotation(phi, theta, psi):
    """ The Euler (3,1,3) rotation matrix

        :param phi: rotation around the z axis
        :param theta: rotation around the new x axis
        :param psi: rotation around the new z axis
        :returns double: area

        Example:

        >>> import numpy as np
        >>> import pytim
        >>> from pytim.utilities import *
        >>> np.set_printoptions(suppress=True)
        >>> print (EulerRotation(np.pi/2.,0,0))
        [[ 0.  1.  0.]
         [-1.  0.  0.]
         [ 0. -0.  1.]]
        >>> np.set_printoptions(suppress=False)

    """

    cph = np.cos(phi)
    cps = np.cos(psi)
    cth = np.cos(theta)
    sph = np.sin(phi)
    sps = np.sin(psi)
    sth = np.sin(theta)
    R1 = [cph * cps - cth * sph * sps, cps * sph + cth * cph * sps, sth * sps]
    R2 = [-cth * cps * sph - cph * sps, cth * cps * cph - sph * sps, cps * sth]
    R3 = [sth * sph, -cph * sth, cth]
    return np.array([R1, R2, R3]) 
Example #27
Source File: test_records.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_0d_recarray_repr(self):
        arr_0d = np.rec.array((1, 2.0, '2003'), dtype='<i4,<f8,<M8[Y]')
        assert_equal(repr(arr_0d), textwrap.dedent("""\
            rec.array((1, 2., '2003'),
                      dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '<M8[Y]')])"""))

        record = arr_0d[()]
        assert_equal(repr(record), "(1, 2., '2003')")
        # 1.13 converted to python scalars before the repr
        try:
            np.set_printoptions(legacy='1.13')
            assert_equal(repr(record), '(1, 2.0, datetime.date(2003, 1, 1))')
        finally:
            np.set_printoptions(legacy=False) 
Example #28
Source File: test_arrayprint.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_bad_args(self):
        assert_raises(ValueError, np.set_printoptions, threshold='nan')
        assert_raises(ValueError, np.set_printoptions, threshold=u'1')
        assert_raises(ValueError, np.set_printoptions, threshold=b'1') 
Example #29
Source File: test_arrayprint.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_linewidth_repr(self):
        a = np.full(7, fill_value=2)
        np.set_printoptions(linewidth=17)
        assert_equal(
            repr(a),
            textwrap.dedent("""\
            array([2, 2, 2,
                   2, 2, 2,
                   2])""")
        )
        np.set_printoptions(linewidth=17, legacy='1.13')
        assert_equal(
            repr(a),
            textwrap.dedent("""\
            array([2, 2, 2,
                   2, 2, 2, 2])""")
        )

        a = np.full(8, fill_value=2)

        np.set_printoptions(linewidth=18, legacy=False)
        assert_equal(
            repr(a),
            textwrap.dedent("""\
            array([2, 2, 2,
                   2, 2, 2,
                   2, 2])""")
        )

        np.set_printoptions(linewidth=18, legacy='1.13')
        assert_equal(
            repr(a),
            textwrap.dedent("""\
            array([2, 2, 2, 2,
                   2, 2, 2, 2])""")
        ) 
Example #30
Source File: test_arrayprint.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dtype_linewidth_wrapping(self):
        np.set_printoptions(linewidth=75)
        assert_equal(repr(np.arange(10,20., dtype='f4')),
            "array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19.], dtype=float32)")
        assert_equal(repr(np.arange(10,23., dtype='f4')), textwrap.dedent("""\
            array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.],
                  dtype=float32)"""))

        styp = '<U4' if sys.version_info[0] >= 3 else '|S4'
        assert_equal(repr(np.ones(3, dtype=styp)),
            "array(['1', '1', '1'], dtype='{}')".format(styp))
        assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent("""\
            array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
                  dtype='{}')""".format(styp)))