Completed
Push — master ( a3685b...e66410 )
by Kyle
01:15
created

Noise.dimentions()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 1
c 5
b 0
f 0
dl 0
loc 3
rs 10
1
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
from __future__ import absolute_import
3
4
import operator
0 ignored issues
show
Unused Code introduced by
The import operator seems to be unused.
Loading history...
5
6
import numpy as np
0 ignored issues
show
Configuration introduced by
The import numpy could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
7
8
from tcod.tcod import _cdata
9
from tcod.libtcod import ffi, lib
10
import tcod.libtcod
11
12
"""Noise implementation constants"""
0 ignored issues
show
Unused Code introduced by
This string statement has no effect and could be removed.
Loading history...
13
SIMPLE = 0
14
FBM = 1
15
TURBULENCE = 2
16
17
class Noise(object):
18
    """
19
20
    The ``hurst`` exponent describes the raggedness of the resultant noise,
21
    with a higher value leading to a smoother noise.
22
    Not used with tcod.noise.SIMPLE.
23
24
    ``lacunarity`` is a multiplier that determines how fast the noise
25
    frequency increases for each successive octave.
26
    Not used with tcod.noise.SIMPLE.
27
28
    Args:
29
        dimensions (int): Must be from 1 to 4.
30
        algorithm (int): Defaults to NOISE_SIMPLEX
31
        implementation (int): Defaults to tcod.noise.SIMPLE
32
        hurst (float): The hurst exponent.  Should be in the 0.0-1.0 range.
33
        lacunarity (float): The noise lacunarity.
34
        octaves (float): The level of detail on fBm and turbulence
35
                         implementations.
36
        rand (Optional[Random]): A Random instance, or None.
37
38
    .. versionadded:: 2.0
39
    """
40
41
    def __init__(self, dimensions, algorithm=2, implementation=SIMPLE,
42
                 hurst=0.5, lacunarity=2.0, octaves=4, rand=None):
43
        if not 0 < dimensions <= 4:
44
            raise ValueError('dimensions must be in range 0 < n <= 4, got %r' %
45
                             (dimensions,))
46
        self._random = rand
47
        self._random_c = _cdata(rand)
48
        self._algorithm = algorithm
49
        self.noise_c = ffi.gc(
50
            ffi.cast(
51
                'perlin_data_t*',
52
                lib.TCOD_noise_new(dimensions, hurst, lacunarity,
53
                                   self._random_c),
54
                ),
55
            lib.TCOD_noise_delete)
56
        self._tdl_noise_c = ffi.new('TDLNoise*', (self.noise_c,
57
                                                  dimensions,
58
                                                  0,
59
                                                  octaves))
60
        self.implementation = implementation # sanity check
61
62
    @property
