Linux, Python, C ++, Brain2 and errors.

Associate
Joined
18 Aug 2020
Posts
26
Location
London
Hi.

I try to make and run first time AI Neural Network on my computer.
Knowledge Python is basic.

I'm using Linux Ubuntu.

I install whole in system using apt.
When show communicate about pip, then I'm doing that.
[Is a lot of problems with right file names and compatibility.]

I try to configure to direction in home catalogue [advice from Gemini].
Port 65432 is unblocked in firewall.

Helpful is Gemini, but can't solve problems what I have now.

Please help me with that.

Python engine:

import brian2
import socket
import numpy as np

from brian2 import Neuron, Eq


# Define neuron equations
eqs = '''
dv/dt = (I - gl*(v-Vl) - gNa*(m**3)*h*(v-VNa) - gK*(n**4)*(v-VK)) / Cm
dm/dt = alpha_m(v)*(1-m) - beta_m(v)*m
dh/dt = alpha_h(v)*(1-h) - beta_h(v)*h
dn/dt = alpha_n(v)*(1-n) - beta_n(v)*n
'''

# Define parameters and functions for the equations (replace with actual definitions)
Vl = -65*mV # Leak reversal potential
VNa = 50*mV # Sodium reversal potential
VK = -70*mV # Potassium reversal potential
Cm = 1*uF/cm2 # Membrane capacitance
gl = 0.3e-3*siemens/cm2 # Leak conductance
gNa = 120e-3*siemens/cm2 # Sodium conductance
gK = 36e-3*siemens/cm2 # Potassium conductance

# Define neuron object using custom equations
neurons = Neuron(eqs=eqs, methods={'alpha_m': alpha_m, 'beta_m': beta_m, 'alpha_h': alpha_h, 'beta_h': beta_h, 'alpha_n': alpha_n, 'beta_n': beta_n}) # Include all required methods


# Standard variables
num_neurons = 1000
duration = 1000 # Simulation duration in milliseconds

# **(Replace with your implementation)**
# Hodgkin-Huxley neuron model with STDP learning (replace with your specific neuron and synapse definitions)
# ... (Include your specific code for defining synapses and learning rules)


# Data variables
average_firing_rates = []
average_synaptic_weights = []

# Recording functions
def record_firing_rates():
global average_firing_rates
average_firing_rates.append(np.mean(spike_monitor.count / (duration * 1000))) # Convert to Hz

def record_synaptic_weights():
global average_synaptic_weights
weights = synapses.weight # Assuming you have a 'synapses' object with weight attribute
average_synaptic_weights.append(np.mean(weights))

# Network monitors
spike_monitor = brian2.SpikeMonitor(source=neurons)
brian2.NetworkOperation(record_firing_rates, dt=10*brian2.ms) # Record every 10 ms
brian2.NetworkOperation(record_synaptic_weights, dt=100*brian2.ms) # Record every 100 ms

# Network socket setup (replace with your IP address and port)
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))

# Run the simulation
brian2.run(duration * brian2.ms)

# Send data to C++ program (replace with IPC if on the same machine)
data = {'firing_rates': average_firing_rates, 'synaptic_weights': average_synaptic_weights}
data_str = str(data) # Convert data to string for sending
s.sendall(data_str.encode())

# Close the socket
s.close()

I have too second code in C++:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sstream>
#include <jsoncpp/json.h> // Include JSON library for parsing

int main() {
// Standard variables
int port = 65432; // Port used by Brian 2 simulation
std::string host = "localhost"; // Replace with IP address of Brian 2 (if not localhost)

// Socket setup
int sockfd;
struct sockaddr_in servaddr;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}

memset(&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = inet_addr(host.c_str());

if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) {
perror("connection failed");
exit(EXIT_FAILURE);
}

