-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathmapgen.py
More file actions
3165 lines (2488 loc) · 116 KB
/
mapgen.py
File metadata and controls
3165 lines (2488 loc) · 116 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
import logging
import warnings
from math import ceil, floor
import matplotlib.pyplot as plt
import numpy as np
from beartype import beartype as typechecker
from beartype.typing import List, Literal, Optional, Tuple, Union, cast
from jaxtyping import Complex, Float, Int, Integer, Real
from scipy.optimize import fmin
from scipy.spatial.transform import Rotation
from scipy.special import jv
import kwave.utils.typing as kt
from kwave.data import Vector
from kwave.utils.conversion import db2neper, neper2db
from kwave.utils.data import scale_SI
from kwave.utils.math import compute_linear_transform, cosd, sind
from kwave.utils.matlab import ind2sub, matlab_assign, matlab_find, sub2ind
from kwave.utils.matrix import max_nd
from kwave.utils.tictoc import TicToc
# GLOBALS
# define literals (ref: http://www.wolframalpha.com/input/?i=golden+angle)
GOLDEN_ANGLE = 2.39996322972865332223155550663361385312499901105811504
PACKING_NUMBER = 7 # 2*pi
@typechecker
def make_cart_disc(
disc_pos: np.ndarray, radius: float, focus_pos: np.ndarray, num_points: int,
plot_disc: Optional[Union[bool, Literal[0, 1]]] = False, use_spiral: Optional[Union[bool, Literal[0, 1]]] = False
) -> np.ndarray:
"""
Create evenly distributed Cartesian points covering a disc.
Args:
disc_pos: Cartesian position of the center of the disc given as a
two (2D) or three (3D) element tuple [m].
radius: Radius of the disc [m].
focus_pos: Any point on the beam axis of the disc given as a three
element tuple [fx, fy, fz] [m]. Can be set to None to define a disc in the x-y plane.
num_points: Number of points on the disc.
plot_disc: Boolean controlling whether the Cartesian points are plotted (default = False).
use_spiral: Boolean controlling whether the Cartesian points are chosen using a spiral sampling pattern.
Concentric sampling is used by default.
Returns:
disc: 2 x num_points or 3 x num_points array of Cartesian coordinates.
"""
# check input values
if radius <= 0:
raise ValueError("The radius must be positive.")
def make_spiral_circle_points(num_points: int, radius: float) -> np.ndarray:
# compute spiral parameters
theta = lambda t: GOLDEN_ANGLE * t
C = np.pi * radius**2 / (num_points - 1)
r = lambda t: np.sqrt(C * t / np.pi)
# compute canonical spiral points
t = np.linspace(0, num_points - 1, num_points)
p0 = np.multiply(np.vstack((np.cos(theta(t)), np.sin(theta(t)))), r(t))
return p0
def make_concentric_circle_points(num_points: int, radius: float) -> Tuple[np.ndarray, int]:
assert num_points >= 1, "The number of points must be greater or equal to 1."
num_radial = int(np.ceil(np.sqrt(num_points / np.pi)))
try:
d_radial = radius / (num_radial - 1)
except ZeroDivisionError:
d_radial = float("inf")
r = np.arange(num_radial) * (radius - d_radial / 2) / (num_radial - 1)
# recompute the number of points that will be created below
num_points = 1
for k in range(2, num_radial + 1):
num_theta = round((k - 1) * PACKING_NUMBER)
num_points += num_theta
# compute canonical concentric circle points
points = np.full((2, num_points), np.nan)
points[:, 0] = [0, 0]
i_left = 1
for k in range(2, num_radial + 1):
num_theta = round((k - 1) * PACKING_NUMBER)
thetas = np.arange(num_theta) * 2 * np.pi / num_theta
p = r[k - 1] * np.vstack((np.cos(thetas), np.sin(thetas)))
i_right = i_left + num_theta
points[:, i_left:i_right] = p
i_left = i_right
return points, num_points
if use_spiral:
p0 = make_spiral_circle_points(num_points, radius)
else:
# otherwise use concentric circles (note that the num_points is increased
# to ensure a full set of concentric rings)
p0, num_points = make_concentric_circle_points(num_points, radius)
# add z-dimension points if in 3D
if len(disc_pos) == 3:
p0 = np.vstack((p0, np.zeros((1, num_points))))
# if 3D and focus_pos is defined, rotate the canonical points to give the
# specified disc
if len(disc_pos) == 3:
# check the focus position isn't coincident with the disc position
if np.all(np.isclose(np.array(disc_pos), np.array(focus_pos))):
raise ValueError("The focus_pos must be different from the disc_pos.")
# compute rotation matrix and apply
R, _ = compute_linear_transform(disc_pos, focus_pos)
p0 = np.dot(R, p0)
# shift the disc to the appropriate center
disc = p0 + np.array(disc_pos).reshape(-1, 1)
# plot results
if plot_disc:
# select suitable axis scaling factor
_, scale, prefix, unit = scale_SI(np.max(disc))
# create the figure
fig = plt.figure()
cmap = plt.get_cmap('viridis', np.shape(disc)[1])
if len(disc_pos) == 2:
ax = fig.add_subplot(111)
ax.scatter(disc[1, :] * scale, disc[0, :] * scale, marker='.',
c=np.arange(np.shape(disc)[1]), cmap=cmap, alpha=0.9, edgecolor=None)
ax.invert_yaxis()
ax.xlabel(f"y-position [{prefix}m]")
ax.ylabel(f"x-position [{prefix}m]")
ax.axis("equal")
ax.grid(True)
ax.box(True)
else:
ax = fig.add_subplot(111, projection="3d")
ax.scatter(disc[0, :] * scale, disc[1, :] * scale, disc[2, :] * scale, marker='.',
c=np.arange(np.shape(disc)[1]), cmap=cmap, alpha=0.9, edgecolor=None)
ax.set_xlabel(f"[{prefix}m]")
ax.set_ylabel(f"[{prefix}m]")
ax.set_zlabel(f"[{prefix}m]")
ax.axis("equal")
ax.grid(True)
ax.box(True)
return np.squeeze(disc)
@typechecker
def make_cart_bowl(
bowl_pos: np.ndarray, radius: float, diameter: float, focus_pos: np.ndarray, num_points: int, plot_bowl: Optional[bool] = False
) -> Float[np.ndarray, "3 NumPoints"]:
"""
Create evenly distributed Cartesian points covering a bowl.
Args:
bowl_pos: Cartesian position of the centre of the rear surface of
the bowl given as a three element vector [bx, by, bz] [m].
radius: Radius of curvature of the bowl [m].
diameter: Diameter of the opening of the bowl [m].
focus_pos: Any point on the beam axis of the bowl given as a three
element vector [fx, fy, fz] [m].
num_points: Number of points on the bowl.
plot_bowl: Boolean controlling whether the Cartesian points are
plotted.
Returns:
3 x num_points array of Cartesian coordinates.
Examples:
bowl = makeCartBowl([0, 0, 0], 1, 2, [0, 0, 1], 100)
bowl = makeCartBowl([0, 0, 0], 1, 2, [0, 0, 1], 100, True)
"""
# check input values
if radius <= 0:
raise ValueError("The radius must be positive.")
if diameter <= 0:
raise ValueError("The diameter must be positive.")
if diameter > 2 * radius:
raise ValueError("The diameter of the bowl must be equal or less than twice the radius of curvature.")
if np.all(bowl_pos == focus_pos):
raise ValueError("The focus_pos must be different from the bowl_pos.")
# check for infinite radius of curvature, and call makeCartDisc instead
if np.isinf(radius):
bowl = make_cart_disc(bowl_pos, diameter / 2, focus_pos, num_points, plot_bowl)
return bowl
# compute arc angle from chord (ref: https://en.wikipedia.org/wiki/Chord_(geometry))
varphi_max = np.arcsin(diameter / (2 * radius))
# compute spiral parameters
theta = lambda t: GOLDEN_ANGLE * t
C = 2 * np.pi * (1 - np.cos(varphi_max)) / (num_points - 1)
varphi = lambda t: np.arccos(1 - C * t / (2 * np.pi))
# compute canonical spiral points
t = np.linspace(0, num_points - 1, num_points)
p0 = np.array([np.cos(theta(t)) * np.sin(varphi(t)), np.sin(theta(t)) * np.sin(varphi(t)), np.cos(varphi(t))])
p0 = radius * p0
# linearly transform the canonical spiral points to give bowl in correct orientation
R, b = compute_linear_transform(bowl_pos, focus_pos, radius)
if b.ndim == 1:
b = np.expand_dims(b, axis=-1) # expand dims for broadcasting
bowl = R @ p0 + b
# plot results
if plot_bowl is True:
# select suitable axis scaling factor
_, scale, prefix, unit = scale_SI(np.max(bowl))
# create the figure
fig = plt.figure()
cmap = plt.get_cmap('viridis', np.shape(bowl)[1])
ax = fig.add_subplot(111, projection="3d")
ax.scatter(bowl[0, :] * scale, bowl[1, :] * scale, bowl[2, :] * scale, marker='.',
c=np.arange(np.shape(bowl)[1]), cmap=cmap, alpha=0.9, edgecolor=None)
ax.set_xlabel("[" + prefix + unit + "]")
ax.set_ylabel("[" + prefix + unit + "]")
ax.set_zlabel("[" + prefix + unit + "]")
ax.set_box_aspect([1, 1, 1])
plt.grid(True)
plt.show()
return bowl
def get_spaced_points(start: float, stop: float, n: int = 100, spacing: str = "linear") -> np.ndarray:
"""
Generate a row vector of either logarithmically or linearly spaced points between `start` and `stop`.
When `spacing` is set to 'linear', the function is identical to the inbuilt `np.linspace` function.
When `spacing` is set to 'log', the function is similar to the inbuilt `np.logspace` function, except
that `start` and `stop` define the start and end numbers, not decades. For logarithmically spaced
points, `start` must be > 0. If `n` < 2, `stop` is returned.
Args:
start: start value for the spaced points
stop: end value for the spaced points
n: number of points to generate
spacing: type of spacing to use, either 'linear' or 'log'
Returns:
points: row vector of spaced points
Raises:
ValueError: if `stop` <= `start` or `spacing` is not 'linear' or 'log'
"""
if stop <= start:
raise ValueError("`stop` must be larger than `start`.")
if spacing == "linear":
return np.linspace(start, stop, num=n)
elif spacing == "log":
return np.geomspace(start, stop, num=n)
else:
raise ValueError(f"`spacing` {spacing} is not a valid argument. Choose from 'linear' or 'log'.")
def fit_power_law_params(a0: float, y: float, c0: float, f_min: float, f_max: float, plot_fit: bool = False) -> Tuple[float, float]:
"""
Calculate absorption parameters that fit a power law over a given frequency range.
This function calculates the absorption parameters that should be defined in the simulation functions
to achieve the desired power law absorption behavior defined by `a0` and `y`. This takes into account
the actual absorption behavior exhibited by the fractional Laplacian wave equation.
This fitting is required when using large absorption values or high frequencies, as the fractional
Laplacian wave equation solved in `kspaceFirstOrderND` and `kspaceSecondOrder` no longer encapsulates
absorption of the form `a = a0*f^y`.
The returned values should be used to define `medium.alpha_coeff` and `medium.alpha_power` within the
simulation functions. The absorption behavior over the frequency range `f_min`:`f_max` will then
follow the power law defined by `a0` and `y`.
Args:
a0: coefficient in the power law absorption equation
y: exponent in the power law absorption equation
c0: speed of sound in the medium
f_min: minimum frequency in the range to fit the power law
f_max: maximum frequency in the range to fit the power law
plot_fit: whether to plot the fit
Returns:
A tuple of the absorption coefficient and fitted exponent of the power law absorption equation.
"""
# define frequency axis
f = get_spaced_points(f_min, f_max, 200)
w = 2 * np.pi * f
# convert user defined a0 to Nepers/((rad/s)^y m)
a0_np = db2neper(a0, y)
desired_absorption = a0_np * w**y
def abs_func(trial_vals):
"""Second-order absorption error"""
a0_np_trial, y_trial = trial_vals
actual_absorption = (
a0_np_trial * w**y_trial / (1 - (y_trial + 1) * a0_np_trial * c0 * np.tan(np.pi * y_trial / 2) * w ** (y_trial - 1))
)
absorption_error = np.sqrt(np.sum((desired_absorption - actual_absorption) ** 2))
return absorption_error
a0_np_fit, y_fit = fmin(abs_func, [a0_np, y])
a0_fit = neper2db(a0_np_fit, y_fit)
if plot_fit:
raise NotImplementedError
return a0_fit, y_fit
def power_law_kramers_kronig(w: np.ndarray, w0: float, c0: float, a0: float, y: float) -> np.ndarray:
"""
Compute the variation in sound speed for an attenuating medium using the Kramers-Kronig for power law attenuation.
This function computes the variation in sound speed for an attenuating medium using the Kramers-Kronig
formula for power law attenuation, where `att = a0 * w^y`. The power law parameters must be in Nepers/m,
with the frequency in rad/s. The variation is given about the sound speed `c0` at a reference frequency `w0`.
Args:
w: input frequency array [rad/s]
w0: reference frequency [rad/s]
c0: sound speed at w0 [m/s]
a0: power law coefficient [Nepers/((rad/s)^y m)]
y: power law exponent, where 0 < y < 3
Returns:
Variation of sound speed with w [m/s]
"""
if 0 >= y or y >= 3:
logging.log(logging.WARN, f"{UserWarning.__name__}: y must be within the interval (0,3)")
warnings.warn("y must be within the interval (0,3)", UserWarning)
c_kk = c0 * np.ones_like(w)
elif y == 1:
# Kramers-Kronig for y = 1
c_kk = 1 / (1 / c0 - 2 * a0 * np.log(w / w0) / np.pi)
else:
# Kramers-Kronig for 0 < y < 1 and 1 < y < 3
c_kk = 1 / (1 / c0 + a0 * np.tan(y * np.pi / 2) * (w ** (y - 1) - w0 ** (y - 1)))
return c_kk
def water_absorption(f: float, temp: Union[float, kt.NP_DOMAIN]) -> Union[float, kt.NP_DOMAIN]:
"""
Calculates the ultrasonic absorption in distilled
water at a given temperature and frequency using a 7 th order
polynomial fitted to the data given by Pinkerton (1949).
Args:
f: f frequency value [MHz]
T: water temperature value [degC]
Returns:
abs: absorption [dB / cm]
Examples:
>>> abs = waterAbsorption(f, T)
References:
[1] J. M. M. Pinkerton (1949) "The Absorption of Ultrasonic Waves in Liquids and its
Relation to Molecular Constitution,"
Proceedings of the Physical Society. Section B, 2, 129-141
"""
NEPER2DB = 8.686
# check temperature is within range
if not np.all([np.all(temp >= 0.0), np.all(temp <= 60.0)]):
raise Warning("Temperature outside range of experimental data")
# conversion factor between Nepers and dB NEPER2DB = 8.686;
# coefficients for 7th order polynomial fit
a = [
56.723531840522710,
-2.899633796917384,
0.099253401567561,
-0.002067402501557,
2.189417428917596e-005,
-6.210860973978427e-008,
-6.402634551821596e-010,
3.869387679459408e-012,
]
# compute absorption
a_on_fsqr = (
a[0] + a[1] * temp + a[2] * temp**2 + a[3] * temp**3 + a[4] * temp**4 + a[5] * temp**5 + a[6] * temp**6 + a[7] * temp**7
) * 1e-17
abs = NEPER2DB * 1e12 * f**2 * a_on_fsqr
return abs
def water_sound_speed(temp: Union[float, kt.NP_DOMAIN]) -> Union[float, kt.NP_DOMAIN]:
"""
Calculate the sound speed in distilled water with temperature according to Marczak (1997)
Args:
temp: The temperature of the water in degrees Celsius.
Returns:
c: The sound speed in distilled water in m/s.
Raises:
ValueError: if `temp` is not between 0 and 95
References:
[1] R. Marczak (1997). "The sound velocity in water as a function of temperature".
Journal of Research of the National Institute of Standards and Technology, 102(6), 561-567.
"""
# check limits
if not np.all([np.all(temp >= 0.0), np.all(temp <= 95.0)]):
raise ValueError("`temp` must be between 0 and 95.")
# find value
p = [2.787860e-9, -1.398845e-6, 3.287156e-4, -5.779136e-2, 5.038813, 1.402385e3]
c = np.polyval(p, temp)
return c
def water_density(temp: Union[kt.NUMERIC, np.ndarray]) -> Union[kt.NUMERIC, np.ndarray]:
"""
Calculate the density of air-saturated water with temperature.
This function calculates the density of air-saturated water at a given temperature using the 4th order polynomial
given by Jones [1].
Args:
temp: water temperature in the range 5 to 40 [degC]
Returns:
density: density of water [kg/m^3]
Raises:
ValueError: if `temp` is not between 5 and 40
References:
[1] F. E. Jones and G. L. Harris (1992) "ITS-90 Density of Water Formulation for Volumetric Standards Calibration,"
Journal of Research of the National Institute of Standards and Technology, 97(3), 335-340.
"""
# check limits
if not np.all([np.all(np.asarray(temp) >= 5.0), np.all(np.asarray(temp) <= 40.0)]):
raise ValueError("`temp` must be between 5 and 40.")
# calculate density of air-saturated water
density = 999.84847 + 6.337563e-2 * temp - 8.523829e-3 * temp**2 + 6.943248e-5 * temp**3 - 3.821216e-7 * temp**4
return density
def water_non_linearity(temp: Union[float, kt.NP_DOMAIN]) -> Union[float, kt.NP_DOMAIN]:
"""
Calculates the parameter of nonlinearity B/A at a
given temperature using a fourth-order polynomial fitted to the data
given by Beyer (1960).
Args:
temp: water temperature in the range 0 to 100 [degC]
Returns:
BonA: parameter of nonlinearity
Examples:
>>> BonA = waterNonlinearity(T)
References:
[1] R. T. Beyer (1960) "Parameter of nonlinearity in fluids,"
J. Acoust. Soc. Am., 32(6), 719-721.
"""
# check limits
if not np.all([np.all(temp >= 0.0), np.all(temp <= 100.0)]):
raise ValueError("`temp` must be between 0 and 100.")
# find value
p = [-4.587913769504693e-08, 1.047843302423604e-05, -9.355518377254833e-04, 5.380874771364909e-2, 4.186533937275504]
BonA = np.polyval(p, temp)
return BonA
@typechecker
def make_ball(
grid_size: Vector, ball_center: Vector, radius: int, plot_ball: bool = False, binary: bool = False
) -> Union[kt.NP_ARRAY_INT_3D, kt.NP_ARRAY_BOOL_3D]:
"""
Creates a binary map of a filled ball within a 3D grid.
Args:
grid_size: size of the 3D grid in [grid points].
ball_center: centre of the ball in [grid points]
radius: ball radius [grid points].
plot_ball: whether to plot the ball using voxelPlot (default = False).
binary: whether to return the ball map as a double precision matrix (False) or a logical matrix (True) (default = False).
Returns:
ball: 3D binary map of a filled ball.
"""
# define literals
MAGNITUDE = 1
assert grid_size.shape == (3,), "grid_size must be a 3 element vector"
assert ball_center.shape == (3,), "ball_center must be a 3 element vector"
# force integer values
grid_size = cast(Vector, grid_size.astype(int))
ball_center = cast(Vector, ball_center.astype(int))
# check for zero values
for i in range(3):
if ball_center[i] == 0:
ball_center[i] = int(floor(grid_size[i] / 2)) + 1
# create empty matrix
ball = np.zeros(grid_size).astype(bool if binary else int)
# define np.pixel map
r = make_pixel_map(grid_size, shift=[0, 0, 0])
# create ball
ball[r <= radius] = MAGNITUDE
# shift centre
ball_center = ball_center - np.ceil(grid_size / 2).astype(int)
ball = np.roll(ball, ball_center, axis=(0, 1, 2))
# plot results
if plot_ball:
_, scale, prefix, _ = scale_SI(np.max(ball))
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.scatter(ball[0] * scale, ball[1] * scale, ball[2] * scale)
ax.set_xlabel("[" + prefix + "m]")
ax.set_ylabel("[" + prefix + "m]")
ax.set_zlabel("[" + prefix + "m]")
ax.set_box_aspect([1, 1, 1])
plt.grid(True)
plt.show()
return ball
@typechecker
def make_cart_sphere(
radius: Union[float, int],
num_points: int,
center_pos: Optional[Union[Real[kt.ScalarLike, "3"], List, Int[np.ndarray, "3"], Float[np.ndarray, "3"]]] = np.zeros((3,)),
plot_sphere: bool = False
) -> Float[np.ndarray, "3 NumPoints"]:
"""
Creates a set of points in Cartesian coordinates defining a sphere.
Args:
radius: the radius of the sphere.
num_points: the number of points to be generated.
center_pos: the coordinates of the center of the sphere. Defaults to (0, 0, 0).
plot_sphere: whether to plot the sphere. Defaults to False.
Returns:
The points on the sphere.
"""
# generate angle functions using the Golden Section Spiral method
inc = np.pi * (3 - np.sqrt(5))
off = 2 / num_points
k = np.arange(0, num_points)
y = k * off - 1 + (off / 2)
r = np.sqrt(1 - (y**2))
phi = k * inc
if num_points <= 0:
raise ValueError("num_points must be greater than 0")
# create the sphere
sphere = radius * np.concatenate([np.cos(phi) * r[np.newaxis, :], y[np.newaxis, :], np.sin(phi) * r[np.newaxis, :]])
# offset if needed
sphere = sphere + center_pos[:, None]
# plot results
if plot_sphere:
# select suitable axis scaling factor
[x_sc, scale, prefix, _] = scale_SI(np.max(sphere))
cmap = plt.get_cmap('viridis', np.shape(sphere)[1])
# create the figure
plt.figure()
# plt.style.use("seaborn-poster")
ax = plt.axes(projection="3d")
ax.scatter(sphere[0, :] * scale, sphere[1, :] * scale, sphere[2, :] * scale, marker='.',
c=np.arange(np.shape(sphere)[1]), cmap=cmap, alpha=0.9, edgecolor=None)
ax.set_xlabel(f"[{prefix} m]")
ax.set_ylabel(f"[{prefix} m]")
ax.set_zlabel(f"[{prefix} m]")
ax.axis("auto")
ax.grid()
plt.show()
return sphere.squeeze()
@typechecker
def make_cart_circle(
radius: float, num_points: int, center_pos: Vector = Vector([0, 0]), arc_angle: float = 2 * np.pi, plot_circle: bool = False
) -> Float[np.ndarray, "2 NumPoints"]:
"""
Create a set of points in cartesian coordinates defining a circle or arc.
This function creates a set of points in cartesian coordinates defining a circle or arc.
Args:
radius: radius of the circle or arc
num_points: number of points to generate
center_pos: center position of the circle or arc
arc_angle: arc angle in radians
plot_circle: whether to plot the circle or arc
Returns:
2 x `num_points` array of cartesian coordinates
"""
# check for arc_angle input
if arc_angle == 2 * np.pi:
full_circle = True
else:
full_circle = False
n_steps = num_points if full_circle else num_points - 1
# create angles
angles = np.arange(0, num_points) * arc_angle / n_steps + np.pi / 2
# create cartesian grid
circle = np.concatenate([radius * np.cos(angles[np.newaxis, :]), radius * np.sin(-angles[np.newaxis])])
# offset if needed
circle = circle + center_pos[:, None]
# plot results
if plot_circle:
# select suitable axis scaling factor
[_, scale, prefix, _] = scale_SI(np.max(abs(circle)))
# create the figure
plt.figure()
plt.plot(circle[1, :] * scale, circle[0, :] * scale, "b.")
plt.xlabel([f"y-position [{prefix} m]"])
plt.ylabel([f"x-position [{prefix} m]"])
plt.axis("equal")
plt.show()
return np.squeeze(circle)
@typechecker
def make_disc(grid_size: Vector, center: Vector, radius, plot_disc=False) -> kt.NP_ARRAY_BOOL_2D:
"""
Create a binary map of a filled disc within a 2D grid.
This function creates a binary map of a filled disc within a two-dimensional grid. The disc position is denoted by 1's
in the matrix with 0's elsewhere. A single grid point is taken as the disc centre, so the total diameter of the disc
will always be an odd number of grid points. If used within a k-Wave grid where dx != dy, the disc will appear oval
shaped. If part of the disc overlaps the grid edge, the rest of the disc will wrap to the grid edge on the opposite
side.
Args:
grid_size: A 2D vector of the grid size in grid points.
center: A 2D vector of the disc centre in grid points.
radius: The radius of the disc.
plot_disc: If set to True, the disc will be plotted using Matplotlib.
Returns:
A binary map of the disc in the 2D grid.
"""
assert len(grid_size) == 2, "Grid size must be 2D."
assert len(center) == 2, "Center must be 2D."
# define literals
MAGNITUDE = 1
# force integer values
grid_size = grid_size.round().astype(int)
center = center.round().astype(int)
# check for zero values
center.x = center.x if center.x != 0 else np.floor(grid_size.x / 2).astype(int) + 1
center.y = center.y if center.y != 0 else np.floor(grid_size.y / 2).astype(int) + 1
# check the inputs
assert np.all(0 < center) and np.all(center <= grid_size), "Disc center must be within grid."
# create empty matrix
disc = np.zeros(grid_size, dtype=bool)
# define np.pixel map
r = make_pixel_map(grid_size, shift=[0, 0])
# create disc
disc[r <= radius] = MAGNITUDE
# shift centre
center = center - np.ceil(grid_size / 2).astype(int)
disc = np.roll(disc, center, axis=(0, 1))
# create the figure
if plot_disc:
_, ax = plt.subplots(1, 1)
ax.imshow(disc)
ax.set_aspect('auto', adjustable='box')
ax.yaxis.set_inverted(True)
plt.show()
return disc
@typechecker
def make_circle(
grid_size: Vector, center: Vector, radius: Real[kt.ScalarLike, ""], arc_angle: Optional[float] = None, plot_circle: bool = False
) -> kt.NP_ARRAY_INT_2D:
"""
Create a binary map of a circle within a 2D grid.
This function creates a binary map of a circle (or arc) using the midpoint circle algorithm within a two-dimensional grid.
The circle position is denoted by 1's in the matrix with 0's elsewhere. A single grid point is taken as the circle
centre, so the total diameter will always be an odd number of grid points. The centre of the circle and the radius
are not constrained by the grid dimensions, so it is possible to create sections of circles or a blank image if none
of the circle intersects the grid.
Args:
grid_size: A 2D vector of the grid size in grid points.
center: A 2D vector of the circle centre in grid points.
radius: The radius of the circle.
arc_angle: The angle of the circular arc in degrees. If set to None, a full circle will be created.
plot_circle: If set to True, the circle will be plotted using Matplotlib.
Returns:
A binary map of the circle in the 2D grid.
"""
assert len(grid_size) == 2, "Grid size must be 2D"
assert len(center) == 2, "Center must be 2D"
# define literals
MAGNITUDE = 1
if arc_angle is None:
arc_angle = 2 * np.pi
elif arc_angle > 2 * np.pi:
arc_angle = 2 * np.pi
elif arc_angle < 0:
arc_angle = 0
# force integer values
grid_size = grid_size.round().astype(int)
center = center.round().astype(int)
radius = int(round(radius))
# check for zero values
center.x = center.x if center.x != 0 else int(floor(grid_size.x / 2)) + 1
center.y = center.y if center.y != 0 else int(floor(grid_size.y / 2)) + 1
cx, cy = center
# create empty matrix
circle = np.zeros(grid_size, dtype=int)
# initialise loop variables
x = 0
y = radius
d = 1 - radius
if (cx >= 1) and (cx <= grid_size.x) and ((cy - y) >= 1) and ((cy - y) <= grid_size.y):
circle[cx - 1, cy - y - 1] = MAGNITUDE
# draw the remaining cardinal points
px = [cx, cx + y, cx - y]
py = [cy + y, cy, cy]
for point_index, (px_i, py_i) in enumerate(zip(px, py)):
# check whether the point is within the arc made by arc_angle, and lies
# within the grid
if (np.arctan2(px_i - cx, py_i - cy) + np.pi) <= arc_angle:
if (px_i >= 1) and (px_i <= grid_size.x) and (py_i >= 1) and (py_i <= grid_size.y):
circle[px_i - 1, py_i - 1] = MAGNITUDE
# loop through the remaining points using the midpoint circle algorithm
while x < (y - 1):
x = x + 1
if d < 0:
d = d + x + x + 1
else:
y = y - 1
a = x - y + 1
d = d + a + a
# setup point indices (break coding standard for readability)
px = [x + cx, y + cx, y + cx, x + cx, -x + cx, -y + cx, -y + cx, -x + cx]
py = [y + cy, x + cy, -x + cy, -y + cy, -y + cy, -x + cy, x + cy, y + cy]
# loop through each point
for point_index, (px_i, py_i) in enumerate(zip(px, py)):
# check whether the point is within the arc made by arc_angle, and
# lies within the grid
if (np.arctan2(px_i - cx, py_i - cy) + np.pi) <= arc_angle:
if (px_i >= 1) and (px_i <= grid_size.x) and (py_i >= 1) and (py_i <= grid_size.y):
circle[px_i - 1, py_i - 1] = MAGNITUDE
if plot_circle:
plt.imshow(circle, cmap="gray_r")
plt.ylabel("x-position [grid points]")
plt.xlabel("y-position [grid points]")
plt.show()
return circle
def make_pixel_map(grid_size: Vector, shift=None, origin_size="single") -> np.ndarray:
"""
Generates a matrix with values of the distance of each pixel from the center of a grid.
This function generates a matrix populated with values of how far each pixel in a grid is from the center. The center
can be a single pixel or a double pixel, and the optional input parameter 'OriginSize' controls this. For grids where
the dimension size and center pixel size are not both odd or even, the optional input parameter 'Shift' can be used to
control the location of the center point.
Args:
grid_size: A 2D or 3D vector of the grid size in grid points.
*args: additional optional arguments
Returns:
r: pixel-radius
Examples:
Single pixel origin size for odd and even (with 'Shift' = [1 1] and
[0 0], respectively) grid sizes:
x x x x x x x x x x x
x 0 x x x x x x 0 x x
x x x x x 0 x x x x x
x x x x x x x x
Double pixel origin size for even and odd (with 'Shift' = [1 1] and
[0 0], respectively) grid sizes:
x x x x x x x x x x x x x x
x 0 0 x x x x x x x 0 0 x x
x 0 0 x x x 0 0 x x 0 0 x x
x x x x x x 0 0 x x x x x x
x x x x x x x x x x
By default, a single pixel centre is used which is shifted towards
the final row and column.
"""
assert len(grid_size) == 2 or len(grid_size) == 3, "Grid size must be a 2 or 3 element vector."
# define defaults
shift_def = 1
Nx = grid_size[0]
Ny = grid_size[1]
Nz = None
if len(grid_size) == 3:
Nz = grid_size[2]
# detect whether the inputs are for two or three dimensions
map_dimension = 2 if Nz is None else 3
if shift is None:
shift = [shift_def] * map_dimension
# catch input errors
assert origin_size in ["single", "double"], "Unknown setting for optional input Center."
assert (
len(shift) == map_dimension
), f"Optional input Shift must have {map_dimension} elements for {map_dimension} dimensional input parameters."
if map_dimension == 2:
# create the maps for each dimension
nx = create_pixel_dim(Nx, origin_size, shift[0])
ny = create_pixel_dim(Ny, origin_size, shift[1])
# create plaid grids
r_x, r_y = np.meshgrid(nx, ny, indexing="ij")
# extract the pixel radius
r = np.sqrt(r_x**2 + r_y**2)
if map_dimension == 3:
# create the maps for each dimension
nx = create_pixel_dim(Nx, origin_size, shift[0])
ny = create_pixel_dim(Ny, origin_size, shift[1])
nz = create_pixel_dim(Nz, origin_size, shift[2])
# create plaid grids
r_x, r_y, r_z = np.meshgrid(nx, ny, nz, indexing="ij")
# extract the pixel radius
r = np.sqrt(r_x**2 + r_y**2 + r_z**2)
return r
def create_pixel_dim(Nx: int, origin_size: float, shift: float) -> Tuple[np.ndarray, float]:
"""
Create an array of pixel dimensions and a pixel size.
Args:
Nx: The number of pixels in the x-dimension.
origin_size: The size of the origin in the x-dimension.
shift: The shift of the pixels in the x-dimension.
Returns:
The pixel dimensions.
"""
# Nested function to create the pixel radius variable
# grid dimension has an even number of points
if Nx % 2 == 0:
# pixel numbering has a single centre point
if origin_size == "single":
# centre point is shifted towards the final pixel
if shift == 1:
nx = np.arange(-Nx / 2, Nx / 2 - 1 + 1, 1)
# centre point is shifted towards the first pixel
else:
nx = np.arange(-Nx / 2 + 1, Nx / 2 + 1, 1)
# pixel numbering has a double centre point
else:
nx = np.hstack([np.arange(-Nx / 2 + 1, 0 + 1, 1), np.arange(0, Nx / 2 - 1 + 1, 1)])
# grid dimension has an odd number of points
else:
# pixel numbering has a single centre point
if origin_size == "single":
nx = np.arange(-(Nx - 1) / 2, (Nx - 1) / 2 + 1, 1)
# pixel numbering has a double centre point
else:
# centre point is shifted towards the final pixel
if shift == 1:
nx = np.hstack([np.arange(-(Nx - 1) / 2, 0 + 1, 1), np.arange(0, (Nx - 1) / 2 - 1 + 1, 1)])
# centre point is shifted towards the first pixel
else:
nx = np.hstack([np.arange(-(Nx - 1) / 2 + 1, 0 + 1, 1), np.arange(0, (Nx - 1) / 2 + 1, 1)])
return nx
@typechecker
def make_line(
grid_size: Vector,
startpoint: Union[Tuple[Int[kt.ScalarLike, ""], Int[kt.ScalarLike, ""]], Int[np.ndarray, "2"]],
endpoint: Optional[Union[Tuple[Int[kt.ScalarLike, ""], Int[kt.ScalarLike, ""]], Int[np.ndarray, "2"]]] = None,
angle: Optional[Float[kt.ScalarLike, ""]] = None,
length: Optional[Int[kt.ScalarLike, ""]] = None,
) -> kt.NP_ARRAY_BOOL_2D:
"""
Generate a line shape with a given start and end point, angle, or length.
Args:
grid_size: The size of the grid in pixels.
startpoint: The start point of the line, given as a tuple of x and y coordinates.
endpoint: The end point of the line, given as a tuple of x and y coordinates.
If not specified, the line is drawn from the start point at a given angle and length.
angle: The angle of the line in radians, measured counterclockwise from the x-axis.
If not specified, the line is drawn from the start point to the end point.
length: The length of the line in pixels.
If not specified, the line is drawn from the start point to the end point.