-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbasicBulkParticleHandler.hpp
More file actions
616 lines (561 loc) · 23 KB
/
Copy pathbasicBulkParticleHandler.hpp
File metadata and controls
616 lines (561 loc) · 23 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
#ifndef BASIC_BULK_PARTICLE_HANDLER_HPP
#define BASIC_BULK_PARTICLE_HANDLER_HPP
#ifdef _OPENMP
#include <omp.h>
#endif
#include <algorithm>
#include <array>
#include <chrono>
#include <fstream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <ParticleType/emcParticleType.hpp>
#include <emcGrid.hpp>
#include <emcParticleDrift.hpp>
#include <emcParticleInitialization.hpp>
#include <emcUtil.hpp>
/**
* @brief Handler is used for basic bulk simulations.
*
* Doesn't use FMM and assumes periodic boundary conditions
* at the end of the simulation space. Also the device type in
* this context is only used to represent the simulation space
* and the doping within that space.
*
* @param device simulated device (in this case only extent of device, doping
* and spacing are needed)
* @param idxTypeToPartType map relating the idx of a particleType to the
* specific particleType
* @param appliedFieldDir direction of the applied field (normalized)
* @param appliedField applied electric field
* @param particles container storing the information of each particle
* (accessible by index of particle type [idxType] and particle index [idxPart])
* @param positionsParticles container storing the particle position of each
* particle (accessible by index of particle type [idxType] and particle index
* [idxPart])
* @param rngs vector containing random number generator(s)
*/
template <class T, class DeviceType, SizeType Dim = DeviceType::Dimension>
struct basicBulkParticleHandler {
typedef emcParticleType<T, DeviceType> ParticleType;
typedef typename DeviceType::SizeVec SizeVec;
typedef typename DeviceType::ValueVec ValueVec;
typedef std::map<SizeType, std::unique_ptr<ParticleType>>
MapIdxToParticleTypes;
private:
DeviceType &device; //!< simulated geometry
MapIdxToParticleTypes
&idxTypeToPartType; //!< map coupling idxType and PartType
ValueVec appliedFieldDir; //!< direction of the el. field (normalized)
ValueVec appliedField; //!< strength of electric field
std::vector<std::vector<emcParticle<T>>> particles;
std::vector<std::vector<std::array<T, Dim>>> positionsParticles;
std::uniform_real_distribution<T> distForLog{1e-6, 1.}, dist{0., 1.};
std::vector<emcRNG> rngs;
public:
basicBulkParticleHandler() = delete;
/**
* @brief Constructs a new object of basicBulkParticleHandler without any
* applied electric field.
*
* @param inDevice simulated device (in this case only extent of device,
* doping and spacing are required to represent the simulation space).
* @param inTypes used particle types for the simulation.
* @param inFieldDirection the direction of the applied field (in case the
* strength is reset, the field is applied in that direction)
*/
basicBulkParticleHandler(DeviceType &inDevice, MapIdxToParticleTypes &inTypes,
const ValueVec &inFieldDirection)
: basicBulkParticleHandler(inDevice, inTypes, inFieldDirection, 0) {}
/**
* @brief Construct a new object of basicBulkParticleHandler, with the given
* applied field.
*
* @param inDevice simulated device (in this case only extent of device,
* doping and spacing are required to represent the simulation space).
* @param inTypes particle types for the simulation.
* @param inFieldDirection the direction of the applied field
* @param inFieldStrength field strength
*/
/// @param inSeed RNG seed; 0 (default) draws a seed from the wall clock.
/// A non-zero value makes the run bit-reproducible.
basicBulkParticleHandler(DeviceType &inDevice, MapIdxToParticleTypes &inTypes,
const ValueVec &inFieldDirection, T inFieldStrength,
long unsigned int inSeed = 0)
: device(inDevice), idxTypeToPartType(inTypes),
appliedFieldDir(inFieldDirection), particles(inTypes.size()),
positionsParticles(inTypes.size()) {
// set electric field
normalize(appliedFieldDir);
appliedField = scale(appliedFieldDir, inFieldStrength);
// initialize scatter tables
for (const auto &partType : idxTypeToPartType) {
if (partType.second->isMoved())
partType.second->initScatterTables();
}
// seed random number generator(s)
rngs.emplace_back(emcRNG(
inSeed != 0 ? inSeed
: static_cast<long unsigned int>(
std::chrono::high_resolution_clock::now()
.time_since_epoch()
.count())));
#ifdef _OPENMP
for (SizeType idxSeed = 1; idxSeed < omp_get_max_threads(); idxSeed++)
rngs.emplace_back(emcRNG(rngs[0]()));
#endif
}
/// @brief function that allows the seeding of the used random number
/// generator(s).
/// @param inSeed seed for the rng.
void setSeed(SizeType inSeed) {
rngs[0].seed(inSeed);
#ifdef _OPENMP
for (SizeType idxSeed = 1; idxSeed < omp_get_max_threads(); idxSeed++)
rngs[idxSeed].seed(rngs[0]());
#endif
}
/// @brief resets the strength of the applied field
/// @param inAppliedFieldStrength new strength of the applied el. field
void resetAppliedFieldStrength(T inAppliedFieldStrength) {
appliedField = scale(appliedFieldDir, inAppliedFieldStrength);
}
/// @brief generates initial nr of Particles at each coord
/// NOTE: the number of particles that are used depends on
/// the used device (that represents the simulation space)
/// and the used particleType!
void generateInitialParticles() {
emcGrid<T, Dim> pot(device.getGridExtent(), 0);
for (const auto &[idxType, partType] : idxTypeToPartType) {
SizeVec coord;
for (coord.fill(0); !device.isEndCoord(coord);
device.advanceCoord(coord)) {
auto nrPartToCreate =
partType->getInitialNrParticles(coord, device, pot);
while (nrPartToCreate >= 1) {
addParticle(idxType, coord, rngs[0]);
nrPartToCreate--;
}
if (dist(rngs[0]) < nrPartToCreate)
addParticle(idxType, coord, rngs[0]);
}
}
}
SizeType getNrParticles(SizeType idxType) const {
return positionsParticles[idxType].size();
}
ValueVec getAppliedField() const { return appliedField; }
void printNrParticles() const {
for (const auto &[idxType, partType] : idxTypeToPartType)
std::cout << "\t" << positionsParticles[idxType].size() << " "
<< partType->getName() << "\n";
}
/**
* @brief moves particles for a specific amount of time.
*
* Motion is based on alternating free-flights and scatter events
* based on the remaining free-flight time that a particle has left.
*
* @param tStep time-step for which the particle moves
*/
void moveParticles(T tStep) {
for (const auto &partType : idxTypeToPartType) {
SizeType idxType = partType.first;
auto &type = partType.second;
if (type->isMoved()) {
auto force = scale(appliedField, type->getCharge());
#pragma omp parallel
{
SizeType idxThread = 0;
#ifdef _OPENMP
idxThread = omp_get_thread_num();
#endif
auto &currRNG = rngs[idxThread];
#pragma omp for
for (SizeType idxPart = 0; idxPart < getNrParticles(idxType);
idxPart++) {
auto &particle = particles[idxType][idxPart];
auto &pos = positionsParticles[idxType][idxPart];
auto valley = type->getValley(particle.valley);
driftParticle(std::min(particle.tau, tStep), particle, valley, pos,
force);
T tRemaining = tStep - particle.tau;
while (tRemaining > 0) {
type->scatterParticle(particle, currRNG);
T newTau =
type->getNewTau(particle.valley, particle.region, currRNG);
particle.tau += newTau;
valley = type->getValley(particle.valley);
driftParticle(std::min(tRemaining, newTau), particle, valley, pos,
force);
tRemaining -= newTau;
}
particle.tau -= tStep;
// handle grain scattering
particle.grainTau -= tStep;
if (particle.grainTau <= 0) {
type->scatterParticleAtGrain(particle, currRNG);
particle.grainTau = type->getNewGrainTau(currRNG);
}
}
}
}
}
}
void print(std::string namePrefix, std::string nameSuffix) const {
for (const auto &[idxType, type] : idxTypeToPartType) {
std::ofstream os;
os.open(namePrefix + type->getName() + nameSuffix + ".txt");
os << device.getMaxPos() << "\n";
auto nrPart = positionsParticles[idxType].size();
for (SizeType idxPart = 0; idxPart < nrPart; idxPart++) {
os << idxPart << " ";
os << positionsParticles[idxType][idxPart];
if (type->isMoved()) {
os << " ";
os << particles[idxType][idxPart].k << " ";
os << particles[idxType][idxPart].energy << " ";
os << particles[idxType][idxPart].subValley << " ";
os << particles[idxType][idxPart].valley;
}
if (idxPart < nrPart - 1)
os << "\n";
}
os.close();
}
}
//! Prints the current drift velocity of each particle.
void printDriftVelocities(std::ofstream &os) const {
for (const auto &[idxType, partType] : idxTypeToPartType) {
if (partType->isMoved()) {
auto nrPart = positionsParticles[idxType].size();
for (SizeType idxPart = 0; idxPart < nrPart; idxPart++) {
auto &part = particles[idxType][idxPart];
auto valley = partType->getValley(part.valley);
auto vel = valley->getVelocity(part.k, part.energy, part.subValley);
auto driftVel = innerProduct(vel, appliedFieldDir);
os << driftVel;
if (idxPart < nrPart - 1)
os << " ";
}
os << std::endl;
}
}
}
//! Prints current velocity of each particle.
void printVelocities(std::ofstream &os) const {
for (const auto &[idxType, partType] : idxTypeToPartType) {
if (partType->isMoved()) {
auto nrPart = positionsParticles[idxType].size();
for (SizeType idxPart = 0; idxPart < nrPart; idxPart++) {
auto &part = particles[idxType][idxPart];
auto valley = partType->getValley(part.valley);
auto vel = valley->getVelocity(part.k, part.energy, part.subValley);
os << vel;
if (idxPart < nrPart - 1)
os << " ";
}
os << std::endl;
}
}
}
//! Returns the current valley occupation for each valley of particleType
//! with given index idxType.
std::vector<T> getValleyOccupationProbability(SizeType idxType) const {
auto &partType = idxTypeToPartType[idxType];
std::vector<T> countPart(partType->getNrValleys(), 0.);
if (getNrParticles(idxType) != 0) {
for (auto &part : particles[idxType]) {
countPart[part.valley]++;
}
std::for_each(countPart.begin(), countPart.end(),
[&](T &nrPart) { nrPart /= getNrParticles(idxType); });
}
return countPart;
}
//! Returns the current average energy for each valley of particleType
//! with given index idxType.
std::vector<T> getAvgEnergy(SizeType idxType) const {
auto &partType = idxTypeToPartType[idxType];
std::vector<T> avgEnergy(partType->getNrValleys(), 0.);
if (getNrParticles(idxType) != 0) {
std::vector<SizeType> countPart(partType->getNrValleys(), 0);
for (auto &part : particles[idxType]) {
avgEnergy[part.valley] += part.energy;
countPart[part.valley]++;
}
std::transform(countPart.begin(), countPart.end(), avgEnergy.begin(),
avgEnergy.begin(), [](SizeType nrPart, T sum) {
if (nrPart != 0)
return sum / nrPart;
else
return 0.;
});
}
return avgEnergy;
}
//! Returns the avgDriftVelocity for each for each valley of particleType
//! with given index idxType.
std::vector<T> getAvgDriftVelocity(SizeType idxType) const {
auto &partType = idxTypeToPartType[idxType];
std::vector<T> avgDriftVel(partType->getNrValleys(), 0.);
if (getNrParticles(idxType) != 0) {
std::vector<SizeType> countPart(partType->getNrValleys(), 0.);
for (const auto &part : particles[idxType]) {
auto valley = partType->getValley(part.valley);
auto velocity =
valley->getVelocity(part.k, part.energy, part.subValley);
avgDriftVel[part.valley] += innerProduct(velocity, appliedFieldDir);
countPart[part.valley]++;
}
std::transform(countPart.begin(), countPart.end(), avgDriftVel.begin(),
avgDriftVel.begin(), [](SizeType nrPart, T sumDrift) {
if (nrPart != 0)
return sumDrift / nrPart;
else
return 0.;
});
}
return avgDriftVel;
}
/**
* @brief Apply binary carrier-carrier scattering to one particle type.
*
* Passes the internal particle vector directly to the scatter object so it
* can form random pairs and perform CM-frame elastic collisions without
* copying data.
*
* @param ccScatter emcCarrierCarrierScatter instance (or any object with a
* scatter(vector<emcParticle<T>>&, T dt, emcRNG&) method)
* @param idxType index of the particle type to scatter
* @param dt time step [s]
*/
template <class CCScatter>
void carrierCarrierScatter(CCScatter &ccScatter, SizeType idxType, T dt) {
ccScatter.scatter(particles[idxType], dt, rngs[0]);
}
/**
* @brief Apply one time step of inter-species (e-h) carrier-carrier scatter.
*
* @param ehScatter scatter object with scatter(electrons, holes, dt, rng)
* @param idxTypeE index of the electron particle type
* @param idxTypeH index of the hole particle type
* @param dt time step [s]
*/
template <class EHScatter>
void interCarrierScatter(EHScatter &ehScatter, SizeType idxTypeE,
SizeType idxTypeH, T dt) {
ehScatter.scatter(particles[idxTypeE], particles[idxTypeH], dt, rngs[0]);
}
/**
* @brief Apply one time step of band-to-band recombination (radiative +
* Auger) across two carrier species.
*
* Delegates to Recomb::recombine(electrons, holes, posE, posH, dt, rng),
* which removes particle pairs and (for Auger) energizes a third carrier.
*
* @param recomb recombination object (emcRecombination or compatible)
* @param idxTypeE index of the electron particle type
* @param idxTypeH index of the hole particle type
* @param dt time step [s]
*/
template <class Recomb>
void recombine(Recomb &recomb, SizeType idxTypeE, SizeType idxTypeH, T dt) {
recomb.recombine(particles[idxTypeE], particles[idxTypeH],
positionsParticles[idxTypeE],
positionsParticles[idxTypeH], dt, rngs[0]);
}
/**
* @brief Apply one time step of energy-selective contact extraction.
*
* Delegates to ESC::extract(particles, pos, dt, rng), which removes carriers
* with kinetic energy in the ESC window at rate 1/tau_ex.
*
* @param esc ESC object (emcEnergySelectiveContact or compatible)
* @param idxType index of the particle type to extract from
* @param dt time step [s]
*/
template <class ESC>
void extractCarriers(ESC &esc, SizeType idxType, T dt) {
esc.extract(particles[idxType], positionsParticles[idxType], dt, rngs[0]);
}
/**
* @brief Like moveParticles but enforces Pauli exclusion (Lugli-Ferry).
*
* Runs SEQUENTIALLY (no OpenMP) because the shared Pauli grid would
* create data races under parallel access.
*
* Algorithm per scatter event:
* 1. Save particle state (k, energy, valley) before calling scatterParticle.
* 2. If the particle's k-vector changed, check pauli.isBlocked(newK).
* 3. If blocked → restore state (treat as self-scatter); increment
* pauli.nRejected.
* 4. If not blocked → call pauli.update(kOld, kNew); increment
* pauli.nScattered.
*
* The Pauli grid must be built (pauli.buildGrid) BEFORE calling this
* method each timestep; the grid is kept live during the step so
* successive scatters within one step see up-to-date occupancies.
*
* @tparam Pauli emcPauliExclusion<T> or compatible occupancy-grid type
* @param tStep simulation time step [s]
* @param idxType index of the particle type to move
* @param pauli Pauli exclusion grid (built externally; mutated in-place)
*/
template <class Pauli>
void moveParticleTypeWithBandFilling(T tStep, SizeType idxType, Pauli &pauli) {
auto &type = idxTypeToPartType.at(idxType);
if (!type->isMoved())
return;
// Rebuild occupancy grid from current particle positions so the
// initial state for this timestep is consistent with any particles
// added, removed, or scattered by preceding steps (recombination, ESC).
pauli.buildGrid(particles[idxType]);
pauli.resetCounters();
auto force = scale(appliedField, type->getCharge());
auto &currRNG = rngs[0]; // sequential — single RNG
for (SizeType idxPart = 0; idxPart < getNrParticles(idxType); idxPart++) {
auto &particle = particles[idxType][idxPart];
auto &pos = positionsParticles[idxType][idxPart];
auto valley = type->getValley(particle.valley);
driftParticle(std::min(particle.tau, tStep), particle, valley, pos, force);
T tRemaining = tStep - particle.tau;
while (tRemaining > 0) {
// Save state before scatter
auto kOld = particle.k;
T eOld = particle.energy;
auto valleyOld = particle.valley;
type->scatterParticle(particle, currRNG);
// Check if k actually changed (scatterParticle may self-scatter)
bool kChanged = (particle.k[0] != kOld[0] ||
particle.k[1] != kOld[1] ||
particle.k[2] != kOld[2]);
if (kChanged) {
pauli.nScattered++;
if (pauli.isBlocked(particle.k)) {
// Reject scatter → restore pre-scatter state
particle.k = kOld;
particle.energy = eOld;
particle.valley = valleyOld;
pauli.nRejected++;
} else {
pauli.update(kOld, particle.k);
}
}
T newTau = type->getNewTau(particle.valley, particle.region, currRNG);
particle.tau += newTau;
valley = type->getValley(particle.valley);
driftParticle(std::min(tRemaining, newTau), particle, valley, pos, force);
tRemaining -= newTau;
}
particle.tau -= tStep;
// Handle grain scattering (not Pauli-gated — grain boundary is classical)
particle.grainTau -= tStep;
if (particle.grainTau <= 0) {
type->scatterParticleAtGrain(particle, currRNG);
particle.grainTau = type->getNewGrainTau(currRNG);
}
}
}
/**
* @brief Like moveParticleTypeWithBandFilling but for a MULTIVALLEY model,
* using a per-valley/per-subvalley Pauli grid (emcMultiValleyPauliExclusion).
*
* The Pauli check/update are keyed by (valley, subValley, k) so that band
* filling is applied within each valley's own Fermi sea (the analytic model
* measures k from each valley's minimum). Runs SEQUENTIALLY.
*
* @tparam Pauli emcMultiValleyPauliExclusion<T> or compatible
*/
template <class Pauli>
void moveParticleTypeWithMultiValleyBandFilling(T tStep, SizeType idxType,
Pauli &pauli) {
auto &type = idxTypeToPartType.at(idxType);
if (!type->isMoved())
return;
pauli.buildGrid(particles[idxType]);
pauli.resetCounters();
auto force = scale(appliedField, type->getCharge());
auto &currRNG = rngs[0];
for (SizeType idxPart = 0; idxPart < getNrParticles(idxType); idxPart++) {
auto &particle = particles[idxType][idxPart];
auto &pos = positionsParticles[idxType][idxPart];
auto valley = type->getValley(particle.valley);
driftParticle(std::min(particle.tau, tStep), particle, valley, pos, force);
T tRemaining = tStep - particle.tau;
while (tRemaining > 0) {
auto kOld = particle.k;
T eOld = particle.energy;
auto valleyOld = particle.valley;
auto subOld = particle.subValley;
type->scatterParticle(particle, currRNG);
bool kChanged =
(particle.k[0] != kOld[0] || particle.k[1] != kOld[1] ||
particle.k[2] != kOld[2]);
if (kChanged) {
pauli.nScattered++;
if (pauli.isBlocked(particle.valley, particle.subValley, particle.k)) {
// reject -> restore pre-scatter state (self-scatter)
particle.k = kOld;
particle.energy = eOld;
particle.valley = valleyOld;
particle.subValley = subOld;
pauli.nRejected++;
} else {
pauli.update(valleyOld, subOld, kOld, particle.valley,
particle.subValley, particle.k);
}
}
T newTau = type->getNewTau(particle.valley, particle.region, currRNG);
particle.tau += newTau;
valley = type->getValley(particle.valley);
driftParticle(std::min(tRemaining, newTau), particle, valley, pos, force);
tRemaining -= newTau;
}
particle.tau -= tStep;
particle.grainTau -= tStep;
if (particle.grainTau <= 0) {
type->scatterParticleAtGrain(particle, currRNG);
particle.grainTau = type->getNewGrainTau(currRNG);
}
}
}
//! Deletes all current particles.
void deleteParticles() {
for (const auto &[idxType, _] : idxTypeToPartType) {
particles[idxType].clear();
positionsParticles[idxType].clear();
}
}
private:
//! Helper that adds a particle of a specific type near the given coordinate
void addParticle(SizeType idxType, const SizeVec &coord, emcRNG &rng) {
positionsParticles[idxType].push_back(initParticlePos(
coord, device.getGridExtent(), device.getSpacing(), rng));
auto &partType = idxTypeToPartType.at(idxType);
if (partType->isMoved()) {
emcParticle<T> part;
part = partType->generateInitialParticle(coord, device, rng);
particles[idxType].push_back(part);
}
}
//! Helper that moves particles and adapts the position if particle
//! leaves device domain (uses periodic BC)
void driftParticle(T dt, emcParticle<T> &part,
const emcAbstractValley<T> *valley,
std::array<T, Dim> &pos, const std::array<T, 3> &force) {
drift(dt, part, valley, pos, force);
auto maxPos = device.getMaxPos();
std::transform(pos.begin(), pos.end(), maxPos.begin(), pos.begin(),
[](auto currPos, auto maxPos) {
if (currPos < 0)
return currPos + maxPos;
if (currPos > maxPos)
return currPos - maxPos;
return currPos;
});
}
};
#endif // BASIC_BULK_PARTICLE_HANDLER_HPP