Skip to content

scan

Scanning mechanics

ScanVariable dataclass

Scan variable container

Source code in process/core/scan.py
32
33
34
35
36
37
38
@dataclass
class ScanVariable:
    """Scan variable container"""

    number: int
    area: Area = field(repr=False)
    _out_name_: str | None = None

number instance-attribute

area = field(repr=False) class-attribute instance-attribute

Area

Bases: Enum

Scan variable data structure area shorthand

this mirrors data_structure.area

Source code in process/core/scan.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Area(Enum):
    """Scan variable data structure area shorthand

    this mirrors data_structure.area
    """

    P = "physics"
    D = "divertor"
    C = "constraints"
    T = "tfcoil"
    TR = "rebco"
    CD = "current_drive"
    NUM = "numerics"
    CST = "costs"
    IR = "impurity_radiation"
    B = "build"
    HT = "heat_transport"
    PF = "pf_coil"
    CS = "cs_fatigue"
    FWBS = "fwbs"

P = 'physics' class-attribute instance-attribute

D = 'divertor' class-attribute instance-attribute

C = 'constraints' class-attribute instance-attribute

T = 'tfcoil' class-attribute instance-attribute

TR = 'rebco' class-attribute instance-attribute

CD = 'current_drive' class-attribute instance-attribute

NUM = 'numerics' class-attribute instance-attribute

CST = 'costs' class-attribute instance-attribute

IR = 'impurity_radiation' class-attribute instance-attribute

B = 'build' class-attribute instance-attribute

HT = 'heat_transport' class-attribute instance-attribute

PF = 'pf_coil' class-attribute instance-attribute

CS = 'cs_fatigue' class-attribute instance-attribute

FWBS = 'fwbs' class-attribute instance-attribute

ScanVariables dataclass

Bases: ScanVariable, Enum

Scan variable options

Source code in process/core/scan.py
 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
class ScanVariables(ScanVariable, Enum):
    """Scan variable options"""

    @classmethod
    def _missing_(cls, value):
        if isinstance(value, int):
            for sv in cls:
                if sv.number == value:
                    return sv
            raise ProcessValueError("Illegal scan variable number", nwp=value)

        if isinstance(value, str):
            return cls[value.replace("(", "__").replace(")", "")]

        return super()._missing_(value)

    @DynamicClassAttribute
    def fname(self):
        """Full name"""
        if "__" in self.name:
            return self.name.replace("__", "(") + ")"
        return self.name

    @DynamicClassAttribute
    def out_name(self):
        """Output name"""
        if self._out_name_ is None:
            return self.fname
        return self._out_name_

    def set(self, data: DataStructure, sweep_val: float):
        """Set value of scan variable

        Raises
        ------
        ProcessValueError
            Scanning f_t_plant_available if i_plant_availability=1"

        """
        var_area = getattr(data, self.area.value)

        if (
            self.number == 22
            and AvailabilityModel(var_area.i_plant_availability)
            != AvailabilityModel.USER_INPUT
        ):
            raise ProcessValueError(
                "Do not scan f_t_plant_available if i_plant_availability=1"
            )

        if "__" in self.name:
            name, index = self.name.split("__")
            getattr(var_area, name)[int(index) - 1] = sweep_val
            if name == "f_nd_impurity_electrons":
                var_area.f_nd_impurity_electron_array[int(index - 1)] = sweep_val
        else:
            setattr(var_area, self.name, sweep_val)
            name = self.name

        self._data_ = getattr(var_area, name)
        self._description_ = get_dicts()["DICT_DESCRIPTIONS"][name]

    @DynamicClassAttribute
    def data(self):
        """Variable value

        Raises
        ------
        ValueError
            data not set
        """
        if hasattr(self, "_data_"):
            return self._data_
        raise ValueError("Data not available")

    @DynamicClassAttribute
    def description(self):
        """Variable description

        Raises
        ------
        ValueError
            description not set
        """
        if hasattr(self, "_description_"):
            return self._description_
        raise ValueError("Description not available")

    def get_val(self, mfile, scan):
        """Get value from mfile"""
        # TODO this will fail for boundu/l we should write the scan variable to
        # the mfile and use that directly (also replacign output names)
        return mfile.get(self.out_name, scan=scan)

    aspect = (1, Area.P)
    pflux_div_heat_load_max_mw = (2, Area.D)
    p_plant_electric_net_required_mw = (3, Area.C)
    hfact = (4, Area.P)
    j_tf_coil_full_area = (5, Area.T)
    pflux_fw_neutron_max_mw = (6, Area.C)
    beamfus0 = (7, Area.P)
    temp_plasma_electron_vol_avg_kev = (9, Area.P)
    boundu__15 = (10, Area.NUM)
    beta_norm_max = (11, Area.P)
    f_c_plasma_bootstrap_max = (12, Area.CD)
    boundu__10 = (13, Area.NUM)
    f_j_tf_wp_critical_max = (14, Area.C)  # TODO is this needed
    rmajor = (16, Area.P)
    b_tf_inboard_max = (17, Area.C, "b_tf_inboard_peak_symmetric")
    eta_cd_norm_hcd_primary_max = (18, Area.C)
    boundl__16 = (19, Area.NUM)
    t_burn_min = (20, Area.C)
    f_t_plant_available = (22, Area.CST)
    p_fusion_total_max_mw = (24, Area.C)
    kappa = (25, Area.P)
    triang = (26, Area.P)
    tbrmin = (27, Area.C)
    b_plasma_toroidal_on_axis = (28, Area.P)
    coreradius = (29, Area.IR)
    f_alpha_energy_confinement_min = (31, Area.C)
    epsvmc = (32, Area.NUM)
    boundu__129 = (38, Area.NUM)
    boundu__131 = (39, Area.NUM)
    boundu__135 = (40, Area.NUM)
    dr_blkt_outboard = (41, Area.B)
    f_nd_impurity_electrons__9 = (42, Area.IR)
    sig_tf_case_max = (44, Area.T)
    temp_tf_superconductor_margin_min = (45, Area.T)
    boundu__152 = (46, Area.NUM)
    n_tf_wp_pancakes = (48, Area.T)
    n_tf_wp_layers = (49, Area.T)
    f_nd_impurity_electrons__13 = (50, Area.IR)
    f_p_div_lower_separatrix = (51, Area.P)
    rad_fraction_sol = (52, Area.P)
    boundu__157 = (53, Area.NUM)
    b_crit_upper_nbti = (54, Area.T)
    dr_shld_inboard = (55, Area.B)
    p_cryo_plant_electric_max_mw = (56, Area.HT)
    boundl__2 = (57, Area.NUM)
    dr_fw_plasma_gap_inboard = (58, Area.B)
    dr_fw_plasma_gap_outboard = (59, Area.B)
    sig_tf_wp_max = (60, Area.T)
    copperaoh_m2_max = (61, Area.TR)
    coheof = (62, Area.PF)
    dr_cs = (63, Area.B)
    ohhghf = (64, Area.PF)
    n_cycle_min = (65, Area.CS)
    oh_steel_frac = (66, Area.PF)
    t_crack_vertical = (67, Area.CS)
    inlet_temp_liq = (68, Area.FWBS)
    outlet_temp_liq = (69, Area.FWBS)
    blpressure_liq = (70, Area.FWBS)
    n_liq_recirc = (71, Area.FWBS)
    bz_channel_conduct_liq = (72, Area.FWBS)
    pnuc_fw_ratio_dcll = (73, Area.FWBS)
    f_nuc_pow_bz_struct = (74, Area.FWBS)
    dx_fw_module = (75, Area.FWBS)
    eta_turbine = (76, Area.HT)
    startupratio = (77, Area.CST)
    fkind = (78, Area.CST)
    eta_ecrh_injector_wall_plug = (79, Area.CD)
    fcoolcp = (80, Area.T)
    n_tf_coil_turns = (81, Area.T)