63
    def dimensions(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
64
        return self._tdl_noise_c.dimensions
65
66
    @property
67
    def dimentions(self): # deprecated
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
68
        return self.dimensions
69
70
    @property
71
    def algorithm(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
72
        return self.noise_c.noise_type
73
    @algorithm.setter
74
    def algorithm(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
75
        lib.TCOD_noise_set_type(self.noise_c, value)
76
77
    @property
78
    def implementation(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
79
        return self._tdl_noise_c.implementation
80
    @implementation.setter
81
    def implementation(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
82
        if not 0 <= value < 3:
83
            raise ValueError('%r is not a valid implementation. ' % (value,))
84
        self._tdl_noise_c.implementation = value
85
86
    @property
87
    def hurst(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
88
        return self.noise_c.H
89
90
    @property
91
    def lacunarity(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
92
        return self.noise_c.lacunarity
93
94
    @property
95
    def octaves(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
96
        return self._tdl_noise_c.octaves
97
    @octaves.setter
98
    def octaves(self, value):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
99
        self._tdl_noise_c.octaves = value
100
101
    def get_point(self, x=0, y=0, z=0, w=0):
102
        """Return the noise value at the (x, y, z, w) point.
103
104
        Args:
105
            x (float): The position on the 1st axis.
106
            y (float): The position on the 2nd axis.
107
            z (float): The position on the 3rd axis.
108
            w (float): The position on the 4th axis.
109
        """
110
        return lib.NoiseGetSample(self._tdl_noise_c, (x, y, z, w))
111
112
    def sample_mgrid(self, mgrid):
113
        """Sample a mesh-grid array and return the result.
114
115
        The :any:`sample_ogrid` method performs better as there is a lot of
116
        overhead when working with large mesh-grids.
117
118
        Args:
119
            mgrid (numpy.ndarray): A mesh-grid array of points to sample.
120
                A contiguous array of type :any:`numpy.float32` is preferred.
121
122
        Returns:
123
            numpy.ndarray: An array of sampled points
124
                           with the shape: ``mgrid.shape[:-1]``.
125
                           The ``dtype`` is :any:`numpy.float32`.
126
127
        .. versionadded:: 2.2
128
        """
129
        mgrid = np.ascontiguousarray(mgrid, np.float32)
130
        if mgrid.shape[0] != self.dimensions:
131
            raise ValueError('mgrid.shape[0] must equal self.dimensions, '
132
                             '%r[0] != %r' % (mgrid.shape, self.dimensions))
133
        out = np.ndarray(mgrid.shape[1:], np.float32)
134
        if mgrid.shape[1:] != out.shape:
135
            raise ValueError('mgrid.shape[1:] must equal out.shape, '
136
                             '%r[1:] != %r' % (mgrid.shape, out.shape))
137
        lib.NoiseSampleMeshGrid(self._tdl_noise_c, out.size,
138
                                ffi.cast('float*', mgrid.ctypes.data),
139
                                ffi.cast('float*', out.ctypes.data))
140
        return out
141
142
    def sample_ogrid(self, ogrid):
143
        """Sample an open mesh-grid array and return the result.
144
145
        Args
146
            ogrid (Sequence[numpy.ndarray]): An open mesh-grid.
147
148
        Returns:
149
            numpy.ndarray: An array of sampled points.  The ``shape`` is based
150
                           on the lengths of the open mesh-grid arrays.
151
                           The ``dtype`` is :any:`numpy.float32`.
152
153
        .. versionadded:: 2.2
154
        """
155
        if len(ogrid) != self.dimensions:
156
            raise ValueError('len(ogrid) must equal self.dimensions, '
157
                             '%r != %r' % (len(ogrid), self.dimensions))
158
        ogrids = [np.ascontiguousarray(array, np.float32) for array in ogrid]
159
        out = np.ndarray([array.size for array in ogrids], np.float32)
160
        lib.NoiseSampleOpenMeshGrid(
161
            self._tdl_noise_c,
162
            len(ogrids),
163
            out.shape,
164
            [ffi.cast('float*', array.ctypes.data) for array in ogrids],
165
            ffi.cast('float*', out.ctypes.data),
166
            )
167
        return out
168
169
    def __getstate__(self):
170
        if self.dimensions < 4 and self.noise_c.waveletTileData == ffi.NULL:
171
            # Trigger a side effect of wavelet, so that copies will be synced.
172
            saved_algo = self.algorithm
173
            self.algorithm = tcod.libtcod.NOISE_WAVELET
0 ignored issues
show
Bug introduced by
The Module tcod.libtcod does not seem to have a member named NOISE_WAVELET.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
174
            self.get_point()
175
            self.algorithm = saved_algo
176
177
        waveletTileData = None
178
        if self.noise_c.waveletTileData != ffi.NULL:
179
            waveletTileData = ffi.buffer(
180
                self.noise_c.waveletTileData[0:32*32*32])[:]
181
        return (
182
            self._random,
183
            self.implementation,
184
            self.octaves,
185
            self.noise_c.ndim,
186
            ffi.buffer(self.noise_c.map)[:],
187
            ffi.buffer(self.noise_c.buffer)[:],
188
            self.noise_c.H,
189
            self.noise_c.lacunarity,
190
            ffi.buffer(self.noise_c.exponent)[:],
191
            waveletTileData,
192
            self.noise_c.noise_type,
193
            )
194
195
    def __setstate__(self, state):
196
        self._random = state[0]
197
        self._random_c = _cdata(self._random)
198
        self.noise_c = ffi.new('perlin_data_t*')
199
        self.noise_c.ndim = state[3]
200
        ffi.buffer(self.noise_c.map)[:] = state[4]
201
        ffi.buffer(self.noise_c.buffer)[:] = state[5]
202
        self.noise_c.H = state[6]
203
        self.noise_c.lacunarity = state[7]
204
        ffi.buffer(self.noise_c.exponent)[:] = state[8]
205
        if state[9]:
206
            # high change of this being prematurely garbage collected!
207
            self.__waveletTileData = ffi.new('float[]', 32*32*32)
0 ignored issues
show
Coding Style introduced by
The attribute __waveletTileData was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
208
            ffi.buffer(self.__waveletTileData)[:] = state[9]
209
        self.noise_c.noise_type = state[10]
210
        self._tdl_noise_c = ffi.new('TDLNoise*',
211
                                    (self.noise_c, self.noise_c.ndim,
212
                                     state[1], state[2]))
213