-
Notifications
You must be signed in to change notification settings - Fork 240
/
doe_generators.py
697 lines (557 loc) · 20.6 KB
/
doe_generators.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
"""
Case generators for Design-of-Experiments Driver.
"""
import csv
import os.path
import re
from collections import OrderedDict
import numpy as np
import pyDOE2
from openmdao.utils.name_maps import prom_name2abs_name
_LEVELS = 2 # default number of levels for pyDOE generators
class DOEGenerator(object):
"""
Base class for a callable object that generates cases for a DOEDriver.
"""
def __call__(self, design_vars, model=None):
"""
Generate case.
Parameters
----------
design_vars : OrderedDict
Dictionary of design variables for which to generate values.
model : Group
The model containing the design variables (used by some subclasses).
Returns
-------
list
list of name, value tuples for the design variables.
"""
return []
class ListGenerator(DOEGenerator):
"""
DOE case generator that reads cases from a provided list of DOE cases.
This DOE case generator will accept an existing data set in the form of
a list of DOE cases, each of which consists of a collection of name/value
pairs specifying values for design variables.
Parameters
----------
data : list
List of collections of name, value pairs for the design variables.
Attributes
----------
_data : list
List of collections of name, value pairs for the design variables.
"""
def __init__(self, data=[]):
"""
Initialize the ListGenerator.
"""
super().__init__()
if not isinstance(data, list):
msg = "Invalid DOE case data, expected a list but got a {}."
raise RuntimeError(msg.format(data.__class__.__name__))
self._data = data
def __call__(self, design_vars, model=None):
"""
Generate case.
Parameters
----------
design_vars : OrderedDict
Dictionary of design variables for which to generate values.
model : Group
The model containing the design variables.
Yields
------
list
list of name, value tuples for the design variables.
"""
for case in self._data:
if not isinstance(case, list):
msg = "Invalid DOE case found, expecting a list of name/value pairs:\n{}"
raise RuntimeError(msg.format(case))
name_map = {}
for tup in case:
if not isinstance(tup, (tuple, list)) or len(tup) != 2:
msg = "Invalid DOE case found, expecting a list of name/value pairs:\n{}"
raise RuntimeError(msg.format(case))
name = tup[0]
if name in design_vars:
name_map[name] = name
elif model:
abs_name = prom_name2abs_name(model, name, 'output')
if abs_name in design_vars:
name_map[name] = abs_name
# any names not found in name_map are invalid design vars
invalid_desvars = [name for name, _ in case if name not in name_map]
if invalid_desvars:
if len(invalid_desvars) > 1:
msg = "Invalid DOE case found, {} are not valid design variables:\n{}"
raise RuntimeError(msg.format(invalid_desvars, case))
else:
msg = "Invalid DOE case found, '{}' is not a valid design variable:\n{}"
raise RuntimeError(msg.format(invalid_desvars[0], case))
yield [(name_map[name], val) for name, val in case]
class CSVGenerator(DOEGenerator):
"""
DOE case generator that reads cases from a CSV file.
This DOE case generator will accept an existing data set in the form of
a CSV file containing DOE cases. The CSV file should have one column per
design variable and the header row should have the names of the design
variables.
Parameters
----------
filename : str
The name of the file from which to read cases.
Attributes
----------
_filename : str
the name of the file from which to read cases
"""
def __init__(self, filename):
"""
Initialize the CSVGenerator.
"""
super().__init__()
if not isinstance(filename, str):
raise RuntimeError("'{}' is not a valid file name.".format(filename))
if not os.path.isfile(filename):
raise RuntimeError("File not found: {}".format(filename))
self._filename = filename
def __call__(self, design_vars, model=None):
"""
Generate case.
Parameters
----------
design_vars : OrderedDict
Dictionary of design variables for which to generate values.
model : Group
The model containing the design variables.
Yields
------
list
list of name, value tuples for the design variables.
"""
name_map = {}
with open(self._filename, 'r') as f:
# map header names to absolute names if necessary
names = re.sub(' ', '', f.readline()).strip().split(',')
for name in names:
if name in design_vars:
name_map[name] = name
elif model:
abs_name = prom_name2abs_name(model, name, 'output')
if abs_name in design_vars:
name_map[name] = abs_name
# any names not found in name_map are invalid design vars
invalid_desvars = [name for name in names if name not in name_map]
if invalid_desvars:
if len(invalid_desvars) > 1:
msg = "Invalid DOE case file, {} are not valid design variables."
raise RuntimeError(msg.format(invalid_desvars))
else:
msg = "Invalid DOE case file, '{}' is not a valid design variable."
raise RuntimeError(msg.format(invalid_desvars[0]))
# read cases from file, parse values into numpy arrays
with open(self._filename, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
case = [(name_map[name.strip()],
np.fromstring(re.sub(r'[\[\]]', '', row[name]), sep=' '))
for name in reader.fieldnames]
yield case
class UniformGenerator(DOEGenerator):
"""
DOE case generator implementing the Uniform method.
Parameters
----------
num_samples : int, optional
The number of samples to run. Defaults to 1.
seed : int or None, optional
Seed for random number generator.
Attributes
----------
_num_samples : int
The number of samples in the DOE.
_seed : int or None
Random seed.
"""
def __init__(self, num_samples=1, seed=None):
"""
Initialize the UniformGenerator.
"""
super().__init__()
self._num_samples = num_samples
self._seed = seed
def __call__(self, design_vars, model=None):
"""
Generate case.
Parameters
----------
design_vars : OrderedDict
Dictionary of design variables for which to generate values.
model : Group
The model containing the design variables (not used).
Yields
------
list
list of name, value tuples for the design variables.
"""
if self._seed is not None:
np.random.seed(self._seed)
for _ in range(self._num_samples):
sample = []
for name, meta in design_vars.items():
size = meta['size']
lower = meta['lower']
if not isinstance(lower, np.ndarray):
lower = lower * np.ones(size)
upper = meta['upper']
if not isinstance(upper, np.ndarray):
upper = upper * np.ones(size)
sample.append((name, np.random.uniform(lower, upper)))
yield sample
class _pyDOE_Generator(DOEGenerator):
"""
Base class for DOE case generators implementing methods from pyDOE2.
Parameters
----------
levels : int or dict, optional
The number of evenly spaced levels between each design variable
lower and upper bound. Dictionary input is supported by Full Factorial or
Generalized Subset Design.
Defaults to 2.
Attributes
----------
_levels : int or dict(str, int)
The number of evenly spaced levels between each design variable
lower and upper bound. Dictionary input is supported by Full Factorial or
Generalized Subset Design.
"""
def __init__(self, levels=_LEVELS):
"""
Initialize the _pyDOE_Generator.
"""
super().__init__()
self._levels = levels
self._sizes = None
def _get_dv_levels(self, name):
"""
Get the number of levels of a design variable.
If the name is not given, it looks for a "default" key in the dictionary. If this is also
missing, it uses the default number of levels (2).
Parameters
----------
name : str
Design variable name
Returns
-------
int
"""
levels = self._levels
if isinstance(levels, int):
return levels
else:
return levels.get(name, levels.get("default", _LEVELS))
def _get_all_levels(self):
"""Return the levels of all factors."""
sizes = self._sizes
if isinstance(self._levels, int): # All have the same number of levels
return [self._levels] * sum(self._sizes.values())
elif isinstance(self._levels, dict): # Different DVs have different number of levels
return sum([v * [self._get_dv_levels(k)] for k, v in sizes.items()], [])
else:
raise ValueError(f"Levels should be an int or dictionary, not '{type(self._levels)}'")
def __call__(self, design_vars, model=None):
"""
Generate case.
Parameters
----------
design_vars : OrderedDict
Dictionary of design variables for which to generate values.
model : Group
The model containing the design variables (not used).
Yields
------
list
list of name, value tuples for the design variables.
"""
self._sizes = OrderedDict([(name, _get_size(meta))
for name, meta in design_vars.items()])
size = sum(self._sizes.values())
doe = self._generate_design(size).astype('int')
# Maximum number of levels, or the default if the maximum is smaller than the default.
# This is to ensure that the array will be big enough even if some keys are missing
# from levels (defaulted).
levels_max = self._levels if isinstance(self._levels, int) else \
max(max(self._levels.values()), _LEVELS)
# Generate values for each level for each design variable
# over the range of that variable's lower to upper bound
# rows = vars (# rows/var = var size), cols = levels
values = np.empty((size, levels_max)) # Initialize array for the largest number of levels
values[:] = np.nan # and fill with NaNs.
row = 0
for name, meta in design_vars.items():
size = _get_size(meta)
for k in range(size):
lower = meta['lower']
if isinstance(lower, np.ndarray):
lower = lower[k]
upper = meta['upper']
if isinstance(upper, np.ndarray):
upper = upper[k]
levels = self._get_dv_levels(name)
values[row, 0:levels] = np.linspace(lower, upper, num=levels)
row += 1
# yield values for doe generated indices
for idxs in doe:
retval = []
row = 0
for name, meta in design_vars.items():
size_i = _get_size(meta)
val = np.empty(size_i)
for k in range(size_i):
idx = idxs[row + k]
val[k] = values[row + k][idx]
retval.append((name, val))
row += size_i
yield retval
def _generate_design(self, size):
"""
Generate DOE design.
Parameters
----------
size : int
The number of factors for the design.
Returns
-------
ndarray
The design matrix as a size x levels array of indices.
"""
pass
class FullFactorialGenerator(_pyDOE_Generator):
"""
DOE case generator implementing the Full Factorial method.
Parameters
----------
levels : int or dict, optional
The number of evenly spaced levels between each design variable
lower and upper bound. Dictionary input is supported by Full Factorial or
Generalized Subset Design.
Defaults to 2.
"""
def _generate_design(self, size):
"""
Generate a full factorial DOE design.
Parameters
----------
size : int
The number of factors for the design.
Returns
-------
ndarray
The design matrix as a size x levels array of indices.
"""
return pyDOE2.fullfact(self._get_all_levels())
class GeneralizedSubsetGenerator(_pyDOE_Generator):
"""
DOE case generator implementing the General Subset Design Factorial method.
Parameters
----------
levels : int or dict
The number of evenly spaced levels between each design variable
lower and upper bound. Defaults to 2.
reduction : int
Reduction factor (bigger than 1). Larger `reduction` means fewer
experiments in the design and more possible complementary designs.
n : int, optional
Number of complementary GSD-designs. The complementary
designs are balanced analogous to fold-over in two-level fractional
factorial designs.
Defaults to 1.
Attributes
----------
_reduction : int
Reduction factor (bigger than 1). Larger `reduction` means fewer
experiments in the design and more possible complementary designs.
_n : int, optional
Number of complementary GSD-designs. The complementary
designs are balanced analogous to fold-over in two-level fractional
factorial designs.
Defaults to 1.
"""
def __init__(self, levels, reduction, n=1):
"""
Initialize the GeneralizedSubsetGenerator.
"""
super().__init__(levels=levels)
self._reduction = reduction
self._n = n
def _generate_design(self, size):
"""
Generate a general subset DOE design.
Parameters
----------
size : int
The number of factors for the design.
Returns
-------
ndarray
The design matrix as a size x levels array of indices.
"""
return pyDOE2.gsd(levels=self._get_all_levels(), reduction=self._reduction, n=self._n)
class PlackettBurmanGenerator(_pyDOE_Generator):
"""
DOE case generator implementing the Plackett-Burman method.
"""
def __init__(self):
"""
Initialize the PlackettBurmanGenerator.
"""
super().__init__(levels=2)
def _generate_design(self, size):
"""
Generate a Plackett-Burman DOE design.
Parameters
----------
size : int
The number of factors for the design.
Returns
-------
ndarray
The design matrix as a size x levels array of indices.
"""
doe = pyDOE2.pbdesign(size)
doe[doe < 0] = 0 # replace -1 with zero
return doe
class BoxBehnkenGenerator(_pyDOE_Generator):
"""
DOE case generator implementing the Box-Behnken method.
Parameters
----------
center : int, optional
The number of center points to include (default = None).
Attributes
----------
_center : int
The number of center points to include.
"""
def __init__(self, center=None):
"""
Initialize the BoxBehnkenGenerator.
"""
super().__init__(levels=3)
self._center = center
def _generate_design(self, size):
"""
Generate a Box-Behnken DOE design.
Parameters
----------
size : int
The number of factors for the design.
Returns
-------
ndarray
The design matrix as a size x levels array of indices.
"""
if size < 3:
raise RuntimeError("Total size of design variables is %d,"
"but must be at least 3 when using %s. " %
(size, self.__class__.__name__))
doe = pyDOE2.bbdesign(size, center=self._center)
return doe + 1 # replace [-1, 0, 1] with [0, 1, 2]
class LatinHypercubeGenerator(DOEGenerator):
"""
DOE case generator implementing Latin hypercube method via pyDOE2.
Parameters
----------
samples : int, optional
The number of samples to generate for each factor (Defaults to n).
criterion : str, optional
Allowable values are "center" or "c", "maximin" or "m",
"centermaximin" or "cm", and "correlation" or "corr". If no value
given, the design is simply randomized.
iterations : int, optional
The number of iterations in the maximin and correlations algorithms
(Defaults to 5).
seed : int, optional
Random seed to use if design is randomized. Defaults to None.
Attributes
----------
_samples : int
The number of evenly spaced levels between each design variable
lower and upper bound.
_criterion : str
the pyDOE criterion to use.
_iterations : int
The number of iterations to use for maximin and correlations algorithms.
_seed : int or None
Random seed.
"""
# supported pyDOE criterion names.
_supported_criterion = [
"center", "c",
"maximin", "m",
"centermaximin", "cm",
"correlation", "corr",
None
]
def __init__(self, samples=None, criterion=None, iterations=5, seed=None):
"""
Initialize the LatinHypercubeGenerator.
See : https://pythonhosted.org/pyDOE/randomized.html
"""
super().__init__()
if criterion not in self._supported_criterion:
raise ValueError("Invalid criterion '%s' specified for %s. "
"Must be one of %s." %
(criterion, self.__class__.__name__,
self._supported_criterion))
self._samples = samples
self._criterion = criterion
self._iterations = iterations
self._seed = seed
def __call__(self, design_vars, model=None):
"""
Generate case.
Parameters
----------
design_vars : OrderedDict
Dictionary of design variables for which to generate values.
model : Group
The model containing the design variables (not used).
Yields
------
list
list of name, value tuples for the design variables.
"""
if self._seed is not None:
np.random.seed(self._seed)
size = sum([meta['size'] for meta in design_vars.values()])
if self._samples is None:
self._samples = size
# generate design
doe = pyDOE2.lhs(size, samples=self._samples,
criterion=self._criterion,
iterations=self._iterations,
random_state=self._seed)
# yield desvar values for doe samples
for row in doe:
retval = []
col = 0
for name, meta in design_vars.items():
size = meta['size']
sample = row[col:col + size]
lower = meta['lower']
if not isinstance(lower, np.ndarray):
lower = lower * np.ones(size)
upper = meta['upper']
if not isinstance(upper, np.ndarray):
upper = upper * np.ones(size)
val = lower + sample * (upper - lower)
retval.append((name, val))
col += size
yield retval
def _get_size(dct):
# Returns global size of the variable if it is distributed, size otherwise.
return dct['global_size'] if dct['distributed'] else dct['size']