aspect = (1, Area.P) class-attribute instance-attribute

pflux_div_heat_load_max_mw = (2, Area.D) class-attribute instance-attribute

p_plant_electric_net_required_mw = (3, Area.C) class-attribute instance-attribute

hfact = (4, Area.P) class-attribute instance-attribute

j_tf_coil_full_area = (5, Area.T) class-attribute instance-attribute

pflux_fw_neutron_max_mw = (6, Area.C) class-attribute instance-attribute

beamfus0 = (7, Area.P) class-attribute instance-attribute

temp_plasma_electron_vol_avg_kev = (9, Area.P) class-attribute instance-attribute

boundu__15 = (10, Area.NUM) class-attribute instance-attribute

beta_norm_max = (11, Area.P) class-attribute instance-attribute

f_c_plasma_bootstrap_max = (12, Area.CD) class-attribute instance-attribute

boundu__10 = (13, Area.NUM) class-attribute instance-attribute

f_j_tf_wp_critical_max = (14, Area.C) class-attribute instance-attribute

rmajor = (16, Area.P) class-attribute instance-attribute

b_tf_inboard_max = (17, Area.C, 'b_tf_inboard_peak_symmetric') class-attribute instance-attribute

eta_cd_norm_hcd_primary_max = (18, Area.C) class-attribute instance-attribute

boundl__16 = (19, Area.NUM) class-attribute instance-attribute

t_burn_min = (20, Area.C) class-attribute instance-attribute

f_t_plant_available = (22, Area.CST) class-attribute instance-attribute

p_fusion_total_max_mw = (24, Area.C) class-attribute instance-attribute

kappa = (25, Area.P) class-attribute instance-attribute

triang = (26, Area.P) class-attribute instance-attribute

tbrmin = (27, Area.C) class-attribute instance-attribute

b_plasma_toroidal_on_axis = (28, Area.P) class-attribute instance-attribute

coreradius = (29, Area.IR) class-attribute instance-attribute

f_alpha_energy_confinement_min = (31, Area.C) class-attribute instance-attribute

epsvmc = (32, Area.NUM) class-attribute instance-attribute

boundu__129 = (38, Area.NUM) class-attribute instance-attribute

boundu__131 = (39, Area.NUM) class-attribute instance-attribute

boundu__135 = (40, Area.NUM) class-attribute instance-attribute

