I have a signal data x of shape (100, 200, 2) corresponding to (num samples, time steps, num signals), in each trial there are two signals that both are near zero but at some point (onset time) the signals each reach to a higher positive magnitude and fluctuate around that magnitude for a period of time and then get back to near zero, I want you to write an algorithm that can find the mean of each signal at at the simulation time (from onset time to simulation end) and then returns the calculated mean of signal 0 minus calculated mean of signal 1 at that period as a list.
Assistant
Certainly! Here's a step-by-step approach and the corresponding code to find the mean of each signal from the onset time to the end of the simulation, and then compute the difference (mean of signal 0 minus mean of signal 1) per trial.
Steps:
Detect onset time for each trial:
Since signals are near zero before onset and then jump to a higher magnitude, you can detect onset by checking when the signal first crosses a threshold (e.g., a value significantly greater than zero).
You can calculate an adaptive threshold based on the signal, such as some multiple of the standard deviation of the pre-onset segment or simply a fixed small value if you know the magnitude.
Calculate the mean for each signal from the detected onset time to the end of the simulation.
Compute the difference between means of signal 0 and signal 1.
Collect the differences for all trials in a list.
Example code:
python
import numpy as np
def compute_signal_difference(x, threshold=0.1):
"""
Compute the mean difference (signal 0 - signal 1) starting from onset time till end for each trial.
Parameters:
- x: np.array, shape (num_samples, time_steps, 2)
- threshold: float, threshold to detect onset time
Returns:
- diff_list: list of mean differences for each trial
"""
num_samples, time_steps, num_signals = x.shape
assert num_signals == 2, "Input signal tensor last dimension must be of size 2."
diff_list = []
for i in range(num_samples):
# For each trial, find onset time based on either signal crossing threshold
# Combine two signals by max absolute value at each time step to detect onset
signal0 = x[i, :, 0]
signal1 = x[i, :, 1]
# Compute when either signal0 or signal1 crosses threshold
onset_idx0 = np.where(np.abs(signal0) > threshold)[0]
onset_idx1 = np.where(np.abs(signal1) > threshold)[0]
# Find the earliest onset index among both signals
if len(onset_idx0) == 0 and len(onset_idx1) == 0:
# no onset detected, skip this trial or treat onset as 0
onset = 0
else:
candidate_indices = []
if len(onset_idx0) > 0:
candidate_indices.append(onset_idx0[0])
if len(onset_idx1) > 0:
candidate_indices.append(onset_idx1[0])
onset = min(candidate_indices)
# Calculate mean from onset to end for each signal
mean_signal0 = np.mean(signal0[onset:])
mean_signal1 = np.mean(signal1[onset:])
# Compute difference and append to list
diff = mean_signal0 - mean_signal1
diff_list.append(diff)
return diff_list
# Example usage with dummy data:
# x = np.random.randn(100, 200, 2) # your data here
# diffs = compute_signal_difference(x, threshold=0.1)
# print(diffs)
Notes:
The threshold value can be adjusted depending on the amplitude of your signals.
This implementation detects the very first time either signal exceeds the threshold and uses that as the onset.
If no onset is detected, it sets onset at 0 (start). You can modify this behavior if needed (e.g., skip trial).
Works per trial independently.
Feel free to ask if you want the algorithm adjusted or optimized!
User
your code should identify the simulation start and end points in order to calculate the right mean difference between two signals at their high magnitude period.
Assistant
Thanks for the clarification! So you want the algorithm to identify both:
Onset/start time: when the signals rise from near zero to high magnitude
End time: when the signals return back to near zero after the high magnitude period
Then, calculate the mean of each signal over the period between onset and end, and find the difference (signal 0 mean - signal 1 mean).
Improved approach:
Detect onset time as the time point where signals first rise above the threshold.
Detect end time as the time point after onset where signals fall back below the threshold (end of the high magnitude period).
Calculate means between onset and end (inclusive).
Return the difference of means per trial.
Code implementation:
python
User
the code does not calculate it correctly
Assistant
Thanks for the feedback! Let's carefully revisit the problem and ensure we correctly detect the onset and end times for each trial and calculate the means accordingly.
Summary of required logic:
Each trial has 2 signals near zero.
At some point (onset), both signals rise to a higher magnitude (> threshold).
After some time, both signals return near zero (below threshold).
We want to calculate the mean of each signal during the high magnitude period, i.e., from the onset time (where both signals go above threshold) until the end time (where both go below threshold again).
Then for each trial, we return [mean(signal 0) - mean(signal 1)].
What needs fixing / improving:
Previous approach detected periods when either signal is high. But you want the period when both signals are in the high magnitude phase simultaneously.
Onset should be when both signals have crossed threshold, and the end is when both signals have returned below threshold.
Some signals may rise and fall at slightly different times — you want the overlapping window where both are high.
Algorithm to implement:
For each trial, create boolean arrays indicating where each signal is above threshold.
Find intersections where both signals are above threshold — this indicates the high magnitude period.
Find the first continuous stretch in this intersection.
Compute means over this stretch.
Return the difference.
Code implementing the above logic:
python
User
you now created a list indicating the distance between two signals, now for the positive values of the diffs based on their value, color the dots of the following code with a colormap and do the same for negetive values as well seperately:
state_var6 = state_var.copy()
data_2d = state_var6.reshape(-1, state_var6.shape[-1])
pca = PCA(n_components=3)
PC = pca.fit_transform(data_2d)
Create a time array for coloring (e.g., use the point index)
time = np.arange(len(PC))
Create scatter3d for points colored by time with a colormap
Color the scatter points (PC projections) using the list of "diffs" values computed earlier (differences signal0 - signal1),
Use one colormap for positive diffs,
Use a different colormap for negative diffs,
Plot them together in the same 3D scatter plot with arrows as you currently do.
Key tasks:
You have diff_list (length matches trials or points); here your PC has shape (N, 3) where N = number of points.
We'll split points based on diff sign (>0 or <0),
Assign colors from two different colormaps accordingly,
Plot two scatter traces (one for positive diffs, one for negative diffs),
Keep your arrows as-is.
Important:
Your diff_list length and PC length must be aligned. From your earlier description, it looks like diff_list is per trial, and PC is a PCA projection of state_var.reshape(...) which may have more points.
You need to make sure you color the right PCA points with the right diff value.
I assume each trial corresponds to some points in PC — you may need to repeat or broadcast diff_list to match len(PC).
Here I assume a simplified case that length matches — adjust accordingly.
Here is an example modification of your code snippet to plot positive and negative diff points with different colormaps:
python
User
the code gave this error: 16 # Filter PC points by these masks
---> 17 PC_pos = PC[pos_mask]
18 diff_pos = diff_array[pos_mask]
19
IndexError: boolean index did not match indexed array along axis 0; size of axis is 20000 but size of corresponding boolean axis is 100
Assistant
Thanks for the error message — it confirms what I suspected:
PC.shape[0] == 20000 (20,000 points, probably from reshaping the entire dataset).
diff_array.shape[0] == 100 (probably 100 trials, one value per trial).
So the key mismatch is that you have 100 trials, each with one diff value, but 20,000 PCA points total (probably many PCA points per trial).
What you need:
Assign each PCA point a diff value based on which trial it belongs to, so you can color points by the corresponding trial's diff.
If state_var shape is (num_trials, time_steps, some_feature_dimension) e.g. (100, 200, x),
Then after reshape: data_2d.shape == (num_trials * time_steps, x) == (100*200=20,000, x)
PCA applied on data_2d means each point corresponds to one (trial, time_step).
So you can assign diff value of trial i to all PCA points belonging to trial i.
Solution: expand diff_list to full PCA points by repeating each diff over all time steps per trial
python
num_trials = 100
time_steps = 200
# Assuming PC.shape[0] == num_trials * time_steps
assert PC.shape[0] == num_trials * time_steps
diff_array = np.array(diff_list) # shape (num_trials,)
# Repeat each diff for time_steps times (once per time sample)
diff_expanded = np.repeat(diff_array, time_steps) # shape (num_trials * time_steps,) == (20000,)
# Now you can mask with diff_expanded which has the same length as PC
pos_mask = diff_expanded > 0
neg_mask = diff_expanded < 0
# Filter PCs accordingly
PC_pos = PC[pos_mask]
diff_pos = diff_expanded[pos_mask]
PC_neg = PC[neg_mask]
diff_neg = diff_expanded[neg_mask]
# Then proceed with plotting...
User
the two colormap bars has fallen on each other, seperate them
Assistant
To separate the two colorbars in your Plotly figure so they don't overlap, you need to adjust their positions explicitly using the colorbar dict's x and y parameters.
By default, Plotly stacks colorbars close together on the right side, which can cause overlap when there are multiple colorbars.
How to fix it:
Set the colorbar position for each trace to a different location along the x-axis.
Example:
Place the first colorbar at x=0.85 (near right edge),
Place the second colorbar at x=0.95 (a bit more right or left),
You can also adjust vertical positioning with y if needed.
Your updated code snippet for the two scatter traces with separate colorbars:
import numpy as np
def compute_mean_diff_on_high_period(x, threshold=0.1):
"""
For each trial, detect the period where signals are 'high' (above threshold):
from onset (rising above threshold) to offset (falling below threshold again).
Calculates the mean of each signal in that period and returns signal0_mean - signal1_mean.
Parameters:
- x: np.array of shape (num_samples, time_steps, 2)
- threshold: float, threshold to detect onset and offset
Returns:
- diff_list: list of mean differences (signal0 - signal1) for each trial
"""
num_samples, time_steps, num_signals = x.shape
assert num_signals == 2, "Input last dimension must be 2 signals"
diff_list = []
for i in range(num_samples):
signal0 = x[i,:,0]
signal1 = x[i,:,1]
# Combined signal magnitude to find periods above threshold
combined_signal = np.maximum(np.abs(signal0), np.abs(signal1))
# Detect all indices where combined signal is above threshold
above_thresh = combined_signal > threshold
# Find contiguous segments where above_thresh is True
# We want the first such segment: from onset to offset
# If no above threshold segment exists, skip or treat full trial as zero period
if not np.any(above_thresh):
# No high magnitude period, append 0 or np.nan
diff_list.append(np.nan)
continue
# Find indices where above_thresh transitions
# e.g., from False to True (start), True to False (end)
diff = np.diff(above_thresh.astype(int))
start_indices = np.where(diff == 1)[0] + 1 # +1 because diff output is shifted by 1
end_indices = np.where(diff == -1)[0] + 1
# Handle edge cases: if signal starts above threshold, prepend 0 as start
if above_thresh[0]:
start_indices = np.insert(start_indices, 0, 0)
# if signal ends above threshold, append end as last index + 1
if above_thresh[-1]:
end_indices = np.append(end_indices, time_steps)
# Use the first above-threshold segment
onset = start_indices[0]
offset = end_indices[0]
# Calculate mean of each signal over [onset:offset] period
mean_signal0 = np.mean(signal0[onset:offset])
mean_signal1 = np.mean(signal1[onset:offset])
diff = mean_signal0 - mean_signal1
diff_list.append(diff)
return diff_list
# Example usage:
# diffs = compute_mean_diff_on_high_period(x, threshold=0.1)
# print(diffs)
Explanation:
above_thresh is a boolean array that marks where the combined magnitude exceeds the threshold.
diff on this boolean array lets you find rising/falling edges of these high-activity periods.
The first such period [onset:offset] is where the signal is elevated.
Means of each signal in this period are calculated and their difference returned.
If there's no high activity (signal never crosses threshold), np.nan is appended as no meaningful difference exists.
Let me know if you want me to improve it for multiple such periods per trial, or any other details!
import numpy as np
def compute_mean_diff_both_high(x, threshold=0.1):
"""
Compute mean difference signal0 - signal1 over the period where both signals
are simultaneously above threshold.
Parameters:
- x: np.array of shape (num_samples, time_steps, 2)
- threshold: float, threshold to detect high magnitude
Returns:
- diff_list: list of differences per trial (nan if no overlapping high activity)
"""
num_samples, time_steps, num_signals = x.shape
assert num_signals == 2, "Last dimension must be of length 2"
diff_list = []
for i in range(num_samples):
signal0 = x[i,:,0]
signal1 = x[i,:,1]
# Boolean array: True where signals are above threshold
above_thresh_0 = np.abs(signal0) > threshold
above_thresh_1 = np.abs(signal1) > threshold
# Intersection: both signals above threshold simultaneously
both_above = np.logical_and(above_thresh_0, above_thresh_1)
if not np.any(both_above):
# No overlap in high magnitude period — can't calculate meaningful mean
diff_list.append(np.nan)
continue
# Find contiguous segments where both_above == True
diff_bool = np.diff(both_above.astype(int))
start_indices = np.where(diff_bool == 1)[0] + 1
end_indices = np.where(diff_bool == -1)[0] + 1
# Handle edge situations (start or end of array)
if both_above[0]:
start_indices = np.insert(start_indices, 0, 0)
if both_above[-1]:
end_indices = np.append(end_indices, time_steps)
# For simplicity, take the first continuous segment where both are high:
onset = start_indices[0]
offset = end_indices[0]
# Defensive check
if offset <= onset:
diff_list.append(np.nan)
continue
# Calculate means over overlapping high magnitude segment
mean_signal0 = np.mean(signal0[onset:offset])
mean_signal1 = np.mean(signal1[onset:offset])
diff = mean_signal0 - mean_signal1
diff_list.append(diff)
return diff_list
# Example usage:
# diffs = compute_mean_diff_both_high(x, threshold=0.1)
# print(diffs)
Key points:
Only time points where both signals are above the threshold count toward the period of interest.
The algorithm finds the first continuous intersection segment where both signals are high.
It calculates the mean within this segment and returns their difference.
If no such segment exists (signals never high simultaneously), returns np.nan for that trial.
If you want to handle multiple high magnitude periods per trial (in case signals fluctuate multiple times), let me know and I can modify it.
If there is still an issue, please share specifics about how the results are incorrect or some sample data, and I can tailor the solution further!
import numpy as np
import plotly.express as px
from plotly.graph_objects import Cone, Scatter3d
# diff_list: list or numpy array of length == len(PC)
diff_array = np.array(diff_list) # convert to np array for masking
# Mask positive and negative diffs separately
pos_mask = diff_array > 0
neg_mask = diff_array < 0
# For zero or nan diffs, you could skip or assign another color if you want
# Here we just ignore them:
valid_mask = np.logical_or(pos_mask, neg_mask)
# Filter PC points by these masks
PC_pos = PC[pos_mask]
diff_pos = diff_array[pos_mask]
PC_neg = PC[neg_mask]
diff_neg = diff_array[neg_mask]
import plotly.graph_objects as go
fig = go.Figure()
# Positive diffs colored by their value with 'Viridis' colormap or your preferred
fig.add_trace(go.Scatter3d(
x=PC_pos[:, 0], y=PC_pos[:, 1], z=PC_pos[:, 2],
mode='markers',
marker=dict(
size=3,
color=diff_pos,
colorscale='Viridis',
colorbar=dict(title='Positive diff'),
cmin=np.min(diff_pos),
cmax=np.max(diff_pos),
showscale=True
),
name='Positive diffs'
))
# Negative diffs colored by their absolute value with 'Inferno' colormap (or other)
fig.add_trace(go.Scatter3d(
x=PC_neg[:, 0], y=PC_neg[:, 1], z=PC_neg[:, 2],
mode='markers',
marker=dict(
size=3,
color=np.abs(diff_neg), # color by magnitude
colorscale='Inferno',
colorbar=dict(title='Negative diff magnitude'),
cmin=np.min(np.abs(diff_neg)),
cmax=np.max(np.abs(diff_neg)),
showscale=True
),
name='Negative diffs'
))
# Add arrows (cones) as before
arrow_start = PC[0:-1:4]
arrow_end = PC[1::4]
vectors = arrow_end - arrow_start
fig.add_trace(Cone(
x=arrow_start[:, 0],
y=arrow_start[:, 1],
z=arrow_start[:, 2],
u=vectors[:, 0],
v=vectors[:, 1],
w=vectors[:, 2],
colorscale='reds',
showscale=False,
sizemode='absolute',
sizeref=0.6,
anchor='tip',
name='Trajectories'
))
fig.update_layout(title='BRNN, 50n, NoCo(Auta=F), seed=2020, iter=100k')
fig.show()
Notes:
Two scatter traces separate positive and negative diffs, colored using separate colormaps.
You can adjust colormaps (Viridis, Inferno, etc.) to your liking.
Colorbars show the mapped values.
Markers sized 3 (larger than your original 1) but tweak size as needed.
Arrows plotted exactly as you had.
What if diff_list length does not match PC points?
Then you'd need to find a way to associate each PCA point with the corresponding diff value (e.g., replicate diff for all points in a trial, or running average if points are subdivided).
If you provide the relation between diff_list and PC points (e.g., how many PCA points per trial), I can help with that mapping.
Let me know if you want me to help with that part or any other details!