-
Notifications
You must be signed in to change notification settings - Fork 11
/
Simulation.ts
196 lines (182 loc) · 6.18 KB
/
Simulation.ts
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
import _ from 'lodash'
import Operator from './Operator'
import Frame from './Frame'
import { generateOperators } from './Elements'
import { weightedRandomInt, startingPolarization, startingDirection } from './helpers'
import { IAbsorption, IGrid, ICell, IIndicator, IXYOperator, IParticle, Elem } from './interfaces'
/**
* Generate the laser indicator from the grid laser cell
* @returns laserIndicator
*/
export function generateLaserIndicator(cells: ICell[]): IIndicator {
const lasers = cells.filter((cell: ICell) => cell.element === Elem.Laser)
if (lasers.length !== 1) {
throw new Error(`Cannot initialize QuantumSimulation. ${lasers.length} != 1 lasers.`)
}
const laserIndicator: IIndicator = {
x: lasers[0].x,
y: lasers[0].y,
direction: startingDirection(lasers[0].rotation),
polarization: startingPolarization(lasers[0].polarization),
}
return laserIndicator
}
/**
* SIMULATION CLASS
* Loads a grid
* Convert its elements into operators and merge them into a global operator.
* Generate simulation frames and absorptions.
*/
export default class Simulation {
readonly sizeX: number
readonly sizeY: number
public operators: IXYOperator[]
public globalOperator: Operator
public frames: Frame[]
public constructor(sizeX: number, sizeY: number, operators: IXYOperator[]) {
this.sizeX = sizeX
this.sizeY = sizeY
this.operators = operators
this.globalOperator = Frame.singlePhotonInteraction(this.sizeX, this.sizeY, this.operators)
this.frames = []
}
public static fromGrid(grid: IGrid): Simulation {
return new Simulation(grid.cols, grid.rows, generateOperators(grid.cells))
}
/**
* Initialize simulation from indicator
* @param indicator IIndicator
*/
public initializeFromIndicator(indicator: IIndicator): void {
this.frames = []
const frame = new Frame(this)
frame.addPhotonFromIndicator(indicator.x, indicator.y, indicator.direction, indicator.polarization)
this.frames.push(frame)
}
/**
* Get last simulation frame
* @returns last frame
*/
public get lastFrame(): Frame {
return this.frames[this.frames.length - 1]
}
/**
* Compute the next simulation frame
* @returns computed frame
*/
public nextFrame(): Frame {
if (this.frames.length === 0) {
throw new Error(`Cannot do nextFrame when there are no frames. initializeFromLaser or something else.`)
}
const frame = new Frame(this, this.lastFrame.vector)
frame.propagateAndInteract()
return frame
}
/**
* Compute next frames until probability threshold
* @param n default number of frames
* @param stopThreshold stop if probability below threshold
* @param logging toggle console debug
*/
public generateFrames(n = 20, stopThreshold = 1e-6, logging = false): void {
for (let i = 0; i < n; i += 1) {
const nextFrame = this.nextFrame()
this.frames.push(nextFrame)
if (this.lastFrame.probability < stopThreshold) {
break
}
}
if (logging) {
console.debug('POST-SIMULATION LOG:')
console.debug('probabilityPerFrame', this.probabilityPerFrame)
console.debug('totalAbsorptionPerFrame', this.totalAbsorptionPerFrame)
console.debug('totalAbsorptionPerTile', this.totalAbsorptionPerTile)
console.debug('An example of realization:')
// const randomSample = this.sampleRandomRealization();
// randomSample.statePerFrame.forEach((state) => console.debug(state.ketString()));
// console.debug(
// `Detected: in ${randomSample.fate.name} at (${randomSample.fate.x},${randomSample.fate.y})`
// );
}
}
/**
* Quantum state probability for each frame.
* @returns probability of frame
*/
public get probabilityPerFrame(): number[] {
return this.frames.map((frame): number => frame.probability)
}
/**
* Quantum state probability of absorption for each frame.
*/
public get totalAbsorptionPerFrame(): number[] {
return this.frames.map((frame): number => frame.totalProbabilityLoss)
}
/**
* Retrieve a list of all the particles for quantum path computation
* @returns particle list
*/
public get allParticles(): IParticle[] {
const result: IParticle[] = []
this.frames.forEach((frame): void => {
frame.particles.forEach((particle): void => {
result.push(particle)
})
})
return result
}
/**
* Total (summed over all frames) absorption per tile.
* {x: -1, y: -1, probability: ...} means falling of the board.
* @todo If needed, I we can add exact (off-board) coordinates of all lost photons.
* @returns E.g.
* [{x: 2, y: 1, probability: 0.25}, {x: 3, y: 5, probability: 0.25}, {x: -1, y: -1, probability: 0.25}]
*/
public get totalAbsorptionPerTile(): IAbsorption[] {
return _(this.frames)
.flatMap((frame): IAbsorption[] => frame.absorptions)
.groupBy((absorption: IAbsorption): string => `(${absorption.x}.${absorption.y})`)
.values()
.map(
(absorptions): IAbsorption => ({
x: absorptions[0].x,
y: absorptions[0].y,
probability: _.sumBy(absorptions, 'probability'),
}),
)
.value()
}
/**
* Create a random realization. So - the state is normalized, until a successful measurement.
* @remark So far for 1 particle.
* @todo Make it work for more particles.
* @todo Maybe make it another object? Or use QuantumFrame?
* @todo Kinda ugly return
*/
public sampleRandomRealization(): {
statePerFrame: Frame[]
probability: number
step: number
x: number
y: number
// eslint-disable-next-line indent
} {
// first, which frame
const lastId = weightedRandomInt(this.totalAbsorptionPerFrame, false)
// -1 if no measurement, and we need to deal with that
const lastFrameAbs = this.frames[lastId].absorptions
const absorptionId = weightedRandomInt(
lastFrameAbs.map((d): number => d.probability),
true,
)
const absorption = lastFrameAbs[absorptionId]
const states = this.frames.slice(0, lastId).map((frame): Frame => frame.normalize())
return {
statePerFrame: states,
probability: absorption.probability,
step: lastId,
x: absorption.x,
y: absorption.y,
}
}
}