dr_blkt_outboard = (41, Area.B) class-attribute instance-attribute

f_nd_impurity_electrons__9 = (42, Area.IR) class-attribute instance-attribute

sig_tf_case_max = (44, Area.T) class-attribute instance-attribute

temp_tf_superconductor_margin_min = (45, Area.T) class-attribute instance-attribute

boundu__152 = (46, Area.NUM) class-attribute instance-attribute

n_tf_wp_pancakes = (48, Area.T) class-attribute instance-attribute

n_tf_wp_layers = (49, Area.T) class-attribute instance-attribute

f_nd_impurity_electrons__13 = (50, Area.IR) class-attribute instance-attribute

f_p_div_lower_separatrix = (51, Area.P) class-attribute instance-attribute

rad_fraction_sol = (52, Area.P) class-attribute instance-attribute

boundu__157 = (53, Area.NUM) class-attribute instance-attribute

b_crit_upper_nbti = (54, Area.T) class-attribute instance-attribute

dr_shld_inboard = (55, Area.B) class-attribute instance-attribute

p_cryo_plant_electric_max_mw = (56, Area.HT) class-attribute instance-attribute

boundl__2 = (57, Area.NUM) class-attribute instance-attribute

dr_fw_plasma_gap_inboard = (58, Area.B) class-attribute instance-attribute

dr_fw_plasma_gap_outboard = (59, Area.B) class-attribute instance-attribute

sig_tf_wp_max = (60, Area.T) class-attribute instance-attribute

copperaoh_m2_max = (61, Area.TR) class-attribute instance-attribute

coheof = (62, Area.PF) class-attribute instance-attribute

dr_cs = (63, Area.B) class-attribute instance-attribute

ohhghf = (64, Area.PF) class-attribute instance-attribute

n_cycle_min = (65, Area.CS) class-attribute instance-attribute

oh_steel_frac = (66, Area.PF) class-attribute instance-attribute

t_crack_vertical = (67, Area.CS) class-attribute instance-attribute

inlet_temp_liq = (68, Area.FWBS) class-attribute instance-attribute

outlet_temp_liq = (69, Area.FWBS) class-attribute instance-attribute

blpressure_liq = (70, Area.FWBS) class-attribute instance-attribute

n_liq_recirc = (71, Area.FWBS) class-attribute instance-attribute

bz_channel_conduct_liq = (72, Area.FWBS) class-attribute instance-attribute

pnuc_fw_ratio_dcll = (73, Area.FWBS) class-attribute instance-attribute

f_nuc_pow_bz_struct = (74, Area.FWBS) class-attribute instance-attribute

dx_fw_module = (75, Area.FWBS) class-attribute instance-attribute

eta_turbine = (76, Area.HT) class-attribute instance-attribute

startupratio = (77, Area.CST) class-attribute instance-attribute

fkind = (78, Area.CST) class-attribute instance-attribute

eta_ecrh_injector_wall_plug = (79, Area.CD) class-attribute instance-attribute

fcoolcp = (80, Area.T) class-attribute instance-attribute

n_tf_coil_turns = (81, Area.T) class-attribute instance-attribute

fname()

Full name

Source code in process/core/scan.py
79
80
81
82
83
84
@DynamicClassAttribute
def fname(self):
    """Full name"""
    if "__" in self.name:
        return self.name.replace("__", "(") + ")"
    return self.name

out_name()

Output name

Source code in process/core/scan.py
86
87
88
89
90
91
@DynamicClassAttribute
def out_name(self):
    """Output name"""
    if self._out_name_ is None:
        return self.fname
    return self._out_name_

set(data, sweep_val)

Set value of scan variable

Raises:

Type Description
ProcessValueError

Scanning f_t_plant_available if i_plant_availability=1"

Source code in process/core/scan.py
 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
def set(self, data: DataStructure, sweep_val: float):
    """Set value of scan variable

    Raises
    ------
    ProcessValueError
        Scanning f_t_plant_available if i_plant_availability=1"

    """
    var_area = getattr(data, self.area.value)

    if (
        self.number == 22
        and AvailabilityModel(var_area.i_plant_availability)
        != AvailabilityModel.USER_INPUT
    ):
        raise ProcessValueError(
            "Do not scan f_t_plant_available if i_plant_availability=1"
        )

    if "__" in self.name:
        name, index = self.name.split("__")
        getattr(var_area, name)[int(index) - 1] = sweep_val
        if name == "f_nd_impurity_electrons":
            var_area.f_nd_impurity_electron_array[int(index - 1)] = sweep_val
    else:
        setattr(var_area, self.name, sweep_val)
        name = self.name

    self._data_ = getattr(var_area, name)
    self._description_ = get_dicts()["DICT_DESCRIPTIONS"][name]

data()

Variable value

Raises:

Type Description
ValueError

data not set

Source code in process/core/scan.py
125
126
127
128
129
130
131
132
133
134
135
136
@DynamicClassAttribute
def data(self):
    """Variable value

    Raises
    ------
    ValueError
        data not set
    """
    if hasattr(self, "_data_"):
        return self._data_
    raise ValueError("Data not available")

description()

Variable description

Raises:

Type Description
ValueError

description not set

