├── workspace ├── assets │ ├── server │ │ └── index.ts │ └── client │ │ ├── index.ts │ │ ├── core │ │ ├── types.ts │ │ └── networksRetriever.ts │ │ ├── infrastructure │ │ ├── ui │ │ │ └── react │ │ │ │ ├── prototype │ │ │ │ ├── Network.tsx │ │ │ │ ├── EventList.tsx │ │ │ │ ├── ProjectCreation.tsx │ │ │ │ ├── ProjectExecution.tsx │ │ │ │ ├── ProjectSelection.tsx │ │ │ │ ├── NetworkGraph.tsx │ │ │ │ ├── ProjectDeployment.tsx │ │ │ │ ├── ProjectExportation.tsx │ │ │ │ ├── NetworkCreation.tsx │ │ │ │ ├── NetworkPipeline.tsx │ │ │ │ ├── NetworkQuerying.tsx │ │ │ │ ├── NetworkTraining.tsx │ │ │ │ ├── NetworkList.tsx │ │ │ │ └── Frame.tsx │ │ │ │ ├── NetworkList.tsx │ │ │ │ ├── hooks │ │ │ │ └── useNetworks.ts │ │ │ │ ├── index.tsx │ │ │ │ ├── Application.tsx │ │ │ │ └── Frame.tsx │ │ └── dataSource │ │ │ └── http.ts │ │ └── bootstrapper.tsx ├── .prettierignore ├── .parcelrc ├── tests │ ├── acceptance │ │ ├── server │ │ │ └── test.ts │ │ └── client │ │ │ ├── user-should-be-able-to-create-a-project-with-multiple-networks-connected-as-a-graph.test.tsx │ │ │ └── user-should-be-able-to-switch-to-ui-prototype.test.tsx │ ├── unit │ │ ├── client │ │ │ └── index.test.tsx │ │ └── server │ │ │ └── index.test.ts │ └── mocks │ │ └── api.json ├── README.md ├── .prettierrc ├── public │ └── index.html ├── .eslintrc ├── jest.config.json ├── LICENSE ├── TODO.md ├── package.json └── tsconfig.json ├── examples ├── .prettierrc ├── .prettierignore ├── .parcelrc ├── assets │ ├── browser-test-network-alpha-continuous │ │ ├── index.html │ │ └── index.ts │ ├── browser-test-network-alpha-stepbystep │ │ ├── index.html │ │ └── index.ts │ ├── cli-test-network-alpha-continuous-0.ts │ ├── cli-test-network-alpha-continuous-1.ts │ ├── cli-test-network-alpha-continuous-2.ts │ ├── cli-test-network-alpha-continuous-3.ts │ ├── cli-test-network-alpha-stepbystep-0.ts │ └── cli-test-network-alpha-continuous-4.ts ├── .eslintrc ├── TODO.md ├── LICENSE ├── README.md ├── package.json └── tsconfig.json ├── .gitignore ├── library ├── .prettierignore ├── .parcelrc ├── .npmignore ├── .prettierrc ├── jest.config.json ├── .eslintrc ├── assets │ ├── infrastructure │ │ └── Calculator │ │ │ └── MathJSCalculator.ts │ ├── core │ │ ├── networks │ │ │ ├── alpha │ │ │ │ ├── NeuronFactory.ts │ │ │ │ ├── SynapseFactory.ts │ │ │ │ ├── NetworkFactory.ts │ │ │ │ ├── types.ts │ │ │ │ ├── Synapse.ts │ │ │ │ ├── Neuron.ts │ │ │ │ └── Network.ts │ │ │ └── types.ts │ │ ├── Brain.ts │ │ ├── BrainFactory.ts │ │ ├── CerebrumFactory.ts │ │ ├── Cerebrum.ts │ │ └── types.ts │ ├── index.ts │ └── bootstrapper.ts ├── LICENSE ├── webpack.config.js ├── package.json ├── TODO.md ├── tests │ └── acceptance │ │ └── should-be-able-to-solve-the-xor-problem.test.ts ├── CHANGELOG.md ├── README.md └── tsconfig.json ├── perception1-large.png ├── perception1-small.png ├── perception10-large.png ├── perception10-small.png ├── perception2-large.png ├── perception2-small.png ├── perception3-large.png ├── perception3-small.png ├── perception4-large.png ├── perception4-small.png ├── perception5-large.png ├── perception5-small.png ├── perception6-large.png ├── perception6-small.png ├── perception7-large.png ├── perception7-small.png ├── perception8-large.png ├── perception8-small.png ├── perception9-large.png ├── perception9-small.png ├── CONTRIBUTING.md ├── README.md └── LICENSE /workspace/assets/server/index.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .parcel-cache 2 | coverage 3 | dist 4 | distributed 5 | node_modules 6 | -------------------------------------------------------------------------------- /examples/.prettierignore: -------------------------------------------------------------------------------- 1 | .parcel-cache 2 | coverage 3 | dist 4 | node_modules 5 | -------------------------------------------------------------------------------- /library/.prettierignore: -------------------------------------------------------------------------------- 1 | .parcel-cache 2 | coverage 3 | dist 4 | node_modules 5 | -------------------------------------------------------------------------------- /workspace/.prettierignore: -------------------------------------------------------------------------------- 1 | .parcel-cache 2 | coverage 3 | dist 4 | node_modules 5 | -------------------------------------------------------------------------------- /perception1-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception1-large.png -------------------------------------------------------------------------------- /perception1-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception1-small.png -------------------------------------------------------------------------------- /perception10-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception10-large.png -------------------------------------------------------------------------------- /perception10-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception10-small.png -------------------------------------------------------------------------------- /perception2-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception2-large.png -------------------------------------------------------------------------------- /perception2-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception2-small.png -------------------------------------------------------------------------------- /perception3-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception3-large.png -------------------------------------------------------------------------------- /perception3-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception3-small.png -------------------------------------------------------------------------------- /perception4-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception4-large.png -------------------------------------------------------------------------------- /perception4-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception4-small.png -------------------------------------------------------------------------------- /perception5-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception5-large.png -------------------------------------------------------------------------------- /perception5-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception5-small.png -------------------------------------------------------------------------------- /perception6-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception6-large.png -------------------------------------------------------------------------------- /perception6-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception6-small.png -------------------------------------------------------------------------------- /perception7-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception7-large.png -------------------------------------------------------------------------------- /perception7-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception7-small.png -------------------------------------------------------------------------------- /perception8-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception8-large.png -------------------------------------------------------------------------------- /perception8-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception8-small.png -------------------------------------------------------------------------------- /perception9-large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception9-large.png -------------------------------------------------------------------------------- /perception9-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniodeluca/dn2a/HEAD/perception9-small.png -------------------------------------------------------------------------------- /examples/.parcelrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@parcel/config-default", 3 | "resolvers": ["parcel-resolver-ts-base-url", "..."] 4 | } -------------------------------------------------------------------------------- /library/.parcelrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@parcel/config-default", 3 | "resolvers": ["parcel-resolver-ts-base-url", "..."] 4 | } -------------------------------------------------------------------------------- /workspace/.parcelrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@parcel/config-default", 3 | "resolvers": ["parcel-resolver-ts-base-url", "..."] 4 | } -------------------------------------------------------------------------------- /workspace/tests/acceptance/server/test.ts: -------------------------------------------------------------------------------- 1 | describe.skip("", () => { 2 | it("", () => { 3 | // 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /workspace/tests/unit/client/index.test.tsx: -------------------------------------------------------------------------------- 1 | describe.skip("", () => { 2 | it("", () => { 3 | // 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /workspace/tests/unit/server/index.test.ts: -------------------------------------------------------------------------------- 1 | describe.skip("", () => { 2 | it("", () => { 3 | // 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /workspace/assets/client/index.ts: -------------------------------------------------------------------------------- 1 | import { components, services } from "./bootstrapper"; 2 | 3 | const { Application } = components; 4 | const { mount } = services; 5 | 6 | mount(Application); 7 | -------------------------------------------------------------------------------- /workspace/assets/client/core/types.ts: -------------------------------------------------------------------------------- 1 | interface Network { 2 | name: string; 3 | } 4 | 5 | type NetworksRetrieverPort = () => Promise; 6 | 7 | export { Network, NetworksRetrieverPort }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/Network.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const Network = () => { 4 | return
Network
; 5 | }; 6 | 7 | export { Network }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/EventList.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const EventList = () => { 4 | return
Event List
; 5 | }; 6 | 7 | export { EventList }; 8 | -------------------------------------------------------------------------------- /library/.npmignore: -------------------------------------------------------------------------------- 1 | .git 2 | .parcel-cache 3 | assets 4 | bower_components 5 | node_modules 6 | tests 7 | 8 | .eslintrc.js 9 | .gitignore 10 | .travis.yml 11 | bower.json 12 | jest.config.ts 13 | tsconfig.json 14 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/ProjectCreation.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ProjectCreation = () => { 4 | return
Project Creation
; 5 | }; 6 | 7 | export { ProjectCreation }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/ProjectExecution.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ProjectExecution = () => { 4 | return
Project Execution
; 5 | }; 6 | 7 | export { ProjectExecution }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/ProjectSelection.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ProjectSelection = () => { 4 | return
Project Selection
; 5 | }; 6 | 7 | export { ProjectSelection }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/NetworkGraph.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NetworkGraph = () => { 4 | return(
Network Graph
); 5 | }; 6 | 7 | export { 8 | NetworkGraph 9 | } 10 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/ProjectDeployment.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ProjectDeployment = () => { 4 | return
Project Deployment
; 5 | }; 6 | 7 | export { ProjectDeployment }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/ProjectExportation.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ProjectExportation = () => { 4 | return
Project Exportation
; 5 | }; 6 | 7 | export { ProjectExportation }; 8 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/NetworkCreation.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NetworkCreation = () => { 4 | return(
Network Creation
); 5 | }; 6 | 7 | export { 8 | NetworkCreation 9 | } 10 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/NetworkPipeline.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NetworkPipeline = () => { 4 | return(
Network Pipeline
); 5 | }; 6 | 7 | export { 8 | NetworkPipeline 9 | } 10 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/NetworkQuerying.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NetworkQuerying = () => { 4 | return(
Network Querying
); 5 | }; 6 | 7 | export { 8 | NetworkQuerying 9 | } 10 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/NetworkTraining.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NetworkTraining = () => { 4 | return(
Network Training
); 5 | }; 6 | 7 | export { 8 | NetworkTraining 9 | } 10 | -------------------------------------------------------------------------------- /library/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "importOrder": ["^@assets/(.*)$", "^@core/(.*)$", "^@networks/(.*)$", "^@infrastructure/(.*)$", "^@tests/(.*)$", "^[./]" ], 4 | "importOrderSeparation": true, 5 | "importOrderSortSpecifiers": true 6 | } -------------------------------------------------------------------------------- /workspace/tests/mocks/api.json: -------------------------------------------------------------------------------- 1 | { 2 | "networks": [ 3 | { 4 | "name": "firstNetwork" 5 | }, 6 | { 7 | "name": "secondNetwork" 8 | }, 9 | { 10 | "name": "thirdNetwork" 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /workspace/README.md: -------------------------------------------------------------------------------- 1 | # DN2A Workspace # 2 | 3 | [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/antoniodeluca/dn2a/main/LICENSE) 4 | 5 | ## About ## 6 | 7 | A web application about easily configuring and controlling neural networks architectures through the DN2A library. 8 | -------------------------------------------------------------------------------- /workspace/assets/client/core/networksRetriever.ts: -------------------------------------------------------------------------------- 1 | import { NetworksRetrieverPort } from "./types"; 2 | 3 | const networksRetriever = 4 | (retrieveNetworks: NetworksRetrieverPort) => async () => { 5 | const networks = await retrieveNetworks(); 6 | 7 | return networks; 8 | }; 9 | 10 | export { networksRetriever }; 11 | -------------------------------------------------------------------------------- /examples/assets/browser-test-network-alpha-continuous/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Test 7 | 8 | 9 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/assets/browser-test-network-alpha-stepbystep/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Test 7 | 8 | 9 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /library/jest.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "ts-jest", 3 | "testEnvironment": "node", 4 | "moduleNameMapper": { 5 | "^@assets/(.*)$": "/assets/$1", 6 | "^@core/(.*)$": "/assets/core/$1", 7 | "^@networks/(.*)$": "/assets/core/networks/$1", 8 | "^@infrastructure/(.*)$": "/assets/infrastructure/$1", 9 | "^@tests/(.*)$": "/tests/$1" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /workspace/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "importOrder": [ 4 | "^@assets/(.*)$", 5 | "^@client/(.*)$", 6 | "^@server/(.*)$", 7 | "^@client-core/(.*)$", 8 | "^@client-infrastructure/(.*)$", 9 | "^@server-core/(.*)$", 10 | "^@server-infrastructure/(.*)$", 11 | "^@tests/(.*)$", 12 | "^[./]" 13 | ], 14 | "importOrderSeparation": true, 15 | "importOrderSortSpecifiers": true 16 | } -------------------------------------------------------------------------------- /examples/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es2021": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended", 8 | "plugin:@typescript-eslint/recommended" 9 | ], 10 | "overrides": [ 11 | ], 12 | "parser": "@typescript-eslint/parser", 13 | "parserOptions": { 14 | "ecmaVersion": "latest", 15 | "sourceType": "module" 16 | }, 17 | "plugins": [ 18 | "@typescript-eslint" 19 | ], 20 | "rules": { 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /library/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es2021": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended", 8 | "plugin:@typescript-eslint/recommended" 9 | ], 10 | "overrides": [ 11 | ], 12 | "parser": "@typescript-eslint/parser", 13 | "parserOptions": { 14 | "ecmaVersion": "latest", 15 | "sourceType": "module" 16 | }, 17 | "plugins": [ 18 | "@typescript-eslint" 19 | ], 20 | "rules": { 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/NetworkList.tsx: -------------------------------------------------------------------------------- 1 | import { DataView } from "primereact/dataview"; 2 | import React from "react"; 3 | 4 | import { Network } from "../../../core/types"; 5 | 6 | interface Props { 7 | networks: Network[]; 8 | networkTemplate: (network: Network) => React.ReactElement; 9 | } 10 | 11 | const NetworkList = (props: Props) => { 12 | const { networks, networkTemplate } = props; 13 | 14 | return ; 15 | }; 16 | 17 | export { NetworkList }; 18 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/hooks/useNetworks.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | 3 | import { Network, NetworksRetrieverPort } from "../../../../core/types"; 4 | 5 | const useNetworks = (retrieveNetworks: NetworksRetrieverPort) => { 6 | const [networks, setNetworks] = useState([] as Network[]); 7 | useEffect(() => { 8 | const loadNetworks = async () => { 9 | const networks = await retrieveNetworks(); 10 | setNetworks(networks); 11 | }; 12 | loadNetworks(); 13 | }, []); 14 | 15 | return networks; 16 | }; 17 | 18 | export { useNetworks }; 19 | -------------------------------------------------------------------------------- /workspace/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | DN2A Workspace 8 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /workspace/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es2021": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended", 8 | "plugin:react/recommended", 9 | "plugin:@typescript-eslint/recommended" 10 | ], 11 | "overrides": [ 12 | ], 13 | "parser": "@typescript-eslint/parser", 14 | "parserOptions": { 15 | "ecmaVersion": "latest", 16 | "sourceType": "module" 17 | }, 18 | "plugins": [ 19 | "react", 20 | "@typescript-eslint" 21 | ], 22 | "rules": { 23 | }, 24 | "settings": { 25 | "react": { 26 | "version": "detect" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to DN2A JavaScript 2 | 3 | Thanks for taking the time to contribute. 4 | 5 | The following is a set of guidelines for contributing to the DN2A JavaScript package. 6 | 7 | ## What should You know before You get started? 8 | 9 | ### Licensing Code 10 | 11 | You, the contributor, accept that your contribution will be accepted only under the terms of the MIT license and that indeed you release your contribution under the terms of the MIT license. 12 | 13 | You, the contributor, confirm to hold the full rights about the code of your contribution and to be fully entitled to give your contribution. 14 | 15 | ## How Can You Contribute? 16 | 17 | ### Reporting Bugs 18 | 19 | ### Pull Requests -------------------------------------------------------------------------------- /examples/TODO.md: -------------------------------------------------------------------------------- 1 | ## To Do 2 | 3 | - [ ] Add examples that support 3D visualization of the network as well as realtime plotting of select neurons/synapses behavior 4 | - [ ] Add examples that support 3D visualization all networks in a Cerebrum as well as realtime plotting of select neurons/synapses behavior 5 | - [ ] Add examples that support 3D visualization all networks in a Brain as well as realtime plotting of select neurons/synapses behavior 6 | - [ ] Add CI/CD pipeline for PRs verification and NPM module publishing 7 | - [ ] Add examples for alternative contexts which go beyond the XOR 8 | - [ ] Add example Docker configuration 9 | 10 | ## In Progress 11 | 12 | - [ ] / 13 | 14 | ## Done 15 | 16 | - [ ] / 17 | -------------------------------------------------------------------------------- /workspace/jest.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "ts-jest", 3 | "testEnvironment": "jsdom", 4 | "moduleNameMapper": { 5 | "\\.(css|less|scss|sss|styl)$": "/node_modules/jest-css-modules", 6 | "^@assets/(.*)$": "/assets/$1", 7 | "^@client/(.*)$": "/assets/client/$1", 8 | "^@server/(.*)$": "/assets/server/$1", 9 | "^@client-core/(.*)$": "/assets/client/core/$1", 10 | "^@client-infrastructure/(.*)$": "/assets/client/infrastructure/$1", 11 | "^@server-core/(.*)$": "/assets/server/core/$1", 12 | "^@server-infrastructure/(.*)$": "/assets/server/infrastructure/$1", 13 | "^@tests/(.*)$": "/tests/$1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/dataSource/http.ts: -------------------------------------------------------------------------------- 1 | import { Network, NetworksRetrieverPort } from "../../core/types"; 2 | 3 | const networkListEndpoint = "http://localhost:3000/networks"; 4 | 5 | interface SourceNetwork { 6 | id: number; 7 | name: string; 8 | } 9 | 10 | const retrieveNetworks: NetworksRetrieverPort = async () => { 11 | const response = await fetch(networkListEndpoint); 12 | const sourceNetworks = (await response.json()) as SourceNetwork[]; 13 | const networks = sourceNetworks.map((sourceNetwork) => { 14 | const { name } = sourceNetwork; 15 | 16 | return { 17 | name, 18 | }; 19 | }) as Network[]; 20 | 21 | return networks; 22 | }; 23 | 24 | export { retrieveNetworks }; 25 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/index.tsx: -------------------------------------------------------------------------------- 1 | import "primeflex/primeflex.css"; 2 | import "primeicons/primeicons.css"; 3 | import "primereact/resources/primereact.css"; 4 | import "primereact/resources/themes/md-dark-indigo/theme.css"; 5 | import React from "react"; 6 | import { createRoot } from "react-dom/client"; 7 | import { BrowserRouter } from "react-router-dom"; 8 | 9 | const mount = (Application: React.FC) => { 10 | const applicationContainer = document.getElementById( 11 | "application-container" 12 | ) as HTMLElement; 13 | const applicationRoot = createRoot(applicationContainer); 14 | applicationRoot.render( 15 | 16 | 17 | 18 | ); 19 | }; 20 | 21 | export { mount }; 22 | -------------------------------------------------------------------------------- /workspace/assets/client/bootstrapper.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | import { networksRetriever } from "./core/networksRetriever"; 4 | import { retrieveNetworks as httpNetworksRetrieverAdapter } from "./infrastructure/dataSource/http"; 5 | import { mount } from "./infrastructure/ui/react"; 6 | import { Application } from "./infrastructure/ui/react/Application"; 7 | 8 | const composedNetworksRetriever = networksRetriever( 9 | httpNetworksRetrieverAdapter 10 | ); 11 | 12 | const services = { 13 | mount, 14 | retrieveNetworks: composedNetworksRetriever, 15 | }; 16 | 17 | const ComposedApplication = () => { 18 | return ; 19 | }; 20 | 21 | const components = { 22 | Application: ComposedApplication, 23 | }; 24 | 25 | export { components, services }; 26 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/Application.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Route, Routes } from "react-router-dom"; 3 | 4 | import { NetworksRetrieverPort } from "@assets/client/core/types"; 5 | 6 | import { Frame } from "./Frame"; 7 | import { Frame as PrototypeFrame } from "./prototype/Frame"; 8 | 9 | interface Props { 10 | retrieveNetworks: NetworksRetrieverPort; 11 | } 12 | 13 | const Application = (props: Props) => { 14 | const { retrieveNetworks } = props; 15 | 16 | return ( 17 | 18 | } 21 | /> 22 | } /> 23 | 24 | ); 25 | }; 26 | 27 | export { Application }; 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Neural Networks Architect (DN2A) # 2 | 3 | [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/antoniodeluca/dn2a/main/LICENSE) 4 | 5 | ## About ## 6 | 7 | A library, workspace and vision around neural networks. 8 | 9 | ### A vision called Perception ### 10 | 11 | ![image](perception1-large.png) 12 | 13 | ![image](perception2-large.png) 14 | 15 | ![image](perception3-large.png) 16 | 17 | ![image](perception4-large.png) 18 | 19 | ![image](perception5-large.png) 20 | 21 | ![image](perception6-large.png) 22 | 23 | ![image](perception7-large.png) 24 | 25 | ![image](perception8-large.png) 26 | 27 | ![image](perception9-large.png) 28 | 29 | ![image](perception10-large.png) 30 | -------------------------------------------------------------------------------- /library/assets/infrastructure/Calculator/MathJSCalculator.ts: -------------------------------------------------------------------------------- 1 | import { EvalFunction, MathExpression, all, create } from "mathjs"; 2 | 3 | import { Calculator } from "@networks/types"; 4 | 5 | const mathjs = create(all); 6 | mathjs.config({ 7 | number: "number", 8 | }); 9 | 10 | class MathJSCalculator implements Calculator { 11 | private compiledExpressions: { [key: string]: EvalFunction } = {}; 12 | 13 | evaluate(expression: MathExpression, scope: unknown): number { 14 | const compiledExpressionIndex = expression.toString(); 15 | if (!this.compiledExpressions[compiledExpressionIndex]) { 16 | this.compiledExpressions[compiledExpressionIndex] = 17 | mathjs.compile(expression); 18 | } 19 | 20 | return this.compiledExpressions[compiledExpressionIndex].evaluate( 21 | scope 22 | ); 23 | } 24 | } 25 | 26 | export { MathJSCalculator }; 27 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/NeuronFactory.ts: -------------------------------------------------------------------------------- 1 | import { Calculator } from "@networks/types"; 2 | 3 | import { Neuron } from "./Neuron"; 4 | import { NeuronConfiguration } from "./types"; 5 | 6 | class NeuronFactory { 7 | private calculator: Calculator; 8 | 9 | private configuration: NeuronConfiguration; 10 | 11 | private getDefaultConfiguration() { 12 | return {} as NeuronConfiguration; 13 | } 14 | 15 | constructor(calculator: Calculator, configuration?: NeuronConfiguration) { 16 | this.calculator = calculator; 17 | 18 | this.configuration = configuration 19 | ? configuration 20 | : this.getDefaultConfiguration(); 21 | } 22 | 23 | getInstance(configuration?: NeuronConfiguration) { 24 | if (configuration) { 25 | this.configuration = configuration; 26 | } 27 | 28 | return new Neuron(this.calculator, this.configuration); 29 | } 30 | } 31 | 32 | export { NeuronFactory }; 33 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/SynapseFactory.ts: -------------------------------------------------------------------------------- 1 | import { Calculator } from "@networks/types"; 2 | 3 | import { Synapse } from "./Synapse"; 4 | import { SynapseConfiguration } from "./types"; 5 | 6 | class SynapseFactory { 7 | private calculator: Calculator; 8 | 9 | private configuration: SynapseConfiguration; 10 | 11 | private getDefaultConfiguration() { 12 | return {} as SynapseConfiguration; 13 | } 14 | 15 | constructor(calculator: Calculator, configuration?: SynapseConfiguration) { 16 | this.calculator = calculator; 17 | 18 | this.configuration = configuration 19 | ? configuration 20 | : this.getDefaultConfiguration(); 21 | } 22 | 23 | getInstance(configuration?: SynapseConfiguration) { 24 | if (configuration) { 25 | this.configuration = configuration; 26 | } 27 | 28 | return new Synapse(this.calculator, this.configuration); 29 | } 30 | } 31 | 32 | export { SynapseFactory }; 33 | -------------------------------------------------------------------------------- /library/assets/core/Brain.ts: -------------------------------------------------------------------------------- 1 | import { BrainConfiguration, BrainInterface, CerebrumInterface } from "./types"; 2 | 3 | class Brain implements BrainInterface { 4 | private configuration: BrainConfiguration; 5 | 6 | private _cerebrum: CerebrumInterface; 7 | 8 | private checkConfiguration() { 9 | return true; 10 | } 11 | 12 | private transformConfiguration() { 13 | return this.configuration; 14 | } 15 | 16 | constructor(configuration: BrainConfiguration) { 17 | this.configuration = configuration; 18 | 19 | if (!this.checkConfiguration()) { 20 | throw "Invalid Brain Module Configuration"; 21 | } 22 | this.configuration = this.transformConfiguration(); 23 | 24 | this._cerebrum = this.configuration.cerebrum.generator.getInstance( 25 | this.configuration.cerebrum.configuration 26 | ); 27 | } 28 | 29 | set cerebrum(value) { 30 | this._cerebrum = value; 31 | } 32 | 33 | get cerebrum() { 34 | return this._cerebrum; 35 | } 36 | } 37 | 38 | export { Brain }; 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2023 Antonio De Luca (contact@antoniodeluca.info) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /library/assets/core/BrainFactory.ts: -------------------------------------------------------------------------------- 1 | import { Calculator } from "@networks/types"; 2 | 3 | import { Brain } from "./Brain"; 4 | import { CerebrumFactory } from "./CerebrumFactory"; 5 | import { BrainConfiguration } from "./types"; 6 | 7 | class BrainFactory { 8 | private calculator: Calculator; 9 | 10 | private configuration: BrainConfiguration; 11 | 12 | private getDefaultConfiguration() { 13 | const cerebrumFactory = new CerebrumFactory(this.calculator); 14 | 15 | return { 16 | cerebrum: { 17 | generator: cerebrumFactory, 18 | }, 19 | } as BrainConfiguration; 20 | } 21 | 22 | constructor(calculator: Calculator, configuration?: BrainConfiguration) { 23 | this.calculator = calculator; 24 | 25 | this.configuration = configuration 26 | ? configuration 27 | : this.getDefaultConfiguration(); 28 | } 29 | 30 | getInstance(configuration?: BrainConfiguration) { 31 | if (configuration) { 32 | this.configuration = configuration; 33 | } 34 | 35 | return new Brain(this.configuration); 36 | } 37 | } 38 | 39 | export { BrainFactory }; 40 | -------------------------------------------------------------------------------- /examples/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2023 Antonio De Luca (contact@antoniodeluca.info) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /library/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2023 Antonio De Luca (contact@antoniodeluca.info) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /workspace/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2023 Antonio De Luca (contact@antoniodeluca.info) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /library/assets/core/networks/types.ts: -------------------------------------------------------------------------------- 1 | import { 2 | QueryingInputPatterns, 3 | QueryingStatus, 4 | TrainingPatterns, 5 | TrainingStatus, 6 | } from "@core/types"; 7 | 8 | interface NetworkInterface { 9 | train: ( 10 | trainingPatterns: TrainingPatterns, 11 | epochCallback?: TrainingEpochCallback, 12 | iterationCallback?: TrainingIterationCallback 13 | ) => void; 14 | 15 | query: ( 16 | queryingPatterns: QueryingInputPatterns, 17 | epochCallback?: QueryingEpochCallback, 18 | iterationCallback?: QueryingIterationCallback 19 | ) => void; 20 | } 21 | 22 | type TrainingEpochCallback = (trainingStatus: TrainingStatus) => void; 23 | 24 | type TrainingIterationCallback = (trainingStatus: TrainingStatus) => void; 25 | 26 | type QueryingEpochCallback = (queryingStatus: QueryingStatus) => void; 27 | 28 | type QueryingIterationCallback = (queryingStatus: QueryingStatus) => void; 29 | 30 | interface Calculator { 31 | evaluate: (expression: string, scope: unknown) => number; 32 | } 33 | 34 | export { 35 | Calculator, 36 | NetworkInterface, 37 | QueryingEpochCallback, 38 | QueryingIterationCallback, 39 | TrainingEpochCallback, 40 | TrainingIterationCallback, 41 | }; 42 | -------------------------------------------------------------------------------- /library/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin"); 3 | const TypingsBundlerPlugin = require("typings-bundler-plugin"); 4 | 5 | const commonConfiguration = { 6 | entry: "./assets/index.ts", 7 | experiments: { 8 | outputModule: true 9 | }, 10 | mode: "production", 11 | module: { 12 | rules: [ 13 | { 14 | test: /\.ts$/, 15 | use: "ts-loader", 16 | exclude: /node_modules/ 17 | } 18 | ] 19 | }, 20 | output: { 21 | path: path.resolve(__dirname, "distributed") 22 | }, 23 | plugins: [ 24 | new TypingsBundlerPlugin({ 25 | out: "types.d.ts" 26 | }) 27 | ], 28 | resolve: { 29 | extensions: [".ts", ".js"], 30 | plugins: [ 31 | new TsconfigPathsPlugin() 32 | ] 33 | } 34 | }; 35 | 36 | const configurationForCJS = { 37 | ...commonConfiguration, 38 | output: { 39 | ...commonConfiguration.output, 40 | filename: "index.js", 41 | libraryTarget: "commonjs" 42 | } 43 | } 44 | 45 | const configurationForESM = { 46 | ...commonConfiguration, 47 | output: { 48 | ...commonConfiguration.output, 49 | filename: "module.js", 50 | libraryTarget: "module" 51 | } 52 | } 53 | 54 | module.exports = [configurationForCJS, configurationForESM]; 55 | -------------------------------------------------------------------------------- /library/assets/core/CerebrumFactory.ts: -------------------------------------------------------------------------------- 1 | import { NetworkFactory as NetworkAlphaFactory } from "@networks/alpha/NetworkFactory"; 2 | import { Calculator } from "@networks/types"; 3 | 4 | import { Cerebrum } from "./Cerebrum"; 5 | import { CerebrumConfiguration } from "./types"; 6 | 7 | class CerebrumFactory { 8 | private calculator: Calculator; 9 | 10 | private configuration: CerebrumConfiguration; 11 | 12 | private getDefaultConfiguration() { 13 | const networkAlphaFactory = new NetworkAlphaFactory(this.calculator); 14 | 15 | return { 16 | networks: [ 17 | { 18 | name: "defaultNetwork", 19 | code: { 20 | generator: networkAlphaFactory, 21 | }, 22 | inputsFrom: ["cerebrum"], 23 | }, 24 | ], 25 | outputsFrom: ["defaultNetwork"], 26 | } as CerebrumConfiguration; 27 | } 28 | 29 | constructor(calculator: Calculator, configuration?: CerebrumConfiguration) { 30 | this.calculator = calculator; 31 | 32 | this.configuration = configuration 33 | ? configuration 34 | : this.getDefaultConfiguration(); 35 | } 36 | 37 | getInstance(configuration?: CerebrumConfiguration) { 38 | if (configuration) { 39 | this.configuration = configuration; 40 | } 41 | 42 | return new Cerebrum(this.configuration); 43 | } 44 | } 45 | 46 | export { CerebrumFactory }; 47 | -------------------------------------------------------------------------------- /workspace/TODO.md: -------------------------------------------------------------------------------- 1 | ## To Do 2 | 3 | - [ ] Allow creation of training data for each neural network 4 | - [ ] Allow independent training of each neural network 5 | - [ ] Enable storing/loading of data and configurations for a single network 6 | - [ ] Enable storing/loading of data and configurations for all networks in a Cerebrum 7 | - [ ] Enable storing/loading of data and configurations for all networks in a Brain 8 | - [ ] Add advanced visualization of the graph of neural networks using 2D pipelines or 3D 9 | - [ ] Allow configuration of parameters for each network 10 | - [ ] Add storing/loading of projects 11 | - [ ] Allow visualization of the state of each single neuron/synapse or network 12 | - [ ] Add CI/CD pipeline for PRs verification and NPM module publishing 13 | - [ ] Add example Docker configuration 14 | 15 | ## In Progress 16 | 17 | - [x] Allow to define a project with multiple networks connected as a graph 18 | *Application is able to show a list of networks* - [@antoniodeluca](https://github.com/antoniodeluca) with PR [#146](https://github.com/antoniodeluca/dn2a/pull/146) 19 | - [x] Create a prototype of the full user interface together relative APIs and activable via feature flag 20 | [@antoniodeluca](https://github.com/antoniodeluca) with PR [#159](https://github.com/antoniodeluca/dn2a/pull/159) 21 | 22 | ## Done 23 | 24 | - [x] Refactoring client application toward clean architecture 25 | [@antoniodeluca](https://github.com/antoniodeluca) with PR [#147](https://github.com/antoniodeluca/dn2a/pull/147) 26 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/Frame.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Route, Routes } from "react-router-dom"; 3 | import { useNavigate } from "react-router-dom"; 4 | 5 | import { Network, NetworksRetrieverPort } from "../../../core/types"; 6 | import { NetworkList } from "./NetworkList"; 7 | import { useNetworks } from "./hooks/useNetworks"; 8 | 9 | interface Props { 10 | retrieveNetworks: NetworksRetrieverPort; 11 | } 12 | 13 | const Frame = (props: Props) => { 14 | const { retrieveNetworks } = props; 15 | const networks = useNetworks(retrieveNetworks); 16 | const navigate = useNavigate(); 17 | 18 | const networkTemplate = (network: Network) => { 19 | return
{network.name}
; 20 | }; 21 | 22 | const switchToUIPrototype = () => { 23 | navigate("/prototype"); 24 | }; 25 | 26 | return ( 27 | <> 28 | 29 | 36 | } 37 | /> 38 | 39 |
40 | 43 |
44 | 45 | ); 46 | }; 47 | 48 | export { Frame }; 49 | -------------------------------------------------------------------------------- /examples/assets/cli-test-network-alpha-continuous-0.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultNetworkAlpha, 3 | QueryingInputPattern, 4 | QueryingStatus, 5 | } from "dn2a"; 6 | 7 | const neuralNetwork = DefaultNetworkAlpha.getInstance(); 8 | 9 | const trainingPatterns = [ 10 | { 11 | input: [0, 0], 12 | output: [0], 13 | }, 14 | { 15 | input: [0, 1], 16 | output: [1], 17 | }, 18 | { 19 | input: [1, 0], 20 | output: [1], 21 | }, 22 | { 23 | input: [1, 1], 24 | output: [0], 25 | }, 26 | ]; 27 | 28 | // Training 29 | neuralNetwork.train(trainingPatterns); 30 | 31 | const queryingPatterns = [ 32 | [0, 0], 33 | [0, 1], 34 | [1, 0], 35 | [1, 1], 36 | ]; 37 | 38 | // Querying 39 | // 40 | // The object passed to the callback function contains information about the querying process. 41 | neuralNetwork.query( 42 | queryingPatterns, 43 | (queryingStatus: QueryingStatus) => { 44 | queryingPatterns.forEach( 45 | ( 46 | queryingPattern: QueryingInputPattern, 47 | queryingPatternIndex: number 48 | ) => { 49 | /* eslint-disable no-console */ 50 | console.log( 51 | `[${queryingPatterns[queryingPatternIndex].join( 52 | ", " 53 | )}] => [${queryingStatus.outputPatterns[ 54 | queryingPatternIndex 55 | ].join(", ")}]` 56 | ); 57 | /* eslint-enable no-console */ 58 | } 59 | ); 60 | }, 61 | undefined 62 | ); 63 | -------------------------------------------------------------------------------- /workspace/tests/acceptance/client/user-should-be-able-to-create-a-project-with-multiple-networks-connected-as-a-graph.test.tsx: -------------------------------------------------------------------------------- 1 | import "@testing-library/jest-dom/extend-expect"; 2 | import { render, screen } from "@testing-library/react"; 3 | import React from "react"; 4 | import { MemoryRouter } from "react-router-dom"; 5 | 6 | import { components } from "@client/bootstrapper"; 7 | 8 | const { Application } = components; 9 | 10 | describe("# User should be able to create a project with multiple networks connected as a graph", () => { 11 | describe("Given user is on the network list page", () => { 12 | const fetchMock = jest.fn(); 13 | global.fetch = fetchMock; 14 | 15 | it("Then user should see the list of already added networks", async () => { 16 | const networks = [ 17 | { 18 | name: "firstNetwork", 19 | }, 20 | { 21 | name: "secondNetwork", 22 | }, 23 | { 24 | name: "thirdNetwork", 25 | }, 26 | ]; 27 | fetchMock.mockImplementation(() => { 28 | return Promise.resolve({ 29 | json: () => Promise.resolve(networks), 30 | }); 31 | }); 32 | 33 | render( 34 | 35 | 36 | 37 | ); 38 | 39 | expect(await screen.findByText("firstNetwork")).not.toBeNull(); 40 | expect(await screen.findByText("secondNetwork")).not.toBeNull(); 41 | expect(await screen.findByText("thirdNetwork")).not.toBeNull(); 42 | }); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/NetworkFactory.ts: -------------------------------------------------------------------------------- 1 | import { Calculator } from "@networks/types"; 2 | 3 | import { Network } from "./Network"; 4 | import { NeuronFactory } from "./NeuronFactory"; 5 | import { SynapseFactory } from "./SynapseFactory"; 6 | import { DataRepository, NetworkConfiguration } from "./types"; 7 | 8 | class NetworkFactory { 9 | private calculator: Calculator; 10 | 11 | private configuration: NetworkConfiguration; 12 | 13 | private getDefaultConfiguration() { 14 | const neuronFactory = new NeuronFactory(this.calculator); 15 | const synapseFactory = new SynapseFactory(this.calculator); 16 | 17 | return { 18 | layerDimensions: [2, 4, 1], 19 | learningMode: "continuous", 20 | learningRate: 0.3, 21 | momentumRate: 0.7, 22 | maximumError: 0.005, 23 | maximumEpoch: 1000, 24 | dataRepository: { neuronLayers: [] } as DataRepository, 25 | neuron: { 26 | generator: neuronFactory, 27 | }, 28 | synapse: { 29 | generator: synapseFactory, 30 | }, 31 | } as NetworkConfiguration; 32 | } 33 | 34 | constructor(calculator: Calculator, configuration?: NetworkConfiguration) { 35 | this.calculator = calculator; 36 | 37 | this.configuration = configuration 38 | ? configuration 39 | : this.getDefaultConfiguration(); 40 | } 41 | 42 | getInstance(configuration?: NetworkConfiguration) { 43 | if (configuration) { 44 | this.configuration = configuration; 45 | } 46 | 47 | return new Network(this.calculator, this.configuration); 48 | } 49 | } 50 | 51 | export { NetworkFactory }; 52 | -------------------------------------------------------------------------------- /workspace/tests/acceptance/client/user-should-be-able-to-switch-to-ui-prototype.test.tsx: -------------------------------------------------------------------------------- 1 | import "@testing-library/jest-dom/extend-expect"; 2 | import { render, screen } from "@testing-library/react"; 3 | import userEvent from "@testing-library/user-event"; 4 | import React from "react"; 5 | import { MemoryRouter } from "react-router-dom"; 6 | 7 | import { components } from "@client/bootstrapper"; 8 | 9 | const { Application } = components; 10 | 11 | describe("# User should be able to switch to UI prototype", () => { 12 | describe("Given user is on any page", () => { 13 | const fetchMock = jest.fn(); 14 | global.fetch = fetchMock; 15 | 16 | it("Then user should be able to switch to UI prototype via a Call-To-Action button", async () => { 17 | const networks = [ 18 | { 19 | name: "firstNetwork", 20 | }, 21 | { 22 | name: "secondNetwork", 23 | }, 24 | { 25 | name: "thirdNetwork", 26 | }, 27 | ]; 28 | fetchMock.mockImplementation(() => { 29 | return Promise.resolve({ 30 | json: () => Promise.resolve(networks), 31 | }); 32 | }); 33 | userEvent.setup(); 34 | render( 35 | 36 | 37 | 38 | ); 39 | 40 | const callToActionButton = await screen.findByText( 41 | "Switch to UI Prototype" 42 | ); 43 | await userEvent.click(callToActionButton); 44 | 45 | expect(await screen.findByText("UI Prototype")).not.toBeNull(); 46 | expect(await screen.findByText("Switch to UI")).not.toBeNull(); 47 | }); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # DN2A Examples # 2 | 3 | [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/antoniodeluca/dn2a-examples/main/LICENSE) 4 | 5 | ## About ## 6 | 7 | Some examples about how to use the DN2A library. 8 | 9 | ## How to use the examples ## 10 | 11 | **Install all dependencies** with 12 | 13 | `npm install` 14 | 15 | **or install all dependencies apart from DN2A library** with `npm install --legacy-peer-deps` so that an independent library version can be manually installed or linked from the local "library" on the repository root (which is useful for library development). 16 | 17 | *Notes:* 18 | 19 | - if not using NPM 7+ the DN2A library, which is a peer dependency, could need to be installed manually or linked in any case as some NPM versions (4/5/6) do not install peer dependencies by default. 20 | - to link the local "library" folder execute `npm link` from there and then `npm link dn2a` from the "examples" folder. 21 | - if working within an environment that is incompatible with `npm link` execute `npm run link` from the "examples" folder as an alternative. 22 | - if using the linked local "library" folder, execute `npm install` from there and then also `npm run build:parcel` or `npm run build:webpack` (which is an alternative for those environments that are incompatible with Parcel). 23 | 24 | **See the examples in action** executing from the "examples" folder one of the NPM scripts that begin with `start:`. 25 | 26 | *Notes:* 27 | 28 | - Node.js oriented examples, those starting with `start:cli:`, can be runned using commands like `npm run start:cli:alpha-continuous`. 29 | - browser oriented ones, those starting with `start:browser:`, can be runned using commands like `npm run start:browser:alpha-continuous:parcel` or `npm run start:browser:alpha-continuous:vite` (which is an alternative for those environments that are incompatible with Parcel). -------------------------------------------------------------------------------- /library/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Antonio De Luca ", 3 | "dependencies": { 4 | "mathjs": "^11.5.0" 5 | }, 6 | "description": "DN2A - Dynamic Neural Networks Architect - Library", 7 | "devDependencies": { 8 | "@parcel/packager-ts": "^2.8.2", 9 | "@parcel/transformer-typescript-types": "^2.8.2", 10 | "@trivago/prettier-plugin-sort-imports": "^4.0.0", 11 | "@types/jest": "^29.2.4", 12 | "@typescript-eslint/eslint-plugin": "^5.50.0", 13 | "@typescript-eslint/parser": "^5.50.0", 14 | "eslint": "^8.30.0", 15 | "eslint-config-prettier": "^8.6.0", 16 | "eslint-plugin-import": "^2.27.5", 17 | "jest": "^29.3.1", 18 | "npm-run-all2": "^6.0.4", 19 | "parcel": "^2.8.2", 20 | "parcel-resolver-ts-base-url": "^1.3.1", 21 | "prettier": "^2.8.4", 22 | "ts-jest": "^29.0.3", 23 | "ts-loader": "^9.4.2", 24 | "ts-node": "^10.9.1", 25 | "tsconfig-paths": "^4.2.0", 26 | "tsconfig-paths-webpack-plugin": "^4.0.1", 27 | "typescript": "^4.9.4", 28 | "typings-bundler-plugin": "^1.0.0", 29 | "webpack": "^5.81.0", 30 | "webpack-cli": "^5.0.2" 31 | }, 32 | "keywords": [ 33 | "neural networks", 34 | "machine learning", 35 | "artificial intelligence" 36 | ], 37 | "license": "MIT", 38 | "main": "distributed/index.js", 39 | "module": "distributed/module.js", 40 | "name": "dn2a", 41 | "repository": { 42 | "type": "git", 43 | "url": "https://github.com/antoniodeluca/dn2a.git" 44 | }, 45 | "scripts": { 46 | "build:parcel": "npx parcel build --no-source-maps", 47 | "build:webpack": "npx webpack --config webpack.config.js", 48 | "format": "prettier './assets/**/*.ts' './tests/**/*.ts' --write", 49 | "lint": "eslint './assets/**/*.ts' './tests/**/*.ts'", 50 | "test": "npx jest --verbose ./tests/*" 51 | }, 52 | "source": "assets/index.ts", 53 | "types": "distributed/types.d.ts", 54 | "version": "0.3.0" 55 | } 56 | -------------------------------------------------------------------------------- /library/assets/index.ts: -------------------------------------------------------------------------------- 1 | import { Brain } from "@core/Brain"; 2 | import { BrainFactory } from "@core/BrainFactory"; 3 | import { Cerebrum } from "@core/Cerebrum"; 4 | import { CerebrumFactory } from "@core/CerebrumFactory"; 5 | import type { 6 | QueryingInputPattern, 7 | QueryingInputPatterns, 8 | QueryingIterationPattern, 9 | QueryingOutputPattern, 10 | QueryingOutputPatterns, 11 | QueryingStatus, 12 | TrainingIterationPattern, 13 | TrainingPattern, 14 | TrainingPatterns, 15 | TrainingStatus, 16 | } from "@core/types"; 17 | 18 | import { Network as NetworkAlpha } from "@networks/alpha/Network"; 19 | import { NetworkFactory as NetworkAlphaFactory } from "@networks/alpha/NetworkFactory"; 20 | import { Neuron as NetworkAlphaNeuron } from "@networks/alpha/Neuron"; 21 | import { NeuronFactory as NetworkAlphaNeuronFactory } from "@networks/alpha/NeuronFactory"; 22 | import { Synapse as NetworkAlphaSynapse } from "@networks/alpha/Synapse"; 23 | import { SynapseFactory as NetworkAlphaSynapseFactory } from "@networks/alpha/SynapseFactory"; 24 | 25 | import { MathJSCalculator } from "@infrastructure/Calculator/MathJSCalculator"; 26 | 27 | import { DefaultBrain } from "./bootstrapper"; 28 | import { DefaultCerebrum } from "./bootstrapper"; 29 | import { DefaultNetworkAlpha } from "./bootstrapper"; 30 | import { DefaultNetworkAlphaNeuron } from "./bootstrapper"; 31 | import { DefaultNetworkAlphaSynapse } from "./bootstrapper"; 32 | 33 | export { 34 | Brain, 35 | BrainFactory, 36 | DefaultBrain, 37 | Cerebrum, 38 | CerebrumFactory, 39 | DefaultCerebrum, 40 | NetworkAlpha, 41 | NetworkAlphaFactory, 42 | DefaultNetworkAlpha, 43 | NetworkAlphaNeuron, 44 | NetworkAlphaNeuronFactory, 45 | DefaultNetworkAlphaNeuron, 46 | NetworkAlphaSynapse, 47 | NetworkAlphaSynapseFactory, 48 | DefaultNetworkAlphaSynapse, 49 | MathJSCalculator, 50 | }; 51 | 52 | export type { 53 | TrainingPattern, 54 | TrainingPatterns, 55 | TrainingIterationPattern, 56 | TrainingStatus, 57 | QueryingInputPattern, 58 | QueryingInputPatterns, 59 | QueryingOutputPattern, 60 | QueryingOutputPatterns, 61 | QueryingIterationPattern, 62 | QueryingStatus, 63 | }; 64 | -------------------------------------------------------------------------------- /examples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Antonio De Luca ", 3 | "description": "DN2A - Dynamic Neural Networks Architect - Examples", 4 | "devDependencies": { 5 | "@parcel/plugin": "^2.8.3", 6 | "@typescript-eslint/eslint-plugin": "^5.50.0", 7 | "@typescript-eslint/parser": "^5.50.0", 8 | "eslint": "^8.30.0", 9 | "eslint-config-prettier": "^8.6.0", 10 | "eslint-plugin-import": "^2.27.5", 11 | "eslint-plugin-jsx-a11y": "^6.7.1", 12 | "npm-run-all2": "^6.0.4", 13 | "parcel": "^2.8.2", 14 | "parcel-resolver-ts-base-url": "^1.3.1", 15 | "prettier": "^2.8.3", 16 | "ts-node": "^10.9.1", 17 | "typescript": "^4.9.4", 18 | "vite": "^4.3.4" 19 | }, 20 | "keywords": [ 21 | "neural networks", 22 | "machine learning", 23 | "artificial intelligence" 24 | ], 25 | "license": "MIT", 26 | "name": "dn2a-examples", 27 | "peerDependencies": { 28 | "dn2a": "0.3.0" 29 | }, 30 | "repository": { 31 | "type": "git", 32 | "url": "https://github.com/antoniodeluca/dn2a-examples.git" 33 | }, 34 | "scripts": { 35 | "format": "prettier ./assets/**/*.{ts,tsx,html,css} --write", 36 | "lint": "eslint ./assets/**/*.{ts,tsx}", 37 | "link": "ls -s ../library ./node_modules/dn2a", 38 | "start": "npx npm-run-all start:*", 39 | "start:browser": "npx npm-run-all start:browser:*", 40 | "start:cli": "npx npm-run-all start:cli:*", 41 | "start:browser:alpha-continuous:parcel": "npx parcel --no-cache assets/browser-test-network-alpha-continuous/index.html", 42 | "start:browser:alpha-continuous:vite": "npx vite assets/browser-test-network-alpha-continuous/", 43 | "start:browser:alpha-stepbystep:parcel": "npx parcel --no-cache assets/browser-test-network-alpha-stepbystep/index.html", 44 | "start:browser:alpha-stepbystep:vite": "npx vite assets/browser-test-network-alpha-stepbystep/", 45 | "start:cli:alpha-continuous-0": "npx ts-node assets/cli-test-network-alpha-continuous-0.ts", 46 | "start:cli:alpha-continuous-1": "npx ts-node assets/cli-test-network-alpha-continuous-1.ts", 47 | "start:cli:alpha-continuous-2": "npx ts-node assets/cli-test-network-alpha-continuous-2.ts", 48 | "start:cli:alpha-continuous-3": "npx ts-node assets/cli-test-network-alpha-continuous-3.ts", 49 | "start:cli:alpha-continuous-4": "npx ts-node assets/cli-test-network-alpha-continuous-4.ts", 50 | "start:cli:alpha-stepbystep-0": "npx ts-node assets/cli-test-network-alpha-stepbystep-0.ts" 51 | }, 52 | "version": "0.1.2" 53 | } 54 | -------------------------------------------------------------------------------- /workspace/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Antonio De Luca ", 3 | "description": "DN2A - Dynamic Neural Networks Architecture - Workspace", 4 | "license": "MIT", 5 | "name": "dn2a-workspace", 6 | "scripts": { 7 | "format": "prettier ./assets/**/*.{ts,tsx} ./public/**/*.{html,css} ./tests/**/*.{ts,tsx} --write", 8 | "lint": "eslint ./assets/**/*.{ts,tsx} ./tests/**/*.{ts,tsx}", 9 | "start:client": "npx parcel ./public/index.html", 10 | "start:server": "npx ts-node ./assets/server/index.ts", 11 | "start:server:mocks": "npx json-server --watch --port=3000 ./tests/mocks/api.json", 12 | "test": "npm run test:client:unit && npm run test:client:acceptance && npm run test:server:unit && npm run test:server:acceptance", 13 | "test:client:acceptance": "npx jest --verbose ./tests/acceptance/client/*", 14 | "test:client:unit": "npx jest --verbose ./tests/unit/client/*", 15 | "test:server:acceptance": "npx jest --verbose ./tests/acceptance/server/*", 16 | "test:server:unit": "npx jest --verbose ./tests/unit/server/*" 17 | }, 18 | "version": "0.1.0", 19 | "devDependencies": { 20 | "@parcel/plugin": "^2.8.3", 21 | "@parcel/transformer-typescript-types": "^2.8.3", 22 | "@testing-library/jest-dom": "^5.16.5", 23 | "@testing-library/react": "^13.4.0", 24 | "@testing-library/user-event": "^14.4.3", 25 | "@trivago/prettier-plugin-sort-imports": "^4.0.0", 26 | "@types/express": "^4.17.15", 27 | "@types/jest": "^29.4.0", 28 | "@types/ramda": "^0.28.22", 29 | "@types/react": "^18.0.27", 30 | "@types/react-dom": "^18.0.10", 31 | "@typescript-eslint/eslint-plugin": "^5.49.0", 32 | "@typescript-eslint/parser": "^5.49.0", 33 | "eslint-config-prettier": "^8.6.0", 34 | "eslint-plugin-import": "^2.27.5", 35 | "eslint-plugin-jsx-a11y": "^6.7.1", 36 | "eslint-plugin-react": "^7.32.1", 37 | "eslint-plugin-react-hooks": "^4.6.0", 38 | "express": "^4.18.2", 39 | "jest": "^29.4.0", 40 | "jest-css-modules": "^2.1.0", 41 | "jest-environment-jsdom": "^29.4.0", 42 | "json-server": "^0.17.1", 43 | "parcel": "^2.8.3", 44 | "parcel-resolver-ts-base-url": "^1.3.1", 45 | "prettier": "^2.8.3", 46 | "primeflex": "^3.3.0", 47 | "primeicons": "^6.0.1", 48 | "primereact": "^8.7.3", 49 | "process": "^0.11.10", 50 | "ramda": "^0.28.0", 51 | "react": "^18.2.0", 52 | "react-dom": "^18.2.0", 53 | "react-router-dom": "^6.8.2", 54 | "rxjs": "^7.8.0", 55 | "ts-jest": "^29.0.5", 56 | "ts-node": "^10.9.1", 57 | "typescript": "^4.9.4" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /examples/assets/cli-test-network-alpha-continuous-1.ts: -------------------------------------------------------------------------------- 1 | import { 2 | MathJSCalculator, 3 | DefaultNetworkAlpha, 4 | NetworkAlphaNeuronFactory, 5 | NetworkAlphaSynapseFactory, 6 | QueryingStatus, 7 | QueryingInputPattern, 8 | } from "dn2a"; 9 | 10 | // The object passed to the constructor function contains properties describing the neural network. 11 | // In case one or more properties are not present they are substituted with defaults. 12 | // Same thing happens if the object is not passed at all. 13 | const mathJSCalculator = new MathJSCalculator(); 14 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 15 | mathJSCalculator 16 | ); 17 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 18 | mathJSCalculator 19 | ); 20 | const neuralNetwork = DefaultNetworkAlpha.getInstance({ 21 | layerDimensions: [2, 4, 4, 1], // the default would be [2, 4, 1] 22 | learningMode: "continuous", 23 | learningRate: 0.3, 24 | momentumRate: 0.7, 25 | maximumError: 0.005, 26 | maximumEpoch: 20000, // the default would be 1000 27 | dataRepository: { neuronLayers: [] }, 28 | neuron: { 29 | generator: networkAlphaNeuronFactory, 30 | }, 31 | synapse: { 32 | generator: networkAlphaSynapseFactory, 33 | }, 34 | }); 35 | 36 | const trainingPatterns = [ 37 | { 38 | input: [0, 0], 39 | output: [0], 40 | }, 41 | { 42 | input: [0, 1], 43 | output: [1], 44 | }, 45 | { 46 | input: [1, 0], 47 | output: [1], 48 | }, 49 | { 50 | input: [1, 1], 51 | output: [0], 52 | }, 53 | ]; 54 | 55 | // Training 56 | neuralNetwork.train(trainingPatterns, undefined, undefined); 57 | 58 | const queryingPatterns = [ 59 | [0, 0], 60 | [0, 1], 61 | [1, 0], 62 | [1, 1], 63 | ]; 64 | 65 | // Querying 66 | // 67 | // The object passed to the callback function contains information about the querying process. 68 | neuralNetwork.query( 69 | queryingPatterns, 70 | (queryingStatus: QueryingStatus) => { 71 | queryingPatterns.forEach( 72 | ( 73 | queryingPattern: QueryingInputPattern, 74 | queryingPatternIndex: number 75 | ) => { 76 | /* eslint-disable no-console */ 77 | console.log( 78 | `[${queryingPatterns[queryingPatternIndex].join( 79 | ", " 80 | )}] => [${queryingStatus.outputPatterns[ 81 | queryingPatternIndex 82 | ].join(", ")}]` 83 | ); 84 | /* eslint-enable no-console */ 85 | } 86 | ); 87 | }, 88 | undefined 89 | ); 90 | -------------------------------------------------------------------------------- /library/assets/core/Cerebrum.ts: -------------------------------------------------------------------------------- 1 | import { 2 | QueryingEpochCallback, 3 | QueryingIterationCallback, 4 | TrainingEpochCallback, 5 | TrainingIterationCallback, 6 | } from "@networks/types"; 7 | 8 | import { 9 | CerebrumConfiguration, 10 | CerebrumInterface, 11 | Network, 12 | NetworkConfiguration, 13 | } from "./types"; 14 | import { QueryingInputPatterns, TrainingPatterns } from "./types"; 15 | 16 | class Cerebrum implements CerebrumInterface { 17 | private configuration: CerebrumConfiguration; 18 | 19 | private networks: Network[]; 20 | 21 | private checkConfiguration() { 22 | return true; 23 | } 24 | 25 | private transformConfiguration() { 26 | return this.configuration; 27 | } 28 | 29 | constructor(configuration: CerebrumConfiguration) { 30 | this.configuration = configuration; 31 | 32 | if (!this.checkConfiguration()) { 33 | throw "Invalid Cerebrum Module Configuration"; 34 | } 35 | this.configuration = this.transformConfiguration(); 36 | 37 | this.networks = []; 38 | 39 | this.configuration.networks.forEach((configuration) => { 40 | this.buildNetwork(configuration); 41 | }); 42 | } 43 | 44 | buildNetwork(configuration: NetworkConfiguration) { 45 | this.networks.push({ 46 | name: configuration.name, 47 | code: configuration.code.generator.getInstance( 48 | configuration.code.configuration 49 | ), 50 | }); 51 | } 52 | 53 | trainNetwork( 54 | trainingPatterns: TrainingPatterns, 55 | epochCallback?: TrainingEpochCallback, 56 | iterationCallback?: TrainingIterationCallback, 57 | networkName = "defaultNetwork" 58 | ) { 59 | const network = this.networks.find((network) => { 60 | return network.name === networkName; 61 | }); 62 | 63 | if (network === undefined) { 64 | throw new Error("Network not found during training"); 65 | } 66 | 67 | network.code.train(trainingPatterns, epochCallback, iterationCallback); 68 | } 69 | 70 | queryNetwork( 71 | queryingPatterns: QueryingInputPatterns, 72 | epochCallback?: QueryingEpochCallback, 73 | iterationCallback?: QueryingIterationCallback, 74 | networkName = "defaultNetwork" 75 | ) { 76 | const network = this.networks.find((network) => { 77 | return network.name === networkName; 78 | }); 79 | 80 | if (network === undefined) { 81 | throw new Error("Network not found during querying"); 82 | } 83 | 84 | network.code.query(queryingPatterns, epochCallback, iterationCallback); 85 | } 86 | } 87 | 88 | export { Cerebrum }; 89 | -------------------------------------------------------------------------------- /examples/assets/cli-test-network-alpha-continuous-2.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultNetworkAlpha, 3 | MathJSCalculator, 4 | NetworkAlphaNeuronFactory, 5 | NetworkAlphaSynapseFactory, 6 | QueryingInputPattern, 7 | QueryingStatus, 8 | TrainingStatus, 9 | } from "dn2a"; 10 | 11 | const mathJSCalculator = new MathJSCalculator(); 12 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 13 | mathJSCalculator 14 | ); 15 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 16 | mathJSCalculator 17 | ); 18 | const neuralNetwork = DefaultNetworkAlpha.getInstance({ 19 | layerDimensions: [2, 4, 4, 1], 20 | learningMode: "continuous", 21 | learningRate: 0.3, 22 | momentumRate: 0.7, 23 | maximumError: 0.005, 24 | maximumEpoch: 20000, 25 | dataRepository: { neuronLayers: [] }, 26 | neuron: { 27 | generator: networkAlphaNeuronFactory, 28 | }, 29 | synapse: { 30 | generator: networkAlphaSynapseFactory, 31 | }, 32 | }); 33 | 34 | const trainingPatterns = [ 35 | { 36 | input: [0, 0], 37 | output: [0], 38 | }, 39 | { 40 | input: [0, 1], 41 | output: [1], 42 | }, 43 | { 44 | input: [1, 0], 45 | output: [1], 46 | }, 47 | { 48 | input: [1, 1], 49 | output: [0], 50 | }, 51 | ]; 52 | 53 | // Training 54 | // 55 | // The object passed to the callback function contains information about the training process. 56 | neuralNetwork.train( 57 | trainingPatterns, 58 | (trainingStatus: TrainingStatus) => { 59 | /* eslint-disable-next-line no-console */ 60 | console.log("Epoch: " + trainingStatus.elapsedEpochCounter); 61 | }, 62 | undefined 63 | ); 64 | 65 | /* eslint-disable no-console */ 66 | console.log(""); 67 | 68 | const queryingPatterns = [ 69 | [0, 0], 70 | [0, 1], 71 | [1, 0], 72 | [1, 1], 73 | ]; 74 | 75 | // Querying 76 | // 77 | // The object passed to the callback function contains information about the querying process. 78 | neuralNetwork.query( 79 | queryingPatterns, 80 | (queryingStatus: QueryingStatus) => { 81 | queryingPatterns.forEach( 82 | ( 83 | queryingPattern: QueryingInputPattern, 84 | queryingPatternIndex: number 85 | ) => { 86 | /* eslint-disable no-console */ 87 | console.log( 88 | `[${queryingPatterns[queryingPatternIndex].join( 89 | ", " 90 | )}] => [${queryingStatus.outputPatterns[ 91 | queryingPatternIndex 92 | ].join(", ")}]` 93 | ); 94 | /* eslint-enable no-console */ 95 | } 96 | ); 97 | }, 98 | undefined 99 | ); 100 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/types.ts: -------------------------------------------------------------------------------- 1 | import { NetworkInterface } from "@networks/types"; 2 | 3 | import { NeuronFactory } from "./NeuronFactory"; 4 | import { SynapseFactory } from "./SynapseFactory"; 5 | 6 | interface DataRepository { 7 | neuronLayers: NeuronInterface[][]; 8 | } 9 | 10 | interface NetworkAlphaInterface extends NetworkInterface { 11 | dataRepository: DataRepository; 12 | } 13 | 14 | interface NetworkConfiguration { 15 | layerDimensions: number[]; 16 | learningMode: "continuous" | "stepatgoal" | "stepbystep"; 17 | learningRate: number; 18 | momentumRate: number; 19 | maximumError: number; 20 | maximumEpoch: number; 21 | dataRepository: DataRepository; 22 | neuron: { 23 | generator: NeuronFactory; 24 | configuration?: NeuronConfiguration; 25 | }; 26 | synapse: { 27 | generator: SynapseFactory; 28 | configuration?: SynapseConfiguration; 29 | }; 30 | } 31 | 32 | interface NeuronInterface { 33 | delta: number; 34 | 35 | expectedOutput: number; 36 | 37 | fixed: boolean; 38 | 39 | incomingConnections: SynapseInterface[]; 40 | 41 | inputSum: number; 42 | 43 | inputs: number[]; 44 | 45 | outgoingConnections: SynapseInterface[]; 46 | 47 | output: number; 48 | 49 | outputError: number; 50 | 51 | previousExpectedOutput: number; 52 | 53 | previousIncomingConnections: SynapseInterface[]; 54 | 55 | previousInputSum: number; 56 | 57 | previousInputs: number[]; 58 | 59 | previousOutgoingConnections: SynapseInterface[]; 60 | 61 | previousOutput: number; 62 | 63 | previousOutputError: number; 64 | 65 | proxy: boolean; 66 | 67 | transferFunction: (value: number) => number; 68 | 69 | addIncomingConnection: (value: SynapseInterface) => void; 70 | 71 | addOutgoingConnection: (value: SynapseInterface) => void; 72 | 73 | addPreviousIncomingConnection: (value: SynapseInterface) => void; 74 | 75 | addPreviousOutgoingConnection: (value: SynapseInterface) => void; 76 | } 77 | 78 | interface NeuronConfiguration { 79 | transferFunction?: (value: number) => number; 80 | } 81 | 82 | interface SynapseInterface { 83 | incomingConnection: NeuronInterface; 84 | 85 | outgoingConnection: NeuronInterface; 86 | 87 | previousIncomingConnection: NeuronInterface; 88 | 89 | previousOutgoingConnection: NeuronInterface; 90 | 91 | previousWeight: number; 92 | 93 | previousWeightChange: number; 94 | 95 | weight: number; 96 | 97 | weightChange: number; 98 | } 99 | 100 | interface SynapseConfiguration { 101 | initializationFunction?: () => number; 102 | } 103 | 104 | export { 105 | DataRepository, 106 | NetworkAlphaInterface as NetworkInterface, 107 | NetworkConfiguration, 108 | NeuronConfiguration, 109 | NeuronInterface, 110 | SynapseConfiguration, 111 | SynapseInterface, 112 | }; 113 | -------------------------------------------------------------------------------- /library/TODO.md: -------------------------------------------------------------------------------- 1 | ## To Do 2 | 3 | - [ ] Add first spiking neural network 4 | - [ ] Improve configuration via factories so that it is not compulsory to send all possible properties in the configuration object 5 | - [ ] Alpha network should not be used by default because hardcoded in the general Cerebrum factory 6 | - [ ] Hardcoded usage of Alpha network should happen if using a specific bootstrapping factory built around it 7 | - [ ] Add new networks as wrappers around third party open source neural networks libraries 8 | - [ ] Add specific bootstraping factories around the new networks as wrappers 9 | - [ ] Implement reactive communication bus into the Cerebrum so that networks can interact with each other using messages each one reference with the name of the network that generated it 10 | - [ ] Enable storing/loading of data and configurations for a single network 11 | - [ ] Enable storing/loading of data and configurations for all networks in a Cerebrum 12 | - [ ] Enable storing/loading of data and configurations for all networks in a Brain 13 | - [ ] Add support for streams and promises to training/querying methods as alternatives to the callbacks 14 | - [ ] Allow use to easily access each single neuron/synapse state change of a network via a event listener approach 15 | - [ ] Fix stepbystep, continuous and stopatgoal learning modes in the Alpha network 16 | - [ ] Refactor training/querying methods in the Alpha network to make them more understandable 17 | - [ ] Complete removal of direct Math.js usage from the Alpha network code making the MathJS adapter responsible for all operations on the basis of a specific interface 18 | - [ ] Improve network resolution mechanism to allow usage of external extensions which respect that same core/infrastructure organization 19 | - [ ] Make each class supporting configuration responsible to validate the settings as well as to throw if needed 20 | - [ ] Add networks that act as logical, persistence, communication and presentation modules to enable programmatic operations 21 | - [ ] Support running each network in a separate web worker 22 | - [ ] Add alternative neuron activation functions in the Alpha network 23 | - [ ] Add alternative synapse update functions in the Alpha network 24 | - [ ] Support networks as WASM modules 25 | - [ ] Add start, pause and stop methods to the Alpha network as well as to the generic network interface 26 | - [ ] Implement decay of synapses in the Alpha network 27 | - [ ] Add example Docker configuration 28 | - [ ] Add data conversion and normalization utilities 29 | - [ ] Support parallelization via Brain sessions intercommunication via HTTP and WebSocket 30 | - [ ] Support realtime parametrization of the Alpha network 31 | - [ ] Add configurable network to execute custom code 32 | - [ ] Support genetic tecniques for training in the Alpha network 33 | - [ ] Support genetic tecniques for training in the Cereburm 34 | - [ ] Support genetic tecniques for training in the Brain 35 | - [ ] Support realtime automatic removal and addition of neurons in the Alpha network 36 | - [ ] Add automatic network dimensions sizing on the basis of training patterns in the Alpha network 37 | 38 | ## In Progress 39 | 40 | - [ ] / 41 | 42 | ## Done 43 | 44 | - [x] Rename "mind" into "network" around the code 45 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/Synapse.ts: -------------------------------------------------------------------------------- 1 | import { all, create } from "mathjs"; 2 | 3 | import { Calculator } from "@networks/types"; 4 | 5 | import { SynapseConfiguration, SynapseInterface } from "./types"; 6 | 7 | const mathjs = create(all); 8 | mathjs.config({ 9 | number: "number", 10 | }); 11 | 12 | class Synapse implements SynapseInterface { 13 | private defaultConfiguration = {} as SynapseConfiguration; 14 | 15 | private configuration: SynapseConfiguration; 16 | 17 | private calculator: Calculator; 18 | 19 | private _incomingConnection; 20 | 21 | private _outgoingConnection; 22 | 23 | private _previousIncomingConnection; 24 | 25 | private _previousOutgoingConnection; 26 | 27 | private _previousWeight = 0; 28 | 29 | private _previousWeightChange = 0; 30 | 31 | private _weight = mathjs.subtract( 32 | 1, 33 | mathjs.multiply(mathjs.random(0, 1), 2) 34 | ); 35 | 36 | private _weightChange = 0; 37 | 38 | private checkConfiguration() { 39 | return true; 40 | } 41 | 42 | private transformConfiguration() { 43 | return this.configuration; 44 | } 45 | 46 | constructor(calculator: Calculator, configuration: SynapseConfiguration) { 47 | this.calculator = calculator; 48 | 49 | this.configuration = configuration; 50 | 51 | if (!this.checkConfiguration()) { 52 | throw "Invalid Synapse Module Configuration"; 53 | } 54 | this.configuration = this.transformConfiguration(); 55 | } 56 | 57 | set incomingConnection(value) { 58 | this._incomingConnection = value; 59 | } 60 | 61 | get incomingConnection() { 62 | return this._incomingConnection; 63 | } 64 | 65 | set outgoingConnection(value) { 66 | this._outgoingConnection = value; 67 | } 68 | 69 | get outgoingConnection() { 70 | return this._outgoingConnection; 71 | } 72 | 73 | set previousIncomingConnection(value) { 74 | this._previousIncomingConnection = value; 75 | } 76 | 77 | get previousIncomingConnection() { 78 | return this._previousIncomingConnection; 79 | } 80 | 81 | set previousOutgoingConnection(value) { 82 | this._previousOutgoingConnection = value; 83 | } 84 | 85 | get previousOutgoingConnection() { 86 | return this._previousOutgoingConnection; 87 | } 88 | 89 | set previousWeight(value) { 90 | this._previousWeight = value; 91 | } 92 | 93 | get previousWeight() { 94 | return this._previousWeight; 95 | } 96 | 97 | set previousWeightChange(value) { 98 | this._previousWeightChange = value; 99 | } 100 | 101 | get previousWeightChange() { 102 | return this._previousWeightChange; 103 | } 104 | 105 | set weight(value) { 106 | this._weight = value; 107 | } 108 | 109 | get weight() { 110 | return this._weight; 111 | } 112 | 113 | set weightChange(value) { 114 | this._weightChange = value; 115 | } 116 | 117 | get weightChange() { 118 | return this._weightChange; 119 | } 120 | } 121 | 122 | export { Synapse }; 123 | -------------------------------------------------------------------------------- /library/assets/core/types.ts: -------------------------------------------------------------------------------- 1 | import { NetworkFactory as NetworkAlphaFactory } from "@networks/alpha/NetworkFactory"; 2 | import { NetworkConfiguration as NetworkAlphaConfiguration } from "@networks/alpha/types"; 3 | import { 4 | QueryingEpochCallback, 5 | QueryingIterationCallback, 6 | TrainingEpochCallback, 7 | TrainingIterationCallback, 8 | } from "@networks/types"; 9 | import { NetworkInterface } from "@networks/types"; 10 | 11 | import { CerebrumFactory } from "./CerebrumFactory"; 12 | 13 | interface TrainingPattern { 14 | input: number[]; 15 | output: number[]; 16 | } 17 | 18 | type TrainingPatterns = TrainingPattern[]; 19 | 20 | interface TrainingIterationPattern { 21 | input: number[]; 22 | target: number[]; 23 | output: number[]; 24 | error: number; 25 | } 26 | 27 | interface TrainingStatus { 28 | outputErrors: number[]; 29 | interruptionRequest: boolean; 30 | elapsedEpochCounter: number; 31 | elapsedIterationCounter: number; 32 | elapsedIterationPattern: TrainingIterationPattern; 33 | } 34 | 35 | type QueryingInputPattern = number[]; 36 | 37 | type QueryingInputPatterns = QueryingInputPattern[]; 38 | 39 | type QueryingOutputPattern = number[]; 40 | 41 | type QueryingOutputPatterns = QueryingOutputPattern[]; 42 | 43 | interface QueryingIterationPattern { 44 | input: number[]; 45 | output: number[]; 46 | } 47 | 48 | interface QueryingStatus { 49 | outputPatterns: number[][]; 50 | elapsedIterationCounter: number; 51 | elapsedIterationPattern: QueryingIterationPattern; 52 | } 53 | 54 | interface CerebrumInterface { 55 | buildNetwork: (configuration: NetworkConfiguration) => void; 56 | 57 | trainNetwork: ( 58 | trainingPatterns: TrainingPatterns, 59 | epochCallback?: TrainingEpochCallback, 60 | iterationCallback?: TrainingIterationCallback, 61 | networkName?: string 62 | ) => void; 63 | 64 | queryNetwork: ( 65 | queryingPatterns: QueryingInputPatterns, 66 | epochCallback?: QueryingEpochCallback, 67 | iterationCallback?: QueryingIterationCallback, 68 | networkName?: string 69 | ) => void; 70 | } 71 | 72 | interface NetworkConfiguration { 73 | name: string; 74 | code: { 75 | generator: NetworkAlphaFactory; 76 | configuration?: NetworkAlphaConfiguration; 77 | }; 78 | inputsFrom: string[]; 79 | } 80 | 81 | interface CerebrumConfiguration { 82 | networks: NetworkConfiguration[]; 83 | outputsFrom: string[]; 84 | } 85 | 86 | interface Network { 87 | name: string; 88 | code: NetworkInterface; 89 | } 90 | 91 | interface BrainInterface { 92 | cerebrum: CerebrumInterface; 93 | } 94 | 95 | interface BrainConfiguration { 96 | cerebrum: { 97 | generator: CerebrumFactory; 98 | configuration?: CerebrumConfiguration; 99 | }; 100 | } 101 | 102 | export { 103 | CerebrumConfiguration, 104 | CerebrumInterface, 105 | Network, 106 | NetworkConfiguration, 107 | BrainConfiguration, 108 | BrainInterface, 109 | TrainingPattern, 110 | TrainingPatterns, 111 | TrainingIterationPattern, 112 | TrainingStatus, 113 | QueryingInputPattern, 114 | QueryingInputPatterns, 115 | QueryingOutputPattern, 116 | QueryingOutputPatterns, 117 | QueryingIterationPattern, 118 | QueryingStatus, 119 | }; 120 | -------------------------------------------------------------------------------- /library/assets/bootstrapper.ts: -------------------------------------------------------------------------------- 1 | import { BrainFactory } from "@core/BrainFactory"; 2 | import { CerebrumFactory } from "@core/CerebrumFactory"; 3 | import { 4 | BrainConfiguration, 5 | BrainInterface, 6 | CerebrumConfiguration, 7 | CerebrumInterface, 8 | } from "@core/types"; 9 | 10 | import { NetworkFactory as NetworkAlphaFactory } from "@networks/alpha/NetworkFactory"; 11 | import { NeuronFactory as NetworkAlphaNeuronFactory } from "@networks/alpha/NeuronFactory"; 12 | import { SynapseFactory as NetworkAlphaSynapseFactory } from "@networks/alpha/SynapseFactory"; 13 | import { 14 | NetworkConfiguration as NetworkAlphaConfiguration, 15 | NetworkInterface as NetworkAlphaInterface, 16 | NeuronInterface as NeuronAlphaInterface, 17 | SynapseInterface as SynapseAlphaInterface, 18 | } from "@networks/alpha/types"; 19 | import { 20 | NeuronConfiguration as NetworkAlphaNeuronConfiguration, 21 | SynapseConfiguration as NetworkAlphaSynapseConfiguration, 22 | } from "@networks/alpha/types"; 23 | 24 | import { MathJSCalculator } from "@infrastructure/Calculator/MathJSCalculator"; 25 | 26 | class DefaultBrain { 27 | static getInstance(configuration?: BrainConfiguration): BrainInterface { 28 | const brainFactory = new BrainFactory( 29 | new MathJSCalculator(), 30 | configuration 31 | ); 32 | const brainInstance = brainFactory.getInstance(); 33 | 34 | return brainInstance; 35 | } 36 | } 37 | 38 | class DefaultCerebrum { 39 | static getInstance( 40 | configuration?: CerebrumConfiguration 41 | ): CerebrumInterface { 42 | const cerebrumFactory = new CerebrumFactory( 43 | new MathJSCalculator(), 44 | configuration 45 | ); 46 | const cerebrumInstance = cerebrumFactory.getInstance(); 47 | 48 | return cerebrumInstance; 49 | } 50 | } 51 | 52 | class DefaultNetworkAlpha { 53 | static getInstance( 54 | configuration?: NetworkAlphaConfiguration 55 | ): NetworkAlphaInterface { 56 | const networkAlphaFactory = new NetworkAlphaFactory( 57 | new MathJSCalculator(), 58 | configuration 59 | ); 60 | const networkAlphaInstance = networkAlphaFactory.getInstance(); 61 | 62 | return networkAlphaInstance; 63 | } 64 | } 65 | 66 | class DefaultNetworkAlphaNeuron { 67 | static getInstance( 68 | configuration?: NetworkAlphaNeuronConfiguration 69 | ): NeuronAlphaInterface { 70 | const neuronFactory = new NetworkAlphaNeuronFactory( 71 | new MathJSCalculator(), 72 | configuration 73 | ); 74 | const neuronInstance = neuronFactory.getInstance(); 75 | 76 | return neuronInstance; 77 | } 78 | } 79 | 80 | class DefaultNetworkAlphaSynapse { 81 | static getInstance( 82 | configuration?: NetworkAlphaSynapseConfiguration 83 | ): SynapseAlphaInterface { 84 | const synapseFactory = new NetworkAlphaSynapseFactory( 85 | new MathJSCalculator(), 86 | configuration 87 | ); 88 | const synapseInstance = synapseFactory.getInstance(); 89 | 90 | return synapseInstance; 91 | } 92 | } 93 | 94 | export { 95 | DefaultBrain, 96 | DefaultCerebrum, 97 | DefaultNetworkAlpha, 98 | DefaultNetworkAlphaNeuron, 99 | DefaultNetworkAlphaSynapse, 100 | }; 101 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/NetworkList.tsx: -------------------------------------------------------------------------------- 1 | import { Column } from "primereact/column"; 2 | import { DataTable } from "primereact/datatable"; 3 | import { Panel } from "primereact/panel"; 4 | import React from "react"; 5 | import { useNavigate } from "react-router-dom"; 6 | 7 | const NetworkList = (props: any) => { 8 | const networks = [...Array(100)].map((network, networkIndex) => ({ 9 | id: `nn-${networkIndex + 1}`, 10 | name: `Neural Network ${networkIndex + 1}`, 11 | type: [ 12 | "alpha", 13 | "beta", 14 | "gamma", 15 | "delta", 16 | "epsilon", 17 | "zeta", 18 | "eta", 19 | "theta", 20 | "iota", 21 | "kappa", 22 | "lambda", 23 | "mu", 24 | "nu", 25 | "xi", 26 | "omicron", 27 | "pi", 28 | "rho", 29 | "sigma", 30 | "tau", 31 | "upsilon", 32 | "phi", 33 | "chi", 34 | "psi", 35 | "omega", 36 | ][Math.floor(24 * Math.random())], 37 | inputSize: Math.ceil(100 * Math.random()), 38 | outputSize: Math.ceil(10 * Math.random()), 39 | inputsFrom: "", 40 | })); 41 | const connectedNetworks = networks.map((network) => ({ 42 | ...network, 43 | inputsFrom: [...Array(Math.ceil(5 * Math.random()))] 44 | .map( 45 | () => networks[Math.floor(networks.length * Math.random())].name 46 | ) 47 | .join(", "), 48 | })); 49 | 50 | const navigate = useNavigate(); 51 | 52 | const openNetwork = (network: any) => { 53 | navigate(`network/${network.id}`); 54 | }; 55 | 56 | return ( 57 | 58 | { 67 | openNetwork(event.value.rowData); 68 | }} 69 | onPage={(event) => { 70 | props.setPage(event.page || 0); 71 | props.setRowsPerPage(event.rows || 10); 72 | }} 73 | > 74 | 79 | 84 | 89 | 94 | 95 | 96 | 97 | ); 98 | }; 99 | 100 | export { NetworkList }; 101 | -------------------------------------------------------------------------------- /examples/assets/cli-test-network-alpha-continuous-3.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultCerebrum, 3 | CerebrumConfiguration, 4 | NetworkAlphaFactory, 5 | NetworkAlphaNeuronFactory, 6 | NetworkAlphaSynapseFactory, 7 | MathJSCalculator, 8 | TrainingStatus, 9 | QueryingStatus, 10 | QueryingInputPattern, 11 | } from "dn2a"; 12 | 13 | const mathJSCalculator = new MathJSCalculator(); 14 | const networkAlphaFactory = new NetworkAlphaFactory(mathJSCalculator); 15 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 16 | mathJSCalculator 17 | ); 18 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 19 | mathJSCalculator 20 | ); 21 | const cerebrum = DefaultCerebrum.getInstance({ 22 | networks: [ 23 | { 24 | name: "firstNeuralNetwork", 25 | code: { 26 | generator: networkAlphaFactory, 27 | configuration: { 28 | layerDimensions: [2, 4, 1], 29 | learningMode: "continuous", 30 | learningRate: 0.3, 31 | momentumRate: 0.7, 32 | maximumError: 0.005, 33 | maximumEpoch: 1000, 34 | dataRepository: { neuronLayers: [] }, 35 | neuron: { 36 | generator: networkAlphaNeuronFactory, 37 | }, 38 | synapse: { 39 | generator: networkAlphaSynapseFactory, 40 | }, 41 | }, 42 | }, 43 | inputsFrom: ["cerebrum"], 44 | }, 45 | ], 46 | outputsFrom: ["firstNeuralNetwork"], 47 | } as CerebrumConfiguration); 48 | 49 | const trainingPatterns = [ 50 | { 51 | input: [0, 0], 52 | output: [0], 53 | }, 54 | { 55 | input: [0, 1], 56 | output: [1], 57 | }, 58 | { 59 | input: [1, 0], 60 | output: [1], 61 | }, 62 | { 63 | input: [1, 1], 64 | output: [0], 65 | }, 66 | ]; 67 | 68 | // Training 69 | // 70 | // The object passed to the callback function contains information about the training process. 71 | // The name passed to the trainNetwork method specifies which specific network to train 72 | cerebrum.trainNetwork( 73 | trainingPatterns, 74 | (trainingStatus: TrainingStatus) => { 75 | /* eslint-disable-next-line no-console */ 76 | console.log(`Epoch: ${trainingStatus.elapsedEpochCounter}`); 77 | }, 78 | undefined, 79 | "firstNeuralNetwork" 80 | ); 81 | 82 | /* eslint-disable no-console */ 83 | console.log(""); 84 | 85 | const queryingPatterns = [ 86 | [0, 0], 87 | [0, 1], 88 | [1, 0], 89 | [1, 1], 90 | ]; 91 | 92 | // Querying 93 | // 94 | // The object passed to the callback function contains information about the querying process. 95 | // The name passed to the queryNetwork method specifies which specific network to query 96 | cerebrum.queryNetwork( 97 | queryingPatterns, 98 | (queryingStatus: QueryingStatus) => { 99 | queryingPatterns.forEach( 100 | ( 101 | queryingPattern: QueryingInputPattern, 102 | queryingPatternIndex: number 103 | ) => { 104 | /* eslint-disable no-console */ 105 | console.log( 106 | `[${queryingPatterns[queryingPatternIndex].join( 107 | ", " 108 | )}] => [${queryingStatus.outputPatterns[ 109 | queryingPatternIndex 110 | ].join(", ")}]` 111 | ); 112 | /* eslint-enable no-console */ 113 | } 114 | ); 115 | }, 116 | undefined, 117 | "firstNeuralNetwork" 118 | ); 119 | -------------------------------------------------------------------------------- /library/tests/acceptance/should-be-able-to-solve-the-xor-problem.test.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CerebrumFactory, 3 | DefaultBrain, 4 | MathJSCalculator, 5 | NetworkAlphaFactory, 6 | NetworkAlphaNeuronFactory, 7 | NetworkAlphaSynapseFactory, 8 | } from "@assets/index"; 9 | 10 | import { CerebrumConfiguration } from "@core/types"; 11 | import { 12 | QueryingInputPattern, 13 | QueryingOutputPattern, 14 | QueryingStatus, 15 | } from "@core/types"; 16 | 17 | describe("When trained with training examples about the XOR problem", () => { 18 | it("Should be able to train up to a satisfying accuracy", () => { 19 | const mathJSCalculator = new MathJSCalculator(); 20 | const cerebrumFactory = new CerebrumFactory(mathJSCalculator); 21 | const networkAlphaFactory = new NetworkAlphaFactory(mathJSCalculator); 22 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 23 | mathJSCalculator 24 | ); 25 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 26 | mathJSCalculator 27 | ); 28 | const brain = DefaultBrain.getInstance({ 29 | cerebrum: { 30 | generator: cerebrumFactory, 31 | configuration: { 32 | networks: [ 33 | { 34 | name: "defaultNetwork", 35 | code: { 36 | generator: networkAlphaFactory, 37 | configuration: { 38 | layerDimensions: [2, 4, 1], 39 | learningMode: "continuous", 40 | learningRate: 0.3, 41 | momentumRate: 0.7, 42 | maximumError: 0.005, 43 | maximumEpoch: 1000000, 44 | dataRepository: { neuronLayers: [] }, 45 | neuron: { 46 | generator: networkAlphaNeuronFactory, 47 | }, 48 | synapse: { 49 | generator: networkAlphaSynapseFactory, 50 | }, 51 | }, 52 | }, 53 | inputsFrom: ["cerebrum"], 54 | }, 55 | ], 56 | outputsFrom: ["defaultNetwork"], 57 | } as CerebrumConfiguration, 58 | }, 59 | }); 60 | const trainingPatterns = [ 61 | { 62 | input: [0, 0], 63 | output: [0], 64 | }, 65 | { 66 | input: [0, 1], 67 | output: [1], 68 | }, 69 | { 70 | input: [1, 0], 71 | output: [1], 72 | }, 73 | { 74 | input: [1, 1], 75 | output: [0], 76 | }, 77 | ]; 78 | const queryingPatterns = [ 79 | [0, 0], 80 | [0, 1], 81 | [1, 0], 82 | [1, 1], 83 | ]; 84 | const expectedQueryingResults = [ 85 | { 86 | input: [0, 0], 87 | output: [expect.closeTo(0.05, 1)], 88 | }, 89 | { 90 | input: [0, 1], 91 | output: [expect.closeTo(0.95, 1)], 92 | }, 93 | { 94 | input: [1, 0], 95 | output: [expect.closeTo(0.95, 1)], 96 | }, 97 | { 98 | input: [1, 1], 99 | output: [expect.closeTo(0.05, 1)], 100 | }, 101 | ]; 102 | 103 | brain.cerebrum.trainNetwork(trainingPatterns); 104 | const queryingResults = [] as { 105 | input: QueryingInputPattern; 106 | output: QueryingOutputPattern; 107 | }[]; 108 | brain.cerebrum.queryNetwork( 109 | queryingPatterns, 110 | (queryingStatus: QueryingStatus) => { 111 | queryingPatterns.forEach( 112 | ( 113 | queryingPattern: QueryingInputPattern, 114 | queryingPatternIndex: number 115 | ) => { 116 | queryingResults.push({ 117 | input: queryingPattern, 118 | output: queryingStatus.outputPatterns[ 119 | queryingPatternIndex 120 | ], 121 | }); 122 | } 123 | ); 124 | }, 125 | undefined, 126 | "defaultNetwork" 127 | ); 128 | 129 | expect(queryingResults).toEqual(expectedQueryingResults); 130 | }); 131 | }); 132 | -------------------------------------------------------------------------------- /examples/assets/cli-test-network-alpha-stepbystep-0.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultBrain, 3 | CerebrumFactory, 4 | MathJSCalculator, 5 | NetworkAlphaFactory, 6 | NetworkAlphaNeuronFactory, 7 | NetworkAlphaSynapseFactory, 8 | TrainingStatus, 9 | QueryingStatus, 10 | QueryingOutputPattern, 11 | } from "dn2a"; 12 | 13 | const mathJSCalculator = new MathJSCalculator(); 14 | const cerebrumFactory = new CerebrumFactory(mathJSCalculator); 15 | const networkAlphaFactory = new NetworkAlphaFactory(mathJSCalculator); 16 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 17 | mathJSCalculator 18 | ); 19 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 20 | mathJSCalculator 21 | ); 22 | const brain = DefaultBrain.getInstance({ 23 | cerebrum: { 24 | generator: cerebrumFactory, 25 | configuration: { 26 | networks: [ 27 | { 28 | name: "defaultNetwork", 29 | code: { 30 | generator: networkAlphaFactory, 31 | configuration: { 32 | layerDimensions: [2, 4, 1], 33 | learningMode: "stepbystep", 34 | learningRate: 0.3, 35 | momentumRate: 0.7, 36 | maximumError: 0.005, 37 | maximumEpoch: 1000, 38 | dataRepository: { neuronLayers: [] }, 39 | neuron: { 40 | generator: networkAlphaNeuronFactory, 41 | }, 42 | synapse: { 43 | generator: networkAlphaSynapseFactory, 44 | }, 45 | }, 46 | }, 47 | inputsFrom: ["cerebrum"], 48 | }, 49 | ], 50 | outputsFrom: ["defaultNetwork"], 51 | }, 52 | }, 53 | }); 54 | 55 | const trainingPatterns = [ 56 | { 57 | input: [0, 0], 58 | output: [0], 59 | }, 60 | { 61 | input: [0, 1], 62 | output: [1], 63 | }, 64 | { 65 | input: [1, 0], 66 | output: [1], 67 | }, 68 | { 69 | input: [1, 1], 70 | output: [0], 71 | }, 72 | ]; 73 | 74 | // Training 75 | // 76 | // The object passed to the callback function contains information about the training process. 77 | interface ErrorStatus { 78 | minimumError: number; 79 | averageError: number; 80 | maximumError: number; 81 | } 82 | brain.cerebrum.trainNetwork( 83 | trainingPatterns, 84 | (trainingStatus: TrainingStatus) => { 85 | const errorStatus = trainingStatus.outputErrors.reduce( 86 | (errorStatus: ErrorStatus, outputError: number) => { 87 | const error = parseFloat(outputError.toString()); 88 | return { 89 | minimumError: 90 | error < errorStatus.minimumError 91 | ? error 92 | : errorStatus.minimumError, 93 | averageError: 94 | errorStatus.averageError + 95 | error / trainingStatus.outputErrors.length, 96 | maximumError: 97 | error > errorStatus.maximumError 98 | ? error 99 | : errorStatus.maximumError, 100 | }; 101 | }, 102 | { 103 | minimumError: 1, 104 | averageError: 0, 105 | maximumError: 0, 106 | } 107 | ); 108 | /* eslint-disable no-console */ 109 | console.log( 110 | `Epoch ${trainingStatus.elapsedEpochCounter}\nMin. Err. = ${errorStatus.minimumError}\nAvg. Err. = ${errorStatus.averageError}\nMax. Err. = ${errorStatus.maximumError}\n` 111 | ); 112 | /* eslint-enable no-console */ 113 | }, 114 | undefined, 115 | "defaultNetwork" 116 | ); 117 | 118 | const queryingPatterns = [ 119 | [0, 0], 120 | [0, 1], 121 | [1, 0], 122 | [1, 1], 123 | ]; 124 | 125 | // Querying 126 | // 127 | // The object passed to the callback function contains information about the querying process. 128 | brain.cerebrum.queryNetwork( 129 | queryingPatterns, 130 | (queryingStatus: QueryingStatus) => { 131 | queryingStatus.outputPatterns.forEach( 132 | ( 133 | outputPattern: QueryingOutputPattern, 134 | outputPatternIndex: number 135 | ) => { 136 | /* eslint-disable no-console */ 137 | console.log( 138 | `Query ${outputPatternIndex}\n[${queryingPatterns[ 139 | outputPatternIndex 140 | ].join(", ")}] = ${outputPattern[0].toString()}\n` 141 | ); 142 | /* eslint-enable no-console */ 143 | } 144 | ); 145 | }, 146 | undefined, 147 | "defaultNetwork" 148 | ); 149 | -------------------------------------------------------------------------------- /examples/assets/cli-test-network-alpha-continuous-4.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultBrain, 3 | BrainConfiguration, 4 | CerebrumFactory, 5 | MathJSCalculator, 6 | NetworkAlphaFactory, 7 | NetworkAlphaNeuronFactory, 8 | NetworkAlphaSynapseFactory, 9 | QueryingOutputPattern, 10 | QueryingStatus, 11 | TrainingStatus, 12 | } from "dn2a"; 13 | 14 | const mathJSCalculator = new MathJSCalculator(); 15 | const cerebrumFactory = new CerebrumFactory(mathJSCalculator); 16 | const networkAlphaFactory = new NetworkAlphaFactory(mathJSCalculator); 17 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 18 | mathJSCalculator 19 | ); 20 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 21 | mathJSCalculator 22 | ); 23 | const brain = DefaultBrain.getInstance({ 24 | cerebrum: { 25 | generator: cerebrumFactory, 26 | configuration: { 27 | networks: [ 28 | { 29 | name: "defaultNetwork", 30 | code: { 31 | generator: networkAlphaFactory, 32 | configuration: { 33 | layerDimensions: [2, 4, 1], 34 | learningMode: "continuous", 35 | learningRate: 0.3, 36 | momentumRate: 0.7, 37 | maximumError: 0.005, 38 | maximumEpoch: 1000, 39 | dataRepository: { neuronLayers: [] }, 40 | neuron: { 41 | generator: networkAlphaNeuronFactory, 42 | }, 43 | synapse: { 44 | generator: networkAlphaSynapseFactory, 45 | }, 46 | }, 47 | }, 48 | inputsFrom: ["cerebrum"], 49 | }, 50 | ], 51 | outputsFrom: ["defaultNetwork"], 52 | }, 53 | }, 54 | } as BrainConfiguration); 55 | 56 | const trainingPatterns = [ 57 | { 58 | input: [0, 0], 59 | output: [0], 60 | }, 61 | { 62 | input: [0, 1], 63 | output: [1], 64 | }, 65 | { 66 | input: [1, 0], 67 | output: [1], 68 | }, 69 | { 70 | input: [1, 1], 71 | output: [0], 72 | }, 73 | ]; 74 | 75 | // Training 76 | // 77 | // The object passed to the callback function contains information about the training process. 78 | interface ErrorStatus { 79 | minimumError: number; 80 | averageError: number; 81 | maximumError: number; 82 | } 83 | brain.cerebrum.trainNetwork( 84 | trainingPatterns, 85 | (trainingStatus: TrainingStatus) => { 86 | const errorStatus = trainingStatus.outputErrors.reduce( 87 | (errorStatus: ErrorStatus, outputError: number) => { 88 | const error = parseFloat(outputError.toString()); 89 | return { 90 | minimumError: 91 | error < errorStatus.minimumError 92 | ? error 93 | : errorStatus.minimumError, 94 | averageError: 95 | errorStatus.averageError + 96 | error / trainingStatus.outputErrors.length, 97 | maximumError: 98 | error > errorStatus.maximumError 99 | ? error 100 | : errorStatus.maximumError, 101 | }; 102 | }, 103 | { 104 | minimumError: 1, 105 | averageError: 0, 106 | maximumError: 0, 107 | } 108 | ); 109 | /* eslint-disable no-console */ 110 | console.log( 111 | `Epoch ${trainingStatus.elapsedEpochCounter}\nMin. Err. = ${errorStatus.minimumError}\nAvg. Err. = ${errorStatus.averageError}\nMax. Err. = ${errorStatus.maximumError}\n` 112 | ); 113 | /* eslint-enable no-console */ 114 | }, 115 | undefined, 116 | "defaultNetwork" 117 | ); 118 | 119 | const queryingPatterns = [ 120 | [0, 0], 121 | [0, 1], 122 | [1, 0], 123 | [1, 1], 124 | ]; 125 | 126 | // Querying 127 | // 128 | // The object passed to the callback function contains information about the querying process. 129 | brain.cerebrum.queryNetwork( 130 | queryingPatterns, 131 | (queryingStatus: QueryingStatus) => { 132 | queryingStatus.outputPatterns.forEach( 133 | ( 134 | outputPattern: QueryingOutputPattern, 135 | outputPatternIndex: number 136 | ) => { 137 | /* eslint-disable no-console */ 138 | console.log( 139 | `[${queryingPatterns[outputPatternIndex].join( 140 | ", " 141 | )}] => [${outputPattern[0].toString()}]` 142 | ); 143 | /* eslint-enable no-console */ 144 | } 145 | ); 146 | }, 147 | undefined, 148 | "defaultNetwork" 149 | ); 150 | -------------------------------------------------------------------------------- /examples/assets/browser-test-network-alpha-stepbystep/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultBrain, 3 | BrainConfiguration, 4 | CerebrumFactory, 5 | MathJSCalculator, 6 | NetworkAlphaFactory, 7 | NetworkAlphaNeuronFactory, 8 | NetworkAlphaSynapseFactory, 9 | TrainingStatus, 10 | QueryingStatus, 11 | QueryingInputPattern, 12 | } from "dn2a"; 13 | 14 | const run = () => { 15 | const mathJSCalculator = new MathJSCalculator(); 16 | const cerebrumFactory = new CerebrumFactory(mathJSCalculator); 17 | const networkAlphaFactory = new NetworkAlphaFactory(mathJSCalculator); 18 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 19 | mathJSCalculator 20 | ); 21 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 22 | mathJSCalculator 23 | ); 24 | const brain = DefaultBrain.getInstance({ 25 | cerebrum: { 26 | generator: cerebrumFactory, 27 | configuration: { 28 | networks: [ 29 | { 30 | name: "defaultNetwork", 31 | code: { 32 | generator: networkAlphaFactory, 33 | configuration: { 34 | layerDimensions: [2, 4, 1], 35 | learningMode: "stepbystep", 36 | learningRate: 0.3, 37 | momentumRate: 0.7, 38 | maximumError: 0.005, 39 | maximumEpoch: 1000, 40 | dataRepository: { neuronLayers: [] }, 41 | neuron: { 42 | generator: networkAlphaNeuronFactory, 43 | }, 44 | synapse: { 45 | generator: networkAlphaSynapseFactory, 46 | }, 47 | }, 48 | }, 49 | inputsFrom: ["cerebrum"], 50 | }, 51 | ], 52 | outputsFrom: ["defaultNetwork"], 53 | }, 54 | }, 55 | } as BrainConfiguration); 56 | 57 | const trainingPatterns = [ 58 | { 59 | input: [0, 0], 60 | output: [0], 61 | }, 62 | { 63 | input: [0, 1], 64 | output: [1], 65 | }, 66 | { 67 | input: [1, 0], 68 | output: [1], 69 | }, 70 | { 71 | input: [1, 1], 72 | output: [0], 73 | }, 74 | ]; 75 | 76 | // Training 77 | interface ErrorStatus { 78 | minimumError: number; 79 | averageError: number; 80 | maximumError: number; 81 | } 82 | brain.cerebrum.trainNetwork( 83 | trainingPatterns, 84 | (trainingStatus: TrainingStatus) => { 85 | const errorStatus = trainingStatus.outputErrors.reduce( 86 | (errorStatus: ErrorStatus, outputError: number) => { 87 | const error = parseFloat(outputError.toString()); 88 | return { 89 | minimumError: 90 | error < errorStatus.minimumError 91 | ? error 92 | : errorStatus.minimumError, 93 | averageError: 94 | errorStatus.averageError + 95 | error / trainingStatus.outputErrors.length, 96 | maximumError: 97 | error > errorStatus.maximumError 98 | ? error 99 | : errorStatus.maximumError, 100 | }; 101 | }, 102 | { 103 | minimumError: 1, 104 | averageError: 0, 105 | maximumError: 0, 106 | } 107 | ); 108 | /* eslint-disable no-console */ 109 | console.log( 110 | `Epoch ${trainingStatus.elapsedEpochCounter}\nMin. Err. = ${errorStatus.minimumError}\nAvg. Err. = ${errorStatus.averageError}\nMax. Err. = ${errorStatus.maximumError}\n` 111 | ); 112 | /* eslint-enable no-console */ 113 | } 114 | ); 115 | 116 | const queryingPatterns = [ 117 | [0, 0], 118 | [0, 1], 119 | [1, 0], 120 | [1, 1], 121 | ]; 122 | 123 | // Querying 124 | // 125 | // The object passed to the callback function contains information about the querying process. 126 | brain.cerebrum.queryNetwork( 127 | queryingPatterns, 128 | (queryingStatus: QueryingStatus) => { 129 | queryingStatus.outputPatterns.forEach( 130 | ( 131 | outputPattern: QueryingInputPattern, 132 | outputPatternIndex: number 133 | ) => { 134 | /* eslint-disable no-console */ 135 | console.log( 136 | `Query ${outputPatternIndex}\n[${queryingPatterns[ 137 | outputPatternIndex 138 | ].join(", ")}] = ${outputPattern[0].toString()}\n` 139 | ); 140 | /* eslint-enable no-console */ 141 | } 142 | ); 143 | } 144 | ); 145 | }; 146 | 147 | document.addEventListener("DOMContentLoaded", run); 148 | -------------------------------------------------------------------------------- /examples/assets/browser-test-network-alpha-continuous/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DefaultBrain, 3 | BrainConfiguration, 4 | CerebrumFactory, 5 | MathJSCalculator, 6 | NetworkAlphaFactory, 7 | NetworkAlphaNeuronFactory, 8 | NetworkAlphaSynapseFactory, 9 | TrainingStatus, 10 | QueryingStatus, 11 | QueryingOutputPattern, 12 | } from "dn2a"; 13 | 14 | const run = () => { 15 | const mathJSCalculator = new MathJSCalculator(); 16 | const cerebrumFactory = new CerebrumFactory(mathJSCalculator); 17 | const networkAlphaFactory = new NetworkAlphaFactory(mathJSCalculator); 18 | const networkAlphaNeuronFactory = new NetworkAlphaNeuronFactory( 19 | mathJSCalculator 20 | ); 21 | const networkAlphaSynapseFactory = new NetworkAlphaSynapseFactory( 22 | mathJSCalculator 23 | ); 24 | const brain = DefaultBrain.getInstance({ 25 | cerebrum: { 26 | generator: cerebrumFactory, 27 | configuration: { 28 | networks: [ 29 | { 30 | name: "defaultNetwork", 31 | code: { 32 | generator: networkAlphaFactory, 33 | configuration: { 34 | layerDimensions: [2, 4, 1], 35 | learningMode: "continuous", 36 | learningRate: 0.3, 37 | momentumRate: 0.7, 38 | maximumError: 0.005, 39 | maximumEpoch: 1000, 40 | dataRepository: { neuronLayers: [] }, 41 | neuron: { 42 | generator: networkAlphaNeuronFactory, 43 | }, 44 | synapse: { 45 | generator: networkAlphaSynapseFactory, 46 | }, 47 | }, 48 | }, 49 | inputsFrom: ["cerebrum"], 50 | }, 51 | ], 52 | outputsFrom: ["defaultNetwork"], 53 | }, 54 | }, 55 | } as BrainConfiguration); 56 | 57 | // Training 58 | const trainingPatterns = [ 59 | { 60 | input: [0, 0], 61 | output: [0], 62 | }, 63 | { 64 | input: [0, 1], 65 | output: [1], 66 | }, 67 | { 68 | input: [1, 0], 69 | output: [1], 70 | }, 71 | { 72 | input: [1, 1], 73 | output: [0], 74 | }, 75 | ]; 76 | 77 | interface ErrorStatus { 78 | minimumError: number; 79 | averageError: number; 80 | maximumError: number; 81 | } 82 | brain.cerebrum.trainNetwork( 83 | trainingPatterns, 84 | (trainingStatus: TrainingStatus) => { 85 | const errorStatus = trainingStatus.outputErrors.reduce( 86 | (errorStatus: ErrorStatus, outputError: number) => { 87 | const error = parseFloat(outputError.toString()); 88 | 89 | return { 90 | minimumError: 91 | error < errorStatus.minimumError 92 | ? error 93 | : errorStatus.minimumError, 94 | averageError: 95 | errorStatus.averageError + 96 | error / trainingStatus.outputErrors.length, 97 | maximumError: 98 | error > errorStatus.maximumError 99 | ? error 100 | : errorStatus.maximumError, 101 | }; 102 | }, 103 | { 104 | minimumError: 1, 105 | averageError: 0, 106 | maximumError: 0, 107 | } 108 | ); 109 | /* eslint-disable no-console */ 110 | console.log( 111 | `Epoch ${trainingStatus.elapsedEpochCounter}\nMin. Err. = ${errorStatus.minimumError}\nAvg. Err. = ${errorStatus.averageError}\nMax. Err. = ${errorStatus.maximumError}\n` 112 | ); 113 | /* eslint-enable no-console */ 114 | } 115 | ); 116 | 117 | const queryingPatterns = [ 118 | [0, 0], 119 | [0, 1], 120 | [1, 0], 121 | [1, 1], 122 | ]; 123 | 124 | // Querying 125 | // 126 | // The object passed to the callback function contains information about the querying process. 127 | brain.cerebrum.queryNetwork( 128 | queryingPatterns, 129 | (queryingStatus: QueryingStatus) => { 130 | queryingStatus.outputPatterns.forEach( 131 | ( 132 | outputPattern: QueryingOutputPattern, 133 | outputPatternIndex: number 134 | ) => { 135 | /* eslint-disable no-console */ 136 | console.log( 137 | `Query ${outputPatternIndex} \n[${queryingPatterns[ 138 | outputPatternIndex 139 | ].join(", ")}] = ${outputPattern[0].toString()}\n` 140 | ); 141 | /* eslint-enable no-console */ 142 | } 143 | ); 144 | } 145 | ); 146 | }; 147 | 148 | document.addEventListener("DOMContentLoaded", run); 149 | -------------------------------------------------------------------------------- /workspace/assets/client/infrastructure/ui/react/prototype/Frame.tsx: -------------------------------------------------------------------------------- 1 | import { Menubar } from "primereact/menubar"; 2 | import React, { useState } from "react"; 3 | import { Route, Routes } from "react-router-dom"; 4 | import { useNavigate } from "react-router-dom"; 5 | import { EventList } from "./EventList"; 6 | 7 | import { Network } from "./Network"; 8 | import { NetworkCreation } from "./NetworkCreation"; 9 | import { NetworkGraph } from "./NetworkGraph"; 10 | import { NetworkList } from "./NetworkList"; 11 | import { NetworkPipeline } from "./NetworkPipeline"; 12 | import { NetworkQuerying } from "./NetworkQuerying"; 13 | import { NetworkTraining } from "./NetworkTraining"; 14 | import { ProjectCreation } from "./ProjectCreation"; 15 | import { ProjectDeployment } from "./ProjectDeployment"; 16 | import { ProjectExecution } from "./ProjectExecution"; 17 | import { ProjectExportation } from "./ProjectExportation"; 18 | import { ProjectSelection } from "./ProjectSelection"; 19 | 20 | const Frame = () => { 21 | const menuVoices = [ 22 | { 23 | label: "File", 24 | items: [ 25 | { 26 | label: "New", 27 | items: [ 28 | { 29 | label: "Project", 30 | url: "/prototype/project-creation" 31 | }, 32 | { 33 | label: "Network", 34 | url: "/prototype/network-creation" 35 | }, 36 | ], 37 | }, 38 | { 39 | label: "Open Project", 40 | url: "/prototype/project-selection" 41 | }, 42 | { 43 | separator: true, 44 | }, 45 | { 46 | label: "Export Project", 47 | url: "/prototype/project-exportation" 48 | }, 49 | ], 50 | }, 51 | { 52 | label: "View", 53 | items: [ 54 | { 55 | label: "List", 56 | url: "/prototype" 57 | }, 58 | { 59 | label: "Pipeline", 60 | url: "/prototype/network-pipeline" 61 | }, 62 | { 63 | label: "Graph", 64 | url: "/prototype/network-graph" 65 | }, 66 | ], 67 | }, 68 | { 69 | label: "Training", 70 | url: "/prototype/network-training" 71 | }, 72 | { 73 | label: "Querying", 74 | url: "/prototype/network-querying" 75 | }, 76 | { 77 | label: "Events", 78 | items: [ 79 | { 80 | label: "List", 81 | url: "/prototype/event-list" 82 | } 83 | ], 84 | }, 85 | { 86 | label: "Run", 87 | icon: "pi pi-fw pi-play", 88 | url: "/prototype/project-execution" 89 | }, 90 | { 91 | label: "Deploy", 92 | icon: "pi pi-fw pi-cloud-upload", 93 | url: "/prototype/project-deployment" 94 | }, 95 | ]; 96 | 97 | const [page, setPage] = useState(0); 98 | const [rowsPerPage, setRowsPerPage] = useState(10); 99 | const navigate = useNavigate(); 100 | 101 | const switchToUIPrototype = () => { 102 | navigate("/"); 103 | }; 104 | 105 | return ( 106 | <> 107 | { console.log(event) }} 112 | /> 113 | 114 | } /> 115 | } /> 116 | } /> 117 | } /> 118 | 127 | } 128 | /> 129 | } /> 130 | } /> 131 | } /> 132 | } /> 133 | } /> 134 | } /> 135 | } /> 136 | } /> 137 | 138 |
139 | 140 |
141 | 142 | ); 143 | }; 144 | 145 | export { Frame }; 146 | -------------------------------------------------------------------------------- /library/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## vX.Y.Z (in progress) 2 | 3 | * NPM modules update. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#70](https://github.com/antoniodeluca/dn2a/pull/70) 4 | * Updated README. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#67](https://github.com/antoniodeluca/dn2a/pull/67) 5 | * Neuron generator method tests. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#66](https://github.com/antoniodeluca/dn2a/pull/66) 6 | * Linting up and running. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#64](https://github.com/antoniodeluca/dn2a/pull/64) 7 | * Added eslint and created a first version of the configuration. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#63](https://github.com/antoniodeluca/dn2a/pull/63) 8 | * Included distributed folder into NPM package. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#62](https://github.com/antoniodeluca/dn2a/pull/62) 9 | * Import of used functions only. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#61](https://github.com/antoniodeluca/dn2a/pull/61) 10 | * README corrections. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#60](https://github.com/antoniodeluca/dn2a/pull/60) 11 | * Updated main entry file name, repository url and examples code. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#59](https://github.com/antoniodeluca/dn2a/pull/59) 12 | * Added a CHANGELOG.md file. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#57](https://github.com/antoniodeluca/dn2a/pull/57) 13 | * Removed unwanted badges. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#56](https://github.com/antoniodeluca/dn2a/pull/56) 14 | * Removed not used alias modules. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#55](https://github.com/antoniodeluca/dn2a/pull/55) 15 | * Updated various variable declarations. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#54](https://github.com/antoniodeluca/dn2a/pull/54) 16 | * Removed folder for compiled assets. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#53](https://github.com/antoniodeluca/dn2a/pull/53) 17 | * New building approach, different files structure and fixed bugs. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#52](https://github.com/antoniodeluca/dn2a/pull/52) 18 | 19 | ## v0.2.0 (1 Nov 2016) 20 | 21 | * Fixed version number reported into the Bower configuration. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#49](https://github.com/antoniodeluca/dn2a/pull/49) 22 | * New parameters for the training and querying status objects plus minor changes. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#20](https://github.com/antoniodeluca/dn2a/pull/20) 23 | * Documentation changes and removal of Async. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#19](https://github.com/antoniodeluca/dn2a/pull/19) 24 | * Added initial version of the CONTRIBUTING file needed to clarify the terms under which is possible to contribute to the project. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#18](https://github.com/antoniodeluca/dn2a/pull/18) 25 | * NPM and Bower configurations updates. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#17](https://github.com/antoniodeluca/dn2a/pull/17) 26 | * Improved testing environment configuration and added some badges. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#15](https://github.com/antoniodeluca/dn2a/pull/15) 27 | * Minor improvements and environment configuration for tests. First test containers have been added. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#14](https://github.com/antoniodeluca/dn2a/pull/14) 28 | 29 | ## v0.1.1 (29 Jul 2016) 30 | 31 | * Fixed some typos. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#13](https://github.com/antoniodeluca/dn2a/pull/13) 32 | 33 | ## v0.1.0 (28 Jul 2016) 34 | 35 | * Removed bundle folder from the ignored items of NPM. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#12](https://github.com/antoniodeluca/dn2a/pull/12) 36 | * Neuron and Synapse module refactoring. Minor improvements. Updated documentation. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#11](https://github.com/antoniodeluca/dn2a/pull/11) 37 | * Other improvement to configurability and new README. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#10](https://github.com/antoniodeluca/dn2a/pull/10) 38 | * Improvement to configurability. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#9](https://github.com/antoniodeluca/dn2a/pull/9) 39 | * Decoupled and exposed modules. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#8](https://github.com/antoniodeluca/dn2a/pull/8) 40 | * Added support for momentum. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#7](https://github.com/antoniodeluca/dn2a/pull/7) 41 | * Improvements to the learning algorithm and new examples. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#6](https://github.com/antoniodeluca/dn2a/pull/6) 42 | * Changes for NPM package publication. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#5](https://github.com/antoniodeluca/dn2a/pull/5) 43 | * Fixed problem with tabs and spaces. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#4](https://github.com/antoniodeluca/dn2a/pull/4) 44 | * Added first version of the main documentation file. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#3](https://github.com/antoniodeluca/dn2a/pull/3) 45 | * Completed weights update functionality and improved the whole code. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#2](https://github.com/antoniodeluca/dn2a/pull/2) 46 | * A first implementation!. From [@antoniodeluca](https://github.com/antoniodeluca) with PR [#1](https://github.com/antoniodeluca/dn2a/pull/1) 47 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/Neuron.ts: -------------------------------------------------------------------------------- 1 | import { all, create } from "mathjs"; 2 | 3 | import { Calculator } from "@networks/types"; 4 | 5 | import { 6 | NeuronConfiguration, 7 | NeuronInterface, 8 | SynapseInterface, 9 | } from "./types"; 10 | 11 | const mathjs = create(all); 12 | mathjs.config({ 13 | number: "number", 14 | }); 15 | 16 | class Neuron implements NeuronInterface { 17 | private configuration: NeuronConfiguration; 18 | 19 | private calculator: Calculator; 20 | 21 | private _delta = 0; 22 | 23 | private _expectedOutput = 0; 24 | 25 | private _fixed = false; 26 | 27 | private _incomingConnections = [] as SynapseInterface[]; 28 | 29 | private _inputSum = 0; 30 | 31 | private _inputs: number[] = []; 32 | 33 | private _outgoingConnections = [] as SynapseInterface[]; 34 | 35 | private _output = 0; 36 | 37 | private _outputError = 0; 38 | 39 | private _previousExpectedOutput = 0; 40 | 41 | private _previousIncomingConnections = [] as SynapseInterface[]; 42 | 43 | private _previousInputSum = 0; 44 | 45 | private _previousInputs: number[] = []; 46 | 47 | private _previousOutgoingConnections = [] as SynapseInterface[]; 48 | 49 | private _previousOutput = 0; 50 | 51 | private _previousOutputError = 0; 52 | 53 | private _proxy = false; 54 | 55 | private _transferFunction = (value: number) => { 56 | return this.calculator.evaluate("1 / (1 + e^-value)", { value }); 57 | }; 58 | 59 | private checkConfiguration() { 60 | return true; 61 | } 62 | 63 | private transformConfiguration() { 64 | return this.configuration; 65 | } 66 | 67 | constructor(calculator: Calculator, configuration: NeuronConfiguration) { 68 | this.calculator = calculator; 69 | 70 | this.configuration = configuration; 71 | 72 | if (!this.checkConfiguration()) { 73 | throw "Invalid Neuron Module Configuration"; 74 | } 75 | this.configuration = this.transformConfiguration(); 76 | } 77 | 78 | addIncomingConnection(value: SynapseInterface) { 79 | this._incomingConnections.push(value); 80 | } 81 | 82 | addOutgoingConnection(value: SynapseInterface) { 83 | this._outgoingConnections.push(value); 84 | } 85 | 86 | addPreviousIncomingConnection(value: SynapseInterface) { 87 | this._previousIncomingConnections.push(value); 88 | } 89 | 90 | addPreviousOutgoingConnection(value: SynapseInterface) { 91 | this._previousOutgoingConnections.push(value); 92 | } 93 | 94 | set delta(value) { 95 | this._delta = value; 96 | } 97 | 98 | get delta() { 99 | return this._delta; 100 | } 101 | 102 | set expectedOutput(value) { 103 | this._expectedOutput = value; 104 | } 105 | 106 | get expectedOutput() { 107 | return this._expectedOutput; 108 | } 109 | 110 | set fixed(value) { 111 | this._fixed = value; 112 | } 113 | 114 | get fixed() { 115 | return this._fixed; 116 | } 117 | 118 | set incomingConnections(value) { 119 | this._incomingConnections = value; 120 | } 121 | 122 | get incomingConnections() { 123 | return this._incomingConnections; 124 | } 125 | 126 | set inputSum(value) { 127 | this._inputSum = value; 128 | } 129 | 130 | get inputSum() { 131 | return this._inputSum; 132 | } 133 | 134 | set inputs(value) { 135 | this._inputs = value; 136 | } 137 | 138 | get inputs() { 139 | return this._inputs; 140 | } 141 | 142 | set outgoingConnections(value) { 143 | this._outgoingConnections = value; 144 | } 145 | 146 | get outgoingConnections() { 147 | return this._outgoingConnections; 148 | } 149 | 150 | set output(value) { 151 | this._output = value; 152 | } 153 | 154 | get output() { 155 | return this._output; 156 | } 157 | 158 | set outputError(value) { 159 | this._outputError = value; 160 | } 161 | 162 | get outputError() { 163 | return this._outputError; 164 | } 165 | 166 | set previousExpectedOutput(value) { 167 | this._previousExpectedOutput = value; 168 | } 169 | 170 | get previousExpectedOutput() { 171 | return this._previousExpectedOutput; 172 | } 173 | 174 | set previousIncomingConnections(value) { 175 | this._previousIncomingConnections = value; 176 | } 177 | 178 | get previousIncomingConnections() { 179 | return this._previousIncomingConnections; 180 | } 181 | 182 | set previousInputSum(value) { 183 | this._previousInputSum = value; 184 | } 185 | 186 | get previousInputSum() { 187 | return this._previousInputSum; 188 | } 189 | 190 | set previousInputs(value) { 191 | this._previousInputs = value; 192 | } 193 | 194 | get previousInputs() { 195 | return this._previousInputs; 196 | } 197 | 198 | set previousOutgoingConnections(value) { 199 | this._previousOutgoingConnections = value; 200 | } 201 | 202 | get previousOutgoingConnections() { 203 | return this._previousOutgoingConnections; 204 | } 205 | 206 | set previousOutput(value) { 207 | this._previousOutput = value; 208 | } 209 | 210 | get previousOutput() { 211 | return this._previousOutput; 212 | } 213 | 214 | set previousOutputError(value) { 215 | this._previousOutputError = value; 216 | } 217 | 218 | get previousOutputError() { 219 | return this._previousOutputError; 220 | } 221 | 222 | set proxy(value) { 223 | this._proxy = value; 224 | } 225 | 226 | get proxy() { 227 | return this._proxy; 228 | } 229 | 230 | set transferFunction(value) { 231 | this._transferFunction = value; 232 | } 233 | 234 | get transferFunction() { 235 | return this._transferFunction; 236 | } 237 | } 238 | 239 | export { Neuron }; 240 | -------------------------------------------------------------------------------- /library/README.md: -------------------------------------------------------------------------------- 1 | # DN2A Library # 2 | 3 | [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/antoniodeluca/dn2a/main/LICENSE) 4 | 5 | ## About ## 6 | 7 | A set of JavaScript modules around neural networks. 8 | 9 | The main goal is about easily design, train and query a graph of neural networks. 10 | 11 | The side goals are to simplify integration, to speed up execution, to allow clustering and to support genetic techniques. 12 | 13 | ## Installation ## 14 | 15 | To install the library through NPM: 16 | 17 | `npm install dn2a` 18 | 19 | ## Modules ## 20 | 21 | ### Network ### 22 | 23 | Module, available in different variations, able to use neurons and synapses to implement configurable and autonomous neural networks. 24 | 25 | #### Available Network Types #### 26 | 27 | 1. **alpha**: standard feed forward neural network with error back propagation controlled by layer dimensions, learning mode, learning rate, momentum rate, maximum allowed error and maximum number of epochs. 28 | 29 | ### Cerebrum ### 30 | 31 | Module for the management of multiple neural networks in terms of configuration, coordination, training, querying and parallelization. 32 | 33 | ### Brain ### 34 | 35 | Module for the management of data normalization, intercommunication with other instances or external software as well as monitoring of the whole session. 36 | 37 | ## Examples ## 38 | 39 | ### Training and Querying a Single Alpha Network with default parametrization ### 40 | 41 | ```typescript 42 | import { NetworkAlpha } from "dn2a"; 43 | 44 | const neuralNetwork = new NetworkAlpha(); 45 | 46 | const trainingPatterns = [ 47 | { 48 | input: [0, 0], 49 | output: [0] 50 | }, 51 | { 52 | input: [0, 1], 53 | output: [1] 54 | }, 55 | { 56 | input: [1, 0], 57 | output: [1] 58 | }, 59 | { 60 | input: [1, 1], 61 | output: [0] 62 | } 63 | ]; 64 | 65 | // Training 66 | neuralNetwork.train(trainingPatterns); 67 | 68 | const queryingPatterns = [ 69 | [0, 0], 70 | [0, 1], 71 | [1, 0], 72 | [1, 1] 73 | ]; 74 | 75 | // Querying 76 | neuralNetwork.query(queryingPatterns, (queryingStatus: any) => { 77 | queryingPatterns.forEach((queryingPattern, queryingPatternIndex) => { 78 | console.log(`[${queryingPatterns[queryingPatternIndex].join(", ")}] => [${queryingStatus.outputPatterns[queryingPatternIndex].join (", ")}]`); 79 | }); 80 | }); 81 | ``` 82 | 83 | ### Training and Querying a Single Alpha Network with custom parametrization ### 84 | 85 | ```typescript 86 | import { NetworkAlpha, NetworkAlphaNeuronFactory, NetworkAlphaSynapseFactory } from "dn2a"; 87 | 88 | const neuralNetwork = new NetworkAlpha({ 89 | layerDimensions: [2, 4, 4, 1], 90 | learningMode: "continuous", 91 | learningRate: 0.3, 92 | momentumRate: 0.7, 93 | maximumError: 0.005, 94 | maximumEpoch: 20000, 95 | dataRepository: { neuronLayers: [] }, 96 | neuron: { 97 | generator: NetworkAlphaNeuronFactory.getInstance 98 | }, 99 | synapse: { 100 | generator: NetworkAlphaSynapseFactory.getInstance 101 | } 102 | }); 103 | 104 | const trainingPatterns = [ 105 | { 106 | input: [0, 0], 107 | output: [0] 108 | }, 109 | { 110 | input: [0, 1], 111 | output: [1] 112 | }, 113 | { 114 | input: [1, 0], 115 | output: [1] 116 | }, 117 | { 118 | input: [1, 1], 119 | output: [0] 120 | } 121 | ]; 122 | 123 | // Training 124 | neuralNetwork.train(trainingPatterns); 125 | 126 | const queryingPatterns = [ 127 | [0, 0], 128 | [0, 1], 129 | [1, 0], 130 | [1, 1] 131 | ]; 132 | 133 | // Querying 134 | neuralNetwork.query(queryingPatterns, (queryingStatus: any) => { 135 | queryingPatterns.forEach((queryingPattern, queryingPatternIndex) => { 136 | console.log(`[${queryingPatterns[queryingPatternIndex].join(", ")}] => [${queryingStatus.outputPatterns[queryingPatternIndex].join(", ")}]`); 137 | }); 138 | }); 139 | ``` 140 | 141 | ### Training and Querying a Single Alpha Network with evolution feedback ### 142 | 143 | ```typescript 144 | import { NetworkAlpha } from "dn2a"; 145 | 146 | const neuralNetwork = new NetworkAlpha(); 147 | 148 | const trainingPatterns = [ 149 | { 150 | input: [0, 0], 151 | output: [0] 152 | }, 153 | { 154 | input: [0, 1], 155 | output: [1] 156 | }, 157 | { 158 | input: [1, 0], 159 | output: [1] 160 | }, 161 | { 162 | input: [1, 1], 163 | output: [0] 164 | } 165 | ]; 166 | 167 | // Training 168 | neuralNetwork.train( 169 | trainingPatterns, 170 | (trainingStatus: any) => { 171 | console.log(`Epoch: ${trainingStatus.elapsedEpochCounter}`); 172 | } 173 | ); 174 | 175 | const queryingPatterns = [ 176 | [0, 0], 177 | [0, 1], 178 | [1, 0], 179 | [1, 1] 180 | ]; 181 | 182 | // Querying 183 | neuralNetwork.query( 184 | queryingPatterns, 185 | (queryingStatus: any) => { 186 | queryingPatterns.forEach((queryingPattern, queryingPatternIndex) => { 187 | console.log(`[${queryingPatterns[queryingPatternIndex].join(", ")}] => [${queryingStatus.outputPatterns[queryingPatternIndex].join(", ")}]`); 188 | }); 189 | } 190 | ); 191 | ``` 192 | 193 | ### Training and Querying a Single Alpha Network through the Cerebrum ### 194 | 195 | ```typescript 196 | import { Cerebrum, CerebrumConfiguration, NetworkAlphaFactory, NetworkAlphaNeuronFactory, NetworkAlphaSynapseFactory } from "dn2a"; 197 | 198 | const cerebrum = new Cerebrum({ 199 | minds: [ 200 | { 201 | name: "firstNeuralNetwork", 202 | network: { 203 | generator: NetworkAlphaFactory.getInstance, 204 | configuration: { 205 | layerDimensions: [2, 4, 1], 206 | learningMode: "continuous", 207 | learningRate: 0.3, 208 | momentumRate: 0.7, 209 | maximumError: 0.005, 210 | maximumEpoch: 1000, 211 | dataRepository: {}, 212 | neuron: { 213 | generator: NetworkAlphaNeuronFactory.getInstance 214 | }, 215 | synapse: { 216 | generator: NetworkAlphaSynapseFactory.getInstance 217 | } 218 | } 219 | }, 220 | inputsFrom: [ 221 | "cerebrum" 222 | ] 223 | } 224 | ], 225 | outputsFrom: [ 226 | "firstNeuralNetwork" 227 | ] 228 | } as CerebrumConfiguration); 229 | 230 | const trainingPatterns = [ 231 | { 232 | input: [0, 0], 233 | output: [0] 234 | }, 235 | { 236 | input: [0, 1], 237 | output: [1] 238 | }, 239 | { 240 | input: [1, 0], 241 | output: [1] 242 | }, 243 | { 244 | input: [1, 1], 245 | output: [0] 246 | } 247 | ]; 248 | 249 | // Training 250 | cerebrum.trainMind( 251 | trainingPatterns, 252 | (trainingStatus: any) => { 253 | console.log(`Epoch: ${trainingStatus.elapsedEpochCounter}`); 254 | }, 255 | (trainingStatus: any) => { 256 | console.log(`Iteration: ${trainingStatus.elapsedIterationCounter}`); 257 | }, 258 | "firstNeuralNetwork" 259 | ); 260 | 261 | const queryingPatterns = [ 262 | [0, 0], 263 | [0, 1], 264 | [1, 0], 265 | [1, 1] 266 | ]; 267 | 268 | // Querying 269 | cerebrum.queryMind( 270 | queryingPatterns, 271 | (queryingStatus: any) => { 272 | queryingPatterns.forEach((queryingPattern, queryingPatternIndex) => { 273 | console.log(`[${queryingPatterns[queryingPatternIndex].join(", ")}] => [${queryingStatus.outputPatterns[queryingPatternIndex].join(", ")}]`); 274 | }); 275 | }, 276 | (queryingStatus: any) => { 277 | console.log(`Iteration: ${queryingStatus.elapsedIterationCounter}`); 278 | }, 279 | "firstNeuralNetwork" 280 | ); 281 | ``` 282 | 283 | ## Creator ## 284 | 285 | [Antonio De Luca](http://www.antoniodeluca.info) 286 | 287 | ---------- 288 | 289 | ## License ## 290 | 291 | MIT 292 | -------------------------------------------------------------------------------- /examples/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "e", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "resolveJsonModule": true, /* Enable importing .json files. */ 39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 40 | 41 | /* JavaScript Support */ 42 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 43 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 45 | 46 | /* Emit */ 47 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 48 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 50 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 51 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 52 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 53 | // "removeComments": true, /* Disable emitting comments. */ 54 | // "noEmit": true, /* Disable emitting files from a compilation. */ 55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 63 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 64 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 67 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 70 | 71 | /* Interop Constraints */ 72 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 73 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 74 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 76 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 77 | 78 | /* Type Checking */ 79 | "strict": true, /* Enable all strict type-checking options. */ 80 | // "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 81 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 82 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 83 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 85 | // "noImplicitThis": false, /* Enable error reporting when 'this' is given the type 'any'. */ 86 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 88 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 89 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 91 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 93 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 98 | 99 | /* Completeness */ 100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /library/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | "paths": { 33 | "@assets/*": ["assets/*"], 34 | "@core/*": ["assets/core/*"], 35 | "@networks/*": ["assets/core/networks/*"], 36 | "@infrastructure/*": ["assets/infrastructure/*"], 37 | "@tests/*": ["tests/*"] 38 | }, /* Specify a set of entries that re-map imports to additional lookup locations. */ 39 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 40 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 41 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 42 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 43 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 44 | // "resolveJsonModule": true, /* Enable importing .json files. */ 45 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 46 | 47 | /* JavaScript Support */ 48 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 49 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 50 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 51 | 52 | /* Emit */ 53 | "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 54 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 55 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 56 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 67 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 68 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 69 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 70 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 71 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 72 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 73 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 74 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 75 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 76 | 77 | /* Interop Constraints */ 78 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": true, /* Enable all strict type-checking options. */ 86 | "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | "noImplicitThis": false, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /workspace/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | "jsx": "react", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | "paths": { 33 | "@assets/*": ["assets/*"], 34 | "@client/*": ["assets/client/*"], 35 | "@server/*": ["assets/server/*"], 36 | "@client-core/*": ["assets/client/core/*"], 37 | "@client-infrastructure/*": ["assets/client/infrastructure/*"], 38 | "@server-core/*": ["assets/server/core/*"], 39 | "@server-infrastructure/*": ["assets/server/infrastructure/*"], 40 | "@tests/*": ["tests/*"] 41 | }, /* Specify a set of entries that re-map imports to additional lookup locations. */ 42 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 43 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 44 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 45 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 46 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 47 | // "resolveJsonModule": true, /* Enable importing .json files. */ 48 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 49 | 50 | /* JavaScript Support */ 51 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 52 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 53 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 54 | 55 | /* Emit */ 56 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 57 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 58 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 59 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 60 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 61 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 62 | // "removeComments": true, /* Disable emitting comments. */ 63 | // "noEmit": true, /* Disable emitting files from a compilation. */ 64 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 65 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 66 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 67 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 68 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 69 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 70 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 71 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 72 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 73 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 74 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 75 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 76 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 77 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 78 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 79 | 80 | /* Interop Constraints */ 81 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 82 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 83 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 84 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 85 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 86 | 87 | /* Type Checking */ 88 | "strict": true, /* Enable all strict type-checking options. */ 89 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 90 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 91 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 92 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 93 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 94 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 95 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 96 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 97 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 98 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 99 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 100 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 101 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 102 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 103 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 104 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 105 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 106 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 107 | 108 | /* Completeness */ 109 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 110 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /library/assets/core/networks/alpha/Network.ts: -------------------------------------------------------------------------------- 1 | import { all, create } from "mathjs"; 2 | 3 | import { QueryingInputPatterns, TrainingPatterns } from "@core/types"; 4 | 5 | import { 6 | Calculator, 7 | QueryingEpochCallback, 8 | QueryingIterationCallback, 9 | TrainingEpochCallback, 10 | TrainingIterationCallback, 11 | } from "@networks/types"; 12 | 13 | import { NeuronFactory } from "./NeuronFactory"; 14 | import { SynapseFactory } from "./SynapseFactory"; 15 | import { DataRepository, NetworkConfiguration } from "./types"; 16 | import { NeuronInterface, SynapseInterface } from "./types"; 17 | 18 | const mathjs = create(all); 19 | mathjs.config({ 20 | number: "number", 21 | }); 22 | 23 | class Network { 24 | private configuration: NetworkConfiguration; 25 | 26 | private calculator: Calculator; 27 | 28 | private _dataRepository: DataRepository; 29 | 30 | private neuronGenerator: NeuronFactory; 31 | 32 | private synapseGenerator: SynapseFactory; 33 | 34 | private checkConfiguration() { 35 | return true; 36 | } 37 | 38 | private transformConfiguration() { 39 | return this.configuration; 40 | } 41 | 42 | private generateNeurons() { 43 | const neuronLayers = [] as NeuronInterface[][]; 44 | this.configuration.layerDimensions.forEach((layerDimension) => { 45 | const layerNeurons = [] as NeuronInterface[]; 46 | const neuronScope = 47 | neuronLayers.length === 0 48 | ? "input" 49 | : neuronLayers.length < 50 | this.configuration.layerDimensions.length - 1 51 | ? "hidden" 52 | : "output"; 53 | [...Array(layerDimension)].forEach(() => { 54 | layerNeurons.push(this.generateNeuron(neuronScope)); 55 | }); 56 | if (neuronScope === "input" || neuronScope === "hidden") { 57 | layerNeurons.push(this.generateNeuron("bias")); 58 | } 59 | neuronLayers.push(layerNeurons); 60 | }); 61 | this._dataRepository.neuronLayers = neuronLayers; 62 | } 63 | 64 | private generateNeuron(scope: string) { 65 | const neuron = this.neuronGenerator.getInstance(); 66 | const proxy = scope === "input" ? true : false; 67 | const fixed = scope === "bias" ? true : false; 68 | const output = fixed ? 1 : 0; 69 | neuron.proxy = proxy; 70 | neuron.fixed = fixed; 71 | neuron.output = output; 72 | return neuron; 73 | } 74 | 75 | private generateSynapses() { 76 | let previousLayerNeurons = [] as NeuronInterface[]; 77 | this._dataRepository.neuronLayers.forEach( 78 | (neuronLayer: NeuronInterface[], neuronLayerIndex: number) => { 79 | const layerNeurons = neuronLayer; 80 | if (neuronLayerIndex > 0) { 81 | layerNeurons.forEach((layerNeuron) => { 82 | if (!layerNeuron.fixed) { 83 | previousLayerNeurons.forEach( 84 | (previousLayerNeuron) => { 85 | const synapse = this.generateSynapse(); 86 | synapse.incomingConnection = 87 | previousLayerNeuron; 88 | synapse.outgoingConnection = layerNeuron; 89 | previousLayerNeuron.addOutgoingConnection( 90 | synapse 91 | ); 92 | layerNeuron.addIncomingConnection(synapse); 93 | } 94 | ); 95 | } 96 | }); 97 | } 98 | previousLayerNeurons = layerNeurons; 99 | } 100 | ); 101 | } 102 | 103 | private generateSynapse() { 104 | const synapse = this.synapseGenerator.getInstance(); 105 | return synapse; 106 | } 107 | 108 | private setInputPattern(inputPattern: number[]) { 109 | this._dataRepository.neuronLayers[0].forEach( 110 | (layerNeuron: NeuronInterface, layerNeuronIndex: number) => { 111 | if (!layerNeuron.fixed) { 112 | layerNeuron.output = inputPattern[layerNeuronIndex]; 113 | } 114 | } 115 | ); 116 | } 117 | 118 | private getInputPattern() { 119 | const inputPattern = [] as number[]; 120 | this._dataRepository.neuronLayers[0].forEach( 121 | (layerNeuron: NeuronInterface, layerNeuronIndex: number) => { 122 | inputPattern[layerNeuronIndex] = layerNeuron.output; 123 | } 124 | ); 125 | return inputPattern; 126 | } 127 | 128 | private setExpectedOutputPattern(expectedOutputPattern: number[]) { 129 | this._dataRepository.neuronLayers[ 130 | this._dataRepository.neuronLayers.length - 1 131 | ].forEach((layerNeuron: NeuronInterface, layerNeuronIndex: number) => { 132 | layerNeuron.expectedOutput = 133 | expectedOutputPattern[layerNeuronIndex]; 134 | }); 135 | } 136 | 137 | private getExpectedOutputPattern() { 138 | const expectedOutputPattern = [] as number[]; 139 | this._dataRepository.neuronLayers[ 140 | this._dataRepository.neuronLayers.length - 1 141 | ].forEach((layerNeuron: NeuronInterface, layerNeuronIndex: number) => { 142 | expectedOutputPattern[layerNeuronIndex] = 143 | layerNeuron.expectedOutput; 144 | }); 145 | return expectedOutputPattern; 146 | } 147 | 148 | private setOutputPattern(outputPattern: number[]) { 149 | this._dataRepository.neuronLayers[ 150 | this._dataRepository.neuronLayers.length - 1 151 | ].forEach((layerNeuron: NeuronInterface, layerNeuronIndex: number) => { 152 | layerNeuron.output = outputPattern[layerNeuronIndex]; 153 | }); 154 | } 155 | 156 | private getOutputPattern() { 157 | const outputPattern = [] as number[]; 158 | this._dataRepository.neuronLayers[ 159 | this._dataRepository.neuronLayers.length - 1 160 | ].forEach((layerNeuron: NeuronInterface, layerNeuronIndex: number) => { 161 | outputPattern[layerNeuronIndex] = layerNeuron.output; 162 | }); 163 | return outputPattern; 164 | } 165 | 166 | private getOutputError() { 167 | const layerNeurons = 168 | this._dataRepository.neuronLayers[ 169 | this._dataRepository.neuronLayers.length - 1 170 | ]; 171 | const numberOfNeuronsInTheLayer = layerNeurons.length; 172 | const layerNeuronOutputErrors = layerNeurons.map( 173 | (layerNeuron: NeuronInterface) => layerNeuron.outputError 174 | ); 175 | const outputError = this.calculator.evaluate( 176 | "sum(dotPow(layerNeuronOutputErrors, 2)) / numberOfNeuronsInTheLayer", 177 | { layerNeuronOutputErrors, numberOfNeuronsInTheLayer } 178 | ); 179 | 180 | return outputError; 181 | } 182 | 183 | private calculateActivations() { 184 | this._dataRepository.neuronLayers.forEach( 185 | (neuronLayer: NeuronInterface[], neuronLayerIndex: number) => { 186 | const layerNeurons = neuronLayer; 187 | if (neuronLayerIndex > 0) { 188 | layerNeurons.forEach((layerNeuron) => { 189 | if (!layerNeuron.fixed) { 190 | const layerNeuronIncomingConnectionOutputs: number[] = 191 | []; 192 | const layerNeuronIncomingConnectionWeights: number[] = 193 | []; 194 | layerNeuron.incomingConnections.map( 195 | (synapse: SynapseInterface) => { 196 | layerNeuronIncomingConnectionOutputs.push( 197 | synapse.incomingConnection.output 198 | ); 199 | layerNeuronIncomingConnectionWeights.push( 200 | synapse.weight 201 | ); 202 | } 203 | ); 204 | layerNeuron.inputSum = this.calculator.evaluate( 205 | "dot(layerNeuronIncomingConnectionOutputs, layerNeuronIncomingConnectionWeights)", 206 | { 207 | layerNeuronIncomingConnectionOutputs, 208 | layerNeuronIncomingConnectionWeights, 209 | } 210 | ); 211 | layerNeuron.output = layerNeuron.transferFunction( 212 | layerNeuron.inputSum 213 | ); 214 | const { expectedOutput, output } = layerNeuron; 215 | layerNeuron.outputError = this.calculator.evaluate( 216 | "expectedOutput - output", 217 | { expectedOutput, output } 218 | ); 219 | } 220 | }); 221 | } 222 | } 223 | ); 224 | } 225 | 226 | private calculateDeltas() { 227 | for ( 228 | let neuronLayerIndex = this._dataRepository.neuronLayers.length - 1; 229 | neuronLayerIndex >= 0; 230 | neuronLayerIndex-- 231 | ) { 232 | if (neuronLayerIndex > 0) { 233 | const layerNeurons = 234 | this._dataRepository.neuronLayers[neuronLayerIndex]; 235 | if ( 236 | neuronLayerIndex === 237 | this._dataRepository.neuronLayers.length - 1 238 | ) { 239 | layerNeurons.forEach((layerNeuron) => { 240 | layerNeuron.delta = mathjs 241 | .chain(layerNeuron.outputError) 242 | .multiply(layerNeuron.output) 243 | .multiply(mathjs.subtract(1, layerNeuron.output)) 244 | .done(); 245 | }); 246 | } else { 247 | layerNeurons.forEach((layerNeuron) => { 248 | if (!layerNeuron.fixed) { 249 | layerNeuron.delta = mathjs 250 | .chain( 251 | layerNeuron.outgoingConnections 252 | .map((synapse) => { 253 | return mathjs.multiply( 254 | synapse.weight, 255 | synapse.outgoingConnection.delta 256 | ); 257 | }) 258 | .reduce((accumulator, value) => { 259 | return mathjs.add( 260 | accumulator, 261 | value 262 | ); 263 | }, 0) 264 | ) 265 | .multiply(layerNeuron.output) 266 | .multiply( 267 | mathjs.subtract(1, layerNeuron.output) 268 | ) 269 | .done(); 270 | } 271 | }); 272 | } 273 | } 274 | } 275 | } 276 | 277 | private calculateWeights(learningRate: number, momentumRate: number) { 278 | this._dataRepository.neuronLayers.forEach( 279 | (neuronLayer, neuronLayerIndex) => { 280 | if (neuronLayerIndex > 0) { 281 | const layerNeurons = neuronLayer; 282 | layerNeurons.forEach((layerNeuron) => { 283 | if (!layerNeuron.fixed) { 284 | layerNeuron.incomingConnections.forEach( 285 | (synapse) => { 286 | synapse.previousWeightChange = 287 | synapse.weightChange; 288 | synapse.weightChange = mathjs.add( 289 | mathjs.multiply( 290 | learningRate, 291 | mathjs.multiply( 292 | layerNeuron.delta, 293 | synapse.incomingConnection 294 | .output 295 | ) 296 | ), 297 | mathjs.multiply( 298 | momentumRate, 299 | synapse.previousWeightChange 300 | ) 301 | ); 302 | synapse.previousWeight = synapse.weight; 303 | synapse.weight = mathjs.add( 304 | synapse.weight, 305 | synapse.weightChange 306 | ); 307 | } 308 | ); 309 | } 310 | }); 311 | } 312 | } 313 | ); 314 | } 315 | 316 | constructor(calculator: Calculator, configuration: NetworkConfiguration) { 317 | this.calculator = calculator; 318 | 319 | this.configuration = configuration; 320 | 321 | if (!this.checkConfiguration()) { 322 | throw "Invalid Alpha Network Module Configuration"; 323 | } 324 | this.configuration = this.transformConfiguration(); 325 | 326 | this._dataRepository = this.configuration.dataRepository; 327 | 328 | this.neuronGenerator = this.configuration.neuron.generator; 329 | 330 | this.synapseGenerator = this.configuration.synapse.generator; 331 | 332 | this.generateNeurons(); 333 | this.generateSynapses(); 334 | } 335 | 336 | set dataRepository(value) { 337 | this._dataRepository = value; 338 | } 339 | 340 | get dataRepository() { 341 | return this._dataRepository; 342 | } 343 | 344 | public train( 345 | trainingPatterns: TrainingPatterns, 346 | epochCallback?: TrainingEpochCallback, 347 | iterationCallback?: TrainingIterationCallback 348 | ) { 349 | let trainingStatus = { 350 | outputErrors: [] as number[], 351 | interruptionRequest: false, 352 | elapsedEpochCounter: 0, 353 | elapsedIterationCounter: 0, 354 | elapsedIterationPattern: { 355 | input: [] as number[], 356 | target: [] as number[], 357 | output: [] as number[], 358 | error: 0, 359 | }, 360 | }; 361 | do { 362 | trainingStatus.outputErrors = []; 363 | trainingStatus.interruptionRequest = true; 364 | trainingStatus.elapsedIterationCounter = 0; 365 | trainingStatus = trainingPatterns.reduce( 366 | (trainingStatus, trainingPattern) => { 367 | this.setInputPattern(trainingPattern.input); 368 | this.setExpectedOutputPattern(trainingPattern.output); 369 | this.calculateActivations(); 370 | this.calculateDeltas(); 371 | this.calculateWeights( 372 | this.configuration.learningRate, 373 | this.configuration.momentumRate 374 | ); 375 | const outputError = this.getOutputError(); 376 | trainingStatus.outputErrors.push(outputError); 377 | trainingStatus.interruptionRequest = Boolean( 378 | trainingStatus.interruptionRequest && 379 | mathjs.smallerEq( 380 | outputError, 381 | this.configuration.maximumError 382 | ) 383 | ); 384 | trainingStatus.elapsedIterationCounter++; 385 | trainingStatus.elapsedIterationPattern.input = 386 | trainingPattern.input; 387 | trainingStatus.elapsedIterationPattern.target = 388 | this.getExpectedOutputPattern(); 389 | trainingStatus.elapsedIterationPattern.output = 390 | this.getOutputPattern(); 391 | trainingStatus.elapsedIterationPattern.error = outputError; 392 | if (iterationCallback) { 393 | iterationCallback(trainingStatus); 394 | } 395 | return trainingStatus; 396 | }, 397 | trainingStatus 398 | ); 399 | trainingStatus.elapsedEpochCounter++; 400 | if (epochCallback) { 401 | epochCallback(trainingStatus); 402 | } 403 | } while ( 404 | this.configuration.learningMode === "continuous" && 405 | !trainingStatus.interruptionRequest && 406 | trainingStatus.elapsedEpochCounter < this.configuration.maximumEpoch 407 | ); 408 | } 409 | 410 | public query( 411 | inputPatterns: QueryingInputPatterns, 412 | epochCallback?: QueryingEpochCallback, 413 | iterationCallback?: QueryingIterationCallback 414 | ) { 415 | const queryingStatus = { 416 | outputPatterns: [] as number[][], 417 | elapsedIterationCounter: 0, 418 | elapsedIterationPattern: { 419 | input: [] as number[], 420 | output: [] as number[], 421 | }, 422 | }; 423 | inputPatterns.forEach((inputPattern) => { 424 | this.setInputPattern(inputPattern); 425 | this.calculateActivations(); 426 | const outputPattern = this.getOutputPattern(); 427 | queryingStatus.outputPatterns.push(outputPattern); 428 | queryingStatus.elapsedIterationCounter++; 429 | queryingStatus.elapsedIterationPattern.input = inputPattern; 430 | queryingStatus.elapsedIterationPattern.output = outputPattern; 431 | if (iterationCallback) { 432 | iterationCallback(queryingStatus); 433 | } 434 | }); 435 | if (epochCallback) { 436 | epochCallback(queryingStatus); 437 | } 438 | } 439 | } 440 | 441 | export { Network }; 442 | --------------------------------------------------------------------------------