SingularityEdge commited on
Commit
2ddbf65
·
verified ·
1 Parent(s): 5b3c5de

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ README.pdf filter=lfs diff=lfs merge=lfs -text
37
+ src/networks_graphs/Con100_Cleft50/graph.graphml filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,71 @@
1
  ---
2
  license: agpl-3.0
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: agpl-3.0
3
+ tags:
4
+ - reservoir-computing
5
+ - echo-state-networks
6
+ - connectomics
7
+ - drone-control
8
+ - robotics
9
+ - pybullet
10
+ - neuroscience
11
+ metrics:
12
+ - rmse
13
  ---
14
+
15
+ # Fly Connectome Echo State Network for Drone Control
16
+
17
+ This repository contains research and simulation code that utilizes biological neural connectivity data (the connectome of the *Drosophila melanogaster* fruit fly) as the reservoir inside an **Echo State Network (ESN)** to perform autonomous drone flight control.
18
+
19
+ ## Project Overview
20
+
21
+ * **Biological Reservoir**: The network reservoir is built from the synaptic connectivity graph of the fly brain. We scale the spectral radius of the graph below `1.0` to guarantee the Echo State Property and stabilize neural dynamics.
22
+ * **Drone Control Task**: The network is trained using Ridge Regression to output 4D control signals (target velocities: $v_x$, $v_y$, $v_z$, and yaw rate) from a 12D drone state vector.
23
+ * **Simulation Environment**: Real-time evaluation is conducted using `gym-pybullet-drones`, a physics engine simulating ground effect, aerodynamic drag, and rotor downwash.
24
+
25
+ ## Directory Structure
26
+
27
+ ```text
28
+ flydrone-esn/
29
+
30
+ ├── README.md # English documentation (with HF YAML front matter)
31
+ ├── README.txt # Detailed Turkish documentation
32
+ ├── requirements.txt # Project dependencies
33
+
34
+ └── src/ # Code files
35
+ ├── utils.py # Core mathematics and ESN reservoir helpers
36
+ ├── database_interaction.ipynb # CAVE API client for retrieving connectome synapses
37
+ ├── drone_data_collection.py # Script to collect training trajectories in PyBullet
38
+ ├── drone_esn_training.py # Script to train Wout using Ridge Regression
39
+ ├── drone_realtime_simulation.py # Script to run the trained model in PyBullet and log video
40
+ ├── classes_by_cell_type.csv # Neuron cell classifications
41
+ └── networks_graphs/ # Connectome .graphml data files
42
+ ```
43
+
44
+ ## Setup and Quick Start
45
+
46
+ ### 1. Install Dependencies
47
+ Make sure you have python 3.10 installed, then run:
48
+ ```bash
49
+ pip install -r requirements.txt
50
+ ```
51
+
52
+ ### 2. Collect Training Data
53
+ To collect drone state-action flight datasets (circular trajectories with sinusoidal height variation) in a headless PyBullet simulator, run:
54
+ ```bash
55
+ python src/drone_data_collection.py
56
+ ```
57
+ This generates the `src/drone_dataset.npz` data file.
58
+
59
+ ### 3. Train the Model
60
+ To scale the connectome matrix and train output weights using Ridge Regression ($\beta = 10^{-6}$), run:
61
+ ```bash
62
+ python src/drone_esn_training.py
63
+ ```
64
+ This saves the trained ESN components inside `src/W_drone_components.pkl`.
65
+
66
+ ### 4. Run the Real-time Simulation
67
+ To run the ESN-controlled drone in the PyBullet simulator with a graphical interface, run:
68
+ ```bash
69
+ python src/drone_realtime_simulation.py
70
+ ```
71
+ This runs the simulation and logs third-person and first-person camera flight recordings to `drone_third_person.mp4` and `drone_first_person.mp4` in your directory.
README.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:694d8bbd3a2c0b57c5529c5ee8bcca5f9af5e8995de85726102fd0168ec6eaf9
3
+ size 83207257
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ scipy
3
+ pandas
4
+ networkx
5
+ scikit-learn
6
+ matplotlib
7
+ seaborn
8
+ pybullet
9
+ gym-pybullet-drones
10
+ caveclient
11
+ torch
src/W.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:636a1d86b4845c126da018f08407a29e8cb6be54de33af9353972b99409f986d
3
+ size 14372683
src/W_drone_components.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54d676045913356123f551a6c9611bbb8f9972dd0c0dc272039e9ba6f7b84ab7
3
+ size 46624271
src/W_in.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f528b1d2e6b9103882df1463722426f7283f27ba955d21e3a9173e6bda61b489
3
+ size 200162
src/W_out.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ef54d3e8586776abfbb6a529b0d4053f24bb402fe447c1e6a3773d3eb1a8b7c
3
+ size 200162
src/bias.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34abd868c6bddd92b077cc86cddc2c953b1f5157ca587a43cdedc992bfa12397
3
+ size 200160
src/database_interaction.ipynb ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# 0 Set up your version of cave-client "
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": null,
13
+ "metadata": {},
14
+ "outputs": [],
15
+ "source": [
16
+ "# only run this one the first time to set up the token, then save your token in a file called token.txt\n",
17
+ "\n",
18
+ "import caveclient\n",
19
+ "import pandas as pd\n",
20
+ "import seaborn as sns\n",
21
+ "from matplotlib import pyplot as plt\n",
22
+ "import numpy as np\n",
23
+ "import time\n",
24
+ "import csv\n",
25
+ "import os\n",
26
+ "\n",
27
+ "\n",
28
+ "client = caveclient.CAVEclient()\n",
29
+ "client.auth.setup_token(make_new=True)"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "execution_count": null,
35
+ "metadata": {},
36
+ "outputs": [],
37
+ "source": [
38
+ "with open('token.txt', 'r') as file:\n",
39
+ " my_token = file.read().strip()\n",
40
+ "\n",
41
+ "datastack_name = \"flywire_fafb_public\"\n",
42
+ "client = caveclient.CAVEclient(datastack_name, auth_token=my_token)\n",
43
+ "\n",
44
+ "# Print all the available versions and relative timestamps\n",
45
+ "for version in client.materialize.get_versions():\n",
46
+ " print(f\"Version {version}: {client.materialize.get_timestamp(version)}\")\n",
47
+ "\n",
48
+ "# Print all the available tables for queries\n",
49
+ "client.materialize.get_tables()\n"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "metadata": {},
55
+ "source": [
56
+ "# 1 Fetch neurons from database\n",
57
+ "## 1.1 By neuron"
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": null,
63
+ "metadata": {},
64
+ "outputs": [],
65
+ "source": [
66
+ "#this is to fetch neurons from the database\n",
67
+ "\n",
68
+ "cell_class_type_annos_df = client.materialize.query_table(\"hierarchical_neuron_annotations\", filter_in_dict={\"classification_system\": [\"cell_class\"]}) #cell type is another good one to look at\n",
69
+ "cell_class_type_annos_df\n",
70
+ "root_ids_cell_types = cell_class_type_annos_df[['pt_root_id', 'cell_type']]\n",
71
+ "root_ids_cell_types.to_csv('classes_by_cell_type.csv', index=False)\n",
72
+ "unique_cell_types = cell_class_type_annos_df['cell_type'].unique()\n",
73
+ "print(unique_cell_types)\n",
74
+ "\n",
75
+ "def read_csv_data(csv_file, cell_types=None):\n",
76
+ " # FIX: column name was 'pt_root_id' instead of 'id', which was causing ValueError\n",
77
+ " data = []\n",
78
+ " with open(csv_file, 'r') as file:\n",
79
+ " csv_reader = csv.reader(file)\n",
80
+ " header = next(csv_reader) # Skip the header row\n",
81
+ " id_index = header.index('pt_root_id')\n",
82
+ " cell_type_index = header.index('cell_type')\n",
83
+ " for row in csv_reader:\n",
84
+ " cell_id = int(row[id_index])\n",
85
+ " cell_type = row[cell_type_index]\n",
86
+ " if cell_types is None or cell_type in cell_types:\n",
87
+ " data.append((cell_id, cell_type))\n",
88
+ " return data\n",
89
+ "\n",
90
+ "csv_file = 'classes_by_cell_type.csv'\n",
91
+ "cell_types = ['CX', 'Kenyon_Cell'] # Example list of cell types\n",
92
+ "data = read_csv_data(csv_file, cell_types)\n",
93
+ "print(data)\n"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "markdown",
98
+ "metadata": {},
99
+ "source": [
100
+ "## 1.2 and by synapse"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": null,
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "# This is to search from the database synapses\n",
110
+ "\n",
111
+ "\n",
112
+ "# Fetch the list of neurons\n",
113
+ "neurons = client.materialize.query_table('proofread_neurons')\n",
114
+ "\n",
115
+ "# Extract unique neuron IDs\n",
116
+ "neuron_ids = neurons['pt_root_id'].unique()\n",
117
+ "\n",
118
+ "# Create a mapping from neuron ID to matrix index\n",
119
+ "neuron_id_to_index = {neuron_id: index for index, neuron_id in enumerate(neuron_ids)}\n",
120
+ "\n",
121
+ "if os.path.isfile('synapses.csv'):\n",
122
+ " already_logged = set(pd.read_csv('synapses.csv')['pre_pt_root_id'])\n",
123
+ "else:\n",
124
+ " already_logged = set()\n",
125
+ "\n",
126
+ "# Open the CSV file in write mode\n",
127
+ "with open('synapses.csv', 'a', newline='') as csvfile:\n",
128
+ " csv_writer = csv.writer(csvfile)\n",
129
+ " # Check if the file is empty\n",
130
+ " if csvfile.tell() == 0:\n",
131
+ " # Write the header row\n",
132
+ " csv_writer.writerow(['id', 'pre_pt_root_id', 'post_pt_root_id', 'connection_score', 'cleft_score', 'gaba', 'ach', 'glut', 'oct', 'ser', 'da', 'valid_nt', 'pre_pt_supervoxel_id', 'post_pt_supervoxel_id', 'neuropil', 'pre_pt_position', 'post_pt_position'])\n",
133
+ " \n",
134
+ " # Iterate through each neuron to fetch its synapses\n",
135
+ " for i, neuron_id in enumerate(neuron_ids):\n",
136
+ " # Check if the neuron ID is already in the first column of the CSV file\n",
137
+ " if neuron_id not in already_logged:\n",
138
+ " # Fetch the synapses for the neuron\n",
139
+ " neuron_start_time = time.time()\n",
140
+ " flag = 0\n",
141
+ " retries = 0\n",
142
+ " max_retries = 5\n",
143
+ " while flag == 0:\n",
144
+ " try:\n",
145
+ " synapses = client.materialize.query_view(\"valid_synapses_nt_np_v6\", filter_in_dict={'pre_pt_root_id': [neuron_id]})\n",
146
+ " flag = 1\n",
147
+ " except Exception as e:\n",
148
+ " # FIX: bare except was swallowing all exceptions (including KeyboardInterrupt)\n",
149
+ " # and never printing the cause. Now it logs the error and retries with a limit.\n",
150
+ " retries += 1\n",
151
+ " print(f\"Lost connection on neuron {i} ({e}), retrying ({retries}/{max_retries})...\")\n",
152
+ " if retries >= max_retries:\n",
153
+ " print(f\"Giving up on neuron {i} after {max_retries} retries.\")\n",
154
+ " break\n",
155
+ " time.sleep(10)\n",
156
+ " with open('token.txt', 'r') as file:\n",
157
+ " my_token = file.read().strip()\n",
158
+ "\n",
159
+ " datastack_name = \"flywire_fafb_public\"\n",
160
+ " client = caveclient.CAVEclient(datastack_name, auth_token=my_token)\n",
161
+ "\n",
162
+ " if flag == 0:\n",
163
+ " continue\n",
164
+ "\n",
165
+ " for _, synapse in synapses.iterrows():\n",
166
+ " list_to_write = []\n",
167
+ " for elem in ['id', 'pre_pt_root_id', 'post_pt_root_id', 'connection_score', 'cleft_score', 'gaba', 'ach', 'glut', 'oct', 'ser', 'da', 'valid_nt', 'pre_pt_supervoxel_id', 'post_pt_supervoxel_id', 'neuropil', 'pre_pt_position', 'post_pt_position']:\n",
168
+ " list_to_write += [synapse[elem]] \n",
169
+ " \n",
170
+ " # Write the synapse details to the CSV file\n",
171
+ " csv_writer.writerow(list_to_write)\n",
172
+ " \n",
173
+ " # Calculate elapsed time and estimate remaining time\n",
174
+ " elapsed_time = time.time() - neuron_start_time\n",
175
+ " print(f\"Processed neuron {i+1}/{len(neuron_ids)} in {elapsed_time:.2f} seconds\")"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "markdown",
180
+ "metadata": {},
181
+ "source": [
182
+ "## 1.3 This is just to check the presence of specific cells inside a .csv file\n"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "#this it too check stuff from a specific .csv file\n",
192
+ "import csv\n",
193
+ "\n",
194
+ "csv_file = 'classes_by_cell_type.csv'\n",
195
+ "cell_types = ['olfactory', 'visual', 'mechanosensory', 'hygrosensory', 'unknown_sensory', 'ocellar', 'gustatory', 'thermosensory'] # Example list of cell types\n",
196
+ "\n",
197
+ "data = []\n",
198
+ "with open(csv_file, 'r') as file:\n",
199
+ " csv_reader = csv.reader(file)\n",
200
+ " header = next(csv_reader) # Skip the header row\n",
201
+ " id_index = header.index('pt_root_id')\n",
202
+ " cell_type_index = header.index('cell_type')\n",
203
+ " for row in csv_reader:\n",
204
+ " cell_id = int(row[id_index])\n",
205
+ " cell_type = row[cell_type_index]\n",
206
+ " if cell_types is None or cell_type in cell_types:\n",
207
+ " data.append((cell_id, cell_type))\n",
208
+ "\n",
209
+ "data_dict = {cell_id: cell_type for cell_id, cell_type in data}\n",
210
+ "\n",
211
+ "\n",
212
+ "\n",
213
+ "print(data)\n",
214
+ "len(data)"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "markdown",
219
+ "metadata": {},
220
+ "source": [
221
+ "# 2 This creates a graph from the .csv (make sure you have the .csv in the right place). IMPORTANT: threshold_connection and threshold_cleft are your quality selection parameters"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": null,
227
+ "metadata": {},
228
+ "outputs": [],
229
+ "source": [
230
+ "\n",
231
+ "import csv\n",
232
+ "import networkx as nx\n",
233
+ "import torch\n",
234
+ "import random\n",
235
+ "import numpy as np\n",
236
+ "import pickle\n",
237
+ "import os\n",
238
+ "\n",
239
+ "threshold_connection = 100 # at the moment this is fully arbitrary and should be changed\n",
240
+ "threshold_cleft = 50\n",
241
+ "\n",
242
+ "# here is the function that will determine the sign of the neurotransmitter\n",
243
+ "\n",
244
+ "def synapse_characteristics(cell_type, neurotransmitter):\n",
245
+ " # General neurotransmitter effects for excitatory/inhibitory/modulatory\n",
246
+ " neurotransmitter_effects = {\n",
247
+ " \"gaba\": \"inhibitory\",\n",
248
+ " \"ach\": \"excitatory\",\n",
249
+ " \"glut\": \"excitatory\",\n",
250
+ " \"oct\": \"modulatory\",\n",
251
+ " \"ser\": \"modulatory\",\n",
252
+ " \"da\": \"modulatory\"\n",
253
+ " }\n",
254
+ "\n",
255
+ " # Cell type-specific effects and threshold modulation patterns\n",
256
+ " cell_type_effects = {\n",
257
+ " \"kenyon_cell\": {\"ach\": (\"excitatory\", \"lower\")},\n",
258
+ " \"alpn\": {\"glut\": (\"excitatory\", None)},\n",
259
+ " \"alln\": {\"gaba\": (\"inhibitory\", None), \"ach\": (\"mixed\", None)},\n",
260
+ " \"dan\": {\"da\": (\"modulatory\", \"lower\")},\n",
261
+ " \"mbon\": {\"da\": (\"modulatory\", \"lower\"), \"ach\": (\"excitatory\", None), \"gaba\": (\"inhibitory\", None)},\n",
262
+ " \"lo\": {\"glut\": (\"excitatory\", None), \"ach\": (\"excitatory\", None)},\n",
263
+ " \"me\": {\"glut\": (\"excitatory\", None), \"ach\": (\"excitatory\", None)},\n",
264
+ " \"visual\": {\"glut\": (\"excitatory\", None)},\n",
265
+ " \"olfactory\": {\"glut\": (\"excitatory\", None)},\n",
266
+ " \"mechanosensory\": {\"glut\": (\"excitatory\", \"lower\"), \"oct\": (\"modulatory\", \"lower\")},\n",
267
+ " \"clock\": {\"da\": (\"modulatory\", \"lower\"), \"ser\": (\"modulatory\", \"raise\")},\n",
268
+ " \"lhcent\": {\"gaba\": (\"inhibitory\", None), \"glut\": (\"excitatory\", None), \"ser\": (\"modulatory\", \"raise\")},\n",
269
+ " \"alin\": {\"gaba\": (\"inhibitory\", None)},\n",
270
+ " \"lhln\": {\"gaba\": (\"inhibitory\", None)},\n",
271
+ " \"tpn\": {\"oct\": (\"modulatory\", \"lower\")}\n",
272
+ " }\n",
273
+ "\n",
274
+ " # Standardize inputs to lowercase for matching\n",
275
+ " neurotransmitter = neurotransmitter.lower()\n",
276
+ " cell_type = cell_type.lower()\n",
277
+ "\n",
278
+ " # Check if the cell type has specific rules for the neurotransmitter\n",
279
+ " if cell_type in cell_type_effects:\n",
280
+ " cell_rules = cell_type_effects[cell_type]\n",
281
+ " if neurotransmitter in cell_rules:\n",
282
+ " effect, threshold_modulation = cell_rules[neurotransmitter]\n",
283
+ " return effect, threshold_modulation\n",
284
+ "\n",
285
+ " # Default to general neurotransmitter effects if no cell-specific rule found\n",
286
+ " effect = neurotransmitter_effects.get(neurotransmitter, \"unknown\")\n",
287
+ " threshold_modulation = None # Default to None if no specific modulation information\n",
288
+ " return effect, threshold_modulation\n",
289
+ "\n",
290
+ "# Step 0: get the class of every cell\n",
291
+ "\n",
292
+ "csv_file = 'classes_by_cell_type.csv'\n",
293
+ "cell_classes = {}\n",
294
+ "biases = {}\n",
295
+ "with open(csv_file, 'r') as file:\n",
296
+ " csv_reader = csv.reader(file)\n",
297
+ " header = next(csv_reader) # Skip the header row\n",
298
+ " id_index = header.index('pt_root_id')\n",
299
+ " cell_type_index = header.index('cell_type')\n",
300
+ " for row in csv_reader:\n",
301
+ " cell_id = row[id_index]\n",
302
+ " cell_type = row[cell_type_index]\n",
303
+ " if cell_id not in cell_classes.keys():\n",
304
+ " cell_classes.update({cell_id: cell_type})\n",
305
+ " biases.update({cell_id: 0})\n",
306
+ "\n",
307
+ "neuro_transmitters = [\"gaba\",\"ach\",\"glut\",\"oct\",\"ser\",\"da\"]\n",
308
+ "\n",
309
+ "# Step 1: Read the CSV file\n",
310
+ "# FIX: file name was 'synapses_complete.csv' but it was never created anywhere.\n",
311
+ "# Since the file written in 1.2 is 'synapses.csv', it should be used here as well.\n",
312
+ "with open('synapses.csv', 'r') as file:\n",
313
+ " print('initializing reader')\n",
314
+ " csv_reader = csv.reader(file)\n",
315
+ " print('reader done')\n",
316
+ " header = next(csv_reader) # Skip the header row\n",
317
+ "\n",
318
+ " # Step 2: Initialize a NetworkX graph\n",
319
+ " print('initializing graph')\n",
320
+ " G = nx.DiGraph()\n",
321
+ " print('graph done')\n",
322
+ "\n",
323
+ " # Step 3: Add edges to the graph\n",
324
+ " current_row = 0\n",
325
+ "\n",
326
+ " # FIX: file was already opened and header skipped; file.seek(0) + next()\n",
327
+ " # was doing the same thing redundantly. Removed.\n",
328
+ "\n",
329
+ " # Iterate through each row in the CSV file\n",
330
+ " unique_neurons = 0\n",
331
+ " for row in csv_reader:\n",
332
+ " if float(row[3]) > threshold_connection and float(row[4]) > threshold_cleft and row[1] in cell_classes.keys() and row[2] in cell_classes.keys():\n",
333
+ " source = row[1] # Assuming the source column is at index 1\n",
334
+ " target = row[2] # Assuming the target column is at index 2\n",
335
+ " weight = float(row[3]) # Assuming the weight column is at index 3\n",
336
+ " neuro_trs = neuro_transmitters[np.argmax([float(row[5]), float(row[6]), float(row[7]), float(row[8]), float(row[9]), float(row[10])])]\n",
337
+ "\n",
338
+ " if target in cell_classes.keys():\n",
339
+ " tmp_cell_class = cell_classes[target]\n",
340
+ " else:\n",
341
+ " tmp_cell_class = \"unknown\"\n",
342
+ " effect, threshold_modulation = synapse_characteristics(tmp_cell_class, neuro_trs)\n",
343
+ "\n",
344
+ " if effect == \"mixed\":\n",
345
+ " effect = random.choice([\"excitatory\", \"inhibitory\"])\n",
346
+ "\n",
347
+ " # FIX: target was already added to G as string, but the comparison checked 'int(target) not in G.nodes()'\n",
348
+ " # -> due to type mismatch the condition was always True.\n",
349
+ " is_new_node = target not in G.nodes()\n",
350
+ "\n",
351
+ " if effect == \"excitatory\":\n",
352
+ " G.add_edge(source, target, weight=weight)\n",
353
+ " elif effect == \"inhibitory\":\n",
354
+ " G.add_edge(source, target, weight=-weight)\n",
355
+ " elif effect == \"modulatory\":\n",
356
+ " if threshold_modulation == \"lower\": # there will probably be the need of modulation for these\n",
357
+ " biases[target] -= weight\n",
358
+ " elif threshold_modulation == \"raise\":\n",
359
+ " biases[target] += weight\n",
360
+ "\n",
361
+ " if effect in (\"excitatory\", \"inhibitory\") and is_new_node:\n",
362
+ " unique_neurons += 1\n",
363
+ "\n",
364
+ " # Update loading bar\n",
365
+ " current_row += 1\n",
366
+ " if current_row % 100000 == 0:\n",
367
+ " print(f\"\\rRows processed: {current_row} Unique neurons found: {unique_neurons} \", end='', flush=True)\n",
368
+ " print(\"\\nProcessing complete.\")\n",
369
+ "\n",
370
+ " directory = f\"networks_graphs/Con{threshold_connection}_Cleft{threshold_cleft}\"\n",
371
+ " # FIX: added exist_ok=True to prevent FileExistsError if the directory already exists\n",
372
+ " os.makedirs(directory, exist_ok=True)\n",
373
+ "\n",
374
+ "# Save the graph\n",
375
+ "is_directed = nx.is_directed(G)\n",
376
+ "print(f\"Is the graph directed? {is_directed}\")\n",
377
+ "nx.write_graphml(G, f\"{directory}/graph.graphml\")\n",
378
+ "# Save biases to a .pkl file\n",
379
+ "with open(f\"{directory}/biases.pkl\", 'wb') as file:\n",
380
+ " pickle.dump(biases, file)\n",
381
+ "\n",
382
+ "if False:\n",
383
+ "\n",
384
+ " #Step 4: Extract edge list\n",
385
+ " edge_index = torch.tensor([(int(u), int(v)) for u, v in G.edges]).t().contiguous()\n",
386
+ " edge_weight = torch.tensor([G[u][v]['weight'] for u, v in G.edges])\n",
387
+ "\n",
388
+ " # Step 5: Create a PyTorch sparse matrix\n",
389
+ " sparse_matrix = torch.sparse_coo_tensor(edge_index, edge_weight, (G.number_of_nodes(), G.number_of_nodes()))\n",
390
+ "\n",
391
+ " print(sparse_matrix)\n",
392
+ "\n"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "execution_count": null,
398
+ "metadata": {},
399
+ "outputs": [],
400
+ "source": [
401
+ "import networkx as nx\n",
402
+ "\n",
403
+ "# Define the directory and file path\n",
404
+ "directory = f\"networks_graphs/Con{threshold_connection}_Cleft{threshold_cleft}\"\n",
405
+ "graph_path = f\"{directory}/graph.graphml\"\n",
406
+ "\n",
407
+ "# Load the graph\n",
408
+ "G = nx.read_graphml(graph_path)\n",
409
+ "if nx.is_directed(G):\n",
410
+ " print(\"The graph is directed.\")\n",
411
+ "else:\n",
412
+ " print(\"The graph is undirected.\")\n",
413
+ "\n",
414
+ "print(f\"Graph loaded with {G.number_of_nodes()} nodes and {G.number_of_edges()} edges.\")\n",
415
+ "\n",
416
+ "# Keep only the largest connected component\n",
417
+ "largest_cc = max(nx.weakly_connected_components(G), key=len)\n",
418
+ "G = G.subgraph(largest_cc).copy()\n",
419
+ "\n",
420
+ "print(f\"Graph reduced to largest connected component with {G.number_of_nodes()} nodes and {G.number_of_edges()} edges.\")"
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "code",
425
+ "execution_count": null,
426
+ "metadata": {},
427
+ "outputs": [],
428
+ "source": [
429
+ "from scipy.sparse import csr_matrix\n",
430
+ "\n",
431
+ "# Convert the graph G to a scipy sparse matrix\n",
432
+ "sparse_matrix = nx.to_scipy_sparse_array(G, weight='weight', format='csr')\n",
433
+ "\n",
434
+ "# Compute the sparsity of the matrix\n",
435
+ "total_elements = sparse_matrix.shape[0] * sparse_matrix.shape[1]\n",
436
+ "nonzero_elements = sparse_matrix.nnz\n",
437
+ "sparsity = 1 - (nonzero_elements / total_elements)\n",
438
+ "print(f\"Sparsity of the matrix: {sparsity:.4f}\")\n",
439
+ "\n",
440
+ "# Check if the matrix is symmetrical\n",
441
+ "is_symmetric = (sparse_matrix != sparse_matrix.T).nnz == 0\n",
442
+ "print(f\"Is the matrix symmetrical? {'Yes' if is_symmetric else 'No'}\")\n",
443
+ "\n",
444
+ "# Save the sparse matrix to a pickle file\n",
445
+ "with open('W_whole_world.pkl', 'wb') as f:\n",
446
+ " pickle.dump(sparse_matrix, f)"
447
+ ]
448
+ }
449
+ ],
450
+ "metadata": {
451
+ "kernelspec": {
452
+ "display_name": "fly_connectome_2",
453
+ "language": "python",
454
+ "name": "python3"
455
+ },
456
+ "language_info": {
457
+ "codemirror_mode": {
458
+ "name": "ipython",
459
+ "version": 3
460
+ },
461
+ "file_extension": ".py",
462
+ "mimetype": "text/x-python",
463
+ "name": "python",
464
+ "nbconvert_exporter": "python",
465
+ "pygments_lexer": "ipython3",
466
+ "version": "3.10.15"
467
+ }
468
+ },
469
+ "nbformat": 4,
470
+ "nbformat_minor": 2
471
+ }
src/drone_data_collection.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+ import time
4
+
5
+ try:
6
+ from gym_pybullet_drones.envs.VelocityAviary import VelocityAviary
7
+ from gym_pybullet_drones.utils.Logger import Logger
8
+ from gym_pybullet_drones.utils.utils import sync, str2bool
9
+ except ImportError:
10
+ print("gym_pybullet_drones is not installed or available.")
11
+ print("Please make sure the environment is set up correctly.")
12
+ exit(1)
13
+
14
+ def collect_data(num_steps=8000, save_path="drone_dataset.npz"):
15
+ """
16
+ Collects flight data for ESN training.
17
+ We will fly in a circle with varying height to generate dynamic states.
18
+ Inputs: 12D state (x,y,z, r,p,y, vx,vy,vz, wx,wy,wz)
19
+ Targets: 4D velocity ref (vx_ref, vy_ref, vz_ref, yaw_rate_ref)
20
+ """
21
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
22
+ if not os.path.isabs(save_path):
23
+ save_path = os.path.join(BASE_DIR, save_path)
24
+ INIT_XYZS = np.array([[0, 0, .5]])
25
+ INIT_RPYS = np.array([[0, 0, 0]])
26
+
27
+ env = VelocityAviary(
28
+ gui=False,
29
+ record=False,
30
+ initial_xyzs=INIT_XYZS,
31
+ initial_rpys=INIT_RPYS
32
+ )
33
+
34
+ states = []
35
+ targets = []
36
+
37
+ obs, info = env.reset()
38
+ state = obs[0]
39
+
40
+ for i in range(num_steps):
41
+ # Generate some target velocities for a figure-8 or circle
42
+ t = i / 100.0
43
+ vx_ref = 0.5 * np.cos(t)
44
+ vy_ref = 0.5 * np.sin(t)
45
+ vz_ref = 0.1 * np.sin(t/2.0)
46
+ yaw_rate_ref = 0.2 * np.cos(t)
47
+
48
+ target_action = np.array([vx_ref, vy_ref, vz_ref, yaw_rate_ref])
49
+
50
+ # Save state and target
51
+ states.append(state)
52
+ targets.append(target_action)
53
+
54
+ # Step env (action is the target velocity)
55
+ obs, reward, terminated, truncated, info = env.step(np.array([target_action]))
56
+ state = obs[0]
57
+
58
+ env.close()
59
+
60
+ states = np.array(states)
61
+ targets = np.array(targets)
62
+
63
+ # Save the data
64
+ np.savez(save_path, states=states, targets=targets)
65
+ print(f"Data saved to {save_path}. Collected {len(states)} steps.")
66
+
67
+ if __name__ == "__main__":
68
+ collect_data(8000, "drone_dataset.npz")
src/drone_dataset.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3fd9e63f820321cf15bab6e5b02e38f11a9fb198af14d9d7893a17023f4e159
3
+ size 1536512
src/drone_esn_training.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pickle
3
+ import scipy.sparse
4
+ import os
5
+ from utils import simulate
6
+
7
+ def train_drone_esn(data_path="drone_dataset.npz"):
8
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
9
+ if not os.path.isabs(data_path):
10
+ data_path = os.path.join(BASE_DIR, data_path)
11
+
12
+ print("Loading data...")
13
+ if not os.path.exists(data_path):
14
+ print(f"{data_path} not found. Run drone_data_collection.py first.")
15
+ return
16
+
17
+ data = np.load(data_path)
18
+ states = data['states'] # shape (T, 12) or (T, 20)
19
+ targets = data['targets'] # shape (T, 4)
20
+
21
+ Nu = states.shape[1]
22
+ Ny = targets.shape[1]
23
+
24
+ # Let's use 80% for training and 20% for testing
25
+ split = int(0.8 * len(states))
26
+ train_u = states[:split]
27
+ train_label = targets[:split]
28
+ test_u = states[split:]
29
+ test_label = targets[split:]
30
+
31
+ print("Loading biological matrices...")
32
+ try:
33
+ with open(os.path.join(BASE_DIR, 'W.pkl'), 'rb') as f:
34
+ W = pickle.load(f)
35
+ Nx = W.shape[0]
36
+
37
+ with open(os.path.join(BASE_DIR, 'W_in.pkl'), 'rb') as f:
38
+ Win_loaded = pickle.load(f)
39
+
40
+ with open(os.path.join(BASE_DIR, 'W_out.pkl'), 'rb') as f:
41
+ Wout_loaded = pickle.load(f)
42
+
43
+ with open(os.path.join(BASE_DIR, 'bias.pkl'), 'rb') as f:
44
+ bias_loaded = pickle.load(f)
45
+
46
+ print("Creating 50K Bi-Hemispheric Brain...")
47
+ W = scipy.sparse.block_diag((W, W))
48
+ Win_loaded = np.concatenate((Win_loaded, Win_loaded))
49
+ Wout_loaded = np.vstack((Wout_loaded, Wout_loaded))
50
+ bias_loaded = np.concatenate((bias_loaded, bias_loaded))
51
+ Nx = W.shape[0] # Update Nx to 50,000
52
+
53
+ except FileNotFoundError:
54
+ print("Biological matrices (W.pkl, etc.) not found! Falling back to a standard random ESN (Nx=500)...")
55
+ Nx = 500
56
+ W = scipy.sparse.random(Nx, Nx, density=0.1, format='csr')
57
+ Win_loaded = np.random.randn(Nx)
58
+ Wout_loaded = np.ones((Nx, 1)) # Select all neurons
59
+ bias_loaded = np.random.randn(Nx, 1) * 0.1
60
+
61
+ # Scale spectral radius to 0.99 (Bypass for 50k as W.pkl is already scaled)
62
+ if Nx < 25000:
63
+ try:
64
+ radius, _ = scipy.sparse.linalg.eigs(W, k=1, which='LM', maxiter=10000, tol=1e-2)
65
+ radius = abs(np.linalg.norm(radius))
66
+ except:
67
+ radius = max(abs(np.linalg.eigvals(W.toarray())))
68
+ W = W * (0.99 / radius)
69
+
70
+ # Ensure Win_loaded and bias_loaded are 1D arrays to prevent sequence assignment error
71
+ Win_loaded = np.asarray(Win_loaded).flatten()
72
+ bias_loaded = np.asarray(bias_loaded).flatten()
73
+
74
+ # Reshape Win as done in main.ipynb
75
+ Win_loaded_reshaped = np.zeros((Nu, Nx))
76
+ for i in range(Nx):
77
+ row = np.random.choice(Nu)
78
+ Win_loaded_reshaped[row, i] = Win_loaded[i]
79
+
80
+ Win = Win_loaded_reshaped
81
+ Win = np.vstack((Win, bias_loaded.T)).transpose()
82
+
83
+ input_scaling = 0.7
84
+ Win[:, :-1] = Win[:, :-1] * input_scaling
85
+
86
+ Wout_mask = Wout_loaded[:, 0]
87
+ mask = (Wout_mask == 1)
88
+
89
+ print("Simulating reservoir on training data...")
90
+ step = 0.9 # 1 - leakage rate
91
+
92
+ # Need to simulate washout. Just use initial state (e.g. 100 steps)
93
+ wash_u = train_u[:100]
94
+ x0 = np.random.random((Nx, 1))
95
+ reservoir_wash = simulate(x0, W, Win, np.hstack((wash_u, np.ones((len(wash_u), 1)))), step)
96
+
97
+ x0 = reservoir_wash[:, -1].reshape((Nx, 1))
98
+
99
+ # Train
100
+ train_u_sim = train_u[100:]
101
+ train_label_sim = train_label[100:]
102
+ train_size = len(train_u_sim)
103
+
104
+ # High RAM limit (64GB) allows using maximum precision (Float64)
105
+ XX = np.zeros((len(np.where(mask)[0]) + 1, len(np.where(mask)[0]) + 1))
106
+ XY = np.zeros((Ny, len(np.where(mask)[0]) + 1))
107
+ Yhat = train_label_sim.T
108
+
109
+ XX, XY, reservoir = simulate(x0, W, Win, np.hstack((train_u_sim, np.ones((train_size, 1)))), step,
110
+ XX, XY, Yhat, building_matrices=True, mask=mask)
111
+
112
+ beta = 1e-6
113
+ print("Performing Ridge Regression (using np.linalg.solve in Float64)...")
114
+ # np.linalg.solve avoids explicit matrix inversion, making it faster and more stable
115
+ Wout = np.linalg.solve(XX + beta * np.identity(XX.shape[0]), XY.T).T
116
+
117
+ # Test error
118
+ X = np.vstack((np.ones((1, train_size)), reservoir.reshape((Nx, train_size))[mask, :]))
119
+ Y_train = Wout @ X
120
+ err_train = np.sqrt(np.mean((Y_train - Yhat)**2))
121
+ print(f"Training RMSE: {err_train}")
122
+
123
+ # Save the trained components
124
+ print("Saving trained network parameters to W_drone_components.pkl...")
125
+ components = {
126
+ 'W': W,
127
+ 'Win': Win,
128
+ 'Wout': Wout,
129
+ 'mask': mask,
130
+ 'alpha': step
131
+ }
132
+ components_path = os.path.join(BASE_DIR, "W_drone_components.pkl")
133
+ with open(components_path, "wb") as f:
134
+ pickle.dump(components, f)
135
+ print("Training complete!")
136
+
137
+ if __name__ == "__main__":
138
+ train_drone_esn()
src/drone_realtime_simulation.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pybullet as p
3
+ import time
4
+ import pickle
5
+ import os
6
+ from gym_pybullet_drones.envs.VelocityAviary import VelocityAviary
7
+ from gym_pybullet_drones.utils.enums import Physics
8
+ from utils import step_compute
9
+
10
+ def run_realtime_simulation():
11
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
12
+ components_path = os.path.join(BASE_DIR, "W_drone_components.pkl")
13
+ if not os.path.exists(components_path):
14
+ print(f"{components_path} not found!")
15
+ return
16
+
17
+ with open(components_path, "rb") as f:
18
+ components = pickle.load(f)
19
+ W, Win, Wout, mask, alpha, Nx = components['W'], components['Win'], components['Wout'], components['mask'], components['alpha'], components['W'].shape[0]
20
+
21
+ # Realistic physics engine features: Ground Effect, Drag, and Downwash
22
+ env = VelocityAviary(
23
+ gui=True,
24
+ initial_xyzs=np.array([[0, 0, .5]]),
25
+ initial_rpys=np.array([[0, 0, 0]]),
26
+ physics=Physics.PYB_GND_DRAG_DW
27
+ )
28
+
29
+ # Close PyBullet GUI side panels and enable shadows for realistic visuals
30
+ p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0, physicsClientId=env.CLIENT)
31
+ p.configureDebugVisualizer(p.COV_ENABLE_SHADOWS, 1, physicsClientId=env.CLIENT)
32
+
33
+ obs, info = env.reset()
34
+ state = obs[0] # VelocityAviary state is size 20
35
+ x = np.random.random((Nx, 1))
36
+
37
+ # --- VIDEO RECORDING SETTINGS ---
38
+ # 1. Third Person camera tracking the drone
39
+ log_id_tp = p.startStateLogging(p.STATE_LOGGING_VIDEO_MP4, "drone_third_person.mp4")
40
+
41
+ # 2. First Person camera (ego-view)
42
+ log_id_fp = p.startStateLogging(p.STATE_LOGGING_VIDEO_MP4, "drone_first_person.mp4")
43
+
44
+ print("Simulation starting, recording video...")
45
+
46
+ try:
47
+ for i in range(43200): # Match simulation length
48
+ # Generate the live CPG clock signal exactly as in training
49
+ clock_signal = np.sin(i * 2 * np.pi / 43200.0)
50
+
51
+ # Blind Flight: Hide global X and Y positions from the network
52
+ state[0] = 0
53
+ state[1] = 0
54
+
55
+ # Append clock signal to make the state vector length 21
56
+ state_with_clock = np.append(state, clock_signal)
57
+
58
+ x, y = step_compute(x, W, Win, Wout, state_with_clock, alpha, mask)
59
+
60
+ # Velocity references are directly generated by ESN (Autonomous flight)
61
+ obs, reward, terminated, truncated, info = env.step(np.array([y.flatten()]))
62
+ state = obs[0]
63
+
64
+ # --- SPECTATOR CAMERA (FREECAM) CONTROL ---
65
+ cam_info = p.getDebugVisualizerCamera(physicsClientId=env.CLIENT)
66
+ cam_yaw = cam_info[8]
67
+ cam_pitch = cam_info[9]
68
+ cam_dist = cam_info[10]
69
+ cam_target = list(cam_info[11])
70
+
71
+ forward = np.array(cam_info[5]) # Camera forward direction
72
+ right = np.array(cam_info[6]) # Camera right direction
73
+
74
+ # Reset Z axis for flat movement in X/Y plane
75
+ forward[2] = 0
76
+ if np.linalg.norm(forward) > 0: forward = forward / np.linalg.norm(forward)
77
+ right[2] = 0
78
+ if np.linalg.norm(right) > 0: right = right / np.linalg.norm(right)
79
+
80
+ keys = p.getKeyboardEvents()
81
+ cam_speed = 0.05
82
+ moved = False
83
+
84
+ # Arrow Keys (Forward-Backward, Left-Right based on camera direction)
85
+ if p.B3G_UP_ARROW in keys and keys[p.B3G_UP_ARROW] & p.KEY_IS_DOWN:
86
+ cam_target[0] += forward[0] * cam_speed
87
+ cam_target[1] += forward[1] * cam_speed
88
+ moved = True
89
+ if p.B3G_DOWN_ARROW in keys and keys[p.B3G_DOWN_ARROW] & p.KEY_IS_DOWN:
90
+ cam_target[0] -= forward[0] * cam_speed
91
+ cam_target[1] -= forward[1] * cam_speed
92
+ moved = True
93
+ if p.B3G_RIGHT_ARROW in keys and keys[p.B3G_RIGHT_ARROW] & p.KEY_IS_DOWN:
94
+ cam_target[0] += right[0] * cam_speed
95
+ cam_target[1] += right[1] * cam_speed
96
+ moved = True
97
+ if p.B3G_LEFT_ARROW in keys and keys[p.B3G_LEFT_ARROW] & p.KEY_IS_DOWN:
98
+ cam_target[0] -= right[0] * cam_speed
99
+ cam_target[1] -= right[1] * cam_speed
100
+ moved = True
101
+
102
+ # Move Up (Space) / Move Down (Shift)
103
+ if 32 in keys and keys[32] & p.KEY_IS_DOWN:
104
+ cam_target[2] += cam_speed
105
+ moved = True
106
+ if p.B3G_SHIFT in keys and keys[p.B3G_SHIFT] & p.KEY_IS_DOWN:
107
+ cam_target[2] -= cam_speed
108
+ moved = True
109
+
110
+ if moved:
111
+ p.resetDebugVisualizerCamera(
112
+ cameraDistance=cam_dist,
113
+ cameraYaw=cam_yaw,
114
+ cameraPitch=cam_pitch,
115
+ cameraTargetPosition=cam_target,
116
+ physicsClientId=env.CLIENT
117
+ )
118
+
119
+ time.sleep(env.CTRL_TIMESTEP)
120
+
121
+ except KeyboardInterrupt:
122
+ print("Stopped by user.")
123
+ finally:
124
+ # --- CLOSE VIDEO RECORDING ---
125
+ p.stopStateLogging(log_id_tp)
126
+ p.stopStateLogging(log_id_fp)
127
+ env.close()
128
+ print("Videos saved: drone_third_person.mp4 and drone_first_person.mp4")
129
+
130
+ if __name__ == "__main__":
131
+ run_realtime_simulation()
src/lib/bindings/utils.js ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function neighbourhoodHighlight(params) {
2
+ // console.log("in nieghbourhoodhighlight");
3
+ allNodes = nodes.get({ returnType: "Object" });
4
+ // originalNodes = JSON.parse(JSON.stringify(allNodes));
5
+ // if something is selected:
6
+ if (params.nodes.length > 0) {
7
+ highlightActive = true;
8
+ var i, j;
9
+ var selectedNode = params.nodes[0];
10
+ var degrees = 2;
11
+
12
+ // mark all nodes as hard to read.
13
+ for (let nodeId in allNodes) {
14
+ // nodeColors[nodeId] = allNodes[nodeId].color;
15
+ allNodes[nodeId].color = "rgba(200,200,200,0.5)";
16
+ if (allNodes[nodeId].hiddenLabel === undefined) {
17
+ allNodes[nodeId].hiddenLabel = allNodes[nodeId].label;
18
+ allNodes[nodeId].label = undefined;
19
+ }
20
+ }
21
+ var connectedNodes = network.getConnectedNodes(selectedNode);
22
+ var allConnectedNodes = [];
23
+
24
+ // get the second degree nodes
25
+ for (i = 1; i < degrees; i++) {
26
+ for (j = 0; j < connectedNodes.length; j++) {
27
+ allConnectedNodes = allConnectedNodes.concat(
28
+ network.getConnectedNodes(connectedNodes[j])
29
+ );
30
+ }
31
+ }
32
+
33
+ // all second degree nodes get a different color and their label back
34
+ for (i = 0; i < allConnectedNodes.length; i++) {
35
+ // allNodes[allConnectedNodes[i]].color = "pink";
36
+ allNodes[allConnectedNodes[i]].color = "rgba(150,150,150,0.75)";
37
+ if (allNodes[allConnectedNodes[i]].hiddenLabel !== undefined) {
38
+ allNodes[allConnectedNodes[i]].label =
39
+ allNodes[allConnectedNodes[i]].hiddenLabel;
40
+ allNodes[allConnectedNodes[i]].hiddenLabel = undefined;
41
+ }
42
+ }
43
+
44
+ // all first degree nodes get their own color and their label back
45
+ for (i = 0; i < connectedNodes.length; i++) {
46
+ // allNodes[connectedNodes[i]].color = undefined;
47
+ allNodes[connectedNodes[i]].color = nodeColors[connectedNodes[i]];
48
+ if (allNodes[connectedNodes[i]].hiddenLabel !== undefined) {
49
+ allNodes[connectedNodes[i]].label =
50
+ allNodes[connectedNodes[i]].hiddenLabel;
51
+ allNodes[connectedNodes[i]].hiddenLabel = undefined;
52
+ }
53
+ }
54
+
55
+ // the main node gets its own color and its label back.
56
+ // allNodes[selectedNode].color = undefined;
57
+ allNodes[selectedNode].color = nodeColors[selectedNode];
58
+ if (allNodes[selectedNode].hiddenLabel !== undefined) {
59
+ allNodes[selectedNode].label = allNodes[selectedNode].hiddenLabel;
60
+ allNodes[selectedNode].hiddenLabel = undefined;
61
+ }
62
+ } else if (highlightActive === true) {
63
+ // console.log("highlightActive was true");
64
+ // reset all nodes
65
+ for (let nodeId in allNodes) {
66
+ // allNodes[nodeId].color = "purple";
67
+ allNodes[nodeId].color = nodeColors[nodeId];
68
+ // delete allNodes[nodeId].color;
69
+ if (allNodes[nodeId].hiddenLabel !== undefined) {
70
+ allNodes[nodeId].label = allNodes[nodeId].hiddenLabel;
71
+ allNodes[nodeId].hiddenLabel = undefined;
72
+ }
73
+ }
74
+ highlightActive = false;
75
+ }
76
+
77
+ // transform the object into an array
78
+ var updateArray = [];
79
+ if (params.nodes.length > 0) {
80
+ for (let nodeId in allNodes) {
81
+ if (allNodes.hasOwnProperty(nodeId)) {
82
+ // console.log(allNodes[nodeId]);
83
+ updateArray.push(allNodes[nodeId]);
84
+ }
85
+ }
86
+ nodes.update(updateArray);
87
+ } else {
88
+ // console.log("Nothing was selected");
89
+ for (let nodeId in allNodes) {
90
+ if (allNodes.hasOwnProperty(nodeId)) {
91
+ // console.log(allNodes[nodeId]);
92
+ // allNodes[nodeId].color = {};
93
+ updateArray.push(allNodes[nodeId]);
94
+ }
95
+ }
96
+ nodes.update(updateArray);
97
+ }
98
+ }
99
+
100
+ function filterHighlight(params) {
101
+ allNodes = nodes.get({ returnType: "Object" });
102
+ // if something is selected:
103
+ if (params.nodes.length > 0) {
104
+ filterActive = true;
105
+ let selectedNodes = params.nodes;
106
+
107
+ // hiding all nodes and saving the label
108
+ for (let nodeId in allNodes) {
109
+ allNodes[nodeId].hidden = true;
110
+ if (allNodes[nodeId].savedLabel === undefined) {
111
+ allNodes[nodeId].savedLabel = allNodes[nodeId].label;
112
+ allNodes[nodeId].label = undefined;
113
+ }
114
+ }
115
+
116
+ for (let i=0; i < selectedNodes.length; i++) {
117
+ allNodes[selectedNodes[i]].hidden = false;
118
+ if (allNodes[selectedNodes[i]].savedLabel !== undefined) {
119
+ allNodes[selectedNodes[i]].label = allNodes[selectedNodes[i]].savedLabel;
120
+ allNodes[selectedNodes[i]].savedLabel = undefined;
121
+ }
122
+ }
123
+
124
+ } else if (filterActive === true) {
125
+ // reset all nodes
126
+ for (let nodeId in allNodes) {
127
+ allNodes[nodeId].hidden = false;
128
+ if (allNodes[nodeId].savedLabel !== undefined) {
129
+ allNodes[nodeId].label = allNodes[nodeId].savedLabel;
130
+ allNodes[nodeId].savedLabel = undefined;
131
+ }
132
+ }
133
+ filterActive = false;
134
+ }
135
+
136
+ // transform the object into an array
137
+ var updateArray = [];
138
+ if (params.nodes.length > 0) {
139
+ for (let nodeId in allNodes) {
140
+ if (allNodes.hasOwnProperty(nodeId)) {
141
+ updateArray.push(allNodes[nodeId]);
142
+ }
143
+ }
144
+ nodes.update(updateArray);
145
+ } else {
146
+ for (let nodeId in allNodes) {
147
+ if (allNodes.hasOwnProperty(nodeId)) {
148
+ updateArray.push(allNodes[nodeId]);
149
+ }
150
+ }
151
+ nodes.update(updateArray);
152
+ }
153
+ }
154
+
155
+ function selectNode(nodes) {
156
+ network.selectNodes(nodes);
157
+ neighbourhoodHighlight({ nodes: nodes });
158
+ return nodes;
159
+ }
160
+
161
+ function selectNodes(nodes) {
162
+ network.selectNodes(nodes);
163
+ filterHighlight({nodes: nodes});
164
+ return nodes;
165
+ }
166
+
167
+ function highlightFilter(filter) {
168
+ let selectedNodes = []
169
+ let selectedProp = filter['property']
170
+ if (filter['item'] === 'node') {
171
+ let allNodes = nodes.get({ returnType: "Object" });
172
+ for (let nodeId in allNodes) {
173
+ if (allNodes[nodeId][selectedProp] && filter['value'].includes((allNodes[nodeId][selectedProp]).toString())) {
174
+ selectedNodes.push(nodeId)
175
+ }
176
+ }
177
+ }
178
+ else if (filter['item'] === 'edge'){
179
+ let allEdges = edges.get({returnType: 'object'});
180
+ // check if the selected property exists for selected edge and select the nodes connected to the edge
181
+ for (let edge in allEdges) {
182
+ if (allEdges[edge][selectedProp] && filter['value'].includes((allEdges[edge][selectedProp]).toString())) {
183
+ selectedNodes.push(allEdges[edge]['from'])
184
+ selectedNodes.push(allEdges[edge]['to'])
185
+ }
186
+ }
187
+ }
188
+ selectNodes(selectedNodes)
189
+ }
src/lib/tom-select/tom-select.complete.min.js ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Tom Select v2.0.0-rc.4
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ */
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TomSelect=t()}(this,(function(){"use strict"
6
+ function e(e,t){e.split(/\s+/).forEach((e=>{t(e)}))}class t{constructor(){this._events={}}on(t,i){e(t,(e=>{this._events[e]=this._events[e]||[],this._events[e].push(i)}))}off(t,i){var s=arguments.length
7
+ 0!==s?e(t,(e=>{if(1===s)return delete this._events[e]
8
+ e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(i),1)})):this._events={}}trigger(t,...i){var s=this
9
+ e(t,(e=>{if(e in s._events!=!1)for(let t of s._events[e])t.apply(s,i)}))}}var i
10
+ const s="[̀-ͯ·ʾ]",n=new RegExp(s,"g")
11
+ var o
12
+ const r={"æ":"ae","ⱥ":"a","ø":"o"},l=new RegExp(Object.keys(r).join("|"),"g"),a=[[67,67],[160,160],[192,438],[452,652],[961,961],[1019,1019],[1083,1083],[1281,1289],[1984,1984],[5095,5095],[7429,7441],[7545,7549],[7680,7935],[8580,8580],[9398,9449],[11360,11391],[42792,42793],[42802,42851],[42873,42897],[42912,42922],[64256,64260],[65313,65338],[65345,65370]],c=e=>e.normalize("NFKD").replace(n,"").toLowerCase().replace(l,(function(e){return r[e]})),d=(e,t="|")=>{if(1==e.length)return e[0]
13
+ var i=1
14
+ return e.forEach((e=>{i=Math.max(i,e.length)})),1==i?"["+e.join("")+"]":"(?:"+e.join(t)+")"},p=e=>{if(1===e.length)return[[e]]
15
+ var t=[]
16
+ return p(e.substring(1)).forEach((function(i){var s=i.slice(0)
17
+ s[0]=e.charAt(0)+s[0],t.push(s),(s=i.slice(0)).unshift(e.charAt(0)),t.push(s)})),t},u=e=>{void 0===o&&(o=(()=>{var e={}
18
+ a.forEach((t=>{for(let s=t[0];s<=t[1];s++){let t=String.fromCharCode(s),n=c(t)
19
+ if(n!=t.toLowerCase()){n in e||(e[n]=[n])
20
+ var i=new RegExp(d(e[n]),"iu")
21
+ t.match(i)||e[n].push(t)}}}))
22
+ var t=Object.keys(e)
23
+ t=t.sort(((e,t)=>t.length-e.length)),i=new RegExp("("+d(t)+"[̀-ͯ·ʾ]*)","g")
24
+ var s={}
25
+ return t.sort(((e,t)=>e.length-t.length)).forEach((t=>{var i=p(t).map((t=>(t=t.map((t=>e.hasOwnProperty(t)?d(e[t]):t)),d(t,""))))
26
+ s[t]=d(i)})),s})())
27
+ return e.normalize("NFKD").toLowerCase().split(i).map((e=>{if(""==e)return""
28
+ const t=c(e)
29
+ if(o.hasOwnProperty(t))return o[t]
30
+ const i=e.normalize("NFC")
31
+ return i!=e?d([e,i]):e})).join("")},h=(e,t)=>{if(e)return e[t]},g=(e,t)=>{if(e){for(var i,s=t.split(".");(i=s.shift())&&(e=e[i]););return e}},f=(e,t,i)=>{var s,n
32
+ return e?-1===(n=(e+="").search(t.regex))?0:(s=t.string.length/e.length,0===n&&(s+=.5),s*i):0},v=e=>(e+"").replace(/([\$\(-\+\.\?\[-\^\{-\}])/g,"\\$1"),m=(e,t)=>{var i=e[t]
33
+ if("function"==typeof i)return i
34
+ i&&!Array.isArray(i)&&(e[t]=[i])},y=(e,t)=>{if(Array.isArray(e))e.forEach(t)
35
+ else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},O=(e,t)=>"number"==typeof e&&"number"==typeof t?e>t?1:e<t?-1:0:(e=c(e+"").toLowerCase())>(t=c(t+"").toLowerCase())?1:t>e?-1:0
36
+ class b{constructor(e,t){this.items=e,this.settings=t||{diacritics:!0}}tokenize(e,t,i){if(!e||!e.length)return[]
37
+ const s=[],n=e.split(/\s+/)
38
+ var o
39
+ return i&&(o=new RegExp("^("+Object.keys(i).map(v).join("|")+"):(.*)$")),n.forEach((e=>{let i,n=null,r=null
40
+ o&&(i=e.match(o))&&(n=i[1],e=i[2]),e.length>0&&(r=v(e),this.settings.diacritics&&(r=u(r)),t&&(r="\\b"+r)),s.push({string:e,regex:r?new RegExp(r,"iu"):null,field:n})})),s}getScoreFunction(e,t){var i=this.prepareSearch(e,t)
41
+ return this._getScoreFunction(i)}_getScoreFunction(e){const t=e.tokens,i=t.length
42
+ if(!i)return function(){return 0}
43
+ const s=e.options.fields,n=e.weights,o=s.length,r=e.getAttrFn
44
+ if(!o)return function(){return 1}
45
+ const l=1===o?function(e,t){const i=s[0].field
46
+ return f(r(t,i),e,n[i])}:function(e,t){var i=0
47
+ if(e.field){const s=r(t,e.field)
48
+ !e.regex&&s?i+=1/o:i+=f(s,e,1)}else y(n,((s,n)=>{i+=f(r(t,n),e,s)}))
49
+ return i/o}
50
+ return 1===i?function(e){return l(t[0],e)}:"and"===e.options.conjunction?function(e){for(var s,n=0,o=0;n<i;n++){if((s=l(t[n],e))<=0)return 0
51
+ o+=s}return o/i}:function(e){var s=0
52
+ return y(t,(t=>{s+=l(t,e)})),s/i}}getSortFunction(e,t){var i=this.prepareSearch(e,t)
53
+ return this._getSortFunction(i)}_getSortFunction(e){var t,i,s
54
+ const n=this,o=e.options,r=!e.query&&o.sort_empty?o.sort_empty:o.sort,l=[],a=[]
55
+ if("function"==typeof r)return r.bind(this)
56
+ const c=function(t,i){return"$score"===t?i.score:e.getAttrFn(n.items[i.id],t)}
57
+ if(r)for(t=0,i=r.length;t<i;t++)(e.query||"$score"!==r[t].field)&&l.push(r[t])
58
+ if(e.query){for(s=!0,t=0,i=l.length;t<i;t++)if("$score"===l[t].field){s=!1
59
+ break}s&&l.unshift({field:"$score",direction:"desc"})}else for(t=0,i=l.length;t<i;t++)if("$score"===l[t].field){l.splice(t,1)
60
+ break}for(t=0,i=l.length;t<i;t++)a.push("desc"===l[t].direction?-1:1)
61
+ const d=l.length
62
+ if(d){if(1===d){const e=l[0].field,t=a[0]
63
+ return function(i,s){return t*O(c(e,i),c(e,s))}}return function(e,t){var i,s,n
64
+ for(i=0;i<d;i++)if(n=l[i].field,s=a[i]*O(c(n,e),c(n,t)))return s
65
+ return 0}}return null}prepareSearch(e,t){const i={}
66
+ var s=Object.assign({},t)
67
+ if(m(s,"sort"),m(s,"sort_empty"),s.fields){m(s,"fields")
68
+ const e=[]
69
+ s.fields.forEach((t=>{"string"==typeof t&&(t={field:t,weight:1}),e.push(t),i[t.field]="weight"in t?t.weight:1})),s.fields=e}return{options:s,query:e.toLowerCase().trim(),tokens:this.tokenize(e,s.respect_word_boundaries,i),total:0,items:[],weights:i,getAttrFn:s.nesting?g:h}}search(e,t){var i,s,n=this
70
+ s=this.prepareSearch(e,t),t=s.options,e=s.query
71
+ const o=t.score||n._getScoreFunction(s)
72
+ e.length?y(n.items,((e,n)=>{i=o(e),(!1===t.filter||i>0)&&s.items.push({score:i,id:n})})):y(n.items,((e,t)=>{s.items.push({score:1,id:t})}))
73
+ const r=n._getSortFunction(s)
74
+ return r&&s.items.sort(r),s.total=s.items.length,"number"==typeof t.limit&&(s.items=s.items.slice(0,t.limit)),s}}const w=e=>{if(e.jquery)return e[0]
75
+ if(e instanceof HTMLElement)return e
76
+ if(e.indexOf("<")>-1){let t=document.createElement("div")
77
+ return t.innerHTML=e.trim(),t.firstChild}return document.querySelector(e)},_=(e,t)=>{var i=document.createEvent("HTMLEvents")
78
+ i.initEvent(t,!0,!1),e.dispatchEvent(i)},I=(e,t)=>{Object.assign(e.style,t)},C=(e,...t)=>{var i=A(t);(e=x(e)).map((e=>{i.map((t=>{e.classList.add(t)}))}))},S=(e,...t)=>{var i=A(t);(e=x(e)).map((e=>{i.map((t=>{e.classList.remove(t)}))}))},A=e=>{var t=[]
79
+ return y(e,(e=>{"string"==typeof e&&(e=e.trim().split(/[\11\12\14\15\40]/)),Array.isArray(e)&&(t=t.concat(e))})),t.filter(Boolean)},x=e=>(Array.isArray(e)||(e=[e]),e),k=(e,t,i)=>{if(!i||i.contains(e))for(;e&&e.matches;){if(e.matches(t))return e
80
+ e=e.parentNode}},F=(e,t=0)=>t>0?e[e.length-1]:e[0],L=(e,t)=>{if(!e)return-1
81
+ t=t||e.nodeName
82
+ for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++
83
+ return i},P=(e,t)=>{y(t,((t,i)=>{null==t?e.removeAttribute(i):e.setAttribute(i,""+t)}))},E=(e,t)=>{e.parentNode&&e.parentNode.replaceChild(t,e)},T=(e,t)=>{if(null===t)return
84
+ if("string"==typeof t){if(!t.length)return
85
+ t=new RegExp(t,"i")}const i=e=>3===e.nodeType?(e=>{var i=e.data.match(t)
86
+ if(i&&e.data.length>0){var s=document.createElement("span")
87
+ s.className="highlight"
88
+ var n=e.splitText(i.index)
89
+ n.splitText(i[0].length)
90
+ var o=n.cloneNode(!0)
91
+ return s.appendChild(o),E(n,s),1}return 0})(e):((e=>{if(1===e.nodeType&&e.childNodes&&!/(script|style)/i.test(e.tagName)&&("highlight"!==e.className||"SPAN"!==e.tagName))for(var t=0;t<e.childNodes.length;++t)t+=i(e.childNodes[t])})(e),0)
92
+ i(e)},V="undefined"!=typeof navigator&&/Mac/.test(navigator.userAgent)?"metaKey":"ctrlKey"
93
+ var j={options:[],optgroups:[],plugins:[],delimiter:",",splitOn:null,persist:!0,diacritics:!0,create:null,createOnBlur:!1,createFilter:null,highlight:!0,openOnFocus:!0,shouldOpen:null,maxOptions:50,maxItems:null,hideSelected:null,duplicates:!1,addPrecedence:!1,selectOnTab:!1,preload:null,allowEmptyOption:!1,loadThrottle:300,loadingClass:"loading",dataAttr:null,optgroupField:"optgroup",valueField:"value",labelField:"text",disabledField:"disabled",optgroupLabelField:"label",optgroupValueField:"value",lockOptgroupOrder:!1,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"ts-wrapper",controlClass:"ts-control",dropdownClass:"ts-dropdown",dropdownContentClass:"ts-dropdown-content",itemClass:"item",optionClass:"option",dropdownParent:null,copyClassesToDropdown:!1,placeholder:null,hidePlaceholder:null,shouldLoad:function(e){return e.length>0},render:{}}
94
+ const q=e=>null==e?null:D(e),D=e=>"boolean"==typeof e?e?"1":"0":e+"",N=e=>(e+"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),z=(e,t)=>{var i
95
+ return function(s,n){var o=this
96
+ i&&(o.loading=Math.max(o.loading-1,0),clearTimeout(i)),i=setTimeout((function(){i=null,o.loadedSearches[s]=!0,e.call(o,s,n)}),t)}},R=(e,t,i)=>{var s,n=e.trigger,o={}
97
+ for(s in e.trigger=function(){var i=arguments[0]
98
+ if(-1===t.indexOf(i))return n.apply(e,arguments)
99
+ o[i]=arguments},i.apply(e,[]),e.trigger=n,o)n.apply(e,o[s])},H=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},B=(e,t,i,s)=>{e.addEventListener(t,i,s)},K=(e,t)=>!!t&&(!!t[e]&&1===(t.altKey?1:0)+(t.ctrlKey?1:0)+(t.shiftKey?1:0)+(t.metaKey?1:0)),M=(e,t)=>{const i=e.getAttribute("id")
100
+ return i||(e.setAttribute("id",t),t)},Q=e=>e.replace(/[\\"']/g,"\\$&"),G=(e,t)=>{t&&e.append(t)}
101
+ function U(e,t){var i=Object.assign({},j,t),s=i.dataAttr,n=i.labelField,o=i.valueField,r=i.disabledField,l=i.optgroupField,a=i.optgroupLabelField,c=i.optgroupValueField,d=e.tagName.toLowerCase(),p=e.getAttribute("placeholder")||e.getAttribute("data-placeholder")
102
+ if(!p&&!i.allowEmptyOption){let t=e.querySelector('option[value=""]')
103
+ t&&(p=t.textContent)}var u,h,g,f,v,m,O={placeholder:p,options:[],optgroups:[],items:[],maxItems:null}
104
+ return"select"===d?(h=O.options,g={},f=1,v=e=>{var t=Object.assign({},e.dataset),i=s&&t[s]
105
+ return"string"==typeof i&&i.length&&(t=Object.assign(t,JSON.parse(i))),t},m=(e,t)=>{var s=q(e.value)
106
+ if(null!=s&&(s||i.allowEmptyOption)){if(g.hasOwnProperty(s)){if(t){var a=g[s][l]
107
+ a?Array.isArray(a)?a.push(t):g[s][l]=[a,t]:g[s][l]=t}}else{var c=v(e)
108
+ c[n]=c[n]||e.textContent,c[o]=c[o]||s,c[r]=c[r]||e.disabled,c[l]=c[l]||t,c.$option=e,g[s]=c,h.push(c)}e.selected&&O.items.push(s)}},O.maxItems=e.hasAttribute("multiple")?null:1,y(e.children,(e=>{var t,i,s
109
+ "optgroup"===(u=e.tagName.toLowerCase())?((s=v(t=e))[a]=s[a]||t.getAttribute("label")||"",s[c]=s[c]||f++,s[r]=s[r]||t.disabled,O.optgroups.push(s),i=s[c],y(t.children,(e=>{m(e,i)}))):"option"===u&&m(e)}))):(()=>{const t=e.getAttribute(s)
110
+ if(t)O.options=JSON.parse(t),y(O.options,(e=>{O.items.push(e[o])}))
111
+ else{var r=e.value.trim()||""
112
+ if(!i.allowEmptyOption&&!r.length)return
113
+ const t=r.split(i.delimiter)
114
+ y(t,(e=>{const t={}
115
+ t[n]=e,t[o]=e,O.options.push(t)})),O.items=t}})(),Object.assign({},j,O,t)}var W=0
116
+ class J extends(function(e){return e.plugins={},class extends e{constructor(...e){super(...e),this.plugins={names:[],settings:{},requested:{},loaded:{}}}static define(t,i){e.plugins[t]={name:t,fn:i}}initializePlugins(e){var t,i
117
+ const s=this,n=[]
118
+ if(Array.isArray(e))e.forEach((e=>{"string"==typeof e?n.push(e):(s.plugins.settings[e.name]=e.options,n.push(e.name))}))
119
+ else if(e)for(t in e)e.hasOwnProperty(t)&&(s.plugins.settings[t]=e[t],n.push(t))
120
+ for(;i=n.shift();)s.require(i)}loadPlugin(t){var i=this,s=i.plugins,n=e.plugins[t]
121
+ if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin')
122
+ s.requested[t]=!0,s.loaded[t]=n.fn.apply(i,[i.plugins.settings[t]||{}]),s.names.push(t)}require(e){var t=this,i=t.plugins
123
+ if(!t.plugins.loaded.hasOwnProperty(e)){if(i.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")')
124
+ t.loadPlugin(e)}return i.loaded[e]}}}(t)){constructor(e,t){var i
125
+ super(),this.order=0,this.isOpen=!1,this.isDisabled=!1,this.isInvalid=!1,this.isValid=!0,this.isLocked=!1,this.isFocused=!1,this.isInputHidden=!1,this.isSetup=!1,this.ignoreFocus=!1,this.hasOptions=!1,this.lastValue="",this.caretPos=0,this.loading=0,this.loadedSearches={},this.activeOption=null,this.activeItems=[],this.optgroups={},this.options={},this.userOptions={},this.items=[],W++
126
+ var s=w(e)
127
+ if(s.tomselect)throw new Error("Tom Select already initialized on this element")
128
+ s.tomselect=this,i=(window.getComputedStyle&&window.getComputedStyle(s,null)).getPropertyValue("direction")
129
+ const n=U(s,t)
130
+ this.settings=n,this.input=s,this.tabIndex=s.tabIndex||0,this.is_select_tag="select"===s.tagName.toLowerCase(),this.rtl=/rtl/i.test(i),this.inputId=M(s,"tomselect-"+W),this.isRequired=s.required,this.sifter=new b(this.options,{diacritics:n.diacritics}),n.mode=n.mode||(1===n.maxItems?"single":"multi"),"boolean"!=typeof n.hideSelected&&(n.hideSelected="multi"===n.mode),"boolean"!=typeof n.hidePlaceholder&&(n.hidePlaceholder="multi"!==n.mode)
131
+ var o=n.createFilter
132
+ "function"!=typeof o&&("string"==typeof o&&(o=new RegExp(o)),o instanceof RegExp?n.createFilter=e=>o.test(e):n.createFilter=()=>!0),this.initializePlugins(n.plugins),this.setupCallbacks(),this.setupTemplates()
133
+ const r=w("<div>"),l=w("<div>"),a=this._render("dropdown"),c=w('<div role="listbox" tabindex="-1">'),d=this.input.getAttribute("class")||"",p=n.mode
134
+ var u
135
+ if(C(r,n.wrapperClass,d,p),C(l,n.controlClass),G(r,l),C(a,n.dropdownClass,p),n.copyClassesToDropdown&&C(a,d),C(c,n.dropdownContentClass),G(a,c),w(n.dropdownParent||r).appendChild(a),n.hasOwnProperty("controlInput"))n.controlInput?(u=w(n.controlInput),this.focus_node=u):(u=w("<input/>"),this.focus_node=l)
136
+ else{u=w('<input type="text" autocomplete="off" size="1" />')
137
+ y(["autocorrect","autocapitalize","autocomplete"],(e=>{s.getAttribute(e)&&P(u,{[e]:s.getAttribute(e)})})),u.tabIndex=-1,l.appendChild(u),this.focus_node=u}this.wrapper=r,this.dropdown=a,this.dropdown_content=c,this.control=l,this.control_input=u,this.setup()}setup(){const e=this,t=e.settings,i=e.control_input,s=e.dropdown,n=e.dropdown_content,o=e.wrapper,r=e.control,l=e.input,a=e.focus_node,c={passive:!0},d=e.inputId+"-ts-dropdown"
138
+ P(n,{id:d}),P(a,{role:"combobox","aria-haspopup":"listbox","aria-expanded":"false","aria-controls":d})
139
+ const p=M(a,e.inputId+"-ts-control"),u="label[for='"+(e=>e.replace(/['"\\]/g,"\\$&"))(e.inputId)+"']",h=document.querySelector(u),g=e.focus.bind(e)
140
+ if(h){B(h,"click",g),P(h,{for:p})
141
+ const t=M(h,e.inputId+"-ts-label")
142
+ P(a,{"aria-labelledby":t}),P(n,{"aria-labelledby":t})}if(o.style.width=l.style.width,e.plugins.names.length){const t="plugin-"+e.plugins.names.join(" plugin-")
143
+ C([o,s],t)}(null===t.maxItems||t.maxItems>1)&&e.is_select_tag&&P(l,{multiple:"multiple"}),e.settings.placeholder&&P(i,{placeholder:t.placeholder}),!e.settings.splitOn&&e.settings.delimiter&&(e.settings.splitOn=new RegExp("\\s*"+v(e.settings.delimiter)+"+\\s*")),t.load&&t.loadThrottle&&(t.load=z(t.load,t.loadThrottle)),e.control_input.type=l.type,B(s,"click",(t=>{const i=k(t.target,"[data-selectable]")
144
+ i&&(e.onOptionSelect(t,i),H(t,!0))})),B(r,"click",(t=>{var s=k(t.target,"[data-ts-item]",r)
145
+ s&&e.onItemSelect(t,s)?H(t,!0):""==i.value&&(e.onClick(),H(t,!0))})),B(i,"mousedown",(e=>{""!==i.value&&e.stopPropagation()})),B(a,"keydown",(t=>e.onKeyDown(t))),B(i,"keypress",(t=>e.onKeyPress(t))),B(i,"input",(t=>e.onInput(t))),B(a,"resize",(()=>e.positionDropdown()),c),B(a,"blur",(t=>e.onBlur(t))),B(a,"focus",(t=>e.onFocus(t))),B(a,"paste",(t=>e.onPaste(t)))
146
+ const f=t=>{const i=t.composedPath()[0]
147
+ if(!o.contains(i)&&!s.contains(i))return e.isFocused&&e.blur(),void e.inputState()
148
+ H(t,!0)}
149
+ var m=()=>{e.isOpen&&e.positionDropdown()}
150
+ B(document,"mousedown",f),B(window,"scroll",m,c),B(window,"resize",m,c),this._destroy=()=>{document.removeEventListener("mousedown",f),window.removeEventListener("sroll",m),window.removeEventListener("resize",m),h&&h.removeEventListener("click",g)},this.revertSettings={innerHTML:l.innerHTML,tabIndex:l.tabIndex},l.tabIndex=-1,l.insertAdjacentElement("afterend",e.wrapper),e.sync(!1),t.items=[],delete t.optgroups,delete t.options,B(l,"invalid",(t=>{e.isValid&&(e.isValid=!1,e.isInvalid=!0,e.refreshState())})),e.updateOriginalInput(),e.refreshItems(),e.close(!1),e.inputState(),e.isSetup=!0,l.disabled?e.disable():e.enable(),e.on("change",this.onChange),C(l,"tomselected","ts-hidden-accessible"),e.trigger("initialize"),!0===t.preload&&e.preload()}setupOptions(e=[],t=[]){this.addOptions(e),y(t,(e=>{this.registerOptionGroup(e)}))}setupTemplates(){var e=this,t=e.settings.labelField,i=e.settings.optgroupLabelField,s={optgroup:e=>{let t=document.createElement("div")
151
+ return t.className="optgroup",t.appendChild(e.options),t},optgroup_header:(e,t)=>'<div class="optgroup-header">'+t(e[i])+"</div>",option:(e,i)=>"<div>"+i(e[t])+"</div>",item:(e,i)=>"<div>"+i(e[t])+"</div>",option_create:(e,t)=>'<div class="create">Add <strong>'+t(e.input)+"</strong>&hellip;</div>",no_results:()=>'<div class="no-results">No results found</div>',loading:()=>'<div class="spinner"></div>',not_loading:()=>{},dropdown:()=>"<div></div>"}
152
+ e.settings.render=Object.assign({},s,e.settings.render)}setupCallbacks(){var e,t,i={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",item_select:"onItemSelect",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur"}
153
+ for(e in i)(t=this.settings[i[e]])&&this.on(e,t)}sync(e=!0){const t=this,i=e?U(t.input,{delimiter:t.settings.delimiter}):t.settings
154
+ t.setupOptions(i.options,i.optgroups),t.setValue(i.items,!0),t.lastQuery=null}onClick(){var e=this
155
+ if(e.activeItems.length>0)return e.clearActiveItems(),void e.focus()
156
+ e.isFocused&&e.isOpen?e.blur():e.focus()}onMouseDown(){}onChange(){_(this.input,"input"),_(this.input,"change")}onPaste(e){var t=this
157
+ t.isFull()||t.isInputHidden||t.isLocked?H(e):t.settings.splitOn&&setTimeout((()=>{var e=t.inputValue()
158
+ if(e.match(t.settings.splitOn)){var i=e.trim().split(t.settings.splitOn)
159
+ y(i,(e=>{t.createItem(e)}))}}),0)}onKeyPress(e){var t=this
160
+ if(!t.isLocked){var i=String.fromCharCode(e.keyCode||e.which)
161
+ return t.settings.create&&"multi"===t.settings.mode&&i===t.settings.delimiter?(t.createItem(),void H(e)):void 0}H(e)}onKeyDown(e){var t=this
162
+ if(t.isLocked)9!==e.keyCode&&H(e)
163
+ else{switch(e.keyCode){case 65:if(K(V,e))return H(e),void t.selectAll()
164
+ break
165
+ case 27:return t.isOpen&&(H(e,!0),t.close()),void t.clearActiveItems()
166
+ case 40:if(!t.isOpen&&t.hasOptions)t.open()
167
+ else if(t.activeOption){let e=t.getAdjacent(t.activeOption,1)
168
+ e&&t.setActiveOption(e)}return void H(e)
169
+ case 38:if(t.activeOption){let e=t.getAdjacent(t.activeOption,-1)
170
+ e&&t.setActiveOption(e)}return void H(e)
171
+ case 13:return void(t.isOpen&&t.activeOption?(t.onOptionSelect(e,t.activeOption),H(e)):t.settings.create&&t.createItem()&&H(e))
172
+ case 37:return void t.advanceSelection(-1,e)
173
+ case 39:return void t.advanceSelection(1,e)
174
+ case 9:return void(t.settings.selectOnTab&&(t.isOpen&&t.activeOption&&(t.onOptionSelect(e,t.activeOption),H(e)),t.settings.create&&t.createItem()&&H(e)))
175
+ case 8:case 46:return void t.deleteSelection(e)}t.isInputHidden&&!K(V,e)&&H(e)}}onInput(e){var t=this
176
+ if(!t.isLocked){var i=t.inputValue()
177
+ t.lastValue!==i&&(t.lastValue=i,t.settings.shouldLoad.call(t,i)&&t.load(i),t.refreshOptions(),t.trigger("type",i))}}onFocus(e){var t=this,i=t.isFocused
178
+ if(t.isDisabled)return t.blur(),void H(e)
179
+ t.ignoreFocus||(t.isFocused=!0,"focus"===t.settings.preload&&t.preload(),i||t.trigger("focus"),t.activeItems.length||(t.showInput(),t.refreshOptions(!!t.settings.openOnFocus)),t.refreshState())}onBlur(e){if(!1!==document.hasFocus()){var t=this
180
+ if(t.isFocused){t.isFocused=!1,t.ignoreFocus=!1
181
+ var i=()=>{t.close(),t.setActiveItem(),t.setCaret(t.items.length),t.trigger("blur")}
182
+ t.settings.create&&t.settings.createOnBlur?t.createItem(null,!1,i):i()}}}onOptionSelect(e,t){var i,s=this
183
+ t&&(t.parentElement&&t.parentElement.matches("[data-disabled]")||(t.classList.contains("create")?s.createItem(null,!0,(()=>{s.settings.closeAfterSelect&&s.close()})):void 0!==(i=t.dataset.value)&&(s.lastQuery=null,s.addItem(i),s.settings.closeAfterSelect&&s.close(),!s.settings.hideSelected&&e.type&&/click/.test(e.type)&&s.setActiveOption(t))))}onItemSelect(e,t){var i=this
184
+ return!i.isLocked&&"multi"===i.settings.mode&&(H(e),i.setActiveItem(t,e),!0)}canLoad(e){return!!this.settings.load&&!this.loadedSearches.hasOwnProperty(e)}load(e){const t=this
185
+ if(!t.canLoad(e))return
186
+ C(t.wrapper,t.settings.loadingClass),t.loading++
187
+ const i=t.loadCallback.bind(t)
188
+ t.settings.load.call(t,e,i)}loadCallback(e,t){const i=this
189
+ i.loading=Math.max(i.loading-1,0),i.lastQuery=null,i.clearActiveOption(),i.setupOptions(e,t),i.refreshOptions(i.isFocused&&!i.isInputHidden),i.loading||S(i.wrapper,i.settings.loadingClass),i.trigger("load",e,t)}preload(){var e=this.wrapper.classList
190
+ e.contains("preloaded")||(e.add("preloaded"),this.load(""))}setTextboxValue(e=""){var t=this.control_input
191
+ t.value!==e&&(t.value=e,_(t,"update"),this.lastValue=e)}getValue(){return this.is_select_tag&&this.input.hasAttribute("multiple")?this.items:this.items.join(this.settings.delimiter)}setValue(e,t){R(this,t?[]:["change"],(()=>{this.clear(t),this.addItems(e,t)}))}setMaxItems(e){0===e&&(e=null),this.settings.maxItems=e,this.refreshState()}setActiveItem(e,t){var i,s,n,o,r,l,a=this
192
+ if("single"!==a.settings.mode){if(!e)return a.clearActiveItems(),void(a.isFocused&&a.showInput())
193
+ if("click"===(i=t&&t.type.toLowerCase())&&K("shiftKey",t)&&a.activeItems.length){for(l=a.getLastActive(),(n=Array.prototype.indexOf.call(a.control.children,l))>(o=Array.prototype.indexOf.call(a.control.children,e))&&(r=n,n=o,o=r),s=n;s<=o;s++)e=a.control.children[s],-1===a.activeItems.indexOf(e)&&a.setActiveItemClass(e)
194
+ H(t)}else"click"===i&&K(V,t)||"keydown"===i&&K("shiftKey",t)?e.classList.contains("active")?a.removeActiveItem(e):a.setActiveItemClass(e):(a.clearActiveItems(),a.setActiveItemClass(e))
195
+ a.hideInput(),a.isFocused||a.focus()}}setActiveItemClass(e){const t=this,i=t.control.querySelector(".last-active")
196
+ i&&S(i,"last-active"),C(e,"active last-active"),t.trigger("item_select",e),-1==t.activeItems.indexOf(e)&&t.activeItems.push(e)}removeActiveItem(e){var t=this.activeItems.indexOf(e)
197
+ this.activeItems.splice(t,1),S(e,"active")}clearActiveItems(){S(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,P(this.focus_node,{"aria-activedescendant":e.getAttribute("id")}),P(e,{"aria-selected":"true"}),C(e,"active"),this.scrollToOption(e)))}scrollToOption(e,t){if(!e)return
198
+ const i=this.dropdown_content,s=i.clientHeight,n=i.scrollTop||0,o=e.offsetHeight,r=e.getBoundingClientRect().top-i.getBoundingClientRect().top+n
199
+ r+o>s+n?this.scroll(r-s+o,t):r<n&&this.scroll(r,t)}scroll(e,t){const i=this.dropdown_content
200
+ t&&(i.style.scrollBehavior=t),i.scrollTop=e,i.style.scrollBehavior=""}clearActiveOption(){this.activeOption&&(S(this.activeOption,"active"),P(this.activeOption,{"aria-selected":null})),this.activeOption=null,P(this.focus_node,{"aria-activedescendant":null})}selectAll(){if("single"===this.settings.mode)return
201
+ const e=this.controlChildren()
202
+ e.length&&(this.hideInput(),this.close(),this.activeItems=e,C(e,"active"))}inputState(){var e=this
203
+ e.control.contains(e.control_input)&&(P(e.control_input,{placeholder:e.settings.placeholder}),e.activeItems.length>0||!e.isFocused&&e.settings.hidePlaceholder&&e.items.length>0?(e.setTextboxValue(),e.isInputHidden=!0):(e.settings.hidePlaceholder&&e.items.length>0&&P(e.control_input,{placeholder:""}),e.isInputHidden=!1),e.wrapper.classList.toggle("input-hidden",e.isInputHidden))}hideInput(){this.inputState()}showInput(){this.inputState()}inputValue(){return this.control_input.value.trim()}focus(){var e=this
204
+ e.isDisabled||(e.ignoreFocus=!0,e.control_input.offsetWidth?e.control_input.focus():e.focus_node.focus(),setTimeout((()=>{e.ignoreFocus=!1,e.onFocus()}),0))}blur(){this.focus_node.blur(),this.onBlur()}getScoreFunction(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())}getSearchOptions(){var e=this.settings,t=e.sortField
205
+ return"string"==typeof e.sortField&&(t=[{field:e.sortField}]),{fields:e.searchField,conjunction:e.searchConjunction,sort:t,nesting:e.nesting}}search(e){var t,i,s,n=this,o=this.getSearchOptions()
206
+ if(n.settings.score&&"function"!=typeof(s=n.settings.score.call(n,e)))throw new Error('Tom Select "score" setting must be a function that returns a function')
207
+ if(e!==n.lastQuery?(n.lastQuery=e,i=n.sifter.search(e,Object.assign(o,{score:s})),n.currentResults=i):i=Object.assign({},n.currentResults),n.settings.hideSelected)for(t=i.items.length-1;t>=0;t--){let e=q(i.items[t].id)
208
+ e&&-1!==n.items.indexOf(e)&&i.items.splice(t,1)}return i}refreshOptions(e=!0){var t,i,s,n,o,r,l,a,c,d,p
209
+ const u={},h=[]
210
+ var g,f=this,v=f.inputValue(),m=f.search(v),O=f.activeOption,b=f.settings.shouldOpen||!1,w=f.dropdown_content
211
+ for(O&&(c=O.dataset.value,d=O.closest("[data-group]")),n=m.items.length,"number"==typeof f.settings.maxOptions&&(n=Math.min(n,f.settings.maxOptions)),n>0&&(b=!0),t=0;t<n;t++){let e=m.items[t].id,n=f.options[e],l=f.getOption(e,!0)
212
+ for(f.settings.hideSelected||l.classList.toggle("selected",f.items.includes(e)),o=n[f.settings.optgroupField]||"",i=0,s=(r=Array.isArray(o)?o:[o])&&r.length;i<s;i++)o=r[i],f.optgroups.hasOwnProperty(o)||(o=""),u.hasOwnProperty(o)||(u[o]=document.createDocumentFragment(),h.push(o)),i>0&&(l=l.cloneNode(!0),P(l,{id:n.$id+"-clone-"+i,"aria-selected":null}),l.classList.add("ts-cloned"),S(l,"active")),c==e&&d&&d.dataset.group===o&&(O=l),u[o].appendChild(l)}this.settings.lockOptgroupOrder&&h.sort(((e,t)=>(f.optgroups[e]&&f.optgroups[e].$order||0)-(f.optgroups[t]&&f.optgroups[t].$order||0))),l=document.createDocumentFragment(),y(h,(e=>{if(f.optgroups.hasOwnProperty(e)&&u[e].children.length){let t=document.createDocumentFragment(),i=f.render("optgroup_header",f.optgroups[e])
213
+ G(t,i),G(t,u[e])
214
+ let s=f.render("optgroup",{group:f.optgroups[e],options:t})
215
+ G(l,s)}else G(l,u[e])})),w.innerHTML="",G(w,l),f.settings.highlight&&(g=w.querySelectorAll("span.highlight"),Array.prototype.forEach.call(g,(function(e){var t=e.parentNode
216
+ t.replaceChild(e.firstChild,e),t.normalize()})),m.query.length&&m.tokens.length&&y(m.tokens,(e=>{T(w,e.regex)})))
217
+ var _=e=>{let t=f.render(e,{input:v})
218
+ return t&&(b=!0,w.insertBefore(t,w.firstChild)),t}
219
+ if(f.loading?_("loading"):f.settings.shouldLoad.call(f,v)?0===m.items.length&&_("no_results"):_("not_loading"),(a=f.canCreate(v))&&(p=_("option_create")),f.hasOptions=m.items.length>0||a,b){if(m.items.length>0){if(!w.contains(O)&&"single"===f.settings.mode&&f.items.length&&(O=f.getOption(f.items[0])),!w.contains(O)){let e=0
220
+ p&&!f.settings.addPrecedence&&(e=1),O=f.selectable()[e]}}else p&&(O=p)
221
+ e&&!f.isOpen&&(f.open(),f.scrollToOption(O,"auto")),f.setActiveOption(O)}else f.clearActiveOption(),e&&f.isOpen&&f.close(!1)}selectable(){return this.dropdown_content.querySelectorAll("[data-selectable]")}addOption(e,t=!1){const i=this
222
+ if(Array.isArray(e))return i.addOptions(e,t),!1
223
+ const s=q(e[i.settings.valueField])
224
+ return null!==s&&!i.options.hasOwnProperty(s)&&(e.$order=e.$order||++i.order,e.$id=i.inputId+"-opt-"+e.$order,i.options[s]=e,i.lastQuery=null,t&&(i.userOptions[s]=t,i.trigger("option_add",s,e)),s)}addOptions(e,t=!1){y(e,(e=>{this.addOption(e,t)}))}registerOption(e){return this.addOption(e)}registerOptionGroup(e){var t=q(e[this.settings.optgroupValueField])
225
+ return null!==t&&(e.$order=e.$order||++this.order,this.optgroups[t]=e,t)}addOptionGroup(e,t){var i
226
+ t[this.settings.optgroupValueField]=e,(i=this.registerOptionGroup(t))&&this.trigger("optgroup_add",i,t)}removeOptionGroup(e){this.optgroups.hasOwnProperty(e)&&(delete this.optgroups[e],this.clearCache(),this.trigger("optgroup_remove",e))}clearOptionGroups(){this.optgroups={},this.clearCache(),this.trigger("optgroup_clear")}updateOption(e,t){const i=this
227
+ var s,n
228
+ const o=q(e),r=q(t[i.settings.valueField])
229
+ if(null===o)return
230
+ if(!i.options.hasOwnProperty(o))return
231
+ if("string"!=typeof r)throw new Error("Value must be set in option data")
232
+ const l=i.getOption(o),a=i.getItem(o)
233
+ if(t.$order=t.$order||i.options[o].$order,delete i.options[o],i.uncacheValue(r),i.options[r]=t,l){if(i.dropdown_content.contains(l)){const e=i._render("option",t)
234
+ E(l,e),i.activeOption===l&&i.setActiveOption(e)}l.remove()}a&&(-1!==(n=i.items.indexOf(o))&&i.items.splice(n,1,r),s=i._render("item",t),a.classList.contains("active")&&C(s,"active"),E(a,s)),i.lastQuery=null}removeOption(e,t){const i=this
235
+ e=D(e),i.uncacheValue(e),delete i.userOptions[e],delete i.options[e],i.lastQuery=null,i.trigger("option_remove",e),i.removeItem(e,t)}clearOptions(){this.loadedSearches={},this.userOptions={},this.clearCache()
236
+ var e={}
237
+ y(this.options,((t,i)=>{this.items.indexOf(i)>=0&&(e[i]=this.options[i])})),this.options=this.sifter.items=e,this.lastQuery=null,this.trigger("option_clear")}getOption(e,t=!1){const i=q(e)
238
+ if(null!==i&&this.options.hasOwnProperty(i)){const e=this.options[i]
239
+ if(e.$div)return e.$div
240
+ if(t)return this._render("option",e)}return null}getAdjacent(e,t,i="option"){var s
241
+ if(!e)return null
242
+ s="item"==i?this.controlChildren():this.dropdown_content.querySelectorAll("[data-selectable]")
243
+ for(let i=0;i<s.length;i++)if(s[i]==e)return t>0?s[i+1]:s[i-1]
244
+ return null}getItem(e){if("object"==typeof e)return e
245
+ var t=q(e)
246
+ return null!==t?this.control.querySelector(`[data-value="${Q(t)}"]`):null}addItems(e,t){var i=this,s=Array.isArray(e)?e:[e]
247
+ for(let e=0,n=(s=s.filter((e=>-1===i.items.indexOf(e)))).length;e<n;e++)i.isPending=e<n-1,i.addItem(s[e],t)}addItem(e,t){R(this,t?[]:["change"],(()=>{var i,s
248
+ const n=this,o=n.settings.mode,r=q(e)
249
+ if((!r||-1===n.items.indexOf(r)||("single"===o&&n.close(),"single"!==o&&n.settings.duplicates))&&null!==r&&n.options.hasOwnProperty(r)&&("single"===o&&n.clear(t),"multi"!==o||!n.isFull())){if(i=n._render("item",n.options[r]),n.control.contains(i)&&(i=i.cloneNode(!0)),s=n.isFull(),n.items.splice(n.caretPos,0,r),n.insertAtCaret(i),n.isSetup){if(!n.isPending&&n.settings.hideSelected){let e=n.getOption(r),t=n.getAdjacent(e,1)
250
+ t&&n.setActiveOption(t)}n.isPending||n.refreshOptions(n.isFocused&&"single"!==o),0!=n.settings.closeAfterSelect&&n.isFull()?n.close():n.isPending||n.positionDropdown(),n.trigger("item_add",r,i),n.isPending||n.updateOriginalInput({silent:t})}(!n.isPending||!s&&n.isFull())&&(n.inputState(),n.refreshState())}}))}removeItem(e=null,t){const i=this
251
+ if(!(e=i.getItem(e)))return
252
+ var s,n
253
+ const o=e.dataset.value
254
+ s=L(e),e.remove(),e.classList.contains("active")&&(n=i.activeItems.indexOf(e),i.activeItems.splice(n,1),S(e,"active")),i.items.splice(s,1),i.lastQuery=null,!i.settings.persist&&i.userOptions.hasOwnProperty(o)&&i.removeOption(o,t),s<i.caretPos&&i.setCaret(i.caretPos-1),i.updateOriginalInput({silent:t}),i.refreshState(),i.positionDropdown(),i.trigger("item_remove",o,e)}createItem(e=null,t=!0,i=(()=>{})){var s,n=this,o=n.caretPos
255
+ if(e=e||n.inputValue(),!n.canCreate(e))return i(),!1
256
+ n.lock()
257
+ var r=!1,l=e=>{if(n.unlock(),!e||"object"!=typeof e)return i()
258
+ var s=q(e[n.settings.valueField])
259
+ if("string"!=typeof s)return i()
260
+ n.setTextboxValue(),n.addOption(e,!0),n.setCaret(o),n.addItem(s),n.refreshOptions(t&&"single"!==n.settings.mode),i(e),r=!0}
261
+ return s="function"==typeof n.settings.create?n.settings.create.call(this,e,l):{[n.settings.labelField]:e,[n.settings.valueField]:e},r||l(s),!0}refreshItems(){var e=this
262
+ e.lastQuery=null,e.isSetup&&e.addItems(e.items),e.updateOriginalInput(),e.refreshState()}refreshState(){const e=this
263
+ e.refreshValidityState()
264
+ const t=e.isFull(),i=e.isLocked
265
+ e.wrapper.classList.toggle("rtl",e.rtl)
266
+ const s=e.wrapper.classList
267
+ var n
268
+ s.toggle("focus",e.isFocused),s.toggle("disabled",e.isDisabled),s.toggle("required",e.isRequired),s.toggle("invalid",!e.isValid),s.toggle("locked",i),s.toggle("full",t),s.toggle("input-active",e.isFocused&&!e.isInputHidden),s.toggle("dropdown-active",e.isOpen),s.toggle("has-options",(n=e.options,0===Object.keys(n).length)),s.toggle("has-items",e.items.length>0)}refreshValidityState(){var e=this
269
+ e.input.checkValidity&&(e.isValid=e.input.checkValidity(),e.isInvalid=!e.isValid)}isFull(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems}updateOriginalInput(e={}){const t=this
270
+ var i,s
271
+ const n=t.input.querySelector('option[value=""]')
272
+ if(t.is_select_tag){const e=[]
273
+ function o(i,s,o){return i||(i=w('<option value="'+N(s)+'">'+N(o)+"</option>")),i!=n&&t.input.append(i),e.push(i),i.selected=!0,i}t.input.querySelectorAll("option:checked").forEach((e=>{e.selected=!1})),0==t.items.length&&"single"==t.settings.mode?o(n,"",""):t.items.forEach((n=>{if(i=t.options[n],s=i[t.settings.labelField]||"",e.includes(i.$option)){o(t.input.querySelector(`option[value="${Q(n)}"]:not(:checked)`),n,s)}else i.$option=o(i.$option,n,s)}))}else t.input.value=t.getValue()
274
+ t.isSetup&&(e.silent||t.trigger("change",t.getValue()))}open(){var e=this
275
+ e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull()||(e.isOpen=!0,P(e.focus_node,{"aria-expanded":"true"}),e.refreshState(),I(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),I(e.dropdown,{visibility:"visible",display:"block"}),e.focus(),e.trigger("dropdown_open",e.dropdown))}close(e=!0){var t=this,i=t.isOpen
276
+ e&&(t.setTextboxValue(),"single"===t.settings.mode&&t.items.length&&t.hideInput()),t.isOpen=!1,P(t.focus_node,{"aria-expanded":"false"}),I(t.dropdown,{display:"none"}),t.settings.hideSelected&&t.clearActiveOption(),t.refreshState(),i&&t.trigger("dropdown_close",t.dropdown)}positionDropdown(){if("body"===this.settings.dropdownParent){var e=this.control,t=e.getBoundingClientRect(),i=e.offsetHeight+t.top+window.scrollY,s=t.left+window.scrollX
277
+ I(this.dropdown,{width:t.width+"px",top:i+"px",left:s+"px"})}}clear(e){var t=this
278
+ if(t.items.length){var i=t.controlChildren()
279
+ y(i,(e=>{t.removeItem(e,!0)})),t.showInput(),e||t.updateOriginalInput(),t.trigger("clear")}}insertAtCaret(e){const t=this,i=t.caretPos,s=t.control
280
+ s.insertBefore(e,s.children[i]),t.setCaret(i+1)}deleteSelection(e){var t,i,s,n,o,r=this
281
+ t=e&&8===e.keyCode?-1:1,i={start:(o=r.control_input).selectionStart||0,length:(o.selectionEnd||0)-(o.selectionStart||0)}
282
+ const l=[]
283
+ if(r.activeItems.length)n=F(r.activeItems,t),s=L(n),t>0&&s++,y(r.activeItems,(e=>l.push(e)))
284
+ else if((r.isFocused||"single"===r.settings.mode)&&r.items.length){const e=r.controlChildren()
285
+ t<0&&0===i.start&&0===i.length?l.push(e[r.caretPos-1]):t>0&&i.start===r.inputValue().length&&l.push(e[r.caretPos])}const a=l.map((e=>e.dataset.value))
286
+ if(!a.length||"function"==typeof r.settings.onDelete&&!1===r.settings.onDelete.call(r,a,e))return!1
287
+ for(H(e,!0),void 0!==s&&r.setCaret(s);l.length;)r.removeItem(l.pop())
288
+ return r.showInput(),r.positionDropdown(),r.refreshOptions(!1),!0}advanceSelection(e,t){var i,s,n=this
289
+ n.rtl&&(e*=-1),n.inputValue().length||(K(V,t)||K("shiftKey",t)?(s=(i=n.getLastActive(e))?i.classList.contains("active")?n.getAdjacent(i,e,"item"):i:e>0?n.control_input.nextElementSibling:n.control_input.previousElementSibling)&&(s.classList.contains("active")&&n.removeActiveItem(i),n.setActiveItemClass(s)):n.moveCaret(e))}moveCaret(e){}getLastActive(e){let t=this.control.querySelector(".last-active")
290
+ if(t)return t
291
+ var i=this.control.querySelectorAll(".active")
292
+ return i?F(i,e):void 0}setCaret(e){this.caretPos=this.items.length}controlChildren(){return Array.from(this.control.querySelectorAll("[data-ts-item]"))}lock(){this.close(),this.isLocked=!0,this.refreshState()}unlock(){this.isLocked=!1,this.refreshState()}disable(){var e=this
293
+ e.input.disabled=!0,e.control_input.disabled=!0,e.focus_node.tabIndex=-1,e.isDisabled=!0,e.lock()}enable(){var e=this
294
+ e.input.disabled=!1,e.control_input.disabled=!1,e.focus_node.tabIndex=e.tabIndex,e.isDisabled=!1,e.unlock()}destroy(){var e=this,t=e.revertSettings
295
+ e.trigger("destroy"),e.off(),e.wrapper.remove(),e.dropdown.remove(),e.input.innerHTML=t.innerHTML,e.input.tabIndex=t.tabIndex,S(e.input,"tomselected","ts-hidden-accessible"),e._destroy(),delete e.input.tomselect}render(e,t){return"function"!=typeof this.settings.render[e]?null:this._render(e,t)}_render(e,t){var i,s,n=""
296
+ const o=this
297
+ return"option"!==e&&"item"!=e||(n=D(t[o.settings.valueField])),null==(s=o.settings.render[e].call(this,t,N))||(s=w(s),"option"===e||"option_create"===e?t[o.settings.disabledField]?P(s,{"aria-disabled":"true"}):P(s,{"data-selectable":""}):"optgroup"===e&&(i=t.group[o.settings.optgroupValueField],P(s,{"data-group":i}),t.group[o.settings.disabledField]&&P(s,{"data-disabled":""})),"option"!==e&&"item"!==e||(P(s,{"data-value":n}),"item"===e?(C(s,o.settings.itemClass),P(s,{"data-ts-item":""})):(C(s,o.settings.optionClass),P(s,{role:"option",id:t.$id}),o.options[n].$div=s))),s}clearCache(){y(this.options,((e,t)=>{e.$div&&(e.$div.remove(),delete e.$div)}))}uncacheValue(e){const t=this.getOption(e)
298
+ t&&t.remove()}canCreate(e){return this.settings.create&&e.length>0&&this.settings.createFilter.call(this,e)}hook(e,t,i){var s=this,n=s[t]
299
+ s[t]=function(){var t,o
300
+ return"after"===e&&(t=n.apply(s,arguments)),o=i.apply(s,arguments),"instead"===e?o:("before"===e&&(t=n.apply(s,arguments)),t)}}}return J.define("change_listener",(function(){B(this.input,"change",(()=>{this.sync()}))})),J.define("checkbox_options",(function(){var e=this,t=e.onOptionSelect
301
+ e.settings.hideSelected=!1
302
+ var i=function(e){setTimeout((()=>{var t=e.querySelector("input")
303
+ e.classList.contains("selected")?t.checked=!0:t.checked=!1}),1)}
304
+ e.hook("after","setupTemplates",(()=>{var t=e.settings.render.option
305
+ e.settings.render.option=(i,s)=>{var n=w(t.call(e,i,s)),o=document.createElement("input")
306
+ o.addEventListener("click",(function(e){H(e)})),o.type="checkbox"
307
+ const r=q(i[e.settings.valueField])
308
+ return r&&e.items.indexOf(r)>-1&&(o.checked=!0),n.prepend(o),n}})),e.on("item_remove",(t=>{var s=e.getOption(t)
309
+ s&&(s.classList.remove("selected"),i(s))})),e.hook("instead","onOptionSelect",((s,n)=>{if(n.classList.contains("selected"))return n.classList.remove("selected"),e.removeItem(n.dataset.value),e.refreshOptions(),void H(s,!0)
310
+ t.call(e,s,n),i(n)}))})),J.define("clear_button",(function(e){const t=this,i=Object.assign({className:"clear-button",title:"Clear All",html:e=>`<div class="${e.className}" title="${e.title}">&times;</div>`},e)
311
+ t.on("initialize",(()=>{var e=w(i.html(i))
312
+ e.addEventListener("click",(e=>{t.clear(),"single"===t.settings.mode&&t.settings.allowEmptyOption&&t.addItem(""),e.preventDefault(),e.stopPropagation()})),t.control.appendChild(e)}))})),J.define("drag_drop",(function(){var e=this
313
+ if(!$.fn.sortable)throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".')
314
+ if("multi"===e.settings.mode){var t=e.lock,i=e.unlock
315
+ e.hook("instead","lock",(()=>{var i=$(e.control).data("sortable")
316
+ return i&&i.disable(),t.call(e)})),e.hook("instead","unlock",(()=>{var t=$(e.control).data("sortable")
317
+ return t&&t.enable(),i.call(e)})),e.on("initialize",(()=>{var t=$(e.control).sortable({items:"[data-value]",forcePlaceholderSize:!0,disabled:e.isLocked,start:(e,i)=>{i.placeholder.css("width",i.helper.css("width")),t.css({overflow:"visible"})},stop:()=>{t.css({overflow:"hidden"})
318
+ var i=[]
319
+ t.children("[data-value]").each((function(){this.dataset.value&&i.push(this.dataset.value)})),e.setValue(i)}})}))}})),J.define("dropdown_header",(function(e){const t=this,i=Object.assign({title:"Untitled",headerClass:"dropdown-header",titleRowClass:"dropdown-header-title",labelClass:"dropdown-header-label",closeClass:"dropdown-header-close",html:e=>'<div class="'+e.headerClass+'"><div class="'+e.titleRowClass+'"><span class="'+e.labelClass+'">'+e.title+'</span><a class="'+e.closeClass+'">&times;</a></div></div>'},e)
320
+ t.on("initialize",(()=>{var e=w(i.html(i)),s=e.querySelector("."+i.closeClass)
321
+ s&&s.addEventListener("click",(e=>{H(e,!0),t.close()})),t.dropdown.insertBefore(e,t.dropdown.firstChild)}))})),J.define("caret_position",(function(){var e=this
322
+ e.hook("instead","setCaret",(t=>{"single"!==e.settings.mode&&e.control.contains(e.control_input)?(t=Math.max(0,Math.min(e.items.length,t)))==e.caretPos||e.isPending||e.controlChildren().forEach(((i,s)=>{s<t?e.control_input.insertAdjacentElement("beforebegin",i):e.control.appendChild(i)})):t=e.items.length,e.caretPos=t})),e.hook("instead","moveCaret",(t=>{if(!e.isFocused)return
323
+ const i=e.getLastActive(t)
324
+ if(i){const s=L(i)
325
+ e.setCaret(t>0?s+1:s),e.setActiveItem()}else e.setCaret(e.caretPos+t)}))})),J.define("dropdown_input",(function(){var e=this
326
+ e.settings.shouldOpen=!0,e.hook("before","setup",(()=>{e.focus_node=e.control,C(e.control_input,"dropdown-input")
327
+ const t=w('<div class="dropdown-input-wrap">')
328
+ t.append(e.control_input),e.dropdown.insertBefore(t,e.dropdown.firstChild)})),e.on("initialize",(()=>{e.control_input.addEventListener("keydown",(t=>{switch(t.keyCode){case 27:return e.isOpen&&(H(t,!0),e.close()),void e.clearActiveItems()
329
+ case 9:e.focus_node.tabIndex=-1}return e.onKeyDown.call(e,t)})),e.on("blur",(()=>{e.focus_node.tabIndex=e.isDisabled?-1:e.tabIndex})),e.on("dropdown_open",(()=>{e.control_input.focus()}))
330
+ const t=e.onBlur
331
+ e.hook("instead","onBlur",(i=>{if(!i||i.relatedTarget!=e.control_input)return t.call(e)})),B(e.control_input,"blur",(()=>e.onBlur())),e.hook("before","close",(()=>{e.isOpen&&e.focus_node.focus()}))}))})),J.define("input_autogrow",(function(){var e=this
332
+ e.on("initialize",(()=>{var t=document.createElement("span"),i=e.control_input
333
+ t.style.cssText="position:absolute; top:-99999px; left:-99999px; width:auto; padding:0; white-space:pre; ",e.wrapper.appendChild(t)
334
+ for(const e of["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"])t.style[e]=i.style[e]
335
+ var s=()=>{e.items.length>0?(t.textContent=i.value,i.style.width=t.clientWidth+"px"):i.style.width=""}
336
+ s(),e.on("update item_add item_remove",s),B(i,"input",s),B(i,"keyup",s),B(i,"blur",s),B(i,"update",s)}))})),J.define("no_backspace_delete",(function(){var e=this,t=e.deleteSelection
337
+ this.hook("instead","deleteSelection",(i=>!!e.activeItems.length&&t.call(e,i)))})),J.define("no_active_items",(function(){this.hook("instead","setActiveItem",(()=>{})),this.hook("instead","selectAll",(()=>{}))})),J.define("optgroup_columns",(function(){var e=this,t=e.onKeyDown
338
+ e.hook("instead","onKeyDown",(i=>{var s,n,o,r
339
+ if(!e.isOpen||37!==i.keyCode&&39!==i.keyCode)return t.call(e,i)
340
+ r=k(e.activeOption,"[data-group]"),s=L(e.activeOption,"[data-selectable]"),r&&(r=37===i.keyCode?r.previousSibling:r.nextSibling)&&(n=(o=r.querySelectorAll("[data-selectable]"))[Math.min(o.length-1,s)])&&e.setActiveOption(n)}))})),J.define("remove_button",(function(e){const t=Object.assign({label:"&times;",title:"Remove",className:"remove",append:!0},e)
341
+ var i=this
342
+ if(t.append){var s='<a href="javascript:void(0)" class="'+t.className+'" tabindex="-1" title="'+N(t.title)+'">'+t.label+"</a>"
343
+ i.hook("after","setupTemplates",(()=>{var e=i.settings.render.item
344
+ i.settings.render.item=(t,n)=>{var o=w(e.call(i,t,n)),r=w(s)
345
+ return o.appendChild(r),B(r,"mousedown",(e=>{H(e,!0)})),B(r,"click",(e=>{if(H(e,!0),!i.isLocked){var t=o.dataset.value
346
+ i.removeItem(t),i.refreshOptions(!1)}})),o}}))}})),J.define("restore_on_backspace",(function(e){const t=this,i=Object.assign({text:e=>e[t.settings.labelField]},e)
347
+ t.on("item_remove",(function(e){if(""===t.control_input.value.trim()){var s=t.options[e]
348
+ s&&t.setTextboxValue(i.text.call(t,s))}}))})),J.define("virtual_scroll",(function(){const e=this,t=e.canLoad,i=e.clearActiveOption,s=e.loadCallback
349
+ var n,o={},r=!1
350
+ if(!e.settings.firstUrl)throw"virtual_scroll plugin requires a firstUrl() method"
351
+ function l(t){return!("number"==typeof e.settings.maxOptions&&n.children.length>=e.settings.maxOptions)&&!(!(t in o)||!o[t])}e.settings.sortField=[{field:"$order"},{field:"$score"}],e.setNextUrl=function(e,t){o[e]=t},e.getUrl=function(t){if(t in o){const e=o[t]
352
+ return o[t]=!1,e}return o={},e.settings.firstUrl(t)},e.hook("instead","clearActiveOption",(()=>{if(!r)return i.call(e)})),e.hook("instead","canLoad",(i=>i in o?l(i):t.call(e,i))),e.hook("instead","loadCallback",((t,i)=>{r||e.clearOptions(),s.call(e,t,i),r=!1})),e.hook("after","refreshOptions",(()=>{const t=e.lastValue
353
+ var i
354
+ l(t)?(i=e.render("loading_more",{query:t}))&&i.setAttribute("data-selectable",""):t in o&&!n.querySelector(".no-results")&&(i=e.render("no_more_results",{query:t})),i&&(C(i,e.settings.optionClass),n.append(i))})),e.on("initialize",(()=>{n=e.dropdown_content,e.settings.render=Object.assign({},{loading_more:function(){return'<div class="loading-more-results">Loading more results ... </div>'},no_more_results:function(){return'<div class="no-more-results">No more results</div>'}},e.settings.render),n.addEventListener("scroll",(function(){n.clientHeight/(n.scrollHeight-n.scrollTop)<.95||l(e.lastValue)&&(r||(r=!0,e.load.call(e,e.lastValue)))}))}))})),J}))
355
+ var tomSelect=function(e,t){return new TomSelect(e,t)}
356
+ //# sourceMappingURL=tom-select.complete.min.js.map
src/lib/tom-select/tom-select.css ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * tom-select.css (v2.0.0-rc.4)
3
+ * Copyright (c) contributors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6
+ * file except in compliance with the License. You may obtain a copy of the License at:
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ * ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ *
14
+ */
15
+ .ts-wrapper.plugin-drag_drop.multi > .ts-control > div.ui-sortable-placeholder {
16
+ visibility: visible !important;
17
+ background: #f2f2f2 !important;
18
+ background: rgba(0, 0, 0, 0.06) !important;
19
+ border: 0 none !important;
20
+ box-shadow: inset 0 0 12px 4px #fff; }
21
+
22
+ .ts-wrapper.plugin-drag_drop .ui-sortable-placeholder::after {
23
+ content: '!';
24
+ visibility: hidden; }
25
+
26
+ .ts-wrapper.plugin-drag_drop .ui-sortable-helper {
27
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); }
28
+
29
+ .plugin-checkbox_options .option input {
30
+ margin-right: 0.5rem; }
31
+
32
+ .plugin-clear_button .ts-control {
33
+ padding-right: calc( 1em + (3 * 6px)) !important; }
34
+
35
+ .plugin-clear_button .clear-button {
36
+ opacity: 0;
37
+ position: absolute;
38
+ top: 8px;
39
+ right: calc(8px - 6px);
40
+ margin-right: 0 !important;
41
+ background: transparent !important;
42
+ transition: opacity 0.5s;
43
+ cursor: pointer; }
44
+
45
+ .plugin-clear_button.single .clear-button {
46
+ right: calc(8px - 6px + 2rem); }
47
+
48
+ .plugin-clear_button.focus.has-items .clear-button,
49
+ .plugin-clear_button:hover.has-items .clear-button {
50
+ opacity: 1; }
51
+
52
+ .ts-wrapper .dropdown-header {
53
+ position: relative;
54
+ padding: 10px 8px;
55
+ border-bottom: 1px solid #d0d0d0;
56
+ background: #f8f8f8;
57
+ border-radius: 3px 3px 0 0; }
58
+
59
+ .ts-wrapper .dropdown-header-close {
60
+ position: absolute;
61
+ right: 8px;
62
+ top: 50%;
63
+ color: #303030;
64
+ opacity: 0.4;
65
+ margin-top: -12px;
66
+ line-height: 20px;
67
+ font-size: 20px !important; }
68
+
69
+ .ts-wrapper .dropdown-header-close:hover {
70
+ color: black; }
71
+
72
+ .plugin-dropdown_input.focus.dropdown-active .ts-control {
73
+ box-shadow: none;
74
+ border: 1px solid #d0d0d0; }
75
+
76
+ .plugin-dropdown_input .dropdown-input {
77
+ border: 1px solid #d0d0d0;
78
+ border-width: 0 0 1px 0;
79
+ display: block;
80
+ padding: 8px 8px;
81
+ box-shadow: none;
82
+ width: 100%;
83
+ background: transparent; }
84
+
85
+ .ts-wrapper.plugin-input_autogrow.has-items .ts-control > input {
86
+ min-width: 0; }
87
+
88
+ .ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input {
89
+ flex: none;
90
+ min-width: 4px; }
91
+ .ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::-webkit-input-placeholder {
92
+ color: transparent; }
93
+ .ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::-ms-input-placeholder {
94
+ color: transparent; }
95
+ .ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::placeholder {
96
+ color: transparent; }
97
+
98
+ .ts-dropdown.plugin-optgroup_columns .ts-dropdown-content {
99
+ display: flex; }
100
+
101
+ .ts-dropdown.plugin-optgroup_columns .optgroup {
102
+ border-right: 1px solid #f2f2f2;
103
+ border-top: 0 none;
104
+ flex-grow: 1;
105
+ flex-basis: 0;
106
+ min-width: 0; }
107
+
108
+ .ts-dropdown.plugin-optgroup_columns .optgroup:last-child {
109
+ border-right: 0 none; }
110
+
111
+ .ts-dropdown.plugin-optgroup_columns .optgroup:before {
112
+ display: none; }
113
+
114
+ .ts-dropdown.plugin-optgroup_columns .optgroup-header {
115
+ border-top: 0 none; }
116
+
117
+ .ts-wrapper.plugin-remove_button .item {
118
+ display: inline-flex;
119
+ align-items: center;
120
+ padding-right: 0 !important; }
121
+
122
+ .ts-wrapper.plugin-remove_button .item .remove {
123
+ color: inherit;
124
+ text-decoration: none;
125
+ vertical-align: middle;
126
+ display: inline-block;
127
+ padding: 2px 6px;
128
+ border-left: 1px solid #d0d0d0;
129
+ border-radius: 0 2px 2px 0;
130
+ box-sizing: border-box;
131
+ margin-left: 6px; }
132
+
133
+ .ts-wrapper.plugin-remove_button .item .remove:hover {
134
+ background: rgba(0, 0, 0, 0.05); }
135
+
136
+ .ts-wrapper.plugin-remove_button .item.active .remove {
137
+ border-left-color: #cacaca; }
138
+
139
+ .ts-wrapper.plugin-remove_button.disabled .item .remove:hover {
140
+ background: none; }
141
+
142
+ .ts-wrapper.plugin-remove_button.disabled .item .remove {
143
+ border-left-color: white; }
144
+
145
+ .ts-wrapper.plugin-remove_button .remove-single {
146
+ position: absolute;
147
+ right: 0;
148
+ top: 0;
149
+ font-size: 23px; }
150
+
151
+ .ts-wrapper {
152
+ position: relative; }
153
+
154
+ .ts-dropdown,
155
+ .ts-control,
156
+ .ts-control input {
157
+ color: #303030;
158
+ font-family: inherit;
159
+ font-size: 13px;
160
+ line-height: 18px;
161
+ font-smoothing: inherit; }
162
+
163
+ .ts-control,
164
+ .ts-wrapper.single.input-active .ts-control {
165
+ background: #fff;
166
+ cursor: text; }
167
+
168
+ .ts-control {
169
+ border: 1px solid #d0d0d0;
170
+ padding: 8px 8px;
171
+ width: 100%;
172
+ overflow: hidden;
173
+ position: relative;
174
+ z-index: 1;
175
+ box-sizing: border-box;
176
+ box-shadow: none;
177
+ border-radius: 3px;
178
+ display: flex;
179
+ flex-wrap: wrap; }
180
+ .ts-wrapper.multi.has-items .ts-control {
181
+ padding: calc( 8px - 2px - 0) 8px calc( 8px - 2px - 3px - 0); }
182
+ .full .ts-control {
183
+ background-color: #fff; }
184
+ .disabled .ts-control,
185
+ .disabled .ts-control * {
186
+ cursor: default !important; }
187
+ .focus .ts-control {
188
+ box-shadow: none; }
189
+ .ts-control > * {
190
+ vertical-align: baseline;
191
+ display: inline-block; }
192
+ .ts-wrapper.multi .ts-control > div {
193
+ cursor: pointer;
194
+ margin: 0 3px 3px 0;
195
+ padding: 2px 6px;
196
+ background: #f2f2f2;
197
+ color: #303030;
198
+ border: 0 solid #d0d0d0; }
199
+ .ts-wrapper.multi .ts-control > div.active {
200
+ background: #e8e8e8;
201
+ color: #303030;
202
+ border: 0 solid #cacaca; }
203
+ .ts-wrapper.multi.disabled .ts-control > div, .ts-wrapper.multi.disabled .ts-control > div.active {
204
+ color: #7d7c7c;
205
+ background: white;
206
+ border: 0 solid white; }
207
+ .ts-control > input {
208
+ flex: 1 1 auto;
209
+ min-width: 7rem;
210
+ display: inline-block !important;
211
+ padding: 0 !important;
212
+ min-height: 0 !important;
213
+ max-height: none !important;
214
+ max-width: 100% !important;
215
+ margin: 0 !important;
216
+ text-indent: 0 !important;
217
+ border: 0 none !important;
218
+ background: none !important;
219
+ line-height: inherit !important;
220
+ -webkit-user-select: auto !important;
221
+ -moz-user-select: auto !important;
222
+ -ms-user-select: auto !important;
223
+ user-select: auto !important;
224
+ box-shadow: none !important; }
225
+ .ts-control > input::-ms-clear {
226
+ display: none; }
227
+ .ts-control > input:focus {
228
+ outline: none !important; }
229
+ .has-items .ts-control > input {
230
+ margin: 0 4px !important; }
231
+ .ts-control.rtl {
232
+ text-align: right; }
233
+ .ts-control.rtl.single .ts-control:after {
234
+ left: 15px;
235
+ right: auto; }
236
+ .ts-control.rtl .ts-control > input {
237
+ margin: 0 4px 0 -2px !important; }
238
+ .disabled .ts-control {
239
+ opacity: 0.5;
240
+ background-color: #fafafa; }
241
+ .input-hidden .ts-control > input {
242
+ opacity: 0;
243
+ position: absolute;
244
+ left: -10000px; }
245
+
246
+ .ts-dropdown {
247
+ position: absolute;
248
+ top: 100%;
249
+ left: 0;
250
+ width: 100%;
251
+ z-index: 10;
252
+ border: 1px solid #d0d0d0;
253
+ background: #fff;
254
+ margin: 0.25rem 0 0 0;
255
+ border-top: 0 none;
256
+ box-sizing: border-box;
257
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
258
+ border-radius: 0 0 3px 3px; }
259
+ .ts-dropdown [data-selectable] {
260
+ cursor: pointer;
261
+ overflow: hidden; }
262
+ .ts-dropdown [data-selectable] .highlight {
263
+ background: rgba(125, 168, 208, 0.2);
264
+ border-radius: 1px; }
265
+ .ts-dropdown .option,
266
+ .ts-dropdown .optgroup-header,
267
+ .ts-dropdown .no-results,
268
+ .ts-dropdown .create {
269
+ padding: 5px 8px; }
270
+ .ts-dropdown .option, .ts-dropdown [data-disabled], .ts-dropdown [data-disabled] [data-selectable].option {
271
+ cursor: inherit;
272
+ opacity: 0.5; }
273
+ .ts-dropdown [data-selectable].option {
274
+ opacity: 1;
275
+ cursor: pointer; }
276
+ .ts-dropdown .optgroup:first-child .optgroup-header {
277
+ border-top: 0 none; }
278
+ .ts-dropdown .optgroup-header {
279
+ color: #303030;
280
+ background: #fff;
281
+ cursor: default; }
282
+ .ts-dropdown .create:hover,
283
+ .ts-dropdown .option:hover,
284
+ .ts-dropdown .active {
285
+ background-color: #f5fafd;
286
+ color: #495c68; }
287
+ .ts-dropdown .create:hover.create,
288
+ .ts-dropdown .option:hover.create,
289
+ .ts-dropdown .active.create {
290
+ color: #495c68; }
291
+ .ts-dropdown .create {
292
+ color: rgba(48, 48, 48, 0.5); }
293
+ .ts-dropdown .spinner {
294
+ display: inline-block;
295
+ width: 30px;
296
+ height: 30px;
297
+ margin: 5px 8px; }
298
+ .ts-dropdown .spinner:after {
299
+ content: " ";
300
+ display: block;
301
+ width: 24px;
302
+ height: 24px;
303
+ margin: 3px;
304
+ border-radius: 50%;
305
+ border: 5px solid #d0d0d0;
306
+ border-color: #d0d0d0 transparent #d0d0d0 transparent;
307
+ animation: lds-dual-ring 1.2s linear infinite; }
308
+
309
+ @keyframes lds-dual-ring {
310
+ 0% {
311
+ transform: rotate(0deg); }
312
+ 100% {
313
+ transform: rotate(360deg); } }
314
+
315
+ .ts-dropdown-content {
316
+ overflow-y: auto;
317
+ overflow-x: hidden;
318
+ max-height: 200px;
319
+ overflow-scrolling: touch;
320
+ scroll-behavior: smooth; }
321
+
322
+ .ts-hidden-accessible {
323
+ border: 0 !important;
324
+ clip: rect(0 0 0 0) !important;
325
+ -webkit-clip-path: inset(50%) !important;
326
+ clip-path: inset(50%) !important;
327
+ height: 1px !important;
328
+ overflow: hidden !important;
329
+ padding: 0 !important;
330
+ position: absolute !important;
331
+ width: 1px !important;
332
+ white-space: nowrap !important; }
333
+
334
+ /*# sourceMappingURL=tom-select.css.map */
src/lib/vis-9.1.2/vis-network.css ADDED
The diff for this file is too large to render. See raw diff
 
src/lib/vis-9.1.2/vis-network.min.js ADDED
The diff for this file is too large to render. See raw diff
 
src/networks_graphs/Con100_Cleft50/biases.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d655d2708c365e4804b6f63faaf7c82224bc299e34ed806a948e1e62e9ca2c54
3
+ size 2471401
src/networks_graphs/Con100_Cleft50/graph.graphml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ba1a4b908deff9fdf12d9caa3d215fabb0cc8f38e395ee5f86327343ce0bd85
3
+ size 681118580
src/utils.py ADDED
@@ -0,0 +1,691 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains functions that could be used in different parts of the project
2
+
3
+ import numpy as np
4
+ import networkx as nx
5
+ import os
6
+ import pickle
7
+ import sys
8
+ import matplotlib.pyplot as plt
9
+ import csv
10
+ import scipy
11
+ from scipy.sparse import csr_matrix
12
+ import copy
13
+ import seaborn as sns
14
+ import pandas as pd
15
+ import random
16
+ from collections import Counter
17
+ import time
18
+ from heapq import heappop, heappush
19
+ import itertools
20
+ from collections import deque
21
+
22
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
23
+
24
+ # These functions are used to handle the reservoir during computation
25
+
26
+ def compute(x, W, Win, u, alpha):
27
+ """
28
+ Computes a single step of the neuron activity
29
+ """
30
+ W_spr = W
31
+ x_spr = csr_matrix(x)
32
+ Win_spr = csr_matrix(Win)
33
+ u_spr = csr_matrix(u)
34
+ newx_spr = np.tanh(W_spr @ x_spr + Win_spr @ u_spr)
35
+ newx = newx_spr.toarray()
36
+ newx = (1-alpha)*x + newx*alpha
37
+ return newx
38
+
39
+ def step_compute(x, W, Win, Wout, u_in, alpha, mask):
40
+ """
41
+ Computes a single step of the neuron activity and returns the output y
42
+ u_in should be the raw input vector WITHOUT the bias term.
43
+ """
44
+ # Reshape u_in to make sure it's a column vector (Nu, 1)
45
+ u_in = np.array(u_in).reshape(-1, 1)
46
+
47
+ # Append bias 1 for the reservoir compute
48
+ u_in_with_bias = np.vstack((u_in, [[1]]))
49
+
50
+ # Calculate new reservoir state
51
+ newx = compute(x, W, Win, u_in_with_bias, alpha)
52
+
53
+ # Calculate output y = Wout @ [1; x[mask]] (Skip connection u_in removed)
54
+ X_col = np.vstack((np.ones((1,1)), newx[mask].reshape(-1, 1)))
55
+ y = Wout @ X_col
56
+
57
+ return newx, y
58
+
59
+ def simulate(x, W, Win, u, alpha, XX = None, XY = None, Yhat = None, building_matrices = False, mask=None):
60
+ """
61
+ Sumulates the neural response to the entire input
62
+ """
63
+ #time0 = time.time()
64
+ # Simulates the Echo State Network over the input u (L x (1+Nu))
65
+ if building_matrices: # this makes the time scale linearly with respect to the number of samples
66
+ if mask is None:
67
+ raise("Need to provide a mask for this step")
68
+ if XX is None or XY is None or Yhat is None:
69
+ raise("You need to provide the the basic matrices to build them incremetally")
70
+ retval = []
71
+ newx = copy.deepcopy(x)
72
+ for u_idx, u_in in enumerate(u):
73
+ #print(time.time())
74
+ newx = compute(newx, W, Win, u_in.reshape((u.shape[1],-1)), alpha)
75
+ retval.append(newx)
76
+ #print(time.time())
77
+ # Skip connection removed
78
+ newx_reshaped = np.hstack((np.ones((1,1)), newx[mask].reshape(1,-1)))
79
+ # Assuming newx_reshaped and Yhat are numpy arrays
80
+ newx_reshaped_col = newx_reshaped.reshape(-1, 1)
81
+ newx_reshaped_row = newx_reshaped.reshape(1, -1)
82
+ Yhat_col = Yhat[:, u_idx].reshape(-1, 1)
83
+
84
+ #print(time.time())
85
+ XX += np.dot(newx_reshaped_col, newx_reshaped_row)
86
+ XY += np.dot(Yhat_col, newx_reshaped_row)
87
+ #print(time.time())
88
+ retval = np.array(retval).reshape((-1,len(x))).transpose()
89
+ #print(f"computation in {time.time() - time0} : {time.time()} - {time0}")
90
+ return XX, XY, retval
91
+ else:
92
+ retval = []
93
+ newx = copy.deepcopy(x)
94
+ for u_in in u:
95
+ newx = compute(newx, W, Win, u_in.reshape((u.shape[1],-1)), alpha)
96
+ retval.append(newx)
97
+ retval = np.array(retval).reshape((-1,len(x))).transpose()
98
+ #print(f"computation in {time.time() - time0} : {time.time()} - {time0}")
99
+ return retval
100
+
101
+ # These functions are used to handle the complete graph of the brain and cut it down into smaller subgraphs
102
+
103
+ def create_connectivity_matrix(num_neu, graph_folder_name, sel_crit, biologically_accurate=False, showing_figure = False, make_comparison = True): # Creates the connectivity matrix ad W, and also W_in, W_out and biases. Saves them in the current directory, ready to be used by main.ipynb
104
+
105
+ # get cells classes, that will be useful for the input definition
106
+
107
+ csv_file = os.path.join(BASE_DIR, 'classes_by_cell_type.csv')
108
+ input_cell_types = ['olfactory', 'visual', 'mechanosensory', 'hygrosensory', 'unknown_sensory', 'ocellar', 'gustatory', 'thermosensory']
109
+ output_cell_types = [
110
+ "MBON", "DAN", "LHCENT", "clock", "pars_intercerebralis",
111
+ "pars_lateralis", "Kenyon_Cell", "ALON", "LOP>ME",
112
+ "LOP>LO.ME", "LOP>LO", "LOP", "TuBu"
113
+ ]
114
+
115
+ data = []
116
+ with open(csv_file, 'r') as file:
117
+ csv_reader = csv.reader(file)
118
+ header = next(csv_reader) # Skip the header row
119
+ id_index = header.index('pt_root_id')
120
+ cell_type_index = header.index('cell_type')
121
+ for row in csv_reader:
122
+ cell_id = row[id_index]
123
+ cell_type = row[cell_type_index]
124
+ data += [(cell_id, cell_type)]
125
+
126
+ data_dict = {str(cell_id): cell_type for cell_id, cell_type in data}
127
+
128
+ # Load the network from a file
129
+
130
+ file_path = os.path.join(BASE_DIR ,'networks_graphs', graph_folder_name)
131
+
132
+ G = nx.read_graphml(os.path.join( file_path,'graph.graphml'))
133
+
134
+ unique_neurons = set(G.nodes())
135
+
136
+ # Load the biases from a file
137
+ with open(os.path.join( file_path,'biases.pkl'), 'rb') as file:
138
+ biases = pickle.load(file)
139
+
140
+
141
+ F, theta = selection_criterion(G=G, num_neu=num_neu, unique_neurons=unique_neurons, biases=biases, data_dict=data_dict, mode=sel_crit)
142
+
143
+ first_elements = {int(u) for u, v in F.edges}
144
+ second_elements = {int(v) for u, v in F.edges}
145
+
146
+ only_first = first_elements - second_elements
147
+ only_second = second_elements - first_elements
148
+ both = first_elements & second_elements
149
+
150
+ if showing_figure:
151
+
152
+ # Create a figure with 4 subplots
153
+ fig, axs = plt.subplots(2, 2, figsize=(12, 8))
154
+
155
+ # Degree distribution
156
+ degrees = [F.degree(n) for n in F.nodes()]
157
+ axs[0, 0].hist(degrees, bins=range(min(degrees), max(degrees) + 1), edgecolor='black')
158
+ axs[0, 0].set_title('Degree Distribution')
159
+ axs[0, 0].set_xlabel('Degree')
160
+ axs[0, 0].set_ylabel('Frequency')
161
+
162
+ # Clustering coefficient distribution
163
+ clustering_coeffs = nx.clustering(F).values()
164
+ axs[0, 1].hist(clustering_coeffs, bins=10, edgecolor='black')
165
+ axs[0, 1].set_title('Clustering Coefficient Distribution')
166
+ axs[0, 1].set_xlabel('Clustering Coefficient')
167
+ axs[0, 1].set_ylabel('Frequency')
168
+
169
+ # Shortest path length distribution
170
+ if nx.is_connected(F):
171
+ path_lengths = dict(nx.all_pairs_shortest_path_length(F))
172
+ lengths = []
173
+ for source in path_lengths:
174
+ for target in path_lengths[source]:
175
+ if source != target:
176
+ lengths.append(path_lengths[source][target])
177
+ axs[1, 0].hist(lengths, bins=range(min(lengths), max(lengths) + 1), edgecolor='black', align='left')
178
+ axs[1, 0].set_title('Shortest Path Length Distribution')
179
+ axs[1, 0].set_xlabel('Path Length')
180
+ axs[1, 0].set_ylabel('Frequency')
181
+ else:
182
+ axs[1, 0].text(0.5, 0.5, "The graph is not connected,\nso shortest path lengths cannot be computed for all pairs of nodes.",
183
+ horizontalalignment='center', verticalalignment='center', transform=axs[1, 0].transAxes)
184
+
185
+ # Connectivity of Unique IDs
186
+ labels = ['Only as Pre-syn', 'Only as Post-syn', 'Both']
187
+ sizes = [len(only_first), len(only_second), len(both)]
188
+ axs[1, 1].bar(labels, sizes, color=['blue', 'orange', 'green'])
189
+ axs[1, 1].set_title('Connectivity of Unique Neurons')
190
+ axs[1, 1].set_xlabel('Category')
191
+ axs[1, 1].set_ylabel('Number of Unique Neurons')
192
+
193
+ # Adjust the spacing between subplots
194
+ plt.tight_layout()
195
+
196
+ # Show the figure
197
+ plt.show()
198
+
199
+ # Save the figure in the /graph_stats/ folder
200
+ if not os.path.exists('graph_stats'):
201
+ os.makedirs('graph_stats')
202
+
203
+ graph_size = len(F.nodes())
204
+ figure_path = os.path.join('graph_stats', f'graph_stats_size_{graph_size}.png')
205
+ fig.savefig(figure_path)
206
+ print(f"Figure saved to {figure_path}")
207
+
208
+ if make_comparison:
209
+
210
+ # Create a graph D with the same sparsity as G but with randomly placed edges
211
+ num_nodes = len(F.nodes())
212
+ num_edges = len(F.edges())
213
+
214
+ # Generate a random graph with the same number of nodes and edges
215
+ D = nx.gnm_random_graph(num_nodes, num_edges)
216
+
217
+ while not nx.is_connected(D):
218
+ D = nx.gnm_random_graph(num_nodes, num_edges)
219
+
220
+ # Relabel the nodes of D to match the node labels of F
221
+ mapping = {i: node for i, node in enumerate(F.nodes())}
222
+ D = nx.relabel_nodes(D, mapping)
223
+
224
+ # Create a figure with 4 subplots
225
+ fig, axs = plt.subplots(2, 2, figsize=(12, 8))
226
+
227
+ # Degree distribution
228
+ degrees = [D.degree(n) for n in D.nodes()]
229
+ axs[0, 0].hist(degrees, bins=range(min(degrees), max(degrees) + 1), edgecolor='black')
230
+ axs[0, 0].set_title('Degree Distribution')
231
+ axs[0, 0].set_xlabel('Degree')
232
+ axs[0, 0].set_ylabel('Frequency')
233
+
234
+ # Clustering coefficient distribution
235
+ clustering_coeffs = nx.clustering(D).values()
236
+ axs[0, 1].hist(clustering_coeffs, bins=10, edgecolor='black')
237
+ axs[0, 1].set_title('Clustering Coefficient Distribution')
238
+ axs[0, 1].set_xlabel('Clustering Coefficient')
239
+ axs[0, 1].set_ylabel('Frequency')
240
+
241
+ # Shortest path length distribution
242
+ if nx.is_connected(D):
243
+ path_lengths = dict(nx.all_pairs_shortest_path_length(D))
244
+ lengths = []
245
+ for source in path_lengths:
246
+ for target in path_lengths[source]:
247
+ if source != target:
248
+ lengths.append(path_lengths[source][target])
249
+ axs[1, 0].hist(lengths, bins=range(min(lengths), max(lengths) + 1), edgecolor='black', align='left')
250
+ axs[1, 0].set_title('Shortest Path Length Distribution')
251
+ axs[1, 0].set_xlabel('Path Length')
252
+ axs[1, 0].set_ylabel('Frequency')
253
+ else:
254
+ axs[1, 0].text(0.5, 0.5, "The graph is not connected,\nso shortest path lengths cannot be computed for all pairs of nodes.",
255
+ horizontalalignment='center', verticalalignment='center', transform=axs[1, 0].transAxes)
256
+
257
+ first_elements_D = {int(u) for u, v in D.edges}
258
+ second_elements_D = {int(v) for u, v in D.edges}
259
+
260
+ only_first_D = first_elements_D - second_elements_D
261
+ only_second_D = second_elements_D - first_elements_D
262
+ both_D = first_elements_D & second_elements_D
263
+
264
+ # Connectivity of Unique IDs
265
+ labels = ['Only as Pre-syn', 'Only as Post-syn', 'Both']
266
+ sizes = [len(only_first_D ), len(only_second_D ), len(both_D )]
267
+ axs[1, 1].bar(labels, sizes, color=['blue', 'orange', 'green'])
268
+ axs[1, 1].set_title('Connectivity of Unique Neurons')
269
+ axs[1, 1].set_xlabel('Category')
270
+ axs[1, 1].set_ylabel('Number of Unique Neurons')
271
+
272
+ # Adjust the spacing between subplots
273
+ plt.tight_layout()
274
+
275
+ # Show the figure
276
+ plt.show()
277
+
278
+
279
+ # Save the figure in the /graph_stats/ folder
280
+ if not os.path.exists('graph_stats'):
281
+ os.makedirs('graph_stats')
282
+
283
+ graph_size = len(F.nodes())
284
+ figure_path = os.path.join('graph_stats', f'graph_stats_size_{graph_size}_random_perm.png')
285
+ fig.savefig(figure_path)
286
+ print(f"Figure saved to {figure_path}")
287
+
288
+
289
+
290
+
291
+ # Convert the connectivity matrix to a sparse matrix
292
+ connectivity_matrix = scipy.sparse.csr_matrix(nx.to_scipy_sparse_array(F, weight='weight'))
293
+
294
+ target_radius = 1
295
+ spectral_radius, _ = scipy.sparse.linalg.eigs(connectivity_matrix, k=1, which='LM')
296
+
297
+ # Rescale the connectivity matrix
298
+ theta = theta.astype('float')
299
+ rescaled_matrix = connectivity_matrix * target_radius/np.linalg.norm(spectral_radius)
300
+ theta *= target_radius/abs(float(np.linalg.norm(spectral_radius)))
301
+
302
+
303
+
304
+ print("Initial Spectral Radius:", spectral_radius)
305
+
306
+ # Keep scaling the matrix down until the spectral radius is below 1
307
+ scaling_factor = .99
308
+
309
+ while True:
310
+ spectral_radius, _ = scipy.sparse.linalg.eigs(rescaled_matrix, k=1, which='LM')
311
+ print(f"\rSpectral Radius: {np.linalg.norm(spectral_radius)}", end='', flush=True)
312
+ if np.linalg.norm(spectral_radius) < 1:
313
+ break
314
+ rescaled_matrix *= scaling_factor
315
+ theta *= scaling_factor
316
+ print(f"\n")
317
+
318
+
319
+ # Create W_in array
320
+ W_in = np.zeros((len(F.nodes()) , 1))
321
+
322
+ # Update W_in based on input_cell_types
323
+ for i, neuron_id in enumerate(F.nodes()):
324
+ if int(neuron_id) in [int(x) for x in list(data_dict.keys())] and data_dict[neuron_id] in input_cell_types:
325
+ W_in[i] = 1
326
+
327
+ if not biologically_accurate or np.max(W_in) == 0:
328
+ print("No input neurons found in the selected neurons, switching to first element only neurons.")
329
+ for i, neuron_id in enumerate(F.nodes()):
330
+ if int(neuron_id) in only_first:
331
+ W_in[i] = 1
332
+
333
+ if np.max(W_in) == 0:
334
+ print("no first element only neurons found")
335
+ W_in = None
336
+
337
+ W_out = np.zeros((len(F.nodes()), 1))
338
+
339
+ # Update W_out based on output_cell_types
340
+ for i, neuron_id in enumerate(F.nodes()):
341
+ if int(neuron_id) in [int(x) for x in list(data_dict.keys())] and data_dict[neuron_id] in output_cell_types:
342
+ W_out[i] = 1
343
+
344
+ if not biologically_accurate or np.max(W_out) == 0:
345
+ print("No output neurons found in the selected neurons, switching to second element only neurons.")
346
+ for i, neuron_id in enumerate(F.nodes()):
347
+ if int(neuron_id) in only_second:
348
+ W_out[i] = 1
349
+
350
+ if np.max(W_out) == 0:
351
+ print("no second element only neurons found")
352
+ W_out = None
353
+
354
+ # Save W_out to a file called W_out
355
+ with open(os.path.join(BASE_DIR, 'W_out.pkl'), 'wb') as file:
356
+ pickle.dump(W_out, file)
357
+
358
+ # Save connectivity_matrix to a file called W
359
+ with open(os.path.join(BASE_DIR, 'W.pkl'), 'wb') as file:
360
+ pickle.dump(rescaled_matrix, file)
361
+
362
+ # Save W_in to a file called W_in
363
+ with open(os.path.join(BASE_DIR, 'W_in.pkl'), 'wb') as file:
364
+ pickle.dump(W_in, file)
365
+
366
+ # Save theta to a file called theta.pkl
367
+ with open(os.path.join(BASE_DIR, 'bias.pkl'), 'wb') as file:
368
+ pickle.dump(theta, file)
369
+
370
+ # This function is similar to the one above, but it does not save the matrices in src/** and only returns the neurons IDs and the unique cell types
371
+
372
+ def get_neurons_id(num_neu, mode, graph_folder_name):
373
+
374
+ # get cells classes, that will be useful for the input definition
375
+
376
+ csv_file = os.path.join(BASE_DIR, 'classes_by_cell_type.csv')
377
+
378
+ data = []
379
+ with open(csv_file, 'r') as file:
380
+ csv_reader = csv.reader(file)
381
+ header = next(csv_reader) # Skip the header row
382
+ id_index = header.index('pt_root_id')
383
+ cell_type_index = header.index('cell_type')
384
+ for row in csv_reader:
385
+ cell_id = row[id_index]
386
+ cell_type = row[cell_type_index]
387
+ data += [(cell_id, cell_type)]
388
+
389
+ data_dict = {str(cell_id): cell_type for cell_id, cell_type in data}
390
+
391
+ # Load the network from a file
392
+
393
+ file_path = os.path.join(BASE_DIR, 'networks_graphs', graph_folder_name)
394
+
395
+ G = nx.read_graphml(os.path.join( file_path,'graph.graphml'))
396
+
397
+ unique_neurons = set(G.nodes())
398
+
399
+ # Calculate the total number of edges for each neuron
400
+ edge_counts = {neuron: G.degree(neuron) for neuron in unique_neurons}
401
+
402
+ # Sort the neuron IDs based on the edge counts in descending order
403
+ sorted_neurons = sorted(unique_neurons, key=lambda neuron: edge_counts[neuron], reverse=True)
404
+
405
+ # Create a sorted list of neuron IDs
406
+ neuron_id_list = list(sorted_neurons)
407
+
408
+ F, _ = selection_criterion(G=G, num_neu=num_neu, unique_neurons=unique_neurons, mode=mode, biases=None, data_dict=data_dict)
409
+
410
+ neuron_ids_in_F = list(F.nodes)
411
+ unique_cell_types_in_F = set(data_dict[neuron_id] for neuron_id in neuron_ids_in_F if neuron_id in data_dict)
412
+ return neuron_ids_in_F, unique_cell_types_in_F
413
+
414
+
415
+ def selection_criterion(G, num_neu, unique_neurons, data_dict, biases = None, mode='connectivity_first', params=None): #This function selects a smaller subset of N neurons from the full NetworkX graph G, and returns the NetworkX graph F, containing N nodes
416
+
417
+ if 'connectivity_first' in mode:
418
+
419
+ # Calculate the total number of edges for each neuron
420
+ edge_counts = {neuron: G.degree(neuron) for neuron in unique_neurons}
421
+
422
+ # Sort the neuron IDs based on the edge counts in descending order
423
+ sorted_neurons = sorted(unique_neurons, key=lambda neuron: edge_counts[neuron], reverse=True)
424
+
425
+ if biases is not None:
426
+ sorted_biases = np.array([biases[nrn] for nrn in sorted_neurons])
427
+
428
+ # Create a sorted list of neuron IDs
429
+ neuron_id_list = list(sorted_neurons)
430
+
431
+ num_neuron = num_neu
432
+
433
+ # Create a subgraph of G with the first num_neurons neurons
434
+ F = G.subgraph(neuron_id_list[:num_neuron])
435
+
436
+ # Create a copy of the subgraph
437
+ F = F.copy()
438
+
439
+ if '2' in mode:
440
+
441
+ if not nx.is_connected(F):
442
+ print("Graph not fully connected, connecting the components")
443
+ components = list(nx.connected_components(F))
444
+ meta_graph = nx.Graph()
445
+ for i, comp in enumerate(components):
446
+ meta_graph.add_node(i)
447
+
448
+ candidate_nodes = set(G.nodes()) - set(F.nodes())
449
+ best_addition = set()
450
+
451
+ F = min_node_connected_subgraph(G, components)
452
+
453
+ print("Pruning components")
454
+
455
+ # Check the number of nodes in F
456
+ while len(F.nodes()) > num_neuron:
457
+ # Find the least connected node
458
+ sorted_nodes = sorted(F.nodes, key=lambda node: F.degree(node))
459
+ for node in sorted_nodes:
460
+ F_tentative = F.copy()
461
+ F_tentative.remove_node(node)
462
+ if nx.is_connected(F_tentative):
463
+ F = F_tentative
464
+ break
465
+ print(f"\rCurrent number of nodes: {len(F.nodes())}", end='', flush=True)
466
+
467
+ print("Adding components")
468
+
469
+ while len(F.nodes()) < num_neuron:
470
+ # Find the node in G that is most connected to nodes already in F
471
+ candidate_nodes = set(G.nodes()) - set(F.nodes())
472
+ best_node = max(candidate_nodes, key=lambda node: len(set(G.neighbors(node)) & set(F.nodes())))
473
+ F.add_node(best_node)
474
+ for neighbor in G.neighbors(best_node):
475
+ if neighbor in F.nodes:
476
+ F.add_edge(best_node, neighbor, weight=G[best_node][neighbor]['weight'])
477
+ else:
478
+
479
+ # Check if the graph is connected
480
+ if not nx.is_connected(F):
481
+ # Find the largest connected component
482
+ largest_component = max(nx.connected_components(F), key=len)
483
+ # Create a new graph with only the largest connected component
484
+ F = F.subgraph(largest_component)
485
+ # Print the number of unique neurons in the new graph
486
+ print("The graph is not fully connected. Only the largest connected component is considered.")
487
+ print("Number of unique neurons in the biggest element:", len(F))
488
+
489
+ if biases is not None:
490
+ theta = sorted_biases[:len(F)]
491
+
492
+ F = F.copy()
493
+
494
+ if not '2' in mode:
495
+
496
+ # Add neurons connected to F from G according to the order in sorted_neurons until num_neurons is reached
497
+ for neuron_id in sorted_neurons:
498
+ if len(F.nodes) >= num_neuron:
499
+ break
500
+ if neuron_id not in F.nodes:
501
+ for neighbor in G.neighbors(neuron_id):
502
+ if neighbor in F.nodes:
503
+ F.add_node(neuron_id)
504
+ F.add_edge(neuron_id, neighbor, weight=G[neuron_id][neighbor]['weight'])
505
+ if biases is not None:
506
+ theta += [biases[neuron_id]]
507
+ break
508
+ print("Number of unique neurons after adding neighbors:", len(F))
509
+
510
+ elif 'proportional_selection' in mode:
511
+
512
+ # Find the largest connected component
513
+ if G.is_directed():
514
+ largest_component = max(nx.weakly_connected_components(G), key=len)
515
+ else:
516
+ largest_component = max(nx.connected_components(G), key=len)
517
+ # Create a new graph with only the largest connected component
518
+ G = G.subgraph(largest_component)
519
+
520
+ # Remove keys from data_dict that are no longer in G
521
+ data_dict = {k: v for k, v in data_dict.items() if k in G.nodes()}
522
+
523
+ if num_neu > len(G.nodes()):
524
+ print(f"Number of neurons requested is greater than the number of neurons in the graph, setting number of neuron to {G.nodes()}")
525
+ return None
526
+
527
+ class_count = Counter(data_dict.values())
528
+ D = []
529
+ nodes_to_keep = set()
530
+ for key_idx, key in enumerate(class_count.keys()):
531
+ fraction = class_count[key] / len(data_dict)
532
+ target_class_ids = [k for k, v in data_dict.items() if v == key]
533
+
534
+ edge_counts = {neuron: G.degree(neuron) for neuron in target_class_ids}
535
+ try:
536
+ sorted_target_class_ids = sorted(target_class_ids, key=lambda neuron: edge_counts[neuron], reverse=True)
537
+ except:
538
+ print(f"Class {key} has no neurons in the graph")
539
+ num_neuron = num_neu
540
+ D_temp = G.subgraph(sorted_target_class_ids[:int(np.ceil(fraction*num_neuron))]).copy()
541
+ D += [D_temp]
542
+ for node in D_temp.nodes():
543
+ nodes_to_keep.add(node)
544
+
545
+ F = G.subgraph(list(nodes_to_keep)).copy()
546
+
547
+ is_conn = nx.is_weakly_connected(F) if F.is_directed() else nx.is_connected(F)
548
+ if not is_conn:
549
+ print("Graph not fully connected, quickly connecting the components with synthetic edges")
550
+ components = list(nx.weakly_connected_components(F) if F.is_directed() else nx.connected_components(F))
551
+
552
+ # Sort components by size descending
553
+ components.sort(key=len, reverse=True)
554
+
555
+ # Connect all smaller components to the largest one with a random weak edge
556
+ largest_comp = list(components[0])
557
+ for i in range(1, len(components)):
558
+ u = np.random.choice(largest_comp)
559
+ v = np.random.choice(list(components[i]))
560
+ # Add a weak directed edge
561
+ F.add_edge(u, v, weight=0.01)
562
+
563
+ print("Pruning components")
564
+
565
+ # Check the number of nodes in F
566
+ while len(F.nodes()) > num_neuron:
567
+ # Find the least connected node
568
+ sorted_nodes = sorted(F.nodes, key=lambda node: F.degree(node))
569
+ for node in sorted_nodes:
570
+ F_tentative = F.copy()
571
+ F_tentative.remove_node(node)
572
+ is_conn_tentative = nx.is_weakly_connected(F_tentative) if F_tentative.is_directed() else nx.is_connected(F_tentative)
573
+ if is_conn_tentative:
574
+ F = F_tentative
575
+ break
576
+ print(f"\rCurrent number of nodes: {len(F.nodes())}", end='', flush=True)
577
+
578
+ print("Adding components")
579
+
580
+ while len(F.nodes()) < num_neuron:
581
+ # Find the node in G that is most connected to nodes already in F
582
+ candidate_nodes = set(G.nodes()) - set(F.nodes())
583
+ best_node = max(candidate_nodes, key=lambda node: len(set(G.neighbors(node)) & set(F.nodes())))
584
+ F.add_node(best_node)
585
+ for neighbor in G.neighbors(best_node):
586
+ if neighbor in F.nodes:
587
+ F.add_edge(best_node, neighbor, weight=G[best_node][neighbor]['weight'])
588
+
589
+ node_ids = list(F.nodes())
590
+
591
+
592
+ if biases is not None:
593
+ theta = np.array([biases[nrn] for nrn in node_ids])
594
+
595
+
596
+ else:
597
+ raise ValueError(f"Invalid selection criterion mode: {mode}")
598
+
599
+ if biases is None:
600
+ theta = None
601
+
602
+ return F, theta
603
+
604
+ def min_node_connected_subgraph(G, components):
605
+ """
606
+ Finds the minimal set of additional nodes needed to connect all given components in G.
607
+
608
+ Parameters:
609
+ G (networkx.Graph): The input graph.
610
+ components (list of sets): Each set contains nodes forming a component.
611
+
612
+ Returns:
613
+ networkx.Graph: The minimal connected subgraph with the fewest extra nodes.
614
+ """
615
+ # Step 1: Identify component representative nodes
616
+ component_representatives = [next(iter(comp)) for comp in components]
617
+
618
+ # Step 2: Build a shortest-path metric graph based on node count
619
+ metric_graph = nx.Graph()
620
+ shortest_paths = {}
621
+
622
+ undirected_G = G.to_undirected(as_view=True) if G.is_directed() else G
623
+
624
+ for u, v in itertools.combinations(component_representatives, 2):
625
+ try:
626
+ # First try directed path
627
+ path = nx.shortest_path(G, source=u, target=v)
628
+ except nx.NetworkXNoPath:
629
+ try:
630
+ # Try the reverse directed path
631
+ path = nx.shortest_path(G, source=v, target=u)
632
+ except nx.NetworkXNoPath:
633
+ # Fallback to undirected path
634
+ try:
635
+ path = nx.shortest_path(undirected_G, source=u, target=v)
636
+ except nx.NetworkXNoPath:
637
+ continue # No path at all
638
+ metric_graph.add_edge(u, v, weight=len(path) - 1)
639
+ shortest_paths[(u, v)] = path
640
+
641
+ # Step 3: Compute MST on the metric graph to ensure minimal connectivity
642
+ mst = nx.minimum_spanning_tree(metric_graph, weight="weight")
643
+
644
+ # Step 4: Extract corresponding paths from the original graph
645
+ added_nodes = set()
646
+ subgraph_edges = set()
647
+
648
+ for u, v in mst.edges:
649
+ path = shortest_paths[(u, v)]
650
+ for i in range(len(path) - 1):
651
+ n1 = path[i]
652
+ n2 = path[i+1]
653
+ added_nodes.update([n1, n2])
654
+ if G.has_edge(n1, n2):
655
+ subgraph_edges.add((n1, n2))
656
+ elif G.has_edge(n2, n1):
657
+ subgraph_edges.add((n2, n1))
658
+
659
+ # Step 5: Construct the minimal connected subgraph
660
+ H = G.edge_subgraph(subgraph_edges).copy()
661
+
662
+ return H
663
+
664
+
665
+
666
+ def create_csr_matrix(size, target_sparsity, data_rvs):
667
+ density = 1 - target_sparsity
668
+ num_nonzero_elements = int(size * size * density)
669
+
670
+ # Generate random row and column indices for the non-zero elements
671
+ row_indices = np.random.randint(0, size, num_nonzero_elements)
672
+ col_indices = np.random.randint(0, size, num_nonzero_elements)
673
+
674
+ # Generate random values using the provided data_rvs function
675
+ data = data_rvs(num_nonzero_elements)
676
+
677
+ # Create the CSR matrix
678
+ csr_matrix = scipy.sparse.csr_matrix((data, (row_indices, col_indices)), shape=(size, size))
679
+
680
+ return csr_matrix
681
+
682
+
683
+ def is_fully_connected(W):
684
+ # Convert the sparse matrix to a NetworkX graph
685
+ graph = nx.from_scipy_sparse_array(W, create_using=nx.DiGraph if scipy.sparse.isspmatrix_csr(W) else nx.Graph)
686
+
687
+ # Check if the graph is strongly connected (for directed graphs) or connected (for undirected graphs)
688
+ if isinstance(graph, nx.DiGraph):
689
+ return nx.is_strongly_connected(graph)
690
+ else:
691
+ return nx.is_connected(graph)