Source code in process/core/scan.py
138
139
140
141
142
143
144
145
146
147
148
149
@DynamicClassAttribute
def description(self):
    """Variable description

    Raises
    ------
    ValueError
        description not set
    """
    if hasattr(self, "_description_"):
        return self._description_
    raise ValueError("Description not available")

get_val(mfile, scan)

Get value from mfile

Source code in process/core/scan.py
151
152
153
154
155
def get_val(self, mfile, scan):
    """Get value from mfile"""
    # TODO this will fail for boundu/l we should write the scan variable to
    # the mfile and use that directly (also replacign output names)
    return mfile.get(self.out_name, scan=scan)

Scan

Perform a parameter scan using the Fortran scan module.

Source code in process/core/scan.py
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
class Scan:
    """Perform a parameter scan using the Fortran scan module."""

    def __init__(self, models: Model, solver: str, data: DataStructure):
        """Immediately run the run_scan() method.

        Parameters
        ----------
        models :
            Physics and engineering model objects
        solver :
            Which solver to use, as specified in solver.py
        data :
            Data structure object
        """
        self.models = models
        self.solver = solver
        self.data = data
        self.solver_handler = SolverHandler(models, solver, data)
        self.run_scan()

    def run_scan(self):
        """Call a solver over a range of values of one of the variables.

        This method calls the optimisation routine VMCON a number of times, by
        performing a sweep over a range of values of a particular variable. A
        number of output variable values are written to the MFILE.DAT file at
        each scan point, for plotting or other post-processing purposes.

        Raises
        ------
        ProcessValueError
            isweep value greater than IPNSCNS
        """
        if self.data.scan.isweep == 0:
            # Solve single problem, rather than an array of problems (scan)
            # doopt() can also run just an evaluation
            start_time = time.time()
            ifail = self.doopt()
            write_output_files(
                models=self.models,
                data=self.data,
                ifail=ifail,
                runtime=time.time() - start_time,
            )
            show_errors(constants.NOUT)
            return

        if self.data.scan.isweep > IPNSCNS:
            raise ProcessValueError(
                "Illegal value of isweep",
                isweep=self.data.scan.isweep,
                IPNSCNS=IPNSCNS,
            )

        if self.data.scan.scan_dim == 2:
            self.scan_2d()
        else:
            self.scan_1d()

    def doopt(self):
        """Run the optimiser or solver."""
        ifail = self.solver_handler.run()
        constraints.constraints_output(self.data, self.solver)

        return ifail

    def scan_1d(self):
        """Run a 1-D scan."""
        # initialise dict which will contain ifail values for each scan point
        scan_1d_ifail_dict = {}

        for iscan in range(1, self.data.scan.isweep + 1):
            self.scan_1d_write_point_header(iscan)
            start_time = time.time()
            ifail = self.doopt()
            scan_1d_ifail_dict[iscan] = ifail
            write_output_files(
                models=self.models,
                data=self.data,
                ifail=ifail,
                runtime=time.time() - start_time,
            )

            show_errors(constants.NOUT)
            logging_model_handler.clear_logs()

        # outvar now contains results
        self.scan_1d_write_plot(self.data.scan)
        print("Scan Convergence Summary \n")
        sweep_values = self.data.scan.sweep[: self.data.scan.isweep]
        nsweep_var = self.scan_select(
            self.data.scan.nsweep, self.data.scan.sweep, self.data.scan.isweep
        )
        converged_count = 0
        # offsets for aligning the converged/unconverged column
        max_sweep_value_length = len(str(np.max(sweep_values)).replace(".", ""))
        offsets = [
            max_sweep_value_length - len(str(sweep_val).replace(".", ""))
            for sweep_val in sweep_values
        ]
        for iscan in range(1, self.data.scan.isweep + 1):
            if scan_1d_ifail_dict[iscan] == 1:
                converged_count += 1
                print(
                    f"Scan {iscan:02d}: {nsweep_var.fname} = {sweep_values[iscan - 1]} "
                    + " " * offsets[iscan - 1]
                    + "\u001b[32mCONVERGED \u001b[0m"
                )
            else:
                print(
                    f"Scan {iscan:02d}: {nsweep_var.fname} = {sweep_values[iscan - 1]} "
                    + " " * offsets[iscan - 1]
                    + "\u001b[31mUNCONVERGED \u001b[0m"
                )
        converged_percentage = converged_count / self.data.scan.isweep * 100
        print(f"\nConvergence Percentage: {converged_percentage:.2f}%")

    def scan_2d(self):
        """Run a 2-D scan."""
        # Initialise intent(out) arrays
        self.scan_2d_init(self.data.scan)
        iscan = 1

        # initialise array which will contain ifail values for each scan point
        scan_2d_ifail_list = np.zeros(
            (NOUTVARS, IPNSCNS),
            dtype=np.float64,
            order="F",
        )
        for iscan_1 in range(1, self.data.scan.isweep + 1):
            for iscan_2 in range(1, self.data.scan.isweep_2 + 1):
                self.scan_2d_write_point_header(iscan, iscan_1, iscan_2)
                start_time = time.time()
                ifail = self.doopt()
                write_output_files(
                    models=self.models,
                    data=self.data,
                    ifail=ifail,
                    runtime=time.time() - start_time,
                )

                show_errors(constants.NOUT)
                logging_model_handler.clear_logs()
                scan_2d_ifail_list[iscan_1][iscan_2] = ifail
                iscan += 1

        print("Scan Convergence Summary\n")
        sweep_1_values = self.data.scan.sweep[: self.data.scan.isweep]
        sweep_2_values = self.data.scan.sweep_2[: self.data.scan.isweep_2]
        nsweep_var = self.scan_select(
            self.data.scan.nsweep, self.data.scan.sweep, self.data.scan.isweep
        )
        nsweep_2_var = self.scan_select(
            self.data.scan.nsweep_2, self.data.scan.sweep_2, self.data.scan.isweep_2
        )
        converged_count = 0
        scan_point = 1
        # offsets for aligning the converged/unconverged column
        max_sweep1_value_length = len(str(np.max(sweep_1_values)).replace(".", ""))
        max_sweep2_value_length = len(str(np.max(sweep_2_values)).replace(".", ""))
        offsets = np.zeros(
            (self.data.scan.isweep, self.data.scan.isweep_2), dtype=int, order="F"
        )
        for count1, sweep1 in enumerate(sweep_1_values):
            for count2, sweep2 in enumerate(sweep_2_values):
                offsets[count1][count2] = (
                    max_sweep1_value_length
                    - len(str(sweep1).replace(".", ""))
                    + max_sweep2_value_length
                    - len(str(sweep2).replace(".", ""))
                )

        for iscan_1 in range(1, self.data.scan.isweep + 1):
            for iscan_2 in range(1, self.data.scan.isweep_2 + 1):
                if scan_2d_ifail_list[iscan_1][iscan_2] == 1:
                    converged_count += 1
                    print(
                        (
                            f"Scan {scan_point:02d}: ({nsweep_var.fname} = "
                            f"{sweep_1_values[iscan_1 - 1]}, {nsweep_2_var.fname} "
                            f"= {sweep_2_values[iscan_2 - 1]}) "
                        )
                        + " " * offsets[iscan_1 - 1][iscan_2 - 1]
                        + "\u001b[32mCONVERGED \u001b[0m"
                    )
                    scan_point += 1
                else:
                    print(
                        (
                            f"Scan {scan_point:02d}: ({nsweep_var.fname} = "
                            f"{sweep_1_values[iscan_1 - 1]}, {nsweep_2_var.fname} = "
                            f"{sweep_2_values[iscan_2 - 1]}) "
                        )
                        + " " * offsets[iscan_1 - 1][iscan_2 - 1]
                        + "\u001b[31mUNCONVERGED \u001b[0m"
                    )
                    scan_point += 1
        converged_percentage = (
            converged_count / (self.data.scan.isweep * self.data.scan.isweep_2) * 100
        )
        print(f"\nConvergence Percentage: {converged_percentage:.2f}%")

    @staticmethod
    def scan_2d_init(scan_data: ScanData):
        """Scan 2d initialisation"""
        process_output.ovarre(
            constants.MFILE,
            "Number of first variable scan points",
            "(isweep)",
            scan_data.isweep,
        )
        process_output.ovarre(
            constants.MFILE,
            "Number of second variable scan points",
            "(isweep_2)",
            scan_data.isweep_2,
        )
        process_output.ovarre(
            constants.MFILE,
            "Scanning first variable number",
            "(nsweep)",
            scan_data.nsweep,
        )
        process_output.ovarre(
            constants.MFILE,
            "Scanning second variable number",
            "(nsweep_2)",
            scan_data.nsweep_2,
        )
        process_output.ovarre(
            constants.MFILE,
            "Scanning second variable number",
            "(nsweep_2)",
            scan_data.nsweep_2,
        )
        process_output.ovarre(
            constants.MFILE,
            "Scanning second variable number",
            "(nsweep_2)",
            scan_data.nsweep_2,
        )

    def scan_1d_write_point_header(self, iscan: int):
        """Scan 1d header"""
        self.data.globals.iscan_global = iscan
        sv = self.scan_select(self.data.scan.nsweep, self.data.scan.sweep, iscan)

        self.data.globals.vlabel = sv.fname
        self.data.globals.xlabel = sv.description

        process_output.oblnkl(constants.NOUT)
        process_output.ostars(constants.NOUT, 110)

        process_output.write(
            constants.NOUT,
            f"***** Scan point {iscan} of {self.data.scan.isweep} : "
            f"{self.data.globals.xlabel}"
            f", {self.data.globals.vlabel} = {self.data.scan.sweep[iscan - 1]} "
            "*****",
        )
        process_output.ostars(constants.NOUT, 110)
        process_output.oblnkl(constants.MFILE)
        process_output.ovarre(constants.MFILE, "Scan point number", "(iscan)", iscan)

        print(
            f"Starting scan point {iscan} of {self.data.scan.isweep} : "
            f"{self.data.globals.xlabel} , {self.data.globals.vlabel}"
            f" = {self.data.scan.sweep[iscan - 1]}"
        )

    def scan_2d_write_point_header(self, iscan, iscan_1, iscan_2):
        """Scan 2d header"""
        iscan_r = self.data.scan.isweep_2 - iscan_2 + 1 if iscan_1 % 2 == 0 else iscan_2

        # Makes iscan available globally (read-only)
        self.data.globals.iscan_global = iscan
        sv_1 = self.scan_select(self.data.scan.nsweep, self.data.scan.sweep, iscan_1)

        self.data.globals.vlabel = sv_1.fname
        self.data.globals.xlabel = sv_1.data.description

        sv_2 = self.scan_select(self.data.scan.nsweep_2, self.data.scan.sweep_2, iscan_r)

        self.data.globals.vlabel_2 = sv_2.fname
        self.data.globals.xlabel_2 = sv_2.data.description

        process_output.oblnkl(constants.NOUT)
        process_output.ostars(constants.NOUT, 110)

        process_output.write(
            constants.NOUT,
            f"***** 2D Scan point {iscan} of "
            f"{self.data.scan.isweep * self.data.scan.isweep_2} : "
            f"{self.data.globals.vlabel} = {self.data.scan.sweep[iscan_1 - 1]} and"
            f" {self.data.globals.vlabel_2} = {self.data.scan.sweep_2[iscan_r - 1]} "
            "*****",
        )
        process_output.ostars(constants.NOUT, 110)
        process_output.oblnkl(constants.MFILE)
        process_output.ovarre(constants.MFILE, "Scan point number", "(iscan)", iscan)

        print(
            f"Starting scan point {iscan}:  {self.data.globals.xlabel}, "
            f"{self.data.globals.vlabel} = {self.data.scan.sweep[iscan_1 - 1]}"
            f" and {self.data.globals.xlabel_2}, "
            f"{self.data.globals.vlabel_2} = {self.data.scan.sweep_2[iscan_r - 1]} "
        )

        return iscan_r

    @staticmethod
    def scan_1d_write_plot(scan_data: ScanData):
        """Scan 1d plotter"""
        if scan_data.first_call_1d:
            process_output.ovarre(
                constants.MFILE,
                "Number of scan points",
                "(isweep)",
                scan_data.isweep,
            )
            process_output.ovarre(
                constants.MFILE,
                "Scanning variable number",
                "(nsweep)",
                scan_data.nsweep,
            )

            scan_data.first_call_1d = False

    def scan_select(self, nsweep, sweep, iscan) -> ScanVariables:
        """Select a scan"""
        sv = ScanVariables(nsweep)
        sv.set(self.data, sweep[iscan - 1])
        return sv

