Modification in Go Bindings and Add Markdown Documentation

This commit is contained in:
Yashwant
2020-06-14 10:15:10 +05:30
parent 4ebfcf438f
commit 2a8fc6ebd4
100 changed files with 7509 additions and 55 deletions
+17 -9
View File
@@ -15,15 +15,18 @@ jobs:
strategy:
matrix:
Plain:
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF'
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=OFF'
Python:
python.version: '3.7'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DPYTHON_EXECUTABLE=/opt/hostedtoolcache/Python/3.7.7/x64/bin/python3'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DPYTHON_EXECUTABLE=/opt/hostedtoolcache/Python/3.7.7/x64/bin/python3 -DBUILD_GO_BINDINGS=OFF'
Julia:
julia.version: '1.3.0'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_JULIA_BINDINGS=ON -DJULIA_EXECUTABLE=/opt/julia-1.3.0/bin/julia'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_JULIA_BINDINGS=ON -DBUILD_GO_BINDINGS=OFF -DJULIA_EXECUTABLE=/opt/julia-1.3.0/bin/julia'
Go:
go.version: '1.11.0'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=ON'
Markdown:
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_MARKDOWN_BINDINGS=ON -DBUILD_PYTHON_BINDINGS=OFF'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_MARKDOWN_BINDINGS=ON -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=OFF'
steps:
- template: linux-steps.yaml
@@ -35,15 +38,20 @@ jobs:
strategy:
matrix:
Plain:
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF'
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=OFF'
python.version: '2.7'
Python:
python.version: '3.7'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_GO_BINDINGS=OFF'
Julia:
python.version: '2.7'
julia.version: '1.3.0'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_JULIA_BINDINGS=ON -DBUILD_PYTHON_BINDINGS=OFF'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_JULIA_BINDINGS=ON -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=OFF'
Go:
python.version: '2.7'
go.version: '1.11.0'
CMakeArgs: '-DDEBUG=OFF -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=ON'
steps:
- template: macos-steps.yaml
@@ -56,7 +64,7 @@ jobs:
strategy:
matrix:
Plain:
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF'
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=OFF'
python.version: '2.7'
CMakeGenerator: '-G "Visual Studio 15 2017 Win64"'
MSBuildVersion: '15.0'
@@ -75,7 +83,7 @@ jobs:
strategy:
matrix:
Plain:
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF'
CMakeArgs: '-DDEBUG=ON -DPROFILE=OFF -DBUILD_PYTHON_BINDINGS=OFF -DBUILD_GO_BINDINGS=OFF'
python.version: '2.7'
CMakeGenerator: '-G "Visual Studio 16 2019"'
MSBuildVersion: '16.0'
+4 -1
View File
@@ -40,7 +40,10 @@ steps:
displayName: 'Install Build Dependencies'
# Configure mlpack (CMake)
- script: unset BOOST_ROOT && mkdir build && cd build && cmake $(CMakeArgs) ..
- script: |
export GOPATH=$PWD
go get gonum.org/v1/gonum/mat/...
unset BOOST_ROOT && mkdir build && cd build && cmake $(CMakeArgs) ..
displayName: 'CMake'
# Build mlpack
+3
View File
@@ -15,6 +15,7 @@ steps:
sudo xcode-select --switch /Applications/Xcode_10.1.app/Contents/Developer
unset BOOST_ROOT
pip install cython numpy pandas zipp configparser
go get -u gonum.org/v1/gonum/mat
brew install openblas armadillo boost
if [ "a$(julia.version)" != "a" ]; then
@@ -28,6 +29,8 @@ steps:
- script: |
unset BOOST_ROOT
mkdir build && cd build
export GOPATH=$PWD
go get -u -t gonum.org/v1/gonum/mat
export PYPATH=$(which python)
cmake $(CMakeArgs) -DPYTHON_EXECUTABLE=$PYPATH ..
displayName: 'CMake'
+14
View File
@@ -0,0 +1,14 @@
# ConfigureGoHCPP.cmake: generate an mlpack .h file for a Go binding given
# input arguments.
#
# This file depends on the following variables being set:
#
# * PROGRAM_NAME: name of the binding
# * PROGRAM_MAIN_FILE: the file containing the mlpackMain() function.
# * GENERATE_GO_IN: path of the generate_go.cpp.in file.
# * GENERATE_GO_OUT: name of the output .go file.
# * GENERATE_CPP_IN: path of the generate_cpp.cpp.in file.
# * GENERATE_CPP_OUT: name of the output .cpp file.
# * GENERATE_H_IN: path of the generate_h.cpp.in file.
# * GENERATE_H_OUT: name of the output .h file.
configure_file("${GENERATE_BINDING_IN}" "${GENERATE_BINDING_OUT}")
+43
View File
@@ -0,0 +1,43 @@
# Find the Go package.
# The module defines the following variables:
# GO_FOUND - true if the Go was found
# GO_EXECUTABLE - path to the executable
# GO_VERSION - Go version number
# GO_PLATFORM - i.e. linux
# GO_ARCH - i.e. amd64
if (GO_FOUND)
return()
endif()
find_program(GO_EXECUTABLE go PATHS $ENV{HOME}/go ENV GOROOT GOPATH PATH_SUFFIXES bin)
if(GO_EXECUTABLE)
if (DEFINED ENV{GOROOT})
set(GO_ROOT "$ENV{GOROOT}")
else()
set(GO_ROOT "/usr/lib/go")
endif()
endif()
# Get the Go version.
if (GO_EXECUTABLE)
execute_process(
COMMAND ${GO_EXECUTABLE} version
OUTPUT_VARIABLE GO_VERSION_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(GO_VERSION_OUTPUT MATCHES "go([0-9]+\\.[0-9]+\\.?[0-9]*)[a-zA-Z0-9]* ([^/]+)/(.*)")
set(GO_VERSION ${CMAKE_MATCH_1})
set(GO_PLATFORM ${CMAKE_MATCH_2})
set(GO_ARCH ${CMAKE_MATCH_3})
endif()
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
Go
REQUIRED_VARS GO_EXECUTABLE
VERSION_VAR GO_VERSION
FAIL_MESSAGE "Go not found"
)
+23
View File
@@ -0,0 +1,23 @@
# The module defines the following variables:
# GONUM_FOUND - true if the Gonum was found
# GONUM - Gonum version number
find_program(GO_EXECUTABLE go PATHS $ENV{HOME}/go ENV GOROOT GOPATH PATH_SUFFIXES bin)
if(GO_EXECUTABLE)
execute_process(
COMMAND ${GO_EXECUTABLE} list gonum.org/v1/gonum/mat
OUTPUT_VARIABLE GONUM_VERSION_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(GONUM_VERSION_OUTPUT MATCHES "gonum.org/v1/gonum/mat")
set(GONUM ${GONUM_VERSION_OUTPUT})
endif()
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
Gonum
REQUIRED_VARS GONUM
FAIL_MESSAGE "Gonum not found"
)
+13
View File
@@ -0,0 +1,13 @@
# GenerateGoBinding.cmake: a CMake script that actually runs the given program to
# generate an mlpack binding file.
#
# This script depends on the following arguments:
#
# GENERATE_H_PROGRAM: the program to run to generate the .h file.
# H_OUTPUT_FILE: the file to store the output in.
# GENERATE_GO_PROGRAM: the program to run to generate the .go file.
# GO_OUTPUT_FILE: the file to store the output in.
# GENERATE_CPP_PROGRAM: the program to run to generate the .cpp file.
# CPP_OUTPUT_FILE: the file to store the output in.
execute_process(COMMAND ${GENERATE_BINDING_PROGRAM}
OUTPUT_FILE ${BINDING_OUTPUT_FILE})
+10
View File
@@ -18,6 +18,7 @@ option(DOWNLOAD_ENSMALLEN "If ensmallen is not found, download it." ON)
option(DOWNLOAD_STB_IMAGE "Download stb_image for image loading." ON)
option(BUILD_PYTHON_BINDINGS "Build Python bindings." ON)
option(BUILD_JULIA_BINDINGS "Build Julia bindings." ON)
option(BUILD_GO_BINDINGS "Build Go bindings." ON)
if (WIN32)
option(BUILD_SHARED_LIBS
@@ -30,6 +31,15 @@ else ()
"Compile shared libraries (if OFF, static libraries are compiled)." ON)
endif()
# Detect whether the user passed BUILD_GO_BINDINGS in order to determine if
# we should fail if Go isn't found.
if (BUILD_GO_BINDINGS)
set(FORCE_BUILD_GO_BINDINGS ON)
else()
set(FORCE_BUILD_GO_BINDINGS OFF)
endif()
option(BUILD_GO_BINDINGS "Build Go bindings." OFF)
# Build Markdown bindings for documentation. This is used as part of website
# generation.
option(BUILD_MARKDOWN_BINDINGS "Build Markdown bindings for website documentation." OFF)
+1
View File
@@ -4,6 +4,7 @@ set(DIRS
julia
markdown
python
go
tests
)
+258
View File
@@ -0,0 +1,258 @@
if (BUILD_GO_BINDINGS)
# We need to check here if Go is even available, since the tests will need it.
find_package(Go 1.11.0)
if (NOT GO_FOUND)
# We can't build anything, so define the macro to do nothing.
macro (add_go_binding name)
# Do nothing.
endmacro ()
return ()
endif ()
find_package(Gonum)
if (NOT GONUM_FOUND)
# We can't build anything, so define the macro to do nothing.
macro (add_go_binding name)
# Do nothing.
endmacro ()
endif ()
# Nothing in this directory will be compiled into mlpack.
set(BINDING_SOURCES
get_type.hpp
get_param.hpp
get_printable_param.hpp
go_option.hpp
mlpack/arma_util.h
mlpack/arma_util.hpp
mlpack/cli_util.h
mlpack/cli_util.hpp
print_class_defn.hpp
print_cpp.cpp
print_cpp.hpp
print_defn_input.hpp
print_defn_output.hpp
print_doc.hpp
print_doc_functions.hpp
print_doc_functions_impl.hpp
print_go.hpp
print_go.cpp
print_h.hpp
print_h.cpp
print_import_decl.hpp
print_input_processing.hpp
print_method_config.hpp
print_method_init.hpp
print_output_processing.hpp
camel_case.hpp
strip_type.hpp
)
# These are all the files we need to compile Go bindings for mlpack that are
# not a part of mlpack itself.
set(CGO_SOURCES
mlpack/arma_util.go
mlpack/cli_util.go
mlpack/doc.go
)
# These are all the files we need to compile Go bindings for mlpack that are
# not a part of mlpack itself.
set(CAPI_SOURCES
mlpack/capi/arma_util.cpp
mlpack/capi/arma_util.h
mlpack/capi/arma_util.hpp
mlpack/capi/cli_util.cpp
mlpack/capi/cli_util.h
mlpack/capi/cli_util.hpp
)
# These are all the files we need to compile Go bindings for mlpack that are
# not a part of mlpack itself.
set(UTIL_SOURCES
mlpack/capi/arma_util.cpp
mlpack/capi/cli_util.cpp
)
set(TEST_SOURCES
tests/go_binding_test.go
)
add_custom_target(go ALL DEPENDS mlpack)
add_custom_target(go_copy ALL DEPENDS mlpack)
if (BUILD_TESTS)
foreach(test_file ${TEST_SOURCES})
add_custom_command(TARGET go_copy PRE_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${test_file}
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/tests/)
endforeach ()
endif ()
# Copy necessary files after making the mlpack/ directory.
add_custom_command(TARGET go_copy PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/
COMMAND ${CMAKE_COMMAND} -E make_directory
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/)
foreach(go_file ${CAPI_SOURCES})
add_custom_command(TARGET go_copy PRE_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${go_file}
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/)
endforeach()
add_custom_command(TARGET go_copy PRE_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
$<TARGET_FILE:mlpack>
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/)
foreach(cgo_file ${CGO_SOURCES})
add_custom_command(TARGET go_copy PRE_BUILD
COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${cgo_file}
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/)
endforeach()
add_library(go_util SHARED
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/mlpack/capi/arma_util.cpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/mlpack/capi/cli_util.cpp)
target_link_libraries(go_util mlpack ${MLPACK_LIBRARIES})
target_compile_definitions(go_util PUBLIC "BINDING_TYPE=BINDING_TYPE_GO")
set_target_properties(go_util PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/)
# Set the include directories correctly.
get_property(GO_INCLUDE_DIRECTORIES DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
PROPERTY INCLUDE_DIRECTORIES)
set (GO_INCLDIRS "${GO_INCLUDE_DIRECTORIES}")
endif()
# Add a macro to build a go binding.
macro (add_go_binding name)
if (BUILD_GO_BINDINGS)
# Append sources (with directory name) to list of all mlpack sources (used at
# the parent scope).
set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
# Create .cpp file for C API, e.g. pca.cpp.
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_cpp_${name}.cpp
COMMAND ${CMAKE_COMMAND}
-DGENERATE_BINDING_IN=${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/generate_cpp.cpp.in
-DGENERATE_BINDING_OUT=${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_cpp_${name}.cpp
-DPROGRAM_MAIN_FILE=${CMAKE_CURRENT_SOURCE_DIR}/${name}_main.cpp
-DPROGRAM_NAME=${name}
-P ${CMAKE_SOURCE_DIR}/CMake/ConfigureGoHCPP.cmake
DEPENDS ${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/generate_cpp.cpp.in)
add_executable(generate_cpp_${name}
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_cpp_${name}.cpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/print_cpp.hpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/print_cpp.cpp)
target_link_libraries(generate_cpp_${name} mlpack ${MLPACK_LIBRARIES})
set_target_properties(generate_cpp_${name} PROPERTIES COMPILE_FLAGS
-DBINDING_TYPE=BINDING_TYPE_GO)
add_custom_command(TARGET generate_cpp_${name} POST_BUILD
COMMAND ${CMAKE_COMMAND}
-DGENERATE_BINDING_PROGRAM=${CMAKE_BINARY_DIR}/bin/generate_cpp_${name}
-DBINDING_OUTPUT_FILE=${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/${name}.cpp
-P ${CMAKE_SOURCE_DIR}/CMake/GenerateGoBinding.cmake)
add_custom_target(build_cpp_${name}
DEPENDS generate_cpp_${name}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/
COMMENT "Building ${name}.cpp for Go binding ...")
add_dependencies(build_cpp_${name} generate_cpp_${name})
# Create .h file for C API, e.g. pca.h.
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_h_${name}.cpp
COMMAND ${CMAKE_COMMAND}
-DGENERATE_BINDING_IN=${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/generate_h.cpp.in
-DGENERATE_BINDING_OUT=${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_h_${name}.cpp
-DPROGRAM_MAIN_FILE=${CMAKE_CURRENT_SOURCE_DIR}/${name}_main.cpp
-DPROGRAM_NAME=${name}
-P ${CMAKE_SOURCE_DIR}/CMake/ConfigureGoHCPP.cmake
DEPENDS ${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/generate_h.cpp.in)
add_executable(generate_h_${name}
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_h_${name}.cpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/print_h.hpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/print_h.cpp)
target_link_libraries(generate_h_${name} mlpack ${MLPACK_LIBRARIES})
set_target_properties(generate_h_${name} PROPERTIES COMPILE_FLAGS
-DBINDING_TYPE=BINDING_TYPE_GO)
add_custom_command(TARGET generate_h_${name} POST_BUILD
COMMAND ${CMAKE_COMMAND}
-DGENERATE_BINDING_PROGRAM=${CMAKE_BINARY_DIR}/bin/generate_h_${name}
-DBINDING_OUTPUT_FILE=${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/${name}.h
-P ${CMAKE_SOURCE_DIR}/CMake/GenerateGoBinding.cmake)
add_custom_target(build_h_${name}
DEPENDS generate_h_${name}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/
COMMENT "Building ${name}.h for Go binding ...")
# Create .go file, pca.go.
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_go_${name}.cpp
COMMAND ${CMAKE_COMMAND}
-DGENERATE_BINDING_IN=${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/generate_go.cpp.in
-DGENERATE_BINDING_OUT=${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_go_${name}.cpp
-DPROGRAM_MAIN_FILE=${CMAKE_CURRENT_SOURCE_DIR}/${name}_main.cpp
-DPROGRAM_NAME=${name}
-P ${CMAKE_SOURCE_DIR}/CMake/ConfigureGoHCPP.cmake
DEPENDS ${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/generate_go.cpp.in)
add_executable(generate_go_${name}
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/generate_go_${name}.cpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/print_go.hpp
${CMAKE_SOURCE_DIR}/src/mlpack/bindings/go/print_go.cpp)
target_link_libraries(generate_go_${name} mlpack ${MLPACK_LIBRARIES})
set_target_properties(generate_go_${name} PROPERTIES COMPILE_FLAGS
-DBINDING_TYPE=BINDING_TYPE_GO)
add_custom_command(TARGET generate_go_${name} POST_BUILD
COMMAND ${CMAKE_COMMAND}
-DGENERATE_BINDING_PROGRAM=${CMAKE_BINARY_DIR}/bin/generate_go_${name}
-DBINDING_OUTPUT_FILE=${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/${name}.go
-P ${CMAKE_SOURCE_DIR}/CMake/GenerateGoBinding.cmake)
add_custom_target(build_go_${name}
DEPENDS generate_go_${name}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/
COMMENT "Building ${name}.go for Go binding ...")
add_dependencies(build_go_${name} go_copy)
add_dependencies(build_go_${name} generate_go_${name})
add_dependencies(build_go_${name} build_cpp_${name})
add_dependencies(build_go_${name} build_h_${name})
# Create, e.g., libmlpack_go_pca.so.
add_library(mlpack_go_${name} SHARED
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/${name}.cpp
${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/${name}.h)
set_source_files_properties(${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/${name}.cpp
PROPERTIES GENERATED TRUE)
set_source_files_properties(${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/capi/${name}.h
PROPERTIES GENERATED TRUE)
target_link_libraries(mlpack_go_${name} mlpack ${MLPACK_LIBRARIES})
target_compile_definitions(mlpack_go_${name} PUBLIC "BINDING_TYPE=BINDING_TYPE_GO")
set_target_properties(mlpack_go_${name} PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/)
install(TARGETS mlpack_go_${name}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
add_dependencies(mlpack_go_${name} build_go_${name})
add_dependencies(mlpack_go_${name} go_util)
add_dependencies(go mlpack_go_${name})
endif ()
endmacro ()
if (BUILD_TESTS)
add_subdirectory(tests)
endif ()
+50
View File
@@ -0,0 +1,50 @@
/**
* @file camel_case.hpp
* @author Yashwant Singh
*
* Given a C++ typename that may have template parameters, return stripped and
* printable versions to be used in Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_CAMEL_CASE_HPP
#define MLPACK_BINDINGS_GO_CAMEL_CASE_HPP
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given an snake_case like, e.g., "logistic_regression", return
* CamelCase(e.g. "LogisticRegression") that can be used in Go code.
*/
inline std::string CamelCase(std::string s)
{
s[0] = std::toupper(s[0]);
size_t n = s.length();
size_t res_ind = 0;
for (size_t i = 0; i < n; i++)
{
// check for spaces in the sentence
if (s[i] == '_')
{
// conversion into upper case
s[i + 1] = toupper(s[i + 1]);
continue;
}
// If not space, copy character
else
s[res_ind++] = s[i];
}
// return string to main
return s.substr(0, res_ind);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+95
View File
@@ -0,0 +1,95 @@
/**
* @file default_param.hpp
* @author Yashwant Singh
*
* Return the default value of a parameter, depending on its type.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_DEFAULT_PARAM_HPP
#define MLPACK_BINDINGS_GO_DEFAULT_PARAM_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/param_data.hpp>
#include <mlpack/core/util/is_std_vector.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Return the default value of an option. This is for regular types.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T, std::string>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* = 0);
/**
* Return the default value of a vector option.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::enable_if<util::IsStdVector<T>>::type* = 0);
/**
* Return the default value of a string option.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::enable_if<std::is_same<T, std::string>>::type* = 0);
/**
* Return the default value of a matrix option, a tuple option, a
* serializable option, or a string option (this returns the default filename,
* or '' if the default is no file).
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::enable_if_c<
arma::is_arma_type<T>::value ||
std::is_same<T, std::tuple<mlpack::data::DatasetInfo,
arma::mat>>::value>::type* /* junk */ = 0);
/**
* Return the default value of a model option (this returns the default
* filename, or '' if the default is no file).
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0);
/**
* Return the default value of an option. This is the function that will be
* placed into the CLI functionMap.
*/
template<typename T>
void DefaultParam(const util::ParamData& data,
const void* /* input */,
void* output)
{
std::string* outstr = (std::string*) output;
*outstr = DefaultParamImpl<typename std::remove_pointer<T>::type>(data);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
// Include implementation.
#include "default_param_impl.hpp"
#endif
@@ -0,0 +1,147 @@
/**
* @file default_param_impl.hpp
* @author Yashwant Singh
*
* Return the default value of a parameter, depending on its type.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_DEFAULT_PARAM_IMPL_HPP
#define MLPACK_BINDINGS_GO_DEFAULT_PARAM_IMPL_HPP
#include "default_param.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Return the default value of an option.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* /* junk */,
const typename boost::disable_if<util::IsStdVector<T>>::type* /* junk */,
const typename boost::disable_if<data::HasSerialize<T>>::type* /* junk */,
const typename boost::disable_if<std::is_same<T, std::string>>::type*,
const typename boost::disable_if<std::is_same<T,
std::tuple<mlpack::data::DatasetInfo, arma::mat>>>::type* /* junk */)
{
std::ostringstream oss;
if (std::is_same<T, bool>::value)
oss << "false";
else
oss << boost::any_cast<T>(data.value);
return oss.str();
}
/**
* Return the default value of a vector option.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::enable_if<util::IsStdVector<T>>::type* /* junk */)
{
// Print each element in an array delimited by square brackets.
std::ostringstream oss;
const T& vector = boost::any_cast<T>(data.value);
if (std::is_same<T, std::vector<std::string>>::value)
{
oss << "[]string{";
if (vector.size() > 0)
{
for (size_t i = 0; i < vector.size() - 1; ++i)
{
oss << "\"" << vector[i] << "\", ";
}
oss << "\"" << vector[vector.size() - 1] << "\"";
}
oss << "}";
}
else if (std::is_same<T, std::vector<int>>::value)
{
oss << "[]int{";
if (vector.size() > 0)
{
for (size_t i = 0; i < vector.size() - 1; ++i)
{
oss << vector[i] << ", ";
}
oss << vector[vector.size() - 1];
}
oss << "}";
}
return oss.str();
}
/**
* Return the default value of a string option.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& data,
const typename boost::enable_if<std::is_same<T, std::string>>::type*)
{
const std::string& s = *boost::any_cast<std::string>(&data.value);
return "\"" + s + "\"";
}
/**
* Return the default value of a matrix option.
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& /* data */,
const typename boost::enable_if_c<
arma::is_arma_type<T>::value ||
std::is_same<T, std::tuple<mlpack::data::DatasetInfo,
arma::mat>>::value>::type* /* junk */)
{
// Get the filename and return it, or return an empty string.
if (std::is_same<T, arma::rowvec>::value ||
std::is_same<T, arma::vec>::value)
{
return "mat.NewDense(1, 1, nil)";
}
else if (std::is_same<T, arma::Col<size_t>>::value ||
std::is_same<T, arma::Row<size_t>>::value)
{
return "mat.NewDense(1, 1, nil)";
}
else if (std::is_same<T, arma::Mat<size_t>>::value)
{
return "mat.NewDense(1, 1, nil)";
}
else
{
return "mat.NewDense(1, 1, nil)";
}
}
/**
* Return the default value of a model option (always "nil").
*/
template<typename T>
std::string DefaultParamImpl(
const util::ParamData& /* data */,
const typename boost::disable_if<arma::is_arma_type<T>>::type* /* junk */,
const typename boost::enable_if<data::HasSerialize<T>>::type* /* junk */)
{
return "nil";
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,49 @@
/*
* @file generate_cpp_${PROGRAM_NAME}.cpp
* @author Yasmine Dumouchel
*
* This is an automatically-generated file that is used to generate the .cpp
* files that are used for the Go bindings. This program will print the
* .cpp file on stdout when run and doesn't need any input parameters.
*
* The CMake variable ${PROGRAM_NAME} must be set for
* this to configure correctly.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#define BINDING_TYPE BINDING_TYPE_GO
// Disable debug output.
#ifdef DEBUG
#define HAD_DEBUG
#undef DEBUG
#endif
#include <mlpack/core/util/log.hpp>
#ifdef HAD_DEBUG
#undef HAD_DEBUG
#define DEBUG
#endif
#include <mlpack/core.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include <mlpack/bindings/go/print_cpp.hpp>
// This will include the ParamData options that are a part of the program.
#include <${PROGRAM_MAIN_FILE}>
using namespace mlpack;
using namespace mlpack::bindings;
using namespace mlpack::bindings::go;
using namespace std;
using namespace mlpack::util;
int main(int /* argc */, char** /* argv */)
{
// All the parameters are registered, but stored, so restore them.
// programName is defined in mlpack_main.hpp.
CLI::RestoreSettings(programName);
PrintCPP(*CLI::GetSingleton().doc, "${PROGRAM_MAIN_FILE}", "${PROGRAM_NAME}");
}
+49
View File
@@ -0,0 +1,49 @@
/*
* @file generate_go_${PROGRAM_NAME}.cpp
* @author Yasmine Dumouchel
*
* This is an automatically-generated file that is used to generate the .go
* files that are used for the Go bindings. This program will print the
* .go file on stdout when run and doesn't need any input parameters.
*
* The CMake variable ${PROGRAM_NAME} must be set for
* this to configure correctly.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#define BINDING_TYPE BINDING_TYPE_GO
// Disable debug output.
#ifdef DEBUG
#define HAD_DEBUG
#undef DEBUG
#endif
#include <mlpack/core/util/log.hpp>
#ifdef HAD_DEBUG
#undef HAD_DEBUG
#define DEBUG
#endif
#include <mlpack/core.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include <mlpack/bindings/go/print_go.hpp>
// This will include the ParamData options that are a part of the program.
#include <${PROGRAM_MAIN_FILE}>
using namespace mlpack;
using namespace mlpack::bindings;
using namespace mlpack::bindings::go;
using namespace std;
using namespace mlpack::util;
int main(int /* argc */, char** /* argv */)
{
// All the parameters are registered, but stored, so restore them.
// programName is defined in mlpack_main.hpp.
CLI::RestoreSettings(programName);
PrintGo(*CLI::GetSingleton().doc, "${PROGRAM_NAME}");
}
+49
View File
@@ -0,0 +1,49 @@
/*
* @file generate_h_${PROGRAM_NAME}.cpp
* @author Yasmine Dumouchel
*
* This is an automatically-generated file that is used to generate the .h
* files that are used for the Go bindings. This program will print the
* .h file on stdout when run and doesn't need any input parameters.
*
* The CMake variable ${PROGRAM_NAME} must be set for
* this to configure correctly.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#define BINDING_TYPE BINDING_TYPE_GO
// Disable debug output.
#ifdef DEBUG
#define HAD_DEBUG
#undef DEBUG
#endif
#include <mlpack/core/util/log.hpp>
#ifdef HAD_DEBUG
#undef HAD_DEBUG
#define DEBUG
#endif
#include <mlpack/core.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include <mlpack/bindings/go/print_h.hpp>
// This will include the ParamData options that are a part of the program.
#include <${PROGRAM_MAIN_FILE}>
using namespace mlpack;
using namespace mlpack::bindings;
using namespace mlpack::bindings::go;
using namespace std;
using namespace mlpack::util;
int main(int /* argc */, char** /* argv */)
{
// All the parameters are registered, but stored, so restore them.
// programName is defined in mlpack_main.hpp.
CLI::RestoreSettings(programName);
PrintH(*CLI::GetSingleton().doc, "${PROGRAM_NAME}");
}
+139
View File
@@ -0,0 +1,139 @@
/**
* @file get_go_type.hpp
* @author Yasmine Dumouchel
* @author Yashwant Singh
*
* Template metaprogramming to return the string representation of the Go
* type for a given Go binding parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GET_GO_TYPE_HPP
#define MLPACK_BINDINGS_GO_GET_GO_TYPE_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/is_std_vector.hpp>
#include "strip_type.hpp"
namespace mlpack {
namespace bindings {
namespace go {
template<typename T>
inline std::string GetGoType(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
return "unknown";
}
template<>
inline std::string GetGoType<int>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<int>>::type*,
const typename boost::disable_if<data::HasSerialize<int>>::type*,
const typename boost::disable_if<arma::is_arma_type<int>>::type*,
const typename boost::disable_if<std::is_same<int,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "int";
}
template<>
inline std::string GetGoType<float>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<float>>::type*,
const typename boost::disable_if<data::HasSerialize<float>>::type*,
const typename boost::disable_if<arma::is_arma_type<float>>::type*,
const typename boost::disable_if<std::is_same<float,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "float32";
}
template<>
inline std::string GetGoType<double>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<double>>::type*,
const typename boost::disable_if<data::HasSerialize<double>>::type*,
const typename boost::disable_if<arma::is_arma_type<double>>::type*,
const typename boost::disable_if<std::is_same<double,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "float64";
}
template<>
inline std::string GetGoType<std::string>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<std::string>>::type*,
const typename boost::disable_if<data::HasSerialize<std::string>>::type*,
const typename boost::disable_if<arma::is_arma_type<std::string>>::type*,
const typename boost::disable_if<std::is_same<std::string,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "string";
}
template<>
inline std::string GetGoType<bool>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<bool>>::type*,
const typename boost::disable_if<data::HasSerialize<bool>>::type*,
const typename boost::disable_if<arma::is_arma_type<bool>>::type*,
const typename boost::disable_if<std::is_same<bool,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "bool";
}
template<typename T>
inline std::string GetGoType(
const util::ParamData& d,
const typename boost::enable_if<util::IsStdVector<T>>::type* = 0)
{
return "[]" + GetGoType<typename T::value_type>(d);
}
template<typename T>
inline std::string GetGoType(
const util::ParamData& /* d */,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
return "mat.Dense";
}
template<typename T>
inline std::string GetGoType(
const util::ParamData& /* d */,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
return "MatrixWithInfo";
}
template<typename T>
inline std::string GetGoType(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
return goStrippedType;
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+37
View File
@@ -0,0 +1,37 @@
/**
* @file get_param.hpp
* @author Yashwant Singh
*
* Get a parameter for a Go binding.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GET_PARAM_HPP
#define MLPACK_BINDINGS_GO_GET_PARAM_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* All Go binding types are exactly what is held in the ParamData, so no
* special handling is necessary.
*/
template<typename T>
void GetParam(const util::ParamData& d,
const void* /* input */,
void* output)
{
*((T**) output) = const_cast<T*>(boost::any_cast<T>(&d.value));
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,126 @@
/**
* @file get_printable_param.hpp
* @author Yashwant Singh
*
* Get a printable version of parameters.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GET_PRINTABLE_PARAM_HPP
#define MLPACK_BINDINGS_GO_GET_PRINTABLE_PARAM_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/is_std_vector.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print an option of a simple type.
*/
template<typename T>
std::string GetPrintableParam(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
std::ostringstream oss;
oss << boost::any_cast<T>(data.value);
return oss.str();
}
/**
* Print a vector option, with spaces between it.
*/
template<typename T>
std::string GetPrintableParam(
const util::ParamData& data,
const typename boost::enable_if<util::IsStdVector<T>>::type* = 0)
{
const T& t = boost::any_cast<T>(data.value);
std::ostringstream oss;
for (size_t i = 0; i < t.size(); ++i)
oss << t[i] << " ";
return oss.str();
}
/**
* Print a matrix option (this prints its size).
*/
template<typename T>
std::string GetPrintableParam(
const util::ParamData& data,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// Get the matrix.
const T& matrix = boost::any_cast<T>(data.value);
std::ostringstream oss;
oss << matrix.n_rows << "x" << matrix.n_cols << " matrix";
return oss.str();
}
/**
* Print a serializable class option (this prints the class name).
*/
template<typename T>
std::string GetPrintableParam(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
std::ostringstream oss;
oss << data.cppType << " model at " << boost::any_cast<T*>(data.value);
return oss.str();
}
/**
* Print a combination DatasetInfo/matrix parameter.
*/
template<typename T>
std::string GetPrintableParam(
const util::ParamData& data,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Get the matrix.
const T& tuple = boost::any_cast<T>(data.value);
const arma::mat& matrix = std::get<1>(tuple);
std::ostringstream oss;
oss << matrix.n_rows << "x" << matrix.n_cols << " matrix with dimension type "
<< "information";
return oss.str();
}
/**
* Print an option into a std::string. This should print a short, one-line
* representation of the object. The string will be stored in the output
* pointer.
*
* @param data Parameter data struct.
* @param input Unused parameter.
* @param output Output storage for the string.
*/
template<typename T>
void GetPrintableParam(const util::ParamData& data,
const void* /* input */,
void* output)
{
*((std::string*) output) =
GetPrintableParam<typename std::remove_pointer<T>::type>(data);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+111
View File
@@ -0,0 +1,111 @@
/**
* @file get_printable_type.hpp
* @author Yashwant Singh
*
* Template metaprogramming to return the string representation of the Go
* type for a given Go binding parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GET_PRINTABLE_TYPE_HPP
#define MLPACK_BINDINGS_GO_GET_PRINTABLE_TYPE_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/is_std_vector.hpp>
namespace mlpack {
namespace bindings {
namespace go {
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0);
template<>
inline std::string GetPrintableType<int>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<int>>::type*,
const typename boost::disable_if<data::HasSerialize<int>>::type*,
const typename boost::disable_if<arma::is_arma_type<int>>::type*,
const typename boost::disable_if<std::is_same<int,
std::tuple<data::DatasetInfo, arma::mat>>>::type*);
template<>
inline std::string GetPrintableType<double>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<double>>::type*,
const typename boost::disable_if<data::HasSerialize<double>>::type*,
const typename boost::disable_if<arma::is_arma_type<double>>::type*,
const typename boost::disable_if<std::is_same<double,
std::tuple<data::DatasetInfo, arma::mat>>>::type*);
template<>
inline std::string GetPrintableType<std::string>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<std::string>>::type*,
const typename boost::disable_if<data::HasSerialize<std::string>>::type*,
const typename boost::disable_if<arma::is_arma_type<std::string>>::type*,
const typename boost::disable_if<std::is_same<std::string,
std::tuple<data::DatasetInfo, arma::mat>>>::type*);
template<>
inline std::string GetPrintableType<bool>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<bool>>::type*,
const typename boost::disable_if<data::HasSerialize<bool>>::type*,
const typename boost::disable_if<arma::is_arma_type<bool>>::type*,
const typename boost::disable_if<std::is_same<bool,
std::tuple<data::DatasetInfo, arma::mat>>>::type*);
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& d,
const typename boost::enable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0);
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& /* d */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0);
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& /* d */,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0);
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0);
template<typename T>
void GetPrintableType(const util::ParamData& d,
const void* /* input */,
void* output)
{
*((std::string*) output) =
GetPrintableType<typename std::remove_pointer<T>::type>(d);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#include "get_printable_type_impl.hpp"
#endif
+139
View File
@@ -0,0 +1,139 @@
/**
* @file get_printable_type_impl.hpp
* @author Yashwant Singh
*
* Template metaprogramming to return the string representation of the Go
* type for a given Go binding parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GET_PRINTABLE_TYPE_IMPL_HPP
#define MLPACK_BINDINGS_GO_GET_PRINTABLE_TYPE_IMPL_HPP
#include "get_printable_type.hpp"
namespace mlpack {
namespace bindings {
namespace go {
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<T>>::type*,
const typename boost::disable_if<data::HasSerialize<T>>::type*,
const typename boost::disable_if<arma::is_arma_type<T>>::type*,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "unknown";
}
template<>
inline std::string GetPrintableType<int>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<int>>::type*,
const typename boost::disable_if<data::HasSerialize<int>>::type*,
const typename boost::disable_if<arma::is_arma_type<int>>::type*,
const typename boost::disable_if<std::is_same<int,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "int";
}
template<>
inline std::string GetPrintableType<double>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<double>>::type*,
const typename boost::disable_if<data::HasSerialize<double>>::type*,
const typename boost::disable_if<arma::is_arma_type<double>>::type*,
const typename boost::disable_if<std::is_same<double,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "float64";
}
template<>
inline std::string GetPrintableType<std::string>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<std::string>>::type*,
const typename boost::disable_if<data::HasSerialize<std::string>>::type*,
const typename boost::disable_if<arma::is_arma_type<std::string>>::type*,
const typename boost::disable_if<std::is_same<std::string,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "string";
}
template<>
inline std::string GetPrintableType<bool>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<bool>>::type*,
const typename boost::disable_if<data::HasSerialize<bool>>::type*,
const typename boost::disable_if<arma::is_arma_type<bool>>::type*,
const typename boost::disable_if<std::is_same<bool,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "bool";
}
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& d,
const typename boost::enable_if<util::IsStdVector<T>>::type*,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "array of " + GetPrintableType<typename T::value_type>(d) + "s";
}
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& /* d */,
const typename boost::enable_if<arma::is_arma_type<T>>::type*,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
std::string type = "*mat.Dense";
if (std::is_same<typename T::elem_type, double>::value)
{
if (T::is_row || T::is_col)
type = "*mat.Dense (1d)";
}
else if (std::is_same<typename T::elem_type, size_t>::value)
{
type = "*mat.Dense (with ints)";
if (T::is_row || T::is_col)
type = "*mat.Dense (1d with ints)";
}
return type;
}
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& /* d */,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return "MatrixWithInfo";
}
template<typename T>
inline std::string GetPrintableType(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type*,
const typename boost::enable_if<data::HasSerialize<T>>::type*,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
return d.cppType + "Type";
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+151
View File
@@ -0,0 +1,151 @@
/**
* @file get_type.hpp
* @author Yasmine Dumouchel
*
* Template metaprogramming to return the string representation of the type
* for the Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GET_TYPE_HPP
#define MLPACK_BINDINGS_GO_GET_TYPE_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/param_data.hpp>
#include <mlpack/core/util/is_std_vector.hpp>
namespace mlpack {
namespace bindings {
namespace go {
template<typename T>
inline std::string GetType(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0)
{
return "unknown";
}
template<>
inline std::string GetType<int>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<int>>::type*,
const typename boost::disable_if<data::HasSerialize<int>>::type*,
const typename boost::disable_if<arma::is_arma_type<int>>::type*)
{
return "Int";
}
template<>
inline std::string GetType<float>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<float>>::type*,
const typename boost::disable_if<data::HasSerialize<float>>::type*,
const typename boost::disable_if<arma::is_arma_type<float>>::type*)
{
return "Float";
}
template<>
inline std::string GetType<double>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<double>>::type*,
const typename boost::disable_if<data::HasSerialize<double>>::type*,
const typename boost::disable_if<arma::is_arma_type<double>>::type*)
{
return "Double";
}
template<>
inline std::string GetType<std::string>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<std::string>>::type*,
const typename boost::disable_if<data::HasSerialize<std::string>>::type*,
const typename boost::disable_if<arma::is_arma_type<std::string>>::type*)
{
return "String";
}
template<>
inline std::string GetType<bool>(
const util::ParamData& /* d */,
const typename boost::disable_if<util::IsStdVector<bool>>::type*,
const typename boost::disable_if<data::HasSerialize<bool>>::type*,
const typename boost::disable_if<arma::is_arma_type<bool>>::type*)
{
return "Bool";
}
template<typename T>
inline std::string GetType(
const util::ParamData& d,
const typename boost::enable_if<util::IsStdVector<T>>::type* = 0)
{
return "Vec" + GetType<typename T::value_type>(d);
}
template<typename T>
inline std::string GetType(
const util::ParamData& /* d */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
std::string type = "";
if (std::is_same<typename T::elem_type, double>::value)
{
if (T::is_row)
type = "Row";
else if (T::is_col)
type = "Col";
else
type = "Mat";
}
else if (std::is_same<typename T::elem_type, size_t>::value)
{
if (T::is_row)
type = "Urow";
else if (T::is_col)
type = "Ucol";
else
type = "Umat";
}
return type;
}
template<typename T>
inline std::string GetType(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
return d.cppType + "*";
}
/**
* Print an option into a std::string. This should print a short, one-line
* representation of the object. The string will be stored in the output
* pointer.
*
* @param data Parameter data struct.
* @param input Unused parameter.
* @param output Output storage for the string.
*/
template<typename T>
void GetType(const util::ParamData& d,
const void* /* input */,
void* output)
{
*((std::string*) output) =
GetType<typename std::remove_pointer<T>::type>(d);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+131
View File
@@ -0,0 +1,131 @@
/**
* @file go_option.hpp
* @author Yasmine Dumouchel
*
* The Go option type.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GOLANG_GO_OPTION_HPP
#define MLPACK_BINDINGS_GOLANG_GO_OPTION_HPP
#include <mlpack/core/util/param_data.hpp>
#include "get_param.hpp"
#include "get_type.hpp"
#include "default_param.hpp"
#include "get_printable_param.hpp"
#include "print_defn_input.hpp"
#include "print_defn_output.hpp"
#include "print_doc.hpp"
#include "print_import_decl.hpp"
#include "print_input_processing.hpp"
#include "print_method_config.hpp"
#include "print_method_init.hpp"
#include "print_model_util.hpp"
#include "print_output_processing.hpp"
namespace mlpack {
namespace bindings {
namespace go {
// Defined in mlpack_main.hpp.
extern std::string programName;
/**
* The Go option class.
*/
template<typename T>
class GoOption
{
public:
/**
* Construct a GoOption object. When constructed, it will register itself
* with CLI. The testName parameter is not used and added for compatibility
* reasons.
*/
GoOption(const T defaultValue,
const std::string& identifier,
const std::string& description,
const std::string& alias,
const std::string& cppName,
const bool required = false,
const bool input = true,
const bool noTranspose = false,
const std::string& /*testName*/ = "")
{
// Create the ParamData object to give to CLI.
util::ParamData data;
data.desc = description;
data.name = identifier;
data.tname = TYPENAME(T);
data.alias = alias[0];
data.wasPassed = false;
data.noTranspose = noTranspose;
data.required = required;
data.input = input;
data.loaded = false;
// Only "verbose" and "copy_all_inputs" will be persistent.
if (identifier == "verbose" /*|| identifier == "copy_all_inputs"*/)
data.persistent = true;
else
data.persistent = false;
data.cppType = cppName;
data.value = boost::any(defaultValue);
// Restore the parameters for this program.
if (identifier != "verbose" /*&& identifier != "copy_all_inputs"*/)
CLI::RestoreSettings(programName, false);
// Set the function pointers that we'll need. All of these function
// pointers will be used by both the program that generates the .cpp,
// the .h, and the .go binding files.
CLI::GetSingleton().functionMap[data.tname]["GetParam"] = &GetParam<T>;
CLI::GetSingleton().functionMap[data.tname]["GetPrintableParam"] =
&GetPrintableParam<T>;
CLI::GetSingleton().functionMap[data.tname]["DefaultParam"] =
&DefaultParam<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintModelUtilCPP"] =
&PrintModelUtilCPP<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintModelUtilH"] =
&PrintModelUtilH<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintModelUtilGo"] =
&PrintModelUtilGo<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintDefnInput"] =
&PrintDefnInput<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintDefnOutput"] =
&PrintDefnOutput<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintDoc"] = &PrintDoc<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintOutputProcessing"] =
&PrintOutputProcessing<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintMethodConfig"] =
&PrintMethodConfig<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintMethodInit"] =
&PrintMethodInit<T>;
CLI::GetSingleton().functionMap[data.tname]["ImportDecl"] =
&ImportDecl<T>;
CLI::GetSingleton().functionMap[data.tname]["PrintInputProcessing"] =
&PrintInputProcessing<T>;
CLI::GetSingleton().functionMap[data.tname]["GetType"] = &GetType<T>;
// Add the ParamData object, then store. This is necessary because we may
// import more than one .so that uses CLI, so we have to keep the options
// separate. programName is a global variable from mlpack_main.hpp.
CLI::Add(std::move(data));
if (identifier != "verbose" /*&& identifier != "copy_all_inputs"*/)
CLI::StoreSettings(programName);
CLI::ClearSettings();
}
};
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+403
View File
@@ -0,0 +1,403 @@
package mlpack
/*
#cgo CFLAGS: -I. -I/capi -g -Wall -Wno-unused-variable
#cgo LDFLAGS: -L. -lgo_util
#include <stdlib.h>
#include <stdio.h>
#include <capi/cli_util.h>
#include <capi/arma_util.h>
*/
import "C"
import (
"runtime"
"unsafe"
"gonum.org/v1/gonum/mat"
)
type mlpackArma struct {
mem unsafe.Pointer
}
// A Tuple containing `float64` data (data) along with a boolean array
// (Categories) indicating which dimensions are categorical (represented by
// `true`) and which are numeric (represented by `false`). The number of
// elements in the boolean array should be the same as the dimensionality of
// the data matrix. It is expected that each row of the matrix corresponds to a
// single data point when calling mlpack bindings.
type MatrixWithInfo struct {
Categories []bool
Data *mat.Dense
}
// A function used for initializing MatrixWithInfo Tuple.
func DataAndInfo() *MatrixWithInfo {
return &MatrixWithInfo {
Categories: nil,
Data: nil,
}
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrMat(identifier string) {
m.mem = C.mlpackArmaPtrMat(C.CString(identifier))
runtime.KeepAlive(m)
}
// Function free is used to free memory when the object leaves Go's scope.
func freeMat(m *mlpackArma) {
C.free(unsafe.Pointer(m.mem))
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrUmat(identifier string) {
m.mem = C.mlpackArmaPtrUmat(C.CString(identifier))
runtime.KeepAlive(m)
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrRow(identifier string) {
m.mem = C.mlpackArmaPtrRow(C.CString(identifier))
runtime.KeepAlive(m)
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrUrow(identifier string) {
m.mem = C.mlpackArmaPtrUrow(C.CString(identifier))
runtime.KeepAlive(m)
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrCol(identifier string) {
m.mem = C.mlpackArmaPtrCol(C.CString(identifier))
runtime.KeepAlive(m)
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrUcol(identifier string) {
m.mem = C.mlpackArmaPtrUcol(C.CString(identifier))
runtime.KeepAlive(m)
}
// Allocates a C memory Pointer via cgo and registers the finalizer
// in order to free the C memory once the input has been registered in Go.
func (m *mlpackArma) allocArmaPtrMatWithInfo(identifier string) {
m.mem = C.mlpackArmaPtrMatWithInfoPtr(C.CString(identifier))
runtime.KeepAlive(m)
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func gonumToArmaMat(identifier string, m *mat.Dense) {
// Get the number of elements in the Armadillo column.
r, c := m.Dims()
blas64General := m.RawMatrix()
data := blas64General.Data
// Pass pointer of the underlying matrix to mlpack.
ptr := unsafe.Pointer(&data[0])
C.mlpackToArmaMat(C.CString(identifier), (*C.double)(ptr), C.size_t(c), C.size_t(r))
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func gonumToArmaUmat(identifier string, m *mat.Dense) {
// Get the number of elements in the Armadillo column.
r, c := m.Dims()
blas64General := m.RawMatrix()
data := blas64General.Data
// Pass pointer of the underlying matrix to mlpack.
ptr := unsafe.Pointer(&data[0])
C.mlpackToArmaUmat(C.CString(identifier), (*C.double)(ptr), C.size_t(c), C.size_t(r))
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func gonumToArmaRow(identifier string, m *mat.Dense) {
// Get the number of elements in the Armadillo column.
e, err := m.Dims()
if (err != 1 && e != 1){
panic("Given matrix must have a single column")
}
// Transpose if Column vector is given
if e == 1 {
m = mat.DenseCopyOf(m.T())
e = err
}
blas64General := m.RawMatrix()
data := blas64General.Data
// Pass pointer of the underlying matrix to mlpack.
ptr := unsafe.Pointer(&data[0])
C.mlpackToArmaRow(C.CString(identifier), (*C.double)(ptr), C.size_t(e))
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func gonumToArmaUrow(identifier string, m *mat.Dense) {
// Get the number of elements in the Armadillo column.
e, err := m.Dims()
if (err != 1 && e != 1){
panic("Given matrix must have a single column")
}
// Transpose if Column vector is given
if e == 1 {
m = mat.DenseCopyOf(m.T())
e = err
}
blas64General := m.RawMatrix()
data := blas64General.Data
// Pass pointer of the underlying matrix to mlpack.
ptr := unsafe.Pointer(&data[0])
C.mlpackToArmaUrow(C.CString(identifier), (*C.double)(ptr), C.size_t(e))
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func gonumToArmaCol(identifier string, m *mat.Dense) {
// Get the number of elements in the Armadillo column.
err, e := m.Dims()
if (err != 1 && e != 1){
panic("Given matrix must have a single row")
}
// Transpose if Row vector is given
if e == 1 {
m = mat.DenseCopyOf(m.T())
e = err
}
blas64General := m.RawMatrix()
data := blas64General.Data
// Pass pointer of the underlying matrix to mlpack.
ptr := unsafe.Pointer(&data[0])
C.mlpackToArmaCol(C.CString(identifier), (*C.double)(ptr), C.size_t(e))
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func gonumToArmaUcol(identifier string, m *mat.Dense) {
// Get the number of elements in the Armadillo column.
err, e := m.Dims()
if (err != 1 && e != 1){
panic("Given matrix must have a single row")
}
// Transpose if Row vector is given
if e == 1 {
m = mat.DenseCopyOf(m.T())
e = err
}
blas64General := m.RawMatrix()
data := blas64General.Data
// Pass pointer of the underlying matrix to mlpack.
ptr := unsafe.Pointer(&data[0])
C.mlpackToArmaUcol(C.CString(identifier), (*C.double)(ptr), C.size_t(e))
}
// GonumToArmaMatWithInfo passes a gonum matrix with info to C by
// using it's gonums underlying blas64.
func gonumToArmaMatWithInfo(identifier string, m *MatrixWithInfo) {
// Get the number of elements in the Armadillo column.
r, c := m.Data.Dims()
blas64General := m.Data.RawMatrix()
DataAndInfo := blas64General.Data
boolarray := m.Categories
// Pass pointer of the underlying matrix to mlpack.
boolptr := unsafe.Pointer(&boolarray[0])
matptr := unsafe.Pointer(&DataAndInfo[0])
C.mlpackToArmaMatWithInfo(C.CString(identifier), (*C.bool)(boolptr),
(*C.double)(matptr), C.size_t(c), C.size_t(r))
}
// ArmaToGonum returns a gonum matrix based on the memory pointer
// of an armadillo matrix.
func (m *mlpackArma) armaToGonumMat(identifier string) *mat.Dense {
// Get the number of elements in the Armadillo row.
c := int(C.mlpackNumRowMat(C.CString(identifier)))
r := int(C.mlpackNumColMat(C.CString(identifier)))
e := int(C.mlpackNumElemMat(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrMat(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
if array != nil {
data := array[:e]
// Initialize result matrix.
output := mat.NewDense(r, c, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
// ArmaToGonum returns a gonum matrix based on the memory pointer
// of an armadillo matrix.
func (m *mlpackArma) armaToGonumArray(identifier string) (int, int, []float64){
// Get the number of elements in the Armadillo row.
c := int(C.mlpackNumRowMat(C.CString(identifier)))
r := int(C.mlpackNumColMat(C.CString(identifier)))
e := int(C.mlpackNumElemMat(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrMat(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
data := array[:e]
return r, c, data
}
// ArmaToGonum returns a gonum matrix based on the memory pointer
// of an armadillo matrix.
func (m *mlpackArma) armaToGonumUmat(identifier string) *mat.Dense {
// Get the number of elements in the Armadillo row.
c := int(C.mlpackNumRowUmat(C.CString(identifier)))
r := int(C.mlpackNumColUmat(C.CString(identifier)))
e := int(C.mlpackNumElemUmat(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrUmat(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
if array != nil {
data := array[:e]
// Initialize result matrix.
output := mat.NewDense(r, c, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
// ArmaRowToGonum returns a gonum vector based on the memory pointer
// of the underlying armadillo object.
func (m *mlpackArma) armaToGonumRow(identifier string) *mat.Dense{
// Get the number of elements in the Armadillo row.
e := int(C.mlpackNumElemRow(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrRow(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
if array != nil {
data := array[:e]
// Initialize result matrix.
output := mat.NewDense(e, 1, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
// ArmaRowToGonum returns a gonum vector based on the memory pointer
// of the underlying armadillo object.
func (m *mlpackArma) armaToGonumUrow(identifier string) *mat.Dense {
// Get the number of elements in the Armadillo row.
e := int(C.mlpackNumElemUrow(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrUrow(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
if array != nil {
data := array[:e]
// Initialize result matrix.
output := mat.NewDense(e, 1, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func (m *mlpackArma) armaToGonumCol(identifier string) *mat.Dense {
// Get the number of elements in the Armadillo column.
e := int(C.mlpackNumElemCol(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrCol(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
if array != nil {
data := array[:e]
// Initialize result matrix.
output := mat.NewDense(1, e, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func (m *mlpackArma) armaToGonumUcol(identifier string) *mat.Dense {
// Get the number of elements in the Armadillo column.
e := int(C.mlpackNumElemUcol(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrUcol(identifier)
// Convert pointer to slice of data, to then pass it to a gonum matrix.
array := (*[1<<30 - 1]float64)(m.mem)
if array != nil {
data := array[:e]
// Initialize result matrix.
output := mat.NewDense(1, e, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
// Passes a Gonum matrix to C by using the underlying data from the Gonum matrix.
func (m *mlpackArma) armaToGonumMatWithInfo(identifier string) *mat.Dense {
// Get number of rows, columns, and elements of the Armadillo matrix.
c := int(C.mlpackArmaMatWithInfoRows(C.CString(identifier)))
r := int(C.mlpackArmaMatWithInfoCols(C.CString(identifier)))
e := int(C.mlpackArmaMatWithInfoElements(C.CString(identifier)))
// Allocate Go memory pointer to the armadillo matrix.
m.allocArmaPtrMatWithInfo(identifier)
matarray := (*[1<<30 - 1]float64)(m.mem)
if matarray != nil {
data := matarray[:e]
// Initialize result matrix.
output := mat.NewDense(r, c, data)
// Return gonum vector.
return output
}
return mat.NewDense(1, 1, nil)
}
@@ -0,0 +1,353 @@
/**
* @file arma_util.cpp
* @author Yasmine Dumouchel
* @author Yashwant Singh
*
* Utility function for Go to pass gonum object to an Armadillo Object and
* vice versa.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/bindings/go/mlpack/capi/arma_util.h>
#include "arma_util.hpp"
#include "cli_util.hpp"
#include <mlpack/core/util/cli.hpp>
namespace mlpack {
namespace util {
extern "C" {
/**
* Pass Gonum Dense pointer and wrap an Armadillo mat around it.
*/
void mlpackToArmaMat(const char* identifier, double* mat,
const size_t row, const size_t col)
{
// Advanced constructor.
arma::mat m(mat, row, col, false, true);
// Set input parameter with corresponding matrix in CLI.
SetParam(identifier, m);
}
/**
* Pass Gonum Dense pointer and wrap an Armadillo mat around it.
*/
void mlpackToArmaUmat(const char* identifier, double* mat,
const size_t row, const size_t col)
{
// Advanced constructor.
arma::mat m(mat, row, col, false, true);
// Advanced constructor
arma::Mat<size_t> matr = arma::conv_to<arma::Mat<size_t>>::from(m);
// Set input parameter with corresponding matrix in CLI.
SetParam(identifier, matr);
}
/**
* Pass Gonum VecDense pointer and wrap an Armadillo rowvec around it.
*/
void mlpackToArmaRow(const char* identifier, double* rowvec, const size_t elem)
{
// Advanced constructor.
arma::rowvec m(rowvec, elem, false, true);
// Set input parameter with corresponding row in CLI.
SetParam(identifier, m);
}
/**
* Pass Gonum VecDense pointer and wrap an Armadillo rowvec around it.
*/
void mlpackToArmaUrow(const char* identifier, double* rowvec, const size_t elem)
{
// Advanced constructor.
arma::rowvec m(rowvec, elem, false, true);
// Advanced constructor
arma::Row<size_t> matr = arma::conv_to<arma::Row<size_t>>::from(m);
// Set input parameter with corresponding row in CLI.
SetParam(identifier, matr);
}
/**
* Pass Gonum VecDense pointer and wrap an Armadillo colvec around it.
*/
void mlpackToArmaCol(const char* identifier, double* colvec, const size_t elem)
{
// Advanced constructor.
arma::colvec m(colvec, elem, false, true);
// Set input parameter with corresponding column in CLI.
SetParam(identifier, m);
}
/**
* Pass Gonum VecDense pointer and wrap an Armadillo colvec around it.
*/
void mlpackToArmaUcol(const char* identifier, double* colvec, const size_t elem)
{
// Advanced constructor.
arma::colvec m(colvec, elem, false, true);
// Advanced constructor
arma::Col<size_t> matr = arma::conv_to<arma::Col<size_t>>::from(m);
// Set input parameter with corresponding column in CLI.
SetParam(identifier, matr);
}
/**
* Return the memory pointer of an Armadillo mat object.
*/
void* mlpackArmaPtrMat(const char* identifier)
{
arma::mat& output = CLI::GetParam<arma::mat>(identifier);
if (output.is_empty())
{
return NULL;
}
void* ptr = GetMemory(output);
return ptr;
}
/**
* Return the memory pointer of an Armadillo umat object.
*/
void* mlpackArmaPtrUmat(const char* identifier)
{
arma::Mat<size_t>& m = CLI::GetParam<arma::Mat<size_t>>(identifier);
// Advanced constructor.
arma::Mat<double> output(arma::conv_to<arma::Mat<double>>::from(m).memptr(),
m.n_rows, m.n_cols, false, true);
if (output.is_empty())
{
return NULL;
}
void* ptr = GetMemory(output);
return ptr;
}
/**
* Return the memory pointer of an Armadillo row object.
*/
void* mlpackArmaPtrRow(const char* identifier)
{
arma::Row<double>& output = CLI::GetParam<arma::Row<double>>(identifier);
if (output.is_empty())
{
return NULL;
}
void* ptr = GetMemory(output);
return ptr;
}
/**
* Return the memory pointer of an Armadillo urow object.
*/
void* mlpackArmaPtrUrow(const char* identifier)
{
arma::Row<size_t>& m = CLI::GetParam<arma::Row<size_t>>(identifier);
// Advanced constructor.
arma::Row<double> output(arma::conv_to<arma::Row<double>>::from(m).memptr(),
m.n_elem, false, true);
if (output.is_empty())
{
return NULL;
}
void* ptr = GetMemory(output);
return ptr;
}
/**
* Return the memory pointer of an Armadillo col object.
*/
void* mlpackArmaPtrCol(const char* identifier)
{
arma::Col<double>& output = CLI::GetParam<arma::Col<double>>(identifier);
if (output.is_empty())
{
return NULL;
}
void* ptr = GetMemory(output);
return ptr;
}
/**
* Return the memory pointer of an Armadillo ucol object.
*/
void* mlpackArmaPtrUcol(const char* identifier)
{
arma::Col<size_t>& m = CLI::GetParam<arma::Col<size_t>>(identifier);
// Advanced constructor.
arma::Col<double> output(arma::conv_to<arma::Col<double>>::from(m).memptr(),
m.n_elem, false, true);
if (output.is_empty())
{
return NULL;
}
void* ptr = GetMemory(output);
return ptr;
}
/**
* Return the number of rows in a Armadillo mat.
*/
int mlpackNumRowMat(const char* identifier)
{
return CLI::GetParam<arma::mat>(identifier).n_rows;
}
/**
* Return the number of columns in an Armadillo mat.
*/
int mlpackNumColMat(const char* identifier)
{
return CLI::GetParam<arma::mat>(identifier).n_cols;
}
/**
* Return the number of elements in an Armadillo mat.
*/
int mlpackNumElemMat(const char* identifier)
{
return CLI::GetParam<arma::mat>(identifier).n_elem;
}
/**
* Return the number of rows in an Armadillo umat.
*/
int mlpackNumRowUmat(const char* identifier)
{
return CLI::GetParam<arma::Mat<size_t>>(identifier).n_rows;
}
/**
* Return the number of columns in an Armadillo umat.
*/
int mlpackNumColUmat(const char* identifier)
{
return CLI::GetParam<arma::Mat<size_t>>(identifier).n_cols;
}
/**
* Return the number of elements in an Armadillo umat.
*/
int mlpackNumElemUmat(const char* identifier)
{
return CLI::GetParam<arma::Mat<size_t>>(identifier).n_elem;
}
/**
* Return the number of elements in an Armadillo row.
*/
int mlpackNumElemRow(const char* identifier)
{
return CLI::GetParam<arma::Row<double>>(identifier).n_elem;
}
/**
* Return the number of elements in an Armadillo urow.
*/
int mlpackNumElemUrow(const char* identifier)
{
return CLI::GetParam<arma::Row<size_t>>(identifier).n_elem;
}
/**
* Return the number of elements in an Armadillo col.
*/
int mlpackNumElemCol(const char* identifier)
{
return CLI::GetParam<arma::Col<double>>(identifier).n_elem;
}
/**
* Return the number of elements in an Armadillo ucol.
*/
int mlpackNumElemUcol(const char* identifier)
{
return CLI::GetParam<arma::Col<size_t>>(identifier).n_elem;
}
/**
* Call CLI::SetParam<std::tuple<data::DatasetInfo, arma::mat>>().
*/
void mlpackToArmaMatWithInfo(const char* identifier,
const bool* dimensions,
double* memptr,
const size_t rows,
const size_t cols)
{
data::DatasetInfo d(rows);
for (size_t i = 0; i < d.Dimensionality(); ++i)
{
d.Type(i) = (dimensions[i]) ? data::Datatype::categorical :
data::Datatype::numeric;
}
arma::mat m(memptr, rows, cols, false, true);
std::get<0>(CLI::GetParam<std::tuple<data::DatasetInfo, arma::mat>>(
identifier)) = std::move(d);
std::get<1>(CLI::GetParam<std::tuple<data::DatasetInfo, arma::mat>>(
identifier)) = std::move(m);
CLI::SetPassed(identifier);
}
/**
* Get the number of elements in a matrix with DatasetInfo parameter.
*/
int mlpackArmaMatWithInfoElements(const char* identifier)
{
typedef std::tuple<data::DatasetInfo, arma::mat> TupleType;
return std::get<1>(CLI::GetParam<TupleType>(identifier)).n_elem;
}
/**
* Get the number of rows in a matrix with DatasetInfo parameter.
*/
int mlpackArmaMatWithInfoRows(const char* identifier)
{
typedef std::tuple<data::DatasetInfo, arma::mat> TupleType;
return std::get<1>(CLI::GetParam<TupleType>(identifier)).n_rows;
}
/**
* Get the number of columns in a matrix with DatasetInfo parameter.
*/
int mlpackArmaMatWithInfoCols(const char* identifier)
{
typedef std::tuple<data::DatasetInfo, arma::mat> TupleType;
return std::get<1>(CLI::GetParam<TupleType>(identifier)).n_cols;
}
/**
* Get a pointer to the memory of the matrix. The calling function is expected
* to own the memory.
*/
void* mlpackArmaPtrMatWithInfoPtr(const char* identifier)
{
typedef std::tuple<data::DatasetInfo, arma::mat> TupleType;
arma::mat& m = std::get<1>(CLI::GetParam<TupleType>(identifier));
if (m.is_empty())
{
return NULL;
}
void* ptr = GetMemory(m);
return ptr;
}
} // extern "C"
} // namespace util
} // namespace mlpack
@@ -0,0 +1,182 @@
/**
* @file arma_util.h
* @author Yasmine Dumouchl
* @author Yashwant Singh
*
* Header file for cgo to call C functions from go.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_MLPACK_ARMAUTIL_H
#define MLPACK_BINDINGS_GO_MLPACK_ARMAUTIL_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/**
* Pass Gonum Dense poconst size_t er and wrap an Armadillo mat around it.
*/
void mlpackToArmaMat(const char* identifier,
double* mat,
const size_t row,
const size_t col);
/**
* Pass Gonum Dense poconst size_t er and wrap an Armadillo mat around it.
*/
void mlpackToArmaUmat(const char* identifier,
double* mat,
const size_t row,
const size_t col);
/**
* Pass Gonum VecDense poconst size_t er and wrap an Armadillo rowvec around it.
*/
void mlpackToArmaRow(const char* identifier,
double* rowvec,
const size_t elem);
/**
* Pass Gonum VecDense poconst size_t er and wrap an Armadillo rowvec around it.
*/
void mlpackToArmaUrow(const char* identifier,
double* rowvec,
const size_t elem);
/**
* Pass Gonum VecDense poconst size_t er and wrap an Armadillo colvec around it.
*/
void mlpackToArmaCol(const char* identifier,
double* colvec,
const size_t elem);
/**
* Pass Gonum VecDense poconst size_t er and wrap an Armadillo colvec around it.
*/
void mlpackToArmaUcol(const char* identifier,
double* colvec,
const size_t elem);
/**
* Return the memory poconst size_t er of an Armadillo mat object.
*/
void* mlpackArmaPtrMat(const char* identifier);
/**
* Return the memory poconst size_t er of an Armadillo umat object.
*/
void* mlpackArmaPtrUmat(const char* identifier);
/**
* Return the memory poconst size_t er of an Armadillo row object.
*/
void* mlpackArmaPtrRow(const char* identifier);
/**
* Return the memory poconst size_t er of an Armadillo urow object.
*/
void* mlpackArmaPtrUrow(const char* identifier);
/**
* Return the memory poconst size_t er of an Armadillo col object.
*/
void* mlpackArmaPtrCol(const char* identifier);
/**
* Return the memory poconst size_t er of an Armadillo ucol object.
*/
void* mlpackArmaPtrUcol(const char* identifier);
/**
* Return the number of rows in a Armadillo mat.
*/
int mlpackNumRowMat(const char* identifier);
/**
* Return the number of columns in an Armadillo mat.
*/
int mlpackNumColMat(const char* identifier);
/**
* Return the number of elements in an Armadillo mat.
*/
int mlpackNumElemMat(const char* identifier);
/**
* Return the number of rows in an Armadillo umat.
*/
int mlpackNumRowUmat(const char* identifier);
/**
* Return the number of columns in an Armadillo umat.
*/
int mlpackNumColUmat(const char* identifier);
/**
* Return the number of elements in an Armadillo umat.
*/
int mlpackNumElemUmat(const char* identifier);
/**
* Return the number of elements in an Armadillo row.
*/
int mlpackNumElemRow(const char* identifier);
/**
* Return the number of elements in an Armadillo urow.
*/
int mlpackNumElemUrow(const char* identifier);
/**
* Return the number of elements in an Armadillo col.
*/
int mlpackNumElemCol(const char* identifier);
/**
* Return the number of elements in an Armadillo ucol.
*/
int mlpackNumElemUcol(const char* identifier);
/**
* Call CLI::SetParam<std::tuple<data::DatasetInfo, arma::mat>>().
*/
void mlpackToArmaMatWithInfo(const char* identifier,
const bool* dimensions,
double* memptr,
const size_t rows,
const size_t cols);
/**
* Get the number of elements in a matrix with DatasetInfo parameter.
*/
int mlpackArmaMatWithInfoElements(const char* identifier);
/**
* Get the number of rows in a matrix with DatasetInfo parameter.
*/
int mlpackArmaMatWithInfoRows(const char* identifier);
/**
* Get the number of columns in a matrix with DatasetInfo parameter.
*/
int mlpackArmaMatWithInfoCols(const char* identifier);
/**
* Get a poconst size_t er to the memory of the matrix. The calling function is expected
* to own the memory.
*/
void* mlpackArmaPtrMatWithInfoPtr(const char* identifier);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif
@@ -0,0 +1,71 @@
/**
* @file arma_util.hpp
* @author Ryan Curtin
*
* Utility function for Go to get memory pointer of an Armadillo Object.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_GONUM_ARMA_UTIL_HPP
#define MLPACK_BINDINGS_GO_GONUM_ARMA_UTIL_HPP
// Include Armadillo via mlpack.
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core.hpp>
namespace mlpack {
/**
* Set the memory state of the given Armadillo object.
*/
template<typename T>
void SetMemState(T& t, int state)
{
const_cast<arma::uhword&>(t.mem_state) = state;
}
/**
* Get the memory state of the given Armadillo object.
*/
template<typename T>
size_t GetMemState(T& t)
{
// Fake the memory state if we are using preallocated memory---since we will
// end up copying that memory, NumPy can own it.
if (t.mem && t.n_elem <= arma::arma_config::mat_prealloc)
return 0;
return (size_t) t.mem_state;
}
/**
* Return the matrix's allocated memory pointer, unless the matrix is using its
* internal preallocated memory, in which case we copy that and return a
* pointer to the memory we just made.
*/
template<typename T>
inline typename T::elem_type* GetMemory(T& m)
{
if (m.mem && m.n_elem <= arma::arma_config::mat_prealloc)
{
// We need to allocate new memory.
typename T::elem_type* mem =
arma::memory::acquire<typename T::elem_type>(m.n_elem);
arma::arrayops::copy(mem, m.memptr(), m.n_elem);
return mem;
}
else
{
arma::access::rw(m.mem_state) = 1;
return m.memptr();
}
}
} // namespace mlpack
#endif
@@ -0,0 +1,258 @@
/**
* @file cli_util.cpp
* @author Yasmine Dumouchel
* @author Yashwant Singh
*
* Utility function for Go to set and get parameters to and from the CLI.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/bindings/go/mlpack/capi/cli_util.h>
#include "cli_util.hpp"
#include <mlpack/core/util/cli.hpp>
namespace mlpack {
extern "C" {
/**
* Set the double parameter to the given value.
*/
void mlpackSetParamDouble(const char* identifier, double value)
{
util::SetParam(identifier, value);
}
/**
* Set the int parameter to the given value.
*/
void mlpackSetParamInt(const char* identifier, int value)
{
util::SetParam(identifier, value);
}
/**
* Set the float parameter to the given value.
*/
void mlpackSetParamFloat(const char* identifier, float value)
{
util::SetParam(identifier, value);
}
/**
* Set the bool parameter to the given value.
*/
void mlpackSetParamBool(const char* identifier, bool value)
{
util::SetParam(identifier, value);
}
/**
* Set the string parameter to the given value.
*/
void mlpackSetParamString(const char* identifier, const char* value)
{
std::string val;
val.assign(value);
util::SetParam(identifier, val);
}
/**
* Set the int vector parameter to the given value.
*/
void mlpackSetParamVectorInt(const char* identifier,
const long long* ints,
const size_t length)
{
// Create a std::vector<int> object; unfortunately this requires copying the
// vector elements.
std::vector<int> vec(length);
for (size_t i = 0; i < length; ++i)
vec[i] = ints[i];
CLI::GetParam<std::vector<int>>(identifier) = std::move(vec);
CLI::SetPassed(identifier);
}
/**
* Call CLI::SetParam<std::vector<std::string>>() to set the length.
*/
void mlpackSetParamVectorStrLen(const char* identifier,
const size_t length)
{
CLI::GetParam<std::vector<std::string>>(identifier).clear();
CLI::GetParam<std::vector<std::string>>(identifier).resize(length);
CLI::SetPassed(identifier);
}
/**
* Set the string vector parameter to the given value.
*/
void mlpackSetParamVectorStr(const char* identifier,
const char* str,
const size_t element)
{
CLI::GetParam<std::vector<std::string>>(identifier)[element] =
std::string(str);
}
/**
* Set the parameter to the given value, given that the type is a pointer.
*/
void mlpackSetParamPtr(const char* identifier,
const double* ptr)
{
util::SetParamPtr(identifier, ptr);
}
/**
* Check if CLI has a specified parameter.
*/
bool mlpackHasParam(const char* identifier)
{
return CLI::HasParam(identifier);
}
/**
* Get the string parameter associated with specified identifier.
*/
const char* mlpackGetParamString(const char* identifier)
{
std::string val = CLI::GetParam<std::string>(identifier);
char* cstr = const_cast<char*>(val.c_str());
return cstr;
}
/**
* Get the double parameter associated with specified identifier.
*/
double mlpackGetParamDouble(const char* identifier)
{
return CLI::GetParam<double>(identifier);
}
/**
* Get the int parameter associated with specified identifier.
*/
int mlpackGetParamInt(const char* identifier)
{
return CLI::GetParam<int>(identifier);
}
/**
* Get the bool parameter associated with specified identifier.
*/
bool mlpackGetParamBool(const char* identifier)
{
return CLI::GetParam<bool>(identifier);
}
/**
* Get the vector<int> parameter associated with specified identifier.
*/
void* mlpackGetVecIntPtr(const char* identifier)
{
const size_t size = mlpackVecIntSize(identifier);
int64_t* ints = new int64_t[size];
for (size_t i = 0; i < size; i++)
ints[i] = CLI::GetParam<std::vector<int>>(identifier)[i];
return ints;
}
/**
* Get the vector<string> parameter associated with specified identifier.
*/
const char* mlpackGetVecStringPtr(const char* identifier, const size_t i)
{
return const_cast<char*>(CLI::GetParam<std::vector<std::string>>(
identifier)[i].c_str());
}
/**
* Get the vector<int> parameter's size.
*/
int mlpackVecIntSize(const char* identifier)
{
return CLI::GetParam<std::vector<int>>(identifier).size();
}
/**
* Get the vector<string> parameter's size.
*/
int mlpackVecStringSize(const char* identifier)
{
return CLI::GetParam<std::vector<std::string>>(identifier).size();
}
/**
* Set parameter as passed.
*/
void mlpackSetPassed(const char* name)
{
CLI::SetPassed(name);
}
/**
* Reset the status of all timers.
*/
void mlpackResetTimers()
{
CLI::GetSingleton().timer.Reset();
}
/**
* Enable timing.
*/
void mlpackEnableTimers()
{
Timer::EnableTiming();
}
/**
* Disable backtraces.
*/
void mlpackDisableBacktrace()
{
Log::Fatal.backtrace = false;
}
/**
* Turn verbose output on.
*/
void mlpackEnableVerbose()
{
Log::Info.ignoreInput = false;
}
/**
* Turn verbose output off.
*/
void mlpackDisableVerbose()
{
Log::Info.ignoreInput = true;
}
/**
* Clear settings.
*/
void mlpackClearSettings()
{
CLI::ClearSettings();
}
/**
* Restore Settings.
*/
void mlpackRestoreSettings(const char* name)
{
CLI::RestoreSettings(name);
}
} // extern C
} // namespace mlpack
@@ -0,0 +1,164 @@
/**
* @file cli_util.h
* @author Yasmine Dumouchel
* @author Yashwant Singh
*
* Header file for cgo to call C functions from go.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_MLPACK_CLI_UTIL_H
#define MLPACK_BINDINGS_GO_MLPACK_CLI_UTIL_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/**
* Set the double parameter to the given value.
*/
void mlpackSetParamDouble(const char* identifier, double value);
/**
* Set the int parameter to the given value.
*/
void mlpackSetParamInt(const char* identifier, int value);
/**
* Set the float parameter to the given value.
*/
void mlpackSetParamFloat(const char* identifier, float value);
/**
* Set the bool parameter to the given value.
*/
void mlpackSetParamBool(const char* identifier, bool value);
/**
* Set the string parameter to the given value.
*/
void mlpackSetParamString(const char* identifier, const char* value);
/**
* Set the parameter to the given value, given that the type is a pointer.
*/
void mlpackSetParamPtr(const char* identifier,
const double* ptr);
/**
* Set the int vector parameter to the given value.
*/
void mlpackSetParamVectorInt(const char* identifier,
const long long* ints,
const size_t length);
/**
* Set the string vector parameter to the given value.
*/
void mlpackSetParamVectorStr(const char* identifier,
const char* str,
const size_t element);
/**
* Call CLI::SetParam<std::vector<std::string>>() to set the length.
*/
void mlpackSetParamVectorStrLen(const char* identifier,
const size_t length);
/**
* Check if CLI has a specified parameter.
*/
bool mlpackHasParam(const char* identifier);
/**
* Get the string parameter associated with specified identifier.
*/
const char* mlpackGetParamString(const char* identifier);
/**
* Get the double parameter associated with specified identifier.
*/
double mlpackGetParamDouble(const char* identifier);
/**
* Get the int parameter associated with specified identifier.
*/
int mlpackGetParamInt(const char* identifier);
/**
* Get the bool parameter associated with specified identifier.
*/
bool mlpackGetParamBool(const char* identifier);
/**
* Get the vector<int> parameter associated with specified identifier.
*/
void* mlpackGetVecIntPtr(const char* identifier);
/**
* Get the vector<string> parameter associated with specified identifier.
*/
const char* mlpackGetVecStringPtr(const char* identifier, const size_t i);
/**
* Get the vector<int> parameter's size.
*/
int mlpackVecIntSize(const char* identifier);
/**
* Get the vector<string> parameter's size.
*/
int mlpackVecStringSize(const char* identifier);
/**
* Set parameter as passed.
*/
void mlpackSetPassed(const char* name);
/**
* Reset the status of all timers.
*/
void mlpackResetTimers();
/**
* Enable timing.
*/
void mlpackEnableTimers();
/**
* Disable backtraces.
*/
void mlpackDisableBacktrace();
/**
* Turn verbose output on.
*/
void mlpackEnableVerbose();
/**
* Turn verbose output off.
*/
void mlpackDisableVerbose();
/**
* Clear settings.
*/
void mlpackClearSettings();
/**
* Restore Settings.
*/
void mlpackRestoreSettings(const char* name);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif
@@ -0,0 +1,102 @@
/**
* @file cli_util.hpp
* @author Yasmine Dumouchel
* @author Yashwant Singh
*
* Utility function for Go to set and get parameters to and from the CLI.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_CLI_UTIL_HPP
#define MLPACK_BINDINGS_GO_CLI_UTIL_HPP
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/data/dataset_mapper.hpp>
namespace mlpack {
namespace util {
/**
* Set the parameter to the given value.
*
* @param identifier Name of parameter.
* @param value Value to set parameter to.
*/
template<typename T>
inline void SetParam(const std::string& identifier, T& value)
{
CLI::GetParam<T>(identifier) = std::move(value);
}
/**
* Set the parameter to the given value, given that the type is a pointer.
*
* @param identifier Name of parameter.
* @param value Value to set parameter to.
* @param copy Whether or not the object should be copied.
*/
template<typename T>
inline void SetParamPtr(const std::string& identifier,
T* value)
{
CLI::GetParam<T*>(identifier) = value;
}
/**
* Return a pointer. This function exists to work around Cython's seeming lack
* of support for template pointer types.
*/
template<typename T>
T* GetParamPtr(const std::string& paramName)
{
return CLI::GetParam<T*>(paramName);
}
/**
* Turn verbose output on.
*/
inline void EnableVerbose()
{
Log::Info.ignoreInput = false;
}
/**
* Turn verbose output off.
*/
inline void DisableVerbose()
{
Log::Info.ignoreInput = true;
}
/**
* Disable backtraces.
*/
inline void DisableBacktrace()
{
Log::Fatal.backtrace = false;
}
/**
* Reset the status of all timers.
*/
inline void ResetTimers()
{
// Just get a new object---removes all old timers.
CLI::GetSingleton().timer.Reset();
}
/**
* Enable timing.
*/
inline void EnableTimers()
{
Timer::EnableTiming();
}
} // namespace util
} // namespace mlpack
#endif
+140
View File
@@ -0,0 +1,140 @@
package mlpack
/*
#cgo CFLAGS: -I. -I/capi -g -Wall
#cgo LDFLAGS: -L${SRCDIR} -Wl,-rpath,${SRCDIR} -lgo_util
#include <capi/cli_util.h>
*/
import "C"
import (
"runtime"
"unsafe"
)
func hasParam(identifier string) bool {
return bool((C.mlpackHasParam(C.CString(identifier))))
}
func setPassed(identifier string) {
C.mlpackSetPassed(C.CString(identifier))
}
func setParamDouble(identifier string, value float64) {
C.mlpackSetParamDouble(C.CString(identifier), C.double(value))
}
func setParamInt(identifier string, value int) {
C.mlpackSetParamInt(C.CString(identifier), C.int(value))
}
func setParamFloat(identifier string, value float64) {
C.mlpackSetParamFloat(C.CString(identifier), C.float(value))
}
func setParamBool(identifier string, value bool) {
C.mlpackSetParamBool(C.CString(identifier), C.bool(value))
}
func setParamString(identifier string, value string) {
C.mlpackSetParamString(C.CString(identifier), C.CString(value))
}
func setParamPtr(identifier string, ptr unsafe.Pointer) {
C.mlpackSetParamPtr(C.CString(identifier), (*C.double)(ptr))
}
func resetTimers() {
C.mlpackResetTimers()
}
func enableTimers() {
C.mlpackEnableTimers()
}
func disableBacktrace() {
C.mlpackDisableBacktrace()
}
func disableVerbose() {
C.mlpackDisableVerbose()
}
func enableVerbose() {
C.mlpackEnableVerbose()
}
func restoreSettings(method string) {
C.mlpackRestoreSettings(C.CString(method))
}
func clearSettings() {
C.mlpackClearSettings()
}
func getParamString(identifier string) string {
val := C.GoString(C.mlpackGetParamString(C.CString(identifier)))
return val
}
func getParamBool(identifier string) bool {
val := bool(C.mlpackGetParamBool(C.CString(identifier)))
return val
}
func getParamInt(identifier string) int {
val := int(C.mlpackGetParamInt(C.CString(identifier)))
return val
}
func getParamDouble(identifier string) float64 {
val := float64(C.mlpackGetParamDouble(C.CString(identifier)))
return val
}
type mlpackVectorType struct {
mem unsafe.Pointer
}
func (v *mlpackVectorType) allocVecIntPtr(identifier string) {
v.mem = C.mlpackGetVecIntPtr(C.CString(identifier))
runtime.KeepAlive(v)
}
func setParamVecInt(identifier string, vecInt []int) {
ptr := unsafe.Pointer(&vecInt[0])
C.mlpackSetParamVectorInt(C.CString(identifier), (*C.longlong)(ptr),
C.size_t(len(vecInt)))
}
func setParamVecString(identifier string, vecString []string) {
C.mlpackSetParamVectorStrLen(C.CString(identifier), C.size_t(len(vecString)))
for i := 0; i < len(vecString); i++ {
C.mlpackSetParamVectorStr(C.CString(identifier), (C.CString)(vecString[i]),
C.size_t(i))
}
}
func getParamVecInt(identifier string) []int {
e := int(C.mlpackVecIntSize(C.CString(identifier)))
var v mlpackVectorType
v.allocVecIntPtr(identifier)
data := (*[1<<30 - 1]int)(v.mem)
output := data[:e]
if output != nil {
return output
}
return []int{}
}
func getParamVecString(identifier string) []string {
e := int(C.mlpackVecStringSize(C.CString(identifier)))
data := make([]string, e)
for i := 0; i < e; i++ {
data[i] = C.GoString(C.mlpackGetVecStringPtr(C.CString(identifier),
C.size_t(i)))
runtime.GC()
}
return data
}
+10
View File
@@ -0,0 +1,10 @@
/*
mlpack is a fast, flexible machine learning library, written in C++, that
aims to provide fast, extensible implementations of cutting-edge machine
learning algorithms. mlpack provides these algorithms as simple command-line
programs, Go bindings, and C++ classes which can then be integrated into
larger-scale machine learning solutions.
*/
package mlpack
+79
View File
@@ -0,0 +1,79 @@
/**
* @file print_cpp.cpp
* @author Yasmine Dumouchel
*
* Implementation of function to generate a .cpp file given a list of parameters
* for the function.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include "print_cpp.hpp"
#include "camel_case.hpp"
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/util/hyphenate_string.hpp>
#include <set>
using namespace mlpack::util;
using namespace std;
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given a list of parameter definition and program documentation, print a
* generated .cpp file to stdout.
*
* @param parameters List of parameters the program will use (from CLI).
* @param programInfo Documentation for the program.
* @param functionName Name of the function (i.e. "pca").
*/
void PrintCPP(const ProgramDoc& programInfo,
const string& mainFilename,
const string& functionName)
{
// Restore parameters.
CLI::RestoreSettings(programInfo.programName);
const std::map<std::string, util::ParamData>& parameters = CLI::Parameters();
typedef std::map<std::string, util::ParamData>::const_iterator ParamIter;
// First, we must generate the header comment and namespace.
cout << "#include \"" << functionName << ".h\""<< endl;
cout << "#include <" << mainFilename << ">" << endl;
cout << "#include <mlpack/bindings/go/mlpack/capi/cli_util.hpp>" << endl;
cout << endl;
cout << "using namespace mlpack;" << endl;
cout << "using namespace mlpack::util;" << endl;
cout << "using namespace std;" << endl;
cout << endl;
// Then we must print utility function for model type parameters if needed.
for (ParamIter it = parameters.begin(); it != parameters.end(); ++it)
{
const util::ParamData& d = it->second;
if (d.input)
CLI::GetSingleton().functionMap[d.tname]["PrintModelUtilCPP"](d,
NULL, NULL);
}
// Finally, we generate the wrapper function for mlpackMain().
std::string goFunctionName = CamelCase(functionName);
cout << "static void " << goFunctionName << "MlpackMain()" << endl;
cout << "{" << endl;
cout << " " << "mlpackMain();" << endl;
cout << "}" << endl;
cout << endl;
cout << "extern \"C\" void mlpack" << goFunctionName << "()" << endl;
cout << "{" << endl;
cout << " " << goFunctionName << "MlpackMain();" << endl;
cout << "}" << endl;
cout << endl;
}
} // namespace go
} // namespace bindings
} // namespace mlpack
+39
View File
@@ -0,0 +1,39 @@
/**
* @file print_cpp.hpp
* @author Yasmine Dumouchel
*
* Given a list of ParamData structures, emit a .cpp file defining the
* Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_CPP_HPP
#define MLPACK_BINDINGS_GO_PRINT_CPP_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given a list of parameter definition and program documentation, print a
* generated .cpp file to stdout.
*
* @param parameters List of parameters the program will use (from CLI).
* @param programInfo Documentation for the program.
* @param functionName Name of the function (i.e. "pca").
*/
void PrintCPP(const util::ProgramDoc& programInfo,
const std::string& mainFilename,
const std::string& functionName);
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+122
View File
@@ -0,0 +1,122 @@
/**
* @file print_defn_input.hpp
* @author Yasmine Dumouchel
*
* Print the definition of an input in a binding .go file for a given
* parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_DEFN_INPUT_HPP
#define MLPACK_BINDINGS_GO_PRINT_DEFN_INPUT_HPP
#include <mlpack/prereqs.hpp>
#include "get_go_type.hpp"
#include "strip_type.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print input in method definition for a regular parameter type.
*/
template<typename T>
void PrintDefnInput(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
if (d.required)
{
std::string name = d.name;
std::cout << name << " " << GetGoType<T>(d);
}
}
/**
* Print input in method definition for a matrix type.
*/
template<typename T>
void PrintDefnInput(
const util::ParamData& d,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// param_name *mat.Dense
if (d.required)
{
std::string name = d.name;
std::cout << name << " *" << GetGoType<T>(d);
}
}
/**
* Print input in method definition for a matrix with info type.
*/
template<typename T>
void PrintDefnInput(
const util::ParamData& d,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// param_name *DataWithInfo
if (d.required)
{
std::string name = d.name;
std::cout << name << " *" << GetGoType<T>(d);
}
}
/**
* Print input in method definition for a serializable model.
*/
template<typename T>
void PrintDefnInput(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// Get the type names we need to use.
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
// param_name *Model_Name
if (d.required)
{
std::string name = d.name;
std::cout << name << " *" << goStrippedType;
}
}
/**
* Given parameter information and the current number of spaces for indentation,
* print the code to process the output to cout. This code assumes that
* data.input is false, and should not be called when data.input is true. If
* this is the only output, the results will be different.
*
* The input pointer should be a pointer to a std::tuple<size_t, bool> where the
* first element is the indentation and the second element is a boolean
* representing whether or not this is the only output parameter.
*
* @param d Parameter data struct.
* @param input Pointer to size_t holding the indentation.
* @param output Unused parameter.
*/
template<typename T>
void PrintDefnInput(const util::ParamData& d,
const void* /* input */,
void* /* output */)
{
PrintDefnInput<typename std::remove_pointer<T>::type>(d);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,104 @@
/**
* @file print_defn_output.hpp
* @author Yasmine Dumouchel
*
* Print the output for the definition in a Go binding .go file for a given
* parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_DEFN_OUTPUT_HPP
#define MLPACK_BINDINGS_GO_PRINT_DEFN_OUTPUT_HPP
#include <mlpack/prereqs.hpp>
#include "get_go_type.hpp"
#include "strip_type.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print output for a regular parameter type.
*/
template<typename T>
void PrintDefnOutput(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
std::cout << GetGoType<T>(d);
}
/**
* Print output for a matrix type.
*/
template<typename T>
void PrintDefnOutput(
const util::ParamData& d,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// *mat.Dense
std::cout << "*" << GetGoType<T>(d);
}
/**
* Print output for a matrix with info type.
*/
template<typename T>
void PrintDefnOutput(
const util::ParamData& d,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// *mat.Dense
std::cout << "*" << GetGoType<T>(d);
}
/**
* Print output for a serializable model.
*/
template<typename T>
void PrintDefnOutput(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// Get the type names we need to use.
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
std::cout << goStrippedType;
}
/**
* Given parameter information and the current number of spaces for indentation,
* print the code to process the output to cout. This code assumes that
* data.input is false, and should not be called when data.input is true. If
* this is the only output, the results will be different.
*
* The input pointer should be a pointer to a std::tuple<size_t, bool> where the
* first element is the indentation and the second element is a boolean
* representing whether or not this is the only output parameter.
*
* @param d Parameter data struct.
* @param input Pointer to size_t holding the indentation.
* @param output Unused parameter.
*/
template<typename T>
void PrintDefnOutput(const util::ParamData& d,
const void* /* input */,
void* /* output */)
{
PrintDefnOutput<typename std::remove_pointer<T>::type>(d);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+74
View File
@@ -0,0 +1,74 @@
/**
* @file print_doc.hpp
* @author Yashwant Singh
* @author Yasmine Dumouchel
*
* Print documentation for a Go binding parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_DOC_HPP
#define MLPACK_BINDINGS_GO_PRINT_DOC_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/hyphenate_string.hpp>
#include "get_go_type.hpp"
#include "camel_case.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print the docstring documentation for a given parameter. You are responsible
* for setting up the line---this does not handle indentation or anything. This
* is meant to produce a line of documentation describing a single parameter.
*
* The indent parameter (void* input, which should be a pointer to a size_t)
* should be passed to know how much to indent for a new line.
*
* @param d Parameter data struct.
* @param input Pointer to size_t containing indent.
* @param output Unused parameter.
*/
template<typename T>
void PrintDoc(const util::ParamData& d,
const void* input,
void* /* output */)
{
const size_t indent = *((size_t*) input);
std::ostringstream oss;
oss << " - ";
oss << CamelCase(d.name) << " (";
oss << GetGoType<typename std::remove_pointer<T>::type>(d) << "): "
<< d.desc;
// Print a default, if possible.
if (!d.required)
{
if (d.cppType == "std::string")
{
oss << " Default value '" << boost::any_cast<std::string>(d.value)
<< "'.";
}
else if (d.cppType == "double")
{
oss << " Default value " << boost::any_cast<double>(d.value) << ".";
}
else if (d.cppType == "int")
{
oss << " Default value " << boost::any_cast<int>(d.value) << ".";
}
}
std::cout << util::HyphenateString(oss.str(), indent + 4);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,149 @@
/**
* @file print_doc_functions.hpp
* @author Yashwant Singh
* @author Yasmine Dumouchel
*
* This file contains functions useful for printing documentation strings
* related to Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_DOC_FUNCTIONS_HPP
#define MLPACK_BINDINGS_GO_PRINT_DOC_FUNCTIONS_HPP
#include <mlpack/core/util/hyphenate_string.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given the name of a binding, print its Go name.
*/
inline std::string GetBindingName(const std::string& bindingName);
/**
* Print any import information for the Go binding.
*/
inline std::string PrintImport();
/**
* Print any special information about output options.
*/
inline std::string PrintOutputOptionInfo();
/**
* Given a parameter type, print the corresponding value.
*/
template<typename T>
inline std::string PrintValue(const T& value, bool quotes);
// Special overload for booleans.
template<>
inline std::string PrintValue(const bool& value, bool quotes);
/**
* Given a parameter name, print its corresponding default value.
*/
inline std::string PrintDefault(const std::string& paramName);
// Base case: no modification needed.
inline void GetOptions(
std::vector<std::tuple<std::string, std::string>>& /* results */);
/**
* Assemble a vector of string tuples indicating parameter names and what should
* be printed for them. (For output parameters, we just need to print the
* value.)
*/
template<typename T, typename... Args>
void GetOptions(
std::vector<std::tuple<std::string, std::string>>& results,
const std::string& paramName,
const T& value,
Args... args);
// Recursion base case.
inline std::string PrintOptionalInputs(/* option */);
// Recursion base case.
inline std::string PrintInputOptions(/* option */);
/**
* Print an input option. This will throw an exception if the parameter does
* not exist in CLI.
*/
template<typename T, typename... Args>
std::string PrintOptionalInputs(const std::string& paramName,
const T& value,
Args... args);
/**
* Print an input option. This will throw an exception if the parameter does
* not exist in CLI.
*/
template<typename T, typename... Args>
std::string PrintInputOptions(const std::string& paramName,
const T& value,
Args... args);
// Recursion base case.
inline std::string PrintOutputOptions();
template<typename... Args>
std::string PrintOutputOptions(Args... args);
/**
* Given a name of a binding and a variable number of arguments (and their
* contents), print the corresponding function call.
*/
template<typename... Args>
std::string ProgramCall(const std::string& programName, Args... args);
/**
* Given the name of a model, print it. Here we do not need to modify anything.
*/
inline std::string PrintModel(const std::string& modelName);
/**
* Given the name of a matrix, print it. Here we do not need to modify
* anything.
*/
inline std::string PrintDataset(const std::string& datasetName);
/**
* Given the parameter name, determine what it would actually be when passed to
* the command line.
*/
inline std::string ParamString(const std::string& paramName);
/**
* Print whether or not we should ignore a check on the given parameter.
*/
inline bool IgnoreCheck(const std::string& paramName);
/**
* Print whether or not we should ignore a check on the given set of
* constraints.
*/
inline bool IgnoreCheck(const std::vector<std::string>& constraints);
/**
* Print whether or not we should ignore a check on the given set of
* constraints.
*/
inline bool IgnoreCheck(
const std::vector<std::pair<std::string, bool>>& constraints,
const std::string& paramName);
} // namespace go
} // namespace bindings
} // namespace mlpack
// Include implementation.
#include "print_doc_functions_impl.hpp"
#endif
@@ -0,0 +1,541 @@
/**
* @file print_doc_functions_impl.hpp
* @author Yashwant Singh
* @author Yasmine Dumouchel
*
* This file contains functions useful for printing documentation strings
* related to Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_DOC_FUNCTIONS_IMPL_HPP
#define MLPACK_BINDINGS_GO_PRINT_DOC_FUNCTIONS_IMPL_HPP
#include <mlpack/core/util/hyphenate_string.hpp>
#include "strip_type.hpp"
#include "camel_case.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given the name of a binding, print its Go name.
*/
inline std::string GetBindingName(const std::string& bindingName)
{
// No modification is needed to the name---we just use it as-is.
return CamelCase(bindingName) + "()";
}
/**
* Print any import information for the Go binding.
*/
inline std::string PrintImport()
{
return "import (\n"
" \"mlpack/build/src/mlpack/bindings/go/mlpack\"\n"
" \"gonum.org/v1/gonum/mat\"\n"
")";
}
/**
* Print any special information about output options.
*/
inline std::string PrintOutputOptionInfo()
{
return "Output options are returned via Go's support for multiple "
"return values.";
}
/**
* Given a parameter type, print the corresponding value.
*/
template<typename T>
inline std::string PrintValue(const T& value, bool quotes)
{
std::ostringstream oss;
if (quotes)
oss << "\"";
oss << value;
if (quotes)
oss << "\"";
return oss.str();
}
// Special overload for booleans.
template<>
inline std::string PrintValue(const bool& value, bool quotes)
{
if (quotes && value)
return "\"true\"";
else if (quotes && !value)
return "\"false\"";
else if (!quotes && value)
return "true";
else
return "false";
}
/**
* Given a parameter name, print its corresponding default value.
*/
inline std::string PrintDefault(const std::string& paramName)
{
if (CLI::Parameters().count(paramName) == 0)
throw std::invalid_argument("unknown parameter " + paramName + "!");
const util::ParamData& d = CLI::Parameters()[paramName];
std::string defaultValue;
CLI::GetSingleton().functionMap[d.tname]["DefaultParam"](d, NULL,
(void*) &defaultValue);
return defaultValue;
}
// Recursion base case.
std::string PrintOptionalInputs() { return ""; }
/**
* Print an input option. This will throw an exception if the parameter does
* not exist in CLI.
*/
template<typename T, typename... Args>
std::string PrintOptionalInputs(const std::string& paramName,
const T& value,
Args... args)
{
// See if this is part of the program.
std::string result = "";
if (CLI::Parameters().count(paramName) > 0)
{
const util::ParamData& d = CLI::Parameters()[paramName];
if (d.input && !d.required)
{
std::string goParamName = CamelCase(paramName);
// Print the input option.
std::ostringstream oss;
oss << " param." << goParamName << " = ";
std::string name;
CLI::GetSingleton().functionMap[d.tname]["GetType"](d, NULL,
(void*) &name);
if (name[name.size() - 1] == '*')
{
oss << "&";
oss << CamelCase(PrintValue(value, d.tname == TYPENAME(std::string)));
}
else
{
oss << PrintValue(value, d.tname == TYPENAME(std::string));
}
oss << "\n";
result = oss.str();
}
}
else
{
// Unknown parameter!
throw std::runtime_error("Unknown parameter '" + paramName + "' " +
"encountered while assembling documentation! Check PROGRAM_INFO() " +
"declaration.");
}
// Continue recursion.
std::string rest = PrintOptionalInputs(args...);
if (rest != "" && result != "")
result += rest;
else if (result == "")
result = rest;
return result;
}
// Recursion base case.
std::string PrintInputOptions() { return ""; }
/**
* Print an input option. This will throw an exception if the parameter does
* not exist in CLI.
*/
template<typename T, typename... Args>
std::string PrintInputOptions(const std::string& paramName,
const T& value,
Args... args)
{
// See if this is part of the program.
std::string result = "";
if (CLI::Parameters().count(paramName) > 0)
{
const util::ParamData& d = CLI::Parameters()[paramName];
if (d.input && d.required)
{
// Print the input option.
std::ostringstream oss;
std::string name;
CLI::GetSingleton().functionMap[d.tname]["GetType"](d, NULL,
(void*) &name);
if (name[name.size() - 1] == '*')
{
oss << "&";
oss << CamelCase(PrintValue(value, d.tname == TYPENAME(std::string)));
}
else
{
oss << PrintValue(value, d.tname == TYPENAME(std::string));
}
result = oss.str();
}
}
else
{
// Unknown parameter!
throw std::runtime_error("Unknown parameter '" + paramName + "' " +
"encountered while assembling documentation! Check PROGRAM_INFO() " +
"declaration.");
}
// Continue recursion.
std::string rest = PrintInputOptions(args...);
if (rest != "" && result != "")
result += ", " + rest;
else if (result == "")
result = rest;
return result;
}
// Base case: no modification needed.
void GetOptions(
std::vector<std::tuple<std::string, std::string>>& /* results */)
{
// Nothing to do.
}
/**
* Assemble a vector of string tuples indicating parameter names and what should
* be printed for them. (For output parameters, we just need to print the
* value.)
*/
template<typename T, typename... Args>
void GetOptions(
std::vector<std::tuple<std::string, std::string>>& results,
const std::string& paramName,
const T& value,
Args... args)
{
// Determine whether or not the value is required.
if (CLI::Parameters().count(paramName) > 0)
{
std::ostringstream oss;
oss << value;
results.push_back(std::make_tuple(paramName, oss.str()));
GetOptions(results, args...);
}
else
{
// Unknown parameter!
throw std::runtime_error("Unknown parameter '" + paramName + "' " +
"encountered while assembling documentation! Check PROGRAM_INFO() " +
"declaration.");
}
}
// Recursion base case.
inline std::string PrintOutputOptions() { return ""; }
template<typename... Args>
std::string PrintOutputOptions(Args... args)
{
// Get the list of output options for the binding.
std::vector<std::string> outputOptions;
for (auto it = CLI::Parameters().begin(); it != CLI::Parameters().end(); ++it)
{
const util::ParamData& d = it->second;
if (!d.input)
outputOptions.push_back(it->first);
}
// Now get the full list of output options that we have.
std::vector<std::tuple<std::string, std::string>> passedOptions;
GetOptions(passedOptions, args...);
// Next, iterate over all the options.
std::ostringstream oss;
for (size_t i = 0; i < outputOptions.size(); ++i)
{
// Does this option exist?
bool found = false;
size_t index = passedOptions.size();
for (size_t j = 0; j < passedOptions.size(); ++j)
{
if (outputOptions[i] == std::get<0>(passedOptions[j]))
{
found = true;
index = j;
break;
}
}
if (found)
{
// We have received this option, so print it.
if (i == 0)
{
oss << " " << CamelCase(std::get<1>(passedOptions[index]));
}
else if (i > 0)
{
oss << ", ";
oss << CamelCase(std::get<1>(passedOptions[index]));
}
}
else
{
// We don't care about this option.
if (i == 0)
{
oss << " _";
}
else if (i > 0)
{
oss << ", _";
}
}
}
return oss.str();
}
/**
* Given a name of a binding and a variable number of arguments (and their
* contents), print the corresponding function call.
*/
template<typename... Args>
std::string ProgramCall(const std::string& programName, Args... args)
{
std::string result = "";
std::string goProgramName = CamelCase(programName);
// Initialize the method parameter structure
std::ostringstream oss;
oss << " param := mlpack.Initialize" << goProgramName << "()\n";
result = oss.str();
oss.str(""); // Reset it.
// Now process each optional parameters.
oss << PrintOptionalInputs(args...);
std::string param = oss.str();
result = result + util::HyphenateString(param, 0);
oss.str(""); // Reset it.
// Now process each output parameters.
oss << PrintOutputOptions(args...);
std::string output = oss.str();
result = result + util::HyphenateString(output, 0);
oss.str(""); // Reset it.
oss << " := mlpack." << goProgramName << "(";
result = result + oss.str();
oss.str(""); // Reset it.
// Now process each input required parameters.
oss << PrintInputOptions(args...);
std::string input = oss.str();
if (input != "")
result = result + input + ", ";
oss.str(""); // Reset it.
if (param != "")
result = result + "param";
result = result + ")";
return result;
}
/**
* Given the name of a model, print it. Here we do not need to modify anything.
*/
inline std::string PrintModel(const std::string& modelName)
{
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(modelName, goStrippedType, strippedType, printedType, defaultsType);
return strippedType;
}
/**
* Given the name of a matrix, print it. Here we do not need to modify
* anything.
*/
inline std::string PrintDataset(const std::string& datasetName)
{
return datasetName;
}
/**
* Given the name of a binding, print its invocation.
*/
inline std::string ProgramCall(const std::string& programName)
{
std::ostringstream oss;
std::string goProgramName = CamelCase(programName);
// Determine if we have any output options.
const std::map<std::string, util::ParamData>& parameters = CLI::Parameters();
oss << " param := mlpack.Initialize" << goProgramName << "()\n";
std::vector<std::string> outputOptions;
for (auto it = CLI::Parameters().begin(); it != CLI::Parameters().end(); ++it)
{
const util::ParamData& d = it->second;
if (!d.input)
outputOptions.push_back(it->first);
}
std::string result = oss.str();
oss.str("");
std::string param = "";
// Now iterate over every input option.
for (auto it = parameters.begin(); it != parameters.end(); ++it)
{
if (it->second.input && !it->second.required && !it->second.persistent)
{
// Print the input option.
oss << " param." << CamelCase(it->second.name) << " = ";
std::string value;
CLI::GetSingleton().functionMap[it->second.tname]["DefaultParam"](
it->second, NULL, (void*) &value);
oss << value;
oss << "\n";
param = oss.str();
}
}
// Now iterate over every optional input option.
for (auto it = parameters.begin(); it != parameters.end(); ++it)
{
if (it->second.input && it->second.required && !it->second.persistent)
{
// Print the input option.
oss << " " << CamelCase(it->second.name) << " := ";
std::string value;
CLI::GetSingleton().functionMap[it->second.tname]["DefaultParam"](
it->second, NULL, (void*) &value);
oss << value;
oss << "\n";
}
}
result += oss.str();
oss.str("");
oss << result;
// Now print output lines.
size_t outputs = 0;
for (auto it = parameters.begin(); it != parameters.end(); ++it)
{
if (!it->second.input)
{
if (outputs > 0)
{
oss << ", ";
oss << CamelCase(it->second.name);
}
else
{
oss << " " << CamelCase(it->second.name);
}
++outputs;
}
}
oss << " := mlpack." << goProgramName << "(";
for (auto i = parameters.begin(); i != parameters.end(); ++i)
{
if (i->second.input && i->second.required && i != parameters.end())
oss << CamelCase(i->second.name) << ", ";
else if (i == parameters.end())
oss << CamelCase(i->second.name);
}
if (param != "")
oss << "param";
oss << ")\n";
result = "";
result = util::HyphenateString(oss.str(), 0);
oss.str("");
oss << result;
return oss.str();
}
/**
* Print any closing call to a program.
*/
inline std::string ProgramCallClose()
{
return ")";
}
/**
* Given the parameter name, determine what it would actually be when passed to
* the command line.
*/
inline std::string ParamString(const std::string& paramName)
{
// For a Go binding we don't need to know the type.
return "\"" + paramName + "\"";
}
/**
* Given the parameter name and an argument, return what should be written as
* documentation when referencing that argument.
*/
template<typename T>
inline std::string ParamString(const std::string& paramName, const T& value)
{
std::ostringstream oss;
oss << paramName << "=" << value;
return oss.str();
}
inline bool IgnoreCheck(const std::string& paramName)
{
return !CLI::Parameters()[paramName].input;
}
inline bool IgnoreCheck(const std::vector<std::string>& constraints)
{
for (size_t i = 0; i < constraints.size(); ++i)
{
if (!CLI::Parameters()[constraints[i]].input)
return true;
}
return false;
}
inline bool IgnoreCheck(
const std::vector<std::pair<std::string, bool>>& constraints,
const std::string& paramName)
{
for (size_t i = 0; i < constraints.size(); ++i)
{
if (!CLI::Parameters()[constraints[i].first].input)
return true;
}
return !CLI::Parameters()[paramName].input;
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+283
View File
@@ -0,0 +1,283 @@
/**
* @file print_go.cpp
* @author Yasmine Dumouchel
*
* Implementation of function to generate a .go file given a list of parameters
* for the function.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include "print_go.hpp"
#include "camel_case.hpp"
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/util/hyphenate_string.hpp>
#include <set>
using namespace mlpack::util;
using namespace std;
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given a list of parameter definition and program documentation, print a
* generated .go file to stdout.
*
* @param parameters List of parameters the program will use (from CLI).
* @param programInfo Documentation for the program.
* @param functionName Name of the function (i.e. "pca").
*/
void PrintGo(const util::ProgramDoc& programInfo,
const std::string& functionName)
{
// Restore parameters.
CLI::RestoreSettings(programInfo.programName);
const std::map<std::string, util::ParamData>& parameters = CLI::Parameters();
typedef std::map<std::string, util::ParamData>::const_iterator ParamIter;
// Split into input and output parameters. Take two passes on the input
// parameters, so that we get the required ones first.
vector<string> inputOptions, outputOptions;
for (ParamIter it = parameters.begin(); it != parameters.end(); ++it)
{
const util::ParamData& d = it->second;
if (d.input && d.required)
{
// Ignore some parameters.
if (d.name != "help" && d.name != "info" && d.name != "version")
inputOptions.push_back(it->first);
}
else if (!d.input)
{
outputOptions.push_back(it->first);
}
}
for (ParamIter it = parameters.begin(); it != parameters.end(); ++it)
{
const util::ParamData& d = it->second;
if (d.input && !d.required &&
d.name != "help" && d.name != "info" &&
d.name != "version")
inputOptions.push_back(it->first);
}
// First, we must generate the mlpack package name.
cout << "package mlpack" << endl;
cout << endl;
// Now we must print the cgo's import libraries and files.
cout << "/*" << endl;
cout << "#cgo CFLAGS: -I./capi -Wall" << endl;
cout << "#cgo LDFLAGS: -L. -lmlpack_go_" << functionName << endl;
cout << "#include <capi/" << functionName << ".h>" << endl;
cout << "#include <stdlib.h>" << endl;
cout << "*/" << endl;
cout << "import \"C\" " << endl;
cout << endl;
// Then we must print the import of the gonum package.
cout << "import (" << endl;
cout << " " << "\"gonum.org/v1/gonum/mat\" " << endl;
for (size_t i = 0; i < inputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(inputOptions[i]);
size_t indent = 2;
CLI::GetSingleton().functionMap[d.tname]["ImportDecl"](d,
(void*) &indent, NULL);
}
cout << ")" << endl;
cout << endl;
std::string goFunctionName = CamelCase(functionName);
// Print Go method configuration struct.
cout << "type " << goFunctionName << "OptionalParam struct {"
<< std::endl;
for (size_t i = 0; i < inputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(inputOptions[i]);
size_t indent = 4;
CLI::GetSingleton().functionMap[d.tname]["PrintMethodConfig"](d,
(void*) &indent, NULL);
}
cout << "}" << endl;
cout << endl;
// Print Go method configurate struct initialization.
cout << "func Initialize" << goFunctionName << "() *"
<< goFunctionName << "OptionalParam {"
<< endl;
cout << " " << "return &" << goFunctionName << "OptionalParam{" << endl;
for (size_t i = 0; i < inputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(inputOptions[i]);
size_t indent = 4;
CLI::GetSingleton().functionMap[d.tname]["PrintMethodInit"](d,
(void*) &indent, NULL);
}
cout << " " << "}" << endl;
cout << "}" << endl;
cout << endl;
// Then we must print utility function for model type parameters if needed.
for (ParamIter it = parameters.begin(); it != parameters.end(); ++it)
{
const util::ParamData& d = it->second;
if (d.input)
CLI::GetSingleton().functionMap[d.tname]["PrintModelUtilGo"](d,
NULL, NULL);
}
// Print the comment describing the function and its parameters.
cout << "/*" << endl;
cout << " " << HyphenateString(programInfo.documentation(), 2) << endl;
cout << endl << endl;
cout << " Input parameters:" << endl;
cout << endl;
for (size_t i = 0; i < inputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(inputOptions[i]);
cout << " ";
size_t indent = 4;
CLI::GetSingleton().functionMap[d.tname]["PrintDoc"](d, (void*) &indent,
NULL);
cout << endl;
}
cout << endl;
cout << " Output parameters:" << endl;
cout << endl;
for (size_t i = 0; i < outputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(outputOptions[i]);
cout << " ";
size_t indent = 4;
CLI::GetSingleton().functionMap[d.tname]["PrintDoc"](d, (void*) &indent,
NULL);
cout << endl;
}
cout << endl;
cout << " */" << endl;
// Print the function definition.
cout << "func " << goFunctionName << "(";
// Then we print the required input.
size_t counter = 0;
for (size_t i = 0; i < inputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(inputOptions[i]);
if (d.required)
{
if (i != 0)
cout << ", ";
CLI::GetSingleton().functionMap[d.tname]["PrintDefnInput"](d, NULL, NULL);
counter++;
}
}
// Then we print the optional parameter struct input.
if (counter == 0)
{
cout << "param *" << goFunctionName << "OptionalParam) (";
}
else
{
cout << ", param *" << goFunctionName << "OptionalParam) (";
}
// We must then print the output options.
for (size_t i = 0; i < outputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(outputOptions[i]);
if (i != 0)
cout << ", ";
std::tuple<size_t, bool> t = std::make_tuple(2, false);
CLI::GetSingleton().functionMap[d.tname]["PrintDefnOutput"](d,
(void*) &t, NULL);
}
// Print opening brace for function.
cout << ") {" << endl;
// Reset any timers and disable backtraces.
cout << " " << "resetTimers()" << endl;
cout << " " << "enableTimers()" << endl;
cout << " " << "disableBacktrace()" << endl;
cout << " " << "disableVerbose()" << endl;
// Restore the parameters.
cout << " " << "restoreSettings(\"" << programInfo.programName
<< "\")" << endl;
cout << endl;
// Do any input processing.
for (size_t i = 0; i < inputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(inputOptions[i]);
size_t indent = 2;
CLI::GetSingleton().functionMap[d.tname]["PrintInputProcessing"](d,
(void*) &indent, NULL);
}
// Set all output options as passed.
cout << " " << "// Mark all output options as passed." << endl;
for (size_t i = 0; i < outputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(outputOptions[i]);
cout << " " << "setPassed(\"" << d.name << "\")" << endl;
}
cout << endl;
// Call the method.
cout << " " << "// Call the mlpack program." << endl;
cout << " " << "C.mlpack" << goFunctionName << "()" << endl;
cout << endl;
// Do any output processing and return.
cout << " " << "// Initialize result variable and get output." << endl;
for (size_t i = 0; i < outputOptions.size(); ++i)
{
const util::ParamData& d = parameters.at(outputOptions[i]);
CLI::GetSingleton().functionMap[d.tname]["PrintOutputProcessing"](d,
NULL, NULL);
}
// Clear the parameters.
cout << endl;
cout << " " << "// Clear settings." << endl;
cout << " " << "clearSettings()" << endl;
cout << endl;
// Return output parameters.
cout << " " << "// Return output(s)." << endl;
cout << " " << "return ";
for (size_t i = 0; i < outputOptions.size(); ++i)
{
if (i != 0)
cout << ", ";
const util::ParamData& d = parameters.at(outputOptions[i]);
cout << CamelCase(d.name);
}
cout << endl;
// Print closing bracket.
cout << "}" << endl;
}
} // namespace go
} // namespace bindings
} // namespace mlpack
+38
View File
@@ -0,0 +1,38 @@
/**
* @file print_go.hpp
* @author Yasmine Dumouchel
*
* Given a list of ParamData structures, emit a .go file defining the
* Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_GO_HPP
#define MLPACK_BINDINGS_GO_PRINT_GO_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given a list of parameter definition and program documentation, print a
* generated .go file to stdout.
*
* @param parameters List of parameters the program will use (from CLI).
* @param programInfo Documentation for the program.
* @param functionName Name of the function (i.e. "pca").
*/
void PrintGo(const util::ProgramDoc& programInfo,
const std::string& functionName);
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+74
View File
@@ -0,0 +1,74 @@
/**
* @file print_h.cpp
* @author Yasmine Dumouchel
*
* Implementation of function to generate a .h file given a list of parameters
* for the function.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include "print_h.hpp"
#include "camel_case.hpp"
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/util/hyphenate_string.hpp>
#include <set>
using namespace mlpack::util;
using namespace std;
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given a list of parameter definition and program documentation, print a
* generated .h file to stdout.
*
* @param parameters List of parameters the program will use (from CLI).
* @param programInfo Documentation for the program.
* @param functionName Name of the function (i.e. "pca").
*/
void PrintH(const util::ProgramDoc& programInfo,
const std::string& functionName)
{
// Restore parameters.
CLI::RestoreSettings(programInfo.programName);
const std::map<std::string, util::ParamData>& parameters = CLI::Parameters();
typedef std::map<std::string, util::ParamData>::const_iterator ParamIter;
// First, we must generate the header comment and namespace.
cout << "#include <stdint.h>" << endl;
cout << "#include <stddef.h>" << endl;
cout << endl;
cout << "#if defined(__cplusplus) || defined(c_plusplus)" << endl;
cout << "extern \"C\" {" << endl;
cout << "#endif" << endl;
cout << endl;
// Then we must print utility function for model type parameters if needed.
for (ParamIter it = parameters.begin(); it != parameters.end(); ++it)
{
const util::ParamData& d = it->second;
if (d.input)
CLI::GetSingleton().functionMap[d.tname]["PrintModelUtilH"](d,
NULL, NULL);
}
std::string goFunctionName = CamelCase(functionName);
// We generate the wrapper function for mlpackMain().
cout << "extern void mlpack" << goFunctionName << "();" << endl;
cout << endl;
// Finally we close print the closing bracket for extern C.
cout << "#if defined(__cplusplus) || defined(c_plusplus)" << endl;
cout << "}" << endl;
cout << "#endif" << endl;
}
} // namespace go
} // namespace bindings
} // namespace mlpack
+38
View File
@@ -0,0 +1,38 @@
/**
* @file print_h.hpp
* @author Yasmine Dumouchel
*
* Given a list of ParamData structures, emit a .h file defining the
* Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_H_HPP
#define MLPACK_BINDINGS_GO_PRINT_H_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given a list of parameter definition and program documentation, print a
* generated .h file to stdout.
*
* @param parameters List of parameters the program will use (from CLI).
* @param programInfo Documentation for the program.
* @param functionName Name of the function (i.e. "pca").
*/
void PrintH(const util::ProgramDoc& programInfo,
const std::string& functionName);
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,86 @@
/**
* @file import_decl.hpp
* @author Yasmine Dumouchel
*
* Print the necessary imports for go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_IMPORT_DECL_HPP
#define MLPACK_BINDINGS_GO_IMPORT_DECL_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* For a serializable type, print a cppclass definition.
*/
template<typename T>
void ImportDecl(
const util::ParamData& /* d */,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
/**
* This will give output of the form:
*
*/
const std::string prefix = std::string(indent, ' ');
// Now import all the necessary packages.
std::cout << prefix << "\"runtime\" " << std::endl;
std::cout << prefix << "\"unsafe\" " << std::endl;
}
/**
* For a non-serializable type, print nothing.
*/
template<typename T>
void ImportDecl(
const util::ParamData& /* d */,
const size_t /* indent */,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0)
{
// Print nothing.
}
/**
* For a matrix type, print nothing.
*/
template<typename T>
void ImportDecl(
const util::ParamData& /* d */,
const size_t /* indent */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// Print nothing.
}
/**
* Print the cppclass definition for a serializable model; print nothing for a
* non-serializable type.
*
* @param d Parameter info struct.
* @param input Pointer to size_t indicating indent.
* @param output Unused parameter.
*/
template<typename T>
void ImportDecl(const util::ParamData& d,
const void* indent,
void* /* output */)
{
ImportDecl<typename std::remove_pointer<T>::type>(d, *((size_t*) indent));
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,336 @@
/**
* @file print_input_processing.hpp
* @author Yasmine Dumouchel
*
* Print input processing for a Go binding option.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_INPUT_PROCESSING_HPP
#define MLPACK_BINDINGS_GO_PRINT_INPUT_PROCESSING_HPP
#include <mlpack/prereqs.hpp>
#include "get_type.hpp"
#include "get_go_type.hpp"
#include "strip_type.hpp"
#include "camel_case.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print input processing for a standard option type.
*/
template<typename T>
void PrintInputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string paramName = d.name;
std::string goParamName = paramName;
if (!paramName.empty())
{
goParamName = CamelCase(goParamName);
}
/**
* This gives us code like:
*
* // Detect if the parameter was passed; set if so.
* if param.Name != nil {
* setParam<d.cppType>("paramName", param.Name)
* setPassed("paramName")
* }
*/
std::cout << prefix << "// Detect if the parameter was passed; set if so."
<< std::endl;
if (!d.required)
{
std::cout << prefix << "if param." << goParamName << " != ";
// Print out default value.
if (d.cppType == "std::string")
{
std::string value = boost::any_cast<std::string>(d.value);
std::cout << "\"" << value << "\"";
}
else if (d.cppType == "double")
{
double value = boost::any_cast<double>(d.value);
std::cout << value;
}
else if (d.cppType == "int")
{
int value = boost::any_cast<int>(d.value);
std::cout << value;
}
else if (d.cppType == "bool")
{
bool value = boost::any_cast<bool>(d.value);
if (value == 0)
std::cout << "false";
else
std::cout << "true";
}
else if (GetType<T>(d) == "VecString" || GetType<T>(d) == "VecInt")
{
std::cout << "nil";
}
// Print function call to set the given parameter into the cli.
std::cout << " {" << std::endl;
std::cout << prefix << prefix << "setParam" << GetType<T>(d) << "(\""
<< d.name << "\", param." << goParamName << ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << prefix << "setPassed(\""
<< d.name << "\")" << std::endl;
// If this parameter is "verbose", then enable verbose output.
if (d.name == "verbose")
std::cout << prefix << prefix << "enableVerbose()" << std::endl;
std::cout << prefix << "}" << std::endl; // Closing brace.
}
else
{
std::string lowercaseParamName = d.name;
lowercaseParamName[0] = std::tolower(lowercaseParamName[0]);
// Print function call to set the given parameter into the cli.
std::cout << prefix << "setParam" << GetType<T>(d) << "(\""
<< lowercaseParamName << "\", " << d.name << ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << "setPassed(\"" << d.name << "\")" << std::endl;
}
std::cout << std::endl; // Extra line is to clear up the code a bit.
}
/**
* Print input processing for a matrix type.
*/
template<typename T>
void PrintInputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
const std::string prefix(indent, ' ');
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string paramName = d.name;
std::string goParamName = paramName;
if (!paramName.empty())
{
goParamName = CamelCase(goParamName);
}
/**
* This gives us code like:
*
* // Detect if the parameter was passed; set if so.
* if param.Name != nil {
* gonumToArma<type>("paramName", param.Name)
* setPassed("paramName")
* }
*/
std::cout << prefix << "// Detect if the parameter was passed; set if so."
<< std::endl;
if (!d.required)
{
std::cout << prefix << "if param." << goParamName
<< " != nil {" << std::endl;
// Print function call to set the given parameter into the cli.
std::cout << prefix << prefix << "gonumToArma" << GetType<T>(d)
<< "(\"" << d.name << "\", param." << goParamName
<< ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << prefix << "setPassed(\"" << d.name << "\")"
<< std::endl;
std::cout << prefix << "}" << std::endl; // Closing brace.
}
else
{
std::string lowercaseParamName = d.name;
lowercaseParamName[0] = std::tolower(lowercaseParamName[0]);
// Print function call to set the given parameter into the cli.
std::cout << prefix << "gonumToArma" << GetType<T>(d)
<< "(\"" << d.name << "\", " << lowercaseParamName
<< ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << "setPassed(\"" << d.name << "\")" << std::endl;
}
std::cout << std::endl; // Extra line is to clear up the code a bit.
}
/**
* Print input processing for a matrix with info type.
*/
template<typename T>
void PrintInputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string paramName = d.name;
std::string goParamName = paramName;
if (!paramName.empty())
{
goParamName = CamelCase(goParamName);
}
/**
* This gives us code like:
*
* // Detect if the parameter was passed; set if so.
* if param.Name != nil {
* gonumToArmaMatWithInfo<type>("paramName", param.Name)
* setPassed("paramName")
* }
*/
std::cout << prefix << "// Detect if the parameter was passed; set if so."
<< std::endl;
if (!d.required)
{
std::cout << prefix << "if param." << goParamName
<< " != nil {" << std::endl;
// Print function call to set the given parameter into the cli.
std::cout << prefix << prefix << "gonumToArmaMatWithInfo"
<< "(\"" << d.name << "\", param." << goParamName
<< ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << prefix << "setPassed(\"" << d.name << "\")"
<< std::endl;
std::cout << prefix << "}" << std::endl; // Closing brace.
}
else
{
std::string lowercaseParamName = d.name;
lowercaseParamName[0] = std::tolower(lowercaseParamName[0]);
// Print function call to set the given parameter into the cli.
std::cout << prefix << "gonumToArmaMatWithInfo"
<< "(\"" << d.name << "\", " << lowercaseParamName
<< ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << "setPassed(\"" << d.name << "\")" << std::endl;
}
std::cout << std::endl; // Extra line is to clear up the code a bit.
}
/**
* Print input processing for a serializable type.
*/
template<typename T>
void PrintInputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// First, get the correct classparamName if needed.
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
const std::string prefix(indent, ' ');
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string paramName = d.name;
std::string goParamName = paramName;
if (!paramName.empty())
{
goParamName = CamelCase(goParamName);
}
/**
* This gives us code like:
*
* // Detect if the parameter was passed; set if so.
* if param.Name != nil {
* set<ModelType>("paramName", param.Name)
* setPassed("paramName")
* }
*/
std::cout << prefix << "// Detect if the parameter was passed; set if so."
<< std::endl;
if (!d.required)
{
std::cout << prefix << "if param." << goParamName << " != nil {"
<< std::endl;
// Print function call to set the given parameter into the cli.
std::cout << prefix << prefix << "set" << strippedType << "(\""
<< d.name << "\", param." << goParamName << ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << prefix << "setPassed(\"" << d.name << "\")"
<< std::endl;
std::cout << prefix << "}" << std::endl; // Closing brace.
}
else
{
// Print function call to set the given parameter into the cli.
std::cout << prefix << "set" << strippedType << "(\"" << d.name
<< "\", " << paramName << ")" << std::endl;
// Print function call to set the given parameter as passed.
std::cout << prefix << "setPassed(\"" << d.name << "\")" << std::endl;
}
std::cout << std::endl; // Extra line is to clear up the code a bit.
}
/**
* Given parameter information and the current number of spaces for indentation,
* print the code to process the input to cout. This code assumes that
* data.input is true, and should not be called when data.input is false.
*
* The number of spaces to indent should be passed through the input pointer.
*
* @param d Parameter data struct.
* @param input Pointer to size_t holding the indentation.
* @param output Unused parameter.
*/
template<typename T>
void PrintInputProcessing(const util::ParamData& d,
const void* input,
void* /* output */)
{
PrintInputProcessing<typename std::remove_pointer<T>::type>(d,
*((size_t*) input));
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,182 @@
/**
* @file print_method_config.hpp
* @author Yashwant Singh
*
* Print configuration struct for optional parameter type of a method for a
* Go binding.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_METHOD_CONFIG_HPP
#define MLPACK_BINDINGS_GO_PRINT_METHOD_CONFIG_HPP
#include <mlpack/prereqs.hpp>
#include "get_go_type.hpp"
#include "strip_type.hpp"
#include "camel_case.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print param in configuration struct for a standard option type.
*/
template<typename T>
void PrintMethodConfig(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << " " << GetGoType<T>(d)
<< std::endl;
}
}
/**
* Print param in configuration struct for a matrix type.
*/
template<typename T>
void PrintMethodConfig(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << " *" << GetGoType<T>(d)
<< std::endl;
}
}
/**
* Print param in configuration struct for a matrix with info type.
*/
template<typename T>
void PrintMethodConfig(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << " *" << GetGoType<T>(d)
<< std::endl;
}
}
/**
* Print param in method configuration struct for a serializable type.
*/
template<typename T>
void PrintMethodConfig(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << " *" << GetGoType<T>(d)
<< std::endl;
}
}
/**
* Given parameter information and the current number of spaces for indentation,
* print the code to process the input to cout. This code assumes that
* data.input is true, and should not be called when data.input is false.
*
* The number of spaces to indent should be passed through the input pointer.
*
* @param d Parameter data struct.
* @param input Pointer to size_t holding the indentation.
* @param output Unused parameter.
*/
template<typename T>
void PrintMethodConfig(const util::ParamData& d,
const void* input,
void* /* output */)
{
PrintMethodConfig<typename std::remove_pointer<T>::type>(d,
*((size_t*) input));
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,204 @@
/**
* @file print_method_init.hpp
* @author Yasmine Dumouchel
*
* Print a config struct initialization function for the optional
* parameter of a method for a Go binding.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_METHOD_INIT_HPP
#define MLPACK_BINDINGS_GO_PRINT_METHOD_INIT_HPP
#include <mlpack/prereqs.hpp>
#include "get_go_type.hpp"
#include "strip_type.hpp"
#include "camel_case.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print parameter with it's default value for a standard option type.
*/
template<typename T>
void PrintMethodInit(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
if (d.cppType == "std::string")
{
std::string value = boost::any_cast<std::string>(d.value);
std::cout << prefix << goParamName << ": \""
<< value << "\"," << std::endl;
}
else if (d.cppType == "double")
{
double value = boost::any_cast<double>(d.value);
std::cout << prefix << goParamName << ": " << value << "," << std::endl;
}
else if (d.cppType == "int")
{
int value = boost::any_cast<int>(d.value);
std::cout << prefix << goParamName << ": " << value << "," << std::endl;
}
else if (d.cppType == "bool")
{
bool value = boost::any_cast<bool>(d.value);
if (value == 0)
std::cout << prefix << goParamName << ": false," << std::endl;
else
std::cout << prefix << goParamName << ": true," << std::endl;
}
}
}
/**
* Print parameter with its default value for a matrix type.
*/
template<typename T>
void PrintMethodInit(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << ": " << def << ","
<< std::endl;
}
}
/**
* Print parameter with its default value for a matrix with info type.
*/
template<typename T>
void PrintMethodInit(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << ": " << def << ","
<< std::endl;
}
}
/**
* Print parameter with its default value for a serializable type.
*/
template<typename T>
void PrintMethodInit(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
const std::string prefix(indent, ' ');
std::string def = "nil";
if (std::is_same<T, bool>::value)
def = "false";
// Capitalize the first letter of parameter name so it is
// of exported type in Go.
std::string name = d.name;
std::string goParamName = name;
if (!name.empty())
{
goParamName = CamelCase(goParamName);
}
// Only print param that are not required.
if (!d.required)
{
std::cout << prefix << goParamName << ": " << def << ","
<< std::endl;
}
}
/**
* Given parameter information and the current number of spaces for indentation,
* print the code to process the input to cout. This code assumes that
* data.input is true, and should not be called when data.input is false.
*
* The number of spaces to indent should be passed through the input pointer.
*
* @param d Parameter data struct.
* @param input Pointer to size_t holding the indentation.
* @param output Unused parameter.
*/
template<typename T>
void PrintMethodInit(const util::ParamData& d,
const void* input,
void* /* output */)
{
PrintMethodInit<typename std::remove_pointer<T>::type>(d,
*((size_t*) input));
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+351
View File
@@ -0,0 +1,351 @@
/**
* @file print_model_util.hpp
* @author Yasmine Dumouchel
*
* Print the functions and structs associated with serializable model.
* for generating the .cpp, .h, and .go binding.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_CLASS_DEFN_HPP
#define MLPACK_BINDINGS_GO_PRINT_CLASS_DEFN_HPP
#include "strip_type.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Non-serializable models don't require any special definitions, so this prints
* nothing.
*/
template<typename T>
void PrintModelUtilCPP(
const util::ParamData& /* d */,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Do nothing.
}
/**
* Matrices don't require any special definitions, so this prints nothing.
*/
template<typename T>
void PrintModelUtilCPP(
const util::ParamData& /* d */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// Do nothing.
}
/**
* Matrices with Info don't require any special definitions, so this prints nothing.
*/
template<typename T>
void PrintModelUtilCPP(
const util::ParamData& /* d */,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Do nothing.
}
/**
* Serializable models require a special class definition.
*/
template<typename T>
void PrintModelUtilCPP(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// First, we have to parse the type. If we have something like, e.g.,
// 'LogisticRegression<>', we must convert this to 'LogisticRegression[].'
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
/**
* This gives us code like:
*
* extern "C" void mlpackSet<Type>Ptr(
* const char* identifier,
* void *value)
* {
* SetParamPtr<Type>(identifier,
* static_cast<Type<T>*(value));
* }
*
*/
std::cout << "extern \"C\" void mlpackSet" << strippedType
<< "Ptr(" << std::endl;
std::cout << " const char* identifier, " << std::endl;
std::cout << " void* value)" << std::endl;
std::cout << "{" << std::endl;
std::cout << " SetParamPtr<" << printedType
<< ">(identifier," << std::endl;
std::cout << " static_cast<" << printedType
<< "*>(value));" << std::endl;
std::cout << "}" << std::endl;
std::cout << std::endl;
/**
* This gives us code like:
*
* extern "C" void *mlpackGet<Type>Ptr(const char* identifier)
* {
* <Type> *modelptr = GetParamPtr<Type>(identifier);
* return modelptr;
* }
*
*/
std::cout << "extern \"C\" void *mlpackGet" << strippedType
<< "Ptr(const char* identifier)" << std::endl;
std::cout << "{" << std::endl;
std::cout << " " << printedType << " *modelptr = GetParamPtr<"
<< printedType << ">(identifier);" << std::endl;
std::cout << " return modelptr;" << std::endl;
std::cout << "}" << std::endl;
std::cout << std::endl;
}
/**
* Print the function to set and get serialization models from Go to mlpack.
*
* @param d Parameter data.
* @param input Unused parameter.
* @param output Unused parameter.
*/
template<typename T>
void PrintModelUtilCPP(const util::ParamData& d,
const void* /* input */,
void* /* output */)
{
PrintModelUtilCPP<typename std::remove_pointer<T>::type>(d);
}
/**
* Non-serializable models don't require any special definitions, so this prints
* nothing.
*/
template<typename T>
void PrintModelUtilH(
const util::ParamData& /* d */,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Do nothing.
}
/**
* Matrices don't require any special definitions, so this prints nothing.
*/
template<typename T>
void PrintModelUtilH(
const util::ParamData& /* d */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// Do nothing.
}
/**
* Matrices with Info don't require any special definitions, so this prints nothing.
*/
template<typename T>
void PrintModelUtilH(
const util::ParamData& /* d */,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Do nothing.
}
/**
* Serializable models require a special class definition.
*/
template<typename T>
void PrintModelUtilH(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// First, we have to parse the type. If we have something like, e.g.,
// 'LogisticRegression<>', we must convert this to 'LogisticRegression[].'
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
/**
* This gives us code like:
*
* extern void *mlpackSet<Type>Ptr(const char* identifier, void* value);
*
*/
std::cout << "extern void mlpackSet" << strippedType
<< "Ptr(const char* identifier, void* value);" << std::endl;
std::cout << std::endl;
/**
* This gives us code like:
*
* extern void *mlpackGet<Type>Ptr(const char* identifier);
*
*/
std::cout << "extern void *mlpackGet" << strippedType
<< "Ptr(const char* identifier);" << std::endl;
std::cout << std::endl;
}
/**
* Print the function to set and get serialization models from Go to mlpack.
*
* @param d Parameter data.
* @param input Unused parameter.
* @param output Unused parameter.
*/
template<typename T>
void PrintModelUtilH(const util::ParamData& d,
const void* /* input */,
void* /* output */)
{
PrintModelUtilH<typename std::remove_pointer<T>::type>(d);
}
/**
* Non-serializable models don't require any special definitions, so this prints
* nothing.
*/
template<typename T>
void PrintModelUtilGo(
const util::ParamData& /* d */,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Do nothing.
}
/**
* Matrices don't require any special definitions, so this prints nothing.
*/
template<typename T>
void PrintModelUtilGo(
const util::ParamData& /* d */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// Do nothing.
}
/**
* Matrices with Info don't require any special definitions, so this prints nothing.
*/
template<typename T>
void PrintModelUtilGo(
const util::ParamData& /* d */,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
// Do nothing.
}
/**
* Serializable models require a special class definition.
*/
template<typename T>
void PrintModelUtilGo(
const util::ParamData& d,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// First, we have to parse the type. If we have something like, e.g.,
// 'LogisticRegression<>', we must convert this to 'LogisticRegression[].'
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
/**
* This gives us code like:
*
* type <Type> struct {
* mem unsafe.Pointer
* }
*
*/
std::cout << "type " << goStrippedType << " struct {" << std::endl;
std::cout << " mem unsafe.Pointer" << std::endl;
std::cout << "}" << std::endl;
std::cout << std::endl;
/**
* This gives us code like:
*
* func (m *<Type>) alloc<Type>(identifier string) {
* m.mem = C.mlpackGet<Type>Ptr(C.CString(identifier))
* runtime.KeepAlive(m)
* }
*
*/
std::cout << "func (m *" << goStrippedType << ") alloc"
<< strippedType << "(identifier string) {" << std::endl;
std::cout << " m.mem = C.mlpackGet" << strippedType
<< "Ptr(C.CString(identifier))" << std::endl;
std::cout << " runtime.KeepAlive(m)" << std::endl;
std::cout << "}" << std::endl;
std::cout << std::endl;
/**
* This gives us code like:
*
* func (m *<Type>) get<Type>(identifier string) {
* m.alloc<Type>(identifier)
* time.Sleep(time.Second)
* runtime.GC()
* }
*
*/
std::cout << "func (m *" << goStrippedType << ") get"
<< strippedType << "(identifier string) {" << std::endl;
std::cout << " m.alloc" << strippedType << "(identifier)" << std::endl;
std::cout << "}" << std::endl;
std::cout << std::endl;
// Print function to set specified mlpack parameter object ptr from Go.
std::cout << "func set" << strippedType
<< "(identifier string, ptr *" << goStrippedType << ") {"
<< std::endl;
std::cout << " C.mlpackSet" << strippedType
<< "Ptr(C.CString(identifier), (unsafe.Pointer)(ptr.mem))"
<< std::endl;
std::cout << "}" << std::endl;
std::cout << std::endl;
}
/**
* Print the Go struct for Go serialization model and their associated
* set and get methods.
*
* @param d Parameter data.
* @param input Unused parameter.
* @param output Unused parameter.
*/
template<typename T>
void PrintModelUtilGo(const util::ParamData& d,
const void* /* input */,
void* /* output */)
{
PrintModelUtilGo<typename std::remove_pointer<T>::type>(d);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,157 @@
/**
* @file print_output_processing.hpp
* @author Yasmine Dumouchel
*
* Print the output processing in a Go binding .go file for a given
* parameter.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_OUTPUT_PROCESSING_HPP
#define MLPACK_BINDINGS_GO_PRINT_OUTPUT_PROCESSING_HPP
#include <mlpack/prereqs.hpp>
#include "get_type.hpp"
#include "strip_type.hpp"
#include "camel_case.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Print output processing for a regular parameter type.
*/
template<typename T>
void PrintOutputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
/**
* This gives us code like:
*
* <paramName> := GetParam<Type>("paramName")
*
*/
std::string name = d.name;
name = CamelCase(name);
std::cout << prefix << name << " := getParam" << GetType<T>(d)
<< "(\"" << d.name << "\")" << std::endl;
}
/**
* Print output processing for a matrix type.
*/
template<typename T>
void PrintOutputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0,
const typename std::enable_if<!std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>::value>::type* = 0)
{
const std::string prefix(indent, ' ');
/**
* This gives us code like:
*
* var <paramName>_ptr mlpackArma
* <paramName> := <paramName>_ptr.ArmaToGonum_<Type>("paramName")
*
*/
std::string name = d.name;
name = CamelCase(name);
std::string dname = CamelCase(name);
name[0] = std::tolower(name[0]);
std::cout << prefix << "var " << name << "Ptr mlpackArma" << std::endl;
std::cout << prefix << dname << " := " << name
<< "Ptr.armaToGonum" << GetType<T>(d)
<< "(\"" << d.name << "\")" << std::endl;
}
/**
* Print output processing for a matrix with info type.
*/
template<typename T>
void PrintOutputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0)
{
const std::string prefix(indent, ' ');
/**
* This gives us code like:
*
* var <paramName>_ptr mlpackArma
* <paramName> := <paramName>_ptr.ArmaToGonumWithInfo<Type>("paramName")
*
*/
std::string name = d.name;
name = CamelCase(name);
std::string dname = CamelCase(name);
name[0] = std::tolower(name[0]);
std::cout << prefix << "var " << name << "Ptr mlpackArma" << std::endl;
std::cout << prefix << dname << " := " << name << "Ptr.armaToGonumWith"
<< "Info(\"" << d.name << "\")" << std::endl;
}
/**
* Print output processing for a serializable model.
*/
template<typename T>
void PrintOutputProcessing(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// Get the type names we need to use.
std::string goStrippedType, strippedType, printedType, defaultsType;
StripType(d.cppType, goStrippedType, strippedType, printedType, defaultsType);
const std::string prefix(indent, ' ');
/**
* This gives us code like:
*
* var <paramName> <Type>
* <paramName> = get<Type>("paramName")
*
*/
std::string name = d.name;
name = CamelCase(name);
std::cout << prefix << "var " << name << " " << goStrippedType << std::endl;
std::cout << prefix << name << ".get" << strippedType
<< "(\"" << d.name << "\")" << std::endl;
}
/**
* @param d Parameter data struct.
* @param input Unused parameter.
* @param output Unused parameter.
*/
template<typename T>
void PrintOutputProcessing(const util::ParamData& d,
const void* /*input*/,
void* /* output */)
{
PrintOutputProcessing<typename std::remove_pointer<T>::type>(d, 2);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+81
View File
@@ -0,0 +1,81 @@
/**
* @file print_type_doc.hpp
* @author Yashwant Singh
*
* Print documentation for a given type, detailing what the type actually is to
* the user.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_TYPE_DOC_HPP
#define MLPACK_BINDINGS_GO_PRINT_TYPE_DOC_HPP
#include <mlpack/core/util/is_std_vector.hpp>
namespace mlpack {
namespace bindings {
namespace go {
/**
* Return a string representing the command-line type of an option.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<util::IsStdVector<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type* = 0);
/**
* Return a string representing the command-line type of a vector.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename std::enable_if<util::IsStdVector<T>::value>::type* = 0);
/**
* Return a string representing the command-line type of a matrix option.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename std::enable_if<arma::is_arma_type<T>::value>::type* = 0);
/**
* Return a string representing the command-line type of a matrix tuple option.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename std::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>::value>::type* = 0);
/**
* Return a string representing the command-line type of a model.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0);
/**
* Print the command-line type of an option into a string.
*/
template<typename T>
void PrintTypeDoc(const util::ParamData& data,
const void* /* input */,
void* output)
{
*((std::string*) output) =
PrintTypeDoc<typename std::remove_pointer<T>::type>(data);
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#include "print_type_doc_impl.hpp"
#endif
@@ -0,0 +1,141 @@
/**
* @file print_type_doc_impl.hpp
* @author Yashwant Singh
*
* Print documentation for a given type.
*/
#ifndef MLPACK_BINDINGS_GO_PRINT_TYPE_DOC_IMPL_HPP
#define MLPACK_BINDINGS_GO_PRINT_TYPE_DOC_IMPL_HPP
#include "print_type_doc.hpp"
namespace mlpack {
namespace bindings {
namespace go {
/**
* Return a string representing the command-line type of an option.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename boost::disable_if<arma::is_arma_type<T>>::type*,
const typename boost::disable_if<util::IsStdVector<T>>::type*,
const typename boost::disable_if<data::HasSerialize<T>>::type*,
const typename boost::disable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>>::type*)
{
// A flag type.
if (std::is_same<T, bool>::value)
{
return "A boolean flag option (`true` or `false`).";
}
// An integer.
else if (std::is_same<T, int>::value)
{
return "An integer (i.e., `1`).";
}
// A floating point value.
else if (std::is_same<T, double>::value)
{
return "A floating-point number (i.e., `0.5`).";
}
// A string.
else if (std::is_same<T, std::string>::value)
{
return "A character string (i.e., `\"hello\"`).";
}
// Not sure what it is...
else
{
throw std::invalid_argument("unknown parameter type " + data.cppType);
}
}
/**
* Return a string representing the command-line type of a vector.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename std::enable_if<util::IsStdVector<T>::value>::type*)
{
if (std::is_same<T, std::vector<int>>::value)
{
return "An array of integers; i.e., `[]int{0, 1, 2}`.";
}
else if (std::is_same<T, std::vector<std::string>>::value)
{
return "An array of strings; i.e., `[]string{\"hello\", \"goodbye\"}`.";
}
else
{
throw std::invalid_argument("unknown vector type " + data.cppType);
}
}
/**
* Return a string representing the command-line type of a matrix option.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& data,
const typename std::enable_if<arma::is_arma_type<T>::value>::type*)
{
if (std::is_same<typename T::elem_type, double>::value
|| std::is_same<typename T::elem_type, size_t>::value)
{
if (T::is_col || T::is_row)
{
return "A 1-d gonum Matrix (that is, a Matrix where either the number"
" of rows or number of columns is 1)";
}
else
{
return "A 2-d arraylike containing data. This can be a gonum matrix. "
"If the type is not already float64, it will be converted.";
}
}
else
{
throw std::invalid_argument("unknown matrix type " + data.cppType);
}
}
/**
* Return a string representing the command-line type of a matrix tuple option.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& /* data */,
const typename std::enable_if<std::is_same<T,
std::tuple<data::DatasetInfo, arma::mat>>::value>::type*)
{
return "A Tuple(MatrixWithInfo) containing `float64` data (Data) along with a"
" boolean array (Categories) indicating which dimensions are categorical "
"(represented by `true`) and which are numeric (represented by `false`)."
" The number of elements in the boolean array should be the same as the"
" dimensionality of the data matrix. It is expected that each row of the"
" matrix corresponds to a single data point when calling mlpack bindings.";
}
/**
* Return a string representing the command-line type of a model.
*/
template<typename T>
std::string PrintTypeDoc(
const util::ParamData& /* data */,
const typename boost::disable_if<arma::is_arma_type<T>>::type*,
const typename boost::enable_if<data::HasSerialize<T>>::type*)
{
return "An mlpack model pointer. This type can be pickled to or from disk, "
"and internally holds a pointer to C++ memory containing the mlpack "
"model. Note that this means that the mlpack model itself cannot be "
"easily inspected in Go;";
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
+74
View File
@@ -0,0 +1,74 @@
/**
* @file strip_type.hpp
* @author Yasmine Dumouchel
*
* Given a C++ typename that may have template parameters, return stripped and
* printable versions to be used in Go bindings.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_BINDINGS_GO_STRIP_TYPE_HPP
#define MLPACK_BINDINGS_GO_STRIP_TYPE_HPP
namespace mlpack {
namespace bindings {
namespace go {
/**
* Given an input type like, e.g., "LogisticRegression<>", return four types
* that can be used in Go code. goStrippedType will be a type with lower first
* letter of parameter name so it is of unexported type in GoDoc
* (e.g. "logisticRegression"), strippedType will be a type with no
* template parameters (e.g. "LogisticRegression"), printedType will be a
* printable type with the template parameters (e.g. "LogisticRegression<>"),
* and defaultsType will be a printable type with a default template parameter
* (e.g. "LogisticRegression<T>") that can be used for class definitions.
*/
inline void StripType(const std::string& inputType,
std::string& goStrippedType,
std::string& strippedType,
std::string& printedType,
std::string& defaultsType)
{
// First, we have to parse the type. If we have something like, e.g.,
// 'LogisticRegression<>', we must convert this to 'LogisticRegression<T>.'
goStrippedType = inputType;
printedType = inputType;
strippedType = inputType;
defaultsType = inputType;
// Lower the first letter of parameter name so it is
// of unexported type in GoDoc.
for (size_t i = 0; i < goStrippedType.size(); i++)
{
goStrippedType[i] = std::tolower(goStrippedType[i]);
if (std::isupper(goStrippedType[i+1]) && !std::isupper(goStrippedType[i+2]))
{
if (isalpha(goStrippedType[i+2]))
break;
}
}
if (printedType.find("<") != std::string::npos)
{
// Are there any template parameters? Or is it the default?
const size_t loc = printedType.find("<>");
if (loc != std::string::npos)
{
// Convert it from "<>".
goStrippedType.replace(loc, 2, "");
strippedType.replace(loc, 2, "");
printedType.replace(loc, 2, "<>");
defaultsType.replace(loc, 2, "<T>");
}
}
}
} // namespace go
} // namespace bindings
} // namespace mlpack
#endif
@@ -0,0 +1,10 @@
# Add the Go binding test.
add_go_binding(test_go_binding)
if (BUILD_GO_BINDINGS)
add_test(NAME go_binding_test
COMMAND go test -v ${CMAKE_CURRENT_SOURCE_DIR}/go_binding_test.go
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/)
set_tests_properties(go_binding_test
PROPERTIES ENVIRONMENT "GOPATH=$ENV{GOPATH}:${CMAKE_BINARY_DIR};LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}:${CMAKE_BINARY_DIR}/src/mlpack/bindings/go/mlpack/")
endif()
@@ -0,0 +1,596 @@
package main
import (
"mlpack/bindings/go/mlpack"
"testing"
"gonum.org/v1/gonum/mat"
)
func TestRunBindingNoFlag(t *testing.T) {
t.Log("Test that when we run the binding correctly (with correct",
"input parameters), we get the expected output.")
param := mlpack.InitializeTestGoBinding()
d := 4.0
i := 12
s := "hello"
_, DoubleOut, IntOut, _, _, _, _, _, _, StringOut, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
if DoubleOut == 5.0 {
t.Errorf("Error. Wrong DoubleOut value.")
}
if IntOut == 13 {
t.Errorf("Error. Wrong IntOut value.")
}
if StringOut == "hello2" {
t.Errorf("Error. Wrong StringOut value.")
}
}
func TestRunBindingCorrectly(t *testing.T) {
t.Log("Test that if we forget the mandatory flag, we should get wrong",
"results.")
param := mlpack.InitializeTestGoBinding()
param.Flag1 = true
d := 4.0
i := 12
s := "hello"
_, DoubleOut, IntOut, _, _, _, _, _, _, StringOut, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
if DoubleOut != 5.0 {
t.Errorf("Error. Wrong DoubleOut value.")
}
if IntOut != 13 {
t.Errorf("Error. Wrong IntOut value.")
}
if StringOut != "hello2" {
t.Errorf("Error. Wrong StringOut value.")
}
}
func TestRunBindingWrongString(t *testing.T) {
t.Log("Test that if we give the wrong string, we should get wrong results.")
param := mlpack.InitializeTestGoBinding()
param.Flag1 = true
d := 4.0
i := 12
s := "goodbye"
_, _, _, _, _, _, _, _, _, StringOut, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
if StringOut == "hello2" {
t.Errorf("Error. Wrong StringOut value.")
}
}
func TestRunBindingWrongInt(t *testing.T) {
t.Log("Test that if we give the wrong int, we should get wrong results.")
param := mlpack.InitializeTestGoBinding()
param.Flag1 = true
d := 4.0
i := 15
s := "hello"
_, _, IntOut, _, _, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
if IntOut == 13 {
t.Errorf("Error. Wrong IntOut value.")
}
}
func TestRunBindingWrongDouble(t *testing.T) {
t.Log("Test that if we give the wrong double, we should get wrong results.")
param := mlpack.InitializeTestGoBinding()
param.Flag1 = true
d := 2.0
i := 12
s := "hello"
_, DoubleOut, _, _, _, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
if DoubleOut == 5.0 {
t.Errorf("Error. Wrong DoubleOut value.")
}
}
func TestRunBadFlag(t *testing.T) {
t.Log("Testing that if we give a second flag, it should fail.")
param := mlpack.InitializeTestGoBinding()
param.Flag1 = true
param.Flag2 = true
d := 2.0
i := 12
s := "hello"
_, DoubleOut, IntOut, _, _, _, _, _, _, StringOut, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
if DoubleOut == 5.0 {
t.Errorf("Error. Wrong DoubleOut value.")
}
if IntOut == 13 {
t.Errorf("Error. Wrong IntOut value.")
}
if StringOut == "hello2" {
t.Errorf("Error. Wrong StringOut value.")
}
}
func TestGonumMatrix(t *testing.T) {
t.Log("Test that the matrix we get back should be the matrix we pass in",
"with the third dimension doubled and the fifth forgotten.")
x := mat.NewDense(3, 5, []float64{
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
})
y := mat.NewDense(3, 4, []float64{
1, 2, 6, 4,
6, 7, 16, 9,
11, 12, 26, 14,
})
param := mlpack.InitializeTestGoBinding()
param.MatrixIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, MatrixOut, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
rows, cols := MatrixOut.Dims()
if rows != 3 || cols != 4 {
panic("error shape")
}
var z mat.Dense
z.Sub(MatrixOut, y)
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
if val := z.At(i, j); val != 0 {
t.Errorf("Error. Value at [i,j] : %v", val)
}
}
}
}
func TestGonumUMatrix(t *testing.T) {
t.Log("Test that the umatrix we get back should be the umatrix we pass",
"in with the third dimension doubled and the fifth forgotten.")
x := mat.NewDense(3, 5, []float64{
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
})
y := mat.NewDense(3, 4, []float64{
1, 2, 6, 4,
6, 7, 16, 9,
11, 12, 26, 14,
})
param := mlpack.InitializeTestGoBinding()
param.UmatrixIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, _, _, _, UmatrixOut, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
rows, cols := UmatrixOut.Dims()
if rows != 3 || cols != 4 {
panic("error shape")
}
var z mat.Dense
z.Sub(UmatrixOut, y)
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
if val := z.At(i, j); val != 0 {
t.Errorf("Error. Value at [i,j] : %v", val)
}
}
}
}
func TestGonumTransposeRow(t *testing.T) {
t.Log("Test a column vector input parameter.")
x := mat.NewDense(1, 9, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.RowIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, RowOut, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
rows, _ := RowOut.Dims()
if rows != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < rows; i++ {
if RowOut.At(i, 0) != x.At(0, i)*2 {
val := RowOut.At(i, 0)
expected := x.At(0, i) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumTransposeURow(t *testing.T) {
t.Log("Test a column vector input parameter.")
x := mat.NewDense(1, 9, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.UrowIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, _, _, _, _, UrowOut, _ :=
mlpack.TestGoBinding(d, i, s, param)
urows, _ := UrowOut.Dims()
if urows != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < urows; i++ {
if UrowOut.At(i, 0) != x.At(0, i)*2 {
val := UrowOut.At(i, 0)
expected := x.At(0, i) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumTransposeCol(t *testing.T) {
t.Log("Test a row vector input parameter.")
x := mat.NewDense(9, 1, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.ColIn = x
d := 4.0
i := 12
s := "hello"
ColOut, _, _, _, _, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
_, cols := ColOut.Dims()
if cols != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < cols; i++ {
if ColOut.At(0, i) != x.At(i, 0)*2 {
val := ColOut.At(0, i)
expected := x.At(i, 0) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumTransposeUCol(t *testing.T) {
t.Log("Test a row vector input parameter.")
x := mat.NewDense(9, 1, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.UcolIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, _, _, UcolOut, _, _, _:=
mlpack.TestGoBinding(d, i, s, param)
_, ucols := UcolOut.Dims()
if ucols != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < ucols; i++ {
if UcolOut.At(0, i) != x.At(i, 0)*2 {
val := UcolOut.At(0, i)
expected := x.At(i, 0) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumRow(t *testing.T) {
t.Log("Test a row vector input parameter.")
x := mat.NewDense(9, 1, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.RowIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, RowOut, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
rows, _ := RowOut.Dims()
if rows != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < rows; i++ {
if RowOut.At(i, 0) != x.At(i, 0)*2 {
val := RowOut.At(i, 0)
expected := x.At(i, 0) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumURow(t *testing.T) {
t.Log("Test a row vector input parameter.")
x := mat.NewDense(9, 1, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.UrowIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, _, _, _, _, UrowOut, _ :=
mlpack.TestGoBinding(d, i, s, param)
urows, _ := UrowOut.Dims()
if urows != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < urows; i++ {
if UrowOut.At(i, 0) != x.At(i, 0)*2 {
val := UrowOut.At(i, 0)
expected := x.At(i, 0) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumCol(t *testing.T) {
t.Log("Test a column vector input parameter.")
x := mat.NewDense(1, 9, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.ColIn = x
d := 4.0
i := 12
s := "hello"
ColOut, _, _, _, _, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
_, cols := ColOut.Dims()
if cols != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < cols; i++ {
if ColOut.At(0, i) != x.At(0, i)*2 {
val := ColOut.At(0, i)
expected := x.At(0, i) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumUCol(t *testing.T) {
t.Log("Test a column vector input parameter.")
x := mat.NewDense(1, 9, []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9,
})
param := mlpack.InitializeTestGoBinding()
param.UcolIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, _, _, UcolOut, _, _, _:=
mlpack.TestGoBinding(d, i, s, param)
_, ucols := UcolOut.Dims()
if ucols != 9 {
t.Errorf("Error. Wrong shape.")
}
for i := 0; i < ucols; i++ {
if UcolOut.At(0, i) != x.At(0, i)*2 {
val := UcolOut.At(0, i)
expected := x.At(0, i) * 2
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumWrongRow(t *testing.T) {
t.Log("Test a wrong shape row vector input parameter.")
// A defer statement defers the execution of a function until
// the surrounding function returns.
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
x := mat.NewDense(3, 5, []float64{
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
})
param := mlpack.InitializeTestGoBinding()
param.RowIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, _, RowOut, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
_, err := RowOut.Dims()
if err == 1 {
t.Errorf("Error. Working.")
}
}
func TestGonumWrongCol(t *testing.T) {
t.Log("Test a wrong shape column vector input parameter.")
// A defer statement defers the execution of a function until
// the surrounding function returns.
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
x := mat.NewDense(3, 5, []float64{
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
})
param := mlpack.InitializeTestGoBinding()
param.RowIn = x
d := 4.0
i := 12
s := "hello"
ColOut, _, _, _, _, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
err, _ := ColOut.Dims()
if err == 1 {
t.Errorf("Error. Working.")
}
}
func TestRunIntVector(t *testing.T) {
t.Log("Test a int vector input paramter.")
param := mlpack.InitializeTestGoBinding()
x := []int{
1, 2, 3, 4, 5, 6,
}
param.VectorIn = x
d := 2.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, _, _, _, _, _, VectorOut :=
mlpack.TestGoBinding(d, i, s, param)
length := len(VectorOut)
if length != 5 {
t.Errorf("Error. Wrong Length.")
}
for i := 0; i < length; i++ {
if x[i] != VectorOut[i]{
val := VectorOut[i]
expected := x[i]
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestRunStringVector(t *testing.T) {
t.Log("Test a string vector input paramter.")
param := mlpack.InitializeTestGoBinding()
x := []string{
"1", "2", "3", "4", "5", "6",
}
param.StrVectorIn = x
d := 2.0
i := 12
s := "hello"
_, _, _, _, _, _, _, _, StrVectorOut, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
length := len(StrVectorOut)
if length != 5 {
t.Errorf("Error. Wrong Length.")
}
for i := 0; i < length; i++ {
if x[i] != StrVectorOut[i] {
val := StrVectorOut[i]
expected := x[i]
t.Errorf("Error. Value at [i] : %v. Expected value : %v",
val, expected)
}
}
}
func TestGonumMatrixWithInfo(t *testing.T) {
t.Log("Test that the matrix_withInfo we get back should be the ",
"matrix_withInfo we pass in with double the element of the matrix .")
x := mlpack.DataAndInfo()
x.Categories = []bool{
false, false, false, false, false,
}
x.Data = mat.NewDense(3, 5, []float64{
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
})
param := mlpack.InitializeTestGoBinding()
param.MatrixAndInfoIn = x
d := 4.0
i := 12
s := "hello"
_, _, _, MatrixAndInfoOut, _, _, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
rows, cols := MatrixAndInfoOut.Dims()
if rows != 3 || cols != 5 {
t.Errorf("Error. Wrong shape. %v, %v", rows, cols)
}
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
if x.Data.At(i, j)*2 != MatrixAndInfoOut.At(i, j) {
val := MatrixAndInfoOut.At(i, j)
expected := x.Data.At(i, j)*2
t.Errorf("Error. Value at [%v,%v] : %v. Expected value : %v",
i, j, val, expected)
}
}
}
}
func TestModel(t *testing.T) {
t.Log("First create a GaussianKernel object, then send it back and",
"make sure we get the right double value.")
param := mlpack.InitializeTestGoBinding()
param.BuildModel = true
d := 4.0
i := 12
s := "hello"
_, _, _, _, _, _, ModelOut, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param)
param2 := mlpack.InitializeTestGoBinding()
param2.ModelIn = &ModelOut
_, _, _, _, _, ModelBwOut, _, _, _, _, _, _, _, _ :=
mlpack.TestGoBinding(d, i, s, param2)
if ModelBwOut != 20.0 {
t.Errorf("Error. Wrong model.")
}
}
@@ -0,0 +1,190 @@
/**
* @file julia_binding_test.cpp
* @author Yashwant Singh
*
* A binding test for Golang.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include <mlpack/core/kernels/gaussian_kernel.hpp>
using namespace std;
using namespace mlpack;
using namespace mlpack::kernel;
PROGRAM_INFO("Golang binding test",
"A simple program to test Golang binding functionality.",
"A simple program to test Golang binding functionality. You can build "
"mlpack with the BUILD_TESTS option set to off, and this binding will "
"no longer be built.");
PARAM_STRING_IN_REQ("string_in", "Input string, must be 'hello'.", "s");
PARAM_INT_IN_REQ("int_in", "Input int, must be 12.", "i");
PARAM_DOUBLE_IN_REQ("double_in", "Input double, must be 4.0.", "d");
PARAM_FLAG("flag1", "Input flag, must be specified.", "f");
PARAM_FLAG("flag2", "Input flag, must not be specified.", "F");
PARAM_MATRIX_IN("matrix_in", "Input matrix.", "m");
PARAM_UMATRIX_IN("umatrix_in", "Input unsigned matrix.", "u");
PARAM_COL_IN("col_in", "Input column.", "c");
PARAM_UCOL_IN("ucol_in", "Input unsigned column.", "");
PARAM_ROW_IN("row_in", "Input row.", "");
PARAM_UROW_IN("urow_in", "Input unsigned row.", "");
PARAM_MATRIX_AND_INFO_IN("matrix_and_info_in", "Input matrix and info.", "");
PARAM_VECTOR_IN(int, "vector_in", "Input vector of numbers.", "");
PARAM_VECTOR_IN(string, "str_vector_in", "Input vector of strings.", "");
PARAM_MODEL_IN(GaussianKernel, "model_in", "Input model.", "");
PARAM_FLAG("build_model", "If true, a model will be returned.", "");
PARAM_STRING_OUT("string_out", "Output string, will be 'hello2'.", "S");
PARAM_INT_OUT("int_out", "Output int, will be 13.");
PARAM_DOUBLE_OUT("double_out", "Output double, will be 5.0.");
PARAM_MATRIX_OUT("matrix_out", "Output matrix.", "M");
PARAM_UMATRIX_OUT("umatrix_out", "Output unsigned matrix.", "U");
PARAM_COL_OUT("col_out", "Output column. 2x input column", "");
PARAM_UCOL_OUT("ucol_out", "Output unsigned column. 2x input column.", "");
PARAM_ROW_OUT("row_out", "Output row. 2x input row.", "");
PARAM_UROW_OUT("urow_out", "Output unsigned row. 2x input row.", "");
PARAM_MATRIX_OUT("matrix_and_info_out", "Output matrix and info; all numeric "
"elements multiplied by 3.", "");
PARAM_VECTOR_OUT(int, "vector_out", "Output vector.", "");
PARAM_VECTOR_OUT(string, "str_vector_out", "Output string vector.", "");
PARAM_MODEL_OUT(GaussianKernel, "model_out", "Output model, with twice the "
"bandwidth.", "");
PARAM_DOUBLE_OUT("model_bw_out", "The bandwidth of the model.");
static void mlpackMain()
{
const string s = CLI::GetParam<string>("string_in");
const int i = CLI::GetParam<int>("int_in");
const double d = CLI::GetParam<double>("double_in");
CLI::GetParam<string>("string_out") = "wrong";
CLI::GetParam<int>("int_out") = 11;
CLI::GetParam<double>("double_out") = 3.0;
// Check that everything is right on the input, and then set output
// accordingly.
if (!CLI::HasParam("flag2") && CLI::HasParam("flag1"))
{
if (s == "hello")
CLI::GetParam<string>("string_out") = "hello2";
if (i == 12)
CLI::GetParam<int>("int_out") = 13;
if (d == 4.0)
CLI::GetParam<double>("double_out") = 5.0;
}
// Input matrices should be at least 5 rows; the 5th row will be dropped and
// the 3rd row will be multiplied by two.
if (CLI::HasParam("matrix_in"))
{
arma::mat out = move(CLI::GetParam<arma::mat>("matrix_in"));
out.shed_row(4);
out.row(2) *= 2.0;
CLI::GetParam<arma::mat>("matrix_out") = move(out);
}
// Input matrices should be at least 5 rows; the 5th row will be dropped and
// the 3rd row will be multiplied by two.
if (CLI::HasParam("umatrix_in"))
{
arma::Mat<size_t> out =
move(CLI::GetParam<arma::Mat<size_t>>("umatrix_in"));
out.shed_row(4);
out.row(2) *= 2;
CLI::GetParam<arma::Mat<size_t>>("umatrix_out") = move(out);
}
// An input column or row should have all elements multiplied by two.
if (CLI::HasParam("col_in"))
{
arma::vec out = move(CLI::GetParam<arma::vec>("col_in"));
out *= 2.0;
CLI::GetParam<arma::vec>("col_out") = move(out);
}
if (CLI::HasParam("ucol_in"))
{
arma::Col<size_t> out =
move(CLI::GetParam<arma::Col<size_t>>("ucol_in"));
out *= 2;
CLI::GetParam<arma::Col<size_t>>("ucol_out") = move(out);
}
if (CLI::HasParam("row_in"))
{
arma::rowvec out = move(CLI::GetParam<arma::rowvec>("row_in"));
out *= 2.0;
CLI::GetParam<arma::rowvec>("row_out") = move(out);
}
if (CLI::HasParam("urow_in"))
{
arma::Row<size_t> out =
move(CLI::GetParam<arma::Row<size_t>>("urow_in"));
out *= 2;
CLI::GetParam<arma::Row<size_t>>("urow_out") = move(out);
}
// Vector arguments should have the last element removed.
if (CLI::HasParam("vector_in"))
{
vector<int> out = move(CLI::GetParam<vector<int>>("vector_in"));
out.pop_back();
CLI::GetParam<vector<int>>("vector_out") = move(out);
}
if (CLI::HasParam("str_vector_in"))
{
vector<string> out = move(CLI::GetParam<vector<string>>("str_vector_in"));
out.pop_back();
CLI::GetParam<vector<string>>("str_vector_out") = move(out);
}
// All numeric elements should be multiplied by 3.
if (CLI::HasParam("matrix_and_info_in"))
{
typedef tuple<data::DatasetInfo, arma::mat> TupleType;
TupleType tuple = move(CLI::GetParam<TupleType>("matrix_and_info_in"));
const data::DatasetInfo& di = std::get<0>(tuple);
arma::mat& m = std::get<1>(tuple);
for (size_t i = 0; i < m.n_rows; ++i)
{
if (di.Type(i) == data::Datatype::numeric)
m.row(i) *= 2.0;
}
CLI::GetParam<arma::mat>("matrix_and_info_out") = move(m);
}
// If we got a request to build a model, then build it.
if (CLI::HasParam("build_model"))
{
CLI::GetParam<GaussianKernel*>("model_out") = new GaussianKernel(10.0);
}
// If we got an input model, double the bandwidth and output that.
if (CLI::HasParam("model_in"))
{
CLI::GetParam<double>("model_bw_out") =
CLI::GetParam<GaussianKernel*>("model_in")->Bandwidth() * 2.0;
}
}
@@ -19,6 +19,7 @@
#include <mlpack/bindings/cli/default_param.hpp>
#include <mlpack/bindings/python/default_param.hpp>
#include <mlpack/bindings/julia/default_param.hpp>
#include <mlpack/bindings/go/default_param.hpp>
namespace mlpack {
namespace bindings {
@@ -48,6 +49,11 @@ void DefaultParam(const util::ParamData& data,
*((std::string*) output) =
julia::DefaultParamImpl<typename std::remove_pointer<T>::type>(data);
}
else if (BindingInfo::Language() == "go")
{
*((std::string*) output) =
go::DefaultParamImpl<typename std::remove_pointer<T>::type>(data);
}
else
{
throw std::invalid_argument("DefaultParam(): unknown "
@@ -37,6 +37,11 @@ std::string GetBindingName(const std::string& language,
// For Julia bindings, the name is unchanged.
return name;
}
else if (language == "go")
{
// For Go bindings, the name is unchanged.
return name;
}
else
{
throw std::invalid_argument("Don't know how to compute binding name for "
@@ -18,6 +18,7 @@
#include <mlpack/bindings/cli/get_printable_type.hpp>
#include <mlpack/bindings/python/get_printable_type.hpp>
#include <mlpack/bindings/julia/get_printable_type.hpp>
#include <mlpack/bindings/go/get_printable_type.hpp>
namespace mlpack {
namespace bindings {
@@ -47,6 +48,11 @@ void GetPrintableType(const util::ParamData& data,
*((std::string*) output) =
julia::GetPrintableType<typename std::remove_pointer<T>::type>(data);
}
else if (BindingInfo::Language() == "go")
{
*((std::string*) output) =
go::GetPrintableType<typename std::remove_pointer<T>::type>(data);
}
else
{
throw std::invalid_argument("GetPrintableType(): unknown "
@@ -21,6 +21,7 @@
#include <mlpack/bindings/cli/print_doc_functions.hpp>
#include <mlpack/bindings/python/print_doc_functions.hpp>
#include <mlpack/bindings/julia/print_doc_functions.hpp>
#include <mlpack/bindings/go/print_doc_functions.hpp>
namespace mlpack {
namespace bindings {
@@ -44,6 +45,10 @@ inline std::string GetBindingName(const std::string& bindingName)
{
return julia::GetBindingName(bindingName);
}
else if (BindingInfo::Language() == "go")
{
return go::GetBindingName(bindingName);
}
else
{
throw std::invalid_argument("PrintValue(): unknown "
@@ -68,6 +73,10 @@ inline std::string PrintLanguage(const std::string& language)
{
return "Julia";
}
else if (language == "go")
{
return "Go";
}
else
{
throw std::invalid_argument("PrintLanguage(): unknown "
@@ -92,6 +101,10 @@ inline std::string PrintImport(const std::string& bindingName)
{
return julia::PrintImport(bindingName);
}
else if (BindingInfo::Language() == "go")
{
return go::PrintImport();
}
else
{
throw std::invalid_argument("PrintImport(): unknown "
@@ -116,6 +129,10 @@ inline std::string PrintOutputOptionInfo()
{
return julia::PrintOutputOptionInfo();
}
else if (BindingInfo::Language() == "go")
{
return go::PrintOutputOptionInfo();
}
else
{
throw std::invalid_argument("PrintOutputOptionInfo(): unknown "
@@ -341,6 +358,10 @@ inline std::string PrintValue(const T& value, bool quotes)
{
result = julia::PrintValue(value, quotes);
}
else if (BindingInfo::Language() == "go")
{
result = go::PrintValue(value, quotes);
}
else
{
throw std::invalid_argument("PrintValue(): unknown "
@@ -380,6 +401,10 @@ inline std::string PrintDefault(const std::string& paramName)
{
oss << julia::PrintDefault(paramName);
}
else if (BindingInfo::Language() == "go")
{
oss << go::PrintDefault(paramName);
}
else
{
throw std::invalid_argument("PrintDefault: unknown "
@@ -408,6 +433,10 @@ inline std::string PrintDataset(const std::string& dataset)
{
result = julia::PrintDataset(dataset);
}
else if (BindingInfo::Language() == "go")
{
result = go::PrintDataset(dataset);
}
else
{
throw std::invalid_argument("PrintDataset(): unknown "
@@ -435,6 +464,10 @@ inline std::string PrintModel(const std::string& model)
{
result = julia::PrintModel(model);
}
else if (BindingInfo::Language() == "go")
{
result = go::PrintModel(model);
}
else
{
throw std::invalid_argument("PrintModel(): unknown "
@@ -468,6 +501,11 @@ std::string ProgramCall(const std::string& programName, Args... args)
// the text in Markdown code, so we don't need to.
s += julia::ProgramCall(programName, args...);
}
else if (BindingInfo::Language() == "go")
{
s += "go\n";
s += go::ProgramCall(programName, args...);
}
else
{
throw std::invalid_argument("ProgramCall(): unknown "
@@ -510,6 +548,14 @@ inline std::string ProgramCall(const std::string& programName)
s += "julia> " + import + "\n";
s += julia::ProgramCall(programName);
}
else if (BindingInfo::Language() == "go")
{
s += "go\n";
std::string import = PrintImport(GetBindingName(programName));
if (import.size() > 0)
s += import + "\n";
s += go::ProgramCall(programName);
}
else
{
throw std::invalid_argument("ProgramCall(): unknown "
@@ -543,6 +589,10 @@ inline std::string ParamString(const std::string& paramName)
{
s = julia::ParamString(paramName);
}
else if (BindingInfo::Language() == "go")
{
s = go::ParamString(paramName);
}
else
{
throw std::invalid_argument("ParamString(): unknown "
@@ -586,6 +636,10 @@ inline bool IgnoreCheck(const T& t)
{
return julia::IgnoreCheck(t);
}
else if (BindingInfo::Language() == "go")
{
return go::IgnoreCheck(t);
}
else
{
throw std::invalid_argument("IgnoreCheck(): unknown "
@@ -18,6 +18,7 @@
#include <mlpack/bindings/cli/print_type_doc.hpp>
#include <mlpack/bindings/python/print_type_doc.hpp>
#include <mlpack/bindings/julia/print_type_doc.hpp>
#include <mlpack/bindings/go/print_type_doc.hpp>
namespace mlpack {
namespace bindings {
@@ -42,6 +43,10 @@ std::string PrintTypeDoc(const util::ParamData& data)
{
return julia::PrintTypeDoc<typename std::remove_pointer<T>::type>(data);
}
else if (BindingInfo::Language() == "go")
{
return go::PrintTypeDoc<typename std::remove_pointer<T>::type>(data);
}
else
{
throw std::invalid_argument("PrintTypeDoc(): unknown "
@@ -14,6 +14,7 @@
#include <mlpack/prereqs.hpp>
#include <mlpack/core/math/lin_alg.hpp>
#include <mlpack/core/math/ccov.hpp>
namespace mlpack {
namespace data {
+45
View File
@@ -22,6 +22,7 @@
#define BINDING_TYPE_TEST 1
#define BINDING_TYPE_PYX 2
#define BINDING_TYPE_JL 3
#define BINDING_TYPE_GO 4
#define BINDING_TYPE_MARKDOWN 128
#define BINDING_TYPE_UNKNOWN -1
@@ -281,6 +282,50 @@ static const std::string testName = "";
PARAM_FLAG("verbose", "Display informational messages and the full list of "
"parameters and timers at the end of execution.", "v");
// Nothing else needs to be defined---the binding will use mlpackMain() as-is.
#elif(BINDING_TYPE == BINDING_TYPE_GO) // This is a Go binding.
#include <mlpack/bindings/go/go_option.hpp>
#include <mlpack/bindings/go/print_doc_functions.hpp>
#define PRINT_PARAM_STRING mlpack::bindings::go::ParamString
#define PRINT_PARAM_VALUE mlpack::bindings::go::PrintValue
#define PRINT_DATASET mlpack::bindings::go::PrintDataset
#define PRINT_MODEL mlpack::bindings::go::PrintModel
#define PRINT_CALL mlpack::bindings::go::ProgramCall
#define BINDING_IGNORE_CHECK mlpack::bindings::go::IgnoreCheck
namespace mlpack {
namespace util {
template<typename T>
using Option = mlpack::bindings::go::GoOption<T>;
}
}
static const std::string testName = "";
#include <mlpack/core/util/param.hpp>
#undef PROGRAM_INFO
#define PROGRAM_INFO(NAME, SHORT_DESC, DESC, ...) \
static mlpack::util::ProgramDoc \
cli_programdoc_dummy_object = mlpack::util::ProgramDoc(NAME, SHORT_DESC, \
[]() { return DESC; }, { __VA_ARGS__ }); \
namespace mlpack { \
namespace bindings { \
namespace go { \
std::string programName = NAME; \
} \
} \
}
PARAM_FLAG("verbose", "Display informational messages and the full list of "
"parameters and timers at the end of execution.", "v");
// Nothing else needs to be defined---the binding will use mlpackMain() as-is.
#elif BINDING_TYPE == BINDING_TYPE_MARKDOWN
// We use BINDING_NAME in PROGRAM_INFO() so it needs to be defined.
+2 -1
View File
@@ -19,4 +19,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(adaboost)
add_python_binding(adaboost)
add_julia_binding(adaboost)
add_markdown_docs(adaboost "cli;python;julia" "classification")
add_go_binding(adaboost)
add_markdown_docs(adaboost "cli;python;julia;go" "classification")
+2 -1
View File
@@ -22,4 +22,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(approx_kfn)
add_python_binding(approx_kfn)
add_julia_binding(approx_kfn)
add_markdown_docs(approx_kfn "cli;python;julia" "geometry")
add_go_binding(approx_kfn)
add_markdown_docs(approx_kfn "cli;python;julia;go" "geometry")
+2 -1
View File
@@ -26,4 +26,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(cf)
add_python_binding(cf)
add_julia_binding(cf)
add_markdown_docs(cf "cli;python;julia" "misc. / other")
add_go_binding(cf)
add_markdown_docs(cf "cli;python;julia;go" "misc. / other")
+2 -1
View File
@@ -19,4 +19,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(dbscan)
add_python_binding(dbscan)
add_julia_binding(dbscan)
add_markdown_docs(dbscan "cli;python;julia" "clustering")
add_go_binding(dbscan)
add_markdown_docs(dbscan "cli;python;julia;go" "clustering")
@@ -17,4 +17,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(decision_stump)
add_python_binding(decision_stump)
add_julia_binding(decision_stump)
add_markdown_docs(decision_stump "cli;python;julia" "classification")
add_go_binding(decision_stump)
add_markdown_docs(decision_stump "cli;python;julia;go" "classification")
@@ -26,4 +26,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(decision_tree)
add_python_binding(decision_tree)
add_julia_binding(decision_tree)
add_markdown_docs(decision_tree "cli;python;julia" "classification")
add_go_binding(decision_tree)
add_markdown_docs(decision_tree "cli;python;julia;go" "classification")
+2 -1
View File
@@ -22,4 +22,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(det)
add_python_binding(det)
add_julia_binding(det)
add_markdown_docs(det "cli;python;julia" "misc. / other")
add_go_binding(det)
add_markdown_docs(det "cli;python;julia;go" "misc. / other")
+2 -1
View File
@@ -24,4 +24,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(emst)
add_python_binding(emst)
add_julia_binding(emst)
add_markdown_docs(emst "cli;python;julia" "geometry")
add_go_binding(emst)
add_markdown_docs(emst "cli;python;julia;go" "geometry")
+2 -1
View File
@@ -23,4 +23,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(fastmks)
add_python_binding(fastmks)
add_julia_binding(fastmks)
add_markdown_docs(fastmks "cli;python;julia" "geometry")
add_go_binding(fastmks)
add_markdown_docs(fastmks "cli;python;julia;go" "geometry")
+6 -3
View File
@@ -27,14 +27,17 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(gmm_train)
add_python_binding(gmm_train)
add_julia_binding(gmm_train)
add_markdown_docs(gmm_train "cli;python;julia" "clustering")
add_go_binding(gmm_train)
add_markdown_docs(gmm_train "cli;python;julia;go" "clustering")
add_cli_executable(gmm_generate)
add_python_binding(gmm_generate)
add_julia_binding(gmm_generate)
add_markdown_docs(gmm_generate "cli;python;julia" "clustering")
#add_go_binding(gmm_generate)
add_markdown_docs(gmm_generate "cli;python;julia;go" "clustering")
add_cli_executable(gmm_probability)
add_python_binding(gmm_probability)
add_julia_binding(gmm_probability)
add_markdown_docs(gmm_probability "cli;python;julia" "clustering")
#add_go_binding(gmm_probability)
add_markdown_docs(gmm_probability "cli;python;julia;go" "clustering")
+8 -4
View File
@@ -22,19 +22,23 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(hmm_train)
add_python_binding(hmm_train)
add_julia_binding(hmm_train)
add_markdown_docs(hmm_train "cli;python;julia" "misc. / other")
#add_go_binding(hmm_train)
add_markdown_docs(hmm_train "cli;python;julia;go" "misc. / other")
add_cli_executable(hmm_loglik)
add_python_binding(hmm_loglik)
add_julia_binding(hmm_loglik)
add_markdown_docs(hmm_loglik "cli;python;julia" "misc. / other")
#add_go_binding(hmm_loglik)
add_markdown_docs(hmm_loglik "cli;python;julia;go" "misc. / other")
add_cli_executable(hmm_viterbi)
add_python_binding(hmm_viterbi)
add_julia_binding(hmm_viterbi)
add_markdown_docs(hmm_viterbi "cli;python;julia" "misc. / other")
#add_go_binding(hmm_viterbi)
add_markdown_docs(hmm_viterbi "cli;python;julia;go" "misc. / other")
add_cli_executable(hmm_generate)
add_python_binding(hmm_generate)
add_julia_binding(hmm_generate)
add_markdown_docs(hmm_generate "cli;python;julia" "misc. / other")
#add_go_binding(hmm_generate)
add_markdown_docs(hmm_generate "cli;python;julia;go" "misc. / other")
@@ -31,4 +31,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(hoeffding_tree)
add_python_binding(hoeffding_tree)
add_julia_binding(hoeffding_tree)
add_markdown_docs(hoeffding_tree "cli;python;julia" "classification")
add_go_binding(hoeffding_tree)
add_markdown_docs(hoeffding_tree "cli;python;julia;go" "classification")
+2 -1
View File
@@ -19,4 +19,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(kernel_pca)
add_python_binding(kernel_pca)
add_julia_binding(kernel_pca)
add_markdown_docs(kernel_pca "cli;python;julia" "transformations")
add_go_binding(kernel_pca)
add_markdown_docs(kernel_pca "cli;python;julia;go" "transformations")
+2 -1
View File
@@ -41,4 +41,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(kmeans)
add_python_binding(kmeans)
add_julia_binding(kmeans)
add_markdown_docs(kmeans "cli;python;julia" "clustering")
add_go_binding(kmeans)
add_markdown_docs(kmeans "cli;python;julia;go" "clustering")
+2 -1
View File
@@ -17,4 +17,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(lars)
add_python_binding(lars)
add_julia_binding(lars)
add_markdown_docs(lars "cli;python;julia" "regression")
add_go_binding(lars)
add_markdown_docs(lars "cli;python;julia;go" "regression")
@@ -18,4 +18,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(linear_regression)
add_python_binding(linear_regression)
add_julia_binding(linear_regression)
add_markdown_docs(linear_regression "cli;python;julia" "regression")
add_go_binding(linear_regression)
add_markdown_docs(linear_regression "cli;python;julia;go" "regression")
+2 -1
View File
@@ -19,5 +19,6 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(linear_svm)
add_python_binding(linear_svm)
add_go_binding(linear_svm)
add_julia_binding(linear_svm)
add_markdown_docs(linear_svm "cli;python;julia" "classification")
add_markdown_docs(linear_svm "cli;python;julia;go" "classification")
+2 -1
View File
@@ -21,4 +21,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(lmnn)
add_python_binding(lmnn)
add_julia_binding(lmnn)
add_markdown_docs(lmnn "cli;python;julia" "transformations")
add_go_binding(lmnn)
add_markdown_docs(lmnn "cli;python;julia;go" "transformations")
@@ -21,4 +21,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(local_coordinate_coding)
add_python_binding(local_coordinate_coding)
add_julia_binding(local_coordinate_coding)
add_markdown_docs(local_coordinate_coding "cli;python;julia" "transformations")
add_go_binding(local_coordinate_coding)
add_markdown_docs(local_coordinate_coding "cli;python;julia;go" "transformations")
@@ -20,4 +20,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(logistic_regression)
add_python_binding(logistic_regression)
add_julia_binding(logistic_regression)
add_markdown_docs(logistic_regression "cli;python;julia" "classification")
add_go_binding(logistic_regression)
add_markdown_docs(logistic_regression "cli;python;julia;go" "classification")
@@ -15,6 +15,8 @@
#define MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_FUNCTION_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/core/math/make_alias.hpp>
#include <mlpack/core/math/shuffle_data.hpp>
namespace mlpack {
namespace regression {
+2 -1
View File
@@ -20,4 +20,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(lsh)
add_python_binding(lsh)
add_julia_binding(lsh)
add_markdown_docs(lsh "cli;python;julia" "geometry")
add_go_binding(lsh)
add_markdown_docs(lsh "cli;python;julia;go" "geometry")
+2 -1
View File
@@ -17,4 +17,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(mean_shift)
add_python_binding(mean_shift)
add_julia_binding(mean_shift)
add_markdown_docs(mean_shift "cli;python;julia" "clustering")
add_go_binding(mean_shift)
add_markdown_docs(mean_shift "cli;python;julia;go" "clustering")
@@ -17,4 +17,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(nbc)
add_python_binding(nbc)
add_julia_binding(nbc)
add_markdown_docs(nbc "cli;python;julia" "classification")
add_go_binding(nbc)
add_markdown_docs(nbc "cli;python;julia;go" "classification")
+2 -1
View File
@@ -19,4 +19,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(nca)
add_python_binding(nca)
add_julia_binding(nca)
add_markdown_docs(nca "cli;python;julia" "transformations")
add_go_binding(nca)
add_markdown_docs(nca "cli;python;julia;go" "transformations")
@@ -15,6 +15,8 @@
#include <mlpack/prereqs.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <mlpack/core/math/make_alias.hpp>
#include <mlpack/core/math/shuffle_data.hpp>
namespace mlpack {
namespace nca {
@@ -30,9 +30,11 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(knn)
add_python_binding(knn)
add_julia_binding(knn)
add_markdown_docs(knn "cli;python;julia" "geometry")
add_go_binding(knn)
add_markdown_docs(knn "cli;python;julia;go" "geometry")
add_cli_executable(kfn)
add_python_binding(kfn)
add_julia_binding(kfn)
add_markdown_docs(kfn "cli;python;julia" "geometry")
add_go_binding(kfn)
add_markdown_docs(kfn "cli;python;julia;go" "geometry")
+1
View File
@@ -1,4 +1,5 @@
add_cli_executable(nmf)
add_python_binding(nmf)
add_julia_binding(nmf)
#add_go_binding(nmf)
add_markdown_docs(nmf "cli;python;julia" "misc. / other")
+2 -1
View File
@@ -19,4 +19,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(pca)
add_python_binding(pca)
add_julia_binding(pca)
add_markdown_docs(pca "cli;python;julia" "transformations")
add_go_binding(pca)
add_markdown_docs(pca "cli;python;julia;go" "transformations")
+2 -1
View File
@@ -20,4 +20,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(perceptron)
add_python_binding(perceptron)
add_julia_binding(perceptron)
add_markdown_docs(perceptron "cli;python;julia" "classification")
add_go_binding(perceptron)
add_markdown_docs(perceptron "cli;python;julia;go" "classification")
+12 -6
View File
@@ -19,33 +19,39 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(preprocess_split)
add_python_binding(preprocess_split)
add_julia_binding(preprocess_split)
add_markdown_docs(preprocess_split "cli;python;julia" "preprocessing")
add_go_binding(preprocess_split)
add_markdown_docs(preprocess_split "cli;python;julia;go" "preprocessing")
add_cli_executable(preprocess_binarize)
add_python_binding(preprocess_binarize)
add_julia_binding(preprocess_binarize)
add_markdown_docs(preprocess_binarize "cli;python;julia" "preprocessing")
add_go_binding(preprocess_binarize)
add_markdown_docs(preprocess_binarize "cli;python;julia;go" "preprocessing")
add_cli_executable(preprocess_describe)
add_python_binding(preprocess_describe)
add_julia_binding(preprocess_describe)
add_markdown_docs(preprocess_describe "cli;python;julia" "preprocessing")
add_go_binding(preprocess_describe)
add_markdown_docs(preprocess_describe "cli;python;julia;go" "preprocessing")
#add_cli_executable(preprocess_scan)
add_cli_executable(preprocess_imputer)
#add_go_binding(preprocess_imputer)
#add_python_binding(preprocess_imputer)
#add_julia_binding(preprocess_imputer)
add_markdown_docs(preprocess_imputer "cli" "preprocessing")
add_cli_executable(preprocess_scale)
add_python_binding(preprocess_scale)
add_go_binding(preprocess_scale)
add_julia_binding(preprocess_scale)
add_markdown_docs(preprocess_scale "cli;python;julia" "preprocessing")
add_markdown_docs(preprocess_scale "cli;python;julia;go" "preprocessing")
if (STB_AVAILABLE)
add_cli_executable(image_converter)
add_python_binding(image_converter)
add_julia_binding(image_converter)
add_markdown_docs(image_converter "cli;python;julia" "preprocessing")
endif ()
add_go_binding(image_converter)
add_markdown_docs(image_converter "cli;python;julia;go" "preprocessing")
endif ()
@@ -83,6 +83,7 @@ PARAM_INT_IN("seed", "Random seed (0 for std::time(NULL)).", "s", 0);
PARAM_FLAG("no_shuffle", "Avoid shuffling and splitting the data.", "S");
using namespace mlpack;
using namespace mlpack::data;
using namespace mlpack::util;
using namespace arma;
using namespace std;
+2 -1
View File
@@ -16,4 +16,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(radical)
add_python_binding(radical)
add_julia_binding(radical)
add_markdown_docs(radical "cli;python;julia" "transformations")
add_go_binding(radical)
add_markdown_docs(radical "cli;python;julia;go" "transformations")
@@ -18,4 +18,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(random_forest)
add_python_binding(random_forest)
add_julia_binding(random_forest)
add_markdown_docs(random_forest "cli;python;julia" "classification")
add_go_binding(random_forest)
add_markdown_docs(random_forest "cli;python;julia;go" "classification")
@@ -22,4 +22,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(range_search)
#add_python_binding(range_search)
#add_julia_binding(range_search)
add_markdown_docs(range_search "cli" "geometry")
add_go_binding(range_search)
add_markdown_docs(range_search "cli;go" "geometry")
+2 -1
View File
@@ -38,4 +38,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(krann)
add_python_binding(krann)
add_julia_binding(krann)
add_markdown_docs(krann "cli;python;julia" "geometry")
add_go_binding(krann)
add_markdown_docs(krann "cli;python;julia;go" "geometry")
@@ -20,4 +20,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(softmax_regression)
add_python_binding(softmax_regression)
add_julia_binding(softmax_regression)
add_markdown_docs(softmax_regression "cli;python;julia" "classification")
add_go_binding(softmax_regression)
add_markdown_docs(softmax_regression "cli;python;julia;go" "classification")
@@ -21,4 +21,5 @@ set(MLPACK_SRCS ${MLPACK_SRCS} ${DIR_SRCS} PARENT_SCOPE)
add_cli_executable(sparse_coding)
add_python_binding(sparse_coding)
add_julia_binding(sparse_coding)
add_markdown_docs(sparse_coding "cli;python;julia" "transformations")
add_go_binding(sparse_coding)
add_markdown_docs(sparse_coding "cli;python;julia;go" "transformations")