diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6b7298c --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*~ +#*# +.DS_Store +*.sdf +*.suo +*.opensdf +*.vcxproj.user +*.o +*.d +build*/ +third-party/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..f2acda0 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "viewer"] + path = viewer + url = git@github.com:tfussell/cort.git + branch = gh-pages diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..6667e0e --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.4.3) + +if(NOT DEFINED CMAKE_SUPPRESS_DEVELOPER_WARNINGS) + set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS 1 CACHE INTERNAL "No dev warnings") +endif() + +option(DEBUG "Set to ON to for debug configuration" OFF) +option(ASMJS "Set to OFF to skip compiling ${PROJECT_NAME} as an emscripten library to be run in the browser" ON) +option(SERVER "Set to ON to compile a standalone executable which acts as a server" OFF) + +if(ASMJS) + set(CMAKE_CXX_COMPILER em++) + set(CMAKE_C_COMPILER emcc) + include_directories(SYSTEM /usr/local/include) + set(CMAKE_CXX_CREATE_STATIC_LIBRARY "em++ -o ") +endif() + + +project(cort) + + +if(ASMJS) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-warn-absolute-paths") +endif() + +if(CMAKE_CONFIGURATION_TYPES) + if(DEBUG) + set(CMAKE_BUILD_TYPE "Debug") + else() + set(CMAKE_BUILD_TYPE "Release") + endif() +endif() + +if(APPLE) + execute_process(COMMAND "sw_vers -productVersion | awk -F'.' '{print $1\".\"$2}'" + OUTPUT_VARIABLE OSX_VERSION) + set(CMAKE_OSX_DEPLOYMENT_TARGET ${OSX_VERSION}) +endif(APPLE) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + +set(PROJECT_VENDOR "Thomas Fussell") +set(PROJECT_CONTACT "thomas.fussell@gmail.com") +set(PROJECT_URL "https://github.com/tfussell/cort") +set(PROJECT_DESCRIPTION "A biological neural network simulation platform") + +set(PROJECT_VERSION_MAJOR "0") +set(PROJECT_VERSION_MINOR "9") +set(PROJECT_VERSION_PATCH "0") +set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}") +set(PROJECT_VERSION_FULL "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") + +set(LIBRARY_VERSION ${PROJECT_VERSION_FULL}) + +include_directories(source) + +file(GLOB BRAIN_SOURCES source/brain/*.*pp) +source_group(brain FILES ${BRAIN_SOURCES}) +file(GLOB INTERFACE_SOURCES source/interface/*.*pp) +source_group(interface FILES ${INTERFACE_SOURCES}) +file(GLOB MATH_SOURCES source/math/*.*pp) +source_group(math FILES ${MATH_SOURCES}) +file(GLOB SIMULATION_SOURCES source/simulation/*.*pp) +source_group(simulation FILES ${SIMULATION_SOURCES}) + +set(SOURCES ${BRAIN_SOURCES} ${INTERFACE_SOURCES} ${MATH_SOURCES} ${SIMULATION_SOURCES}) + +if(SERVER) + file(GLOB SERVER_SOURCES source/server/*.*pp) + source_group(server FILES ${SERVER_SOURCES}) + + add_executable(cort ${SOURCES} ${SERVER_SOURCES}) + target_link_libraries(cort boost_system) + + add_custom_command(TARGET cort + POST_BUILD + COMMAND cp cort ../viewer + COMMAND cd ../viewer && ./cort + DEPENDS cort) +else() + file(GLOB EMBIND_SOURCES source/embind/*.*pp) + source_group(embind FILES ${EMBIND_SOURCES}) + + add_library(cort.js STATIC ${SOURCES} ${EMBIND_SOURCES}) + + set_target_properties(cort.js PROPERTIES PREFIX "") + set_target_properties(cort.js PROPERTIES SUFFIX ".bc") + + add_custom_command(TARGET cort.js + POST_BUILD + COMMAND emcc cort.js.bc -o cort.js --bind + COMMAND cp cort.js ../viewer/js/cort.js + COMMAND cd ../viewer && python3 -m http.server + DEPENDS cort.js.bc) +endif() diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cd13356 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2006-2014 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f8dceea --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +
+==== +cort is a platform for simulating, exploring, evolving, and interacting with biologically-inspired neural networks. It is written in C++, but can be compiled into JavaScript using Emscripten for easy cross-platform deployment. + +To try cort, click on [this demo](http://tfussell.github.io/cort/demo). + +Build +===== +This repository includes the latest emscripten compiled version of cort in bin/cort.html. If you'd like to compile cort yourself, make sure you have a C++ compiler that supports C++11, an updated browser, and emscripten. + +1. Copy repository + + git clone https://github.com/tfussell/cort +2. Compile using premake and platform build system + + cd cort/build && ./build-emscripten.sh +3. Run/view the simulation + + open cort/bin/cort.html + +License +======= +cort is licenced under the MIT license. +cort uses a modified version of [nxxcxx's Neural-Network](https://github.com/nxxcxx/Neural-Network) for visualization which is in turn based on [three.js](http://threejs.org). Both of these are also licensed under the MIT license. diff --git a/docs/intro.md b/docs/intro.md new file mode 100644 index 0000000..2d5992a --- /dev/null +++ b/docs/intro.md @@ -0,0 +1,12 @@ +Structure +========= +cort uses a modified client-server model. The optional client-side allows for visualization of and interaction with the current simulation and runs in the browser. The server-side is a simulation written in C++ containing a brain model defined by a JSON file. +From highest to lowest level, the structure of the server-side looks like: +Simulation - A simulation holds zero or more entities. There is only one simulation per instance of Cort. The simulation proceeds in a series of steps. In each step, every entity is updated in an arbitrary order. Every step represents a predetermined amount of time. A simulation continues until the application exits. +Entity - An entity is anything that can be simulated indepedently of other entities. It receives its inputs from other entities and the environment (part of the Simulation) and then creates outputs which affect other entities or change the environment. Every entity is created based on a JSON file. +Brain(Entity) - A brain is a type of entity. A brain is composed of zero or more layers. +Layer - A layer is a set of neurons which are created according to a certain pattern. We know that there is insufficient information in the human DNA to determine the type, position, behavior, etc. of every neuron so neurons must be created based on a generative algorithm. In general, a Layer is categorized by its dimension: 1D, 2D, or 3D. +Neuron - A neuron is the funademntal unit of compuation. Updating a neuron occurs in two steps. First, every neuron updates its membrane potential based on signals that were transmitted by presynaptic neurons and subsequently opened membrane receptors. +Connection +Synapse +Neurotransmitter diff --git a/package.json b/package.json new file mode 100644 index 0000000..9e6f4a2 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "cort", + "version": "0.1.0", + "description": "a platform for simulating and interacting with neural networks", + "main": "index.js", + "directories": { + "doc": "docs" + }, + "scripts": { + "test": "make -C build/gmake test" + }, + "repository": { + "type": "git", + "url": "https://github.com/tfussell/cort" + }, + "keywords": [ + "bnn", + "ann", + "neural", + "threejs" + ], + "author": "Thomas Fussell (https://thomas.fussell.io)", + "license": "MIT", + "bugs": { + "url": "https://github.com/tfussell/cort/issues" + }, + "homepage": "https://github.com/tfussell/cort" +} diff --git a/resources/cort.png b/resources/cort.png new file mode 100644 index 0000000..c91e63e Binary files /dev/null and b/resources/cort.png differ diff --git a/source/brain/brain.cpp b/source/brain/brain.cpp new file mode 100644 index 0000000..5f4cc68 --- /dev/null +++ b/source/brain/brain.cpp @@ -0,0 +1,226 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include +#include + +#include "brain/brain.hpp" +#include "brain/connection.hpp" +#include "brain/layer_factory.hpp" +#include "simulation/timer.hpp" + +namespace cort { + +brain::brain() : + current_time_(0) +{ +} + +brain::~brain() +{ +} + +void brain::load(const std::string &json_string) +{ + auto json = nlohmann::json::parse(json_string); + + for(auto &layer : json["layers"]) + { + add_layer(layer); + } + + for(auto &connection : json["connections"]) + { + add_connection(connection); + } +} + +void brain::add_layer(const nlohmann::json &settings) +{ + std::string name = settings["name"]; + layers_[name] = layer_factory::create_layer(settings); +} + +void brain::update(double time) +{ + current_time_ = time; + + for(auto &layer : layers_) + { + for(auto &neuron : *layer.second.get()) + { + neuron->update_inputs(current_time_); + } + } + + for(auto &layer : layers_) + { + for(auto &neuron : *layer.second.get()) + { + neuron->update(current_time_); + } + } +} + +void brain::reset() +{ + +} + +void brain::add_connection(const nlohmann::json &settings) +{ + std::string from = settings["from"]; + std::string to = settings["to"]; + get_layer(from)->connect_to(*get_layer(to), settings); +} + +std::string brain::serialize_structure() const +{ + auto structure = nlohmann::json::object(); + auto &neurons = structure["neurons"]; + neurons = nlohmann::json::object(); + + for(auto &layer : layers_) + { + for(auto &neuron : *layer.second.get()) + { + auto neuron_id = std::to_string(neuron->get_id()); + auto &neuron_obj = neurons[neuron_id] = nlohmann::json::object(); + auto position = neuron->get_world_position(); + neuron_obj["position"] = nlohmann::json::array({position.x, position.y, position.z}); + auto &connections = neuron_obj["connections"]; + connections = nlohmann::json::object(); + + for(auto connection : neuron->get_outputs()) + { + auto postsynaptic = connection->get_postsynaptic(); + auto postsynaptic_id = std::to_string(postsynaptic->get_id()); + auto &connection_obj = connections[postsynaptic_id]; + connection_obj = nlohmann::json::object(); + connection_obj["weight"] = 0; + } + } + } + + return structure.dump(); +} + +std::string brain::serialize_state() const +{ + auto state = nlohmann::json::object(); + auto &neurons = state["neurons"]; + neurons = nlohmann::json::object(); + + for(auto &layer : layers_) + { + for(auto &neuron : *layer.second.get()) + { + auto neuron_id = std::to_string(neuron->get_id()); + auto &neuron_obj = neurons[neuron_id] = nlohmann::json::object(); + neuron_obj["voltage"] = neuron->get_voltage(); + auto &signals = neuron_obj["signals"] = nlohmann::json::object(); + auto &new_signals = neuron_obj["new_signals"] = nlohmann::json::object(); + auto &deleted_signals = neuron_obj["deleted_signals"] = nlohmann::json::object(); + + for(auto connection : neuron->get_outputs()) + { + while(connection->has_new_signal()) + { + auto signal = connection->pop_new_signal(); + auto &signal_obj = new_signals[std::to_string(signal.first)] = nlohmann::json::object(); + signal_obj["target_id"] = (int)connection->get_postsynaptic()->get_id(); + signal_obj["type"] = signal.second.second == 0 ? "action_potential" : signal.second.second == 1 ? "backpropagation_up" : signal.second.second == 2 ? "backpropagation_down" : "teaching"; + } + + while(connection->has_deleted_signal()) + { + auto signal = connection->pop_deleted_signal(); + auto &signal_obj = deleted_signals[std::to_string(signal.first)] = nlohmann::json::object(); + signal_obj["target_id"] = (int)connection->get_postsynaptic()->get_id(); + } + + for(auto &signal : *connection) + { + auto &signal_obj = signals[std::to_string(signal.first)] = nlohmann::json::object(); + signal_obj["state"] = signal.second.first / connection->get_length(); + signal_obj["target_id"] = (int)connection->get_postsynaptic()->get_id(); + } + } + } + } + + return state.dump(); +} + +void brain::set_input_image(const std::string &image_string) +{ + for(auto &layer : *this) + { + if(!layer.second->has_class("image")) continue; + + std::stringstream ss(image_string); + int part; + + for(auto &neuron : *layer.second) + { + ss >> part; + + if(part > 50) + { + neuron->set_external_current(14); + } + else + { + neuron->set_external_current(0); + } + } + } +} + +void brain::train(const std::string &input_image, const std::string &expected_output) +{ + set_input_image(input_image); + + if(expected_output == "") return; + + for(auto &layer : *this) + { + if(!layer.second->has_class("trainable")) continue; + + for(auto &neuron : *layer.second.get()) + { + neuron->clear_class(); + + if(neuron->get_label() == expected_output) + { + neuron->add_class("expected_fire"); + } + else + { + neuron->add_class("expected_no_fire"); + } + } + } +} + +} // namespace cort diff --git a/source/brain/brain.hpp b/source/brain/brain.hpp new file mode 100644 index 0000000..7c7a82b --- /dev/null +++ b/source/brain/brain.hpp @@ -0,0 +1,81 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +#include "brain/neuron.hpp" +#include "brain/layer2.hpp" +#include "simulation/entity.hpp" +#include "simulation/trainer.hpp" + +namespace cort { + +/* + This class represents a simulated brain. It can be constructed programmatically or from a "geneotype" which encodes its function and structure. It holds an internal state which may be serialized/deserialized. It functions in discrete time increments based on external time signals. Effectively, it has three parts. The input layers provide afferent signals. The central part processes these signals and stores an internal state. The final part is the set of motor layers which translate efferent signals into actions. + */ +class brain : public entity +{ +public: + using layer_container = std::unordered_map>; + using iterator = layer_container::iterator; + using const_iterator = layer_container::const_iterator; + + brain(); + virtual ~brain(); + + iterator begin() { return layers_.begin(); } + const_iterator begin() const { return cbegin(); } + const_iterator cbegin() const { return layers_.cbegin(); } + iterator end() { return layers_.end(); } + const_iterator end() const { return cend(); } + const_iterator cend() const { return layers_.cend(); } + + void load(const std::string &json_string); + void add_layer(const nlohmann::json &settings); + void add_connection(const nlohmann::json &settings); + + void set_input_image(const std::string &image_string); + +// void PrintState(); + void reset() override; + void update(double time) override; + layer *get_layer(const std::string &name) override { return layers_.at(name).get(); } + trainer *get_trainer() { return trainer_; } + void set_trainer(trainer &trainer) { trainer_ = &trainer; } + std::string serialize(); + void deserialize(const std::string &str); + + std::string serialize_structure() const override; + std::string serialize_state() const override; + + void train(const std::string &input_image, const std::string &expected_output); + +private: + double current_time_; + layer_container layers_; + trainer *trainer_; +}; + +} // namespace cort diff --git a/source/brain/connection.cpp b/source/brain/connection.cpp new file mode 100644 index 0000000..289fba4 --- /dev/null +++ b/source/brain/connection.cpp @@ -0,0 +1,129 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "brain/connection.hpp" + +namespace cort { + +std::size_t connection::num_signals_ = 0; +const double connection::transmission_velocity_ = 0.1; + +connection::connection(neuron *presynaptic, neuron *postsynaptic, double receptor_current) : + length_(1), + presynaptic_(presynaptic), + postsynaptic_(postsynaptic), + synapse_(presynaptic, postsynaptic, receptor_current) +{ + if(presynaptic_ != nullptr) + { + presynaptic_->add_output(this); + } + + if(postsynaptic_ != nullptr) + { + postsynaptic_->add_input(this); + } + + if(presynaptic_ && postsynaptic_) + { + auto pre_pos = presynaptic_->get_world_position(); + auto post_pos = postsynaptic_->get_world_position(); + auto dist = (pre_pos - post_pos).length(); + length_ = dist; + } +} + +connection::~connection() {} + +bool connection::has_updates() const +{ + return !signals_.empty() || has_deleted_signal() || has_new_signal(); +} + +void connection::update(double time) +{ + auto iter = signals_.begin(); + bool activate = false; + + while(iter != signals_.end()) + { + auto &signal = *iter; + signal.second.first += transmission_velocity_; + + if(signal.second.first > length_) + { + if(signal.second.second == 0) + { + activate = true; + } + + iter = signals_.erase(iter); + + if(new_signals_.find(signal.first) != new_signals_.end()) + { + // signal hasn't been popped from new list since it was created, so we don't care if it was deleted + new_signals_.erase(signal.first); + } + else + { + deleted_signals_[signal.first] = signal.second; + } + } + else + { + iter++; + } + } + + if(activate) + { + synapse_.activate(); + } + + synapse_.update(time); +} + +void connection::send_signal(int type) +{ + signal_type signal = {0, type}; + signals_.push_front({next_signal(), signal}); + new_signals_[signals_.front().first] = signal; +} + +connection::signal_id_pair connection::pop_deleted_signal() +{ + auto front = *deleted_signals_.begin(); + deleted_signals_.erase(deleted_signals_.begin()); + + return front; +} + +connection::signal_id_pair connection::pop_new_signal() +{ + auto front = *new_signals_.begin(); + new_signals_.erase(new_signals_.begin()); + + return front; +} + +} // namespace cort diff --git a/source/brain/connection.hpp b/source/brain/connection.hpp new file mode 100644 index 0000000..bf42500 --- /dev/null +++ b/source/brain/connection.hpp @@ -0,0 +1,84 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include +#include +#include + +#include "neuron.hpp" +#include "synapse.hpp" + +namespace cort { + +class connection +{ +public: + using signal_type = std::pair; + using signal_id_pair = std::pair; + using signal_container = std::list; + using signal_assoc_container = std::unordered_map; + + static std::size_t next_signal() { return num_signals_++; } + + connection(neuron *presynaptic, neuron *postsynaptic, double receptor_current); + ~connection(); + + bool has_updates() const; + + double get_length() const { return length_; } + + void update(double time); + void send_signal(int type); + synapse &get_synapse() { return synapse_; } + + neuron *get_presynaptic() const { return presynaptic_; } + neuron *get_postsynaptic() const { return postsynaptic_; } + + bool has_deleted_signal() const { return !deleted_signals_.empty(); } + signal_id_pair pop_deleted_signal(); + bool has_new_signal() const { return !new_signals_.empty(); } + signal_id_pair pop_new_signal(); + + signal_container::iterator begin() { return signals_.begin(); } + signal_container::const_iterator begin() const { return signals_.cbegin(); } + signal_container::iterator end() { return signals_.end(); } + signal_container::const_iterator end() const { return signals_.cend(); } + +private: + static const double transmission_velocity_; + static std::size_t num_signals_; + + double length_; + signal_container signals_; + signal_assoc_container new_signals_; + signal_assoc_container deleted_signals_; + + neuron *presynaptic_; + neuron *postsynaptic_; + + synapse synapse_; +}; + +} // namespace cort diff --git a/source/brain/emitter.cpp b/source/brain/emitter.cpp new file mode 100644 index 0000000..a47fd62 --- /dev/null +++ b/source/brain/emitter.cpp @@ -0,0 +1,75 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "brain/emitter.hpp" + +namespace cort { + +emitter::emitter() : + open_(false), + duration_(0.0), + //type_(neurotransmitter_type::invalid), + time_last_opened_(-(std::numeric_limits::max)()), + //max_amount_(0.0), + //regen_rate_(0.0), + amount_released_(0) +{ + +} + +emitter::emitter(neurotransmitter_type /*type*/, double duration, double amountPerOpening, double /*maxAmount*/, double /*regenRate*/) : + open_(false), + duration_(duration), + //type_(type), + time_last_opened_(-(std::numeric_limits::max)()), + //max_amount_(maxAmount), + //regen_rate_(regenRate), + amount_released_(amountPerOpening) +{ + +} + +void emitter::open(double time) +{ + time_last_opened_ = time; +} + +void emitter::update(double time) +{ + if(time - time_last_opened_ >= duration_) + { + open_ = false; + } +} + +bool emitter::is_open() +{ + return open_; +} + +void emitter::change_weight(double amount) +{ + amount_released_ += amount; +} + +} // namespace cort diff --git a/source/brain/emitter.hpp b/source/brain/emitter.hpp new file mode 100644 index 0000000..977e589 --- /dev/null +++ b/source/brain/emitter.hpp @@ -0,0 +1,52 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +#include "brain/neurotransmitter.hpp" + +namespace cort { + +class emitter +{ +public: + emitter(); + emitter(neurotransmitter_type type, double duration, double amountPerOpening, double maxAmount, double regenRate); + + void open(double time); + void update(double time); + bool is_open(); + void change_weight(double amount); + +private: + bool open_; + double duration_; + //neurotransmitter_type type_; + double time_last_opened_; + //double max_amount_; + //double regen_rate_; + double amount_released_; +}; + +} // namespace cort diff --git a/source/brain/interface1.cpp b/source/brain/interface1.cpp new file mode 100644 index 0000000..e18997a --- /dev/null +++ b/source/brain/interface1.cpp @@ -0,0 +1,38 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "brain/interface1.hpp" + +namespace cort { + +interface1::interface1(layer1 &layer) : layer_(layer) +{ + +} + +interface1::~interface1() +{ + +} + +} // namespace cort diff --git a/source/brain/interface1.hpp b/source/brain/interface1.hpp new file mode 100644 index 0000000..849cbbd --- /dev/null +++ b/source/brain/interface1.hpp @@ -0,0 +1,44 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +namespace cort { + +class layer1; + +class interface1 +{ +public: + interface1(layer1 &layer); + ~interface1(); + +protected: + layer1 &get_layer() { return layer_; } + +private: + layer1 &layer_; +}; + +} // namespace cort diff --git a/source/brain/layer.cpp b/source/brain/layer.cpp new file mode 100644 index 0000000..d2041d9 --- /dev/null +++ b/source/brain/layer.cpp @@ -0,0 +1,60 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include +#include + +#include "brain/layer.hpp" +#include "brain/neuron.hpp" +#include "brain/synapse.hpp" + +namespace cort { + +std::size_t layer::num_layers_ = 0; + +layer::layer() : + position_(0, 0, 0), + rotation_(1, 0, 0, 0), + id_(num_layers_++) +{ +} + +layer::~layer() +{ + +} + +void layer::add_neuron(std::unique_ptr n) +{ + neurons_.push_back(std::move(n)); +} + +void layer::oscillate(double period) +{ + for(auto &neuron : *this) + { + neuron->oscillate(period); + } +} + +} // namespace cort diff --git a/source/brain/layer.hpp b/source/brain/layer.hpp new file mode 100644 index 0000000..ff3f32d --- /dev/null +++ b/source/brain/layer.hpp @@ -0,0 +1,78 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include +#include + +#include "math/quaternion.hpp" +#include "math/vector3.hpp" + +namespace cort { + +class neuron; + +class layer +{ + public: + using neuron_container = std::vector>; + using iterator = neuron_container::iterator; + using const_iterator = neuron_container::const_iterator; + + layer(); + virtual ~layer() = 0; + + std::size_t size() const { return neurons_.size(); } + + iterator begin() { return neurons_.begin(); } + const_iterator begin() const { return cbegin(); } + const_iterator cbegin() const { return neurons_.cbegin(); } + iterator end() { return neurons_.end(); } + const_iterator end() const { return cend(); } + const_iterator cend() const { return neurons_.cend(); } + + virtual void connect_to(layer &target, const nlohmann::json &settings) = 0; + virtual void set_position(vector3 position) = 0; + virtual void set_rotation(const quaternion &rotation) = 0; + virtual std::string get_type() const = 0; + + void add_class(const std::string &_class) { class_.insert(_class); } + bool has_class(const std::string &_class) const { return class_.find(_class) != class_.end(); } + + void oscillate(double period); + +protected: + void add_neuron(std::unique_ptr neuron); + + vector3 position_; + quaternion rotation_; + +private: + static std::size_t num_layers_; + std::size_t id_; + neuron_container neurons_; + std::unordered_set class_; +}; + +} // namespace cort diff --git a/source/brain/layer1.hpp b/source/brain/layer1.hpp new file mode 100644 index 0000000..3a21a1d --- /dev/null +++ b/source/brain/layer1.hpp @@ -0,0 +1,36 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include "brain/layer.hpp" + +namespace cort { + +class layer1 : layer +{ +public: + layer1(const rana::value &settings); + virtual ~layer1(); +}; + +} // namespace cort diff --git a/source/brain/layer2.cpp b/source/brain/layer2.cpp new file mode 100644 index 0000000..cc4482c --- /dev/null +++ b/source/brain/layer2.cpp @@ -0,0 +1,251 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include +#include +#include +#include +#include +#include +#include + +#include "brain/layer2.hpp" +#include "brain/connection.hpp" +#include "brain/neuron.hpp" + +namespace { + +std::vector split_string(const std::string &to_split, char delim) +{ + std::size_t index = to_split.find(delim); + std::size_t prev = 0; + std::vector split; + + while(index != std::string::npos) + { + split.push_back(to_split.substr(prev, index - prev)); + prev = index + 1; // skip delim + index = to_split.find(delim, prev); + } + + split.push_back(to_split.substr(prev)); + + return split; +} + +} // namespace + +namespace cort { + +layer2::layer2(const nlohmann::json &settings) +{ + int width = settings["width"]; + int length = settings["length"]; + + for(int i = 0; i < width; i++) + { + for(int j = 0; j < length; j++) + { + auto n = std::unique_ptr(new neuron()); + n->set_local_position(vector3(0.5 + i - width / 2.0, 0, 0.5 + j - length / 2.0)); + add_neuron(std::move(n)); + } + } + + auto center = settings["center"]; + vector3 pos(center[0], center[1], center[2]); + set_position(pos); + + if(settings.find("orientation") != settings.end()) + { + auto orientation = settings["orientation"]; + auto deg2rad = [](double degrees) + { + // mod for floating point + // TODO: this can be more efficient but I don't feel like thinking about it right now + int rotations = std::abs(static_cast(degrees)) / 360 + (degrees < 0 ? 1 : 0); + degrees += 360 * rotations; + return degrees / 180.0 * 3.141592653589793238462643383279; + }; + auto rotation = quaternion::from_yaw_pitch_roll(deg2rad(orientation[0]), + deg2rad(orientation[1]), + deg2rad(orientation[2])); + set_rotation(rotation); + } +} + +layer2::~layer2() +{ + +} + +void layer2::connect_to(layer &target, const nlohmann::json &settings) +{ + if(target.get_type() != "layer2") + { + throw std::runtime_error("not implemented"); + } + + double current_change = 10; + + if(settings.find("current-change") != settings.end()) + { + current_change = settings["current-change"]; + } + + if(settings["type"] == "full") + { + for(auto &source_neuron : *this) + { + for(auto &target_neuron : target) + { + new connection(source_neuron.get(), target_neuron.get(), current_change); + } + } + } + else if(settings["type"] == "projection") + { + double source_density = settings["source-density"]; + double target_density = settings["target-density"]; + + double min_distance = 0; + if(settings.find("minimum-distance") != settings.end()) + { + min_distance = settings["minimum-distance"]; + } + + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_real_distribution source_dist(0.0,1.0); + std::poisson_distribution<> target_dist(target_density); + + auto source_region_strings = split_string(settings["source-region"], ','); + auto source_x0 = std::stod(source_region_strings[0]); + auto source_y0 = std::stod(source_region_strings[1]); + auto source_x1 = std::stod(source_region_strings[2]); + auto source_y1 = std::stod(source_region_strings[3]); + + double source_width = source_x1 - source_x0; + double source_height = source_y1 - source_y0; + + auto target_region_strings = split_string(settings["target-region"], ','); + auto target_x0 = std::stod(target_region_strings[0]); + auto target_y0 = std::stod(target_region_strings[1]); + auto target_x1 = std::stod(target_region_strings[2]); + auto target_y1 = std::stod(target_region_strings[3]); + + double target_width = target_x1 - target_x0; + double target_height = target_y1 - target_y0; + + double x_scale = target_width / source_width; + double y_scale = target_height / source_height; + + for(auto &source_neuron : *this) + { + if(source_dist(gen) > source_density) + { + continue; + } + + auto source_pos = source_neuron->get_local_position(); + + // use z here because local coordinates are in the xz plane, not xy + if(source_pos.x >= source_x0 + && source_pos.z >= source_y0 + && source_pos.x <= source_x1 + && source_pos.z <= source_y1) + { + auto dest_x = target_x0 + (source_pos.x - source_x0) * x_scale; + auto dest_y = target_y0 + (source_pos.z - source_y0) * y_scale; + + std::unordered_set connected; + auto connections = static_cast(target_density);//target_dist(gen)); + + while(connected.size() < connections) + { + std::pair closest = {nullptr, -1}; + + for(auto &target_neuron : target) + { + if(target_neuron.get() == source_neuron.get()) continue; + + auto target_pos = target_neuron->get_local_position(); + auto delta_x = dest_x - target_pos.x; + auto delta_y = dest_y - target_pos.z; + auto distance = std::sqrt(delta_x * delta_x + delta_y * delta_y); + + if(connected.find(target_neuron.get()) == connected.end() + && (closest.second == -1 || closest.second > distance) + && distance >= min_distance) + { + closest = {target_neuron.get(), distance}; + } + } + + if(closest.first != nullptr) + { + new connection(source_neuron.get(), closest.first, current_change); + connected.insert(closest.first); + } + else + { + if(connected.empty()) + { + std::printf("no connections"); + std::cerr << "warning: no neurons found in target region" << std::endl; + } + + break; + } + } + } + } + } +} + +void layer2::set_position(vector3 position) +{ + position_ = position; + + for(auto &neuron : *this) + { + neuron->update_world_position(position_, rotation_); + } +} + +std::string layer2::get_type() const +{ + return "layer2"; +} + +void layer2::set_rotation(const quaternion &rotation) +{ + rotation_ = rotation; + + for(auto &neuron : *this) + { + neuron->update_world_position(position_, rotation_); + } +} + +} // namespace cort diff --git a/source/brain/layer2.hpp b/source/brain/layer2.hpp new file mode 100644 index 0000000..5bcb5df --- /dev/null +++ b/source/brain/layer2.hpp @@ -0,0 +1,45 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +#include "brain/layer.hpp" + +namespace cort { + +class beuron; + +class layer2 : public layer +{ + public: + layer2(const nlohmann::json &settings); + virtual ~layer2(); + + /*virtual*/ void connect_to(layer &target, const nlohmann::json &settings); + /*virtual*/ void set_position(vector3 position); + /*virtual*/ void set_rotation(const quaternion &rotation); + /*virtual*/ std::string get_type() const; +}; + +} // namespace cort diff --git a/source/brain/layer_factory.cpp b/source/brain/layer_factory.cpp new file mode 100644 index 0000000..b88db71 --- /dev/null +++ b/source/brain/layer_factory.cpp @@ -0,0 +1,61 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "brain/layer_factory.hpp" +#include "brain/layer2.hpp" +#include "brain/neuron.hpp" + +namespace cort { + +std::unique_ptr layer_factory::create_layer(const nlohmann::json &settings) +{ + std::unique_ptr layer_ptr(new layer2(settings)); + + if(settings.find("class") != settings.end()) + { + for(auto &_class : settings.at("class")) + { + layer_ptr->add_class(_class); + + if(_class == "oscillator") + { + auto period = settings["oscillation-period"]; + layer_ptr->oscillate(period); + } + else if(_class == "labeled") + { + auto labels = settings["neuron-labels"]; + auto label_iter = labels.begin(); + + for(auto &neuron : *layer_ptr.get()) + { + neuron->set_label(*label_iter++); + } + } + } + } + + return std::move(layer_ptr); +} + +} // namespace cort diff --git a/source/brain/layer_factory.hpp b/source/brain/layer_factory.hpp new file mode 100644 index 0000000..dd3c0f3 --- /dev/null +++ b/source/brain/layer_factory.hpp @@ -0,0 +1,38 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +namespace cort { + +class layer; + +class layer_factory +{ +public: + static std::unique_ptr create_layer(const nlohmann::json &settings); +}; + +} // namespace cort diff --git a/source/brain/neuron.cpp b/source/brain/neuron.cpp new file mode 100644 index 0000000..a58fe23 --- /dev/null +++ b/source/brain/neuron.cpp @@ -0,0 +1,245 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include +#include + +#include "brain/neuron.hpp" +#include "brain/connection.hpp" +#include "simulation/random_number_generator.hpp" + +namespace cort { + +/* + * Translated from: http://www.afodor.net/HHModel.htm + */ + +std::size_t neuron::num_neurons_ = 0; + +neuron::neuron() : + id_(num_neurons_++), + current_time_(0), + input_current_(0), + backpropagation_time_(0), + cm_(1.0), //Membrane capaciatance in uF/cm^2 + v_(-70.0), //Initial membrane potential + percent_na_channels_(100.0), + percent_k_channels_(100.0), + gna_(percent_na_channels_ * 120 / 100), //Maximum conductances in mS/cm^2 + gk_(percent_k_channels_ * 36 / 100), + gl_(0.3), + vna_(45.0), //Nernst reversal potentials in mV + vk_(-82.0), + vl_(-59.387), + activation_voltage_(-20.0), + firing_(false), + backpropagating_(false), + last_fired_(-100), + external_current_(0), + is_oscillator_(false), + oscillation_period_(0) +{ + double alphaH = 0.07 * std::exp(-1 * (v_ + 70.0) / 20.0); + double betaH = 1.0 / (1.0 + std::exp(-1 * (v_ + 40.0) / 10.0)); + h_ = alphaH / (alphaH + betaH); + + double alphaM = 0.1 * (v_ + 45.0) / (1.0 - std::exp(-1 * (v_ + 45.0) / 10.0)); + double betaM = 4.0 * std::exp(-1 * (v_ + 70.0) / 18.0); + m_ = alphaM / (alphaM + betaM); + + double alphaN = 0.01 * (v_ + 60) / (1.0 - std::exp(-1 * (v_ + 60.0) / 10.0)); + double betaN = 0.125 * std::exp(-1 * (v_ + 70.0) / 80.0); + n_ = alphaN / (alphaN + betaN); + + received_neurotransmitters_.push_back(neurotransmitter_type::glutamate); + emitted_neurotransmitters_.push_back(neurotransmitter_type::glutamate); +} + +neuron::~neuron() +{ + +} + +void neuron::update(double time) +{ + double last_time = current_time_; + + current_time_ = time; + delta_time_ = current_time_ - last_time; + + if(is_oscillator_) + { + if(!firing_ && current_time_ - last_fired_ > oscillation_period_) + { + on_action_potential_begin(); + } + else if(firing_) + { + on_action_potential_end(); + } + + return; + } + + double alphaH = 0.07 * std::exp(-1 * (v_ + 70.0) / 20.0); + double betaH = 1.0 / (1.0 + std::exp(-1 * (v_ + 40.0) / 10.0)); + double deltaH = (alphaH * (1 - h_) - betaH * h_) * delta_time_ * 1000; + + double alphaM = 0.1 * (v_ + 45.0) / (1.0 - std::exp(-1 * (v_ + 45.0) / 10.0)); + double betaM = 4.0 * std::exp(-1 * (v_ + 70.0) / 18.0); + double deltaM = (alphaM * (1 - m_) - betaM * m_) * delta_time_ * 1000; + + double alphaN = 0.01 * (v_ + 60) / (1.0 - std::exp(-1 * (v_ + 60.0) / 10.0)); + double betaN = 0.125 * std::exp(-1 * (v_ + 70.0) / 80.0); + double deltaN = (alphaN * (1 - n_) - betaN * n_) * delta_time_ * 1000; + + double naCurrent = gna_ * (v_ - vna_) * m_ * m_ * m_ * h_; + double kCurrent = gk_ * (v_ - vk_) * n_ * n_ * n_ * n_; + double lCurrent = gl_ * (v_ - vl_); + + double deltaV = ((input_current_ - kCurrent - naCurrent - lCurrent) / cm_) * delta_time_ * 1000; + + v_ += deltaV; + h_ += deltaH; + m_ += deltaM; + n_ += deltaN; + + if(!firing_ && v_ >= activation_voltage_) + { + on_action_potential_begin(); + } + else if(firing_ && v_ < activation_voltage_) + { + on_action_potential_end(); + } + + if(backpropagating_ && current_time_ - backpropagation_time_ > 0.001) + { + backpropagating_ = false; + } +} + +void neuron::on_action_potential_begin() +{ + firing_ = true; + last_fired_ = current_time_; + + for(auto connection : outputs_) + { + connection->send_signal(0); + } + + if(has_class("expected_fire") || has_class("expected_no_fire")) + { + std::cout << get_label() << " " << has_class("expected_fire") << " " << has_class("expected_no_fire") << std::endl; + + for(auto in_connection : inputs_) + { + for(auto sibling_connection : in_connection->get_presynaptic()->outputs_) + { + sibling_connection->get_postsynaptic()->backpropagate(); + } + } + } +} + +void neuron::on_action_potential_end() +{ + firing_ = false; +} + +void neuron::backpropagate() +{ + if(backpropagating_) return; + + bool fired_recently = std::abs(current_time_ - last_fired_) < 0.003; + bool up = false; + bool down = false; + + if(has_class("expected_fire") && !fired_recently) + { + std::cout << get_label() << " should have fired, didn't " << current_time_ << " " << last_fired_ << " " << (current_time_ - last_fired_) << std::endl; + up = true; + } + else if(has_class("expected_no_fire") && fired_recently) + { + std::cout << get_label() << " shouldn't have fired, did " << current_time_ << " " << last_fired_ << " " << (current_time_ - last_fired_) << std::endl; + down = true; + } + + if(!up && !down) + { + std::cout << get_label() << " no change" << current_time_ << " " << last_fired_ << " " << (current_time_ - last_fired_) << std::endl; + return; + } + + backpropagating_ = true; + backpropagation_time_ = current_time_; + + for(auto connection : inputs_) + { + if(connection->get_presynaptic()->has_class("collector")) continue; + + if(current_time_ - connection->get_presynaptic()->last_fired_ < 0.005) + { + if(up) + { + connection->get_synapse().backpropagate_up(); + connection->send_signal(1); + } + else + { + connection->get_synapse().backpropagate_down(); + connection->send_signal(2); + } + } + } +} + +void neuron::add_input(connection *conn) +{ + inputs_.push_back(conn); +} + +void neuron::add_output(connection *conn) +{ + outputs_.push_back(conn); +} + +void neuron::update_inputs(double time) +{ + input_current_ = external_current_; + + for(auto connection : inputs_) + { + connection->update(time); + input_current_ += connection->get_synapse().get_total_current(); + } +} + +void neuron::update_world_position(vector3 parent_position, const quaternion &parent_rotation) +{ + world_position_ = (parent_rotation * local_position_) + parent_position; +} + +} // namespace cort diff --git a/source/brain/neuron.hpp b/source/brain/neuron.hpp new file mode 100644 index 0000000..c3238a5 --- /dev/null +++ b/source/brain/neuron.hpp @@ -0,0 +1,128 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +#include "brain/neurotransmitter.hpp" +#include "brain/receptor.hpp" +#include "math/quaternion.hpp" +#include "math/vector3.hpp" + +namespace cort { + +class connection; + +class neuron +{ +public: + neuron(); + ~neuron(); + + std::size_t get_id() const { return id_; } + + void update(double time); + void augment_voltage(double amount); + void add_input(connection *conn); + void add_output(connection *conn); + void update_inputs(double time); + void activate_receptor(neurotransmitter_type neurotrans); + void backpropagate(); + + double get_last_fired() { return last_fired_; } + + std::vector get_emitted_neurotransmitters() { return emitted_neurotransmitters_; } + std::vector get_received_neurotransmitters() { return received_neurotransmitters_; } + + std::vector &get_inputs() { return inputs_; } + std::vector &get_outputs() { return outputs_; } + + void set_voltage(double v) { v_ = v; } + double get_voltage() { return v_; } + + vector3 get_local_position() const { return local_position_; } + void set_local_position(vector3 position) { local_position_ = position; } + void update_world_position(vector3 parent_position, const quaternion &parent_rotation); + vector3 get_world_position() const { return world_position_; } + + void set_external_current(double current) { external_current_ = current; } + + void oscillate(double period) { is_oscillator_ = true; oscillation_period_ = period; } + + void add_class(const std::string &to_add) { class_.insert(to_add); } + + void clear_class() { class_.clear(); } + + bool has_class(const std::string &to_check) { return class_.count(to_check) == 1; } + + void set_label(const std::string &label) { label_ = label; } + + std::string get_label() const { return label_; } + +private: + friend class bci_speech_from_file; + + static std::size_t num_neurons_; + + void on_action_potential_begin(); + void on_action_potential_end(); + + std::size_t id_; + + std::vector emitted_neurotransmitters_; + std::vector received_neurotransmitters_; + + double current_time_; + double delta_time_; + double last_time_; + double backpropagation_time_; + + std::vector inputs_; + std::vector outputs_; + + double input_current_; + double cm_; + double v_; + double percent_na_channels_; + double percent_k_channels_; + double gna_, gk_, gl_; + double vna_, vk_, vl_; + double n_, m_, h_; + double activation_voltage_; + bool firing_; + bool backpropagating_; + double last_fired_; + double external_current_; + + bool is_oscillator_; + double oscillation_period_; + + vector3 local_position_; + vector3 world_position_; + + std::unordered_set class_; + std::string label_; +}; + +} // namespace cort diff --git a/source/brain/neurotransmitter.hpp b/source/brain/neurotransmitter.hpp new file mode 100644 index 0000000..c4b11dc --- /dev/null +++ b/source/brain/neurotransmitter.hpp @@ -0,0 +1,44 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once + +namespace cort { + +enum neurotransmitter_type +{ + invalid, + glutamate, + gaba, + seratonin, + dopamine, + glycine, + aspartate, + epinephrine, + norepinephrine, + histamine, + acetylecholhine, + adenosine +}; + +} // namespace cort diff --git a/source/brain/receptor.cpp b/source/brain/receptor.cpp new file mode 100644 index 0000000..bfe348a --- /dev/null +++ b/source/brain/receptor.cpp @@ -0,0 +1,83 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include + +#include "brain/receptor.hpp" + +namespace cort { + +receptor::receptor() : + open_(false), + duration_(0), + current_change_per_molecule_(0), + time_last_opened_(-(std::numeric_limits::max)()) +{ + +} + +receptor::receptor(neurotransmitter_type /*type*/, double duration, double currentChange) : + open_(false), + duration_(duration), + current_change_per_molecule_(currentChange), + time_last_opened_(-1 * (duration + 0.01)) //can't be zero as it would make it appear to be open, can't be very negative as that would be large delta-time +{ + +} + +receptor::~receptor() +{ + +} + +void receptor::open(double currentTime) +{ + time_last_opened_ = currentTime; + open_ = true; +} + +void receptor::update(double currentTime) +{ + if(open_ && currentTime - time_last_opened_ >= duration_) + { + open_ = false; + } +} + +bool receptor::is_open() +{ + return open_; +} + +double receptor::get_current_change() +{ + return current_change_per_molecule_; +} + +void receptor::change_weight(double amount) +{ + std::cout << "receptor changed from " << current_change_per_molecule_ << " to " << current_change_per_molecule_ + amount << std::endl; + current_change_per_molecule_ += amount; +} + +} // namespace cort diff --git a/source/brain/receptor.hpp b/source/brain/receptor.hpp new file mode 100644 index 0000000..bb728ba --- /dev/null +++ b/source/brain/receptor.hpp @@ -0,0 +1,52 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +#include "brain/Neurotransmitter.hpp" + +namespace cort { + +class receptor +{ +public: + receptor(); + receptor(neurotransmitter_type type, double duration, double currentChange); + ~receptor(); + + void open(double currentTime); + void update(double currentTime); + bool is_open(); + double get_current_change(); + void change_weight(double amount); + +private: + bool open_; + double duration_; + //NeurotransmitterType m_Type; + double current_change_per_molecule_; + double time_last_opened_; +}; + +} // namespace cort diff --git a/source/brain/synapse.cpp b/source/brain/synapse.cpp new file mode 100644 index 0000000..3620031 --- /dev/null +++ b/source/brain/synapse.cpp @@ -0,0 +1,197 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include +#include + +#include "brain/synapse.hpp" +#include "brain/neuron.hpp" +#include "simulation/random_number_generator.hpp" + +namespace { + +template +std::vector intersect(const std::vector &left, const std::vector &right) +{ + std::vector intersection; + + for(const auto &i : left) + { + if(std::find(right.begin(), right.end(), i) != right.end()) + { + intersection.push_back(i); + } + } + + return intersection; +} + +} + +namespace cort { + +synapse::synapse(neuron *pre, neuron *post, double receptor_current) : + current_time_(0), + delta_time_(1), + activation_duration_(0.001), + time_last_activated_(0), + presynaptic_(pre), + postsynaptic_(post), + hebbian_(true) +{ + double duration = 0.001; + + if(pre != nullptr && post == nullptr) + { + for(auto nt : pre->get_emitted_neurotransmitters()) + { + emitters_[nt] = emitter(nt, 0.1, 1.0, 10.0, 2.0); + } + } + + if(post != nullptr && pre == nullptr) + { + for(auto nt : post->get_received_neurotransmitters()) + { + receptors_[nt] = receptor(nt, duration, receptor_current); + } + } + + // ignore signals that are emitted but not received and vice versa + if(post != nullptr && pre != nullptr) + { + auto intersection = intersect(pre->get_emitted_neurotransmitters(), + post->get_received_neurotransmitters()); + + emitted_ = intersection; + received_ = intersection; + + for(auto nt : intersection) + { + emitters_[nt] = emitter(nt, 0.01, 1, 10.0, 2.0); + receptors_[nt] = receptor(nt, duration, receptor_current); + } + } +} + +synapse::~synapse() +{ +} + +void synapse::update(double time) +{ + double lastTime = current_time_; + current_time_ = time; + delta_time_ = current_time_ - lastTime; + + for(std::size_t i = 0; i < emitted_.size(); i++) + { + emitters_[emitted_[i]].update(time); + } + + for(std::size_t i = 0; i < received_.size(); i++) + { + receptors_[received_[i]].update(time); + } +} + +void synapse::activate() +{ + for(std::size_t i = 0; i < received_.size(); i++) + { + receptors_[received_[i]].open(current_time_); + } +} + +void synapse::backpropagate_up() +{ + if(!postsynaptic_ || !presynaptic_) + { + return; + } + + double timeDiff = postsynaptic_->get_last_fired() - presynaptic_->get_last_fired(); + double weightChange = 0.5;//0.8 * std::exp(-timeDiff); + + for(std::size_t i = 0; i < emitted_.size(); i++) + { + emitters_[emitted_[i]].change_weight(weightChange); + } + + for(std::size_t i = 0; i < received_.size(); i++) + { + receptors_[received_[i]].change_weight(weightChange); + } + + //presynaptic_->backpropagate_up(); +} + +void synapse::backpropagate_down() +{ + if(!postsynaptic_ || !presynaptic_) + { + return; + } + + double timeDiff = postsynaptic_->get_last_fired() - presynaptic_->get_last_fired(); + double weightChange = -0.5;//-0.5 * std::exp(-timeDiff); + + for(std::size_t i = 0; i < emitted_.size(); i++) + { + emitters_[emitted_[i]].change_weight(weightChange); + } + + for(std::size_t i = 0; i < received_.size(); i++) + { + receptors_[received_[i]].change_weight(weightChange); + } + + //presynaptic_->backpropagate_down(); +} + +/* +void Synapse::activate_receptor(NeurotransmitterType receptorType) +{ + if(m_Receptors.find(receptorType) != m_Receptors.end()) + { + m_Receptors[receptorType].Open(m_CurrentTime); + } +} +*/ + +double synapse::get_total_current() +{ + total_current_ = 0.; + + for(auto i = receptors_.begin(); i != receptors_.end(); i++) + { + if(i->second.is_open()) + { + total_current_ += i->second.get_current_change(); + } + } + + return total_current_; +} + +} // namespace cort diff --git a/source/brain/synapse.hpp b/source/brain/synapse.hpp new file mode 100644 index 0000000..6edde7f --- /dev/null +++ b/source/brain/synapse.hpp @@ -0,0 +1,74 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include +#include + +#include "brain/emitter.hpp" +#include "brain/neurotransmitter.hpp" +#include "brain/receptor.hpp" + +namespace cort { + +class neuron; + +class synapse +{ +public: + synapse(neuron *presynaptic, neuron *postsynaptic, double receptor_current); + ~synapse(); + + void activate(); + void update(double time); + double get_total_current(); + + void backpropagate_up(); + void backpropagate_down(); + + neuron *get_presynaptic_neuron() const { return presynaptic_; } + neuron *get_postsynaptic_neuron() const { return postsynaptic_; } + +private: + friend class bci_speech_from_file; + + std::vector emitted_; + std::vector received_; + + std::map emitters_; + std::map receptors_; + + double current_time_; + double delta_time_; + double activation_duration_; + double time_last_activated_; + double total_current_; + + neuron *presynaptic_; + neuron *postsynaptic_; + + bool hebbian_; +}; + +} // namespace cort diff --git a/source/embind/cort_api.cpp b/source/embind/cort_api.cpp new file mode 100644 index 0000000..f987368 --- /dev/null +++ b/source/embind/cort_api.cpp @@ -0,0 +1,82 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include + +#include "embind/cort_api.hpp" +#include "brain/connection.hpp" + +using namespace emscripten; + +cort_api::cort_api() : + simulation_(2000, 50000000, 100000) +{ + simulation_.add_entity(brain_); +} + +void cort_api::load_script(std::string contents) +{ + brain_.load(contents); +} + +std::string cort_api::get_structure() +{ + return brain_.serialize_structure(); +} + +std::string cort_api::get_state() +{ + return brain_.serialize_state(); +} + +void cort_api::step() +{ + simulation_.step(); +} + +double cort_api::get_sim_time() +{ + return simulation_.get_total_sim_time(); +} + +void cort_api::set_input_image(std::string image_string) +{ + brain_.set_input_image(image_string); +} + +void cort_api::train(std::string image_string, std::string expected_output) +{ + brain_.train(image_string, expected_output); +} + +EMSCRIPTEN_BINDINGS(cort_bindings) { + class_("cort_api") + .constructor<>() + .function("load_script", &cort_api::load_script) + .function("step", &cort_api::step) + .function("set_input_image", &cort_api::set_input_image) + .function("train", &cort_api::train) + .function("get_sim_time", &cort_api::get_sim_time) + .function("get_structure", &cort_api::get_structure) + .function("get_state", &cort_api::get_state); +} diff --git a/source/embind/cort_api.hpp b/source/embind/cort_api.hpp new file mode 100644 index 0000000..ff0e2bf --- /dev/null +++ b/source/embind/cort_api.hpp @@ -0,0 +1,49 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include + +#include "simulation/simulation.hpp" + +class cort_api +{ +public: + cort_api(); + + void load_script(std::string contents); + + std::string get_structure(); + std::string get_state(); + + void step(); + + double get_sim_time(); + + void set_input_image(std::string image_string); + + void train(std::string image_string, std::string expected_output); + +private: + cort::simulation simulation_; + cort::brain brain_; +}; diff --git a/source/interface/bci.cpp b/source/interface/bci.cpp new file mode 100644 index 0000000..4a4d7b8 --- /dev/null +++ b/source/interface/bci.cpp @@ -0,0 +1,38 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "interface/bci.hpp" + +namespace cort { + +bci::bci() +{ + +} + +bci::~bci() +{ + +} + +} // namespace cort diff --git a/source/interface/bci.hpp b/source/interface/bci.hpp new file mode 100644 index 0000000..162a8e6 --- /dev/null +++ b/source/interface/bci.hpp @@ -0,0 +1,56 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +namespace cort { + +class layer; + +enum class bci_type +{ + input, + output +}; + +class bci +{ +public: + bci(); + virtual ~bci(); + + void set_layer(layer *layer) { layer_ = layer; }; + layer *get_layer() const { return layer_; }; + + virtual void initialize() = 0; + + virtual std::string get_state() = 0; + virtual void set_state(const std::string &state) = 0; + +private: + layer *layer_; +}; + +} // namespace cort + diff --git a/source/interface/bci_reward_punishment.cpp b/source/interface/bci_reward_punishment.cpp new file mode 100644 index 0000000..f248733 --- /dev/null +++ b/source/interface/bci_reward_punishment.cpp @@ -0,0 +1,75 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include + +#include "interface/bci_reward_punishment.hpp" +#include "brain/layer.hpp" +#include "brain/neurotransmitter.hpp" +#include "brain/neuron.hpp" + +namespace cort { + +bci_reward_punishment::bci_reward_punishment(layer *layer) +{ + set_layer(layer); + initialize(); +} + +bci_reward_punishment::~bci_reward_punishment() +{ +} + +void bci_reward_punishment::initialize() +{ + +} + +std::string bci_reward_punishment::get_state() +{ + return ""; +} + +void bci_reward_punishment::set_state(const std::string &/*state*/) +{ +/* + std::printf("Reward: %s\n",state.c_str()); + + if(state == "Good") + { + for(unsigned int i = 0; i < m_Interface->GetSize(); i++) + { + m_Interface->GetNeuron(i)->BackpropagateUp(); + } + } + else if(state == "Bad") + { + for(unsigned int i = 0; i < m_Interface->GetSize(); i++) + { + m_Interface->GetNeuron(i)->BackpropagateDown(); + } + } +*/ +} + +} // namespace cort diff --git a/source/interface/bci_reward_punishment.hpp b/source/interface/bci_reward_punishment.hpp new file mode 100644 index 0000000..a692c8b --- /dev/null +++ b/source/interface/bci_reward_punishment.hpp @@ -0,0 +1,44 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +#include "interface/BCI.hpp" + +namespace cort { + +class bci_reward_punishment : public bci +{ +public: + bci_reward_punishment(layer *layer); + ~bci_reward_punishment(); + + /*virtual*/ void initialize(); + + /*virtual*/ std::string get_state(); + /*virtual*/ void set_state(const std::string &state); +}; + +} // namespace cort diff --git a/source/interface/bci_speech_from_file.cpp b/source/interface/bci_speech_from_file.cpp new file mode 100644 index 0000000..18f2123 --- /dev/null +++ b/source/interface/bci_speech_from_file.cpp @@ -0,0 +1,137 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include + +#include "interface/bci_speech_from_file.hpp" +#include "brain/neurotransmitter.hpp" +#include "brain/neuron.hpp" +#include "brain/layer.hpp" + +namespace cort { + +bci_speech_from_file::bci_speech_from_file(layer *layer, const std::string &filename) : + filename_(filename) +{ + set_layer(layer); + initialize(); +} + +bci_speech_from_file::~bci_speech_from_file() +{ + +} + +void bci_speech_from_file::initialize() +{ + load_script(filename_); +} + +void bci_speech_from_file::load_script(const std::string &/*filename*/) +{ +/* + std::fstream f("../scripts/" + filename); + + if(!f.is_open()) + { + std::printf("Error opening file: %s\n",filename.c_str()); + return; + } + + std::printf("Loading BCI commands from file: %s\n",filename.c_str()); + int numCommands = 0; + f >> numCommands; + int index; + std::string line; + int i = 0; + + while(i++ < numCommands && f.good()) + { + f >> index; + f >> line; + Neuron *neuron = m_Interface->GetNeuron(index); + + if(m_Type == BciType_Input) + { + m_SynapseCommandMap[line] = new Synapse(0, neuron); + } + else if(m_Type == BciType_Output) + { + m_SynapseCommandMap[line] = new Synapse(neuron, 0); + } + } + + f.close(); +*/ +} + +std::string bci_speech_from_file::get_state() +{ +/* + for(std::unordered_map::iterator i = m_SynapseCommandMap.begin(); i != m_SynapseCommandMap.end(); i++) + { + if(i->second->m_Presynaptic->m_LastFired == i->second->m_Presynaptic->m_CurrentTime) + { + return i->first; + } + } +*/ + return ""; +} + +void bci_speech_from_file::set_state(const std::string &/*state*/) +{ +/* + if(m_SynapseCommandMap.find(state) != m_SynapseCommandMap.end()) + { + std::printf("Set state: %s\n", state.c_str()); + m_SynapseCommandMap[state]->ActivateReceptor(NT_Glutamate); + } +*/ +} +/* +Neuron *bci_speech_from_file::GetNeuron(const std::string &state) +{ + Synapse *syn = 0; + + if(m_SynapseCommandMap.find(state) != m_SynapseCommandMap.end()) + { + syn = m_SynapseCommandMap[state]; + } + + if(syn && m_Type == BciType_Input) + { + return syn->m_Postsynaptic; + } + else if(syn && m_Type == BciType_Output) + { + return syn->m_Presynaptic; + } + else + { + return 0; + } +} +*/ + +} // namespace cort diff --git a/source/interface/bci_speech_from_file.hpp b/source/interface/bci_speech_from_file.hpp new file mode 100644 index 0000000..7fbc0ad --- /dev/null +++ b/source/interface/bci_speech_from_file.hpp @@ -0,0 +1,54 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +#include "interface/bci.hpp" + +namespace cort { + +class synapse; + +class bci_speech_from_file : public bci +{ +public: + bci_speech_from_file(layer *layer, const std::string &filename); + ~bci_speech_from_file(); + + void load_script(const std::string &filename); + + /*virtual*/ void initialize(); + + /*virtual*/ std::string get_state(); + /*virtual*/ void set_state(const std::string &state); + +// Neuron *GetNeuron(const std::string &state); + +private: + std::string filename_; + std::unordered_map synapse_command_map_; +}; + +} // namespace cort diff --git a/source/interface/script.cpp b/source/interface/script.cpp new file mode 100644 index 0000000..9e080b5 --- /dev/null +++ b/source/interface/script.cpp @@ -0,0 +1,71 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "interface/script.hpp" + +namespace cort { + +script::script(const std::string &filename) : + filename_(filename) +{ + std::string fullpath = "../scripts/" + filename_; + stream_.open(fullpath, std::ifstream::in); + + if(!stream_.is_open()) + { + throw std::runtime_error("Error opening file in __func__(__LINE__) in __FILE__: " + filename_); + } +} + +script::~script() +{ + stream_.close(); +} + +std::string script::get_next_string() +{ + std::string ret(""); + stream_ >> ret; + return ret; +} + +int script::get_next_int() +{ + int ret = 0; + stream_ >> ret; + return ret; +} + +double script::get_next_double() +{ + double ret = 0; + stream_ >> ret; + return ret; +} + +bool script::is_finished() +{ + return !stream_.good(); +} + +} // namespace cort diff --git a/source/interface/script.hpp b/source/interface/script.hpp new file mode 100644 index 0000000..ef94b69 --- /dev/null +++ b/source/interface/script.hpp @@ -0,0 +1,46 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +namespace cort { + +class script +{ +public: + script(const std::string &filename); + ~script(); + + bool is_finished(); + int get_next_int(); + std::string get_next_string(); + double get_next_double(); + +private: + std::string filename_; + std::ifstream stream_; +}; + +} // namespace cort diff --git a/source/math/quaternion.hpp b/source/math/quaternion.hpp new file mode 100644 index 0000000..265e19e --- /dev/null +++ b/source/math/quaternion.hpp @@ -0,0 +1,90 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once + +#include "vector3.hpp" + +namespace cort { + +class quaternion +{ +public: + static quaternion from_yaw_pitch_roll(const vector3 &v) + { + return from_yaw_pitch_roll(v.x, v.y, v.z); + } + + static quaternion from_yaw_pitch_roll(double yaw, double pitch, double roll) + { + double cy = std::cos(yaw / 2); + double sy = std::sin(yaw / 2); + double cr = std::cos(-roll / 2); + double sr = std::sin(-roll / 2); + double cp = std::cos(-pitch / 2); + double sp = std::sin(-pitch / 2); + + return quaternion(cr * cp * cy - sr * sp * sy, + cr * sp * cy - sr * cp * sy, + cr * cp * sy + sr * sp * cy, + sr * cp * cy + cr * sp * sy); + } + + quaternion(double w, double x, double y, double z) : w(w), x(x), y(y), z(z) {} + quaternion(double w, vector3 v) : w(w), x(v.x), y(v.y), z(v.z) {} + quaternion() : quaternion(0, 0, 0, 0) {} + quaternion(const quaternion &other) : quaternion(other.w, other.x, other.y, other.z) {} + + void normalize() { auto l = length(); if(l == 0) return; w /= l; x /= l; y /= l; z /= l; } + double length() const { return std::sqrt(w * w + x * x + y * y + z * z); } + + quaternion conjugate() const { return quaternion(w, vector3(x, y, z) * -1); } + + quaternion &operator=(quaternion other) { w = other.w; x = other.x; y = other.y; z = other.z; return *this; } + quaternion operator+(quaternion other) const { return quaternion(w + other.w, x + other.x, y + other.y, z + other.z); } + quaternion operator-(quaternion other) const { return quaternion(w - other.w, x - other.x, y - other.y, z - other.z); } + vector3 operator*(const vector3 &v) const { return (*this * quaternion(0, v) * conjugate()).vector_part(); } + quaternion operator*(quaternion other) const + { + auto v1 = vector_part(); + auto v2 = other.vector_part(); + return quaternion(w * other.w - v1.dot(v2), w * v2 + other.w * v1 + v1 * v2); + } + quaternion operator*(double scalar) const { return quaternion(w * scalar, x * scalar, y * scalar, z * scalar); } + quaternion operator/(double scalar) const { return quaternion(w / scalar, x / scalar, y / scalar, z / scalar); } + + vector3 vector_part() const { return vector3(x, y, z); } + + double w; + double x; + double y; + double z; +}; + +inline std::ostream &operator<<(std::ostream &stream, const quaternion &q) +{ + stream << "quaternion(" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << ")"; + return stream; +} + +} // namespace cort diff --git a/source/math/vector3.hpp b/source/math/vector3.hpp new file mode 100644 index 0000000..32d8d4b --- /dev/null +++ b/source/math/vector3.hpp @@ -0,0 +1,66 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include + +namespace cort { + +struct vector3 +{ + vector3(double x, double y, double z) : x(x), y(y), z(z) {} + vector3() : vector3(0, 0, 0) {} + vector3(const vector3 &other) : vector3(other.x, other.y, other.z) {} + + void normalize() { auto l = length(); if(l == 0) return; x /= l; y /= l; z /= l; } + double length() const { return std::sqrt(x * x + y * y + z * z); } + double dot(vector3 other) const { return x * other.x + y * other.y + z * other.z; } + + vector3 &operator=(vector3 other) { x = other.x; y = other.y; z = other.z; return *this; } + vector3 operator+(vector3 other) const { return vector3(x + other.x, y + other.y, z + other.z); } + vector3 operator-(vector3 other) const { return vector3(x - other.x, y - other.y, z - other.z); } + vector3 operator*(vector3 other) const { return vector3(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); } + vector3 operator*(double scalar) const { return vector3(x * scalar, y * scalar, z * scalar); } + vector3 operator/(double scalar) const { return vector3(x / scalar, y / scalar, z / scalar); } + vector3 &operator+=(vector3 other) { *this = *this + other; return *this; } + vector3 &operator-=(vector3 other) { *this = *this - other; return *this; } + vector3 &operator*=(vector3 other) { *this = *this * other; return *this; } + vector3 &operator*=(double scalar) { *this = *this * scalar; return *this; } + vector3 &operator/=(double scalar) { *this = *this * (1 / scalar); return *this; } + + double x; + double y; + double z; +}; + +inline vector3 operator*(double scalar, vector3 vector) { return vector * scalar; } +inline vector3 operator/(double scalar, vector3 vector) { return vector / scalar; } + +inline std::ostream &operator<<(std::ostream &stream, const vector3 &v) +{ + stream << "vector3(" << v.x << ", " << v.y << ", " << v.z << ")"; + return stream; +} + +} // namespace cort diff --git a/source/server/connection.cpp b/source/server/connection.cpp new file mode 100755 index 0000000..5e5a348 --- /dev/null +++ b/source/server/connection.cpp @@ -0,0 +1,105 @@ +// +// connection.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "connection.hpp" +#include +#include +#include +#include "connection_manager.hpp" +#include "request_handler.hpp" + +namespace http { +namespace server { + +connection::connection(boost::asio::ip::tcp::socket socket, + connection_manager& manager, request_handler& handler) + : socket_(std::move(socket)), + connection_manager_(manager), + request_handler_(handler) +{ +} + +void connection::start() +{ + do_read(); +} + +void connection::stop() +{ + socket_.close(); +} + +void connection::do_read() +{ + auto self(shared_from_this()); + socket_.async_read_some(boost::asio::buffer(buffer_), + [this, self](boost::system::error_code ec, std::size_t bytes_transferred) + { + if (!ec) + { + request_parser::result_type result; + + std::tie(result, std::ignore) = request_parser_.parse( + request_, buffer_.data(), buffer_.data() + bytes_transferred); + + auto t = std::time(0); + auto now = *std::localtime(&t); + + std::cout << "[" << now.tm_mday << "/" << now.tm_mon << "/" << now.tm_year << " "; + std::cout << now.tm_hour << ":" << now.tm_min << ":" << now.tm_sec << "] "; + std::cout << "\"" << request_.method << " " << request_.uri << " HTTP/" << request_.http_version_major << "." << request_.http_version_minor << "\" "; + + if (result == request_parser::good) + { + request_handler_.handle_request(request_, reply_); + std::cout << reply_.status << std::endl; + do_write(); + } + else if (result == request_parser::bad) + { + reply_ = reply::stock_reply(reply::bad_request); + std::cout << reply::bad_request << std::endl; + do_write(); + } + else + { + do_read(); + } + } + else if (ec != boost::asio::error::operation_aborted) + { + connection_manager_.stop(shared_from_this()); + } + }); +} + +void connection::do_write() +{ + auto self(shared_from_this()); + boost::asio::async_write(socket_, reply_.to_buffers(), + [this, self](boost::system::error_code ec, std::size_t) + { + if (!ec) + { + // Initiate graceful connection closure. + boost::system::error_code ignored_ec; + socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, + ignored_ec); + } + + if (ec != boost::asio::error::operation_aborted) + { + connection_manager_.stop(shared_from_this()); + } + }); +} + +} // namespace server +} // namespace http diff --git a/source/server/connection.hpp b/source/server/connection.hpp new file mode 100755 index 0000000..3c87b6a --- /dev/null +++ b/source/server/connection.hpp @@ -0,0 +1,79 @@ +// +// connection.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_CONNECTION_HPP +#define HTTP_CONNECTION_HPP + +#include +#include +#include +#include "reply.hpp" +#include "request.hpp" +#include "request_handler.hpp" +#include "request_parser.hpp" + +namespace http { +namespace server { + +class connection_manager; + +/// Represents a single connection from a client. +class connection + : public std::enable_shared_from_this +{ +public: + connection(const connection&) = delete; + connection& operator=(const connection&) = delete; + + /// Construct a connection with the given socket. + explicit connection(boost::asio::ip::tcp::socket socket, + connection_manager& manager, request_handler& handler); + + /// Start the first asynchronous operation for the connection. + void start(); + + /// Stop all asynchronous operations associated with the connection. + void stop(); + +private: + /// Perform an asynchronous read operation. + void do_read(); + + /// Perform an asynchronous write operation. + void do_write(); + + /// Socket for the connection. + boost::asio::ip::tcp::socket socket_; + + /// The manager for this connection. + connection_manager& connection_manager_; + + /// The handler used to process the incoming request. + request_handler& request_handler_; + + /// Buffer for incoming data. + std::array buffer_; + + /// The incoming request. + request request_; + + /// The parser for the incoming request. + request_parser request_parser_; + + /// The reply to be sent back to the client. + reply reply_; +}; + +typedef std::shared_ptr connection_ptr; + +} // namespace server +} // namespace http + +#endif // HTTP_CONNECTION_HPP diff --git a/source/server/connection_manager.cpp b/source/server/connection_manager.cpp new file mode 100755 index 0000000..5699ed1 --- /dev/null +++ b/source/server/connection_manager.cpp @@ -0,0 +1,40 @@ +// +// connection_manager.cpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "connection_manager.hpp" + +namespace http { +namespace server { + +connection_manager::connection_manager() +{ +} + +void connection_manager::start(connection_ptr c) +{ + connections_.insert(c); + c->start(); +} + +void connection_manager::stop(connection_ptr c) +{ + connections_.erase(c); + c->stop(); +} + +void connection_manager::stop_all() +{ + for (auto c: connections_) + c->stop(); + connections_.clear(); +} + +} // namespace server +} // namespace http diff --git a/source/server/connection_manager.hpp b/source/server/connection_manager.hpp new file mode 100755 index 0000000..400d14b --- /dev/null +++ b/source/server/connection_manager.hpp @@ -0,0 +1,48 @@ +// +// connection_manager.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_CONNECTION_MANAGER_HPP +#define HTTP_CONNECTION_MANAGER_HPP + +#include +#include "connection.hpp" + +namespace http { +namespace server { + +/// Manages open connections so that they may be cleanly stopped when the server +/// needs to shut down. +class connection_manager +{ +public: + connection_manager(const connection_manager&) = delete; + connection_manager& operator=(const connection_manager&) = delete; + + /// Construct a connection manager. + connection_manager(); + + /// Add the specified connection to the manager and start it. + void start(connection_ptr c); + + /// Stop the specified connection. + void stop(connection_ptr c); + + /// Stop all connections. + void stop_all(); + +private: + /// The managed connections. + std::set connections_; +}; + +} // namespace server +} // namespace http + +#endif // HTTP_CONNECTION_MANAGER_HPP diff --git a/source/server/header.hpp b/source/server/header.hpp new file mode 100755 index 0000000..524097e --- /dev/null +++ b/source/server/header.hpp @@ -0,0 +1,28 @@ +// +// header.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_HEADER_HPP +#define HTTP_HEADER_HPP + +#include + +namespace http { +namespace server { + +struct header +{ + std::string name; + std::string value; +}; + +} // namespace server +} // namespace http + +#endif // HTTP_HEADER_HPP diff --git a/source/server/main.cpp b/source/server/main.cpp new file mode 100755 index 0000000..e57e7e6 --- /dev/null +++ b/source/server/main.cpp @@ -0,0 +1,28 @@ +// +// main.cpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include +#include +#include +#include + +int main(int argc, char* argv[]) +{ + const std::string ip = "0.0.0.0"; + const std::string port = "8000"; + const std::string path = "./"; + + std::cout << "Serving HTTP on " << ip << " port " << port << " ..." << std::endl; + + http::server::server s(ip, port, path); + s.run(); + + return 0; +} diff --git a/source/server/mime_types.cpp b/source/server/mime_types.cpp new file mode 100755 index 0000000..5741410 --- /dev/null +++ b/source/server/mime_types.cpp @@ -0,0 +1,46 @@ +// +// mime_types.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "mime_types.hpp" + +namespace http { +namespace server { +namespace mime_types { + +struct mapping +{ + const char* extension; + const char* mime_type; +} mappings[] = +{ + { "gif", "image/gif" }, + { "htm", "text/html" }, + { "html", "text/html" }, + { "jpg", "image/jpeg" }, + { "png", "image/png" }, + { "css", "text/css" } +}; + +std::string extension_to_type(const std::string& extension) +{ + for (mapping m: mappings) + { + if (m.extension == extension) + { + return m.mime_type; + } + } + + return "text/plain"; +} + +} // namespace mime_types +} // namespace server +} // namespace http diff --git a/source/server/mime_types.hpp b/source/server/mime_types.hpp new file mode 100755 index 0000000..e5881f2 --- /dev/null +++ b/source/server/mime_types.hpp @@ -0,0 +1,27 @@ +// +// mime_types.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_MIME_TYPES_HPP +#define HTTP_MIME_TYPES_HPP + +#include + +namespace http { +namespace server { +namespace mime_types { + +/// Convert a file extension into a MIME type. +std::string extension_to_type(const std::string& extension); + +} // namespace mime_types +} // namespace server +} // namespace http + +#endif // HTTP_MIME_TYPES_HPP diff --git a/source/server/reply.cpp b/source/server/reply.cpp new file mode 100755 index 0000000..5651d65 --- /dev/null +++ b/source/server/reply.cpp @@ -0,0 +1,255 @@ +// +// reply.cpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "reply.hpp" +#include + +namespace http { +namespace server { + +namespace status_strings { + +const std::string ok = + "HTTP/1.0 200 OK\r\n"; +const std::string created = + "HTTP/1.0 201 Created\r\n"; +const std::string accepted = + "HTTP/1.0 202 Accepted\r\n"; +const std::string no_content = + "HTTP/1.0 204 No Content\r\n"; +const std::string multiple_choices = + "HTTP/1.0 300 Multiple Choices\r\n"; +const std::string moved_permanently = + "HTTP/1.0 301 Moved Permanently\r\n"; +const std::string moved_temporarily = + "HTTP/1.0 302 Moved Temporarily\r\n"; +const std::string not_modified = + "HTTP/1.0 304 Not Modified\r\n"; +const std::string bad_request = + "HTTP/1.0 400 Bad Request\r\n"; +const std::string unauthorized = + "HTTP/1.0 401 Unauthorized\r\n"; +const std::string forbidden = + "HTTP/1.0 403 Forbidden\r\n"; +const std::string not_found = + "HTTP/1.0 404 Not Found\r\n"; +const std::string internal_server_error = + "HTTP/1.0 500 Internal Server Error\r\n"; +const std::string not_implemented = + "HTTP/1.0 501 Not Implemented\r\n"; +const std::string bad_gateway = + "HTTP/1.0 502 Bad Gateway\r\n"; +const std::string service_unavailable = + "HTTP/1.0 503 Service Unavailable\r\n"; + +boost::asio::const_buffer to_buffer(reply::status_type status) +{ + switch (status) + { + case reply::ok: + return boost::asio::buffer(ok); + case reply::created: + return boost::asio::buffer(created); + case reply::accepted: + return boost::asio::buffer(accepted); + case reply::no_content: + return boost::asio::buffer(no_content); + case reply::multiple_choices: + return boost::asio::buffer(multiple_choices); + case reply::moved_permanently: + return boost::asio::buffer(moved_permanently); + case reply::moved_temporarily: + return boost::asio::buffer(moved_temporarily); + case reply::not_modified: + return boost::asio::buffer(not_modified); + case reply::bad_request: + return boost::asio::buffer(bad_request); + case reply::unauthorized: + return boost::asio::buffer(unauthorized); + case reply::forbidden: + return boost::asio::buffer(forbidden); + case reply::not_found: + return boost::asio::buffer(not_found); + case reply::internal_server_error: + return boost::asio::buffer(internal_server_error); + case reply::not_implemented: + return boost::asio::buffer(not_implemented); + case reply::bad_gateway: + return boost::asio::buffer(bad_gateway); + case reply::service_unavailable: + return boost::asio::buffer(service_unavailable); + default: + return boost::asio::buffer(internal_server_error); + } +} + +} // namespace status_strings + +namespace misc_strings { + +const char name_value_separator[] = { ':', ' ' }; +const char crlf[] = { '\r', '\n' }; + +} // namespace misc_strings + +std::vector reply::to_buffers() +{ + std::vector buffers; + buffers.push_back(status_strings::to_buffer(status)); + for (std::size_t i = 0; i < headers.size(); ++i) + { + header& h = headers[i]; + buffers.push_back(boost::asio::buffer(h.name)); + buffers.push_back(boost::asio::buffer(misc_strings::name_value_separator)); + buffers.push_back(boost::asio::buffer(h.value)); + buffers.push_back(boost::asio::buffer(misc_strings::crlf)); + } + buffers.push_back(boost::asio::buffer(misc_strings::crlf)); + buffers.push_back(boost::asio::buffer(content)); + return buffers; +} + +namespace stock_replies { + +const char ok[] = ""; +const char created[] = + "" + "Created" + "

201 Created

" + ""; +const char accepted[] = + "" + "Accepted" + "

202 Accepted

" + ""; +const char no_content[] = + "" + "No Content" + "

204 Content

" + ""; +const char multiple_choices[] = + "" + "Multiple Choices" + "

300 Multiple Choices

" + ""; +const char moved_permanently[] = + "" + "Moved Permanently" + "

301 Moved Permanently

" + ""; +const char moved_temporarily[] = + "" + "Moved Temporarily" + "

302 Moved Temporarily

" + ""; +const char not_modified[] = + "" + "Not Modified" + "

304 Not Modified

" + ""; +const char bad_request[] = + "" + "Bad Request" + "

400 Bad Request

" + ""; +const char unauthorized[] = + "" + "Unauthorized" + "

401 Unauthorized

" + ""; +const char forbidden[] = + "" + "Forbidden" + "

403 Forbidden

" + ""; +const char not_found[] = + "" + "Not Found" + "

404 Not Found

" + ""; +const char internal_server_error[] = + "" + "Internal Server Error" + "

500 Internal Server Error

" + ""; +const char not_implemented[] = + "" + "Not Implemented" + "

501 Not Implemented

" + ""; +const char bad_gateway[] = + "" + "Bad Gateway" + "

502 Bad Gateway

" + ""; +const char service_unavailable[] = + "" + "Service Unavailable" + "

503 Service Unavailable

" + ""; + +std::string to_string(reply::status_type status) +{ + switch (status) + { + case reply::ok: + return ok; + case reply::created: + return created; + case reply::accepted: + return accepted; + case reply::no_content: + return no_content; + case reply::multiple_choices: + return multiple_choices; + case reply::moved_permanently: + return moved_permanently; + case reply::moved_temporarily: + return moved_temporarily; + case reply::not_modified: + return not_modified; + case reply::bad_request: + return bad_request; + case reply::unauthorized: + return unauthorized; + case reply::forbidden: + return forbidden; + case reply::not_found: + return not_found; + case reply::internal_server_error: + return internal_server_error; + case reply::not_implemented: + return not_implemented; + case reply::bad_gateway: + return bad_gateway; + case reply::service_unavailable: + return service_unavailable; + default: + return internal_server_error; + } +} + +} // namespace stock_replies + +reply reply::stock_reply(reply::status_type status) +{ + reply rep; + rep.status = status; + rep.content = stock_replies::to_string(status); + rep.headers.resize(2); + rep.headers[0].name = "Content-Length"; + rep.headers[0].value = std::to_string(rep.content.size()); + rep.headers[1].name = "Content-Type"; + rep.headers[1].value = "text/html"; + return rep; +} + +} // namespace server +} // namespace http diff --git a/source/server/reply.hpp b/source/server/reply.hpp new file mode 100755 index 0000000..f391121 --- /dev/null +++ b/source/server/reply.hpp @@ -0,0 +1,64 @@ +// +// reply.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_REPLY_HPP +#define HTTP_REPLY_HPP + +#include +#include +#include +#include "header.hpp" + +namespace http { +namespace server { + +/// A reply to be sent to a client. +struct reply +{ + /// The status of the reply. + enum status_type + { + ok = 200, + created = 201, + accepted = 202, + no_content = 204, + multiple_choices = 300, + moved_permanently = 301, + moved_temporarily = 302, + not_modified = 304, + bad_request = 400, + unauthorized = 401, + forbidden = 403, + not_found = 404, + internal_server_error = 500, + not_implemented = 501, + bad_gateway = 502, + service_unavailable = 503 + } status; + + /// The headers to be included in the reply. + std::vector
headers; + + /// The content to be sent in the reply. + std::string content; + + /// Convert the reply into a vector of buffers. The buffers do not own the + /// underlying memory blocks, therefore the reply object must remain valid and + /// not be changed until the write operation has completed. + std::vector to_buffers(); + + /// Get a stock reply. + static reply stock_reply(status_type status); +}; + +} // namespace server +} // namespace http + +#endif // HTTP_REPLY_HPP diff --git a/source/server/request.hpp b/source/server/request.hpp new file mode 100755 index 0000000..da858c3 --- /dev/null +++ b/source/server/request.hpp @@ -0,0 +1,35 @@ +// +// request.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_REQUEST_HPP +#define HTTP_REQUEST_HPP + +#include +#include +#include "header.hpp" + +namespace http { +namespace server { + +/// A request received from a client. +struct request +{ + std::string method; + std::string uri; + int http_version_major; + int http_version_minor; + std::vector
headers; + std::string body; +}; + +} // namespace server +} // namespace http + +#endif // HTTP_REQUEST_HPP diff --git a/source/server/request_handler.cpp b/source/server/request_handler.cpp new file mode 100755 index 0000000..26ed26b --- /dev/null +++ b/source/server/request_handler.cpp @@ -0,0 +1,173 @@ +// +// request_handler.cpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "request_handler.hpp" +#include +#include +#include +#include +#include +#include "mime_types.hpp" +#include "reply.hpp" +#include "request.hpp" + +namespace http { +namespace server { + +request_handler::request_handler(const std::string& doc_root) + : doc_root_(doc_root), + simulation_(2000, 50000000, 100000) +{ + simulation_.add_entity(brain_); +} + +void request_handler::handle_request(const request& req, reply& rep) +{ + // Decode url to path. + std::string request_path; + if (!url_decode(req.uri, request_path)) + { + rep = reply::stock_reply(reply::bad_request); + return; + } + + // Request path must be absolute and not contain "..". + if (request_path.empty() || request_path[0] != '/' + || request_path.find("..") != std::string::npos) + { + rep = reply::stock_reply(reply::bad_request); + return; + } + + if (request_path.substr(0, 5) == "/api/") + { + auto target = request_path.substr(5); + std::string response_string; + + if (target == "load_script") + { + brain_.load(req.body); + } + else if (target == "state") + { + simulation_.step();// simulation_.step(); simulation_.step(); + response_string = brain_.serialize_state(); + } + else if (target == "structure") + { + response_string = brain_.serialize_structure(); + } + else if (target == "step") + { + simulation_.step(); + } + else if (target == "get_sim_time") + { + response_string = std::to_string(simulation_.get_total_sim_time()); + } + else if (target == "train") + { + auto json = nlohmann::json::parse(req.body); + brain_.train(json["image"], json["expected"]); + } + else if (target == "input_image") + { + brain_.set_input_image(req.body); + } + + // new std::thread([](cort::simulation *s) { s->start(); }, &simulation_); + + rep.status = reply::ok; + rep.content = response_string; + rep.headers.resize(2); + rep.headers[0].name = "Content-Length"; + rep.headers[0].value = std::to_string(rep.content.size()); + rep.headers[1].name = "Content-Type"; + rep.headers[1].value = mime_types::extension_to_type("text/json"); + return; + } + + // If path ends in slash (i.e. is a directory) then add "index.html". + if (request_path[request_path.size() - 1] == '/') + { + request_path += "index.html"; + } + + // Determine the file extension. + std::size_t last_slash_pos = request_path.find_last_of("/"); + std::size_t last_dot_pos = request_path.find_last_of("."); + std::string extension; + if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) + { + extension = request_path.substr(last_dot_pos + 1); + } + + // Open the file to send back. + std::string full_path = doc_root_ + request_path; + std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); + if (!is) + { + rep = reply::stock_reply(reply::not_found); + return; + } + + // Fill out the reply to be sent to the client. + rep.status = reply::ok; + char buf[512]; + while (is.read(buf, sizeof(buf)).gcount() > 0) + rep.content.append(buf, is.gcount()); + rep.headers.resize(2); + rep.headers[0].name = "Content-Length"; + rep.headers[0].value = std::to_string(rep.content.size()); + rep.headers[1].name = "Content-Type"; + rep.headers[1].value = mime_types::extension_to_type(extension); +} + +bool request_handler::url_decode(const std::string& in, std::string& out) +{ + out.clear(); + out.reserve(in.size()); + for (std::size_t i = 0; i < in.size(); ++i) + { + if (in[i] == '%') + { + if (i + 3 <= in.size()) + { + int value = 0; + std::istringstream is(in.substr(i + 1, 2)); + if (is >> std::hex >> value) + { + out += static_cast(value); + i += 2; + } + else + { + return false; + } + } + else + { + return false; + } + } + else if (in[i] == '+') + { + out += ' '; + } + else + { + out += in[i]; + } + } + return true; +} + +} // namespace server +} // namespace http diff --git a/source/server/request_handler.hpp b/source/server/request_handler.hpp new file mode 100755 index 0000000..d8c83a4 --- /dev/null +++ b/source/server/request_handler.hpp @@ -0,0 +1,52 @@ +// +// request_handler.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_REQUEST_HANDLER_HPP +#define HTTP_REQUEST_HANDLER_HPP + +#include + +#include "simulation/simulation.hpp" + +namespace http { +namespace server { + +struct reply; +struct request; + +/// The common handler for all incoming requests. +class request_handler +{ +public: + request_handler(const request_handler&) = delete; + request_handler& operator=(const request_handler&) = delete; + + /// Construct with a directory containing files to be served. + explicit request_handler(const std::string& doc_root); + + /// Handle a request and produce a reply. + void handle_request(const request& req, reply& rep); + +private: + /// The directory containing the files to be served. + std::string doc_root_; + + /// Perform URL-decoding on a string. Returns false if the encoding was + /// invalid. + static bool url_decode(const std::string& in, std::string& out); + + cort::simulation simulation_; + cort::brain brain_; +}; + +} // namespace server +} // namespace http + +#endif // HTTP_REQUEST_HANDLER_HPP diff --git a/source/server/request_parser.cpp b/source/server/request_parser.cpp new file mode 100755 index 0000000..457d4f2 --- /dev/null +++ b/source/server/request_parser.cpp @@ -0,0 +1,333 @@ +// +// request_parser.cpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +#include +#include "request_parser.hpp" +#include "request.hpp" + +namespace http { +namespace server { + +request_parser::request_parser() + : state_(method_start), + body_content_length_(0) +{ +} + +void request_parser::reset() +{ + state_ = method_start; + body_content_length_ = 0; +} + +request_parser::result_type request_parser::consume(request& req, char input) +{ + switch (state_) + { + case method_start: + if (!is_char(input) || is_ctl(input) || is_tspecial(input)) + { + return bad; + } + else + { + state_ = method; + req.method.push_back(input); + return indeterminate; + } + case method: + if (input == ' ') + { + state_ = uri; + return indeterminate; + } + else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) + { + return bad; + } + else + { + req.method.push_back(input); + return indeterminate; + } + case uri: + if (input == ' ') + { + state_ = http_version_h; + return indeterminate; + } + else if (is_ctl(input)) + { + return bad; + } + else + { + req.uri.push_back(input); + return indeterminate; + } + case http_version_h: + if (input == 'H') + { + state_ = http_version_t_1; + return indeterminate; + } + else + { + return bad; + } + case http_version_t_1: + if (input == 'T') + { + state_ = http_version_t_2; + return indeterminate; + } + else + { + return bad; + } + case http_version_t_2: + if (input == 'T') + { + state_ = http_version_p; + return indeterminate; + } + else + { + return bad; + } + case http_version_p: + if (input == 'P') + { + state_ = http_version_slash; + return indeterminate; + } + else + { + return bad; + } + case http_version_slash: + if (input == '/') + { + req.http_version_major = 0; + req.http_version_minor = 0; + state_ = http_version_major_start; + return indeterminate; + } + else + { + return bad; + } + case http_version_major_start: + if (is_digit(input)) + { + req.http_version_major = req.http_version_major * 10 + input - '0'; + state_ = http_version_major; + return indeterminate; + } + else + { + return bad; + } + case http_version_major: + if (input == '.') + { + state_ = http_version_minor_start; + return indeterminate; + } + else if (is_digit(input)) + { + req.http_version_major = req.http_version_major * 10 + input - '0'; + return indeterminate; + } + else + { + return bad; + } + case http_version_minor_start: + if (is_digit(input)) + { + req.http_version_minor = req.http_version_minor * 10 + input - '0'; + state_ = http_version_minor; + return indeterminate; + } + else + { + return bad; + } + case http_version_minor: + if (input == '\r') + { + state_ = expecting_newline_1; + return indeterminate; + } + else if (is_digit(input)) + { + req.http_version_minor = req.http_version_minor * 10 + input - '0'; + return indeterminate; + } + else + { + return bad; + } + case expecting_newline_1: + if (input == '\n') + { + state_ = header_line_start; + return indeterminate; + } + else + { + return bad; + } + case header_line_start: + if (input == '\r') + { + state_ = expecting_newline_3; + return indeterminate; + } + else if (!req.headers.empty() && (input == ' ' || input == '\t')) + { + state_ = header_lws; + return indeterminate; + } + else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) + { + return bad; + } + else + { + req.headers.push_back(header()); + req.headers.back().name.push_back(input); + state_ = header_name; + return indeterminate; + } + case header_lws: + if (input == '\r') + { + state_ = expecting_newline_2; + return indeterminate; + } + else if (input == ' ' || input == '\t') + { + return indeterminate; + } + else if (is_ctl(input)) + { + return bad; + } + else + { + state_ = header_value; + req.headers.back().value.push_back(input); + return indeterminate; + } + case header_name: + if (input == ':') + { + state_ = space_before_header_value; + return indeterminate; + } + else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) + { + return bad; + } + else + { + req.headers.back().name.push_back(input); + return indeterminate; + } + case space_before_header_value: + if (input == ' ') + { + state_ = header_value; + return indeterminate; + } + else + { + return bad; + } + case header_value: + if (input == '\r') + { + if (req.headers.back().name == "Content-Length") + { + body_content_length_ = std::stoi(req.headers.back().value); + } + state_ = expecting_newline_2; + return indeterminate; + } + else if (is_ctl(input)) + { + return bad; + } + else + { + req.headers.back().value.push_back(input); + return indeterminate; + } + case expecting_newline_2: + if (input == '\n') + { + state_ = header_line_start; + return indeterminate; + } + else + { + return bad; + } + case expecting_newline_3: + if (body_content_length_ > 0) + { + state_ = body; + return indeterminate; + } + return (input == '\n') ? good : bad; + case body: + req.body.push_back(input); + if (req.body.length() < body_content_length_) + { + return indeterminate; + } + return good; + default: + return bad; + } +} + +bool request_parser::is_char(int c) +{ + return c >= 0 && c <= 127; +} + +bool request_parser::is_ctl(int c) +{ + return (c >= 0 && c <= 31) || (c == 127); +} + +bool request_parser::is_tspecial(int c) +{ + switch (c) + { + case '(': case ')': case '<': case '>': case '@': + case ',': case ';': case ':': case '\\': case '"': + case '/': case '[': case ']': case '?': case '=': + case '{': case '}': case ' ': case '\t': + return true; + default: + return false; + } +} + +bool request_parser::is_digit(int c) +{ + return c >= '0' && c <= '9'; +} + +} // namespace server +} // namespace http diff --git a/source/server/request_parser.hpp b/source/server/request_parser.hpp new file mode 100755 index 0000000..c636a6b --- /dev/null +++ b/source/server/request_parser.hpp @@ -0,0 +1,99 @@ +// +// request_parser.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_REQUEST_PARSER_HPP +#define HTTP_REQUEST_PARSER_HPP + +#include + +namespace http { +namespace server { + +struct request; + +/// Parser for incoming requests. +class request_parser +{ +public: + /// Construct ready to parse the request method. + request_parser(); + + /// Reset to initial parser state. + void reset(); + + /// Result of parse. + enum result_type { good, bad, indeterminate }; + + /// Parse some data. The enum return value is good when a complete request has + /// been parsed, bad if the data is invalid, indeterminate when more data is + /// required. The InputIterator return value indicates how much of the input + /// has been consumed. + template + std::tuple parse(request& req, + InputIterator begin, InputIterator end) + { + while (begin != end) + { + result_type result = consume(req, *begin++); + if (result == good || result == bad) + return std::make_tuple(result, begin); + } + return std::make_tuple(indeterminate, begin); + } + +private: + /// Handle the next character of input. + result_type consume(request& req, char input); + + /// Check if a byte is an HTTP character. + static bool is_char(int c); + + /// Check if a byte is an HTTP control character. + static bool is_ctl(int c); + + /// Check if a byte is defined as an HTTP tspecial character. + static bool is_tspecial(int c); + + /// Check if a byte is a digit. + static bool is_digit(int c); + + /// The current state of the parser. + enum state + { + method_start, + method, + uri, + http_version_h, + http_version_t_1, + http_version_t_2, + http_version_p, + http_version_slash, + http_version_major_start, + http_version_major, + http_version_minor_start, + http_version_minor, + expecting_newline_1, + header_line_start, + header_lws, + header_name, + space_before_header_value, + header_value, + expecting_newline_2, + expecting_newline_3, + body + } state_; + + std::size_t body_content_length_; +}; + +} // namespace server +} // namespace http + +#endif // HTTP_REQUEST_PARSER_HPP diff --git a/source/server/server.cpp b/source/server/server.cpp new file mode 100755 index 0000000..25ad6b4 --- /dev/null +++ b/source/server/server.cpp @@ -0,0 +1,94 @@ +// +// server.cpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "server.hpp" +#include +#include + +namespace http { +namespace server { + +server::server(const std::string& address, const std::string& port, + const std::string& doc_root) + : io_service_(), + signals_(io_service_), + acceptor_(io_service_), + connection_manager_(), + socket_(io_service_), + request_handler_(doc_root) +{ + // Register to handle the signals that indicate when the server should exit. + // It is safe to register for the same signal multiple times in a program, + // provided all registration for the specified signal is made through Asio. + signals_.add(SIGINT); + signals_.add(SIGTERM); +#if defined(SIGQUIT) + signals_.add(SIGQUIT); +#endif // defined(SIGQUIT) + + do_await_stop(); + + // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). + boost::asio::ip::tcp::resolver resolver(io_service_); + boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve({address, port}); + acceptor_.open(endpoint.protocol()); + acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); + acceptor_.bind(endpoint); + acceptor_.listen(); + + do_accept(); +} + +void server::run() +{ + // The io_service::run() call will block until all asynchronous operations + // have finished. While the server is running, there is always at least one + // asynchronous operation outstanding: the asynchronous accept call waiting + // for new incoming connections. + io_service_.run(); +} + +void server::do_accept() +{ + acceptor_.async_accept(socket_, + [this](boost::system::error_code ec) + { + // Check whether the server was stopped by a signal before this + // completion handler had a chance to run. + if (!acceptor_.is_open()) + { + return; + } + + if (!ec) + { + connection_manager_.start(std::make_shared( + std::move(socket_), connection_manager_, request_handler_)); + } + + do_accept(); + }); +} + +void server::do_await_stop() +{ + signals_.async_wait( + [this](boost::system::error_code /*ec*/, int /*signo*/) + { + // The server is stopped by cancelling all outstanding asynchronous + // operations. Once all operations have finished the io_service::run() + // call will exit. + acceptor_.close(); + connection_manager_.stop_all(); + }); +} + +} // namespace server +} // namespace http diff --git a/source/server/server.hpp b/source/server/server.hpp new file mode 100755 index 0000000..39fc3a4 --- /dev/null +++ b/source/server/server.hpp @@ -0,0 +1,67 @@ +// +// server.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef HTTP_SERVER_HPP +#define HTTP_SERVER_HPP + +#include +#include +#include "connection.hpp" +#include "connection_manager.hpp" +#include "request_handler.hpp" + +namespace http { +namespace server { + +/// The top-level class of the HTTP server. +class server +{ +public: + server(const server&) = delete; + server& operator=(const server&) = delete; + + /// Construct the server to listen on the specified TCP address and port, and + /// serve up files from the given directory. + explicit server(const std::string& address, const std::string& port, + const std::string& doc_root); + + /// Run the server's io_service loop. + void run(); + +private: + /// Perform an asynchronous accept operation. + void do_accept(); + + /// Wait for a request to stop the server. + void do_await_stop(); + + /// The io_service used to perform asynchronous operations. + boost::asio::io_service io_service_; + + /// The signal_set is used to register for process termination notifications. + boost::asio::signal_set signals_; + + /// Acceptor used to listen for incoming connections. + boost::asio::ip::tcp::acceptor acceptor_; + + /// The connection manager which owns all live connections. + connection_manager connection_manager_; + + /// The next socket to be accepted. + boost::asio::ip::tcp::socket socket_; + + /// The handler for all incoming requests. + request_handler request_handler_; +}; + +} // namespace server +} // namespace http + +#endif // HTTP_SERVER_HPP diff --git a/source/simulation/entity.cpp b/source/simulation/entity.cpp new file mode 100644 index 0000000..ede72db --- /dev/null +++ b/source/simulation/entity.cpp @@ -0,0 +1,39 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "simulation/entity.hpp" + +namespace cort { + +int entity::next_id_ = 0; + +entity::entity() : + id_(next_id_++) +{ +} + +entity::~entity() +{ +} + +} // namespace cort diff --git a/source/simulation/entity.hpp b/source/simulation/entity.hpp new file mode 100644 index 0000000..2ea69cf --- /dev/null +++ b/source/simulation/entity.hpp @@ -0,0 +1,51 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +namespace cort { + +class layer; + +class entity +{ +public: + entity(); + virtual ~entity() = 0; + + int get_id() { return id_; } + + virtual std::string serialize_structure() const = 0; + virtual std::string serialize_state() const = 0; + + virtual void update(double time) = 0; + virtual void reset() = 0; + virtual layer *get_layer(const std::string &name) = 0; + +private: + static int next_id_; + int id_; +}; + +} // namespace cort diff --git a/source/simulation/random_number_generator.cpp b/source/simulation/random_number_generator.cpp new file mode 100644 index 0000000..3d1af5f --- /dev/null +++ b/source/simulation/random_number_generator.cpp @@ -0,0 +1,133 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include + +#include "simulation/random_number_generator.hpp" + +namespace cort { + +random_number_generator::random_number_generator() +{ + std::time_t time = std::time(0); + seed(static_cast(time)); +} + +random_number_generator::random_number_generator(int seed) +{ + this->seed(seed); +} + +random_number_generator::~random_number_generator() +{ + +} + +unsigned int random_number_generator::rand_uint() +{ + unsigned long long int sum; + sum = (unsigned long long int)2111111111UL * (unsigned long long int)x[3] + + (unsigned long long int)1492 * (unsigned long long int)(x[2]) + + (unsigned long long int)1776 * (unsigned long long int)(x[1]) + + (unsigned long long int)5115 * (unsigned long long int)(x[0]) + + (unsigned long long int)x[4]; + x[3] = x[2]; + x[2] = x[1]; + x[1] = x[0]; + x[4] = (unsigned int)(sum >> 32); + x[0] = (unsigned int)sum; + return x[0]; +} + +double random_number_generator::rand_double() +{ + return (double)rand_uint() * (1. / (65536. * 65536.)); +} + +double random_number_generator::rand_double(double max) +{ + return rand_double() * max; +} + +double random_number_generator::rand_double(double min, double max) +{ + return min + rand_double() * (max - min); +} + +int random_number_generator::rand_int(int max) +{ + return rand_int(0, max); +} + +int random_number_generator::rand_int(int min, int max) +{ + if(max <= min) + { + if(max == min) + { + return min; + } + else + { + return 0x80000000; + } + } + + unsigned int interval = (unsigned int)(max - min); + return ((int)(interval * rand_double())) + min; +} + +void random_number_generator::seed(int seed) +{ + int i; + unsigned int s = seed; + + for(i = 0; i < 5; i++) + { + s = s * 29943829 - 1; + x[i] = s; + } + + for(i = 0; i < 19; i++) + { + rand_uint(); + } +} + +std::istream &operator>>(std::istream &in, random_number_generator &rng) +{ + for(int i = 0; i < 5; i++) + { + in >> rng.x[i]; + } + + return in; +} + +std::ostream &operator<<(std::ostream &out, const random_number_generator &rng) +{ + out << rng.x[0] << " " << rng.x[1] << " " << rng.x[2] << " " << rng.x[3] << " " << rng.x[4]; + return out; +} + +} // namespace cort diff --git a/source/simulation/random_number_generator.hpp b/source/simulation/random_number_generator.hpp new file mode 100644 index 0000000..2f49800 --- /dev/null +++ b/source/simulation/random_number_generator.hpp @@ -0,0 +1,51 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +namespace cort { + +class random_number_generator +{ +public: + random_number_generator(int seed); + random_number_generator(); + ~random_number_generator(); + + void seed(int seed); + int rand_int(int min, int max); + int rand_int(int max); + double rand_double(); + double rand_double(double min); + double rand_double(double min, double max); + unsigned int rand_uint(); + + friend std::ostream &operator<<(std::ostream &out, const random_number_generator &rng); + friend std::istream &operator>>(std::istream &out, random_number_generator &rng); + +private: + unsigned int x[5]; +}; + +} // namespace cort diff --git a/source/simulation/simulation.cpp b/source/simulation/simulation.cpp new file mode 100644 index 0000000..be47b4d --- /dev/null +++ b/source/simulation/simulation.cpp @@ -0,0 +1,109 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include +#include + +#include "simulation/simulation.hpp" +#include "brain/connection.hpp" +#include "simulation/entity.hpp" +#include "simulation/timer.hpp" + +namespace cort { + +simulation::simulation(double timeToSimulate, double stepsPerRealSec, double stepsPerSimSec) : + current_step_(0), + end_step_(static_cast(timeToSimulate * stepsPerSimSec)), + real_seconds_per_step_(1 / stepsPerRealSec), + steps_per_real_second_(stepsPerRealSec), + sim_seconds_per_step_(1 / stepsPerSimSec), + steps_per_sim_second_(stepsPerSimSec), + sim_time_(timeToSimulate) +{ + +} + +simulation::~simulation() +{ + +} + +void simulation::start() +{ + std::cout << "simulation started" << std::endl; + + timer_.reset(); + double currentTime = timer_.get_time_in_seconds(); + double startTime = currentTime; + + step(); + + while(current_step_ < end_step_) + { + while(timer_.get_time_in_seconds() - currentTime < real_seconds_per_step_) + { + } + + currentTime = timer_.get_time_in_seconds(); + std::cout << current_step_ << std::endl; + + step(); + } + + std::printf("Final simulation rate: %fs(sim)/s(real)\n", sim_time_ / (currentTime - startTime)); +} + +void simulation::stop() +{ + +} + +void simulation::step() +{ + for(auto entity : entities_) + { + entity->update(current_step_ * sim_seconds_per_step_); + } + + current_step_++; +} + +void simulation::reset() +{ + for(auto entity : entities_) + { + entity->reset(); + } +} + +std::string simulation::serialize_entity_structure(std::size_t entity_index) +{ + return entities_[entity_index]->serialize_structure(); +} + +std::string simulation::serialize_entity_state(std::size_t entity_index) +{ + return entities_[entity_index]->serialize_state(); +} + +} // namespace cort diff --git a/source/simulation/simulation.hpp b/source/simulation/simulation.hpp new file mode 100644 index 0000000..9577118 --- /dev/null +++ b/source/simulation/simulation.hpp @@ -0,0 +1,95 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +#include "brain/brain.hpp" +#include "simulation/trainer.hpp" +#include "simulation/timer.hpp" + +namespace cort { + +class entity; + +class simulation +{ + public: + simulation(double timeToSimulate, double stepsPerRealSec, double stepsPerSimSec); + ~simulation(); + + void start(); + void stop(); + void reset(); + void step(); + + std::string serialize_entity_structure(std::size_t entity_index); + std::string serialize_entity_state(std::size_t entity_index); + + void add_entity(entity &ent) { entities_.push_back(&ent); } + + double get_percent_completion() { return ((double)current_step_) / end_step_; } + unsigned int get_current_step() { return current_step_; } + double get_total_sim_time() { return current_step_ * sim_seconds_per_step_; } + + void set_real_seconds_per_step(double seconds) + { + real_seconds_per_step_ = seconds; + steps_per_real_second_ = 1 / seconds; + } + double get_real_seconds_per_step() { return real_seconds_per_step_; } + + void set_steps_per_real_second(double steps) + { + steps_per_real_second_ = steps; + real_seconds_per_step_ = 1 / steps; + } + double get_steps_per_real_second() { return steps_per_real_second_; } + + void set_sim_seconds_per_step(double seconds) + { + sim_seconds_per_step_ = seconds; + steps_per_sim_second_ = 1 / seconds; + } + double get_sim_seconds_per_step() { return sim_seconds_per_step_; } + + void set_steps_per_sim_second(double steps) + { + steps_per_sim_second_ = steps; + sim_seconds_per_step_ = 1 / steps; + } + double get_steps_per_sim_second() { return steps_per_sim_second_; } + + private: + std::vector entities_; + int current_step_; + int end_step_; + double real_seconds_per_step_; + double steps_per_real_second_; + double sim_seconds_per_step_; + double steps_per_sim_second_; + double sim_time_; + timer timer_; +}; + +} // namespace cort diff --git a/source/simulation/timer.cpp b/source/simulation/timer.cpp new file mode 100644 index 0000000..b0ec066 --- /dev/null +++ b/source/simulation/timer.cpp @@ -0,0 +1,88 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "simulation/timer.hpp" + +namespace cort { + +timer::timer() +{ + reset(); +} + +timer::~timer() +{ +} + +void timer::reset() +{ +#ifndef _WIN32 + zeroClock = clock(); + gettimeofday(&start, NULL); +#else + LARGE_INTEGER ticksPerSecond; + QueryPerformanceFrequency(&ticksPerSecond); + updateFrequency = double(ticksPerSecond.QuadPart) / 1000000.0; +#endif +} + +unsigned long timer::get_time() +{ +#ifndef _WIN32 + struct timeval now; + gettimeofday(&now, NULL); + return (now.tv_sec - start.tv_sec) * 1000000 + (now.tv_usec - start.tv_usec); +#else + LARGE_INTEGER tick; + QueryPerformanceCounter(&tick); + return static_cast((tick.QuadPart - start) / updateFrequency); +#endif +} + +double timer::get_time_in_seconds() +{ + return get_time() / 1000000.0; +} + +double timer::get_resolution() +{ + reset(); + const double t0 = get_time() / 1000000.0; + double t1, t2; + + do + { + t1 = get_time() / 1000000.0; + } + while(t1 == t0); + + do + { + t2 = get_time() / 1000000.0; + } + while(t2 == t1); + + return (t2 - t1); +} + +} // namespace cort diff --git a/source/simulation/timer.hpp b/source/simulation/timer.hpp new file mode 100644 index 0000000..7f296b5 --- /dev/null +++ b/source/simulation/timer.hpp @@ -0,0 +1,56 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include +#include +#ifndef _WIN32 +#include +#else +#include +#endif + +namespace cort { + +class timer +{ + public: + timer(); + ~timer(); + + void reset(); + unsigned long get_time(); + double get_time_in_seconds(); + double get_resolution(); + + private: +#ifndef _WIN32 + struct timeval start; + clock_t zeroClock; +#else + int64_t start; + double updateFrequency; +#endif +}; + +} // namespace cort diff --git a/source/simulation/trainer.cpp b/source/simulation/trainer.cpp new file mode 100644 index 0000000..4a66e4f --- /dev/null +++ b/source/simulation/trainer.cpp @@ -0,0 +1,331 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#include "simulation/trainer.hpp" +#include "brain/brain.hpp" +#include "interface/script.hpp" +#include "simulation/entity.hpp" + +namespace cort { + +trainer::trainer(const std::string &filename, brain * /*ent*/) : script_(filename) {};/* : + m_CurrentTime(0), + m_DeltaTime(0), + m_WaitStart(0.), + m_WaitDuration(0.), + m_Waiting(false), + m_CurrentRepeats(0), + m_NumRepeats(0), + m_TimeBtStartMsgAndInput(0.), + m_TimeToWaitForTestResponse(0.), + m_TimeBtOutputAndEndMsg(0.), + m_TimeBtTrainInAndOut(0.), + m_TimeBtTrainIterations(0.), + m_TimeBtTestIterations(0.), + m_TotalTrainingIterations(0), + m_TotalTestingIterations(0), + m_CurrTrainingIteration(0), + m_CurrTestingIteration(0), + m_ID(0), + m_Input(""), + m_ExpectedOutput(""), + m_BciReward(nullptr), + m_BciInput(nullptr), + m_BciOutput(nullptr), + m_BciOutputTrainer(nullptr), + m_Script(filename), + m_State(TeachStartMsg) +{ + std::string inputCommandsFile = m_Script.GetNextString(); + std::string outputCommandsFile = m_Script.GetNextString(); + + m_BciInput = new BCI_SpeechFromFile(ent->get_layer("input"), inputCommandsFile); + m_BciReward = new BCI_RewardPunishment(ent->get_layer("output")); + m_BciOutput = new BCI_SpeechFromFile(ent->get_layer("output"), outputCommandsFile); + m_BciOutputTrainer = new BCI_SpeechFromFile(ent->get_layer("outputTrainer"), outputCommandsFile); + + m_TimeBtTrainInAndOut = m_Script.GetNextDouble(); + m_TimeBtTrainIterations = m_Script.GetNextDouble(); + m_TimeBtTestIterations = m_Script.GetNextDouble(); + m_TotalTrainingIterations = m_Script.GetNextInt(); + m_TotalTestingIterations = m_Script.GetNextInt(); + m_TimeBtStartMsgAndInput = m_Script.GetNextDouble(); + m_TimeToWaitForTestResponse = m_Script.GetNextDouble(); + m_TimeBtOutputAndEndMsg = m_Script.GetNextDouble(); + + m_Input = m_Script.GetNextString(); + m_ExpectedOutput = m_Script.GetNextString(); + m_NumRepeats = m_Script.GetNextInt(); + + Wait(m_TimeBtTrainIterations); +} +*/ + +trainer::~trainer() +{ + if(bci_input_) + delete bci_input_; + + if(bci_output_) + delete bci_output_; + + if(bci_output_trainer_) + delete bci_output_trainer_; +} + +void trainer::wait(double duration) +{ + waiting_ = true; + wait_start_ = current_time_; + wait_duration_ = duration; +} + +bool trainer::is_completed() +{ + return state_ == training_state::completed; +} + +//I guess this is a finite state machine? +//Maybe there's a better way to do it, but this made sense +void trainer::update(double /*time*/) +{ +/* + double last = m_CurrentTime; + + m_CurrentTime = time; + m_DeltaTime = m_CurrentTime - last; + + std::string output = ""; + + if(m_Waiting) + { + if(m_State == TestWaitForOutput) + { + output = m_BciOutput->get_state(); + + if(output != "") + { + m_Waiting = false; + } + } + + if(m_CurrentTime >= m_WaitStart + m_WaitDuration) + { + m_Waiting = false; + } + } + + if(!m_Waiting) + { + switch(m_State) + { + case TeachStartMsg: + { + //m_BciInput->SetState("StartTeach"); + m_State = TeachSetInput; + + Wait(m_TimeBtStartMsgAndInput); + + break; + } + + case TeachSetInput: + { + m_BciInput->set_state(m_Input); + std::printf("Taught Input: %s\n", m_Input.c_str()); + m_State = TeachSetOutput; + + Wait(m_TimeBtTrainInAndOut); + + break; + } + + case TeachSetOutput: + { + m_BciOutputTrainer->set_state(m_ExpectedOutput); + std::printf("Taught Output: %s\n", m_ExpectedOutput.c_str()); + m_State = TeachEndMsg; + + Wait(m_TimeBtOutputAndEndMsg); + + break; + } + + case TeachEndMsg: + { + //m_BciInput->set_state("EndTeach"); + + if(++m_CurrentRepeats == m_NumRepeats) + { + if(++m_CurrTrainingIteration == m_TotalTrainingIterations) + { + m_State = TestStartMsg; + m_CurrTestingIteration = 0; + + Wait(m_TimeBtTestIterations); + + break; + } + + m_Input = m_Script.GetNextString(); + m_ExpectedOutput = m_Script.GetNextString(); + m_NumRepeats = m_Script.GetNextInt(); + + m_CurrentRepeats = 0; + } + + m_State = TeachStartMsg; + + Wait(m_TimeBtTrainIterations); + + break; + } + + case TestStartMsg: + { + //m_BciInput->set_state("StartTest"); + m_State = TestSetInput; + + Wait(m_TimeBtStartMsgAndInput); + break; + } + + case TestSetInput: + { + m_Input = m_Script.GetNextString(); + m_ExpectedOutput = m_Script.GetNextString(); + + m_BciInput->set_state(m_Input); + std::printf("Testing Input: %s\n", m_Input.c_str()); + + m_State = TestWaitForOutput; + + Wait(m_TimeToWaitForTestResponse); + + break; + } + + case TestWaitForOutput: + { + std::printf("Received Response: %s (Correct Response: %s)\n", output.c_str(),m_ExpectedOutput.c_str()); + + m_BciOutput->get_neuron(m_ExpectedOutput)->BackpropagateUp(); + if(output != "" && output != m_ExpectedOutput) + { + m_BciOutput->GetNeuron(output)->BackpropagateDown(); + std::printf("Bad\n"); + //m_BciReward->set_state("Good"); + } + else + { + std::printf("Good\n"); + } + + if(output == m_ExpectedOutput) + { + m_BciOutput->GetNeuron(output)->BackpropagateUp(); + std::printf("Good\n"); + //m_BciReward->set_state("Good"); + } + else + { + if(output != "") + m_BciOutput->GetNeuron(output)->BackpropagateDown(); + else + { + for(std::map::iterator i = m_BciOutput->m_SynapseCommandMap.begin(); i != m_BciOutput->m_SynapseCommandMap.end(); i++) + { + m_BciOutput->GetNeuron(i->first)->BackpropagateUp(); + } + } + std::printf("Bad\n"); + //m_BciReward->set_state("Bad"); + } + + m_State = TestEndMsg; + + Wait(m_TimeBtOutputAndEndMsg); + + break; + } + + case TestEndMsg: + { + //m_BciInput->set_state("EndTest"); + + if(++m_CurrTestingIteration == m_TotalTestingIterations) + { + std::printf("Trainer Finished\n"); + m_State = Finished; + + Wait(m_TimeBtTestIterations); + + break; + } + + m_State = TestStartMsg; + + Wait(m_TimeBtTestIterations); + + break; + } + + case Finished: + default: + { + break; + } + } + } +*/ +} + +layer *trainer::get_layer(const std::string &name) +{ + if(name == "input") + { + return bci_input_->get_layer(); + } + else if(name == "output") + { + return bci_output_->get_layer(); + } + else if(name == "outputTrainer") + { + return bci_output_trainer_->get_layer(); + } + + return 0; +} + +void trainer::reset() +{ + +} + +void trainer::print_state() +{ + +} + +} // namespace cort diff --git a/source/simulation/trainer.hpp b/source/simulation/trainer.hpp new file mode 100644 index 0000000..057f1ff --- /dev/null +++ b/source/simulation/trainer.hpp @@ -0,0 +1,102 @@ +/* +The MIT License (MIT) + +Copyright (c) 2006-2016 Thomas Fussell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once +#include + +#include "interface/bci_speech_from_file.hpp" +#include "interface/bci_reward_punishment.hpp" +#include "interface/script.hpp" +#include "simulation/entity.hpp" + +namespace cort { + +class brain; + +enum training_state +{ + uninitialized, + initialized, + teach_start_message, + teach_set_input, + teach_set_output, + teach_end_message, + test_start_message, + test_set_input, + test_attend_output, + test_end_message, + completed +}; + +class trainer : public entity +{ +public: + trainer(); + trainer(const std::string &scriptFilename, brain *brain); + ~trainer(); + + bool is_completed(); + void update(double time); + void reset(); + void print_state(); + layer *get_layer(const std::string &inter); + +private: + void wait(double duration); + + double current_time_; + double delta_time_; + double wait_start_; + double wait_duration_; + bool waiting_; + + int repeat_; + int num_repeats_; + + double time_between_start_message_and_input_; + double time_to_wait_for_test_response_; + double time_between_output_and_end_; + + double time_between_train_in_and_out_; + double time_between_train_iterations_; + double time_between_test_iterations_; + + int total_training_iterations_; + int total_testing_iterations_; + + int training_iteration_; + int testing_iteration_; + + std::string input_; + std::string expected_output_; + + bci_reward_punishment *bci_reward_; + bci_speech_from_file *bci_input_; + bci_speech_from_file *bci_output_; + bci_speech_from_file *bci_output_trainer_; + + script script_; + training_state state_; +}; + +} // namespace cort diff --git a/viewer b/viewer new file mode 160000 index 0000000..857cd88 --- /dev/null +++ b/viewer @@ -0,0 +1 @@ +Subproject commit 857cd886630ca25563dbdccaea6fd46d22f6a532