Repository navigation
Expand file tree
/
Copy pathgeom.py
More file actions
1163 lines (1002 loc) · 38.1 KB
/
Copy pathgeom.py
File metadata and controls
1163 lines (1002 loc) · 38.1 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module for Geometry and Metric objects
"""
from xml.etree.ElementTree import SubElement
import numpy as np
class Metric:
def __init__(self, partvars, varnames, units, volunits):
"""
Abstract object defining metrics for a subset of variables.
The main function of a Metric is definig a transformation from a
subset of particle variables to certain parametrized variables,
which can be more suitable for applying KDE.
See geom._metrics for available metrics.
Parameters
----------
partvars: list of int
Indices of the particle variables to parametrize (see
varnames global list).
varnames: list of str
Names of parametrized variables.
units: list of str
Units of each parametrized variable.
volunits: str
Units of the product of variables to parametrize.
"""
self.partvars = partvars
if len(varnames) != len(units):
raise ValueError("varnames and units must have same len.")
self.dim = len(varnames)
self.varnames = varnames
self.varmap = {name: idx for idx, name in enumerate(varnames)}
self.units = units
self.volunits = volunits
def transform(self, parts):
"""Transform particle variables to parametrized variables."""
return parts
def inverse_transform(self, vecs):
"""Transform parametrized variables to particle variables."""
return vecs
def jac(self, parts):
"""Jacobian of transformation."""
return np.ones(len(parts))
def mean(self, parts=None, vecs=None, weights=None):
"""
Mean of particle variables.
Mean is computed in parametrized space, and transformed back to
particle variables.
Parameters
----------
parts: array-like, optional
Array of particle variables.
vecs: array-like, optional
Array of parametrized variables. If set, overrides parts.
weights: array-like, optional
Array of particle statistic weights.
"""
if vecs is None:
vecs = self.transform(parts)
return self.inverse_transform(
np.average(vecs, axis=0, weights=weights)
)
def std(self, parts=None, vecs=None, weights=None):
"""
Standard deviation of particle variables.
Standard deviation is computed in parametrized space, and
transformed back to particle variables.
Parameters
----------
parts: array-like, optional
Array of particle variables.
vecs: array-like, optional
Array of parametrized variables. If set, overrides parts.
weights: array-like, optional
Array of particle statistic weights.
"""
if vecs is None:
vecs = self.transform(parts)
mn = np.average(vecs, axis=0, weights=weights)
return np.sqrt(np.average((vecs - mn) ** 2, axis=0, weights=weights))
def save(self, mtree):
"""Save Metric parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
SubElement(mtree, "params").set("nps", "0")
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build Metric."""
raise Exception("Load method not implemented.")
class Geometry(Metric):
def __init__(self, metrics, trasl=None, rot=None):
"""
Object defining particle variables treatment (metrics).
The main function of a Geometry is definig a transformation from
particle variables to certain parametrized variables, which can
be more suitable for applying KDE.
Parameters
----------
metrics: list
List of metrics for each subset of variables. They must
cover all particle variables (energy, position,
direction and time).
trasl: array-like, optional
Spatial traslation for source. Default is no traslation.
rot: numpy.ndarray or scipy.spatial.transform.Rotation, optional
Spatial rotation for source. Can be a scipy Rotation object,
or any array-like which can be used to generate a scipy
Rotation object (rotation vector, quaternion or rotation
matrix). Rotation is applied after traslation in transform,
and before traslation in inverse_transform. Default is no
rotation.
"""
partvars = range(8)
varnames = sum([metric.varnames for metric in metrics], [])
units = sum([metric.units for metric in metrics], [])
volunits = "".join([metric.volunits + " " for metric in metrics])[:-1]
super().__init__(partvars, varnames, units, volunits)
self.ms = metrics
if trasl is not None:
trasl = np.array(trasl).reshape(-1)
if trasl.shape != (3,):
raise ValueError("Invalid trasl.")
if rot is not None:
import scipy.spatial.transform as st
if not isinstance(rot, st.Rotation):
rot = np.array(rot)
if rot.shape == (4,):
rot = st.Rotation.from_quat(rot)
elif rot.shape == (3, 3):
rot = st.Rotation.from_matrix(rot)
elif rot.shape == (3,):
rot = st.Rotation.from_rotvec(rot)
else:
raise ValueError("Invalid rot.")
self.trasl = trasl
self.rot = rot
def transform(self, parts):
"""Transform particle variables to parametrized variables."""
if self.trasl is not None:
parts[:, 1:4] -= self.trasl # Position
if self.rot is not None:
parts[:, 1:4] = self.rot.apply(
parts[:, 1:4], inverse=True
) # Position
parts[:, 4:7] = self.rot.apply(
parts[:, 4:7], inverse=True
) # Direction
vecss = []
for metric in self.ms:
vecss.append(metric.transform(parts[:, metric.partvars]))
return np.concatenate(vecss, axis=1)
def inverse_transform(self, vecs):
"""Transform parametrized variables to particle variables."""
parts = np.zeros((len(vecs), 8))
end = 0
for metric in self.ms:
start = end
end = start + metric.dim
parts[:, metric.partvars] = metric.inverse_transform(
vecs[:, start:end]
)
if self.trasl is not None:
parts[:, 1:4] += self.trasl # Position
if self.rot is not None:
parts[:, 1:4] = self.rot.apply(parts[:, 1:4]) # Position
parts[:, 4:7] = self.rot.apply(parts[:, 4:7]) # Direction
return parts
def jac(self, parts):
"""Jacobian of transformation."""
if self.trasl is not None:
parts[:, 1:4] -= self.trasl # Position
if self.rot is not None:
parts[:, 1:4] = self.rot.apply(
parts[:, 1:4], inverse=True
) # Position
parts[:, 4:7] = self.rot.apply(
parts[:, 4:7], inverse=True
) # Direction
jacs = []
for metric in self.ms:
jacs.append(metric.jac(parts[:, metric.partvars]))
return np.prod(jacs, axis=1)
def mean(self, parts=None, vecs=None, weights=None):
"""
Mean of particle variables.
Mean is computed in parametrized space, and transformed back to
particle variables.
Parameters
----------
parts: array-like, optional
Array of particle variables.
vecs: array-like, optional
Array of parametrized variables. If set, overrides parts.
weights: array-like, optional
Array of particle statistic weights.
"""
if vecs is None:
vecs = self.transform(parts)
means = []
end = 0
for metric in self.ms:
start = end
end = start + metric.dim
means.append(metric.mean(vecs=vecs[:, start:end], weights=weights))
return np.concatenate(means)
def std(self, parts=None, vecs=None, weights=None):
"""
Standard deviation of particle variables.
Standard deviation is computed in parametrized space, and
transformed back to particle variables.
Parameters
----------
parts: array-like, optional
Array of particle variables.
vecs: array-like, optional
Array of parametrized variables. If set, overrides parts.
weights: array-like, optional
Array of particle statistic weights.
"""
if vecs is None:
vecs = self.transform(parts)
stds = []
end = 0
for metric in self.ms:
start = end
end = start + metric.dim
stds.append(metric.std(vecs=vecs[:, start:end], weights=weights))
return np.concatenate(stds)
def save(self, gtree):
"""Save Geometry parameters into XML tree."""
gtree.set("order", str(len(self.ms)))
for metric in self.ms:
mtree = SubElement(gtree, metric.__class__.__name__)
metric.save(mtree)
trasl = (
np.array_str(self.trasl)[1:-1] if self.trasl is not None else ""
)
SubElement(gtree, "trasl").text = trasl
rot = (
np.array_str(self.rot.as_rotvec())[1:-1]
if self.rot is not None
else ""
)
SubElement(gtree, "rot").text = rot
@staticmethod
def load(gtree):
"""Load parameters from XML tree and build Geometry."""
order = int(gtree.attrib["order"])
metrics = []
for i in range(order):
metricname = gtree[i].tag
if metricname not in _metrics:
raise Exception("Invalid metricname {}".format(metricname))
metrics.append(_metrics[metricname].load(gtree[i]))
if gtree[-2].text:
trasl = np.array(gtree[-2].text.split(), dtype="float64")
else:
trasl = None
if gtree[-1].text:
rot = np.array(gtree[-1].text.split(), dtype="float64")
else:
rot = None
return Geometry(metrics, trasl=trasl, rot=rot)
# Inherited Metrics
class Energy(Metric):
def __init__(self):
"""Simple metric for energy, with no transformation."""
super().__init__([0], ["ekin"], ["MeV"], "MeV")
def load(mtree):
"""Build Energy."""
return Energy()
class Lethargy(Metric):
def __init__(self, E0=10):
"""
Lethargy metric for energy.
Lethargy is defined as:
u = log(E0 / ekin)
Parameters
----------
E0: float
Reference energy. Typically, it is the highest energy in the
system.
"""
super().__init__([0], ["u"], ["[let]"], "MeV")
self.E0 = E0
def transform(self, ekins):
"""Transform energy to lethargy."""
return np.log(self.E0 / ekins)
def inverse_transform(self, us):
"""Transform lethargy to energy."""
return self.E0 * np.exp(-us)
def jac(self, ekins):
"""Jacobian of lethargy transformation."""
return 1 / ekins.reshape(-1)
def save(self, mtree):
"""Save Lethargy parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "1")
paramsel.text = "{}".format(self.E0)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build Lethargy."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 1 or len(params) != 1 or int(mtree[1].attrib["nps"]) != 1:
raise Exception("Invalid metric tree.")
return Lethargy(*params)
class Wavelength(Metric):
def __init__(self):
"""
Wavelength metric for energy.
Wavelength is defined as:
lambda [AA] = 9.045 / sqrt(E [meV])
"""
super().__init__([0], ["l"], ["[AA]"], "AA")
def transform(self, ekins):
"""Transform energy to wavelenght."""
return 9.045 / np.sqrt(ekins * 1e9)
def inverse_transform(self, ls):
"""Transform wavelength to energy."""
return 81.82e-9 / ls ** 2
def jac(self, ekins):
"""Jacobian of wavelength transformation."""
return 9.045 / (2 * np.sqrt(ekins ** 3))
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build Wavelength."""
return Wavelength()
class Time(Metric):
def __init__(self):
"""Simple metric for time, with no transformation."""
super().__init__([7], ["t"], ["ms"], "ms")
def load(mtree):
"""Build Time."""
return Time()
class Decade(Metric):
def __init__(self):
"""
Decade metric for time.
Decade is defined as:
d = log(t)
"""
super().__init__([7], ["d"], ["[dec]"], "ms")
def transform(self, ts):
"""Transform time to decade."""
return np.log10(ts)
def inverse_transform(self, ds):
"""Transform deacde to time."""
return 10 ** ds
def jac(self, ts):
"""Jacobian of lethargy transformation."""
return np.log10(np.e) / ts.reshape(-1)
@staticmethod
def load(mtree):
"""Build Decade."""
return Decade()
class Vol(Metric):
def __init__(
self,
xmin=-np.inf,
xmax=np.inf,
ymin=-np.inf,
ymax=np.inf,
zmin=-np.inf,
zmax=np.inf,
):
"""
Simple metric for 3D position, with no transformation.
Each spatial variable (x, y, z) is delimited between a min and
max value. By default these are -infinity and infinity,
respectively. All positions in the particle list should be
inside these limits.
Axis system of reference can be changed by means of the 'trasl'
and 'rot' arguments of the Geometry object.
"""
super().__init__(
[1, 2, 3], ["x", "y", "z"], ["cm", "cm", "cm"], "cm^3"
)
self.xmin = xmin
self.xmax = xmax
self.ymin = ymin
self.ymax = ymax
self.zmin = zmin
self.zmax = zmax
def save(self, mtree):
"""Save Vol parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "6")
paramsel.text = "{} {} {} {} {} {}".format(
self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax
)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build Vol."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 3 or len(params) != 6 or int(mtree[1].attrib["nps"]) != 6:
raise Exception("Invalid metric tree.")
return Vol(*params)
class SurfXY(Metric):
def __init__(
self, xmin=-np.inf, xmax=np.inf, ymin=-np.inf, ymax=np.inf, z=0
):
"""
Simple metric for 2D position, with no transformation.
Spatial variables x and y are delimited between a min and max
value. By default these are -infinity and infinity,
respectively. All positions in the particle list should be
inside these limits.
z has the fixed value given as argument.
Axis system of reference can be changed by means of the 'trasl'
and 'rot' arguments of the Geometry object.
"""
super().__init__([1, 2, 3], ["x", "y"], ["cm", "cm"], "cm^2")
self.z = z
self.xmin = xmin
self.xmax = xmax
self.ymin = ymin
self.ymax = ymax
def transform(self, poss):
"""Transform volume position (x,y,z) to flat position (x,y)."""
return poss[:, :2]
def inverse_transform(self, poss):
"""Transform flat position (x,y) to volume position (x,y,z)."""
z_col = np.broadcast_to(self.z, (*poss.shape[:-1], 1))
return np.concatenate((poss, z_col), axis=1)
def save(self, mtree):
"""Save SurfXY parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "5")
paramsel.text = "{} {} {} {} {}".format(
self.xmin, self.xmax, self.ymin, self.ymax, self.z
)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build SurfXY."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 2 or len(params) != 5 or int(mtree[1].attrib["nps"]) != 5:
raise Exception("Invalid metric tree.")
return SurfXY(*params)
class SurfR(Metric):
def __init__(
self, rho_min=0, rho_max=np.inf, psi_min=-np.pi, psi_max=np.pi, z=0
):
"""
Polar parametrization for position.
Polar variables are defined as follows:
rho: radius, in [cm]
psi: azimuthal angle, starting from x direction, in [deg].
Spatial variable rho is delimited between a min and max
value. By default these are zero and infinity,
respectively. All positions in the particle list should be
inside these limits.
z has the fixed value given as argument.
"""
super().__init__([1, 2, 3], ["rho", "psi"], ["cm", "deg"], "cm")
self.z = z
self.rho_min = rho_min
self.rho_max = rho_max
self.psi_min = psi_min
self.psi_max = psi_max
def transform(self, poss):
"""
Transform volume position (x,y,z)
to circular flat position (rho,psi).
"""
rhos = np.sqrt(poss[:, 0] ** 2 + poss[:, 1] ** 2)
psis = np.arctan2(poss[:, 1], poss[:, 0]) * 180 / np.pi
return np.stack((rhos, psis), axis=1)
def inverse_transform(self, poss):
"""
Transform polar flat position (rho,psi)
to volume position (x,y,z).
"""
z_col = np.broadcast_to(self.z, (*poss.shape[:-1], 1))
x_col = poss[:, 0] * np.cos(poss[:, 1] * np.pi / 180)
y_col = poss[:, 0] * np.sin(poss[:, 1] * np.pi / 180)
return np.stack((x_col, y_col, z_col), axis=1)
def save(self, mtree):
"""Save SurfCirc parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "5")
paramsel.text = "{} {} {} {} {}".format(
self.rho_min, self.rho_max, self.psi_min, self.psi_max, self.z
)
def jac(self, poss):
"""Jacobian of polar transformation."""
rhos = np.sqrt(poss[:, 0] ** 2 + poss[:, 1] ** 2)
return 1 / rhos.reshape(-1)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build SurfCirc."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 2 or len(params) != 5 or int(mtree[1].attrib["nps"]) != 5:
raise Exception("Invalid metric tree.")
return SurfR(*params)
class SurfR2(Metric):
def __init__(
self, rho_min=0, rho_max=np.inf, psi_min=-np.pi, psi_max=np.pi, z=0
):
"""
Pseudo-polar parametrization for position.
Polar variables are defined as follows:
rho2: radius squared, in [cm²]
psi: azimuthal angle, starting from x direction, in [deg].
Spatial variable rho2 is delimited between a min and max
value. By default these are zero and infinity,
respectively. All positions in the particle list should be
inside these limits.
z has the fixed value given as argument.
"""
super().__init__([1, 2, 3], ["rho^2", "psi"], ["cm^2", "deg"], "cm^2")
self.z = z
self.rho_min = rho_min
self.rho_max = rho_max
self.psi_min = psi_min
self.psi_max = psi_max
def transform(self, poss):
"""
Transform volume position (x,y,z)
to circular flat position (rho2,psi).
"""
rhos = poss[:, 0] ** 2 + poss[:, 1] ** 2
psis = np.arctan2(poss[:, 1], poss[:, 0]) * 180 / np.pi
return np.stack((rhos, psis), axis=1)
def inverse_transform(self, poss):
"""
Transform polar flat position (rho2,psi)
to volume position (x,y,z).
"""
z_col = np.broadcast_to(self.z, (*poss.shape[:-1], 1))
x_col = poss[:, 0] ** 0.5 * np.cos(poss[:, 1] * np.pi / 180)
y_col = poss[:, 0] ** 0.5 * np.sin(poss[:, 1] * np.pi / 180)
return np.stack((x_col, y_col, z_col), axis=1)
def save(self, mtree):
"""Save SurfCirc parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "5")
paramsel.text = "{} {} {} {} {}".format(
self.rho_min, self.rho_max, self.psi_min, self.psi_max, self.z
)
def jac(self, poss):
"""Jacobian of polar transformation."""
return np.full(len(poss[:, 0]), 2)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build SurfCirc."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 2 or len(params) != 5 or int(mtree[1].attrib["nps"]) != 5:
raise Exception("Invalid metric tree.")
return SurfR2(*params)
class SurfCircle(Metric):
def __init__(
self, rho_min=0, rho_max=np.inf, psi_min=-np.pi, psi_max=np.pi, z=0
):
"""
Simple metric for 2D position, with no transformation.
Spatial variables x and y are delimited between a min and max
value for the radius (rho) and the angle (psi), in polar
coordinates. By default these are 0 and infinity for rho, and
-pi and pi for psi, respectively. All positions in the
particle list should be inside these limits.
z has the fixed value given as argument.
Axis system of reference can be changed by means of the 'trasl'
and 'rot' arguments of the Geometry object.
"""
super().__init__([1, 2, 3], ["x", "y"], ["cm", "cm"], "cm^2")
self.z = z
self.rho_min = rho_min
self.rho_max = rho_max
self.psi_min = psi_min
self.psi_max = psi_max
def transform(self, poss):
"""Transform volume position (x,y,z) to flat position (x,y)."""
return poss[:, :2]
def inverse_transform(self, poss):
"""Transform flat position (x,y) to volume position (x,y,z)."""
z_col = np.broadcast_to(self.z, (*poss.shape[:-1], 1))
return np.concatenate((poss, z_col), axis=1)
def save(self, mtree):
"""Save SurfXY parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "5")
paramsel.text = "{} {} {} {} {}".format(
self.rho_min, self.rho_max, self.psi_min, self.psi_max, self.z
)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build SurfXY."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 2 or len(params) != 5 or int(mtree[1].attrib["nps"]) != 5:
raise Exception("Invalid metric tree.")
return SurfCircle(*params)
class Guide(Metric):
def __init__(self, xwidth, yheight, zmax=np.inf, rcurv=None):
"""
Guide metric for position and direction.
Position is parametrized with following variables:
- z: distance along guide, following curvature (if any).
- t: transversal direction along mirrors, starting at\
(x+,y-) corner, towards (x+,y+) corner.
Direction is parametrized with following variables:
- mu: cosine of angle between particle direction and mirror\
normal.
- phi: azimuthal angle, starting from z direction, in [deg].
Axis system of reference can be changed by means of the 'trasl'
and 'rot' arguments of the Geometry object.
Parameters
----------
xwidth: float
Guide width.
yheight: float
Guide height.
zmax: float
Guide length.
rcurv: float
Curvature radius, defined as follows. Default is no\
curvature.
- rcurv > 0 for curvature towards negative x
- rcurv < 0 for curvature towards negative x
- rcurv = 0 or rcurv = infinity for no curvature
"""
super().__init__(
[1, 2, 3, 4, 5, 6],
["z", "t", "theta", "phi"],
["cm", "cm", "deg", "deg"],
"cm^2 sr",
)
self.xwidth = xwidth
self.yheight = yheight
self.zmax = zmax
self.rcurv = rcurv
def transform(self, posdirs):
"""Transform position and direction to guide variables."""
xs, ys, zs, dxs, dys, dzs = posdirs.T
if self.rcurv is not None:
rs = np.sqrt((self.rcurv + xs) ** 2 + zs ** 2)
xs = np.sign(self.rcurv) * rs - self.rcurv
zs = np.abs(self.rcurv) * np.arcsin(zs / rs)
dxs2 = dxs
dzs2 = dzs
angs = zs / self.rcurv
dxs = dxs2 * np.cos(angs) + dzs2 * np.sin(angs)
dzs = -dxs2 * np.sin(angs) + dzs2 * np.cos(angs)
mask0 = np.logical_and(
(ys / self.yheight > -xs / self.xwidth),
(ys / self.yheight < xs / self.xwidth),
) # mirror x pos
mask1 = np.logical_and(
(ys / self.yheight > xs / self.xwidth),
(ys / self.yheight > -xs / self.xwidth),
) # mirror y pos
mask2 = np.logical_and(
(ys / self.yheight < -xs / self.xwidth),
(ys / self.yheight > xs / self.xwidth),
) # mirror x neg
mask3 = np.logical_and(
(ys / self.yheight < xs / self.xwidth),
(ys / self.yheight < -xs / self.xwidth),
) # mirror y neg
ts = np.empty_like(xs)
ts[mask0] = 0.5 * self.yheight + ys[mask0]
ts[mask1] = 1.0 * self.yheight + 0.5 * self.xwidth - xs[mask1]
ts[mask2] = 1.5 * self.yheight + 1.0 * self.xwidth - ys[mask2]
ts[mask3] = 2.0 * self.yheight + 1.5 * self.xwidth + xs[mask3]
mus = np.empty_like(dxs)
phis = np.empty_like(dxs)
mus[mask0] = dxs[mask0]
phis[mask0] = np.arctan2(-dys[mask0], dzs[mask0])
mus[mask1] = dys[mask1]
phis[mask1] = np.arctan2(dxs[mask1], dzs[mask1])
mus[mask2] = -dxs[mask2]
phis[mask2] = np.arctan2(dys[mask2], dzs[mask2])
mus[mask3] = -dys[mask3]
phis[mask3] = np.arctan2(-dxs[mask3], dzs[mask3])
phis *= 180 / np.pi
return np.stack((zs, ts, mus, phis), axis=1)
def inverse_transform(self, posdirs):
"""Transform guide variables to position and direction."""
zs, ts, mus, phis = posdirs.T
phis *= np.pi / 180
mask0 = ts < self.yheight # mirror x pos
mask1 = np.logical_and(
(ts > self.yheight), (ts < self.yheight + self.xwidth)
) # mirror y pos
mask2 = np.logical_and(
(ts > self.yheight + self.xwidth),
(ts < 2 * self.yheight + self.xwidth),
) # mirror x neg
mask3 = ts > 2 * self.yheight + self.xwidth # mirror y neg
xs = np.empty_like(ts)
ys = np.empty_like(ts)
xs[mask0] = self.xwidth / 2
ys[mask0] = ts[mask0] - 0.5 * self.yheight
ys[mask1] = self.yheight / 2
xs[mask1] = -ts[mask1] + 1.0 * self.yheight + 0.5 * self.xwidth
xs[mask2] = -self.xwidth / 2
ys[mask2] = -ts[mask2] + 1.5 * self.yheight + 1.0 * self.xwidth
ys[mask3] = -self.yheight / 2
xs[mask3] = ts[mask3] - 2.0 * self.yheight - 1.5 * self.xwidth
dxs = np.empty_like(mus)
dys = np.empty_like(mus)
dzs = np.empty_like(mus)
dxs[mask0] = mus[mask0]
dzs[mask0] = np.sqrt(1 - mus[mask0] ** 2) * np.cos(phis[mask0])
dys[mask0] = -np.sqrt(1 - mus[mask0] ** 2) * np.sin(phis[mask0])
dys[mask1] = mus[mask1]
dzs[mask1] = np.sqrt(1 - mus[mask1] ** 2) * np.cos(phis[mask1])
dxs[mask1] = np.sqrt(1 - mus[mask1] ** 2) * np.sin(phis[mask1])
dxs[mask2] = -mus[mask2]
dzs[mask2] = np.sqrt(1 - mus[mask2] ** 2) * np.cos(phis[mask2])
dys[mask2] = np.sqrt(1 - mus[mask2] ** 2) * np.sin(phis[mask2])
dys[mask3] = -mus[mask3]
dzs[mask3] = np.sqrt(1 - mus[mask3] ** 2) * np.cos(phis[mask3])
dxs[mask3] = -np.sqrt(1 - mus[mask3] ** 2) * np.sin(phis[mask3])
if self.rcurv is not None:
rs = (self.rcurv + xs) * np.sign(self.rcurv)
angs = zs / self.rcurv
xs = (
np.sign(self.rcurv) * rs * np.cos(zs / self.rcurv) - self.rcurv
)
zs = rs * np.sin(np.abs(zs / self.rcurv))
dxs2 = dxs
dzs2 = dzs
dxs = dxs2 * np.cos(angs) - dzs2 * np.sin(angs)
dzs = dxs2 * np.sin(angs) + dzs2 * np.cos(angs)
return np.stack((xs, ys, zs, dxs, dys, dzs), axis=1)
def save(self, mtree):
"""Save Guide parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "4")
paramsel.text = "{} {} {} {}".format(
self.xwidth, self.yheight, self.zmax, self.rcurv
)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build Guide."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="float64")
if dim != 6 or len(params) != 4 or int(mtree[1].attrib["nps"]) != 4:
raise Exception("Invalid metric tree.")
return Guide(*params)
class Isotrop(Metric):
def __init__(self, keep_xdir=False, keep_ydir=False, keep_zdir=False):
"""
Simple metric for direction, with no transformation.
Distance is measured as the euclidean distance between 3D
unitary direction vectors.
Axis orientation can be changed by means of the rot' argument of
the Geometry object.
Parameters
----------
keep_xdir: bool
If True, when using the source for sampling new particles,
perturbation will not change dirx sign.
keep_ydir: bool
If True, when using the source for sampling new particles,
perturbation will not change diry sign.
keep_zdir: bool
If True, when using the source for sampling new particles,
perturbation will not change dirz sign.
"""
super().__init__(
[4, 5, 6],
["dx", "dy", "dz"],
["[dir]", "[dir]", "[dir]"],
"[dir]^3",
)
self.keep_xdir = keep_xdir
self.keep_ydir = keep_ydir
self.keep_zdir = keep_zdir
def mean(self, dirs=None, vecs=None, weights=None):
"""
Mean of directions.
Mean is computed as the euclidean mean of direction vectors,
normalized to 1.
Parameters
----------
dirs: array-like, optional
Array of directions.
vecs: array-like, optional
Array of parametrized directions. If set, overrides dirs.
weights: array-like, optional
Array of particle statistic weights.
"""
if vecs is None:
vecs = self.transform(dirs)
mn = np.average(vecs, axis=0, weights=weights)
mn_norm = np.linalg.norm(mn)
if mn_norm == 0:
mn_norm = 1
return mn / mn_norm
def std(self, dirs=None, vecs=None, weights=None):
"""
Standard deviation of directions.
Standard deviation is computed as the euclidean standard
deviation of direction vectors minus its mean (computed with
mean method).
Parameters
----------
dirs: array-like, optional
Array of directions.
vecs: array-like, optional
Array of parametrized directions. If set, overrides dirs.
weights: array-like, optional
Array of particle statistic weights.
"""
if vecs is None:
vecs = self.transform(dirs)
mn = self.mean(vecs=vecs, weights=weights)
std = np.sqrt(
np.mean(np.average((vecs - mn) ** 2, axis=0, weights=weights))
)
return np.array(3 * [std])
def save(self, mtree):
"""Save Guide parameters into XML tree."""
SubElement(mtree, "dim").text = str(self.dim)
paramsel = SubElement(mtree, "params")
paramsel.set("nps", "3")
paramsel.text = "{:d} {:d} {:d}".format(
self.keep_xdir, self.keep_ydir, self.keep_zdir
)
@staticmethod
def load(mtree):
"""Load parameters from XML tree and build Isotrop."""
dim = int(mtree[0].text)
params = np.array(mtree[1].text.split(), dtype="int")
if dim != 3 or len(params) != 3 or int(mtree[1].attrib["nps"]) != 3:
raise Exception("Invalid metric tree.")
return Isotrop(*params)
class Polar(Metric):
def __init__(self):
"""
Polar parametrization for direction.
Polar angles are defined as follows:
theta: angle between direction and z, in [deg].
phi: azimuthal angle, starting from x direction, in [deg].
Axis orientation can be changed by means of the rot' argument of
the Geometry object.
"""
super().__init__([4, 5, 6], ["theta", "phi"], ["deg", "deg"], "sr^2")
def transform(self, dirs):
"""Transform directions to polar angles."""
thetas = np.arccos(dirs[:, 2]) * 180 / np.pi
phis = np.arctan2(dirs[:, 1], dirs[:, 0]) * 180 / np.pi
return np.stack((thetas, phis), axis=1)
def inverse_transform(self, tps):
"""Transform polar angles to directions."""
thetas, phis = tps.T
dxs = np.sin(thetas * np.pi / 180) * np.cos(phis * np.pi / 180)
dys = np.sin(thetas * np.pi / 180) * np.sin(phis * np.pi / 180)
dzs = np.cos(thetas * np.pi / 180)
return np.stack((dxs, dys, dzs), axis=1)
def jac(self, dirs):
"""Jacobian of polar transformation."""
thetas = np.arccos(dirs[:, 2])
return (180 / np.pi) ** 2 / np.sin(thetas)