forked from google-deepmind/deepmind-research
-
Notifications
You must be signed in to change notification settings - Fork 0
/
targets.py
622 lines (510 loc) · 20 KB
/
targets.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
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Reward targets that return target+actual."""
import abc
import math
from typing import List, Optional, Sequence, Tuple
import dataclasses
import numpy as np
import scipy
from fusion_tcv import fge_state
from fusion_tcv import named_array
from fusion_tcv import shape
from fusion_tcv import tcv_common
class TargetError(Exception):
"""For when a target can't be computed."""
@dataclasses.dataclass(frozen=True)
class Target:
actual: float
target: float
@classmethod
def invalid(cls):
"""This target is invalid and should be ignored. Equivalent to weight=0."""
return cls(float("nan"), float("nan"))
class AbstractTarget(abc.ABC):
"""Measure something about the simulation, with a target and actual value."""
@property
def name(self) -> str:
"""Returns a name for the target."""
return self.__class__.__name__
@abc.abstractproperty
def outputs(self) -> int:
"""Return the number of outputs this produces."""
@abc.abstractmethod
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
"""Returns a list of targets."""
@dataclasses.dataclass(frozen=True)
class AbstractSingleValuePerDomainTarget(AbstractTarget):
"""Base class for single value per plasma domain targets."""
target: Optional[Sequence[float]] = None
indices: List[int] = dataclasses.field(default_factory=lambda: [0])
def __post_init__(self):
if self.indices not in ([0], [1], [0, 1]):
raise ValueError(
f"Invalid indices: {self.indices}, must be [0], [1] or [0, 1].")
if self.target and len(self.target) != len(self.indices):
raise ValueError("Wrong number of targets.")
@property
def outputs(self) -> int:
return len(self.indices)
@property
def name(self) -> str:
return f"{super().name}: " + ",".join(str(i) for i in self.indices)
@dataclasses.dataclass(frozen=True)
class R(AbstractSingleValuePerDomainTarget):
"""Target for R."""
def __call__(self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
r_d, _, _ = state.rzip_d
if self.target is None:
return [Target(r_d[idx], references["R"][idx]) for idx in self.indices]
else:
return [Target(r_d[idx], target)
for idx, target in zip(self.indices, self.target)]
@dataclasses.dataclass(frozen=True)
class Z(AbstractSingleValuePerDomainTarget):
"""Target for Z."""
def __call__(self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
_, z_d, _ = state.rzip_d
if self.target is None:
return [Target(z_d[idx], references["Z"][idx]) for idx in self.indices]
else:
return [Target(z_d[idx], target)
for idx, target in zip(self.indices, self.target)]
@dataclasses.dataclass(frozen=True)
class Ip(AbstractSingleValuePerDomainTarget):
"""Target for Ip."""
def __call__(self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
_, _, ip_d = state.rzip_d
if self.target is None:
return [Target(ip_d[idx], references["Ip"][idx]) for idx in self.indices]
else:
return [Target(ip_d[idx], target)
for idx, target in zip(self.indices, self.target)]
class OHCurrentsClose(AbstractTarget):
"""Target for keeping OH currents close."""
@property
def outputs(self) -> int:
return 1
def __call__(self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
oh_coil_currents = state.get_coil_currents_by_type("OH")
diff = abs(oh_coil_currents[0] - oh_coil_currents[1])
return [Target(diff, 0)]
class EFCurrents(AbstractTarget):
"""EFCurrents, useful for avoiding stuck coils."""
@property
def outputs(self) -> int:
return 16
def __call__(self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
currents = np.concatenate([state.get_coil_currents_by_type("E"),
state.get_coil_currents_by_type("F")])
return [Target(c, 0) for c in currents]
@dataclasses.dataclass(frozen=True)
class VoltageOOB(AbstractTarget):
"""Target for how much the voltages exceed the bounds."""
relative: bool = True
@property
def outputs(self) -> int:
return tcv_common.NUM_ACTIONS
def __call__(self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
bounds = tcv_common.action_spec()
excess = (np.maximum(bounds.minimum - voltages, 0) +
np.maximum(voltages - bounds.maximum, 0))
if self.relative:
excess /= (bounds.maximum - bounds.minimum)
return [Target(v, 0) for v in excess]
@dataclasses.dataclass(frozen=True)
class ShapeElongation(AbstractSingleValuePerDomainTarget):
"""Try to keep the elongation close to the references."""
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.target is not None:
targets = self.target
else:
targets = references["kappa"][self.indices]
return [Target(state.elongation[i], target)
for i, target in zip(self.indices, targets)]
@dataclasses.dataclass(frozen=True)
class ShapeTriangularity(AbstractSingleValuePerDomainTarget):
"""Try to keep the triangularity close to the references."""
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.target is not None:
targets = self.target
else:
targets = references["delta"][self.indices]
return [Target(state.triangularity[i], target)
for i, target in zip(self.indices, targets)]
@dataclasses.dataclass(frozen=True)
class ShapeRadius(AbstractSingleValuePerDomainTarget):
"""Try to keep the shape radius close to the references."""
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.target is not None:
targets = self.target
else:
targets = references["radius"][self.indices]
return [Target(state.radius[i], target)
for i, target in zip(self.indices, targets)]
@dataclasses.dataclass(frozen=True)
class AbstractPointsTarget(AbstractTarget):
"""Base class for shape point targets."""
points: Optional[shape.ShapePoints] = None
ref_name: Optional[str] = None
num_points: Optional[int] = None
def __post_init__(self):
if self.points is not None:
return
elif self.ref_name is None:
raise ValueError("Must specify points or ref_name")
else:
ref_name = f"{self.ref_name}_r"
if ref_name not in tcv_common.REF_RANGES:
raise ValueError(f"{self.ref_name} is invalid.")
elif (self.num_points is not None and
self.num_points > tcv_common.REF_RANGES.count(ref_name)):
raise ValueError(
(f"Requesting more points ({self.num_points}) than {self.ref_name} "
"provides."))
@property
def outputs(self) -> int:
return len(self.points) if self.points is not None else self.num_points
def _target_points(
self, references: named_array.NamedArray) -> shape.ShapePoints:
if self.points is not None:
return self.points
else:
return shape.points_from_references(
references, self.ref_name, self.num_points)
def splined_lcfs_points(
state: fge_state.FGEState,
num_points: int,
domain: int = 0) -> shape.ShapePoints:
"""Return a smooth lcfs, cleaning FGE x-point artifacts."""
points = state.get_lcfs_points(domain)
x_point = (shape.Point(*state.limit_point_d[domain])
if state.is_diverted_d[domain] else None)
if x_point is not None:
x_points = [x_point]
# Drop points near the x-point due to noise in the shape projection near
# the x-point.
points = [p for p in points if shape.dist(p, x_point) > 0.1]
points.append(x_point)
points = shape.sort_by_angle(points)
else:
x_points = []
return shape.spline_interpolate_points(points, num_points, x_points)
@dataclasses.dataclass(frozen=True)
class ShapeLCFSDistance(AbstractPointsTarget):
"""Try to keep the shape close to the references.
Check the distance from the target shape points to the smooth LCFS.
"""
ref_name: str = dataclasses.field(default="shape", init=False)
domain: int = dataclasses.field(default=0, init=False)
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
lcfs = splined_lcfs_points(state, 90, self.domain)
outputs = []
for p in self._target_points(references):
if p.r == 0: # For invalid/changing number of points.
outputs.append(Target.invalid())
continue
dist = shape.dist_point_to_surface(np.array(lcfs), np.array(p))
outputs.append(Target(dist, 0))
return outputs
def flux_at_points(state: fge_state.FGEState, points: np.ndarray) -> np.ndarray:
"""Return the normalized interpolated flux values at a set of points."""
# Normalized flux such that the LCFS has a value of 1, 0 in the middle,
# and bigger than 1 farther out.
normalized_flux = ( # (LY.Fx - LY.FA) / (LY.FB - LY.FA)
(state.flux - state.magnetic_axis_flux_strength) /
(state.lcfs_flux_strength - state.magnetic_axis_flux_strength)).T
smooth_flux = scipy.interpolate.RectBivariateSpline(
np.squeeze(state.r_coordinates),
np.squeeze(state.z_coordinates),
normalized_flux)
return smooth_flux(points[:, 0], points[:, 1], grid=False)
@dataclasses.dataclass(frozen=True)
class ShapeNormalizedLCFSFlux(AbstractPointsTarget):
"""Try to keep the shape close to the references using flux.
Check the normalized flux values at points along the target shape. This works
in flux space, not linear distance, so may encourage smaller plasmas than the
distance based shape rewards.
"""
ref_name: str = dataclasses.field(default="shape1", init=False)
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
outputs = []
for p in self._target_points(references):
if p.r == 0: # For invalid/changing number of points.
outputs.append(Target.invalid())
else:
outputs.append(Target(
flux_at_points(state, np.array([p]))[0], 1))
return outputs
@dataclasses.dataclass(frozen=True)
class LegsNormalizedFlux(ShapeNormalizedLCFSFlux):
"""Try to keep the legs references close to the LCFS."""
ref_name: str = dataclasses.field(default="legs", init=False)
@dataclasses.dataclass(frozen=True)
class AbstractXPointTarget(AbstractPointsTarget):
"""Base class for x-point targets."""
ref_name: str = dataclasses.field(default="x_points", init=False)
@dataclasses.dataclass(frozen=True)
class XPointFluxGradient(AbstractXPointTarget):
"""Keep target points as an X point by attempting 0 flux gradient."""
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
eps = 0.01
targets = []
for point in self._target_points(references):
if point.r == 0: # For invalid/changing number of points.
targets.append(Target.invalid())
continue
diff_points = np.array([
[point.r - eps, point.z],
[point.r + eps, point.z],
[point.r, point.z - eps],
[point.r, point.z + eps],
])
flux_values = flux_at_points(state, diff_points)
diff = ((np.abs(flux_values[0] - flux_values[1]) / (2 * eps)) +
(np.abs(flux_values[2] - flux_values[3]) / (2 * eps)))
targets.append(Target(diff, 0))
return targets
def _dist(p1: shape.Point, p2: shape.Point):
return math.hypot(p1.r - p2.r, p1.z - p2.z)
def _min_dist(pt: shape.Point, points: shape.ShapePoints,
min_dist: float) -> Tuple[Optional[int], float]:
index = None
for i, point in enumerate(points):
dist = _dist(pt, point)
if dist < min_dist:
index = i
min_dist = dist
return index, min_dist
@dataclasses.dataclass(frozen=True)
class XPointDistance(AbstractXPointTarget):
"""Keep target points as an X point by attempting to minimize distance.
This assigns the x-points to targets without replacement. The first target
will get the distance to the nearest x-point. The second target will get the
closest, but ignoring the one assigned to the first target point. If none are
within `max_dist`, then no x-point is assigned and that distance will be
returned.
It may be worth switching to a fancier algorithm that tries to minimize the
total distance between targets and x-points, but that's slower, and we may
actually care about some x-points more (eg a diverted point is more
important than one farther away).
"""
max_dist: float = 0.2
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
x_points = state.x_points
targets = []
for target_point in self._target_points(references):
if target_point.r == 0: # For invalid/changing number of points.
targets.append(Target.invalid())
continue
index, min_dist = _min_dist(target_point, x_points, self.max_dist)
if index is not None:
x_points.pop(index)
targets.append(Target(min_dist, 0))
return targets
@dataclasses.dataclass(frozen=True)
class XPointFar(AbstractXPointTarget):
"""Keep extraneous x-points far away from the LCFS.
Returns the distance from the LCFS to any true x-point that is far from a
target x-point.
This assigns the x-points to targets without replacement. The first target
will get the distance to the nearest x-point. The second target will get the
closest, but ignoring the one assigned to the first target point. If none are
within `max_dist`, then no x-point is assigned and that distance will be
returned.
It may be worth switching to a fancier algorithm that tries to minimize the
total distance between targets and x-points, but that's slower, and we may
actually care about some x-points more (eg a diverted point is more
important than one farther away).
"""
max_dist: float = 0.2
domain: int = 0
diverted: Optional[shape.Diverted] = None
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.diverted is not None:
target = self.diverted
else:
target = shape.Diverted.from_refs(references)
if target == shape.Diverted.ANY:
return [] # Don't care.
x_points = state.x_points
# Filter out x-points that are near target x-points.
for target_point in self._target_points(references):
if target_point.r == 0: # For invalid/changing number of points.
continue
index, _ = _min_dist(target_point, x_points, self.max_dist)
if index is not None:
x_points.pop(index)
if not x_points:
return [Target(100, 0)] # No x-point gives full reward, not weight=0.
lcfs = state.get_lcfs_points(self.domain)
return [Target(shape.dist_point_to_surface(np.array(lcfs), np.array(p)), 0)
for p in x_points]
@dataclasses.dataclass(frozen=True)
class XPointNormalizedFlux(AbstractXPointTarget):
"""Keep the actual X points close to the LCFS.
Choose the x-points based on their distance to the target x-points.
"""
max_dist: float = 0.2
diverted: Optional[shape.Diverted] = None
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.diverted is not None:
diverted = self.diverted
else:
diverted = shape.Diverted.from_refs(references)
x_points = state.x_points
fluxes = list(flux_at_points(state, np.array(x_points).reshape((-1, 2))))
targets = []
# We should probably minimize the overall distance between targets and
# x-points, but the algorithm is complicated, so instead be greedy and
# assume they're given in priority order, or farther apart than max_dist.
for target_point in self._target_points(references):
if target_point.r == 0 or diverted != shape.Diverted.DIVERTED:
# For invalid/changing number of points.
targets.append(Target.invalid())
continue
index, _ = _min_dist(target_point, x_points, self.max_dist)
if index is not None:
targets.append(Target(fluxes[index], 1))
x_points.pop(index)
fluxes.pop(index)
else:
targets.append(Target(0, 1))
return targets
@dataclasses.dataclass(frozen=True)
class XPointCount(AbstractTarget):
"""Target for number of x-points. Useful to avoid more than you want."""
target: Optional[int] = None
@property
def outputs(self) -> int:
return 1
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.target is not None:
target = self.target
else:
target_points = shape.points_from_references(
references, "x_points", tcv_common.REF_RANGES.count("x_points_r"))
target = sum(1 for p in target_points if p.r != 0)
return [Target(len(state.x_points), target)]
@dataclasses.dataclass(frozen=True)
class Diverted(AbstractTarget):
"""Target for whether the plasma is diverted by an x-point."""
diverted: Optional[shape.Diverted] = None
@property
def outputs(self) -> int:
return 1
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.diverted is not None:
target = self.diverted
else:
target = shape.Diverted.from_refs(references)
actual = 1 if state.is_diverted_d[0] else 0
if target == shape.Diverted.ANY:
return [Target.invalid()] # Don't care.
elif target == shape.Diverted.DIVERTED:
return [Target(actual, 1)]
return [Target(actual, 0)]
@dataclasses.dataclass(frozen=True)
class LimitPoint(AbstractPointsTarget):
"""Target for where the plasma is limited, either on the wall or x-point."""
ref_name: str = dataclasses.field(default="limit_point", init=False)
num_points: int = dataclasses.field(default=1, init=False)
diverted: Optional[shape.Diverted] = None
max_dist: float = 1
def __call__(
self,
voltages: np.ndarray,
state: fge_state.FGEState,
references: named_array.NamedArray) -> List[Target]:
if self.diverted is not None:
diverted_target = self.diverted
else:
diverted_target = shape.Diverted.from_refs(references)
if diverted_target == shape.Diverted.ANY:
return [Target.invalid()]
target_point = self._target_points(references)[0]
if target_point.r == 0:
return [Target.invalid()]
limit_point = shape.Point(*state.limit_point_d[0])
dist = np.hypot(*(target_point - limit_point))
is_diverted = state.is_diverted_d[0]
if diverted_target == shape.Diverted.DIVERTED:
return [Target((dist if is_diverted else self.max_dist), 0)]
return [Target((dist if not is_diverted else self.max_dist), 0)]