Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / utils / tests / test_misc.py @ 5cef0f13

History | View | Annotate | Download (6.53 KB)

1
# -*- encoding: utf-8 -*-
2
from nose.tools import *
3
from nose import SkipTest
4
import networkx as nx
5
from networkx.utils import *
6

    
7

    
8
def test_is_string_like():
9
    assert_true(is_string_like("aaaa"))
10
    assert_false(is_string_like(None))
11
    assert_false(is_string_like(123))
12

    
13

    
14
def test_iterable():
15
    assert_false(iterable(None))
16
    assert_false(iterable(10))
17
    assert_true(iterable([1, 2, 3]))
18
    assert_true(iterable((1, 2, 3)))
19
    assert_true(iterable({1: "A", 2: "X"}))
20
    assert_true(iterable("ABC"))
21

    
22

    
23
def test_graph_iterable():
24
    K = nx.complete_graph(10)
25
    assert_true(iterable(K))
26
    assert_true(iterable(K.nodes()))
27
    assert_true(iterable(K.edges()))
28

    
29

    
30
def test_is_list_of_ints():
31
    assert_true(is_list_of_ints([1, 2, 3, 42]))
32
    assert_false(is_list_of_ints([1, 2, 3, "kermit"]))
33

    
34

    
35
def test_random_number_distribution():
36
    # smoke test only
37
    z = powerlaw_sequence(20, exponent=2.5)
38
    z = discrete_sequence(20, distribution=[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3])
39

    
40

    
41
def test_make_str_with_bytes():
42
    import sys
43
    PY2 = sys.version_info[0] == 2
44

    
45
    x = "qualité"
46
    y = make_str(x)
47
    if PY2:
48
        assert_true(isinstance(y, unicode))
49
        # Since file encoding is utf-8, the é will be two bytes.
50
        assert_true(len(y) == 8)
51
    else:
52
        assert_true(isinstance(y, str))
53
        assert_true(len(y) == 7)
54

    
55

    
56
def test_make_str_with_unicode():
57
    import sys
58
    PY2 = sys.version_info[0] == 2
59
    if PY2:
60
        x = unicode("qualité", encoding='utf-8')
61
        y = make_str(x)
62
        assert_true(isinstance(y, unicode))
63
        assert_true(len(y) == 7)
64
    else:
65
        x = "qualité"
66
        y = make_str(x)
67
        assert_true(isinstance(y, str))
68
        assert_true(len(y) == 7)
69

    
70

    
71
class TestNumpyArray(object):
72
    @classmethod
73
    def setupClass(cls):
74
        global numpy
75
        global assert_allclose
76
        try:
77
            import numpy
78
            from numpy.testing import assert_allclose
79
        except ImportError:
80
            raise SkipTest('NumPy not available.')
81

    
82
    def test_dict_to_numpy_array1(self):
83
        d = {'a': 1, 'b': 2}
84
        a = dict_to_numpy_array1(d, mapping={'a': 0, 'b': 1})
85
        assert_allclose(a, numpy.array([1, 2]))
86
        a = dict_to_numpy_array1(d, mapping={'b': 0, 'a': 1})
87
        assert_allclose(a, numpy.array([2, 1]))
88

    
89
        a = dict_to_numpy_array1(d)
90
        assert_allclose(a.sum(), 3)
91

    
92
    def test_dict_to_numpy_array2(self):
93
        d = {'a': {'a': 1, 'b': 2},
94
             'b': {'a': 10, 'b': 20}}
95

    
96
        mapping = {'a': 1, 'b': 0}
97
        a = dict_to_numpy_array2(d, mapping=mapping)
98
        assert_allclose(a, numpy.array([[20, 10], [2, 1]]))
99

    
100
        a = dict_to_numpy_array2(d)
101
        assert_allclose(a.sum(), 33)
102

    
103
    def test_dict_to_numpy_array_a(self):
104
        d = {'a': {'a': 1, 'b': 2},
105
             'b': {'a': 10, 'b': 20}}
106

    
107
        mapping = {'a': 0, 'b': 1}
108
        a = dict_to_numpy_array(d, mapping=mapping)
109
        assert_allclose(a, numpy.array([[1, 2], [10, 20]]))
110

    
111
        mapping = {'a': 1, 'b': 0}
112
        a = dict_to_numpy_array(d, mapping=mapping)
113
        assert_allclose(a, numpy.array([[20, 10], [2, 1]]))
114

    
115
        a = dict_to_numpy_array2(d)
116
        assert_allclose(a.sum(), 33)
117

    
118
    def test_dict_to_numpy_array_b(self):
119
        d = {'a': 1, 'b': 2}
