-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathSimulation.jl
More file actions
1334 lines (1191 loc) · 76.4 KB
/
Simulation.jl
File metadata and controls
1334 lines (1191 loc) · 76.4 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
abstract type AbstractSimulation{T <: SSDFloat} end
"""
mutable struct Simulation{T <: SSDFloat, CS <: AbstractCoordinateSystem} <: AbstractSimulation{T}
Collection of all parts of a simulation of a [`SolidStateDetector`](@ref).
## Parametric types
* `T`: Precision type.
* `CS`: Coordinate system (`Cartesian` or `Cylindrical`).
## Fields
* `config_dict::AbstractDict`: Dictionary (parsed configuration file) which initialized the simulation.
* `input_units::NamedTuple`: Units with which the `config_dict` should be parsed.
* `medium::NamedTuple`: Medium of the world.
* `detector::Union{SolidStateDetector{T}, Missing}`: The [`SolidStateDetector`](@ref) of the simulation.
* `world::World{T, 3, CS}`: The [`World`](@ref) of the simulation.
* `q_eff_imp::Union{EffectiveChargeDensity{T}, Missing}`: Effective charge resulting from the impurites in the [`Semiconductor`](@ref) of the `detector`.
* `imp_scale::Union{ImpurityScale{T}, Missing}`: Scale (alpha channel) of the impurity density (for depletion handling).
* `q_eff_fix::Union{EffectiveChargeDensity{T}, Missing}`: Fixed charge resulting from fixed space charges in [`Passive`](@ref) of the `detector`.
* `ϵ_r::Union{DielectricDistribution{T}, Missing}`: The [`DielectricDistribution`](@ref) of the simulation.
* `point_types::Union{PointTypes{T}, Missing}`: The [`PointTypes`](@ref) of the simulation.
* `electric_potential::Union{ElectricPotential{T}, Missing}`: The [`ElectricPotential`](@ref) of the simulation.
* `weighting_potentials::Vector{Any}`: The [`WeightingPotential`](@ref) for each [`Contact`](@ref) of the `detector` in the simulation.
* `electric_field::Union{ElectricField{T}, Missing}`: The [`ElectricField`](@ref) of the simulation.
"""
mutable struct Simulation{T <: SSDFloat, CS <: AbstractCoordinateSystem} <: AbstractSimulation{T}
config_dict::AbstractDict
input_units::NamedTuple
medium::NamedTuple # this should become a struct at some point
detector::Union{SolidStateDetector{T}, Missing}
world::World{T, 3, CS}
q_eff_imp::Union{EffectiveChargeDensity{T}, Missing} # Effective charge coming from the impurites of the semiconductors
imp_scale::Union{ImpurityScale{T}, Missing}
q_eff_fix::Union{EffectiveChargeDensity{T}, Missing} # Fixed charge coming from fixed space charges, e.g. charged up surface layers
ϵ_r::Union{DielectricDistribution{T}, Missing}
point_types::Union{PointTypes{T}, Missing}
electric_potential::Union{ElectricPotential{T}, Missing}
weighting_potentials::Vector{Any}
electric_field::Union{ElectricField{T}, Missing}
end
function Simulation{T,CS}() where {T <: SSDFloat, CS <: AbstractCoordinateSystem}
Simulation{T, CS}(
Dict(),
default_unit_tuple(),
material_properties[materials["vacuum"]],
missing,
World(CS,(T(0),T(1),T(0),T(1),T(0),T(1))),
missing,
missing,
missing,
missing,
missing,
missing,
[missing],
missing
)
end
get_precision_type(::Simulation{T}) where {T} = T
get_coordinate_system(::Simulation{T, CS}) where {T, CS} = CS
function NamedTuple(sim::Simulation{T}) where {T <: SSDFloat}
wpots_strings = ["WeightingPotential_$(contact.id)" for contact in sim.detector.contacts]
nt = (
detector_json_string = _namedtuple(sim.config_dict),
electric_potential = _namedtuple(sim.electric_potential),
q_eff_imp = _namedtuple(sim.q_eff_imp),
imp_scale = _namedtuple(sim.imp_scale),
q_eff_fix = _namedtuple(sim.q_eff_fix),
ϵ_r = _namedtuple(sim.ϵ_r),
point_types = _namedtuple(sim.point_types),
electric_field = _namedtuple(sim.electric_field),
weighting_potentials = NamedTuple{Tuple(Symbol.(wpots_strings))}(_namedtuple.(sim.weighting_potentials))
)
return nt
end
Base.convert(T::Type{NamedTuple}, x::Simulation) = T(x)
function Simulation(nt::NamedTuple)
missing_tuple = _namedtuple(missing)
if nt.electric_potential !== missing_tuple
epot = ElectricPotential(nt.electric_potential)
T = eltype(epot.data)
sim = Simulation{T}( _dict(nt.detector_json_string) )
sim.electric_potential = epot
sim.q_eff_imp = EffectiveChargeDensity(nt.q_eff_imp)
sim.q_eff_fix = EffectiveChargeDensity(nt.q_eff_fix)
sim.ϵ_r = DielectricDistribution(nt.ϵ_r)
sim.point_types = PointTypes(nt.point_types)
sim.imp_scale = if !haskey(nt, :imp_scale)
@warn """Stored simulation does not have a field for `imp_scale` (impurity scale) as this was
first introduced in SolidStateDetectors.jl v0.8 for improved depletion handling.
It is advised to recalculate the simulation with the latest version.
The field `imp_scale` is determined from `point_types`:
* undepleted point -> imp_scale = 0;
* depleted point -> imp_scale = 1;
"""
ImpurityScale(T.(.!is_undepleted_point_type.(sim.point_types.data)), sim.point_types.grid)
else
ImpurityScale(nt.imp_scale)
end
sim.electric_field = haskey(nt, :electric_field) && nt.electric_field !== missing_tuple ? ElectricField(nt.electric_field) : missing
else
T = Float32
sim = Simulation{T}( _dict(nt.detector_json_string) )
end
sim.weighting_potentials = if haskey(nt, :weighting_potentials)
[let wp = Symbol("WeightingPotential_$(contact.id)")
haskey(nt.weighting_potentials, wp) && getfield(nt.weighting_potentials, wp) !== missing_tuple ? WeightingPotential(getfield(nt.weighting_potentials, wp)) : missing
end for contact in sim.detector.contacts]
else
[missing for contact in sim.detector.contacts]
end
return sim
end
Base.convert(T::Type{Simulation}, x::NamedTuple) = T(x)
function Base.:(==)(sim1::P, sim2::P) where {P <: Union{Simulation, SolidStateDetector, AbstractObject, AbstractChargeDriftModel, AbstractTemperatureModel}}
return typeof(sim1) == typeof(sim2) && all(broadcast(field -> isequal(getfield(sim1, field), getfield(sim2, field)), fieldnames(P)))
end
function println(io::IO, sim::Simulation{T}) where {T <: SSDFloat}
println(typeof(sim), " - Coordinate system: ", get_coordinate_system(sim))
println(" Environment Material: $(sim.medium.name)")
println(" Detector: $(sim.detector.name)")
println(" Electric potential: ", !ismissing(sim.electric_potential) ? size(sim.electric_potential) : missing)
println(" Charge density: ", !ismissing(sim.q_eff_imp) ? size(sim.q_eff_imp) : missing)
println(" Impurity scale: ", !ismissing(sim.imp_scale) ? size(sim.imp_scale) : missing)
println(" Fix Charge density: ", !ismissing(sim.q_eff_fix) ? size(sim.q_eff_fix) : missing)
println(" Dielectric distribution: ", !ismissing(sim.ϵ_r) ? size(sim.ϵ_r) : missing)
println(" Point types: ", !ismissing(sim.point_types) ? size(sim.point_types) : missing)
println(" Electric field: ", !ismissing(sim.electric_field) ? size(sim.electric_field) : missing)
println(" Weighting potentials: ")
for contact in sim.detector.contacts
print(" Contact $(contact.id): ")
println(!ismissing(sim.weighting_potentials[contact.id]) ? size(sim.weighting_potentials[contact.id]) : missing)
end
end
function print(io::IO, sim::Simulation{T}) where {T <: SSDFloat}
print(io, "Simulation{$T} - ", "$(sim.detector.name)")
end
function show(io::IO, sim::Simulation{T}) where {T <: SSDFloat} println(io, sim) end
function show(io::IO, ::MIME"text/plain", sim::Simulation{T}) where {T <: SSDFloat}
show(io, sim)
end
function Simulation{T}(dict::AbstractDict)::Simulation{T} where {T <: SSDFloat}
CS::CoordinateSystemType = Cartesian
if haskey(dict, "grid")
if isa(dict["grid"], AbstractDict)
CS = if dict["grid"]["coordinates"] == "cartesian"
Cartesian
elseif dict["grid"]["coordinates"] == "cylindrical"
Cylindrical
else
@assert "`grid` in config file needs `coordinates` that are either `cartesian` or `cylindrical`"
end
elseif isa(dict["grid"], String)
CS = if dict["grid"] == "cartesian"
Cartesian
elseif dict["grid"] == "cylindrical"
Cylindrical
else
@assert "`grid` type in config file needs to be either `cartesian` or `cylindrical`"
end
end
end
sim::Simulation{T,CS} = Simulation{T,CS}()
sim.config_dict = dict
sim.input_units = construct_units(dict)
sim.medium = material_properties[materials[haskey(dict, "medium") ? dict["medium"] : "vacuum"]]
sim.detector = SolidStateDetector{T}(dict, sim.input_units)
sim.world = if haskey(dict, "grid") && isa(dict["grid"], AbstractDict) && haskey(dict["grid"], "axes")
World(T, dict["grid"], sim.input_units)
else let det = sim.detector
world_limits = get_world_limits_from_objects(CS, det)
World(CS, world_limits)
end
end
sim.weighting_potentials = Missing[ missing for i in 1:length(sim.detector.contacts)]
return sim
end
function Simulation{T}(config_file::AbstractString)::Simulation{T} where{T <: SSDFloat}
dict = parse_config_file(config_file)
return Simulation{T}( dict )
end
function Simulation(config_file::AbstractString)::Simulation{Float32}
return Simulation{Float32}( config_file )
end
# Functions
"""
Grid(sim::Simulation{T, Cartesian}; kwargs...)
Grid(sim::Simulation{T, Cylindrical}; kwargs...)
Initializes a [`Grid`](@ref) based on the objects defined in a [`Simulation`](@ref).
The important points of all objects are sampled and added to the ticks of the grid.
The grid initialization can be tuned using a set of keyword arguments listed below.
## Arguments
* `sim::Simulation{T, S}`: [`Simulation`](@ref) for which the grid will be defined.
## Keywords
* `max_tick_distance = missing`: Maximum distance between neighbouring ticks of the grid.
Additional grid ticks will be added if two neighbouring ticks are too far apart.
`max_tick_distance` can either be a `Quantity`, e.g. `1u"mm"`, or a Tuple of `Quantity`,
e.g. `(1u"mm", 15u"°", 3u"mm")`,
to set it for each axis of the `Grid` separately. Note that a `CartesianGrid3D` requires a
`Tuple{LengthQuantity, LengthQuantity, LengthQuantity}` while a `CylindricalGrid` requires a
`Tuple{LengthQuantity, AngleQuantity, LengthQuantity}`.
If `max_tick_distance` is `missing`, one fourth of the axis length is used.
* `max_distance_ratio::Real = 5`: If the ratio between a tick and its left and right neighbour
is greater than `max_distance_ratio`, additional ticks are added between the ticks that are
further apart. This prevents the ticks from being too unevenly spaced.
* `add_ticks_between_important_ticks::Bool = true`: If set to `true`, additional points
will be added in between the important points obtained from sampling the objects of the
simulation. If some objects are too close together, this will ensure a noticeable gap
between them in the calculation of potentials and fields.
* `for_weighting_potential::Bool = false`: Grid will be optimized for the calculation of
an [`ElectricPotential`](@ref) if set to `true`, and of a [`WeightingPotential`](@ref)
if set to `false`.
"""
function Grid(sim::Simulation{T, Cylindrical};
for_weighting_potential::Bool = false,
max_tick_distance::Union{Missing, LengthQuantity, Tuple{LengthQuantity, AngleQuantity, LengthQuantity}} = missing,
max_distance_ratio::Real = 5,
add_ticks_between_important_ticks::Bool = true)::CylindricalGrid{T} where {T}
det = sim.detector
world = sim.world
world_Δs = width.(world.intervals)
world_Δr, world_Δφ, world_Δz = world_Δs
samples::Vector{CylindricalPoint{T}} = sample(det, Cylindrical)
important_r_ticks::Vector{T} = map(p -> p.r, samples)
important_φ_ticks::Vector{T} = map(p -> p.φ, samples)
important_z_ticks::Vector{T} = map(p -> p.z, samples)
second_order_imp_ticks = if for_weighting_potential
strong_electric_field_ticks = !ismissing(sim.electric_potential) ? get_ticks_at_positions_of_large_gradient(sim.electric_potential) : (T[], T[], T[])
surface_of_depleted_volume_ticks = !ismissing(sim.imp_scale) ? get_ticks_at_positions_of_edge_of_depleted_volumes(sim.imp_scale) : (T[], T[], T[])
vcat.(strong_electric_field_ticks, surface_of_depleted_volume_ticks)
else
(T[], T[], T[])
end
world_r_mid = (world.intervals[1].right + world.intervals[1].left)/2
if for_weighting_potential && world_Δφ > 0
world_φ_int = SSDInterval{T, :closed, :open, :periodic, :periodic}(0, 2π)
world_Δφ = width(world_φ_int)
else
world_φ_int = world.intervals[2]
end
max_distance_z = T(world_Δz / 4)
max_distance_φ = T(world_Δφ / 4)
max_distance_r = T(world_Δr / 4)
if !ismissing(max_tick_distance)
if max_tick_distance isa LengthQuantity
max_distance_z = max_distance_r = T(to_internal_units(max_tick_distance))
max_distance_φ = max_distance_z / world_r_mid
else #if max_tick_distance isa Tuple{LengthQuantity, AngleQuantity, LengthQuantity}
max_distance_r = T(to_internal_units(max_tick_distance[1]))
max_distance_φ = T(to_internal_units(max_tick_distance[2]))
max_distance_z = T(to_internal_units(max_tick_distance[3]))
end
end
append!(important_r_ticks, endpoints(world.intervals[1])...)
important_r_ticks = unique!(sort!(important_r_ticks))
if add_ticks_between_important_ticks
important_r_ticks = sort!(vcat(important_r_ticks, StatsBase.midpoints(important_r_ticks)))
end
iL = searchsortedfirst(important_r_ticks, world.intervals[1].left)
iR = searchsortedfirst(important_r_ticks, world.intervals[1].right)
important_r_ticks = unique(map(t -> isapprox(t, 0, atol = 1e-12) ? zero(T) : t, important_r_ticks[iL:iR]))
important_r_ticks = merge_close_ticks(important_r_ticks)
imp2order_r_ticks = merge_close_ticks(second_order_imp_ticks[1], min_diff = world_Δs[1] / 20)
important_r_ticks = merge_second_order_important_ticks(important_r_ticks, imp2order_r_ticks, min_diff = world_Δs[1] / 20)
important_r_ticks = initialize_axis_ticks(important_r_ticks; max_ratio = T(max_distance_ratio))
important_r_ticks = fill_up_ticks(important_r_ticks, max_distance_r)
append!(important_z_ticks, endpoints(world.intervals[3])...)
important_z_ticks = unique!(sort!(important_z_ticks))
if add_ticks_between_important_ticks
important_z_ticks = sort!(vcat(important_z_ticks, StatsBase.midpoints(important_z_ticks)))
end
iL = searchsortedfirst(important_z_ticks, world.intervals[3].left)
iR = searchsortedfirst(important_z_ticks, world.intervals[3].right)
important_z_ticks = unique(map(t -> isapprox(t, 0, atol = 1e-12) ? zero(T) : t, important_z_ticks[iL:iR]))
important_z_ticks = merge_close_ticks(important_z_ticks)
imp2order_z_ticks = merge_close_ticks(second_order_imp_ticks[3], min_diff = world_Δs[3] / 20)
important_z_ticks = merge_second_order_important_ticks(important_z_ticks, imp2order_z_ticks, min_diff = world_Δs[3] / 20)
important_z_ticks = initialize_axis_ticks(important_z_ticks; max_ratio = T(max_distance_ratio))
important_z_ticks = fill_up_ticks(important_z_ticks, max_distance_z)
append!(important_φ_ticks, endpoints(world_φ_int)...)
important_φ_ticks = unique!(sort!(important_φ_ticks))
if add_ticks_between_important_ticks
important_φ_ticks = sort!(vcat(important_φ_ticks, StatsBase.midpoints(important_φ_ticks)))
end
iL = searchsortedfirst(important_φ_ticks, world_φ_int.left)
iR = searchsortedfirst(important_φ_ticks, world_φ_int.right)
important_φ_ticks = unique(map(t -> isapprox(t, 0, atol = 1e-3) ? zero(T) : t, important_φ_ticks[iL:iR]))
important_φ_ticks = merge_close_ticks(important_φ_ticks, min_diff = T(1e-3))
imp2order_φ_ticks = merge_close_ticks(second_order_imp_ticks[2], min_diff = world_Δs[2] / 20)
important_φ_ticks = merge_second_order_important_ticks(important_φ_ticks, imp2order_φ_ticks, min_diff = world_Δs[2] / 20)
important_φ_ticks = initialize_axis_ticks(important_φ_ticks; max_ratio = T(max_distance_ratio))
important_φ_ticks = fill_up_ticks(important_φ_ticks, max_distance_φ)
# r
L, R, BL, BR = get_boundary_types(world.intervals[1])
int_r = Interval{L, R, T}(endpoints(world.intervals[1])...)
ax_r = even_tick_axis(DiscreteAxis{T, BL, BR}(int_r, important_r_ticks))
# φ
L, R, BL, BR = get_boundary_types(world_φ_int)
int_φ = Interval{L, R, T}(endpoints(world_φ_int)...)
ax_φ = if int_φ.left == int_φ.right
DiscreteAxis{T, BL, BR}(int_φ, T[int_φ.left])
else
DiscreteAxis{T, BL, BR}(int_φ, important_φ_ticks)
end
if length(ax_φ) > 1
φticks = if R == :open
important_φ_ticks[1:end-1]
else
important_φ_ticks
end
ax_φ = typeof(ax_φ)(int_φ, φticks)
end
int_φ = ax_φ.interval
if isodd(length(ax_φ)) && length(ax_φ) > 1 # must be even
imax = findmax(diff(φticks))[2]
push!(φticks, (φticks[imax] + φticks[imax+1]) / 2)
sort!(φticks)
ax_φ = typeof(ax_φ)(int_φ, φticks) # must be even
end
if length(ax_φ) > 1
@assert iseven(length(ax_φ)) "CylindricalGrid must have even number of points in φ."
end
#z
L, R, BL, BR = get_boundary_types(world.intervals[3])
int_z = Interval{L, R, T}(endpoints(world.intervals[3])...)
ax_z = even_tick_axis(DiscreteAxis{T, BL, BR}(int_z, important_z_ticks))
return CylindricalGrid{T}( (ax_r, ax_φ, ax_z) )
end
function Grid( sim::Simulation{T, Cartesian};
max_tick_distance::Union{Missing, LengthQuantity, Tuple{LengthQuantity, LengthQuantity, LengthQuantity}} = missing,
max_distance_ratio::Real = 5,
add_ticks_between_important_ticks::Bool = true,
for_weighting_potential::Bool = false)::CartesianGrid3D{T} where {T}
det = sim.detector
world = sim.world
world_Δs = width.(world.intervals)
world_Δx, world_Δy, world_Δz = world_Δs
samples::Vector{CartesianPoint{T}} = sample(det, Cartesian)
important_x_ticks::Vector{T} = map(p -> p.x, samples)
important_y_ticks::Vector{T} = map(p -> p.y, samples)
important_z_ticks::Vector{T} = map(p -> p.z, samples)
second_order_imp_ticks = if for_weighting_potential
strong_electric_field_ticks = !ismissing(sim.electric_potential) ? get_ticks_at_positions_of_large_gradient(sim.electric_potential) : (T[], T[], T[])
surface_of_depleted_volume_ticks = !ismissing(sim.imp_scale) ? get_ticks_at_positions_of_edge_of_depleted_volumes(sim.imp_scale) : (T[], T[], T[])
vcat.(strong_electric_field_ticks, surface_of_depleted_volume_ticks)
else
(T[], T[], T[])
end
max_distance_x = T(world_Δx / 4)
max_distance_y = T(world_Δy / 4)
max_distance_z = T(world_Δz / 4)
min_max_distance = min(max_distance_x, max_distance_y, max_distance_z)
max_distance_x = max_distance_y = max_distance_z = min_max_distance
if !ismissing(max_tick_distance)
if max_tick_distance isa LengthQuantity
max_distance_x = max_distance_y = max_distance_z =
T(to_internal_units(max_tick_distance))
else
max_distance_x = T(to_internal_units(max_tick_distance[1]))
max_distance_y = T(to_internal_units(max_tick_distance[2]))
max_distance_z = T(to_internal_units(max_tick_distance[3]))
end
end
append!(important_x_ticks, endpoints(world.intervals[1]))
important_x_ticks = unique!(sort!(important_x_ticks))
if add_ticks_between_important_ticks
important_x_ticks = sort!(vcat(important_x_ticks, StatsBase.midpoints(important_x_ticks)))
end
iL = searchsortedfirst(important_x_ticks, world.intervals[1].left)
iR = searchsortedfirst(important_x_ticks, world.intervals[1].right)
important_x_ticks = unique(map(t -> isapprox(t, 0, atol = 1e-12) ? zero(T) : t, important_x_ticks[iL:iR]))
important_x_ticks = merge_close_ticks(important_x_ticks)
imp2order_x_ticks = merge_close_ticks(second_order_imp_ticks[1], min_diff = world_Δs[1] / 20)
important_x_ticks = merge_second_order_important_ticks(important_x_ticks, imp2order_x_ticks, min_diff = world_Δs[1] / 20)
important_x_ticks = initialize_axis_ticks(important_x_ticks; max_ratio = T(max_distance_ratio))
important_x_ticks = fill_up_ticks(important_x_ticks, max_distance_x)
append!(important_y_ticks, endpoints(world.intervals[2]))
important_y_ticks = unique!(sort!(important_y_ticks))
if add_ticks_between_important_ticks
important_y_ticks = sort!(vcat(important_y_ticks, StatsBase.midpoints(important_y_ticks)))
end
iL = searchsortedfirst(important_y_ticks, world.intervals[2].left)
iR = searchsortedfirst(important_y_ticks, world.intervals[2].right)
important_y_ticks = unique(map(t -> isapprox(t, 0, atol = 1e-12) ? zero(T) : t, important_y_ticks[iL:iR]))
important_y_ticks = merge_close_ticks(important_y_ticks)
imp2order_y_ticks = merge_close_ticks(second_order_imp_ticks[2], min_diff = world_Δs[2] / 20)
important_y_ticks = merge_second_order_important_ticks(important_y_ticks, imp2order_y_ticks, min_diff = world_Δs[2] / 20)
important_y_ticks = initialize_axis_ticks(important_y_ticks; max_ratio = T(max_distance_ratio))
important_y_ticks = fill_up_ticks(important_y_ticks, max_distance_y)
append!(important_z_ticks, endpoints(world.intervals[3]))
important_z_ticks = unique!(sort!(important_z_ticks))
if add_ticks_between_important_ticks
important_z_ticks = sort!(vcat(important_z_ticks, StatsBase.midpoints(important_z_ticks)))
end
iL = searchsortedfirst(important_z_ticks, world.intervals[3].left)
iR = searchsortedfirst(important_z_ticks, world.intervals[3].right)
important_z_ticks = unique(map(t -> isapprox(t, 0, atol = 1e-12) ? zero(T) : t, important_z_ticks[iL:iR]))
important_z_ticks = merge_close_ticks(important_z_ticks)
imp2order_z_ticks = merge_close_ticks(second_order_imp_ticks[3], min_diff = world_Δs[3] / 20)
important_z_ticks = merge_second_order_important_ticks(important_z_ticks, imp2order_z_ticks, min_diff = world_Δs[3] / 20)
important_z_ticks = initialize_axis_ticks(important_z_ticks; max_ratio = T(max_distance_ratio))
important_z_ticks = fill_up_ticks(important_z_ticks, max_distance_z)
# x
L, R, BL, BR = get_boundary_types(world.intervals[1])
int_x = Interval{L, R, T}(endpoints(world.intervals[1])...)
ax_x = even_tick_axis(DiscreteAxis{T, BL, BR}(int_x, important_x_ticks))
# y
L, R, BL, BR = get_boundary_types(world.intervals[2])
int_y = Interval{L, R, T}(endpoints(world.intervals[2])...)
ax_y = even_tick_axis(DiscreteAxis{T, BL, BR}(int_y, important_y_ticks))
# z
L, R, BL, BR = get_boundary_types(world.intervals[3])
int_z = Interval{L, R, T}(endpoints(world.intervals[3])...)
ax_z = even_tick_axis(DiscreteAxis{T, BL, BR}(int_z, important_z_ticks))
return CartesianGrid3D{T}( (ax_x, ax_y, ax_z) )
end
function _guess_optimal_number_of_threads_for_SOR(gs::NTuple{3, Integer}, max_nthreads::Integer, S::Union{Type{Cylindrical}, Type{Cartesian}})::Int
max_nthreads = min(Base.Threads.nthreads(), max_nthreads)
n = S == Cylindrical ? gs[2] * gs[3] : gs[1] * gs[2] # Number of grid points to be updated in each iteration of the outer loop
return min(nextpow(2, max(cld(n+1, 25), 4)), max_nthreads)
end
"""
apply_initial_state!(sim::Simulation{T}, ::Type{ElectricPotential}, grid::Grid{T} = Grid(sim);
not_only_paint_contacts::Bool = true, paint_contacts::Bool = true)::Nothing where {T <: SSDFloat}
Applies the initial state for the calculation of the [`ElectricPotential`](@ref).
It overwrites `sim.electric_potential`, `sim.q_eff_imp`, `sim.q_eff_fix`, `sim.ϵ` and `sim.point_types`
with the material properties and fixed potentials defined in `sim.detector`.
## Arguments
* `sim::Simulation{T}`: [`Simulation`](@ref) for which the initial state should be applied.
* `grid::Grid{T}`: [`Grid`](@ref) to apply the initial state on. If no `grid` is given,
a default `Grid` is determined from `sim`.
## Keywords
* `not_only_paint_contacts::Bool = true`: Whether to only use the painting algorithm of the surfaces of [`Contact`](@ref)
without checking if points are actually inside them.
Setting it to `false` should improve the performance but the points inside of [`Contact`](@ref) are not fixed anymore.
* `paint_contacts::Bool = true`: Enable or disable the painting of the surfaces of the [`Contact`](@ref) onto the `grid`.
## Examples
```julia
apply_initial_state!(sim, ElectricPotential, paint_contacts = false)
```
"""
function apply_initial_state!(sim::Simulation{T, CS}, ::Type{ElectricPotential}, grid::Grid{T} = Grid(sim);
not_only_paint_contacts::Bool = true, paint_contacts::Bool = true)::Nothing where {T <: SSDFloat, CS}
pcs = PotentialCalculationSetup(
sim.detector, grid, sim.medium;
use_nthreads = _guess_optimal_number_of_threads_for_SOR(size(grid), Base.Threads.nthreads(), CS),
not_only_paint_contacts, paint_contacts
);
sim.q_eff_imp = EffectiveChargeDensity(EffectiveChargeDensityArray(pcs), grid)
sim.imp_scale = ImpurityScale(ImpurityScaleArray(pcs), grid)
sim.q_eff_fix = EffectiveChargeDensity(FixedEffectiveChargeDensityArray(pcs), grid)
sim.ϵ_r = DielectricDistribution(DielectricDistributionArray(pcs), get_extended_midpoints_grid(grid))
sim.point_types = PointTypes(PointTypeArray(pcs), grid)
sim.electric_potential = ElectricPotential(ElectricPotentialArray(pcs), grid)
nothing
end
"""
apply_initial_state!(sim::Simulation{T}, ::Type{WeightingPotential}, contact_id::Int, grid::Grid{T} = Grid(sim))::Nothing
Applies the initial state for the calculation of the [`WeightingPotential`](@ref) for the [`Contact`}(@ref) with the id `contact_id`.
It overwrites `sim.weighting_potentials[contact_id]` with the fixed values on the [`Contact`}(@ref).
## Arguments
* `sim::Simulation{T}`: [`Simulation`](@ref) for which the initial state should be applied.
* `contact_id::Int`: The `id` of the [`Contact`](@ref) for which the [`WeightingPotential`](@ref) is to be calculated.
* `grid::Grid{T}`: [`Grid`](@ref) to apply the initial state on. If no `grid` is given,
a default `Grid` is determined from `sim`.
## Keywords
* `not_only_paint_contacts::Bool = true`: Whether to only use the painting algorithm of the surfaces of [`Contact`](@ref)
without checking if points are actually inside them.
Setting it to `false` should improve the performance but the points inside of [`Contact`](@ref) are not fixed anymore.
* `paint_contacts::Bool = true`: Enable or disable the painting of the surfaces of the [`Contact`](@ref) onto the `grid`.
## Examples
```julia
apply_initial_state!(sim, WeightingPotential, 1) # => applies initial state for weighting potential of contact with id 1
```
"""
function apply_initial_state!(sim::Simulation{T}, ::Type{WeightingPotential}, contact_id::Int, grid::Grid{T} = Grid(sim);
not_only_paint_contacts::Bool = true, paint_contacts::Bool = true, depletion_handling::Bool = false)::Nothing where {T <: SSDFloat}
pcs = PotentialCalculationSetup(
sim.detector,
grid,
sim.medium,
missing,
depletion_handling ? sim.imp_scale.data : missing,
weighting_potential_contact_id = contact_id;
not_only_paint_contacts,
paint_contacts,
point_types = depletion_handling ? sim.point_types : missing
);
sim.weighting_potentials[contact_id] = WeightingPotential(ElectricPotentialArray(pcs), grid)
nothing
end
"""
update_till_convergence!( sim::Simulation{T} ::Type{ElectricPotential}, convergence_limit::Real; kwargs...)::T
Takes the current state of `sim.electric_potential` and updates it until it has converged.
There are several keyword arguments which can be used to tune the simulation.
## Arguments
* `sim::Simulation{T}`: [`Simulation`](@ref) for which `sim.electric_potential` will be updated.
* `convergence_limit::Real`: `convergence_limit` times the bias voltage sets the convergence limit of the relaxation.
The convergence value is the absolute maximum difference of the potential between two iterations of all grid points.
Default is `1e-7`.
## Keywords
* `n_iterations_between_checks::Int`: Number of iterations between checks. Default is set to `500`.
* `max_n_iterations::Int`: Set the maximum number of iterations which are performed after each grid refinement.
Default is `-1`. If set to `-1` there will be no limit.
* `depletion_handling::Bool`: Enables the handling of undepleted regions. Default is `false`.
* `use_nthreads::Int`: Number of threads to use in the computation. Default is `Base.Threads.nthreads()`.
The environment variable `JULIA_NUM_THREADS` must be set appropriately before the Julia session was
started (e.g. `export JULIA_NUM_THREADS=8` in case of bash).
* `not_only_paint_contacts::Bool = true`: Whether to only use the painting algorithm of the surfaces of [`Contact`](@ref)
without checking if points are actually inside them.
Setting it to `false` should improve the performance but the points inside of [`Contact`](@ref) are not fixed anymore.
* `paint_contacts::Bool = true`: Enable or disable the painting of the surfaces of the [`Contact`](@ref) onto the `grid`.
* `sor_consts::Union{<:Real, NTuple{2, <:Real}}`: Two element tuple in case of cylindrical coordinates.
First element contains the SOR constant for `r` = 0.
Second contains the constant at the outer most grid point in `r`. A linear scaling is applied in between.
First element should be smaller than the second one and both should be `∈ [1.0, 2.0]`. Default is `[1.4, 1.85]`.
In case of Cartesian coordinates, only one value is taken.
* `verbose::Bool=true`: Boolean whether info output is produced or not.
## Example
```julia
SolidStateDetectors.update_till_convergence!(sim, ElectricPotential, 1e-6, depletion_handling = true)
```
"""
function update_till_convergence!( sim::Simulation{T,CS},
::Type{ElectricPotential},
convergence_limit::Real = 1e-7;
n_iterations_between_checks::Int = 500,
max_n_iterations::Int = -1,
depletion_handling::Bool = false,
use_nthreads::Int = Base.Threads.nthreads(),
not_only_paint_contacts::Bool = true,
paint_contacts::Bool = true,
device_array_type::Type{<:AbstractArray} = Array,
sor_consts::Union{Missing, T, NTuple{2, T}} = missing,
verbose::Bool = true
)::T where {T <: SSDFloat, CS <: AbstractCoordinateSystem}
if ismissing(sor_consts)
sor_consts = CS == Cylindrical ? (T(1.4), T(1.85)) : T(1.4)
elseif length(sor_consts) == 1 && CS == Cylindrical
sor_consts = (T(sor_consts), T(sor_consts))
elseif length(sor_consts) > 1 && CS == Cartesian
sor_consts = T(sor_consts[1])
end
only_2d = length(sim.electric_potential.grid.axes[2]) == 1
pcs = Adapt.adapt(device_array_type, PotentialCalculationSetup(
sim.detector, sim.electric_potential.grid, sim.medium, sim.electric_potential.data, sim.imp_scale.data, sor_consts = T.(sor_consts),
use_nthreads = _guess_optimal_number_of_threads_for_SOR(size(sim.electric_potential.grid), Base.Threads.nthreads(), CS),
not_only_paint_contacts = not_only_paint_contacts, paint_contacts = paint_contacts,
))
via_KernelAbstractions = device_array_type <: GPUArrays.AnyGPUArray
# This is just to be able to test the KernelAbstractions.jl backend on the CPU
# as we cannot test it on GPU on GitHub. See also "SOR GPU Backend" test set.
cf::T = _update_till_convergence!( pcs, T(convergence_limit), via_KernelAbstractions;
only2d = Val{only_2d}(),
depletion_handling = Val{depletion_handling}(),
is_weighting_potential = Val{false}(),
use_nthreads = use_nthreads,
n_iterations_between_checks = n_iterations_between_checks,
max_n_iterations = max_n_iterations,
verbose = verbose )
pcs = Adapt.adapt(Array, pcs)
grid = Grid(pcs)
sim.q_eff_imp = EffectiveChargeDensity(EffectiveChargeDensityArray(pcs), grid)
sim.imp_scale = ImpurityScale(ImpurityScaleArray(pcs), grid)
sim.q_eff_fix = EffectiveChargeDensity(FixedEffectiveChargeDensityArray(pcs), grid)
sim.ϵ_r = DielectricDistribution(DielectricDistributionArray(pcs), get_extended_midpoints_grid(grid))
sim.electric_potential = ElectricPotential(ElectricPotentialArray(pcs), grid)
sim.point_types = PointTypes(PointTypeArray(pcs), grid)
cf
end
"""
update_till_convergence!( sim::Simulation{T} ::Type{WeightingPotential}, contact_id::Int, convergence_limit::Real; kwargs...)::T
Takes the current state of `sim.weighting_potentials[contact_id]` and updates it until it has converged.
There are several keyword arguments which can be used to tune the simulation.
## Arguments
* `sim::Simulation{T}`: [`Simulation`](@ref) for which `sim.weighting_potentials[contact_id]` will be updated.
* `contact_id::Int`: The `id` of the [`Contact`](@ref) for which the [`WeightingPotential`](@ref) is to be calculated.
* `convergence_limit::Real`: `convergence_limit` times the bias voltage sets the convergence limit of the relaxation.
The convergence value is the absolute maximum difference of the potential between two iterations of all grid points.
Default is `1e-7`.
## Keywords
* `n_iterations_between_checks::Int`: Number of iterations between checks. Default is set to `500`.
* `max_n_iterations::Int`: Set the maximum number of iterations which are performed after each grid refinement.
Default is `-1`. If set to `-1` there will be no limit.
* `depletion_handling::Bool`: Enables the handling of undepleted regions. Default is `false`. This is an experimental feature:
In undepleted regions (determined in `calculate_electric_potential!(sim; depletion_handling = true)`), the dielectric permittivity
of the semiconductor is scaled up to mimic conductive behavior. The scale factor can be tuned via
the function [`scaling_factor_for_permittivity_in_undepleted_region`](@ref).
* `use_nthreads::Int`: Number of threads to use in the computation. Default is `Base.Threads.nthreads()`.
The environment variable `JULIA_NUM_THREADS` must be set appropriately before the Julia session was
started (e.g. `export JULIA_NUM_THREADS=8` in case of bash).
* `not_only_paint_contacts::Bool = true`: Whether to only use the painting algorithm of the surfaces of [`Contact`](@ref)
without checking if points are actually inside them.
Setting it to `false` should improve the performance but the points inside of [`Contact`](@ref) are not fixed anymore.
* `paint_contacts::Bool = true`: Enable or disable the painting of the surfaces of the [`Contact`](@ref) onto the `grid`.
* `sor_consts::Union{<:Real, NTuple{2, <:Real}}`: Two element tuple in case of cylindrical coordinates.
First element contains the SOR constant for `r` = 0.
Second contains the constant at the outer most grid point in `r`. A linear scaling is applied in between.
First element should be smaller than the second one and both should be `∈ [1.0, 2.0]`. Default is `[1.4, 1.85]`.
In case of Cartesian coordinates, only one value is taken.
* `verbose::Bool=true`: Boolean whether info output is produced or not.
## Example
```julia
SolidStateDetectors.update_till_convergence!(sim, WeightingPotential, 1, 1e-6, use_nthreads = 4)
```
"""
function update_till_convergence!( sim::Simulation{T, CS},
::Type{WeightingPotential},
contact_id::Int,
convergence_limit::Real = 1e-7;
n_iterations_between_checks::Int = 500,
max_n_iterations::Int = -1,
depletion_handling::Bool = false,
not_only_paint_contacts::Bool = true,
paint_contacts::Bool = true,
use_nthreads::Int = Base.Threads.nthreads(),
device_array_type::Type{<:AbstractArray} = Array,
sor_consts::Union{Missing, T, NTuple{2, T}} = missing,
verbose::Bool = true
)::T where {T <: SSDFloat, CS <: AbstractCoordinateSystem}
if ismissing(sor_consts)
sor_consts = CS == Cylindrical ? (T(1.4), T(1.85)) : T(1.4)
elseif length(sor_consts) == 1 && CS == Cylindrical
sor_consts = (T(sor_consts), T(sor_consts))
elseif length(sor_consts) > 1 && CS == Cartesian
sor_consts = T(sor_consts[1])
end
only_2d::Bool = length(sim.weighting_potentials[contact_id].grid.axes[2]) == 1
pcs = Adapt.adapt(device_array_type, PotentialCalculationSetup(
sim.detector,
sim.weighting_potentials[contact_id].grid,
sim.medium,
sim.weighting_potentials[contact_id].data,
depletion_handling ? sim.imp_scale.data : ones(T, size(sim.weighting_potentials[contact_id].data)) ,
sor_consts = T.(sor_consts),
weighting_potential_contact_id = contact_id,
use_nthreads = _guess_optimal_number_of_threads_for_SOR(size(sim.weighting_potentials[contact_id].grid), Base.Threads.nthreads(), CS),
not_only_paint_contacts = not_only_paint_contacts,
paint_contacts = paint_contacts,
point_types = depletion_handling ? sim.point_types : missing)
);
via_KernelAbstractions = device_array_type <: GPUArrays.AnyGPUArray
# This is just to be able to test the KernelAbstractions.jl backend on the CPU
# as we cannot test it on GPU on GitHub. See also "SOR GPU Backend" test set.
cf::T = _update_till_convergence!( pcs, T(convergence_limit), via_KernelAbstractions;
only2d = Val{only_2d}(),
depletion_handling = Val{false}(),
is_weighting_potential = Val{true}(),
use_nthreads = use_nthreads,
n_iterations_between_checks = n_iterations_between_checks,
max_n_iterations = max_n_iterations,
verbose = verbose )
pcs = Adapt.adapt(Array, pcs)
sim.weighting_potentials[contact_id] = WeightingPotential(ElectricPotentialArray(pcs), sim.weighting_potentials[contact_id].grid)
cf
end
"""
refine!(sim::Simulation{T}, ::Type{ElectricPotential}, max_diffs::Tuple, minimum_distances::Tuple, kwargs...)
Takes the current state of `sim.electric_potential` and refines it with respect to the input arguments
`max_diffs` and `minimum_distances` by
1. extending the `grid` of `sim.electric_potential` to be a closed grid in all dimensions,
2. refining the axis of the grid based on `max_diffs` and `minimum_distances`:
Insert new ticks between two existing ticks such that the potential difference between each tick becomes
smaller than `max_diff[i]` (`i` -> dimension) but that the distances between the ticks stays larger than `minimum_distances[i]`, and
3. creating the new data array for the refined grid and fill it by interpolation of the the initial `grid`.
## Arguments
* `sim::Simulation{T}`: [`Simulation`](@ref) for which `sim.electric_potential` will be refined.
* `max_diffs::Tuple{<:Real,<:Real,<:Real}`: Maximum potential difference between two discrete ticks of `sim.electric_potential.grid` after refinement.
* `minimum_distances::Tuple{<:Real,<:Real,<:Real}`: Minimum distance (in SI Units) between two discrete ticks of `sim.electric_potential.grid` after refinement.
## Examples
```julia
SolidStateDetectors.refine!(sim, ElectricPotential, max_diffs = (100, 100, 100), minimum_distances = (0.01, 0.02, 0.01))
```
"""
function refine!(sim::Simulation{T}, ::Type{ElectricPotential},
max_diffs::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0)),
minimum_distances::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0));
not_only_paint_contacts::Bool = true,
paint_contacts::Bool = true,
update_other_fields::Bool = false) where {T <: SSDFloat}
sim.electric_potential = refine_scalar_potential(sim.electric_potential, T.(max_diffs), T.(minimum_distances))
if update_other_fields
pcs = PotentialCalculationSetup(sim.detector, sim.electric_potential.grid, sim.medium, sim.electric_potential.data,
not_only_paint_contacts = not_only_paint_contacts, paint_contacts = paint_contacts)
sim.imp_scale = ImpurityScale(ImpurityScaleArray(pcs), sim.electric_potential.grid)
sim.q_eff_imp = EffectiveChargeDensity(EffectiveChargeDensityArray(pcs), sim.electric_potential.grid)
sim.q_eff_fix = EffectiveChargeDensity(FixedEffectiveChargeDensityArray(pcs), sim.electric_potential.grid)
sim.ϵ_r = DielectricDistribution(DielectricDistributionArray(pcs), get_extended_midpoints_grid(sim.electric_potential.grid))
sim.point_types = PointTypes(PointTypeArray(pcs), sim.electric_potential.grid)
end
nothing
end
"""
refine!(sim::Simulation{T}, ::Type{WeightingPotential}, max_diffs::Tuple{<:Real,<:Real,<:Real}, minimum_distances::Tuple{<:Real,<:Real,<:Real})
Takes the current state of `sim.weighting_potentials[contact_id]` and refines it with respect to the input arguments
`max_diffs` and `minimum_distances` by
1. extending the `grid` of `sim.weighting_potentials[contact_id]` to be a closed grid in all dimensions,
2. refining the axis of the grid based on `max_diffs` and `minimum_distances`:
Insert new ticks between two existing ticks such that the potential difference between each tick becomes
smaller than `max_diff[i]` (`i` -> dimension) but that the distances between the ticks stays larger than `minimum_distances[i]`, and
3. creating the new data array for the refined grid and fill it by interpolation of the the initial `grid`.
## Arguments
* `sim::Simulation{T}`: [`Simulation`](@ref) for which `sim.weighting_potentials[contact_id]` will be refined.
* `contact_id::Int`: The `id` of the [`Contact`](@ref) for which the [`WeightingPotential`](@ref) is refined.
* `max_diffs::Tuple{<:Real,<:Real,<:Real}`: Maximum potential difference between two discrete ticks of `sim.weighting_potentials[contact_id].grid` after refinement.
* `minimum_distances::Tuple{<:Real,<:Real,<:Real}`: Minimum distance (in SI Units) between two discrete ticks of `sim.weighting_potentials[contact_id].grid` after refinement.
## Examples
```julia
SolidStateDetectors.refine!(sim, WeightingPotential, 1, max_diffs = (0.01, 0.01, 0.01), minimum_distances = (0.01, 0.02, 0.01))
```
"""
function refine!(sim::Simulation{T}, ::Type{WeightingPotential}, contact_id::Int,
max_diffs::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0)),
minimum_distances::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0))) where {T <: SSDFloat}
sim.weighting_potentials[contact_id] = refine_scalar_potential(sim.weighting_potentials[contact_id], max_diffs, minimum_distances)
nothing
end
function _calculate_potential!( sim::Simulation{T, CS}, potential_type::UnionAll, contact_id::Union{Missing, Int} = missing;
convergence_limit::Real = 1e-7,
refinement_limits::Union{Missing, <:Real, Vector{<:Real}, Tuple{<:Real,<:Real,<:Real}, Vector{<:Tuple{<:Real, <:Real, <:Real}}} = [0.2, 0.1, 0.05],
min_tick_distance::Union{Missing, LengthQuantity, Tuple{LengthQuantity, <:Union{LengthQuantity, AngleQuantity}, LengthQuantity}} = missing,
max_tick_distance::Union{Missing, LengthQuantity, Tuple{LengthQuantity, <:Union{LengthQuantity, AngleQuantity}, LengthQuantity}} = missing,
max_distance_ratio::Real = 5,
depletion_handling::Bool = false,
use_nthreads::Union{Int, Vector{Int}} = Base.Threads.nthreads(),
sor_consts::Union{Missing, <:Real, Tuple{<:Real,<:Real}} = missing,
max_n_iterations::Int = 50000,
n_iterations_between_checks::Int = 1000,
not_only_paint_contacts::Bool = true,
paint_contacts::Bool = true,
verbose::Bool = true,
device_array_type::Type{<:AbstractArray} = Array,
initialize::Bool = true,
grid::Union{Missing, Grid{T}} = initialize ? missing : (potential_type == ElectricPotential ? sim.electric_potential.grid : sim.weighting_potentials[contact_id].grid)
)::Nothing where {T <: SSDFloat, CS <: AbstractCoordinateSystem}
begin # preperations
onCPU = !(device_array_type <: GPUArrays.AnyGPUArray)
convergence_limit::T = T(convergence_limit)
isEP::Bool = potential_type == ElectricPotential
isWP::Bool = !isEP
if ismissing(grid)
grid = Grid(sim, for_weighting_potential = isWP, max_tick_distance = max_tick_distance, max_distance_ratio = max_distance_ratio)
end
if ismissing(sor_consts)
sor_consts = CS == Cylindrical ? (T(1.4), T(1.85)) : T(1.4)
elseif length(sor_consts) == 1 && CS == Cylindrical
sor_consts = (T(sor_consts), T(sor_consts))
elseif length(sor_consts) > 1 && CS == Cartesian
sor_consts = T(sor_consts[1])
else
sor_consts = T.(sor_consts)
end
min_tick_distance::NTuple{3, T} = if CS == Cylindrical
if !ismissing(min_tick_distance)
if min_tick_distance isa LengthQuantity
world_r_mid = (sim.world.intervals[1].right + sim.world.intervals[1].left)/2
min_distance_z = min_distance_r = T(to_internal_units(min_tick_distance))
min_distance_r, min_distance_z / world_r_mid, min_distance_z
else
T(to_internal_units(min_tick_distance[1])),
T(to_internal_units(min_tick_distance[2])),
T(to_internal_units(min_tick_distance[3]))
end
else
(T(1e-5), T(1e-5) / (0.25 * grid.axes[1][end]), T(1e-5))
end
else
if !ismissing(min_tick_distance)
if min_tick_distance isa LengthQuantity
min_distance = T(to_internal_units(min_tick_distance))
min_distance, min_distance, min_distance
else
T(to_internal_units(min_tick_distance[1])),
T(to_internal_units(min_tick_distance[2])),
T(to_internal_units(min_tick_distance[3]))
end
else
(T(1e-5), T(1e-5), T(1e-5))
end
end
refine = !ismissing(refinement_limits)
if !(refinement_limits isa Vector) refinement_limits = [refinement_limits] end
n_refinement_steps = length(refinement_limits)
max_nthreads, guess_nt = if use_nthreads isa Int
if use_nthreads > Base.Threads.nthreads()
use_nthreads = Base.Threads.nthreads();
@warn "`use_nthreads` was set to `Base.Threads.nthreads() = $(Base.Threads.nthreads())`.
The environment variable `JULIA_NUM_THREADS` must be set appropriately before the julia session is started."
end
fill(use_nthreads, n_refinement_steps+1), true
else
if length(use_nthreads) > n_refinement_steps+1
use_nthreads = use_nthreads[1:n_refinement_steps+1]
end
_nt = fill(maximum(use_nthreads), n_refinement_steps+1)
_nt[1:length(use_nthreads)] = use_nthreads
_nt, false
end
only_2d::Bool = length(grid.axes[2]) == 1 ? true : false
if CS == Cylindrical
cyclic::T = width(grid.axes[2].interval)
n_φ_sym::Int = only_2d ? 1 : round(Int, round(T(2π) / cyclic, digits = 3))
n_φ_sym_info_txt = if only_2d
"φ symmetry: Detector is φ-symmetric -> 2D computation."
else
"φ symmetry: calculating just 1/$(n_φ_sym) in φ of the detector."
end
end
contact_potentials::Vector{T} = [contact.potential for contact in sim.detector.contacts]
bias_voltage::T = (length(contact_potentials) > 0) ? (maximum(contact_potentials) - minimum(contact_potentials)) : T(0)
if isWP bias_voltage = T(1) end
if verbose
sim_name = haskey(sim.config_dict, "name") ? sim.config_dict["name"] : "Unnamed"
println(
"Simulation: $(sim_name)\n",
"$(isEP ? "Electric" : "Weighting") Potential Calculation$(isEP ? "" : " - ID: $contact_id")\n",
if isEP "Bias voltage: $(bias_voltage) V\n" else "" end,
if CS == Cylindrical "$n_φ_sym_info_txt\n" else "" end,
"Precision: $T\n",
"Device: $(onCPU ? "CPU" : "GPU")\n",
onCPU ? "Max. CPU Threads: $(maximum(max_nthreads))\n" : "",
"Coordinate system: $(CS)\n",
"N Refinements: -> $(n_refinement_steps)\n",
"Convergence limit: $convergence_limit $(isEP ? " => $(round(abs(bias_voltage * convergence_limit), sigdigits=2)) V" : "")\n",
"Initial grid size: $(size(grid))\n",
)
end
end
if initialize
if isEP
apply_initial_state!(sim, potential_type, grid; not_only_paint_contacts, paint_contacts)
update_till_convergence!( sim, potential_type, convergence_limit,
n_iterations_between_checks = n_iterations_between_checks,
max_n_iterations = max_n_iterations,
depletion_handling = depletion_handling,
device_array_type = device_array_type,
use_nthreads = guess_nt ? _guess_optimal_number_of_threads_for_SOR(size(sim.electric_potential.grid), max_nthreads[1], CS) : max_nthreads[1],
sor_consts = sor_consts )
else
apply_initial_state!(sim, potential_type, contact_id, grid; not_only_paint_contacts, paint_contacts, depletion_handling)
update_till_convergence!( sim, potential_type, contact_id, convergence_limit,
n_iterations_between_checks = n_iterations_between_checks,
max_n_iterations = max_n_iterations,
depletion_handling = depletion_handling,
device_array_type = device_array_type,
use_nthreads = guess_nt ? _guess_optimal_number_of_threads_for_SOR(size(sim.weighting_potentials[contact_id].grid), max_nthreads[1], CS) : max_nthreads[1],
sor_consts = sor_consts )
end
end
# refinement_counter::Int = 1
if refine
for iref in 1:n_refinement_steps
is_last_ref = iref >= 3 || iref == n_refinement_steps
# SOR is good in order to converge quickly against the final state.
# However, when already close to the final state, its better to
# to switch it off (sor_const = 1)
ref_limits = T.(_extend_refinement_limits(refinement_limits[iref]))
if isEP
max_diffs = if iszero(bias_voltage)
abs.(ref_limits .* (extrema(sim.electric_potential.data) |> e -> e[2] - e[1]))
else
abs.(ref_limits .* bias_voltage)
end
refine!(sim, ElectricPotential, max_diffs, min_tick_distance)
nt = guess_nt ? _guess_optimal_number_of_threads_for_SOR(size(sim.electric_potential.grid), max_nthreads[iref+1], CS) : max_nthreads[iref+1]
verbose && println("Grid size: $(size(sim.electric_potential.data)) - $(onCPU ? "using $(nt) threads now" : "GPU")")
update_till_convergence!( sim, potential_type, convergence_limit,
n_iterations_between_checks = n_iterations_between_checks,
max_n_iterations = max_n_iterations,
depletion_handling = depletion_handling,
use_nthreads = nt,
device_array_type = device_array_type,
not_only_paint_contacts = not_only_paint_contacts,
paint_contacts = paint_contacts,
sor_consts = is_last_ref ? T(1) : sor_consts )
else
max_diffs = abs.(ref_limits)
refine!(sim, WeightingPotential, contact_id, max_diffs, min_tick_distance)
nt = guess_nt ? _guess_optimal_number_of_threads_for_SOR(size(sim.weighting_potentials[contact_id].grid), max_nthreads[iref+1], CS) : max_nthreads[iref+1]
verbose && println("Grid size: $(size(sim.weighting_potentials[contact_id].data)) - $(onCPU ? "using $(nt) threads now" : "GPU")")
update_till_convergence!( sim, potential_type, contact_id, convergence_limit,
n_iterations_between_checks = n_iterations_between_checks,
max_n_iterations = max_n_iterations,
depletion_handling = depletion_handling,
use_nthreads = nt,
device_array_type = device_array_type,
not_only_paint_contacts = not_only_paint_contacts,
paint_contacts = paint_contacts,
sor_consts = is_last_ref ? T(1) : sor_consts )
end
end
end
if verbose && depletion_handling && isEP
maximum_applied_potential = maximum(broadcast(c -> c.potential, sim.detector.contacts))
minimum_applied_potential = minimum(broadcast(c -> c.potential, sim.detector.contacts))
@inbounds for i in eachindex(sim.electric_potential.data)
if sim.electric_potential.data[i] < minimum_applied_potential # p-type
@warn """Detector seems not to be fully depleted at a bias voltage of $(bias_voltage) V.
At least one grid point has a smaller potential value ($(sim.electric_potential.data[i]) V)