-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEParVI.py
5572 lines (4583 loc) · 218 KB
/
EParVI.py
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
# -*- coding: utf-8 -*-
"""EParVI [publish].ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1S4nauGK_Hit7UQdvJz1zLFnL3M34x-jG
"""
wd = '~/EH for sampling/Yong/'
"""# shared funcs."""
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import gamma
from matplotlib.colors import LinearSegmentedColormap, Normalize
import os
import time
import pickle
from scipy.spatial.distance import cdist
import copy
from scipy.stats import multivariate_normal
from scipy.stats import norm
np.random.seed(111)
# Metropolis-Hastings sampling for generating ground truth samples
def metropolis_hastings(target_p, num_samples, proposal_std=1.0):
# Initial guess
x_current = np.random.randn(2)
samples = []
for _ in range(num_samples):
# Propose a new point
x_proposal = x_current + np.random.randn(2) * proposal_std
# Calculate acceptance ratio
acceptance_ratio = target_p(x_proposal) / target_p(x_current)
# Accept or reject the new point
if np.random.rand() < acceptance_ratio:
x_current = x_proposal
samples.append(x_current)
return np.array(samples)
# compute the comparison metric MMD**2
def polynomial_kernel(x, y):
return (np.dot(x, y.T) / 3 + 1) ** 3
def compute_mmd2(X, Y):
N = X.shape[0]
M = Y.shape[0]
# Compute the polynomial kernel values
Kxx = polynomial_kernel(X, X) # Kernel between all pairs in X
Kyy = polynomial_kernel(Y, Y) # Kernel between all pairs in Y
Kxy = polynomial_kernel(X, Y) # Kernel between all pairs in X and Y
# Compute the terms in the MMD squared formula
term1 = (1 / (N * N)) * np.sum(Kxx)
term2 = (1 / (M * M)) * np.sum(Kyy)
term3 = (2 / (N * M)) * np.sum(Kxy)
# Compute MMD squared
mmd2 = term1 + term2 - term3
return mmd2
# X = np.random.randn(200, 2)
# Y = np.random.randn(5000, 2)
# mmd2_value = compute_mmd2(X, Y)
# print(f"MMD^2: {mmd2_value}")
# General parameters (can be over-written later for each individual case)
def set_params(update_rule, overwrite_params_dict=None):
M_neg = 400 # Number of negative charges
M_pos = 50**2 # Number of positive charges
d = 2 # Dimensionality
q_neg = np.ones(M_neg) # Charge of negative particles
q_pos = 1.0 # Charge of positive particles
q_pos_auto_annealing = False
epsilon_0 = 8.854e-12 # Permittivity of free space; alternatively: 55.26349406
SEED = 111 # Random seed for reproducibility
num_steps = 100 # Number of time steps
plot_interval = 5 # Plot every 10 steps
normalize_overall_forces = True # Whether to normalize forces or not. It affects the choose of step size later.
normalise_attr_forces = False # Whether to normalize attracting forces or not
particle_filtering = False
move_threshold = 1e-4 # Movement threshold for early stopping
patience = 5 # Number of consecutive steps with small movements to trigger early stopping
tau = 0.1
delta_t = 0.01
noise_std = 0
if update_rule == 'Euler':
tau = 0.1 # Time step size
noise_std = 0.01 # Standard deviation for Gaussian noise added to the positions
elif update_rule == 'Verlet':
q_pos = 5.0
num_steps = 300
delta_t = 0.01 # Time step size
noise_std = 0 # Standard deviation for Gaussian noise added to the positions
elif update_rule == 'damped_Verlet':
q_pos = 5.0
num_steps = 300
tau = 0.5 # Parameter tau
delta_t = 0.1 # Time step size
noise_std = 0
params_dict = {
'M_neg': M_neg,
'M_pos': M_pos,
'd': d,
'q_neg': q_neg,
'q_pos': q_pos,
'q_pos_auto_annealing': q_pos_auto_annealing,
'epsilon_0': epsilon_0,
'SEED': SEED,
'num_steps': num_steps,
'plot_interval': plot_interval,
'normalize_overall_forces': normalize_overall_forces,
'normalise_attr_forces': normalise_attr_forces,
'particle_filtering': particle_filtering,
'move_threshold': move_threshold,
'patience': patience,
'tau': tau,
'delta_t': delta_t,
'noise_std': noise_std
}
# overwrite parameters if provided
if overwrite_params_dict is not None:
for key, value in overwrite_params_dict.items():
if key in params_dict:
params_dict[key] = value
return params_dict
def initialize_positions(target_p, M_neg, M_pos, d, init_dict=None, SEED=111):
np.random.seed(SEED)
init_type = init_dict['init_type']
# Initialize the positions of the positive charges on a grid within [low_xy, high_xy] x [low_xy, high_xy]
grid_size = int(np.ceil(M_pos**(1/d)))
linspace = np.linspace(init_dict['low_xy'], init_dict['high_xy'], grid_size)
mesh = np.meshgrid(*([linspace]*d))
x_pos = np.vstack([m.ravel() for m in mesh]).T[:M_pos]
# Initialize the positions of the negative charges within [low_uniform, high_uniform] x [low_uniform, high_uniform]
if init_type == 'uniform':
uniform_boundaries = [(init_dict['low_uniform'], init_dict['high_uniform']), (init_dict['low_uniform'], init_dict['high_uniform'])]
x_neg = np.random.uniform(
low=[low for (low, high) in uniform_boundaries],
high=[high for (low, high) in uniform_boundaries],
size=(M_neg, d)
)
elif init_type == 'gaussian':
x_neg = np.random.normal(loc=init_dict['initial_gaussian_center'], scale=init_dict['initial_gaussian_std'], size=(M_neg, d))
x_neg = np.clip(x_neg, init_dict['low_xy'], init_dict['high_xy'])
elif init_type == 'probabilistic':
# Grid points
grid_size = 100
linspace = np.linspace(init_dict['low_xy'], init_dict['high_xy'], grid_size)
mesh = np.meshgrid(*([linspace] * d))
grid_points = np.vstack([m.ravel() for m in mesh]).T
# Compute probability mass at each grid point
probabilities = target_p(grid_points)
probabilities = probabilities.flatten()
probabilities /= np.sum(probabilities) # Normalize to sum to 1
# Sample indices based on the probabilities
sampled_indices = np.random.choice(len(grid_points), size=M_neg, p=probabilities)
x_neg = grid_points[sampled_indices]
else:
raise ValueError("init_type must be either 'uniform', 'gaussian', or 'probabilistic'")
return x_neg, x_pos
def compute_forces(x_neg, x_pos, q_neg, q_pos, target_p, epsilon_0, d, normalise_attr_forces):
M_neg = x_neg.shape[0]
M_pos = x_pos.shape[0]
F_rep = np.zeros_like(x_neg)
F_attr = np.zeros_like(x_neg)
# Compute the normalization constant for target_p if normalization is enabled
if normalise_attr_forces:
attr_normalization_constant = np.sum([target_p(x_pos[i_prime]) for i_prime in range(M_pos)])
else:
attr_normalization_constant = 1 # Set to 1 to avoid altering the target_p values
# Compute repulsive forces
for j in range(M_neg):
for i in range(M_neg):
if i != j:
r_ij = np.linalg.norm(x_neg[j] - x_neg[i])
if r_ij > 0:
F_rep[j] += (q_neg[i] * q_neg[j] * gamma(d/2)) / (2 * np.pi**(d/2) * epsilon_0 * r_ij**(d-1)) * (x_neg[j] - x_neg[i]) / r_ij
# Compute attractive forces
for j in range(M_neg):
for i_prime in range(M_pos):
r_ij = np.linalg.norm(x_neg[j] - x_pos[i_prime])
if r_ij > 0:
normalized_target_p = target_p(x_pos[i_prime]) / attr_normalization_constant
F_attr[j] -= (q_pos * normalized_target_p * q_neg[j] * gamma(d/2)) / (2 * np.pi**(d/2) * epsilon_0 * r_ij**(d-1)) * (x_neg[j] - x_pos[i_prime]) / r_ij
print(f'F_rep:\n {F_rep[:10]} \n F_attr:\n {F_attr[:10]}')
return F_rep, F_attr, F_rep + F_attr
def plot_density(target_p, x_min, x_max, y_min, y_max, num_points=100):
x = np.linspace(x_min, x_max, num_points)
y = np.linspace(y_min, y_max, num_points)
X, Y = np.meshgrid(x, y)
Z = np.array([target_p(np.array([x, y])) for x, y in zip(np.ravel(X), np.ravel(Y))])
Z = Z.reshape(X.shape)
# create a custom white-dark pink colormap
colors = [(1, 1, 1), (0.6, 0, 0.3)] # white to dark pink
n_bins = 100 # Discretize the interpolation into 100 steps
cmap_name = 'white_dark_pink'
cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins)
return X, Y, Z, cm
def evolve_system(init_dict, update_rule, x_neg, x_pos, params_dict, target_p, ground_truth_samples):
d = params_dict['d']
q_neg = params_dict['q_neg']
q_pos = params_dict['q_pos']
q_pos_auto_annealing = params_dict['q_pos_auto_annealing']
num_steps = params_dict['num_steps']
plot_interval = params_dict['plot_interval']
normalize_overall_forces = params_dict['normalize_overall_forces']
normalise_attr_forces = params_dict['normalise_attr_forces']
particle_filtering = params_dict['particle_filtering']
move_threshold = params_dict['move_threshold']
patience = params_dict['patience']
noise_std = params_dict['noise_std']
delta_t = params_dict['delta_t']
epsilon_0 = params_dict['epsilon_0']
tau = params_dict['tau']
low_xy = init_dict['low_xy']
high_xy = init_dict['high_xy']
margin = init_dict['margin']
x_neg_prev = x_neg.copy()
consecutive_small_moves = 0
# create a dict to store all negative particle trajectories
all_trajectories = {idx: [] for idx in range(params_dict['M_neg'])}
# plot theoretical density
fig, ax = plt.subplots(figsize=(8, 6))
X, Y, Z, cm = plot_density(target_p, low_xy-margin, high_xy+margin, low_xy-margin, high_xy+margin)
img = ax.imshow(Z, extent=(low_xy-margin, high_xy+margin, low_xy-margin, high_xy+margin), origin='lower', cmap=cm, alpha=0.5)
if not os.path.exists('plots'):
os.makedirs('plots')
# Move negative particles
particle_counts_vec = []
remained_neg_indices_all_iterations = []
removed_neg_indices_all_iterations = []
original_neg_indices = np.arange(params_dict['M_neg'])
if q_pos_auto_annealing and normalise_attr_forces: # then q_pos=params_dict['q_pos'] is interpreted as how many times at initial the positive charge is
init_F_rep = compute_forces(x_neg, x_pos, q_neg, q_pos, target_p, epsilon_0, d, normalise_attr_forces)[0]
init_distances = cdist(x_neg, x_pos, metric='euclidean')
median_init_distances = np.median(init_distances.flatten())
q_pos0 = q_pos * np.max(np.abs(init_F_rep)) * median_init_distances**(d-1) * epsilon_0 * 2 * np.pi**(d/2) / (q_neg[0] * gamma(d/2))
q_pos = copy.deepcopy(q_pos0)
print(f'q_pos: {q_pos}')
step_time_vec = []
MMD2_vec = []
NLL_vec = []
for t in range(num_steps):
print(f'step: {t}')
start_time = time.time()
# count how many of x_neg are lying within the square [low_xy,high_xy]×[low_xy,high_xy] in the current iteration.
mask = (x_neg[:, 0] >= low_xy) & (x_neg[:, 0] <= high_xy) & (x_neg[:, 1] >= low_xy) & (x_neg[:, 1] <= high_xy)
count = np.sum(mask); particle_counts_vec.append(count)
print(f'no. of negative charges currently contained within the square [{low_xy},{high_xy}] (particle_filtering:{particle_filtering}): {count}')
if particle_filtering: # remove those negative charges falling outside
x_neg = x_neg[mask]
remained_indices = original_neg_indices[mask]
removed_indices = original_neg_indices[~mask]
remained_neg_indices_all_iterations.append(remained_indices.tolist())
removed_neg_indices_all_iterations.append(removed_indices.tolist())
original_neg_indices = remained_indices
else:
remained_indices = original_neg_indices
# attach the trajectories
for idx_original, idx_new in zip(remained_indices, np.arange(len(remained_indices))):
all_trajectories[idx_original].append(x_neg[idx_new].copy())
# compute MMD^2 and mean logp
mmd2_value = compute_mmd2(x_neg[remained_indices], ground_truth_samples); MMD2_vec.append(mmd2_value)
nll_value = -np.mean(np.log(target_p(x_neg[remained_indices])+1e-10)); NLL_vec.append(nll_value)
# plot intermediate figures
if t % plot_interval == 0 or t == num_steps - 1:
# plot negative particles
ax.clear()
img = ax.imshow(Z, extent=(low_xy-margin, high_xy+margin, low_xy-margin, high_xy+margin), origin='lower', cmap=cm, alpha=0.5)
scatter_neg = ax.scatter(x_neg[:, 0], x_neg[:, 1], c='blue', s=3, label='Negative charges')
# Color the positive charges based on their probability values
# pos_p_values = target_p(x_pos)
# norm = Normalize(vmin=np.min(pos_p_values), vmax=np.max(pos_p_values))
# pos_colors = plt.cm.autumn(norm(pos_p_values))
# scatter_pos = ax.scatter(x_pos[:, 0], x_pos[:, 1], facecolor=pos_colors, label='Positive charges', marker='o', s=1, linewidths=1.5)
# Draw grid lines aligned with the positive charge positions
# grid_lines = np.unique(x_pos)
# ax.grid(color='lightgrey', linestyle='-', linewidth=0.5)
# ax.set_xticks(grid_lines[::10])
# ax.set_yticks(grid_lines[::10])
ax.set_xlim(low_xy-margin, high_xy+margin)
ax.set_ylim(low_xy-margin, high_xy+margin)
ax.set_xlabel(r'$x_1$')
ax.set_ylabel(r'$x_2$')
ax.set_title(f'Distribution of charges at Step {t}')
# ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=2)
# save the figure
plt.savefig(wd+f'plots/step_{t}.png')
# Now x_neg, x_pos (and q_pos) are both set up, we are ready to comput the forces.
F_rep, F_attr, F = compute_forces(x_neg, x_pos, q_neg, q_pos, target_p, epsilon_0, d, normalise_attr_forces)
if normalize_overall_forces:
# Normalize the force vectors for each particle
norm_F = np.linalg.norm(F, axis=1).reshape(-1, 1)
norm_F[norm_F == 0] = 1 # Avoid division by zero
F = F / norm_F
if update_rule == 'Euler':
# Simple Euler method
delta_x = tau * F
elif update_rule == 'Verlet':
# Verlet Integration (Leapfrog Method)
delta_x = F * (delta_t ** 2) + 2 * x_neg - x_neg_prev - x_neg
elif update_rule == 'damped_Verlet':
# Damped Verlet Integration (Modified Method)
delta_x = tau * (F * (delta_t ** 2) + (x_neg - x_neg_prev))
else:
raise ValueError("Invalid update rule specified.")
x_neg_next = x_neg + delta_x
# Add Gaussian noise to the positions
noise = np.random.normal(loc=0, scale=noise_std, size=x_neg.shape)
x_neg_next += noise
# Update positions
x_neg_prev = x_neg.copy()
x_neg = x_neg_next
# annealing q_pos
if q_pos_auto_annealing and normalise_attr_forces:
q_pos = np.max([(q_pos0 - 1) * np.exp(-0.1 * t) + 1, 0.5*q_pos0]) # q_pos decreases from q_pos and lower bounded by 1 = q_neg
print(f'q_pos: {q_pos}')
end_time = time.time(); step_time = end_time - start_time; print(f'step time: {step_time} seconds')
step_time_vec.append(step_time)
# save x_neg in each iteration
np.savez(wd+f'plots/[step:{t}: x_neg, x_pos, step_time, mmd2_value, nll_value].npz',
x_neg=x_neg, x_pos=x_pos, step_time=step_time, mmd2_value=mmd2_value, nll_value=nll_value)
# check for early stopping
if np.all(np.linalg.norm(delta_x + noise, axis=1) < move_threshold):
consecutive_small_moves += 1
else:
consecutive_small_moves = 0
if consecutive_small_moves >= patience:
print(f"Early stopping at step {t} due to small movements.")
break
return x_neg, all_trajectories, particle_counts_vec, remained_neg_indices_all_iterations, removed_neg_indices_all_iterations, step_time_vec, MMD2_vec, NLL_vec
# plot the all_trajectories of selected particles
def trajectory_plot(all_trajectories, selected_indices, target_p, x_pos, low_xy, high_xy, margin, params_dict, init_dict, total_time):
fig, ax = plt.subplots(figsize=(8, 6))
X, Y, Z, cm = plot_density(target_p, low_xy-margin, high_xy+margin, low_xy-margin, high_xy+margin)
img = ax.imshow(Z, extent=(low_xy-margin, high_xy+margin, low_xy-margin, high_xy+margin), origin='lower', cmap=cm, alpha=0.5)
# Plot positive charges
norm = Normalize(vmin=np.min(target_p(x_pos)), vmax=np.max(target_p(x_pos)))
pos_colors = plt.cm.autumn(norm(target_p(x_pos)))
scatter_pos = ax.scatter(x_pos[:, 0], x_pos[:, 1], facecolor=pos_colors, label='Positive charges', marker='o', s=1, linewidths=1.5)
grid_lines = np.unique(x_pos)
ax.grid(color='lightgrey', linestyle='-', linewidth=0.5)
ax.set_xticks(grid_lines[::10])
ax.set_yticks(grid_lines[::10])
# Create a colormap for the trajectories
num_colors = len(selected_indices)
colors = plt.cm.viridis(np.linspace(0, 1, num_colors))
# Plot all trajectories
for idx, color in zip(selected_indices, colors):
traj = np.array(all_trajectories[idx])
ax.plot(traj[:, 0], traj[:, 1], color=color, label='Trajectory' if idx == selected_indices[0] else "") # Plot entire trajectory
ax.scatter(traj[0, 0], traj[0, 1], color=color, marker='o', s=60, label='Initial position' if idx == selected_indices[0] else "") # Initial position
ax.scatter(traj[-1, 0], traj[-1, 1], color=color, marker='s', s=60, label='Final position' if idx == selected_indices[0] else "") # Final position
ax.set_xlim(low_xy-margin, high_xy+margin)
ax.set_ylim(low_xy-margin, high_xy+margin)
ax.set_xlabel(r'$x_1$')
ax.set_ylabel(r'$x_2$')
ax.set_title('Trajectories of selected particles')
# ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=4)
plt.savefig(wd+f"plots/selected_trajectories (M_neg:{params_dict['M_neg']},M_pos:{params_dict['M_pos']},num_steps:{params_dict['num_steps']},init_type:{init_dict['init_type']},total_time:{total_time}).png")
plt.show()
"""# Gaussian2D: uni-modal."""
np.random.seed(111)
def target_p(x):
return np.exp(-np.sum((x - 0.5)**2) / 0.1)
update_rule = 'Verlet'
params_dict = set_params(update_rule,{'q_pos': 1.0,
'q_pos_auto_annealing': False,
'normalize_overall_forces': True,
'normalise_attr_forces': False,
'particle_filtering': False,
'noise_std':0}) # noise_std: 0 or 0.01
init_dict = {'init_type':'uniform', 'low_uniform':0, 'high_uniform':0.5, 'low_xy': 0, 'high_xy': 1, 'margin':0.1}
start_time = time.time()
# Initialize positions with a seed for reproducibility
x_neg, x_pos = initialize_positions(target_p=target_p,
M_neg=params_dict['M_neg'],
M_pos=params_dict['M_pos'],
d=params_dict['d'],
init_dict=init_dict,
SEED=params_dict['SEED'])
# generate 5000 ground truth samples
samples = metropolis_hastings(target_p, 5000)
# Evolve the system and plot intermediate steps
x_neg_final, all_trajectories, particle_counts_vec, remained_neg_indices_all_iterations, removed_neg_indices_all_iterations, step_time_vec, MMD2_vec, NLL_vec = evolve_system(
init_dict=init_dict,
update_rule=update_rule,
x_neg=x_neg,
x_pos=x_pos,
params_dict=params_dict,
target_p=target_p,
ground_truth_samples=samples)
end_time = time.time(); total_time = end_time - start_time; print(f'total run time: {total_time} seconds')
# plot trajectories for selected particles
selected_indices = [0,100,200,299]
trajectory_plot(all_trajectories=all_trajectories,
selected_indices=selected_indices,
target_p=target_p,
x_pos=x_pos,
low_xy=init_dict['low_xy'],
high_xy=init_dict['high_xy'],
margin=init_dict['margin'],
params_dict=params_dict,
init_dict=init_dict,
total_time=total_time)
# save results
results_dict = {'update_rule':update_rule,
'params_dict':params_dict,
'init_dict':init_dict,
'init_x_neg':x_neg,
'init_x_pos':x_pos,
'x_neg_final':x_neg_final,
'all_trajectories':all_trajectories,
'particle_counts_vec': particle_counts_vec,
'selected_indices':selected_indices,
'total_time':total_time,
'step_time_vec':step_time_vec,
'MMD2_vec':MMD2_vec,
'NLL_vec':NLL_vec}
# saving the dictionary
with open(wd+'plots/results_dict.pkl', 'wb') as file:
pickle.dump(results_dict, file)
"""# Gaussian2D: bi-modal."""
np.random.seed(111)
def target_p(x):
x1, x2 = np.atleast_2d(x).T
mean1 = np.array([0, 0])
cov1 = np.array([[1, -0.5], [-0.5, 1]])
mean2 = np.array([4, 4])
cov2 = np.array([[1, 0.5], [0.5, 1]])
diff1 = np.stack([x1 - mean1[0], x2 - mean1[1]], axis=-1)
inv_cov1 = np.linalg.inv(cov1)
exponent1 = -0.5 * np.einsum('...i,ij,...j->...', diff1, inv_cov1, diff1)
diff2 = np.stack([x1 - mean2[0], x2 - mean2[1]], axis=-1)
inv_cov2 = np.linalg.inv(cov2)
exponent2 = -0.5 * np.einsum('...i,ij,...j->...', diff2, inv_cov2, diff2)
return 0.7*np.exp(exponent1) + 0.3*np.exp(exponent2)
update_rule = 'Euler'
params_dict = set_params(update_rule,{'q_pos': 1.0,
'q_pos_auto_annealing': False,
'normalize_overall_forces': True,
'normalise_attr_forces': False,
'particle_filtering': False,
'noise_std':0})
init_dict = {'init_type':'uniform', 'low_uniform':-3, 'high_uniform':7, 'low_xy': -3, 'high_xy': 7, 'margin':0}
start_time = time.time()
# Initialize positions with a seed for reproducibility
x_neg, x_pos = initialize_positions(target_p=target_p,
M_neg=params_dict['M_neg'],
M_pos=params_dict['M_pos'],
d=params_dict['d'],
init_dict=init_dict,
SEED=params_dict['SEED'])
# Egenerate 5000 ground truth samples
samples = metropolis_hastings(target_p, 5000)
# Evolve the system and plot intermediate steps
x_neg_final, all_trajectories, particle_counts_vec, remained_neg_indices_all_iterations, removed_neg_indices_all_iterations, step_time_vec, MMD2_vec, NLL_vec = evolve_system(
init_dict=init_dict,
update_rule=update_rule,
x_neg=x_neg,
x_pos=x_pos,
params_dict=params_dict,
target_p=target_p,
ground_truth_samples=samples)
end_time = time.time(); total_time = end_time - start_time; print(f'total run time: {total_time} seconds')
# plot trajectories for selected particles
selected_indices = [0,100,200,299]
trajectory_plot(all_trajectories=all_trajectories,
selected_indices=selected_indices,
target_p=target_p,
x_pos=x_pos,
low_xy=init_dict['low_xy'],
high_xy=init_dict['high_xy'],
margin=init_dict['margin'],
params_dict=params_dict,
init_dict=init_dict,
total_time=total_time)
# save results
results_dict = {'update_rule':update_rule,
'params_dict':params_dict,
'init_dict':init_dict,
'init_x_neg':x_neg,
'init_x_pos':x_pos,
'x_neg_final':x_neg_final,
'all_trajectories':all_trajectories,
'particle_counts_vec': particle_counts_vec,
'selected_indices':selected_indices,
'total_time':total_time,
'step_time_vec':step_time_vec,
'MMD2_vec':MMD2_vec,
'NLL_vec':NLL_vec}
# saving the dictionary
with open(wd+'plots/results_dict.pkl', 'wb') as file:
pickle.dump(results_dict, file)
"""# Moon-shaped."""
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def formula(x1, x2):
term1 = -x1**2 / 2
term2 = -(1/2) * (10 * x2 + 3 * x1**2 - 3)**2
result = np.exp(term1 + term2)
return result
# Create a grid of values
x1_values = np.linspace(-5, 5, 400)
x2_values = np.linspace(-5, 5, 400)
X1, X2 = np.meshgrid(x1_values, x2_values)
Z = formula(X1, X2)
# Plot the function
plt.figure(figsize=(10, 8))
plt.contourf(X1, X2, Z, levels=50, cmap='viridis')
plt.colorbar(label='Function value')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.title('Plot of the function')
plt.show()
np.random.seed(111)
def target_p(x):
x1, x2 = np.atleast_2d(x).T
term1 = -x1**2 / 2
term2 = -(1/2) * (10 * x2 + 3 * x1**2 - 3)**2
return np.exp(term1 + term2)
update_rule = 'Euler'
params_dict = set_params(update_rule,{'q_pos': 1.0,
'q_pos_auto_annealing': False,
'normalize_overall_forces': True,
'normalise_attr_forces': False,
'particle_filtering': False,
'noise_std':0})
init_dict = {'init_type':'gaussian', 'initial_gaussian_center':np.array([0, 0]), 'initial_gaussian_std':1, 'low_xy': -3, 'high_xy': 3, 'margin':0}
start_time = time.time()
# Initialize positions with a seed for reproducibility
x_neg, x_pos = initialize_positions(target_p=target_p,
M_neg=params_dict['M_neg'],
M_pos=params_dict['M_pos'],
d=params_dict['d'],
init_dict=init_dict,
SEED=params_dict['SEED'])
# Egenerate 5000 ground truth samples
samples = metropolis_hastings(target_p, 5000)
# Evolve the system and plot intermediate steps
x_neg_final, all_trajectories, particle_counts_vec, remained_neg_indices_all_iterations, removed_neg_indices_all_iterations, step_time_vec, MMD2_vec, NLL_vec = evolve_system(
init_dict=init_dict,
update_rule=update_rule,
x_neg=x_neg,
x_pos=x_pos,
params_dict=params_dict,
target_p=target_p,
ground_truth_samples=samples)
end_time = time.time(); total_time = end_time - start_time; print(f'total run time: {total_time} seconds')
# plot trajectories for selected particles
selected_indices = [0,100,200,299]
trajectory_plot(all_trajectories=all_trajectories,
selected_indices=selected_indices,
target_p=target_p,
x_pos=x_pos,
low_xy=init_dict['low_xy'],
high_xy=init_dict['high_xy'],
margin=init_dict['margin'],
params_dict=params_dict,
init_dict=init_dict,
total_time=total_time)
# save results
results_dict = {'update_rule':update_rule,
'params_dict':params_dict,
'init_dict':init_dict,
'init_x_neg':x_neg,
'init_x_pos':x_pos,
'x_neg_final':x_neg_final,
'all_trajectories':all_trajectories,
'particle_counts_vec': particle_counts_vec,
'selected_indices':selected_indices,
'total_time':total_time,
'step_time_vec':step_time_vec,
'MMD2_vec':MMD2_vec,
'NLL_vec':NLL_vec}
# saving the dictionary
with open(wd+'plots/results_dict.pkl', 'wb') as file:
pickle.dump(results_dict, file)
"""# Double banana."""
import numpy as np
import matplotlib.pyplot as plt
def formula(x1, x2):
return np.exp(-2 * ((x1 ** 2 + x2 ** 2) - 3) ** 2 + np.log(np.exp(-2 * (x1 - 2) ** 2) + np.exp(-2 * (x1 + 2) ** 2)))
# Create a grid of values
x1_values = np.linspace(-5, 5, 400)
x2_values = np.linspace(-5, 5, 400)
X1, X2 = np.meshgrid(x1_values, x2_values)
Z = formula(X1, X2)
# Plot the function
plt.figure(figsize=(10, 8))
plt.contourf(X1, X2, Z, levels=50, cmap='viridis')
plt.colorbar(label='Function value')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.title('Double banana')
plt.show()
# draw 5000 samples using MH
np.random.seed(111)
def target_p(x):
x1, x2 = np.atleast_2d(x).T
return np.exp(-2 * ((x1 ** 2 + x2 ** 2) - 3) ** 2 + np.log(np.exp(-2 * (x1 - 2) ** 2) + np.exp(-2 * (x1 + 2) ** 2)))
samples = metropolis_hastings(target_p, 5000)
plt.scatter(samples[:, 0], samples[:, 1], alpha=0.5, s=1)
plt.title('Samples from target distribution')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.show()
np.random.seed(111)
def target_p(x):
x1, x2 = np.atleast_2d(x).T
return np.exp(-2 * ((x1 ** 2 + x2 ** 2) - 3) ** 2 + np.log(np.exp(-2 * (x1 - 2) ** 2) + np.exp(-2 * (x1 + 2) ** 2)))
update_rule = 'Euler'
params_dict = set_params(update_rule,{'q_pos': 1.0,
'q_pos_auto_annealing': False,
'normalize_overall_forces': True,
'normalise_attr_forces': False,
'particle_filtering': False,
'noise_std':0})
init_dict = {'init_type':'uniform', 'low_uniform':-3, 'high_uniform':3, 'low_xy': -3, 'high_xy': 3, 'margin':0}
start_time = time.time()
# Initialize positions with a seed for reproducibility
x_neg, x_pos = initialize_positions(target_p=target_p,
M_neg=params_dict['M_neg'],
M_pos=params_dict['M_pos'],
d=params_dict['d'],
init_dict=init_dict,
SEED=params_dict['SEED'])
# Egenerate 5000 ground truth samples
samples = metropolis_hastings(target_p, 5000)
# Evolve the system and plot intermediate steps
x_neg_final, all_trajectories, particle_counts_vec, remained_neg_indices_all_iterations, removed_neg_indices_all_iterations, step_time_vec, MMD2_vec, NLL_vec = evolve_system(
init_dict=init_dict,
update_rule=update_rule,
x_neg=x_neg,
x_pos=x_pos,
params_dict=params_dict,
target_p=target_p,
ground_truth_samples=samples)
end_time = time.time(); total_time = end_time - start_time; print(f'total run time: {total_time} seconds')
# plot trajectories for selected particles
selected_indices = [18, 16,20,80]
trajectory_plot(all_trajectories=all_trajectories,
selected_indices=selected_indices,
target_p=target_p,
x_pos=x_pos,
low_xy=init_dict['low_xy'],
high_xy=init_dict['high_xy'],
margin=init_dict['margin'],
params_dict=params_dict,
init_dict=init_dict,
total_time=total_time)
# save results
results_dict = {'update_rule':update_rule,
'params_dict':params_dict,
'init_dict':init_dict,
'init_x_neg':x_neg,
'init_x_pos':x_pos,
'x_neg_final':x_neg_final,
'all_trajectories':all_trajectories,
'particle_counts_vec': particle_counts_vec,
'selected_indices':selected_indices,
'total_time':total_time,
'step_time_vec':step_time_vec,
'MMD2_vec':MMD2_vec,
'NLL_vec':NLL_vec}
# saving the dictionary
with open(wd+'plots/results_dict.pkl', 'wb') as file:
pickle.dump(results_dict, file)
"""# Wave."""
import numpy as np
import matplotlib.pyplot as plt
def target_p(x):
x1 = x[:, 0]
x2 = x[:, 1]
target_p = -0.5 * (x2 - np.sin(np.pi * x1 / 2)) ** 2 / 0.16
return np.exp(target_p)
# Create a grid of values
x1_values = np.linspace(-5, 5, 400)
x2_values = np.linspace(-5, 5, 400)
X1, X2 = np.meshgrid(x1_values, x2_values)
X = np.column_stack([X1.ravel(), X2.ravel()])
# Compute target_p
target_p_values = target_p(X)
# Reshape target_p for contour plot
target_p_values = target_p_values.reshape(X1.shape)
# Plot the function target_p
plt.figure(figsize=(10, 6))
plt.contourf(X1, X2, target_p_values, levels=50, cmap='viridis')
plt.colorbar(label='Log Probability Density')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.title('Contour Plot of $\log p(x)$')
plt.show()
np.random.seed(111)
def target_p(x):
x1, x2 = np.atleast_2d(x).T
return np.exp(-0.5 * (x2 - np.sin(np.pi * x1 / 2)) ** 2 / 0.16)
update_rule = 'Euler'
params_dict = set_params(update_rule,{'q_pos': 1.0,
'q_pos_auto_annealing': False,
'normalize_overall_forces': True,
'normalise_attr_forces': False,
'particle_filtering': False,
'noise_std':0})
init_dict = {'init_type':'uniform', 'low_uniform':-3, 'high_uniform':3, 'low_xy': -3, 'high_xy': 3, 'margin':0}
start_time = time.time()
# Initialize positions with a seed for reproducibility
x_neg, x_pos = initialize_positions(target_p=target_p,
M_neg=params_dict['M_neg'],
M_pos=params_dict['M_pos'],
d=params_dict['d'],
init_dict=init_dict,
SEED=params_dict['SEED'])
# Egenerate 5000 ground truth samples
samples = metropolis_hastings(target_p, 5000)
# Evolve the system and plot intermediate steps
x_neg_final, all_trajectories, particle_counts_vec, remained_neg_indices_all_iterations, removed_neg_indices_all_iterations, step_time_vec, MMD2_vec, NLL_vec = evolve_system(
init_dict=init_dict,
update_rule=update_rule,
x_neg=x_neg,
x_pos=x_pos,
params_dict=params_dict,
target_p=target_p,
ground_truth_samples=samples)
end_time = time.time(); total_time = end_time - start_time; print(f'total run time: {total_time} seconds')
# plot trajectories for selected particles
selected_indices = [0,100,200,299]
trajectory_plot(all_trajectories=all_trajectories,
selected_indices=selected_indices,
target_p=target_p,
x_pos=x_pos,
low_xy=init_dict['low_xy'],
high_xy=init_dict['high_xy'],
margin=init_dict['margin'],
params_dict=params_dict,
init_dict=init_dict,
total_time=total_time)
# save results
results_dict = {'update_rule':update_rule,
'params_dict':params_dict,
'init_dict':init_dict,
'init_x_neg':x_neg,
'init_x_pos':x_pos,
'x_neg_final':x_neg_final,
'all_trajectories':all_trajectories,
'particle_counts_vec': particle_counts_vec,
'selected_indices':selected_indices,
'total_time':total_time,
'step_time_vec':step_time_vec,
'MMD2_vec':MMD2_vec,
'NLL_vec':NLL_vec}
# saving the dictionary
with open(wd+'plots/results_dict.pkl', 'wb') as file:
pickle.dump(results_dict, file)
"""# Neal's funnel."""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# Parameters
sigma = 3.0 # Standard deviation for v
n_samples = 10000 # Number of samples
# Define the density function
def density(x, y, sigma):
# p(y | sigma) = N(y | 0, sigma^2)
p_y = norm.pdf(y, 0, sigma)
# p(x | y) = N(x | 0, exp(y))
p_x_given_y = norm.pdf(x, 0, np.exp(y / 2))
return p_x_given_y * p_y
# Create a grid over [-5, 5] x [-5, 5]
x = np.linspace(-5, 5, 100)
y = np.linspace(-8, 6, 100)
X, Y = np.meshgrid(x, y)
# Evaluate the density over the grid
Z = density(X, Y, sigma)
# Plotting the density
plt.figure(figsize=(10, 8))
contour = plt.contourf(X, Y, Z, levels=50, cmap='viridis')
plt.colorbar(contour, label='Density')
plt.title("Density Contour Plot")
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.grid(True)
plt.show()
"""## HMC."""
# !pip install pymc arviz
!pip install --upgrade numpy scipy theano pymc arviz
import pymc as pm
import arviz as az
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from matplotlib.colors import LinearSegmentedColormap
import pymc as pm
import arviz as az
np.random.seed(111)
# Define the target density function
def target_p(x):
x1, x2 = np.atleast_2d(x).T
p_x2 = norm.pdf(x2, 0, 3.0) # Standard deviation for v
p_x1_given_x2 = norm.pdf(x1, 0, np.exp(x2 / 2))
return p_x1_given_x2 * p_x2
# Parameters for sampling and plotting
low_xy, high_xy = -7, 3
margin = 0
# Define the PyMC3 model for HMC
with pm.Model() as model:
x2 = pm.Normal('x2', mu=0, sigma=3.0)
x1 = pm.Normal('x1', mu=0, sigma=pm.math.exp(x2 / 2))
# Sample using HMC
trace = pm.sample(4000, tune=1000, chains=1, cores=1, return_inferencedata=True, discard_tuned_samples=True, random_seed=111)
# Extract samples
HMC_samples = trace.posterior.stack(draws=("chain", "draw")).to_dataframe()
HMC_samples = HMC_samples.iloc[::10,:]
# Plotting the samples and the density contours with marginal distributions
fig, ax_main = plt.subplots(figsize=(8, 6))
X, Y, Z, cm = plot_density(target_p, low_xy - margin, high_xy + margin, low_xy - margin, high_xy + margin)
img = ax_main.imshow(Z, extent=(low_xy - margin, high_xy + margin, low_xy - margin, high_xy + margin), origin='lower', cmap=cm, alpha=0.5)
# Plot the samples
scatter_samples = ax_main.scatter(HMC_samples['x1'], HMC_samples['x2'], c='blue', s=3, label='HMC samples')
# Overlay contour lines
contour = ax_main.contour(X, Y, Z, levels=10, colors='white', linewidths=0.5)
# Set plot limits and labels
ax_main.set_xlim(low_xy - margin, high_xy + margin)
ax_main.set_ylim(low_xy - margin, high_xy + margin)
ax_main.set_xlabel(r'$x_1$')
ax_main.set_ylabel(r'$x_2$')
ax_main.legend(loc='lower left')
# Create inset axes for the histograms
ax_histx = inset_axes(ax_main, width="100%", height="60%", loc='upper center',
bbox_to_anchor=(0, 0.92, 1, 0.2), bbox_transform=ax_main.transAxes, borderpad=0)
ax_histy = inset_axes(ax_main, width="60%", height="100%", loc='center right',
bbox_to_anchor=(0.92, 0, 0.2, 1), bbox_transform=ax_main.transAxes, borderpad=0)
# Marginal histograms
ax_histx.hist(HMC_samples['x1'], bins=180, density=True, color='blue', alpha=0.6)
ax_histy.hist(HMC_samples['x2'], bins=60, density=True, color='blue', alpha=0.6, orientation='horizontal')
# Hide x labels and tick labels for the hist plots
plt.setp(ax_histx.get_xticklabels(), visible=True)
plt.setp(ax_histy.get_yticklabels(), visible=True)
# Disable y-ticks for the histograms
ax_histx.yaxis.set_ticks([])
ax_histy.xaxis.set_ticks([])
# Set the same x-ticks for the upper histogram
ax_histx.set_xlim(ax_main.get_xlim())
# Set the same y-ticks for the right histogram
ax_histy.set_ylim(ax_main.get_ylim())
plt.savefig(wd+f'final results/Neal funnel/HMC.png')
plt.show()
HMC_samples_pairs = HMC_samples[['x1', 'x2']].to_numpy()
np.save(wd+'final results/Neal funnel/HMC_samples.npy', HMC_samples_pairs)
"""## MH."""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from matplotlib.colors import LinearSegmentedColormap
import time
np.random.seed(111)
# Define the target density function
def target_p(x):
x1, x2 = np.atleast_2d(x).T
p_x2 = norm.pdf(x2, 0, 3.0) # Standard deviation for v
p_x1_given_x2 = norm.pdf(x1, 0, np.exp(x2 / 2))
return p_x1_given_x2 * p_x2