Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Mersenne Twister from C++ standard library #1559

Merged
merged 6 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 3 additions & 44 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -659,10 +659,10 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-------------------------------------------------------------------------------
--

The Mersenne-Twister implementation "Randomkit" in brian2.random.randomkit is
based on code by Jean-Sebastien Roy, provided under the MIT license:
The `rand()` and `randn()` implementations are based on code by
Jean-Sebastien Roy, provided under the MIT license:

Copyright (c) 2003-2005, Jean-Sebastien Roy ([email protected])

Expand All @@ -687,47 +687,6 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

--

The rk_random and rk_seed functions algorithms and the original design of
the Mersenne Twister RNG:

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

--

Original algorithm for the implementation of rk_interval function from
Richard J. Wagner's implementation of the Mersenne Twister RNG, optimised by
Magnus Jonsson.

--

Constants used in the rk_double implementation by Isaku Wada.

--
Expand Down
11 changes: 3 additions & 8 deletions brian2/devices/cpp_standalone/codeobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,23 +138,18 @@ def generate_rand_code(rand_func, owner):
thread_number = "0"
else:
thread_number = "omp_get_thread_num()"
if rand_func == "rand":
rk_call = "rk_double"
elif rand_func == "randn":
rk_call = "rk_gauss"
else:
if rand_func not in ["rand", "randn"]:
raise AssertionError(rand_func)
code = """
double _%RAND_FUNC%(const int _vectorisation_idx) {
return %RK_CALL%(brian::_mersenne_twister_states[%THREAD_NUMBER%]);
inline double _%RAND_FUNC%(const int _vectorisation_idx) {
return brian::_random_generators[%THREAD_NUMBER%].%RAND_FUNC%();
}
"""
code = replace(
code,
{
"%THREAD_NUMBER%": thread_number,
"%RAND_FUNC%": rand_func,
"%RK_CALL%": rk_call,
},
)
return {"support_code": code}
Expand Down
40 changes: 5 additions & 35 deletions brian2/devices/cpp_standalone/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

import numpy as np

import brian2
from brian2.codegen.codeobject import check_compiler_kwds
from brian2.codegen.cpp_prefs import get_compiler_and_args, get_msvc_env
from brian2.codegen.generators.cpp_generator import c_data_type
Expand Down Expand Up @@ -228,8 +227,8 @@ def __init__(self):
self.extra_compile_args = []
self.define_macros = []
self.headers = []
self.include_dirs = ["brianlib/randomkit"]
self.library_dirs = ["brianlib/randomkit"]
self.include_dirs = []
self.library_dirs = []
self.runtime_library_dirs = []
self.run_environment_variables = {}
if sys.platform.startswith("darwin"):
Expand Down Expand Up @@ -873,13 +872,10 @@ def generate_main_source(self, writer):
nb_threads = 1
main_lines.append(f"for (int _i=0; _i<{nb_threads}; _i++)")
if seed is None: # random
main_lines.append(
" rk_randomseed(brian::_mersenne_twister_states[_i]);"
)
main_lines.append(" brian::_random_generators[_i].seed();")
else:
main_lines.append(
f" rk_seed({seed!r}L + _i,"
" brian::_mersenne_twister_states[_i]);"
f" brian::_random_generators[_i].seed({seed!r}L + _i);"
)
else:
raise NotImplementedError(f"Unknown main queue function type {func}")
Expand Down Expand Up @@ -1084,28 +1080,6 @@ def copy_source_files(self, writer, directory):
os.path.join(directory, "brianlib", "stdint_compat.h"),
)

# Copy the RandomKit implementation
if not os.path.exists(os.path.join(directory, "brianlib", "randomkit")):
os.mkdir(os.path.join(directory, "brianlib", "randomkit"))
shutil.copy2(
os.path.join(
os.path.split(inspect.getsourcefile(brian2))[0],
"random",
"randomkit",
"randomkit.c",
),
os.path.join(directory, "brianlib", "randomkit", "randomkit.c"),
)
shutil.copy2(
os.path.join(
os.path.split(inspect.getsourcefile(brian2))[0],
"random",
"randomkit",
"randomkit.h",
),
os.path.join(directory, "brianlib", "randomkit", "randomkit.h"),
)

def _insert_func_namespace(self, func, code_object, namespace):
impl = func.implementations[self.code_object_class()]
func_namespace = impl.get_namespace(code_object.owner)
Expand Down Expand Up @@ -1583,9 +1557,7 @@ def build(
for codeobj in self.code_objects.values()
for source_file in codeobj.compiler_kwds.get("sources", [])
]
additional_source_files += codeobj_source_files + [
"brianlib/randomkit/randomkit.c"
]
additional_source_files += codeobj_source_files

for d in ["code_objects", "results", "static_arrays"]:
ensure_directory(os.path.join(directory, d))
Expand Down Expand Up @@ -1703,7 +1675,6 @@ def delete(self, code=True, data=True, directory=True, force=False):
fnames.extend(
[
os.path.join("brianlib", "spikequeue.h"),
os.path.join("brianlib", "randomkit", "randomkit.h"),
os.path.join("brianlib", "stdint_compat.h"),
]
)
Expand Down Expand Up @@ -1731,7 +1702,6 @@ def delete(self, code=True, data=True, directory=True, force=False):

if directory:
directories = [
os.path.join("brianlib", "randomkit"),
"brianlib",
"code_objects",
"results",
Expand Down
2 changes: 1 addition & 1 deletion brian2/devices/cpp_standalone/templates/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
{{ openmp_pragma('include') }}
#include "run.h"
#include "brianlib/common_math.h"
#include "randomkit.h"

{% for codeobj in code_objects | sort(attribute='name') %}
#include "code_objects/{{codeobj.name}}.h"
Expand Down Expand Up @@ -36,6 +35,7 @@ void set_from_command_line(const std::vector<std::string> args)
}
int main(int argc, char **argv)
{
std::random_device _rd;
std::vector<std::string> args(argv + 1, argv + argc);
if (args.size() >=2 && args[0] == "--results_dir")
{
Expand Down
Loading
Loading