-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
1506 lines (1238 loc) · 58.5 KB
/
model.py
File metadata and controls
1506 lines (1238 loc) · 58.5 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
"""
Cosmological Time-Scaling Model: Numerical Pipeline
==========================================================
This module implements the pipeline for testing the time-scaling model.
The pipeline includes:
1. Symbolic framework definition
2. Observational data fitting (Supernovae, GRB, Cosmic Chronometers, CMB)
3. Scalar field dynamics simulation
4. Statistical model comparison with MCMC support
Date: 2025 (Artur Chudzik)
Link: https://github.com/archudzik/timeScalingModel
"""
import os
from scipy.optimize import minimize
from scipy.signal import find_peaks
from scipy.optimize import curve_fit
from scipy.integrate import solve_ivp
from scipy.optimize import minimize_scalar
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.integrate import solve_ivp, quad
import sympy as sp
import warnings
import emcee
from scipy.optimize import differential_evolution
random_number = 1234
os.chdir(os.path.dirname(os.path.abspath(__file__)))
warnings.filterwarnings('ignore')
np.random.seed(random_number)
class CosmologicalFramework:
"""
Symbolic framework for cosmological equations and relationships.
Defines the mathematical foundation of the time-scaling model.
"""
def __init__(self):
self.setup_symbols()
self.derive_equations()
def setup_symbols(self):
"""Initialize symbolic variables"""
self.t, self.t0 = sp.symbols('t t0', positive=True)
self.alpha = sp.Function('alpha')(self.t)
self.alpha_dot = sp.diff(self.alpha, self.t)
self.alpha_2dot = sp.diff(self.alpha, self.t, 2)
self.G = sp.symbols('G', positive=True)
self.c = sp.symbols('c', positive=True)
def derive_equations(self):
"""Derive key cosmological relationships"""
# Scale factor
self.a = (self.t / self.t0)**self.alpha
self.a_dot = sp.diff(self.a, self.t)
self.a_2dot = sp.diff(self.a_dot, self.t)
self.a_3dot = sp.diff(self.a_2dot, self.t)
# Hubble parameter
# For time-varying alpha: H = (α + α̇*ln(t/t₀))/t
self.H = (self.alpha + self.alpha_dot *
sp.log(self.t / self.t0)) / self.t
# Energy density from first Friedmann equation
self.rho = sp.simplify((3 * self.H**2) / (8 * sp.pi * self.G))
# Pressure from second Friedmann equation
# ä/a = -4πG(ρ + 3p/c²)/3
lhs = self.a_2dot / self.a
self.p = sp.simplify((-(lhs * 3) / (4 * sp.pi * self.G)) - self.rho)
# Equation of state parameter
self.w = sp.simplify(self.p / (self.rho * self.c**2))
# Deceleration parameter
self.q = sp.simplify(-self.a * self.a_2dot / self.a_dot**2)
# Jerk parameter
self.jerk = sp.simplify(self.a**2 * self.a_3dot / self.a_dot**3)
def print_equations(self):
print("=== Cosmological Framework Equations ===")
print(f"Scale factor a(t): {self.a}")
print(f"Hubble parameter H(t): {self.H}")
print(f"Energy density ρ(t): {self.rho}")
print(f"Pressure p(t): {self.p}")
print(f"Equation of state w(t): {self.w}")
print(f"Deceleration parameter q(t): {self.q}")
print(f"Jerk parameter j(t): {self.jerk}")
class ObservationalDataAnalyzer:
"""
Handles fitting cosmological models to observational data
"""
def __init__(self):
self.c = 299792.458 # km/s
self.r_s = 147.78 # Mpc (sound horizon)
self.M_B = -19.3 # Absolute magnitude
self.sn_M_B = 25 + self.M_B # SN Absolute magnitude
self.grb_M_B = 25 # GRB Absolute magnitude
self.cmb_M_B = 5 # CMB Absolute magnitude
self.bounds_lcdm = [(65, 75), (0, 0.5)] # H0, Omega_m
self.bounds_ts = [(70, 75), (1, 2)] # H0, alpha
self.bounds_lcdm_cmb = [(65, 75), (0, 20)] # H0, mu0
self.bounds_ts_cmb = [(70, 75), (1, 2), (0, 20)] # H0, alpha, mu0
self.h_planck_measured = 67.4
# Model results storage
self.results = {}
self.cmb_data = {}
def load_planck_tt_spectrum(self, file_path):
"""
Load and properly process Planck TT power spectrum data
"""
ell_vals = []
cl_vals = []
cl_err_vals = []
with open(file_path, 'r') as file:
for line in file:
if line.strip() and not line.startswith('#'):
parts = line.split()
if len(parts) >= 2:
ell_vals.append(float(parts[0]))
cl_vals.append(float(parts[1]))
# If error column exists, use it; otherwise estimate
if len(parts) >= 3:
cl_err_vals.append(float(parts[2]))
else:
# Estimate error as ~5% of signal for high-ell, higher for low-ell
if float(parts[0]) < 30:
cl_err_vals.append(0.1 * float(parts[1]))
else:
cl_err_vals.append(0.05 * float(parts[1]))
ell_vals = np.array(ell_vals)
cl_vals = np.array(cl_vals)
cl_err_vals = np.array(cl_err_vals)
# Convert to D_ell = ell(ell+1)C_ell/(2π)
Dl_vals = ell_vals * (ell_vals + 1) * cl_vals / (2 * np.pi)
Dl_err_vals = ell_vals * (ell_vals + 1) * cl_err_vals / (2 * np.pi)
return ell_vals, cl_vals, Dl_vals, Dl_err_vals
def load_real_data(
self,
path_cc="./dataset/Chronometers.txt",
path_supernova="./dataset/Pantheon+SH0ES.csv",
path_grb="./dataset/GRB.txt",
path_cmb="./dataset/Planck-TT.txt"
):
"""
Load real observational data including enhanced CMB processing
"""
cc_data = np.loadtxt(path_cc)
z_cc = cc_data[:, 0]
H_cc = cc_data[:, 1]
H_err = cc_data[:, 2]
self.cc_data = {'z': z_cc, 'H': H_cc, 'H_err': H_err}
pantheon_data = pd.read_csv(path_supernova)
pantheon_data = pantheon_data[[
'zHD', 'm_b_corr', 'm_b_corr_err_DIAG']].dropna()
pantheon_data.columns = ['z', 'mu', 'mu_err']
z_sn = pantheon_data['z'].values
mu_obs = pantheon_data['mu'].values
mu_err = pantheon_data['mu_err'].values
self.sn_data = {'z': z_sn, 'mu': mu_obs, 'mu_err': mu_err}
grb_data_fixed = pd.read_csv(path_grb, sep=' ')
grb_data_clean = grb_data_fixed[['Redshift', 'mu', 'sigma_mu']].copy()
grb_data_clean.columns = ['z', 'mu', 'sigma_mu']
self.grb_data = grb_data_clean
# Enhanced CMB data loading
ell_vals, cl_vals, Dl_vals, Dl_err_vals = self.load_planck_tt_spectrum(
path_cmb)
self.cmb_data = {
'ell': ell_vals,
'Dl': Dl_vals,
'Dl_err': Dl_err_vals,
'ell_full': ell_vals,
'Dl_full': Dl_vals,
'Dl_err_full': Dl_err_vals,
'cl_vals': cl_vals
}
print(f"Loaded: {len(self.cc_data['z'])} CC, {len(self.sn_data['z'])} SN, "
f"{len(self.grb_data)} GRB, {len(self.cmb_data['ell'])} CMB points")
def _distance_modulus_LCDM(self, z, H0, Omega_m, M_B):
"""Calculate distance modulus for LCDM model"""
def integrand(z_val):
return self.c / (H0 * np.sqrt(Omega_m * (1 + z_val)**3 + (1 - Omega_m)))
DL = []
for zi in z:
integral = quad(integrand, 0, zi)[0]
DL.append((1 + zi) * integral)
DL = np.array(DL)
return 5 * np.log10(DL) + M_B
def _distance_modulus_time_scaling(self, z, H0, alpha, M_B):
"""Calculate distance modulus for time-scaling model"""
def integrand(z_val):
return self.c / (H0 * (1 + z_val)**(1/alpha))
DL = []
for zi in z:
integral = quad(integrand, 0, zi)[0]
DL.append((1 + zi) * integral)
DL = np.array(DL)
return 5 * np.log10(DL) + M_B
def _H_LCDM(self, z, H0, Omega_m):
"""Hubble parameter for LCDM"""
return H0 * np.sqrt(Omega_m * (1 + z)**3 + (1 - Omega_m))
def _H_time_scaling(self, z, H0, alpha):
"""Hubble parameter for time-scaling model"""
return H0 * (1 + z)**(1.0 / alpha)
def _DM_over_rs_LCDM(self, z, H0, Omega_m):
"""Angular diameter distance over sound horizon for LCDM"""
def integrand(z_val):
return self.c / (H0 * np.sqrt(Omega_m * (1 + z_val)**3 + (1 - Omega_m)))
DM = []
for zi in z:
integral = quad(integrand, 0, zi)[0]
DM.append(integral / (1 + zi)) # Angular diameter distance
return np.array(DM) / self.r_s
def _DM_over_rs_time_scaling(self, z, H0, alpha):
"""Angular diameter distance over sound horizon for time-scaling"""
def integrand(z_val):
return self.c / (H0 * (1 + z_val)**(1/alpha))
DM = []
for zi in z:
integral = quad(integrand, 0, zi)[0]
DM.append(integral / (1 + zi)) # Angular diameter distance
return np.array(DM) / self.r_s
def _fit_supernovae(self):
"""Fit models to supernova data (original implementation)"""
z, mu_obs, mu_err = self.sn_data['z'], self.sn_data['mu'], self.sn_data['mu_err']
def chi2_lcdm(params):
H0, Om = params
mu_model = self._distance_modulus_LCDM(z, H0, Om, self.sn_M_B)
return np.sum(((mu_obs - mu_model) / mu_err)**2)
def chi2_time_scaling(params):
H0, alpha = params
mu_model = self._distance_modulus_time_scaling(
z, H0, alpha, self.sn_M_B)
return np.sum(((mu_obs - mu_model) / mu_err)**2)
res_lcdm = differential_evolution(
chi2_lcdm, bounds=self.bounds_lcdm)
res_ts = differential_evolution(
chi2_time_scaling, bounds=self.bounds_ts)
n_data = len(z)
self.results['SN'] = {
'LCDM': {
'params': res_lcdm.x,
'chi2': res_lcdm.fun,
'AIC': res_lcdm.fun + 2*2,
'BIC': res_lcdm.fun + 2*np.log(n_data),
},
'Time-Scaling': {
'params': res_ts.x,
'chi2': res_ts.fun,
'AIC': res_ts.fun + 2*2,
'BIC': res_ts.fun + 2*np.log(n_data),
}
}
def _fit_grb(self):
"""Fit GRB-derived distance modulus data"""
z = self.grb_data['z'].values
mu_obs = self.grb_data['mu'].values
mu_err = self.grb_data['sigma_mu'].values
def chi2_lcdm(params):
H0, Om = params
mu_model = self._distance_modulus_LCDM(z, H0, Om, self.grb_M_B)
return np.sum(((mu_obs - mu_model) / mu_err) ** 2)
def chi2_ts(params):
H0, alpha = params
mu_model = self._distance_modulus_time_scaling(
z, H0, alpha, self.grb_M_B)
return np.sum(((mu_obs - mu_model) / mu_err) ** 2)
res_lcdm = differential_evolution(chi2_lcdm, bounds=self.bounds_lcdm)
res_ts = differential_evolution(chi2_ts, bounds=self.bounds_ts)
n_data = len(z)
self.results['GRB'] = {
'LCDM': {
'params': res_lcdm.x,
'chi2': res_lcdm.fun,
'AIC': res_lcdm.fun + 2 * 2,
'BIC': res_lcdm.fun + 2 * np.log(n_data)
},
'Time-Scaling': {
'params': res_ts.x,
'chi2': res_ts.fun,
'AIC': res_ts.fun + 2 * 2,
'BIC': res_ts.fun + 2 * np.log(n_data)
}
}
def _fit_cosmic_chronometers(self):
"""Fit models to cosmic chronometer data"""
z_cc = self.cc_data['z']
H_obs = self.cc_data['H']
H_err = self.cc_data['H_err']
def chi2_lcdm(params):
H0, Om = params
H_model = self._H_LCDM(z_cc, H0, Om)
return np.sum(((H_obs - H_model) / H_err)**2)
def chi2_time_scaling(params):
H0, alpha = params
H_model = self._H_time_scaling(z_cc, H0, alpha)
return np.sum(((H_obs - H_model) / H_err)**2)
res_lcdm = differential_evolution(chi2_lcdm, bounds=self.bounds_lcdm)
res_ts = differential_evolution(
chi2_time_scaling, bounds=self.bounds_ts)
n_data = len(z_cc)
self.results['CC'] = {
'LCDM': {'params': res_lcdm.x, 'chi2': res_lcdm.fun,
'AIC': res_lcdm.fun + 2*2, 'BIC': res_lcdm.fun + 2*np.log(n_data)},
'Time-Scaling': {'params': res_ts.x, 'chi2': res_ts.fun,
'AIC': res_ts.fun + 2*2, 'BIC': res_ts.fun + 2*np.log(n_data)}
}
def _fit_cmb(self):
"""Fit simplified models to transformed Planck D_ell spectrum using μ_CMB = log10(D_ell)"""
# Approximate redshift mapping for multipoles
ell = self.cmb_data['ell']
Dl = self.cmb_data['Dl']
Dl_err = self.cmb_data['Dl_err']
valid = Dl > 0
# Filter all arrays
ell = ell[valid]
Dl = Dl[valid]
Dl_err = Dl_err[valid]
# Brute-force optimization for completeness:
def error_kappa(kappa):
ell_peak = 220
z_target = 1089
z_eff = kappa * ell_peak
return abs(z_eff - z_target)
# Minimize absolute error between z_eff and z_target
result_kappa = minimize_scalar(
error_kappa, bounds=(1, 10), method='bounded')
best_kappa = result_kappa.x
print(f"best_kappa={best_kappa}")
# Redshift mapping and transformed modulus
z_vals = ell * best_kappa
mu_cmb = np.log10(Dl)
mu_err_prop = np.abs(0.434 * Dl_err / Dl)
mu_err = np.minimum(mu_err_prop, 0.1 * mu_cmb)
def lcdm_model(z, H0, mu0):
return np.log10(1 + z) + np.log10(H0 / self.h_planck_measured) + mu0
def timescaling_model(z, H0, alpha, mu0):
return np.log10(1e3 / (1 + z) ** (1 - alpha) * (H0 / self.h_planck_measured)) + mu0
def chi2_lcdm(p):
H0, mu0 = p
model = lcdm_model(z_vals, H0, mu0)
return np.sum(((mu_cmb - model) / mu_err) ** 2)
def chi2_ts(p):
H0, alpha, mu0 = p
model = timescaling_model(z_vals, H0, alpha, mu0)
return np.sum(((mu_cmb - model) / mu_err) ** 2)
res_lcdm = minimize(
chi2_lcdm, x0=[self.h_planck_measured, 5.0], bounds=self.bounds_lcdm_cmb, method='L-BFGS-B')
res_ts = minimize(
chi2_ts, x0=[self.h_planck_measured, 1.0, 5.0], bounds=self.bounds_ts_cmb, method='L-BFGS-B')
self.results['CMB'] = {
'LCDM': {
'params': res_lcdm.x,
'chi2': res_lcdm.fun,
'AIC': res_lcdm.fun + 2 * 1,
'BIC': res_lcdm.fun + 1 * np.log(len(z_vals)),
},
'Time-Scaling': {
'params': res_ts.x,
'chi2': res_ts.fun,
'AIC': res_ts.fun + 2 * 2,
'BIC': res_ts.fun + 2 * np.log(len(z_vals)),
},
'mu_data': {
'z': z_vals,
'mu': mu_cmb,
'mu_err': mu_err
}
}
def _fit_all(self):
"""
Fit models to all datasets simultaneously (combined analysis)
"""
print("Fitting combined analysis to all datasets...")
def chi2_lcdm_combined(params):
"""Combined chi-squared for LCDM across all datasets"""
H0, Om = params
chi2_total = 0
# Supernova contribution
mu_model_sn = self._distance_modulus_LCDM(
self.sn_data['z'], H0, Om, self.sn_M_B)
chi2_total += np.sum(((self.sn_data['mu'] -
mu_model_sn) / self.sn_data['mu_err'])**2)
# GRB contribution
mu_model_grb = self._distance_modulus_LCDM(
self.grb_data['z'], H0, Om, self.grb_M_B)
chi2_total += np.sum(((self.grb_data['mu'] -
mu_model_grb) / self.grb_data['sigma_mu'])**2)
# Cosmic Chronometers contribution
H_model_cc = self._H_LCDM(self.cc_data['z'], H0, Om)
chi2_total += np.sum(((self.cc_data['H'] -
H_model_cc) / self.cc_data['H_err'])**2)
# CMB contribution (simplified)
if 'mu_data' in self.results.get('CMB', {}):
z_cmb = self.results['CMB']['mu_data']['z']
mu_cmb = self.results['CMB']['mu_data']['mu']
mu_err_cmb = self.results['CMB']['mu_data']['mu_err']
# Use the same CMB model as in _fit_cmb but with fixed mu0
mu0_fixed = 5.0 # Or use the best-fit value from individual CMB fit
mu_model_cmb = np.log10(
1 + z_cmb) + np.log10(H0 / self.h_planck_measured) + mu0_fixed
chi2_total += np.sum(((mu_cmb - mu_model_cmb) / mu_err_cmb)**2)
return chi2_total
def chi2_time_scaling_combined(params):
"""Combined chi-squared for Time-Scaling model across all datasets"""
H0, alpha = params
chi2_total = 0
# Supernova contribution
mu_model_sn = self._distance_modulus_time_scaling(
self.sn_data['z'], H0, alpha, self.sn_M_B)
chi2_total += np.sum(((self.sn_data['mu'] -
mu_model_sn) / self.sn_data['mu_err'])**2)
# GRB contribution
mu_model_grb = self._distance_modulus_time_scaling(
self.grb_data['z'], H0, alpha, self.grb_M_B)
chi2_total += np.sum(((self.grb_data['mu'] -
mu_model_grb) / self.grb_data['sigma_mu'])**2)
# Cosmic Chronometers contribution
H_model_cc = self._H_time_scaling(self.cc_data['z'], H0, alpha)
chi2_total += np.sum(((self.cc_data['H'] -
H_model_cc) / self.cc_data['H_err'])**2)
# CMB contribution (simplified)
if 'mu_data' in self.results.get('CMB', {}):
z_cmb = self.results['CMB']['mu_data']['z']
mu_cmb = self.results['CMB']['mu_data']['mu']
mu_err_cmb = self.results['CMB']['mu_data']['mu_err']
# Use the same CMB model as in _fit_cmb but with fixed mu0
mu0_fixed = 5.0 # Or use the best-fit value from individual CMB fit
mu_model_cmb = np.log10(
1e3 / (1 + z_cmb)**(1 - alpha) * (H0 / self.h_planck_measured)) + mu0_fixed
chi2_total += np.sum(((mu_cmb - mu_model_cmb) / mu_err_cmb)**2)
return chi2_total
# Perform optimization
res_lcdm_combined = differential_evolution(
chi2_lcdm_combined, bounds=self.bounds_lcdm)
res_ts_combined = differential_evolution(
chi2_time_scaling_combined, bounds=self.bounds_ts)
# Calculate total number of data points
n_data_total = (len(self.sn_data['z']) + len(self.grb_data) +
len(self.cc_data['z']))
# Add CMB data points if available
if 'mu_data' in self.results.get('CMB', {}):
n_data_total += len(self.results['CMB']['mu_data']['z'])
# Store results
self.results['COMBINED'] = {
'LCDM': {
'params': res_lcdm_combined.x,
'chi2': res_lcdm_combined.fun,
'AIC': res_lcdm_combined.fun + 2*2, # 2 parameters
'BIC': res_lcdm_combined.fun + 2*np.log(n_data_total),
'chi2_reduced': res_lcdm_combined.fun / (n_data_total - 2)
},
'Time-Scaling': {
'params': res_ts_combined.x,
'chi2': res_ts_combined.fun,
'AIC': res_ts_combined.fun + 2*2, # 2 parameters
'BIC': res_ts_combined.fun + 2*np.log(n_data_total),
'chi2_reduced': res_ts_combined.fun / (n_data_total - 2)
}
}
print(
f"Combined analysis completed with {n_data_total} total data points")
def _fit_all_unified(self):
"""
Fit models to all datasets simultaneously with unified M_B treatment
"""
print("Fitting unified analysis to all datasets...")
def chi2_lcdm_unified(params):
"""Unified chi-squared for LCDM with simultaneous M_B fitting"""
H0, Om, M_B_sn, M_B_grb = params # Fit for both M_B values
chi2_total = 0
# Supernova contribution
mu_model_sn = self._distance_modulus_LCDM(
self.sn_data['z'], H0, Om, M_B_sn)
chi2_total += np.sum(((self.sn_data['mu'] -
mu_model_sn) / self.sn_data['mu_err'])**2)
# GRB contribution
mu_model_grb = self._distance_modulus_LCDM(
self.grb_data['z'], H0, Om, M_B_grb)
chi2_total += np.sum(((self.grb_data['mu'] -
mu_model_grb) / self.grb_data['sigma_mu'])**2)
# Cosmic Chronometers contribution (no M_B dependence)
H_model_cc = self._H_LCDM(self.cc_data['z'], H0, Om)
chi2_total += np.sum(((self.cc_data['H'] -
H_model_cc) / self.cc_data['H_err'])**2)
# CMB contribution (no M_B dependence)
if 'mu_data' in self.results.get('CMB', {}):
z_cmb = self.results['CMB']['mu_data']['z']
mu_cmb = self.results['CMB']['mu_data']['mu']
mu_err_cmb = self.results['CMB']['mu_data']['mu_err']
mu0_fixed = 5.0
mu_model_cmb = np.log10(
1 + z_cmb) + np.log10(H0 / self.h_planck_measured) + mu0_fixed
chi2_total += np.sum(((mu_cmb - mu_model_cmb) / mu_err_cmb)**2)
return chi2_total
def chi2_time_scaling_unified(params):
"""Unified chi-squared for Time-Scaling model with simultaneous M_B fitting"""
H0, alpha, M_B_sn, M_B_grb = params
chi2_total = 0
# Supernova contribution
mu_model_sn = self._distance_modulus_time_scaling(
self.sn_data['z'], H0, alpha, M_B_sn)
chi2_total += np.sum(((self.sn_data['mu'] -
mu_model_sn) / self.sn_data['mu_err'])**2)
# GRB contribution
mu_model_grb = self._distance_modulus_time_scaling(
self.grb_data['z'], H0, alpha, M_B_grb)
chi2_total += np.sum(((self.grb_data['mu'] -
mu_model_grb) / self.grb_data['sigma_mu'])**2)
# Cosmic Chronometers contribution
H_model_cc = self._H_time_scaling(self.cc_data['z'], H0, alpha)
chi2_total += np.sum(((self.cc_data['H'] -
H_model_cc) / self.cc_data['H_err'])**2)
# CMB contribution
if 'mu_data' in self.results.get('CMB', {}):
z_cmb = self.results['CMB']['mu_data']['z']
mu_cmb = self.results['CMB']['mu_data']['mu']
mu_err_cmb = self.results['CMB']['mu_data']['mu_err']
mu0_fixed = 5.0
mu_model_cmb = np.log10(
1e3 / (1 + z_cmb)**(1 - alpha) * (H0 / self.h_planck_measured)) + mu0_fixed
chi2_total += np.sum(((mu_cmb - mu_model_cmb) / mu_err_cmb)**2)
return chi2_total
def chi2_lcdm_cc_only(params):
"""LCDM chi-squared for CC data only"""
H0, Om = params
H_model_cc = self._H_LCDM(self.cc_data['z'], H0, Om)
return np.sum(((self.cc_data['H'] - H_model_cc) / self.cc_data['H_err'])**2)
def chi2_time_scaling_cc_only(params):
"""Time-Scaling chi-squared for CC data only"""
H0, alpha = params
H_model_cc = self._H_time_scaling(self.cc_data['z'], H0, alpha)
return np.sum(((self.cc_data['H'] - H_model_cc) / self.cc_data['H_err'])**2)
# Bounds including M_B parameters
bounds_lcdm_unified = [
self.bounds_lcdm[0], # H0 bounds
self.bounds_lcdm[1], # Om bounds
(-25, 25), # M_B_sn bounds (typical range)
(-35, 25) # M_B_grb bounds (typical range)
]
bounds_ts_unified = [
self.bounds_ts[0], # H0 bounds
self.bounds_ts[1], # alpha bounds
(-25, 25), # M_B_sn bounds
(-35, 25) # M_B_grb bounds
]
# Perform optimization for unified fits
res_lcdm_unified = differential_evolution(
chi2_lcdm_unified, bounds=bounds_lcdm_unified)
res_ts_unified = differential_evolution(
chi2_time_scaling_unified, bounds=bounds_ts_unified)
# Perform optimization for CC-only fits
res_lcdm_cc = differential_evolution(
chi2_lcdm_cc_only, bounds=self.bounds_lcdm)
res_ts_cc = differential_evolution(
chi2_time_scaling_cc_only, bounds=self.bounds_ts)
# Calculate total data points
n_data_total = (len(self.sn_data['z']) + len(self.grb_data) +
len(self.cc_data['z']))
if 'mu_data' in self.results.get('CMB', {}):
n_data_total += len(self.results['CMB']['mu_data']['z'])
n_data_cc = len(self.cc_data['z'])
# Store results with parameter names
self.results['COMBINED'] = {
'LCDM': {
'H0': res_lcdm_unified.x[0],
'Om': res_lcdm_unified.x[1],
'M_B_sn': res_lcdm_unified.x[2],
'M_B_grb': res_lcdm_unified.x[3],
'params': res_lcdm_unified.x,
'chi2': res_lcdm_unified.fun,
'AIC': res_lcdm_unified.fun + 2*4, # 4 parameters now
'BIC': res_lcdm_unified.fun + 4*np.log(n_data_total),
'chi2_reduced': res_lcdm_unified.fun / (n_data_total - 4)
},
'Time-Scaling': {
'H0': res_ts_unified.x[0],
'alpha': res_ts_unified.x[1],
'M_B_sn': res_ts_unified.x[2],
'M_B_grb': res_ts_unified.x[3],
'params': res_ts_unified.x,
'chi2': res_ts_unified.fun,
'AIC': res_ts_unified.fun + 2*4, # 4 parameters now
'BIC': res_ts_unified.fun + 4*np.log(n_data_total),
'chi2_reduced': res_ts_unified.fun / (n_data_total - 4)
}
}
# Store CC-only results
self.results['CC'] = {
'LCDM': {
'H0': res_lcdm_cc.x[0],
'Om': res_lcdm_cc.x[1],
'params': res_lcdm_cc.x,
'chi2': res_lcdm_cc.fun,
'AIC': res_lcdm_cc.fun + 2*2,
'BIC': res_lcdm_cc.fun + 2*np.log(n_data_cc),
'chi2_reduced': res_lcdm_cc.fun / (n_data_cc - 2)
},
'Time-Scaling': {
'H0': res_ts_cc.x[0],
'alpha': res_ts_cc.x[1],
'params': res_ts_cc.x,
'chi2': res_ts_cc.fun,
'AIC': res_ts_cc.fun + 2*2,
'BIC': res_ts_cc.fun + 2*np.log(n_data_cc),
'chi2_reduced': res_ts_cc.fun / (n_data_cc - 2)
}
}
def print_results(self):
print("\n" + "="*80)
print("COMPREHENSIVE MODEL FITTING RESULTS")
print("="*80)
datasets = ['CC', 'SN', 'GRB', 'CMB', 'COMBINED']
models = ['LCDM', 'Time-Scaling']
for dataset in datasets:
if dataset in self.results:
print(f"\n{dataset} Dataset:")
print("-" * 40)
for model in models:
if model in self.results[dataset]:
res = self.results[dataset][model]
params = res['params']
if model == 'LCDM':
if dataset == 'CMB':
print(f"{model:15s}: H₀={params[0]:.2f}")
else:
print(
f"{model:15s}: H₀={params[0]:.2f}, Ωₘ={params[1]:.3f}")
else: # Time-Scaling
print(
f"{model:15s}: H₀={params[0]:.2f}, α={params[1]:.3f}")
print(
f"{'':15s} χ²={res['chi2']:.2f}, AIC={res['AIC']:.2f}, BIC={res['BIC']:.2f}")
if 'chi2_reduced' in res:
print(f"{'':15s} χ²ᵣₑd={res['chi2_reduced']:.3f}")
# Add comparison for combined results
if dataset == 'COMBINED':
print("\n" + "-" * 40)
print("MODEL COMPARISON (Combined Analysis):")
lcdm_aic = self.results['COMBINED']['LCDM']['AIC']
ts_aic = self.results['COMBINED']['Time-Scaling']['AIC']
delta_aic = abs(lcdm_aic - ts_aic)
better_model = "LCDM" if lcdm_aic < ts_aic else "Time-Scaling"
print(f"ΔAIC = {delta_aic:.2f} (favors {better_model})")
lcdm_bic = self.results['COMBINED']['LCDM']['BIC']
ts_bic = self.results['COMBINED']['Time-Scaling']['BIC']
delta_bic = abs(lcdm_bic - ts_bic)
better_model_bic = "LCDM" if lcdm_bic < ts_bic else "Time-Scaling"
print(
f"ΔBIC = {delta_bic:.2f} (favors {better_model_bic})")
def plot_observations_fit(self):
"""Create comprehensive plot of observational data fits"""
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
# Cosmic Chronometers plot
ax = axes[0, 0]
z_cc = self.cc_data['z']
H_obs = self.cc_data['H']
H_err = self.cc_data['H_err']
ax.errorbar(z_cc, H_obs, yerr=H_err, fmt='o', color='black',
label='CC Data', markersize=4)
z_plot_cc = np.linspace(min(z_cc), max(z_cc), 100)
lcdm_params = self.results['CC']['LCDM']['params']
ts_params = self.results['CC']['Time-Scaling']['params']
H_lcdm = self._H_LCDM(z_plot_cc, *lcdm_params)
H_ts = self._H_time_scaling(z_plot_cc, *ts_params)
ax.plot(z_plot_cc, H_lcdm, '-', color='red',
label='ΛCDM', linewidth=2)
ax.plot(z_plot_cc, H_ts, '--', color='blue',
label='Time-Scaling', linewidth=2)
ax.set_xlabel('Redshift z')
ax.set_ylabel('H(z) [km/s/Mpc]')
ax.set_title('Cosmic Chronometers')
ax.legend()
ax.grid(True, alpha=0.3)
# Add informative textbox for CC
cc_lcdm_chi2 = self.results['CC']['LCDM'].get('chi2', 'N/A')
cc_ts_chi2 = self.results['CC']['Time-Scaling'].get('chi2', 'N/A')
cc_text = f'ΛCDM: H₀={lcdm_params[0]:.1f}'
if cc_lcdm_chi2 != 'N/A':
cc_text += f', χ²={cc_lcdm_chi2:.2f}'
cc_text += f'\nTime-Scaling: H₀={ts_params[0]:.1f}, α={ts_params[1]:.3f}'
if cc_ts_chi2 != 'N/A':
cc_text += f', χ²={cc_ts_chi2:.2f}'
ax.text(0.05, 0.05, cc_text, transform=ax.transAxes, fontsize=10,
verticalalignment='bottom', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
# Supernova plot
ax = axes[0, 1]
z_sn = self.sn_data['z']
mu_obs = self.sn_data['mu']
mu_err = self.sn_data['mu_err']
ax.errorbar(z_sn, mu_obs, yerr=mu_err, fmt='o', color='black',
label='SN Data', alpha=0.7, markersize=2)
z_plot = np.linspace(min(z_sn), max(z_sn), 100)
lcdm_params = self.results['SN']['LCDM']['params']
ts_params = self.results['SN']['Time-Scaling']['params']
mu_lcdm = self._distance_modulus_LCDM(
z_plot, *lcdm_params, M_B=self.sn_M_B)
mu_ts = self._distance_modulus_time_scaling(
z_plot, *ts_params, M_B=self.sn_M_B)
ax.plot(z_plot, mu_lcdm, '-', color='red', label='ΛCDM', linewidth=2)
ax.plot(z_plot, mu_ts, '--', color='blue',
label='Time-Scaling', linewidth=2)
ax.set_xlabel('Redshift z')
ax.set_ylabel('Distance Modulus μ')
ax.set_title('Type Ia Supernovae')
ax.legend()
ax.grid(True, alpha=0.3)
# Add informative textbox for SN
sn_lcdm_chi2 = self.results['SN']['LCDM'].get('chi2', 'N/A')
sn_ts_chi2 = self.results['SN']['Time-Scaling'].get('chi2', 'N/A')
sn_text = f'ΛCDM: H₀={lcdm_params[0]:.1f}, Ωₘ={lcdm_params[1]:.3f}'
if sn_lcdm_chi2 != 'N/A':
sn_text += f', χ²={sn_lcdm_chi2:.2f}'
sn_text += f'\nTime-Scaling: H₀={ts_params[0]:.1f}, α={ts_params[1]:.3f}'
if sn_ts_chi2 != 'N/A':
sn_text += f', χ²={sn_ts_chi2:.2f}'
ax.text(0.05, 0.05, sn_text, transform=ax.transAxes, fontsize=10,
verticalalignment='bottom', bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8))
# GRB plot
ax = axes[1, 0]
z_grb = self.grb_data['z']
mu_grb = self.grb_data['mu']
err_grb = self.grb_data['sigma_mu']
ax.errorbar(z_grb, mu_grb, yerr=err_grb, fmt='o', color='black',
label='GRB Data', markersize=4)
z_plot_grb = np.linspace(min(z_grb), max(z_grb), 100)
lcdm_params_grb = self.results['GRB']['LCDM']['params']
ts_params_grb = self.results['GRB']['Time-Scaling']['params']
mu_lcdm_grb = self._distance_modulus_LCDM(
z_plot_grb, *lcdm_params_grb, M_B=self.grb_M_B)
mu_ts_grb = self._distance_modulus_time_scaling(
z_plot_grb, *ts_params_grb, M_B=self.grb_M_B)
ax.plot(z_plot_grb, mu_lcdm_grb, '-', color='red',
label='ΛCDM', linewidth=2)
ax.plot(z_plot_grb, mu_ts_grb, '--', color='blue',
label='Time-Scaling', linewidth=2)
ax.set_xlabel('Redshift z')
ax.set_ylabel('Distance Modulus μ')
ax.set_title('Gamma-Ray Bursts')
ax.legend()
ax.grid(True, alpha=0.3)
# Add informative textbox for GRB
grb_lcdm_chi2 = self.results['GRB']['LCDM'].get('chi2', 'N/A')
grb_ts_chi2 = self.results['GRB']['Time-Scaling'].get('chi2', 'N/A')
grb_text = f'ΛCDM: H₀={lcdm_params_grb[0]:.1f}, Ωₘ={lcdm_params_grb[1]:.3f}'
if grb_lcdm_chi2 != 'N/A':
grb_text += f', χ²={grb_lcdm_chi2:.2f}'
grb_text += f'\nTime-Scaling: H₀={ts_params_grb[0]:.1f}, α={ts_params_grb[1]:.3f}'
if grb_ts_chi2 != 'N/A':
grb_text += f', χ²={grb_ts_chi2:.2f}'
ax.text(0.05, 0.05, grb_text, transform=ax.transAxes, fontsize=10,
verticalalignment='bottom', bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))
# CMB plot
ax = axes[1, 1]
# Real Planck-transformed data
z_vals = self.results['CMB']['mu_data']['z']
mu_vals = self.results['CMB']['mu_data']['mu']
mu_err = self.results['CMB']['mu_data']['mu_err']
ax.errorbar(z_vals, mu_vals, yerr=mu_err, fmt='.', color='black',
label='Planck-derived $\\mu_{\\mathrm{CMB}}$', alpha=0.5)
# Smooth model fits
z_dense = np.linspace(min(z_vals), max(z_vals), 500)
# ΛCDM model parameters
H0_lcdm, mu0_lcdm = self.results['CMB']['LCDM']['params']
mu_lcdm = np.log10(1 + z_dense) + np.log10(H0_lcdm /
self.h_planck_measured) + mu0_lcdm
# Time-Scaling model parameters
H0_ts, alpha_ts, mu0_ts = self.results['CMB']['Time-Scaling']['params']
mu_ts = np.log10(1e3 / (1 + z_dense) ** (1 - alpha_ts)
* (H0_ts / self.h_planck_measured)) + mu0_ts
# Plot model curves
ax.plot(z_dense, mu_lcdm, 'r-', linewidth=2,
label=fr'ΛCDM Fit')
ax.plot(z_dense, mu_ts, 'b--', linewidth=2,
label=fr'Time-Scaling Fit')
# Axis and legend
ax.set_xlabel('Redshift z (ℓ / 14)')
ax.set_ylabel(r'$\mu_{\mathrm{CMB}} = \log_{10} D_\ell$')
ax.set_title('Planck 2018 TT')
ax.grid(True, alpha=0.3)
ax.legend()
# Enhanced informative textbox for CMB (keeping the detailed format from original)
cmb_lcdm_chi2 = self.results['CMB']['LCDM'].get('chi2', 'N/A')
cmb_ts_chi2 = self.results['CMB']['Time-Scaling'].get('chi2', 'N/A')
cmb_text = f'ΛCDM: H₀={H0_lcdm:.2f}, μ₀={mu0_lcdm:.2f}'
if cmb_lcdm_chi2 != 'N/A':
cmb_text += f', χ²={cmb_lcdm_chi2:.2f}'
cmb_text += f'\nTime-Scaling: H₀={H0_ts:.2f}, α={alpha_ts:.2f}, μ₀={mu0_ts:.2f}'
if cmb_ts_chi2 != 'N/A':
cmb_text += f', χ²={cmb_ts_chi2:.2f}'
ax.text(0.05, 0.05, cmb_text, transform=ax.transAxes, fontsize=10,
verticalalignment='bottom', bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.8))
plt.tight_layout()
return fig
def plot_observations_fit_combined(self):
# COMBINED plot - Corrected version
fig, ax = plt.subplots(figsize=(16, 12))
# Plot all datasets together with different colors/markers
# Supernova data
ax.errorbar(self.sn_data['z'], self.sn_data['mu'], yerr=self.sn_data['mu_err'],
fmt='o', color='red', alpha=0.6, markersize=4, label='Supernovae')
# GRB data
ax.errorbar(self.grb_data['z'], self.grb_data['mu'], yerr=self.grb_data['sigma_mu'],
fmt='^', color='blue', alpha=0.6, markersize=4, label='GRBs')
# CMB data (if available)
if 'mu_data' in self.results.get('CMB', {}):
z_cmb = self.results['CMB']['mu_data']['z']
mu_cmb = self.results['CMB']['mu_data']['mu']
mu_err_cmb = self.results['CMB']['mu_data']['mu_err']
ax.errorbar(z_cmb, mu_cmb, yerr=mu_err_cmb, fmt='s', color='green',
alpha=0.6, markersize=4, label='CMB-derived')
# Create redshift range for smooth model curves
z_min = min(np.min(self.sn_data['z']), np.min(self.grb_data['z']))
z_max = max(np.max(self.sn_data['z']), np.max(self.grb_data['z']))
if 'mu_data' in self.results.get('CMB', {}):
z_min = min(z_min, np.min(self.results['CMB']['mu_data']['z']))
z_max = max(z_max, np.max(self.results['CMB']['mu_data']['z']))
z_dense = np.linspace(z_min, z_max, 500)
# ΛCDM model parameters (4 parameters: H0, Om, M_B_sn, M_B_grb)
H0_lcdm, Om_lcdm, M_B_sn_lcdm, M_B_grb_lcdm = self.results['COMBINED']['LCDM']['params']
# Time-Scaling model parameters (4 parameters: H0, alpha, M_B_sn, M_B_grb)
H0_ts, alpha_ts, M_B_sn_ts, M_B_grb_ts = self.results['COMBINED']['Time-Scaling']['params']
# Plot ΛCDM model curves for both SN and GRB using their respective M_B
mu_lcdm_sn = self._distance_modulus_LCDM(
z_dense, H0_lcdm, Om_lcdm, M_B_sn_lcdm)
mu_lcdm_grb = self._distance_modulus_LCDM(
z_dense, H0_lcdm, Om_lcdm, M_B_grb_lcdm)
# Plot Time-Scaling model curves
mu_ts_sn = self._distance_modulus_time_scaling(
z_dense, H0_ts, alpha_ts, M_B_sn_ts)
mu_ts_grb = self._distance_modulus_time_scaling(
z_dense, H0_ts, alpha_ts, M_B_grb_ts)
# Plot model curves
ax.plot(z_dense, mu_lcdm_sn, 'r-',
linewidth=2, label='ΛCDM (SN scale)')
ax.plot(z_dense, mu_lcdm_grb, 'r:',
linewidth=2, label='ΛCDM (GRB scale)')
ax.plot(z_dense, mu_ts_sn, 'b-', linewidth=2,