120

    
121
        mapping = {'a': 0, 'b': 1}
122
        a = dict_to_numpy_array(d, mapping=mapping)
123
        assert_allclose(a, numpy.array([1, 2]))
124

    
125
        a = dict_to_numpy_array1(d)
126
        assert_allclose(a.sum(), 3)
127

    
128

    
129
def test_pairwise():
130
    nodes = range(4)
131
    node_pairs = [(0, 1), (1, 2), (2, 3)]
132
    node_pairs_cycle = node_pairs + [(3, 0)]
133
    assert_equal(list(pairwise(nodes)), node_pairs)
134
    assert_equal(list(pairwise(iter(nodes))), node_pairs)
135
    assert_equal(list(pairwise(nodes, cyclic=True)), node_pairs_cycle)
136
    empty_iter = iter(())
137
    assert_equal(list(pairwise(empty_iter)), [])
138
    empty_iter = iter(())
139
    assert_equal(list(pairwise(empty_iter, cyclic=True)), [])
140

    
141

    
142
def test_groups():
143
    many_to_one = dict(zip('abcde', [0, 0, 1, 1, 2]))
144
    actual = groups(many_to_one)
145
    expected = {0: {'a', 'b'}, 1: {'c', 'd'}, 2: {'e'}}
146
    assert_equal(actual, expected)
147
    assert_equal({}, groups({}))
148

    
149

    
150
def test_to_tuple():
151
    a_list = [1, 2, [1, 3]]
152
    actual = to_tuple(a_list)
153
    expected = (1, 2, (1, 3))
154
    assert_equal(actual, expected)
155

    
156
    a_tuple = (1, 2)
157
    actual = to_tuple(a_tuple)
158
    expected = a_tuple
159
    assert_equal(actual, expected)
160

    
161
    a_mix = (1, 2, [1, 3])
162
    actual = to_tuple(a_mix)
163
    expected = (1, 2, (1, 3))
164
    assert_equal(actual, expected)
165

    
166

    
167
def test_create_random_state():
168
    try:
169
        import numpy as np
170
    except ImportError:
171
        raise SkipTest('numpy not available.')
172

    
173
    rs = np.random.RandomState
174

    
175
    assert_true(isinstance(create_random_state(1), rs))
176
    assert_true(isinstance(create_random_state(None), rs))
177
    assert_true(isinstance(create_random_state(np.random), rs))
178
    assert_true(isinstance(create_random_state(rs(1)), rs))
179
    assert_raises(ValueError, create_random_state, 'a')
180

    
181
    assert_true(np.all((rs(1).rand(10) == create_random_state(1).rand(10))))
182

    
183

    
184
def test_create_py_random_state():
185
    pyrs = random.Random
186

    
187
    assert_true(isinstance(create_py_random_state(1), pyrs))
188
    assert_true(isinstance(create_py_random_state(None), pyrs))
189
    assert_true(isinstance(create_py_random_state(pyrs(1)), pyrs))
190
    assert_raises(ValueError, create_py_random_state, 'a')
191

    
192
    try:
193
        import numpy as np
194
    except ImportError:
195
        raise SkipTest('numpy not available.')
196

    
197
    rs = np.random.RandomState
198
    nprs = PythonRandomInterface
199
    assert_true(isinstance(create_py_random_state(np.random), nprs))
200
    assert_true(isinstance(create_py_random_state(rs(1)), nprs))
201
    # test default rng input
202
    assert_true(isinstance(PythonRandomInterface(), nprs))
203

    
204

    
205
def test_PythonRandomInterface():
206
    try:
207
        import numpy as np
208
    except ImportError:
209
        raise SkipTest('numpy not available.')
210
    rs = np.random.RandomState
211
    rng = PythonRandomInterface(rs(42))
212
    rs42 = rs(42)
213

    
214
    # make sure these functions are same as expected outcome
215
    assert_equal(rng.randrange(3, 5), rs42.randint(3, 5))
216
    assert_true(np.all(rng.choice([1, 2, 3]) == rs42.choice([1, 2, 3])))
217
    assert_equal(rng.gauss(0, 1), rs42.normal(0, 1))
218
    assert_equal(rng.expovariate(1.5), rs42.exponential(1/1.5))
219
    assert_true(np.all(rng.shuffle([1, 2, 3]) == rs42.shuffle([1, 2, 3])))
220
    assert_true(np.all(rng.sample([1, 2, 3], 2) ==
221
                       rs42.choice([1, 2, 3], (2,), replace=False)))
222
    assert_equal(rng.randint(3, 5), rs42.randint(3, 6))
223
    assert_equal(rng.random(), rs42.random_sample())