models = models instance-attribute

solver = solver instance-attribute

data = data instance-attribute

solver_handler = SolverHandler(models, solver, data) instance-attribute

run_scan()

Call a solver over a range of values of one of the variables.

This method calls the optimisation routine VMCON a number of times, by performing a sweep over a range of values of a particular variable. A number of output variable values are written to the MFILE.DAT file at each scan point, for plotting or other post-processing purposes.

Raises:

Type Description
ProcessValueError

isweep value greater than IPNSCNS

Source code in process/core/scan.py
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
def run_scan(self):
    """Call a solver over a range of values of one of the variables.

    This method calls the optimisation routine VMCON a number of times, by
    performing a sweep over a range of values of a particular variable. A
    number of output variable values are written to the MFILE.DAT file at
    each scan point, for plotting or other post-processing purposes.

    Raises
    ------
    ProcessValueError
        isweep value greater than IPNSCNS
    """
    if self.data.scan.isweep == 0:
        # Solve single problem, rather than an array of problems (scan)
        # doopt() can also run just an evaluation
        start_time = time.time()
        ifail = self.doopt()
        write_output_files(
            models=self.models,
            data=self.data,
            ifail=ifail,
            runtime=time.time() - start_time,
        )
        show_errors(constants.NOUT)
        return

    if self.data.scan.isweep > IPNSCNS:
        raise ProcessValueError(
            "Illegal value of isweep",
            isweep=self.data.scan.isweep,
            IPNSCNS=IPNSCNS,
        )

    if self.data.scan.scan_dim == 2:
        self.scan_2d()
    else:
        self.scan_1d()