// Data receiving and processing loop
while (1) {
char buffer[1024]; // Adjust buffer size based on data volume
int n = recv(sockfd, buffer, sizeof(buffer), 0);
if (n == 0) {
printf("Connection closed by server\n");
break;
} else if (n == -1) {
perror("recv failed");
exit(EXIT_FAILURE);
}

// Parse received data (assuming JSON format)
std::string data_str(buffer, n);
Json::Reader reader;
Json::Value data;
if (!reader.parse(data_str, data)) {

Error:

Python 3.12.3 (main, Apr 10 2024, 05:33:47) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.

= RESTART: /home/peter/python/ai_neural_brain_2/engine_brain_2.py =
ERROR Brian 2 encountered an unexpected error. If you think this is a bug in Brian 2, please report this issue either to the discourse forum at <http://brian.discourse.group/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /tmp/brian_debug_vkzoele7.log Additionally, you can also include a copy of the script that was run, available at: /tmp/brian_script_fgiuug_k.py Thanks! [brian2]
Traceback (most recent call last):
File "/usr/lib/python3.12/idlelib/run.py", line 580, in runcode
exec(code, self.locals)
File "/home/peter/python/ai_neural_brain_2/engine_brain_2.py", line 5, in <module>
from brian2 import Neuron, Eq
ImportError: cannot import name 'Neuron' from 'brian2' (/usr/lib/python3/dist-packages/brian2/__init__.py)
 
Last edited:
One of your errors is that you’re failing to call Neuron, Eq. Do they exist within Brian2? Checking the documentation you can try replacing it with:

Python:
from brian2 import *

Which will import everything, and you can see if that’s the issue.

ERROR Brian 2 encountered an unexpected error. If you think this is a bug in Brian 2, please report this issue either to the discourse forum at <http://brian.discourse.group/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /tmp/brian_debug_qs10hpz8.log Additionally, you can also include a copy of the script that was run, available at: /tmp/brian_script_lhty_uks.py Thanks! [brian2]
Traceback (most recent call last):
File "/usr/lib/python3.12/idlelib/run.py", line 580, in runcode
exec(code, self.locals)
File "/home/peter/python/ai_neural_brain_2/engine_brain_2.py", line 27, in <module>
neurons = Neuron(eqs=eqs, methods={'alpha_m': alpha_m, 'beta_m': beta_m, 'alpha_h': alpha_h, 'beta_h': beta_h, 'alpha_n': alpha_n, 'beta_n': beta_n}) # Include all required methods
^^^^^^
NameError: name 'Neuron' is not defined
sudo apt install python3-brian
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3-brian is already the newest version (2.5.4-4build1).
0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded.


sudo apt-get reinstall python3-brian
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 31 not upgraded.
Need to get 0 B/622 kB of archives.
After this operation, 0 B of additional disk space will be used.
(Reading database ... 336660 files and directories currently installed.)
Preparing to unpack .../python3-brian_2.5.4-4build1_all.deb ...
Unpacking python3-brian (2.5.4-4build1) over (2.5.4-4build1) ...
Setting up python3-brian (2.5.4-4build1) ...


python -m pip install matplotlib pytest ipython notebook
Command 'python' not found, did you mean:
command 'python3' from deb python3
command 'python' from deb python-is-python3


python3 -m pip install matplotlib pytest ipython notebook
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.

If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

See /usr/share/doc/python3.12/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.


python -m pip install brian2tools
Command 'python' not found, did you mean:
command 'python3' from deb python3
command 'python' from deb python-is-python3


python3 -m pip install brian2tools
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.

If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

See /usr/share/doc/python3.12/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.
 
Last edited:
I think you need to understand how Python works a little bit better, and also read the Brain2 documentation reference to see how this is supposed to look. LLM will not help you unless you can explicitly tell it what the problem is and walk through it with it. I haven't used this library before, but looking at the examples

From a very quick Google, you might want to use NeuronGroup, I spun up a quick pyenv and installed Brain2 and Plot and managed to run the example:


I also successfully got ChatGPT to spit out a quick and simple Neuron example which runs perfectly.

Python:
import brian2 as b2
import matplotlib.pyplot as plt

# Neuron parameters
Cm = 1 * b2.ufarad  # membrane capacitance
gl = 5 * b2.nsiemens  # leak conductance
El = -65 * b2.mV  # leak reversal potential
V_th = -50 * b2.mV  # spike threshold
V_reset = -65 * b2.mV  # reset potential after spike

# Neuron model equations
eqs = '''
dv/dt = (gl * (El - v) + I) / Cm : volt
I : amp  # input current
'''

# Create a single neuron
neuron = b2.NeuronGroup(1, eqs, threshold='v > V_th', reset='v = V_reset', method='exact')
neuron.v = El  # initial condition

# Create a constant input current
input_current = 200 * b2.pamp  # amplitude of the input current
neuron.I = input_current

# Record the membrane potential
monitor = b2.StateMonitor(neuron, 'v', record=True)

# Run the simulation for 100 ms
duration = 100 * b2.ms
b2.run(duration)

# Plot the membrane potential over time
plt.figure(figsize=(10, 4))
plt.plot(monitor.t / b2.ms, monitor.v[0] / b2.mV)
plt.xlabel('Time (ms)')
plt.ylabel('Membrane potential (mV)')
plt.title('Membrane potential of a single neuron over time')
plt.grid(True)
plt.show()

Note again how it uses NeuronGroup. I'd focus around there.
 
I have fun with that.
1 time I almost blow up CPU.

Python:
import brian2 as b2
import matplotlib.pyplot as plt
from IPython.display import Image, display
import multiprocessing

# Set the number of threads to the number of CPU cores
b2.prefs.devices.cpp_standalone.openmp_threads = multiprocessing.cpu_count()

# Neuron parameters
Cm = 1000 * b2.ufarad  # membrane capacitance
gl = 500 * b2.nsiemens  # leak conductance
El = -65 * b2.mV  # leak reversal potential
V_th = -50 * b2.mV  # spike threshold
V_reset = -65 * b2.mV  # reset potential after spike

# Synapse parameters
tau_syn = 1000 * b2.ms  # synaptic time constant
E_syn = 0 * b2.mV  # synaptic reversal potential
w_syn = 0.1 * b2.nS  # synaptic weight

# Neuron model equations
eqs = '''
dv/dt = (gl * (El - v) + I + Isyn) / Cm : volt
I : amp  # input current
Isyn : amp  # synaptic current
'''

# Create a group of neurons
num_neurons = 1000000 #human 100 000 000 000
neuron = b2.NeuronGroup(num_neurons, eqs, threshold='v > V_th', reset='v = V_reset', method='exact')
neuron.v = El  # initial condition

# Create synapses
synapses = b2.Synapses(neuron, neuron,
                       model='''w : siemens
                                Isyn_post = w * (v_pre - v_post) : amp (summed)''',
                       on_pre='Isyn_post += w * (E_syn - v_post)')
# connect each neuron to 10% of the other neurons
synapses.connect(condition='i != j', p=1000)
synapses.w = w_syn

# Create a constant input current
input_current = 200 * b2.pamp  # amplitude of the input current
neuron.I = input_current

# Record the membrane potential
monitor = b2.StateMonitor(neuron, 'v', record=True)

# Run the simulation for 100 ms
duration = 1000 * b2.ms
b2.run(duration)

# Plot the membrane potential over time for the first neuron
plt.figure(figsize=(100, 10))
plt.plot(monitor.t / b2.ms, monitor.v[0] / b2.mV)
plt.xlabel('Time (ms)')
plt.ylabel('Membrane potential (mV)')
plt.title('Membrane potential of the first neuron over time')
plt.grid(True)
plt.show()

# Optionally, you can also plot the membrane potentials of other neurons
plt.figure(figsize=(100, 10))
for i in range(100):  # plot the first 5 neurons for better visualization
    plt.plot(monitor.t / b2.ms, monitor.v[i] / b2.mV, label=f'Neuron {i}')
plt.xlabel('Time (ms)')
plt.ylabel('Membrane potential (mV)')
plt.title('Membrane potentials of multiple neurons over time')
plt.legend()
plt.grid(True)
plt.show()

# Display the uploaded diagrams
display(Image)
 
At that, a moment works.
How make that to stage when I can talk with that?

Edit:

I install that:

sudo apt-get installpython3-charset-normalizer python3-pyaudio espeak-ng-espeak python3-espeak python3-pykml python3-charset-normalizer qt6-speech-speechd-plugin qt6-speech-flite-plugin qtspeech5-flite-plugin python3-guess-language python3-nltk python3-virtualenv python3-venv python3-charset-normalizer python3-virtualenv

pipx install SpeechRecognition python3-charset-normalizer pyttsx3

pip always have problems ...

The next stage will be virtualization of the person.
 
Last edited:
I try to use Vosk, but all time is:

Python 3.12.3 (main, Apr 10 2024, 05:33:47) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.

= RESTART: /home/peter/python/ai_neural_brain_2/engine_brain_2_11_neurons_group_and_synapses_talking.py
ERROR Brian 2 encountered an unexpected error. If you think this is a bug in Brian 2, please report this issue either to the discourse forum at <http://brian.discourse.group/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /tmp/brian_debug_vmaxybiq.log Additionally, you can also include a copy of the script that was run, available at: /tmp/brian_script_pehr7l4x.py Thanks! [brian2]
Traceback (most recent call last):
File "/usr/lib/python3.12/idlelib/run.py", line 580, in runcode
exec(code, self.locals)
File "/home/peter/python/ai_neural_brain_2/engine_brain_2_11_neurons_group_and_synapses_talking.py", line 6, in <module>
import vosk
ModuleNotFoundError: No module named 'vosk'

I make that:

peter@peter-ThinkPad-P51:~$ source /home/peter/venv/bin/activate
(venv) peter@peter-ThinkPad-P51:~$ source /home/peter/venv/bin/activate
(venv) peter@peter-ThinkPad-P51:~$ python3 -c "import vosk; print('Vosk successfully imported!')"
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ echo $(python3 -c "import vosk; print('Vosk successfully imported!')")
bash: !': event not found
bash: !': event not found
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ echo $(python3 -c "import vosk; print('Vosk successfully imported!')")
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ python3 -c "import vosk; print('Vosk successfully imported!')
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ echo $(python3 -c 'import vosk; print("Vosk successfully imported!")')
Vosk successfully imported!
(venv) peter@peter-ThinkPad-P51:~$

And:

sudo chmod 775 -R /home/peter/venv/*
sudo chmod 775 -R /home/peter/venv/
sudo chmod +x -R /home/peter/venv/
sudo chmod +x -R /home/peter/venv/*
sudo chown peter -R /home/peter/venv/*
sudo chown peter -R /home/peter/venv/

Nothing change.

Someone can help me with that?

Thanks.
 
I try to use Vosk, but all time is:

Code:
Python 3.12.3 (main, Apr 10 2024, 05:33:47) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.

= RESTART: /home/peter/python/ai_neural_brain_2/engine_brain_2_11_neurons_group_and_synapses_talking.py
ERROR      Brian 2 encountered an unexpected error. If you think this is a bug in Brian 2, please report this issue either to the discourse forum at <http://brian.discourse.group/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /tmp/brian_debug_vmaxybiq.log  Additionally, you can also include a copy of the script that was run, available at: /tmp/brian_script_pehr7l4x.py Thanks! [brian2]
Traceback (most recent call last):
  File "/usr/lib/python3.12/idlelib/run.py", line 580, in runcode
    exec(code, self.locals)
  File "/home/peter/python/ai_neural_brain_2/engine_brain_2_11_neurons_group_and_synapses_talking.py", line 6, in <module>
    import vosk
ModuleNotFoundError: No module named 'vosk'

I make that:

Code:
peter@peter-ThinkPad-P51:~$ source /home/peter/venv/bin/activate
(venv) peter@peter-ThinkPad-P51:~$ source /home/peter/venv/bin/activate
(venv) peter@peter-ThinkPad-P51:~$ python3 -c "import vosk; print('Vosk successfully imported!')"
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ echo $(python3 -c "import vosk; print('Vosk successfully imported!')")
bash: !': event not found
bash: !': event not found
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ echo $(python3 -c "import vosk; print('Vosk successfully imported!')")
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ python3 -c "import vosk; print('Vosk successfully imported!')
bash: !': event not found
(venv) peter@peter-ThinkPad-P51:~$ echo $(python3 -c 'import vosk; print("Vosk successfully imported!")')
Vosk successfully imported!
(venv) peter@peter-ThinkPad-P51:~$

And:

Code:
sudo chmod 775 -R /home/peter/venv/*
sudo chmod 775 -R /home/peter/venv/
sudo chmod +x -R /home/peter/venv/
sudo chmod +x -R /home/peter/venv/*
sudo chown peter -R /home/peter/venv/*
sudo chown peter -R /home/peter/venv/

Code:
set -H
echo "print('Hello, World!')" | python3
bash: !': event not found
set +H
echo "print('Hello, World!')" | python3
Hello, World!

Nothing change.

Someone can help me with that?

Thanks.
 
Last edited:
I have 2 catalogs:
- myenvy
- venv

I make back.

I copied both to self without replace and with replace.

Nothing change.

Is that same.

Code:
I make that again.
sudo chmod 775 -R /home/peter/venv/*
sudo chmod 775 -R /home/peter/venv/
sudo chmod +x -R /home/peter/venv/
sudo chmod +x -R /home/peter/venv/*
sudo chown peter -R /home/peter/venv/*
sudo chown peter -R /home/peter/venv/

sudo chmod 775 -R /home/peter/myenv/*
sudo chmod 775 -R /home/peter/myenv/
sudo chmod +x -R /home/peter/myenv/
sudo chmod +x -R /home/peter/myenv/*
sudo chown peter -R /home/peter/myenv/*
sudo chown peter -R /home/peter/myenv/
Code:
echo 'We are single quoted here!'
We are single quoted here!

echo "We are double quoted here!"
We are double quoted here!
 
Last edited:
Back
Top Bottom