-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyFDTD.py
1670 lines (1351 loc) · 58 KB
/
pyFDTD.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
# import matplotlib
# matplotlib.use('TkAgg')
# matplotlib.use('wxAgg')
# matplotlib.use('Qt5Agg')
import numpy as np
from PIL import Image
# import time
# Constants
PI = np.pi
# Start settings
NDIM = 2
NXYZ = [100, 150, 50]
X_STEP = 0.01
SRC_XYZ = [[0.25, 0.75, 0.1]]
REC_XYZ = [[0.75, 0.25, 0.2]]
SRC_TYPE_DEFAULT = "Gauss deriv 1"
C0 = 344
SIM_TIME = 0.01
PLOT_UPDATE_TIME = 0.01
PLOT_ITH_UPDATE = 1
DO_PLOT = True
DEBUG = False
DEBUG_PREFIX = ""
USE_SCIPY = True # WARNING - set to False is limited and untested
USE_MATPLOTLIB = True
# If using scipy or not (for 2D convolve)
if USE_SCIPY:
from scipy.signal import convolve2d, resample
from scipy import ndimage
from scipy.io import wavfile
else:
# TODO - non-scipy wav write
()
if USE_MATPLOTLIB:
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
# TODO
# GIF
# - Test 3D vertical orientation
# - Do 1D
# - Add src/recs??
# Test 1D and 3D
# - Sim
# - 1D no negative component??
# - Mesh creating
# Plots:
# - Add src/rec labels
# - Add optional plotSliceHeight for 3D
# Do staggered mesh to grid
# Add proper examples
# Do proper readme
# Add more debug text?
# Improve mesh fix (diagonals causing dispersion??)
# Alter src/rec to a dict - e.g. srcXyz -> src['Xyz']
# Future:
# Filter surfaces
# Thread??
class pyFDTD:
def __init__(self,
NDim=NDIM,
debug=DEBUG,
debugPrefix=DEBUG_PREFIX,
doPlot=DO_PLOT):
# Init
# No. dimensions, debug and plot modes
self.NDim = NDim
self.debugPrefix = debugPrefix
self.debug = debug
self.doPlot = doPlot
# Update on debug
self.printToDebug('__init__')
# Define defaults
self.setDefaults()
# Set basic inputs
self.setInputs()
# Default empty mesh
self.meshReset(doPrepareMesh=True)
# Default source and receivers
for src in SRC_XYZ:
self.addSrc(src[0:self.NDim])
for rec in REC_XYZ:
self.addRec(rec[0:self.NDim])
def setDefaults(self):
# Update on debug
self.printToDebug('setDefaults')
# Defaults
self.c = C0
self.X = X_STEP
self.t = SIM_TIME
self.plotUpdateTime = PLOT_UPDATE_TIME
self.plotIthUpdate = PLOT_ITH_UPDATE
self.saveRecData = False
self.recDataFile = 'recData.wav'
self.fsOut = None
self.saveGif = False
self.gifFile = 'gifOut.gif'
self.gifFrameTime = 40 # ms
self.gifLoopNum = 0
self.gifArea = None
self.beta = 0
self.betaBorder = 0
self.betaType = 'admittance'
self.betaMode = 'constant'
self.cLims = [-0.1, 0.1]
self.c0 = [1.0, 1.0, 1.0]
self.c1 = [0.0, 0.0, 1.0]
self.c2 = [1.0, 0.0, 0.0]
self.da = 0
self.db = 0
self.dc = 0
self.imageThreshold = 0
self.plotShowMask = True
self.plotMaskColInvert = False
self.plotShowColBar = True
self.plotShowSrc = True
self.plotShowRec = True
self.image = None
self.mesh = None
self.doSrcRecCoordsCheck \
= True
self.srcXyz = []
self.recXyz = []
self.srcXyzDisc = []
self.recXyzDisc = []
self.srcData = []
self.recData = []
self.srcInd = []
self.recInd = []
self.srcFlatInd = []
self.recFlatInd = []
self.srcNodeType = []
self.recNodeType = []
self.srcAmp = []
self.recAmp = []
self.srcStrength = []
self.recStrength = []
self.srcT0 = []
self.srcFreq = []
self.srcType = []
self.srcN = len(self.srcXyz)
self.recN = len(self.recXyz)
self.psn, self.pon, self.pgn = None, None, None
self.psn1, self.psn2, self.psn3 = None, None, None
self.pon1, self.pon2, self.pon3 = None, None, None
self.bp1_1, self.bp1_2, self.bp1_3 = None, None, None
self.bm1 = None
self.updatePlotThisLoop = None
self.running = False
self.figNum = None
# Default grid size
self.Nxyz = NXYZ[0:self.NDim]
# Adjust colour plot limits according to No. dimensions
cLimScale = (1/40)**(self.NDim-2)
self.cLims = [cLim*cLimScale for cLim in self.cLims]
def run(self):
# Run full simulation
# Update on debug
self.printToDebug('run')
# Ensure basic inputs are up to date
self.setInputs()
# Sets back to start of sim
self.runReset()
# Check mesh
self.checkMesh()
# Prepare mesh
self.prepareMesh()
# Loop round until end of sim
self.runSteps(self.Nt)
def runSteps(self, nSteps = None):
# Run specified number of steps
# No setting of inputs, resetting sim etc.
# Default to plotIthUpdate number of steps
if nSteps == None:
nSteps = self.plotIthUpdate
# Do to end loop number
endLoopNum = self.loopNum+nSteps
endLoopNum = min(endLoopNum, self.Nt)
# # Check loop number (determines state of self.running)
# self.checkLoopNum()
# Loop...
while self.loopNum < endLoopNum:
# Break if not running
# Note: currently does nothing - need to do in different thread
# for this to have an effect
if self.loopNum > 0 and not self.running:
return self.running
# Run simulation step
self.runStep()
return self.running
def runStep(self):
# Run single simulation step
# No setting of inputs, resetting sim etc.
# Single run step
i = self.loopNum
# Where we're up to (1-indexed)
self.printToDebug("runStep %i/%i"%(self.loopNum+1,self.Nt))
# Update plot on this loop
self.updatePlotThisLoop = (self.loopNum+1)%self.plotIthUpdate == 0
if i >= self.Nt:
# Finished
self.running = False
return self.running
elif i <= 0:
# Set running to true if on firt loop
self.running = True
else:
# Do grid update on i > 0
# Multiply previous surface pressures by beta-1
self.pz.flat[self.psn] *= self.bm1
# Swap p and pz
self.p, self.pz = self.pz, self.p
# Convolve with 'a' matrix, while swapping p and pz back again
self.p *= -1
if USE_SCIPY:
if self.NDim == 1:
self.p += np.convolve(self.pz,self.a,mode='same')
elif self.NDim == 2:
# Because faster than ndimage.convolve
self.p += convolve2d(self.pz, self.a, mode='same')
elif self.NDim == 3:
self.p += ndimage.convolve(self.pz, self.a, mode='constant')
else:
# Numpy equivalent assuming a is expected 2D matrix
# (i.e. [[0,0.5,0], [0.5,0,0.5], [0,0.5,0]])
for k in range(0,self.Nxyz[0]):
self.p[k,:] += np.convolve(self.pz[k,:],self.a[1,:],mode='same')
for k in range(0,self.Nxyz[1]):
self.p[:,k] += np.convolve(self.pz[:,k],self.a[1,:],mode='same')
# Sum of prev pressures at opp nodes
sumPz1 = self.pz.flat[self.pon1]
sumPz2 = self.pz.flat[self.pon2[:,0]] + self.pz.flat[self.pon2[:,1]]
sumPz3 = self.pz.flat[self.pon3[:,0]] + self.pz.flat[self.pon3[:,1]] + \
self.pz.flat[self.pon3[:,2]]
# Add pressure from 'opposite' nodes
self.p.flat[self.psn1] = (self.p.flat[self.psn1] + self.d1*sumPz1) * self.bp1_1 # Surfaces
self.p.flat[self.psn2] = (self.p.flat[self.psn2] + self.d1*sumPz2) * self.bp1_2 # Edges
self.p.flat[self.psn3] = (self.p.flat[self.psn3] + self.d1*sumPz3) * self.bp1_3 # Corners
# Set 'ghosts' back to zero
self.p.flat[self.pgn] = 0.0
# Add source pressure
for j in range(0,self.srcN):
self.p.flat[self.srcFlatInd[j]] += \
self.srcStrength[j] * self.srcData[j][i]
# Store receiver pressure
for j in range(0,self.recN):
self.recData[j][i] = \
self.recStrength[j] * self.p.flat[self.recFlatInd[j]]
# Update plot
self.updatePlot()
# Update loop number or finish
if i >= self.Nt-1:
# This was the last loop
self.running = False
# Save result
if self.saveRecData:
self.writeRecData()
# Save GIF
if self.saveGif:
self.writeGifData()
elif self.running:
# Increment loop number if still running
self.loopNum +=1
return self.running
def runReset(self):
# Reset sim to beginning
# Update on debug
self.printToDebug('runReset')
# Set pressure field to zeros
self.pReset()
# Reset all src/receiver data
self.srcRecDataReset()
# Clear plot
#self.updatePlot(True)
self.makePlot()
# Reset loop count
self.loopNum = 0
def stop(self):
# Stop sim
# Update on debug
self.printToDebug('stop')
# Stop simulation
self.running = False
def checkLoopNum(self):
# Check loop number - don't think used anymore
# Check loop num to see if valid
if self.loopNum == 0:
# Start of sim
self.running = True
elif self.loopNum == self.Nt:
# End of sim
self.running = False
def setInputs(self):
# Set the basic inputs
# Update on debug
self.printToDebug('setInputs')
# Stop if basic inputs are redefined
self.stop()
# Courant No. and update coeffs
self.courantNo()
self.updateCoeffs()
self.getConvMat()
# Sample rate, time step, and new speed of sound
self.fs = round(self.c/(self.lam*self.X))
self.T = 1/self.fs
self.c = self.X*self.lam/self.T
# Size of space
self.NDim = len(self.Nxyz)
self.D = [(N-1)*self.X for N in self.Nxyz]
# Total problem size
self.Ntot = np.prod(self.Nxyz)
# Number time steps
self.Nt = int(np.ceil(self.t/self.T))
# check coordinates of source/receivers
if self.doSrcRecCoordsCheck:
self.checkSrcRecCoords()
# Set colour map
self.setCMap()
def courantNo(self):
# Define Courant No.
self.lam2 = [1-4*self.da, (1-8*self.da+16*self.da**2)/(2-4*self.db), \
(1-12*self.da+48*self.da**2-64*self.da**3)/ \
(3-12*self.db+16*self.dc)]
self.lam2 = np.min(self.lam2[0:self.NDim])
self.lam = np.sqrt(self.lam2)
def updateCoeffs(self):
# Calculate update coefficients
dims = [0]*3
for i in range(0,self.NDim):
dims[i] = 1
lambda2 = self.lam2
self.d1 = lambda2*(1-2*(self.NDim-1)*self.db+dims[2]*4*self.dc)
self.d2 = lambda2*(dims[1]*self.db-dims[2]*2*self.dc)
self.d3 = lambda2*dims[2]*self.dc
self.d4 = 2*(1-self.NDim*lambda2+ \
dims[1]*((self.NDim-1)**2+self.NDim-1)*self.db*lambda2- \
dims[2]*4*self.dc*lambda2)
def getConvMat(self):
# Make convolutin matrix
if self.NDim == 1:
self.a = np.zeros((3))
self.a[[0,2]] = self.d1
self.a[1] = self.d4
elif self.NDim == 2:
self.a = np.zeros((3,3))
self.a[1,[0,2]] = self.d1
self.a[[0,2],1] = self.d1
self.a[[0,2],0] = self.d2
self.a[[0,2],2] = self.d2
self.a[1,1] = self.d4
elif self.NDim == 3:
self.a = np.zeros((3,3,3))
self.a.flat[np.array([4,10,12,14,16,22])] = self.d1
self.a.flat[np.arange(1,12,2)] = self.d2
self.a.flat[np.arange(15,26,2)] = self.d2
self.a.flat[np.array([0,2,6,8,18,20,24,26])] = self.d3
self.a[1,1,1] = self.d4
def checkSrcRecCoords(self):
# Check source and receiver coordinates
# Delete if outside area and move if not
for i in range(0,self.srcN):
ii = self.srcN-i-1 # Go backwards
if not self.checkCoords(self.srcXyz[ii]):
self.delSrc(ii)
else:
self.moveSrc(self.srcXyz[ii], ii)
for i in range(0,self.recN):
ii = self.recN-i-1 # Go backwards
if not self.checkCoords(self.recXyz[ii]):
self.delRec(ii)
else:
self.moveRec(self.recXyz[ii], ii)
def checkCoords(self, xyz):
# Check if coordinates are in range
if len(xyz) != self.NDim:
return False
else:
coordsCheck = True
for i, x in enumerate(xyz):
coordsCheck = coordsCheck and x >= 0 and x <= self.D[i]
return coordsCheck
def pReset(self):
# Set pressure field to zeros
self.p = np.zeros((self.Nxyz))
self.pz = np.zeros((self.Nxyz))
def checkMesh(self, fix=True):
# Check mesh (and attempt to fix if specified)
# Update on debug
self.printToDebug('checkMesh')
# Grid size (this should already have happened)
self.Nxyz = list(self.mesh.shape)
# No issues found unless find otherwise
anyIssues = False
# Counters
dim = 0;
consecDims = 0;
# Loop round dimensions until no more changes
while consecDims < self.NDim:
# Size of current dimension
Ni = self.Nxyz[dim]
# Indices to either side of nodes
inds1 = np.abs(np.arange(Ni)-1)
inds2 = np.flip(Ni-1-inds1)
indShape = np.ones(self.NDim, dtype=int)
indShape[dim] = Ni
inds1 = np.reshape(inds1, indShape)
inds2 = np.reshape(inds2, indShape)
# get neighbours
neighbours1 = np.take_along_axis(self.mesh, inds1, axis=dim)
neighbours2 = np.take_along_axis(self.mesh, inds2, axis=dim)
# Find surrounding surfaces around single air nodes
invalid = np.logical_or(neighbours1==0, neighbours2==0)
invalid = np.logical_or(invalid, self.mesh!=0)
neighbours1[invalid] = 0
neighbours2[invalid] = 0
# Combine and average (if floats, otherwise not needed)
if self.mesh.dtype.kind == 'f':
neighbours1 += neighbours2
neighbours1 *= 0.5
# Any nodes found that need fixing?
foundNodes = np.any(neighbours1>0)
# No change occurred unless find otherwise
anyChange = False
if foundNodes:
# Houston, we have a problem
anyIssues = True
if fix:
self.mesh += neighbours1
# Changes have been made
anyChange = True
# Update consecutive dimensions with no change
if anyChange:
# Reset
consecDims = 0
else:
# Increase
consecDims += 1
# Next dimension to look at
dim = np.remainder(dim+1, self.NDim)
return anyIssues
def prepareMesh(self, betaMode = None):
# Update on debug
self.printToDebug('prepareMesh')
# Make update parameters for grid from numpy array
# WARNING: by no means fool proof and/or well tested!!!
# Admittance type
if betaMode is None:
betaMode = self.betaMode
# Grid size (this should already have happened)
self.Nxyz = list(self.mesh.shape)
# Copy of input as zeros and ones
nodes = (self.mesh>0).astype(int)
# Dimensions
dims = np.arange(self.NDim).astype(int)
Ni = np.array(self.Nxyz).astype(int)
# Empty lists
self.pgn = np.empty((0)).astype(int)
self.psn = np.empty((0)).astype(int)
self.pon = np.empty((0)).astype(int)
beta = np.empty((0))
# Loop round dimensions
for i in range(0,self.NDim):
# Differences in positive and negative direction along i-th dimension
diff1 = np.diff(nodes,n=1,append=1)
diff2 = np.flip(np.diff(np.flip(nodes, axis=-1),n=1,append=1), axis=-1)
# Flatten
diff1 = diff1.flatten()
diff2 = diff2.flatten()
# Surface node indices
self.psn1 = np.where(diff1==1)[0]
self.psn2 = np.where(diff2==1)[0]
# 'Opposite' node indices
self.pon1 = self.psn1-1
self.pon2 = self.psn2+1
# # 'Ghost' node indices
# pgn1 = np.where(diff1<0)[0]
# pgn2 = np.where(diff2<0)[0]
# 'Ghost' node indices
pgn1 = self.psn1+1
pgn2 = self.psn2-1
# Ghosts
# If surfaces were first or last and hence ghosts would be in a
# different dimension(/column etc.)
isFirstIndex = np.remainder(pgn1,Ni[-1])==0
isLastIndex = np.remainder(self.psn2,Ni[-1])==0
# Default to beta on border
if hasattr(self.betaBorder, "__len__"):
i1 = (dims[-1]*2)%len(self.betaBorder)
i2 = (dims[-1]*2+1)%len(self.betaBorder)
# Note switch in i1 and i2 as my 1s and 2s were defined the
# other way round when I first wrote this
betaBorder1 = self.betaBorder[i2]
betaBorder2 = self.betaBorder[i1]
else:
betaBorder1 = self.betaBorder
betaBorder2 = self.betaBorder
beta1 = np.ones(len(pgn1))*betaBorder1
beta2 = np.ones(len(pgn2))*betaBorder2
# And then if not on border...
if betaMode == 'constant':
beta1[isFirstIndex==False] = self.beta
beta2[isLastIndex==False] = self.beta
elif betaMode == 'varying':
# Admittance on ghost nodes
inds = self.indFixDims(pgn1[isFirstIndex==False], Ni, dims)
beta1[isFirstIndex==False] = 1-self.mesh.flat[inds]
inds = self.indFixDims(pgn2[isLastIndex==False], Ni, dims)
beta2[isLastIndex==False] = 1-self.mesh.flat[inds]
# Get rid of ghosts at border
pgn1 = pgn1[isFirstIndex==False]
pgn2 = pgn2[isLastIndex==False]
# Opposites
# If surfaces were first or last and hence opposites would be in a
# different dimension(/column etc.)
isFirstIndex = np.remainder(self.psn1,Ni[-1])==0
isLastIndex = np.remainder(self.pon2,Ni[-1])==0
# Check nodes are in same dimension and an 'air' node
ind_check = np.logical_or(isFirstIndex, nodes.flat[self.pon1]!=0)
if ind_check.any():
self.pon1 = self.pon1[ind_check==False]
self.psn1 = self.psn1[ind_check==False]
#pgn1 = pgn1[ind_check==False] # It's still a ghost node!
beta1 = beta1[ind_check==False]
ind_check = np.logical_or(isLastIndex, nodes.flat[self.pon2]!=0)
if ind_check.any():
#pgn2 = psn2[ind_check]
self.pon2 = self.pon2[ind_check==False]
self.psn2 = self.psn2[ind_check==False]
#pgn2 = pgn2[ind_check==False] # It's still a ghost node!
beta2 = beta2[ind_check==False]
# Concatenate lists
self.psn1 = np.append(self.psn1, self.psn2)
self.pon1 = np.append(self.pon1, self.pon2)
pgn1 = np.append(pgn1, pgn2)
beta1 = np.append(beta1, beta2)
# Convert to correct indices (to account for shifting dimensions at
# beginning)
self.psn1 = self.indFixDims(self.psn1, Ni, dims)
self.pon1 = self.indFixDims(self.pon1, Ni, dims)
pgn1 = self.indFixDims(pgn1, Ni, dims)
# Add to lists
self.psn = np.append(self.psn, self.psn1)
self.pon = np.append(self.pon, self.pon1)
self.pgn = np.append(self.pgn, pgn1)
beta = np.append(beta, beta1)
# shift dimensions
oldDims = dims
dims = np.roll(dims,1)
Ni = np.roll(Ni,1)
nodes = np.moveaxis(nodes,dims,oldDims)
# Sort order
indSort = np.argsort(self.psn)
self.psn = self.psn[indSort]
self.pon = self.pon[indSort]
beta = beta[indSort]
# Convert to admittance if beta values are NIAC
if self.betaType == 'absorption':
beta = self.abs2Admit(beta)
# Only keep unique ghost nodes
self.pgn = np.unique(self.pgn)
# Find surfaces occuring 1-3 times
psn_unique, psn_uni_n, psn_uni_count = np.unique(self.psn,
return_index=True,
return_counts=True)
self.psn1 = psn_unique[psn_uni_count==1]
self.psn2 = psn_unique[psn_uni_count==2]
self.psn3 = psn_unique[psn_uni_count==3]
# Find opposites and admittances - plain surfaces
#Ns1 = psn1.size
n = psn_uni_n[psn_uni_count==1]
self.pon1 = self.pon[n]
b1 = beta[n]
# Find opposites and admittances - edges
Ns2 = self.psn2.size
self.pon2 = np.zeros((Ns2,2), dtype=int)
b2 = np.zeros((Ns2,2))
for i in range(Ns2):
n = np.where(self.psn==self.psn2[i])
self.pon2[i,:] = self.pon[n]
b2[i,:] = beta[n]
# Find opposites and admittances - corners
Ns3 = self.psn3.size
self.pon3 = np.zeros((Ns3,3), dtype=int)
b3 = np.zeros((Ns3,3))
for i in range(Ns3):
n = np.where(self.psn==self.psn3[i])
self.pon3[i,:] = self.pon[n]
b3[i,:] = beta[n]
# Concatenated surface pressures
self.psn = np.concatenate((self.psn1,self.psn2,self.psn3))
# Beta+1 and beta-1
self.bp1_1 = self.lam*b1+1
self.bp1_2 = self.lam*b2.sum(axis=-1)+1
self.bp1_3 = self.lam*b3.sum(axis=-1)+1
self.bm1 = np.concatenate((self.bp1_1,self.bp1_2,self.bp1_3))-2
# Use inverse of beta+1s (avoids division)
self.bp1_1 = 1/self.bp1_1
self.bp1_2 = 1/self.bp1_2
self.bp1_3 = 1/self.bp1_3
# Another speed up alteration
self.bm1 *= -1
# Source on surface amplitude factor
self.srcSurfAmp = [1]*self.srcN
for i in range(self.srcN):
# Flat index to source
self.srcFlatInd[i] = np.ravel_multi_index(self.srcInd[i], self.Nxyz)
# Find if on non-air node
self.srcNodeType[i] = nodes.flat[self.srcFlatInd[i]]
if self.srcNodeType[i]:
# If src ind is on mesh (non-air) node then set to zero
self.srcStrength[i] = 0
else:
# Otherwise find if on surface type
n1 = self.srcFlatInd[i]==self.psn1
n2 = self.srcFlatInd[i]==self.psn2
n3 = self.srcFlatInd[i]==self.psn3
if np.any(n1):
n1 = np.where(n1)[0][0]
self.srcSurfAmp[i] = 2/(1+b1[n1])
elif np.any(n2):
n2 = np.where(n2)[0][0]
self.srcSurfAmp[i] = np.prod(2/(1+b2[n2,:]))
elif np.any(n3):
n3 = np.where(n3)[0][0]
self.srcSurfAmp[i] = np.prod(2/(1+b3[n3,:]))
# Source strength is amplitude and surface factor combined
self.srcStrength[i] = self.srcAmp[i] * self.srcSurfAmp[i]
# Receivers
for i in range(self.recN):
# Flat index
self.recFlatInd[i] = np.ravel_multi_index(self.recInd[i], self.Nxyz)
# Find node type
self.recNodeType[i] = nodes.flat[self.recFlatInd[i]]
# 'Strength'
self.recStrength[i] = self.recAmp[i]
def abs2Admit(self, alpha):
# Convert normal incidence absorption coefficient data to normalised admittance
R = np.sqrt(1-alpha)
admit = (1-R)/(1+R)
return admit
def srcOnMesh(self):
# Check valid source positions
# Update on debug
self.printToDebug('srcOnMesh')
onMesh = False
for i, nodeType in enumerate(self.srcNodeType):
if self.srcAmp[i]!=0 and nodeType != 0:
onMesh = True
return onMesh
def recOnMesh(self):
# Check valid receiver positions
# Update on debug
self.printToDebug('recOnMesh')
onMesh = False
for i, nodeType in enumerate(self.recNodeType):
if self.recAmp[i]!=0 and nodeType != 0:
onMesh = True
return onMesh
def srcRecOnMesh(self):
# Check valid source and receiver positions
onMesh = self.srcOnMesh() or self.recOnMesh()
return onMesh
def indFixDims(self, inds, Ni, dims):
# Shift dimensions of flat indices
# Number of dimensions
NDims = dims.size
# Number of indices
NInd = inds.size
if NInd > 0:
# Unflatten indices (as numpy array)
inds = np.unravel_index(inds, Ni)
inds = np.array(inds)
# Shift dimensions
invDims = [np.where(i==dims)[0][0] for i in range(NDims)]
Ni = Ni[invDims]
inds = inds[invDims,:]
# Convert back to flat indices
inds = np.ravel_multi_index(inds, Ni)
return inds
def newEmptyMesh(self, Nxyz=NXYZ):
# define new empty mesh size
# Update on debug
self.printToDebug('newEmptyMesh')
# Set the new size
self.Nxyz = Nxyz
# Set new inputs
self.setInputs()
# Define using makeReset
self.meshReset()
def meshReset(self, doPrepareMesh=False):
# Reset to blank mesh
# Update on debug
self.printToDebug('meshReset')
#self.mesh = np.zeros((self.Nxyz), dtype=int)
self.mesh = np.zeros((self.Nxyz))
if doPrepareMesh:
self.prepareMesh()
def image2Mesh(self, threshold=None, addToPlot=True,
xMesh=None, yMesh=None, xOffset=0, yOffset=0):
# Make binary (black and white) or greyscale version of mesh from image
# 2D mesh is assumed
# Update on debug
self.printToDebug('image2Mesh')
if threshold != None:
self.imageThreshold = threshold
# Get mesh from image
if self.image is None:
# Size of requested mesh
if xMesh is None: xMesh=self.Nxyz[0]
if yMesh is None: yMesh=self.Nxyz[1]
# Make empty mesh if no image
self.mesh = np.zeros((xMesh, yMesh))
else:
# Otherwise...
# Size of image
imX, imY = self.image.shape
# Size of requested mesh
if xMesh is None: xMesh=imX
if yMesh is None: yMesh=imY
# Opposite of image (white = 0, black = 255)
self.mesh = 255-self.image
# Make sure floats
self.mesh = self.mesh.astype(float)
# Set to zero if below threshold
self.mesh[self.mesh <= 255*self.imageThreshold] = 0
# # Scale if doing 'varying' or otherwise set rest to one
# if self.betaMode == 'varying':
# self.mesh = self.mesh * 1/255
# else:
# self.mesh[self.mesh > 255*self.imageThreshold] = 1
# Now always do scaling so image doesn't get made binary
self.mesh = self.mesh * 1/255
# Pad/trim if not same size
if xMesh!=imX or yMesh!=imY:
# Size of new mesh
if xMesh is None: xMesh = imX
if yMesh is None: yMesh = imY
# Start and end indices for new mesh
x1 = max(xOffset,0)
y1 = max(yOffset,0)
x2 = min(imX+xOffset,xMesh)
y2 = min(imY+yOffset,yMesh)
# Start and end indices for original mesh
x10 = -min(xOffset,0)
y10 = -min(yOffset,0)
x20 = min(xMesh-xOffset,imX)
y20 = min(yMesh-yOffset,imY)
# Make new blank mesh and add pad/trimmed orig
meshOrig = self.mesh
self.mesh = np.zeros((xMesh,yMesh))
self.mesh[x1:x2,y1:y2] = meshOrig[x10:x20,y10:y20]
# Set sim to match new mesh size
self.Nxyz = list(self.mesh.shape)
# Add to plot
if addToPlot:
self.updatePlotMask()
def repDecMesh(self, rep=None, dec=None):
# Repeat and/or decimate mesh
if rep != None:
self.mesh = self.repeatData(self.mesh, rep)
if dec != None:
self.mesh = self.decimateData(self.mesh, dec)
self.Nxyz = list(self.mesh.shape)
def updateWithImage(self):
# Make new mesh array but don't plot
self.image2Mesh(addToPlot=False)
# Reset inputs
self.setInputs()
# Reset pressures etc..
self.runReset()
# Add mesh array to plot
self.updatePlotMask()
def loadImage(self, file, doReset=True, sizeLimits = None):
# Update on debug
self.printToDebug('loadImage')
# Load image from file (as normalised greyscale)
self.image = Image.open(file).convert('L')
# Convert to numpy array and flip to account for direction in
# 'vertical' data
self.image = np.asarray(self.image)
self.image = np.flip(self.image, axis=0)
# Clear mesh
self.mesh = None
if not sizeLimits is None:
# If size limits then check if needs trimming/padding