doopt()

Run the optimiser or solver.

Source code in process/core/scan.py
288
289
290
291
292
293
def doopt(self):
    """Run the optimiser or solver."""
    ifail = self.solver_handler.run()
    constraints.constraints_output(self.data, self.solver)

    return ifail

scan_1d()

Run a 1-D scan.

Source code in process/core/scan.py
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
def scan_1d(self):
    """Run a 1-D scan."""
    # initialise dict which will contain ifail values for each scan point
    scan_1d_ifail_dict = {}

    for iscan in range(1, self.data.scan.isweep + 1):
        self.scan_1d_write_point_header(iscan)
        start_time = time.time()
        ifail = self.doopt()
        scan_1d_ifail_dict[iscan] = ifail
        write_output_files(
            models=self.models,
            data=self.data,
            ifail=ifail,
            runtime=time.time() - start_time,
        )

        show_errors(constants.NOUT)
        logging_model_handler.clear_logs()

    # outvar now contains results
    self.scan_1d_write_plot(self.data.scan)
    print("Scan Convergence Summary \n")
    sweep_values = self.data.scan.sweep[: self.data.scan.isweep]
    nsweep_var = self.scan_select(
        self.data.scan.nsweep, self.data.scan.sweep, self.data.scan.isweep
    )
    converged_count = 0
    # offsets for aligning the converged/unconverged column
    max_sweep_value_length = len(str(np.max(sweep_values)).replace(".", ""))
    offsets = [
        max_sweep_value_length - len(str(sweep_val).replace(".", ""))
        for sweep_val in sweep_values
    ]
    for iscan in range(1, self.data.scan.isweep + 1):
        if scan_1d_ifail_dict[iscan] == 1:
            converged_count += 1
            print(
                f"Scan {iscan:02d}: {nsweep_var.fname} = {sweep_values[iscan - 1]} "
                + " " * offsets[iscan - 1]
                + "\u001b[32mCONVERGED \u001b[0m"
            )
        else:
            print(
                f"Scan {iscan:02d}: {nsweep_var.fname} = {sweep_values[iscan - 1]} "
                + " " * offsets[iscan - 1]
                + "\u001b[31mUNCONVERGED \u001b[0m"
            )
    converged_percentage = converged_count / self.data.scan.isweep * 100
    print(f"\nConvergence Percentage: {converged_percentage:.2f}%")

