-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheasyClock_v3.5.py
More file actions
2717 lines (2160 loc) · 105 KB
/
Copy patheasyClock_v3.5.py
File metadata and controls
2717 lines (2160 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Enable export of CWT time-resolved data.
import os
import sys
import shutil
import tempfile
import subprocess
import pandas as pd
import numpy as np
import colorsys
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pywt
import statsmodels.formula.api as smf
from statsmodels.stats.multitest import multipletests
from scipy.stats import kendalltau
from scipy.signal import find_peaks
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.ar_model import AutoReg,ar_select_order
from scipy.optimize import curve_fit
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QMessageBox, QInputDialog, QDialog, QVBoxLayout, QHBoxLayout,QComboBox,QFileDialog,QDialogButtonBox,QApplication,
QLabel, QPushButton, QTextEdit, QScrollArea, QWidget, QSizePolicy, QColorDialog,QLineEdit,QProgressDialog
)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Arial"
def generate_distinct_colors(n):
hsv_colors = [(i / n, 0.5, 0.95) for i in range(n)]
rgb_colors = [colorsys.hsv_to_rgb(*h) for h in hsv_colors]
return ['#%02x%02x%02x' % tuple(int(c * 255) for c in rgb) for rgb in rgb_colors]
def get_resource_path(filename):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, filename)
return os.path.join(os.path.abspath("."), filename)
def acrophase_to_hours(rad_phase, period=24):
hours = (rad_phase * period) / (2 * np.pi)
return hours % period
# ------------------------
# Python-JTK function
# ------------------------
def generate_triangle_template_time(times, period, lag, asymmetry=0.5):
"""
Generate a triangle template aligned to real timepoints.
`times`: array of time values
`period`: float, desired period in same units as time
`lag`: phase shift in time units (e.g., hours)
`asymmetry`: float between 0 and 1 indicating peak position in the cycle
"""
peak_time = asymmetry * period
template = np.zeros_like(times, dtype=float)
for i, t in enumerate(times):
t_mod = (t - lag) % period
if t_mod <= peak_time:
template[i] = t_mod / peak_time if peak_time != 0 else 1.0
else:
template[i] = (period - t_mod) / (period - peak_time) if period != peak_time else 0.0
return pd.Series(template).rank().values
def run_discrete_jtk(series, period_range=range(22, 27), lag_range=None, asymmetries=[0.5]):
"""
Run JTK using triangle templates aligned to actual timepoints (non-uniform supported).
Run triangle-based JTK_CYCLE with user-defined period and lag (acrophase) ranges.
"""
times = series.index.to_numpy()
y = series.rank().values
n = len(y)
best_p = 1.0
best_tau = 0.0
best_per = None
best_lag = None
best_asym = None
best_ref = None
test_results = []
for period in period_range:
lags = lag_range if lag_range else np.arange(0, period, 1)
for asym in asymmetries:
for lag in lags:
ref = generate_triangle_template_time(times, period, lag, asym)
tau, pval = kendalltau(y, ref)
test_results.append((pval, tau, period, lag, asym))
if pval < best_p:
best_p = pval
best_tau = tau
best_per = period
best_lag = lag
best_asym = asym
best_ref = ref
bonf_p = min(1.0, best_p * len(test_results))
amp = (np.percentile(series.values, 90) - np.percentile(series.values, 10)) / 2
acrophase = (
(best_lag + best_asym * best_per+ best_per / 2) % best_per if best_tau < 0
else (best_lag + best_asym * best_per) % best_per
)
return {
'P': round(best_p, 6),
'ADJ.P': round(bonf_p, 6),
'PER': round(best_per, 2),
'AMP': round(amp, 4),
'Acrophase': round(acrophase, 2),
'ASYM': round(best_asym, 2),
'TAU':round(best_tau, 2),
'LAG':round(best_lag, 2),
'Method': 'Python-JTK'
}
# ------------------------
# Noise handling functions
# ------------------------
def is_white_noise_ranked(residuals, lags=10):
"""
Returns True (white-noise) if p-value > 0.05.
"""
residuals = residuals.dropna()
if len(residuals) < lags + 1:
return True
try:
lb_test = acorr_ljungbox(residuals, lags=[lags],return_df=True)
p_value = lb_test['lb_pvalue'].iloc[0]
return p_value > 0.05
except Exception:
return True
def prewhiten_ranked_residuals(residuals, maxlag=1):
#Fit AR to rank residuals and return whitened residuals aligned to original index.
#residuals: pandas Series (rank-domain noise)
e = residuals.dropna()
if len(e) < maxlag + 2:
return residuals # not enough data
try:
model = AutoReg(e, lags=maxlag, old_names=False).fit()
phi = model.params.values # AR coefficients
# Prewhiten: e_pw[t] = e[t] - sum(phi[k] * e[t-k])
e_pw = e.copy()
for i in range(maxlag, len(e)):
e_pw.iloc[i] = e.iloc[i] - np.dot(phi[1:], e.iloc[i-maxlag:i][::-1])
# Align with original residual index (first few NaNs)
e_pw = pd.Series(e_pw, index=e.index)
return e_pw
except Exception as e:
print(f"AR prewhitening failed: {e}")
return residuals
def run_Python_JTK_with_noise_handling_ranked(
series, period_range, lag_range, asymmetries, ar_lag=1, ljungbox_lag=10
):
# initial JTK
temp_res = run_discrete_jtk(series, period_range=period_range,
lag_range=lag_range, asymmetries=asymmetries)
if not temp_res or temp_res.get('PER') is None:
return temp_res, False
times = series.index.to_numpy()
# best template for that PER/LAG/ASYM
template_vals = generate_triangle_template_time(
times, temp_res['PER'], temp_res['LAG'], temp_res['ASYM']
)
template_rank = pd.Series(template_vals, index=series.index).rank()
# rank series & compute rank-residuals
r = series.rank()
e = r - template_rank
# Autocorrelation test on rank-residuals
if is_white_noise_ranked(e, lags=ljungbox_lag):
return temp_res, False # no AR detected
# AR prewhiten **residuals only**
e_pw = prewhiten_ranked_residuals(e, maxlag=ar_lag)
# reconstruct whitened rank-series
r_pw = template_rank + e_pw # preserve rhythm, whiten noise
# JTK on reconstructed prewhitened series
jtk_res = run_discrete_jtk(r_pw, period_range=period_range,
lag_range=lag_range, asymmetries=asymmetries)
if jtk_res:
jtk_res['Method'] = 'AR-JTK'
amp = (np.percentile(series.values, 90) - np.percentile(series.values, 10)) / 2
jtk_res['AMP'] = round(amp, 4)
return jtk_res, True
# ------------------------
# Cosine-Kendall function
# ------------------------
def run_Cosine_Kendall(series, period_range=[20,20.5,21,21.5,22,22.5,23,23.5,24,24.5,25,25.5,26,26.5,27,27.5,28], interval=1):
y = series.rank().values
n = len(y)
best_p = 1.0
best_tau = 0.0
best_per = None
best_lag = None
test_results = []
t = series.index.to_numpy()
for period in period_range:
for lag in np.arange(0, period, 0.5):
radians = 2 * np.pi * (t - lag) / period
ref = np.cos(radians)
ref_ranked = pd.Series(ref).rank().values
tau, pval = kendalltau(y, ref_ranked)
test_results.append((pval, tau, period, lag))
if pval < best_p:
best_p = pval
best_tau = tau
best_per = period
best_lag = lag
bonf_p = min(1.0, best_p * len(test_results))
amp = (np.percentile(series.values, 90) - np.percentile(series.values, 10)) / 2
#### using corrected lag when tau < 0 because of Kendall's tau method.
corrected_lag = (best_lag - best_per / 2) % best_per if best_tau < 0 else best_lag
return {
'ADJ.P': round(bonf_p, 6),
'PER': round(best_per, 2),
'AMP': round(amp, 4),
'Acrophase': round(corrected_lag, 2),
'corrected_lag': round(corrected_lag, 2),
'Method': 'Cosine-Kendall'
}
# ------------------------
# Cosinor analysis function
# ------------------------
def fit_group_cosinor(df, period_list=[20,20.5,21,21.5,22,22.5,23,23.5,24,24.5,25,25.5,26,26.5,27,27.5,28]):
results = []
for test in df['test'].unique():
subset = df[df['test'] == test]
x = subset['x'].values
y = subset['y'].values
test_results = []
best_aic = np.inf
best_result = None
best_p = 1.0
for per in period_list:
omega = 2 * np.pi / per
cos_term = np.cos(omega * x)
sin_term = np.sin(omega * x)
X = np.column_stack([np.ones(len(x)), cos_term, sin_term])
model = sm.OLS(y, X).fit()
pval = model.f_pvalue
test_results.append(pval)
if model.aic < best_aic:
beta_cos, beta_sin = model.params[1], model.params[2]
amp = np.sqrt(beta_cos ** 2 + beta_sin ** 2)
phase = np.arctan2(-beta_sin, beta_cos)
cov = model.cov_params()
var_amp = (beta_cos**2 * cov[2, 2] +
beta_sin**2 * cov[1, 1] +
2 * beta_cos * beta_sin * cov[1, 2]) / amp**2
se_amp = np.sqrt(var_amp)
ci_amp = (amp - 1.96 * se_amp, amp + 1.96 * se_amp)
var_phase = ((beta_sin**2 * cov[1, 1] +
beta_cos**2 * cov[2, 2] -
2 * beta_cos * beta_sin * cov[1, 2]) /
(beta_cos**2 + beta_sin**2)**2)
se_phase = np.sqrt(var_phase)
ci_phase = (phase - 1.96 * se_phase, phase + 1.96 * se_phase)
best_aic = model.aic
best_p = pval
best_result = {
'test': test,
'period': per,
'p': pval,
'mesor': model.params[0],
'amplitude': amp,
'p(amplitude)': model.pvalues[1],
'CI(amplitude)': [ci_amp[0], ci_amp[1]],
'acrophase': acrophase_to_hours(phase, per),
'p(acrophase)': model.pvalues[2],
'CI(acrophase)': [ci_phase[0], ci_phase[1]],
'Acrophase': (-phase) * per / (2 * np.pi)
}
if best_result:
m = len(test_results)
bonf_p = min(1.0, best_p * m)
best_result['ADJ.P'] = bonf_p
results.append(best_result)
df_results = pd.DataFrame(results)
return df_results
# ------------------------
# Harmonic Cosinor function (Kendall's tau test)
# ------------------------
def fit_group_harmonic_cosinor(df, period_range=[20,20.5,21,21.5,22,22.5,23,23.5,24,24.5,25,25.5,26,26.5,27,27.5,28],
harmonics=2):
x = df['x'].values
y = df['y'].values
y_ranked = pd.Series(y).rank().values
best_p = 1.0
best_tau = 0.0
best_per = None
best_lag = None
test_results = []
for period in period_range:
for lag in np.arange(0, period, 0.5):
ref = np.zeros(len(x))
for h in range(1, harmonics + 1):
ref += np.cos(2 * np.pi * h * (x - lag) / period)
ref_ranked = pd.Series(ref).rank().values
# Ensure same size before correlation
if len(y_ranked) != len(ref_ranked):
continue
tau, pval = kendalltau(y_ranked, ref_ranked)
test_results.append((pval, tau, period, lag))
if pval < best_p:
best_p = pval
best_tau = tau
best_per = period
best_lag = lag
bonf_p = min(1.0, best_p * len(test_results)) # Bonferroni correction
amp_est = (np.percentile(y, 90) - np.percentile(y, 10)) / 2
#Generate model for parameter estimation (1 cycle)
t_grid = np.linspace(0, best_per,1000)
model_wave = np.zeros_like(t_grid)
for h in range(1, harmonics + 1):
model_wave += np.cos(2 * np.pi * h * (t_grid - best_lag) / best_per)
# For plotting (full time)
t_grid_full = np.linspace(x.min(), x.max(), 1000)
model_wave_full = np.zeros_like(t_grid_full)
for h in range(1, harmonics + 1):
model_wave_full += np.cos(2 * np.pi * h * (t_grid_full - best_lag) / best_per)
if best_tau < 0:
model_wave *= -1
model_wave_full *= -1
#Find peaks (local maxima)
from scipy.signal import find_peaks
peaks, _ = find_peaks(model_wave, distance=200) # ensures apart two peaks from 200/1000 period.
# Fallback if not enough peaks detected
if len(peaks) < 2:
# Pick top 2 highest points (by value), sorted by time
peak_indices = np.argsort(model_wave)[-2:]
else:
# Get the 2 highest peaks among detected peaks
peak_indices = peaks[np.argsort(model_wave[peaks])[-2:]]
# Sort indices by time
peak_indices = sorted(peak_indices)
# Calculate acrophase and amplitude per peak
acrophases = [acrophase_to_hours(t_grid[i] / best_per * 2 * np.pi, best_per) for i in peak_indices]
if best_tau < 0:
acrophases = [(a + best_per / 2) % best_per for a in acrophases]
# Normalize the model wave to [0, 1]
norm_model_wave = (model_wave - np.min(model_wave)) / np.ptp(model_wave)
# Get real amplitude estimates based on normalized peak height
peak_amps = [round(norm_model_wave[i] * amp_est * 2, 4) for i in peak_indices]
# # Pair acrophases with amps, sort by acrophase time
acrophase_amp_pairs = sorted(zip(acrophases, peak_amps), key=lambda x: x[0])
acrophases = [round(a, 2) for a, _ in acrophase_amp_pairs]
peak_amps = [round(a, 4) for _, a in acrophase_amp_pairs]
# return the model wave parameters for plotting the best fit
fit_model = {
't_grid': t_grid,
'model_wave': amp_est * norm_model_wave,
't_grid_full': t_grid_full,
'model_wave_full': amp_est * (model_wave_full - np.min(model_wave)) / np.ptp(model_wave),
'params': {
'period': best_per,
'lag': best_lag,
'acrophases': acrophases,
'amplitudes': peak_amps,
'bonferroni_p': bonf_p
}
}
return pd.DataFrame([{
'ADJ.P': round(bonf_p, 6),
'PER': round(best_per, 2),
'AMP1': round(peak_amps[0], 4),
'AMP2': round(peak_amps[1], 4),
'Acrophase1': round(acrophases[0], 2),
'Acrophase2': round(acrophases[1], 2),
'Method': 'Harmonic-Cosinor'
}]), fit_model
# ------------------------
# Continuous Wavelet Transform (CWT)
# non-stationary circadian signals with time-varying analysis
# ------------------------
def fit_group_cwt(df, sampling_interval=0.5, wavelet='cmor1.5-1.0'):
results = []
ridge_results = []
for test in df['test'].unique():
subset = df[df['test'] == test].sort_values('x')
x = subset['x'].values
y = subset['y'].values
# Detrend the signal to highlight oscillations
y_detrended = y - np.mean(y)
# Scales corresponding to ~20–28 h periods (assuming 1 sample per 0.5 h)
# wavelet scales roughly relate to period ≈ scale * sampling_interval
period_range = np.arange(20, 28.1, 0.1)
scales = period_range / sampling_interval
# Perform the continuous wavelet transform
coef, freqs = pywt.cwt(y_detrended, scales, wavelet, sampling_period=sampling_interval)
power = np.abs(coef) ** 2
# Average power across time to get global wavelet spectrum
global_power = power.mean(axis=1)
dominant_idx = np.argmax(global_power)
dominant_period = period_range[dominant_idx]
dominant_power = global_power[dominant_idx]
# Estimate period drift: find dominant period per timepoint
ridge_indices = np.argmax(power, axis=0)
dom_periods_over_time = period_range[ridge_indices]
ridge_power = power[ridge_indices, np.arange(power.shape[1])]
period_variation = np.std(dom_periods_over_time)
# Store plotting/ridge data
for t, per, rp in zip(x, dom_periods_over_time, ridge_power):
ridge_results.append({
'test': test,
'time': float(t),
'dominant_period_timepoint': float(per),
'ridge_power_raw': float(rp)
})
# Optional: detect amplitude modulation
mean_power = np.mean(power, axis=0)
amp_peaks, _ = find_peaks(mean_power)
amp_fluctuations = len(amp_peaks)
results.append({
'test': test,
'dominant_period': round(dominant_period, 2),
'mean_power': round(float(np.mean(global_power)), 4),
'period_variation': round(float(period_variation), 3),
'amplitude_modulations': amp_fluctuations,
'Method': 'CWT analysis'
})
return pd.DataFrame(results), pd.DataFrame(ridge_results)
# ------------------------
# linear mixed-effects model (LME)
# ------------------------
def LME_model(df, dependent, fixed_effects, random_effect):
# Construct formula string
fixed_str = " + ".join(fixed_effects)
formula = f"{dependent} ~ {fixed_str}"
# Fit model
model = smf.mixedlm(formula, df, groups=df[random_effect])
result = model.fit()
# Extract results
summary_df = pd.DataFrame({
"Term": result.params.index,
"Estimate": result.params.values,
"StdErr": result.bse.values,
"z-value": result.tvalues.values,
"p-value": result.pvalues.values
})
return summary_df
class SpanDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Add Shaded Span")
layout = QVBoxLayout(self)
self.start_label = QLabel("Start Time (hr):")
self.start_box = QtWidgets.QSpinBox()
self.start_box.setRange(0, 999)
self.end_label = QLabel("End Time (hr):")
self.end_box = QtWidgets.QSpinBox()
self.end_box.setRange(0, 999)
self.color_label = QLabel("Span Color:")
self.color_button = QPushButton("Choose Color")
self.color = "#888888" # default gray
self.color_button.clicked.connect(self.choose_color)
layout.addWidget(self.start_label)
layout.addWidget(self.start_box)
layout.addWidget(self.end_label)
layout.addWidget(self.end_box)
layout.addWidget(self.color_label)
layout.addWidget(self.color_button)
btn = QPushButton("Add Span")
btn.clicked.connect(self.accept)
layout.addWidget(btn)
def choose_color(self):
color = QColorDialog.getColor()
if color.isValid():
self.color = color.name()
self.color_button.setStyleSheet(f"background-color: {self.color};")
def get_values(self):
if not hasattr(self, "color"):
self.color = "#888888"
return self.start_box.value(), self.end_box.value(), self.color
class RenameLegendDialog(QDialog):
def __init__(self, labels, parent=None):
super().__init__(parent)
self.setWindowTitle("Rename Legend Labels")
self.layout = QVBoxLayout(self)
self.inputs = {}
for label in labels:
row = QHBoxLayout()
row.addWidget(QLabel(label))
edit = QtWidgets.QLineEdit()
edit.setText(label)
self.inputs[label] = edit
row.addWidget(edit)
self.layout.addLayout(row)
btn = QPushButton("Apply")
btn.clicked.connect(self.accept)
self.layout.addWidget(btn)
def get_renamed(self):
return {old: box.text() for old, box in self.inputs.items()}
class JTKParamDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("JTK Parameter Setup")
layout = QVBoxLayout(self)
self.period_input = QLineEdit("22,23,24,25,26")
self.lag_input = QLineEdit("0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23")
self.asym_input = QLineEdit("0.2,0.5,0.8") # Optional
layout.addWidget(QLabel("<<estimate Periods (comma-separated)>>\n note: more periods you select, the slower efficiency you get!"))
layout.addWidget(self.period_input)
layout.addWidget(QLabel("<<estimate Lags (when the waveform starts rising) (comma-separated)>>\n note: please use default values if you are unsure!"))
layout.addWidget(self.lag_input)
layout.addWidget(QLabel("<<estimate Asymmetries (range: 0-1)>>\n = 0.5 → symmetric (equal rise and fall time)\n < 0.5 → left-skewed (rises quickly, falls slowly)\n > 0.5 → right-skewed (rises slowly, falls quickly)\nExample: 0.2,0.5,0.8"))
layout.addWidget(self.asym_input)
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
layout.addWidget(buttons)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
def get_params(self):
periods = [int(p.strip()) for p in self.period_input.text().split(",")]
lags = [int(l.strip()) for l in self.lag_input.text().split(",")]
asyms = [float(a.strip()) for a in self.asym_input.text().split(",")]
return periods, lags, asyms
class JTKParamDialog_Noise(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("JTK Parameter Setup (Noise Handling)")
layout = QVBoxLayout(self)
self.period_input = QLineEdit("22,23,24,25,26")
self.lag_input = QLineEdit("0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23")
self.asym_input = QLineEdit("0.2,0.5,0.8")
layout.addWidget(QLabel("Parameters for JTK (Noise Handling)"))
layout.addWidget(QLabel("<<estimate Periods (comma-separated)>>\n note: more periods you select, the slower efficiency you get!"))
layout.addWidget(self.period_input)
layout.addWidget(QLabel("<<estimate Lags (when the waveform starts rising)>>\n note: please use default values if you are unsure!"))
layout.addWidget(self.lag_input)
layout.addWidget(QLabel("<<estimate Asymmetries (range: 0-1)>>\n = 0.5 → symmetric (equal rise and fall time)\n < 0.5 → left-skewed (rises quickly, falls slowly)\n > 0.5 → right-skewed (rises slowly, falls quickly)\nExample: 0.2,0.5,0.8"))
layout.addWidget(self.asym_input)
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
layout.addWidget(buttons)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
def get_params(self):
periods = [int(p.strip()) for p in self.period_input.text().split(",")]
lags = [int(l.strip()) for l in self.lag_input.text().split(",")]
asyms = [float(a.strip()) for a in self.asym_input.text().split(",")]
return periods, lags, asyms
LEGEND_OPTIONS = {
"loc": "upper right",
"fontsize": 10,
"framealpha": 0.5
}
class CircadianApp(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("easyClock")
self.resize(1000, 900)
self.legend_settings = {
"loc": "upper right",
"fontsize": 10,
"framealpha": 0.5
}
self.group_display_names = {}
self.raw_data = {k: None for k in ["file_1", "file_2", "file_3"]}
self.group_assignments = {}
self.group_means = {k: {} for k in self.raw_data}
self.group_sems = {k: {} for k in self.raw_data}
self.group_colors = {}
self.shaded_spans = {}
self.result_table = []
self.latest_result_df = None
self.y_axis_limits = {
"file_1": None,
"file_2": None,
"file_3": None
}
self.x_labels = {k: "Time" for k in self.raw_data}
self.y_labels = {
"file_1": "Y Label",
"file_2": "Y Label",
"file_3": "Y Label"
}
self.titles = {k: k.capitalize() for k in self.raw_data}
central = QtWidgets.QWidget()
self.setCentralWidget(central)
layout = QtWidgets.QVBoxLayout(central)
self.status = QTextEdit("Status: waiting for input")
self.status.setReadOnly(True)
layout.addWidget(self.status)
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.canvas_widget = QWidget()
canvas_layout = QVBoxLayout(self.canvas_widget)
canvas_layout.addWidget(self.canvas)
self.canvas_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.canvas_widget)
layout.addWidget(self.scroll)
layout.addWidget(self._add_button("Export Plot to PDF", self.export_plot))
layout.addWidget(self._add_button("Export Result Table", self.export_results_table))
menu = self.menuBar()
file_menu = menu.addMenu("File")
file_menu.addAction("Load Data", self.load_data)
edit_menu = menu.addMenu("Edit")
edit_menu.addAction("Axis Labels", self.set_axis_labels)
yaxis_action = QtWidgets.QAction("Axis-Y Limits", self)
yaxis_action.triggered.connect(self.edit_y_axis_limits)
edit_menu.addAction(yaxis_action)
edit_menu.addAction("Shaded Span Adding", self.collect_shaded_spans)
edit_menu.addAction("Shaded Span Removing", self.remove_shaded_span)
edit_menu.addAction("Legend Format", self.set_legend_style)
edit_menu.addAction("Legend Labels", self.rename_legend_labels)
analysis_menu=menu.addMenu("Analysis")
analysis_menu.addAction("Cosine-Kendall and Cosinor",self.run_analysis)
analysis_menu.addAction("Python-JTK (non-parametric test)",self.run_pythonJTK_analysis)
analysis_menu.addAction("Harmonic Cosinor (bimodal test)",self.run_fit_group_harmonic_cosinor)
analysis_menu.addAction("AR-JTK (AR noise handling, slower speed)", self.run_pythonJTK_analysis_noise)
analysis_menu.addAction("Continuous Wavelet Transform (non-stationary rhythms)", self.run_CWT_analysis)
analysis_menu=menu.addMenu("Analysis Extension")
analysis_menu.addAction("Individual rhtyhms (Python-JTK)", self.run_individual_pythonJTK_analysis_noise)
analysis_menu.addAction("Linear mixed-effects (run after individual analysis)", self.run_LME_analysis)
visualize_menu=menu.addMenu("Visualization")
actogram_action = QtWidgets.QAction("Plot Actogram", self)
actogram_action.triggered.connect(self.plot_actogram)
visualize_menu.addAction(actogram_action)
cosinor_plot_action = QtWidgets.QAction("Plot Cosinor Fitting", self)
cosinor_plot_action.triggered.connect(lambda:self.plot_cosinor_fitting_model())
visualize_menu.addAction(cosinor_plot_action)
cosinor_kendall_plot_action = QtWidgets.QAction("Plot Cosinor-Kendall Fitting", self)
cosinor_kendall_plot_action.triggered.connect(lambda:self.plot_cosinor_kendall_fitting_model())
visualize_menu.addAction(cosinor_kendall_plot_action)
python_jtk_plot_action = QtWidgets.QAction("Plot Python-JTK / AR-JTK Fitting", self)
python_jtk_plot_action.triggered.connect(lambda:self.plot_python_jtk_fitting_model())
visualize_menu.addAction(python_jtk_plot_action)
harmonic_cosinor_plot_action = QtWidgets.QAction("Plot Harmonic-Cosinor Fitting", self)
harmonic_cosinor_plot_action.triggered.connect(lambda:self.plot_harmonic_cosinor_fitting_model())
visualize_menu.addAction(harmonic_cosinor_plot_action)
cwt_plot_action = QtWidgets.QAction("Plot CWT Fitting", self)
cwt_plot_action.triggered.connect(lambda:self.plot_cwt())
visualize_menu.addAction(cwt_plot_action)
about_menu = menu.addMenu("Read Me")
about_menu.addAction("Developer", self.show_developer)
about_menu.addAction("Note", self.show_Notes)
about_menu.addAction("Acknowledgements and Feedback", self.show_Feedback)
def _add_button(self, label, callback):
btn = QPushButton(label)
btn.clicked.connect(callback)
return btn
def show_developer(self):
QMessageBox.about(
self,
"About easyClock",
"🕓 easyClock v3.5\n\n"
"Developed by: Binbin Wu Ph.D.\n"
"Ja Lab, UF Scripps Institute, University of Florida\n"
"© 2026. All rights reserved.\n\n"
"Please cite:\neasyClock: A User-Friendly Desktop Application for Circadian Rhythm Analysis and Visualization.\n\n")
def show_Notes(self):
QMessageBox.about(
self,
"About Instructions",
"This app can input up to 3 files in the same time, click cancel to skip 1 or 2 file input.\n\n"
"This app is desigined for analyzing circadian rhythms, so at least 48 hr data is required for analysis.\n\n"
"Read Figure 2 of the following paper for understading the correct data format:\n\n"
"easyClock: A User-Friendly Desktop Application for Circadian Rhythm Analysis and Visualization.")
def show_Feedback(self):
QMessageBox.about(
self,
"Acknowledgments",
"We thank the following individuals for providing valuable feedback:\n\n"
"Dr. Yutong Xiao (Max Planck, Florida)\n"
"Alayna Garland (Kenan Fellow)\n"
"Dr. Qiankun He (Zhengzhou University)\n\n"
"- - - - Feedback - - - -\n"
"Email me < binbinwu.phd@gmail.com >")
def rename_legend_labels(self):
if not self.group_assignments:
QMessageBox.information(self, "No groups", "No groups available to rename.")
return
current = list(self.group_assignments.keys())
dialog = RenameLegendDialog(current, self)
if dialog.exec_() == QDialog.Accepted:
renamed = dialog.get_renamed()
# Update group assignments and colors
new_assignments = {}
new_colors = {}
for old, new in renamed.items():
new_assignments[new] = self.group_assignments[old]
new_colors[new] = self.group_colors.get(old, "#000000")
self.group_assignments = new_assignments
self.group_colors = new_colors
# Recalculate means and SEMs with new group names
self.group_means = {k: {} for k in self.raw_data}
self.group_sems = {k: {} for k in self.raw_data}
for dtype, df in self.raw_data.items():
if df is not None:
for group, flies in self.group_assignments.items():
valid = [f for f in flies if f in df.columns]
if not valid:
continue
gdf = df[valid]
self.group_means[dtype][group] = gdf.mean(axis=1)
self.group_sems[dtype][group] = gdf.sem(axis=1)
self.plot_all()
def set_axis_labels(self):
dtype, ok = QInputDialog.getItem(self, "File Type", "Which plot?", ["file_1", "file_2", "file_3"], 0, False)
if not ok:
return
title, ok1 = QInputDialog.getText(self, "Plot Title", "Title:", text=self.titles.get(dtype, dtype.capitalize()))
if ok1:
self.titles[dtype] = title
xlabel, ok2 = QInputDialog.getText(self, "X Label", "Label:", text=self.x_labels.get(dtype, "Time"))
if ok2:
self.x_labels[dtype] = xlabel
ylabel, ok3 = QInputDialog.getText(self, "Y Label", "Label:", text=self.y_labels.get(dtype, "Value"))
if ok3:
self.y_labels[dtype] = ylabel
self.plot_all()
def set_legend_style(self):
locs = ['upper right', 'upper left', 'lower right', 'lower left',
'upper center', 'lower center', 'center right', 'center left', 'center']
loc, ok1 = QInputDialog.getItem(self, "Legend Location", "Select location:", locs, editable=False)
if not ok1:
return
fs, ok2 = QInputDialog.getInt(self, "Font Size", "Size:", value=self.legend_settings['fontsize'], min=0, max=20)
if not ok2:
return
alpha, ok3 = QInputDialog.getDouble(self, "Frame Alpha", "Transparency (0-1):", value=self.legend_settings['framealpha'], min=0.0, max=1.0, decimals=1)
if not ok3:
return
self.legend_settings = {"loc": loc, "fontsize": fs, "framealpha": alpha}
self.plot_all()
def edit_y_axis_limits(self):
dtype, ok = QInputDialog.getItem(self, "Select Plot", "Choose plot:", ["file_1", "file_2", "file_3"], 0, False)
if not ok:
return
current_limits = self.y_axis_limits.get(dtype, (None, None))
ymin, ok1 = QInputDialog.getDouble(self, f"{dtype.capitalize()} Y Min", "Enter Y-axis min (leave 0 for auto):", 0, decimals=3)
if not ok1:
return
ymax, ok2 = QInputDialog.getDouble(self, f"{dtype.capitalize()} Y Max", "Enter Y-axis max (leave 0 for auto):", 0, decimals=3)
if not ok2:
return
# Auto range if either is zero
if ymin == 0 and ymax == 0:
self.y_axis_limits[dtype] = None
else:
self.y_axis_limits[dtype] = (ymin, ymax)
self.plot_all()
def collect_shaded_spans(self):
dtype, ok = QInputDialog.getItem(
self, "File Type", "Assign shaded span to which plot?",
list(self.group_means.keys()), 0, False
)
if not ok or not dtype:
return
if dtype not in self.shaded_spans:
self.shaded_spans[dtype] = []
while True:
dialog = SpanDialog(self)
if dialog.exec_() != QDialog.Accepted:
break
start, end, color = dialog.get_values()
if end <= start:
QMessageBox.warning(self, "Invalid Span", "End must be greater than start.")
continue
self.shaded_spans[dtype].append((start, end, color))
self.plot_all()
def load_data(self):
import csv
self.group_assignments.clear()
self.group_means = {k: {} for k in self.raw_data}
self.group_sems = {k: {} for k in self.raw_data}
self.group_colors.clear()
fly_ids = [] # original labels (may have duplicates)
unique_ids = [] # unique column ids
self.column_label_map = {} # maps unique_id → original label
reference_labels = None # store the first file's unique labels
for dtype in self.raw_data:
path, _ = QtWidgets.QFileDialog.getOpenFileName(
self, f"Load {dtype} CSV", "", "CSV Files (*.csv)"
)
if path:
try:
# Read raw header with utf-8-sig to support BOM and preserve duplicate labels
with open(path, "r", encoding="utf-8-sig", newline="") as f:
reader = csv.reader(f)
header = next(reader)
if "Time" not in header:
raise ValueError("'Time' column missing in header.")
time_index = header.index("Time")
raw_cols = header[:time_index] + header[time_index + 1:]
# Clean headers: preserve duplicates(original labels), label unnamed ones
cleaned_labels = []
unnamed_counter = 1
for label in raw_cols:
clean = str(label).strip()
if clean == "" or clean.lower().startswith("unnamed"):
clean = f"Unnamed_{unnamed_counter}"
unnamed_counter += 1
cleaned_labels.append(clean)
# --- Ensure unique IDs for DataFrame columns ---
seen = {}
unique_labels = []
for label in cleaned_labels:
if label not in seen:
seen[label] = 1
unique_labels.append(label)
else:
seen[label] += 1
unique_labels.append(f"{label}_{seen[label]}")
# --- Consistency check with reference ---
if reference_labels is None:
reference_labels = cleaned_labels[:] # save original labels from first file
else:
if cleaned_labels != reference_labels:
QMessageBox.warning(
self,
"Inconsistent Column labels between files",
f"Skipped {os.path.basename(path)}\n\n"
f"Column labels do not match the first dataset."
)
self.status.append(
f"Skipped {dtype} ({os.path.basename(path)}) due to inconsistent labels."
)
continue # skip this file entirely
# Load data with proper encoding and label assignment
df = pd.read_csv(path, index_col="Time", encoding="utf-8-sig")
df.columns = unique_labels
self.raw_data[dtype] = df