scan_2d()

Run a 2-D scan.

Source code in process/core/scan.py
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
def scan_2d(self):
    """Run a 2-D scan."""
    # Initialise intent(out) arrays
    self.scan_2d_init(self.data.scan)
    iscan = 1

    # initialise array which will contain ifail values for each scan point
    scan_2d_ifail_list = np.zeros(
        (NOUTVARS, IPNSCNS),
        dtype=np.float64,
        order="F",
    )
    for iscan_1 in range(1, self.data.scan.isweep + 1):
        for iscan_2 in range(1, self.data.scan.isweep_2 + 1):
            self.scan_2d_write_point_header(iscan, iscan_1, iscan_2)
            start_time = time.time()
            ifail = self.doopt()
            write_output_files(
                models=self.models,
                data=self.data,
                ifail=ifail,
                runtime=time.time() - start_time,
            )

            show_errors(constants.NOUT)
            logging_model_handler.clear_logs()
            scan_2d_ifail_list[iscan_1][iscan_2] = ifail
            iscan += 1

    print("Scan Convergence Summary\n")
    sweep_1_values = self.data.scan.sweep[: self.data.scan.isweep]
    sweep_2_values = self.data.scan.sweep_2[: self.data.scan.isweep_2]
    nsweep_var = self.scan_select(
        self.data.scan.nsweep, self.data.scan.sweep, self.data.scan.isweep
    )
    nsweep_2_var = self.scan_select(
        self.data.scan.nsweep_2, self.data.scan.sweep_2, self.data.scan.isweep_2
    )
    converged_count = 0
    scan_point = 1
    # offsets for aligning the converged/unconverged column
    max_sweep1_value_length = len(str(np.max(sweep_1_values)).replace(".", ""))
    max_sweep2_value_length = len(str(np.max(sweep_2_values)).replace(".", ""))
    offsets = np.zeros(
        (self.data.scan.isweep, self.data.scan.isweep_2), dtype=int, order="F"
    )
    for count1, sweep1 in enumerate(sweep_1_values):
        for count2, sweep2 in enumerate(sweep_2_values):
            offsets[count1][count2] = (
                max_sweep1_value_length
                - len(str(sweep1).replace(".", ""))
                + max_sweep2_value_length
                - len(str(sweep2).replace(".", ""))
            )

    for iscan_1 in range(1, self.data.scan.isweep + 1):
        for iscan_2 in range(1, self.data.scan.isweep_2 + 1):
            if scan_2d_ifail_list[iscan_1][iscan_2] == 1:
                converged_count += 1
                print(
                    (
                        f"Scan {scan_point:02d}: ({nsweep_var.fname} = "
                        f"{sweep_1_values[iscan_1 - 1]}, {nsweep_2_var.fname} "
                        f"= {sweep_2_values[iscan_2 - 1]}) "
                    )
                    + " " * offsets[iscan_1 - 1][iscan_2 - 1]
                    + "\u001b[32mCONVERGED \u001b[0m"
                )
                scan_point += 1
            else:
                print(
                    (
                        f"Scan {scan_point:02d}: ({nsweep_var.fname} = "
                        f"{sweep_1_values[iscan_1 - 1]}, {nsweep_2_var.fname} = "
                        f"{sweep_2_values[iscan_2 - 1]}) "
                    )
                    + " " * offsets[iscan_1 - 1][iscan_2 - 1]
                    + "\u001b[31mUNCONVERGED \u001b[0m"
                )
                scan_point += 1
    converged_percentage = (
        converged_count / (self.data.scan.isweep * self.data.scan.isweep_2) * 100
    )
    print(f"\nConvergence Percentage: {converged_percentage:.2f}%")

scan_2d_init(scan_data) staticmethod

Scan 2d initialisation

Source code in process/core/scan.py
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
@staticmethod
def scan_2d_init(scan_data: ScanData):
    """Scan 2d initialisation"""
    process_output.ovarre(
        constants.MFILE,
        "Number of first variable scan points",
        "(isweep)",
        scan_data.isweep,
    )
    process_output.ovarre(
        constants.MFILE,
        "Number of second variable scan points",
        "(isweep_2)",
        scan_data.isweep_2,
    )
    process_output.ovarre(
        constants.MFILE,
        "Scanning first variable number",
        "(nsweep)",
        scan_data.nsweep,
    )
    process_output.ovarre(
        constants.MFILE,
        "Scanning second variable number",
        "(nsweep_2)",
        scan_data.nsweep_2,
    )
    process_output.ovarre(
        constants.MFILE,
        "Scanning second variable number",
        "(nsweep_2)",
        scan_data.nsweep_2,
    )
    process_output.ovarre(
        constants.MFILE,
        "Scanning second variable number",
        "(nsweep_2)",
        scan_data.nsweep_2,
    )

scan_1d_write_point_header(iscan)

Scan 1d header

Source code in process/core/scan.py
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
def scan_1d_write_point_header(self, iscan: int):
    """Scan 1d header"""
    self.data.globals.iscan_global = iscan
    sv = self.scan_select(self.data.scan.nsweep, self.data.scan.sweep, iscan)

    self.data.globals.vlabel = sv.fname
    self.data.globals.xlabel = sv.description

    process_output.oblnkl(constants.NOUT)
    process_output.ostars(constants.NOUT, 110)

    process_output.write(
        constants.NOUT,
        f"***** Scan point {iscan} of {self.data.scan.isweep} : "
        f"{self.data.globals.xlabel}"
        f", {self.data.globals.vlabel} = {self.data.scan.sweep[iscan - 1]} "
        "*****",
    )
    process_output.ostars(constants.NOUT, 110)
    process_output.oblnkl(constants.MFILE)
    process_output.ovarre(constants.MFILE, "Scan point number", "(iscan)", iscan)

    print(
        f"Starting scan point {iscan} of {self.data.scan.isweep} : "
        f"{self.data.globals.xlabel} , {self.data.globals.vlabel}"
        f" = {self.data.scan.sweep[iscan - 1]}"
    )

scan_2d_write_point_header(iscan, iscan_1, iscan_2)

Scan 2d header

Source code in process/core/scan.py
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
def scan_2d_write_point_header(self, iscan, iscan_1, iscan_2):
    """Scan 2d header"""
    iscan_r = self.data.scan.isweep_2 - iscan_2 + 1 if iscan_1 % 2 == 0 else iscan_2

    # Makes iscan available globally (read-only)
    self.data.globals.iscan_global = iscan
    sv_1 = self.scan_select(self.data.scan.nsweep, self.data.scan.sweep, iscan_1)

    self.data.globals.vlabel = sv_1.fname
    self.data.globals.xlabel = sv_1.data.description

    sv_2 = self.scan_select(self.data.scan.nsweep_2, self.data.scan.sweep_2, iscan_r)

    self.data.globals.vlabel_2 = sv_2.fname
    self.data.globals.xlabel_2 = sv_2.data.description

    process_output.oblnkl(constants.NOUT)
    process_output.ostars(constants.NOUT, 110)

    process_output.write(
        constants.NOUT,
        f"***** 2D Scan point {iscan} of "
        f"{self.data.scan.isweep * self.data.scan.isweep_2} : "
        f"{self.data.globals.vlabel} = {self.data.scan.sweep[iscan_1 - 1]} and"
        f" {self.data.globals.vlabel_2} = {self.data.scan.sweep_2[iscan_r - 1]} "
        "*****",
    )
    process_output.ostars(constants.NOUT, 110)
    process_output.oblnkl(constants.MFILE)
    process_output.ovarre(constants.MFILE, "Scan point number", "(iscan)", iscan)

    print(
        f"Starting scan point {iscan}:  {self.data.globals.xlabel}, "
        f"{self.data.globals.vlabel} = {self.data.scan.sweep[iscan_1 - 1]}"
        f" and {self.data.globals.xlabel_2}, "
        f"{self.data.globals.vlabel_2} = {self.data.scan.sweep_2[iscan_r - 1]} "
    )

    return iscan_r

scan_1d_write_plot(scan_data) staticmethod

Scan 1d plotter

Source code in process/core/scan.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
@staticmethod
def scan_1d_write_plot(scan_data: ScanData):
    """Scan 1d plotter"""
    if scan_data.first_call_1d:
        process_output.ovarre(
            constants.MFILE,
            "Number of scan points",
            "(isweep)",
            scan_data.isweep,
        )
        process_output.ovarre(
            constants.MFILE,
            "Scanning variable number",
            "(nsweep)",
            scan_data.nsweep,
        )

        scan_data.first_call_1d = False

scan_select(nsweep, sweep, iscan)

Select a scan

Source code in process/core/scan.py
558
559
560
561
562
def scan_select(self, nsweep, sweep, iscan) -> ScanVariables:
    """Select a scan"""
    sv = ScanVariables(nsweep)
    sv.set(self.data, sweep[iscan - 1])
    return sv