forked from mdolab/pygeo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DVGeometry.py
3765 lines (3086 loc) · 148 KB
/
DVGeometry.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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ======================================================================
# Imports
# ======================================================================
from __future__ import print_function
import copy,time
try:
from collections import OrderedDict
except ImportError:
try:
from ordereddict import OrderedDict
except ImportError:
print("Could not find any OrderedDict class. For 2.6 and earlier, "
"use:\n pip install ordereddict")
import numpy
from scipy import sparse
from mpi4py import MPI
from pyspline import pySpline
from . import pyNetwork, pyBlock, geo_utils
import pdb
import os
class Error(Exception):
"""
Format the error message in a box to make it clear this
was a explicitly raised exception.
"""
def __init__(self, message):
msg = '\n+'+'-'*78+'+'+'\n' + '| DVGeometry Error: '
i = 19
for word in message.split():
if len(word) + i + 1 > 78: # Finish line and start new one
msg += ' '*(78-i)+'|\n| ' + word + ' '
i = 1 + len(word)+1
else:
msg += word + ' '
i += len(word)+1
msg += ' '*(78-i) + '|\n' + '+'+'-'*78+'+'+'\n'
print(msg)
Exception.__init__(self)
class DVGeometry(object):
"""
A class for manipulating geometry.
The purpose of the DVGeometry class is to provide a mapping from
user-supplied design variables to an arbitrary set of discrete,
three-dimensional coordinates. These three-dimensional coordinates
can in general represent anything, but will typically be the
surface of an aerodynamic mesh, the nodes of a FE mesh or the
nodes of another geometric construct.
In a very general sense, DVGeometry performs two primary
functions:
1. Given a new set of design variables, update the
three-dimensional coordinates: :math:`X_{DV}\\rightarrow
X_{pt}` where :math:`X_{pt}` are the coordinates and :math:`X_{DV}`
are the user variables.
2. Determine the derivative of the coordinates with respect to the
design variables. That is the derivative :math:`\\frac{dX_{pt}}{dX_{DV}}`
DVGeometry uses the *Free-Form Deformation* approach for goemetry
manipulation. The basic idea is the coordinates are *embedded* in
a clear-flexible jelly-like block. Then by stretching moving and
'poking' the volume, the coordinates that are embedded inside move
along with overall deformation of the volume.
Parameters
----------
fileName : str
filename of FFD file. This must be a ascii formatted plot3D file
in fortran ordering.
complex : bool
Make the entire object complex. This should **only** be used when
debugging the entire tool-chain with the complex step method.
child : bool
Flag to indicate that this object is a child of parent DVGeo object
Examples
--------
The general sequence of operations for using DVGeometry is as follows::
>>> from pygeo import *
>>> DVGeo = DVGeometry('FFD_file.fmt')
>>> # Embed a set of coordinates Xpt into the object
>>> DVGeo.addPointSet(Xpt, 'myPoints')
>>> # Associate a 'reference axis' for large-scale manipulation
>>> DVGeo.addRefAxis('wing_axis', axis_curve)
>>> # Define a global design variable function:
>>> def twist(val, geo):
>>> geo.rot_z['wing_axis'].coef[:] = val[:]
>>> # Now add this as a global variable:
>>> DVGeo.addGeoDVGlobal('wing_twist', 0.0, twist, lower=-10, upper=10)
>>> # Now add local (shape) variables
>>> DVGeo.addGeoDVLocal('shape', lower=-0.5, upper=0.5, axis='y')
>>>
"""
def __init__(self, fileName, complex=False, child=False, faceFreeze=None, *args, **kwargs):
self.DV_listGlobal = OrderedDict() # Global Design Variable List
self.DV_listLocal = OrderedDict() # Local Design Variable List
self.DV_listSectionLocal = OrderedDict() # Local Normal Design Variable List
# Coefficient rotation matrix dict for Section Local variables
self.coefRotM = {}
# Flags to determine if this DVGeometry is a parent or child
self.isChild = child
self.children = []
self.iChild = None
self.points = OrderedDict()
self.updated = {}
self.masks = None
self.finalized = False
self.complex = complex
if self.complex:
self.dtype = 'D'
else:
self.dtype = 'd'
# Load the FFD file in FFD mode. Also note that args and
# kwargs are passed through in case additional pyBlock options
# need to be set.
self.FFD = pyBlock('plot3d', fileName=fileName, FFD=True,
*args, **kwargs)
self.origFFDCoef = self.FFD.coef.copy()
# Jacobians:
self.ptSetNames = []
self.JT = {}
self.nPts = {}
# Derivatives of Xref and Coef provided by the parent to the
# children
self.dXrefdXdvg = None
self.dCoefdXdvg = None
self.dXrefdXdvl = None
self.dCoefdXdvl = None
# derivative counters for offsets
self.nDV_T = None
self.nDVG_T = None
self.nDVL_T = None
self.nDVSL_T = None
self.nDVG_count = 0
self.nDVL_count = 0
self.nDVSL_count = 0
# The set of user supplied axis.
self.axis = OrderedDict()
# Generate coefMask regardless
coefMask = []
for iVol in range(self.FFD.nVol):
coefMask.append(numpy.zeros((self.FFD.vols[iVol].nCtlu,
self.FFD.vols[iVol].nCtlv,
self.FFD.vols[iVol].nCtlw), dtype=bool))
# Now do the faceFreeze
if faceFreeze is not None:
for iVol in range(self.FFD.nVol):
key = '%d'%iVol
if key in faceFreeze.keys():
if 'iLow' in faceFreeze[key]:
coefMask[iVol][0, :, :] = True
coefMask[iVol][1, :, :] = True
if 'iHigh' in faceFreeze[key]:
coefMask[iVol][-1, :, :] = True
coefMask[iVol][-2, :, :] = True
if 'jLow' in faceFreeze[key]:
coefMask[iVol][:, 0, :] = True
coefMask[iVol][:, 1, :] = True
if 'jHigh' in faceFreeze[key]:
coefMask[iVol][:, -1, :] = True
coefMask[iVol][:, -2, :] = True
if 'kLow' in faceFreeze[key]:
coefMask[iVol][:, :, 0] = True
coefMask[iVol][:, :, 1] = True
if 'kHigh' in faceFreeze[key]:
coefMask[iVol][:, :, -1] = True
coefMask[iVol][:, :, -2] = True
# Finally we need to convert coefMask to the flattened global
# coef type:
tmp = numpy.zeros(len(self.FFD.coef), dtype=bool)
for iVol in range(self.FFD.nVol):
for i in range(coefMask[iVol].shape[0]):
for j in range(coefMask[iVol].shape[1]):
for k in range(coefMask[iVol].shape[2]):
ind = self.FFD.topo.lIndex[iVol][i, j, k]
if coefMask[iVol][i, j, k]:
tmp[ind] = True
self.masks = tmp
def addRefAxis(self, name, curve=None, xFraction=None, volumes=None,
rotType=5, axis='x', alignIndex=None, rotAxisVar=None,
xFractionOrder=2, includeVols=[], ignoreInd=[],
raySize=1.5):
"""
This function is used to add a 'reference' axis to the
DVGeometry object. Adding a reference axis is only required
when 'global' design variables are to be used, i.e. variables
like span, sweep, chord etc --- variables that affect many FFD
control points.
There are two different ways that a reference can be
specified:
#. The first is explicitly a pySpline curve object using the
keyword argument curve=<curve>.
#. The second is to specify the xFraction variable. There are a
few caveats with the use of this method. First, DVGeometry
will try to determine automatically the orientation of the FFD
volume. Then, a reference axis will consist of the same number of
control points as the number of span-wise sections in the FFD volume
and will be oriented in the streamwise (x-direction) according to the
xPercent keyword argument.
Parameters
----------
name : str
Name of the reference axis. This name is used in the
user-supplied design variable functions to determine what
axis operations occur on.
curve : pySpline curve object
Supply exactly the desired reference axis
xFraction : float
Specify the stream-wise extent
volumes : list or array or integers
List of the volume indices, in 0-based ordering that this
reference axis should manipulate. If xFraction is
specified, the volumes argument must contain at most 1
volume. If the volumes is not given, then all volumes are
taken.
rotType : int
Integer in range 0->6 (inclusive) to determine the order
that the rotations are made.
0. Intrinsic rotation, rot_theta is rotation about axis
1. x-y-z
2. x-z-y
3. y-z-x
4. y-x-z
5. z-x-y Default (x-streamwise y-up z-out wing)
6. z-y-x
7. z-x-y + rot_theta
8. z-x-y + rotation about section axis (to allow for winglet rotation)
axis: str
Axis along which to project points/control points onto the
ref axis. Default is 'x' which will project rays.
alignIndex: str
FFD axis along which the reference axis will lie. Can be 'i', 'j',
or 'k'. Only necessary when using xFraction.
rotAxisVar: str
If rotType == 8, then you must specify the name of the section local
variable which should be used to compute the orientation of the theta
rotation.
xFractionOrder : int
Order of spline used for refaxis curve.
includeVols : list
List of additional volumes to add to reference axis after the
automatic generation of the ref axis based on the volumes list using
xFraction.
ignoreInd : list
List of indices that should be ignored from the volumes that were
added to this reference axis. This can be handy if you have a single
volume but you want to link different sets of indices to different
reference axes.
Notes
-----
One of curve or xFraction must be specified.
Examples
--------
>>> # Simple wing with single volume FFD, reference axis at 1/4 chord:
>>> DVGeo.addRefAxis('wing', xFraction=0.25)
>>> # Multiblock FFD, wing is volume 6.
>>> DVGeo.addRefAxis('wing', xFraction=0.25, volumes=[6])
>>> # Multiblock FFD, multiple volumes attached refAxis
>>> DVGeo.addRefAxis('wing', myCurve, volumes=[2,3,4])
Returns
-------
nAxis : int
The number of control points on the reference axis.
"""
# We don't do any of the final processing here; we simply
# record the information the user has supplied into a
# dictionary structure.
if axis is None:
pass
elif axis.lower() == 'x':
axis = numpy.array([1, 0, 0], 'd')
elif axis.lower() == 'y':
axis = numpy.array([0, 1, 0], 'd')
elif axis.lower() == 'z':
axis = numpy.array([0, 0, 1], 'd')
if curve is not None:
# Explicit curve has been supplied:
if self.FFD.symmPlane is None:
if volumes is None:
volumes = numpy.arange(self.FFD.nVol)
self.axis[name] = {'curve':curve, 'volumes':volumes,
'rotType':rotType, 'axis':axis}
else:
# get the direction of the symmetry plane
if self.FFD.symmPlane.lower() == 'x':
index = 0
elif self.FFD.symmPlane.lower() == 'y':
index = 1
elif self.FFD.symmPlane.lower() == 'z':
index = 2
# mirror the axis and attach the mirrored vols
if volumes is None:
volumes = numpy.arange(self.FFD.nVol/2)
volumesSymm = []
for volume in volumes:
volumesSymm.append(volume+self.FFD.nVol/2)
curveSymm = copy.deepcopy(curve)
curveSymm.reverse()
for coef in curveSymm.coef:
curveSymm.coef[:,index]=-curveSymm.coef[:,index]
self.axis[name] = {'curve':curve, 'volumes':volumes,
'rotType':rotType, 'axis':axis}
self.axis[name+'Symm'] = {'curve':curveSymm, 'volumes':volumesSymm,
'rotType':rotType, 'axis':axis}
nAxis = len(curve.coef)
elif xFraction is not None:
# Some assumptions
# - FFD should be a close approximation of geometry surface so that
# xFraction roughly corresponds to airfoil LE, TE, or 1/4 chord
# - User provides 'i', 'j' or 'k' to specify which block direction
# the reference axis should project
# - if no volumes are listed, it is assumed that all volumes are
# included
# - 'x' is streamwise direction
# This is the block direction along which the reference axis will lie
# alignIndex = 'K'
if alignIndex is None:
raise Error('Must specify alignIndex to use xFraction.')
# Get index direction along which refaxis will be aligned
if alignIndex.lower() == 'i':
alignIndex = 0
faceCol = 2
elif alignIndex.lower() == 'j':
alignIndex = 1
faceCol = 4
elif alignIndex.lower() == 'k':
alignIndex = 2
faceCol = 0
if volumes is None:
volumes = range(self.FFD.nVol)
# Reorder the volumes in sequential order and check if orientation is correct
v = list(volumes)
nVol = len(v)
volOrd = [v.pop(0)]
faceLink = self.FFD.topo.faceLink
for iter in range(nVol):
for vInd, i in enumerate(v):
for pInd, j in enumerate(volOrd):
if faceLink[i,faceCol] == faceLink[j,faceCol+1]:
volOrd.insert(pInd+1, v.pop(vInd))
break
elif faceLink[i,faceCol+1] == faceLink[j,faceCol]:
volOrd.insert(pInd, v.pop(vInd))
break
if len(volOrd) < nVol:
raise Error("The volumes are not ordered with matching faces"
" in the direction of the reference axis.")
# Count total number of sections and check if volumes are aligned
# face to face along refaxis direction
lIndex = self.FFD.topo.lIndex
nSections = []
for i in range(len(volOrd)):
if i == 0:
nSections.append(lIndex[volOrd[i]].shape[alignIndex])
else:
nSections.append(lIndex[volOrd[i]].shape[alignIndex] - 1)
refaxisNodes = numpy.zeros((sum(nSections), 3))
# Loop through sections and compute node location
place = 0
for j, vol in enumerate(volOrd):
sectionArr = numpy.rollaxis(lIndex[vol], alignIndex, 0)
skip = 0
if j > 0:
skip = 1
for i in range(nSections[j]):
LE = numpy.min(self.FFD.coef[sectionArr[i+skip,:,:],0])
TE = numpy.max(self.FFD.coef[sectionArr[i+skip,:,:],0])
refaxisNodes[place+i,0] = xFraction*(TE - LE) + LE
refaxisNodes[place+i,1] = numpy.mean(self.FFD.coef[sectionArr[i+skip,:,:],1])
refaxisNodes[place+i,2] = numpy.mean(self.FFD.coef[sectionArr[i+skip,:,:],2])
place += i + 1
# Add additional volumes
for iVol in includeVols:
if iVol not in volumes:
volumes.append(iVol)
# Generate reference axis pySpline curve
curve = pySpline.Curve(X=refaxisNodes, k=2)
nAxis = len(curve.coef)
self.axis[name] = {'curve':curve, 'volumes':volumes,
'rotType':rotType, 'axis':axis,
'rotAxisVar':rotAxisVar}
else:
raise Error("One of 'curve' or 'xFraction' must be "
"specified for a call to addRefAxis")
# Specify indices to be ignored
self.axis[name]['ignoreInd'] = ignoreInd
# Add the raySize multiplication factor for this axis
self.axis[name]['raySize'] = raySize
return nAxis
def addPointSet(self, points, ptName, origConfig=True, **kwargs):
"""
Add a set of coordinates to DVGeometry
The is the main way that geometry, in the form of a coordinate
list is given to DVGeoemtry to be manipulated.
Parameters
----------
points : array, size (N,3)
The coordinates to embed. These cordinates *should* all
project into the interior of the FFD volume.
ptName : str
A user supplied name to associate with the set of
coordinates. This name will need to be provided when
updating the coordinates or when getting the derivatives
of the coordinates.
origConfig : bool
Flag determine if the coordinates are projected into the
undeformed or deformed configuration. This should almost
always be True except in circumstances when the user knows
exactly what they are doing."""
# save this name so that we can zero out the jacobians properly
self.ptSetNames.append(ptName)
self.zeroJacobians([ptName])
self.nPts[ptName]=None
points = numpy.array(points).real.astype('d')
self.points[ptName] = points
# Ensure we project into the undeformed geometry
if origConfig:
tmpCoef = self.FFD.coef.copy()
self.FFD.coef = self.origFFDCoef
self.FFD._updateVolumeCoef()
# Project the last set of points into the volume
if self.isChild:
self.FFD.attachPoints(
self.points[ptName], ptName, interiorOnly=True, **kwargs)
else:
self.FFD.attachPoints(
self.points[ptName], ptName, interiorOnly=False)
if origConfig:
self.FFD.coef = tmpCoef
self.FFD._updateVolumeCoef()
# Now embed into the children:
for child in self.children:
child.addPointSet(points, ptName, origConfig, **kwargs)
self.FFD.calcdPtdCoef(ptName)
self.updated[ptName] = False
def addChild(self, childDVGeo):
"""Embed a child FFD into this object.
An FFD child is a 'sub' FFD that is fully contained within
another, parent FFD. A child FFD is also an instance of
DVGeometry which may have its own global and/or local design
variables. Coordinates do **not** need to be added to the
children. The parent object will take care of that in a call
to addPointSet().
Parameters
----------
childDVGeo : instance of DVGeometry
DVGeo object to use as a sub-FFD
"""
# Make sure the DVGeo being added is flaged as a child:
if childDVGeo.isChild is False:
raise Error("Trying to add a child FFD that has NOT been "
"created as a child. This operation is illegal.")
# Extract the coef from the child FFD and ref axis and embed
# them into the parent and compute their derivatives
iChild = len(self.children)
childDVGeo.iChild = iChild
self.FFD.attachPoints(childDVGeo.FFD.coef, 'child%d_coef'%(iChild))
self.FFD.calcdPtdCoef('child%d_coef'%(iChild))
# We must finalize the Child here since we need the ref axis
# coefficients
childDVGeo._finalizeAxis()
self.FFD.attachPoints(childDVGeo.refAxis.coef, 'child%d_axis'%(iChild))
self.FFD.calcdPtdCoef('child%d_axis'%(iChild))
# Add the child to the parent and return
self.children.append(childDVGeo)
def addGeoDVGlobal(self, dvName, value, func, lower=None, upper=None,
scale=1.0, config=None):
"""
Add a global design variable to the DVGeometry object. This
type of design variable acts on one or more reference axis.
Parameters
----------
dvName : str
A unique name to be given to this design variable group
value : float, or iterable list of floats
The starting value(s) for the design variable. This
parameter may be a single variable or a numpy array
(or list) if the function requires more than one
variable. The number of variables is determined by the
rank (and if rank ==1, the length) of this parameter.
lower : float, or iterable list of floats
The lower bound(s) for the variable(s). A single variable
is permissable even if an array is given for value. However,
if an array is given for 'lower', it must be the same length
as 'value'
func : python function
The python function handle that will be used to apply the
design variable
upper : float, or iterable list of floats
The upper bound(s) for the variable(s). Same restrictions as
'lower'
scale : float, or iterable list of floats
The scaling of the variables. A good approximate scale to
start with is approximately 1.0/(upper-lower). This gives
variables that are of order ~1.0.
config : str or list
Define what configurations this design variable will be applied to
Use a string for a single configuration or a list for multiple
configurations. The default value of None implies that the design
variable appies to *ALL* configurations.
"""
if type(config) == str:
config = [config]
self.DV_listGlobal[dvName] = geoDVGlobal(
dvName, value, lower, upper, scale, func, config)
def addGeoDVLocal(self, dvName, lower=None, upper=None, scale=1.0,
axis='y', volList=None, pointSelect=None, config=None):
"""
Add one or more local design variables ot the DVGeometry
object. Local variables are used for small shape modifications.
Parameters
----------
dvName : str
A unique name to be given to this design variable group
lower : float
The lower bound for the variable(s). This will be applied to
all shape variables
upper : float
The upper bound for the variable(s). This will be applied to
all shape variables
scale : flot
The scaling of the variables. A good approximate scale to
start with is approximately 1.0/(upper-lower). This gives
variables that are of order ~1.0.
axis : str. Default is 'y'
The coordinate directions to move. Permissible values are 'x',
'y' and 'z'. If more than one direction is required, use multiple
calls to addGeoDVLocal with different axis values.
volList : list
Use the control points on the volume indicies given in volList.
You should use pointSelect = None, otherwise this will not work.
pointSelect : pointSelect object. Default is None Use a
pointSelect object to select a subset of the total number
of control points. See the documentation for the
pointSelect class in geo_utils. Using pointSelect discards everything in
volList.
config : str or list
Define what configurations this design variable will be applied to
Use a string for a single configuration or a list for multiple
configurations. The default value of None implies that the design
variable appies to *ALL* configurations.
Returns
-------
N : int
The number of design variables added.
Examples
--------
>>> # Add all variables in FFD as local shape variables
>>> # moving in the y direction, within +/- 1.0 units
>>> DVGeo.addGeoDVLocal('shape_vars', lower=-1.0, upper= 1.0, axis='y')
>>> # As above, but moving in the x and y directions.
>>> nVar = DVGeo.addGeoDVLocal('shape_vars_x', lower=-1.0, upper= 1.0, axis='x')
>>> nVar = DVGeo.addGeoDVLocal('shape_vars_y', lower=-1.0, upper= 1.0, axis='y')
>>> # Create a point select to use: (box from (0,0,0) to (10,0,10) with
>>> # any point projecting into the point along 'y' axis will be selected.
>>> PS = geo_utils.PointSelect(type = 'y', pt1=[0,0,0], pt2=[10, 0, 10])
>>> nVar = DVGeo.addGeoDVLocal('shape_vars', lower=-1.0, upper=1.0, pointSelect=PS)
"""
if type(config) == str:
config = [config]
if pointSelect is not None:
if pointSelect.type != 'ijkBounds':
pts, ind = pointSelect.getPoints(self.FFD.coef)
else:
pts, ind = pointSelect.getPoints_ijk(self)
elif volList is not None:
if self.FFD.symmPlane is not None:
volListTmp = []
for vol in volList:
volListTmp.append(vol)
for vol in volList:
volListTmp.append(vol+self.FFD.nVol/2)
volList = volListTmp
volList = numpy.atleast_1d(volList).astype('int')
ind = []
for iVol in volList:
ind.extend(self.FFD.topo.lIndex[iVol].flatten())
ind = geo_utils.unique(ind)
else:
# Just take'em all
ind = numpy.arange(len(self.FFD.coef))
self.DV_listLocal[dvName] = geoDVLocal(dvName, lower, upper,
scale, axis, ind, self.masks,
config)
return self.DV_listLocal[dvName].nVal
def addGeoDVSectionLocal(self, dvName, secIndex, lower=None, upper=None,
scale=1.0, axis=1, pointSelect=None, volList=None,
orient0=None, orient2='svd', config=None):
"""Add one or more section local design variables to the DVGeometry
object. Section local variables are used as an alternative to local
variables when it is desirable to deform a cross-section shape within a
plane that is consistent with the original cross-section orientation.
This is helpful in at least two common scenarios:
1) The original geometry has cross-sections that are not aligned with
the global coordinate axes. For instance, with a winglet, we want
the shape variables to deform normal to the winglet surface
instead of in the x, y, or z directions.
2) The global design variables cause changes in the geometry that
rotate the orientation of the original cross-section planes. In
this case, we want the shape variables to deform in directions
aligned with the rotated cross-section plane, which may not be
the x, y, or z directions.
** Warnings **
- Rotations in an upper level (parent) FFD will not propagate down
to the lower level FFDs due to limitations of the current
implementation.
- Section local design variables should not be specified at the same
time as local design variables. This will most likely not result
in the desired behavior.
Parameters
----------
dvName : str
A unique name to be given to this design variable group
lower : float
The lower bound for the variable(s). This will be applied to
all shape variables
upper : float
The upper bound for the variable(s). This will be applied to
all shape variables
scale : flot
The scaling of the variables. A good approximate scale to
start with is approximately 1.0/(upper-lower). This gives
variables that are of order ~1.0.
axis : int
The coordinate directions to move. Permissible values are
0: longitudinal direction (in section plane)
1: latitudinal direction (in section plane)
2: transverse direction (out of section plane)
If more than one direction is required, use multiple calls to
addGeoDVSectionLocal with different axis values.
1
^
|
o-----o--------o----|----o--------o--------o-----o
| | | j
| x---------> 0 | ^
| / | |
o-----o--------o--/------o--------o--------o-----o
/ ----> i
/
2
pointSelect : pointSelect object. Default is None Use a
pointSelect object to select a subset of the total number
of control points. See the documentation for the
pointSelect class in geo_utils. Using pointSelect discards everything in
volList.
You can create a PointSelect object by using, for instance:
>>> PS = geo_utils.PointSelect(type = 'y', pt1=[0,0,0], pt2=[10, 0, 10])
Check the other PointSelect options in geo_utils.py
volList : list
Use the control points on the volume indicies given in volList. If
None, all volumes will be included.
PointSelect has priority over volList. So if you use PointSelect, the values
defined in volList will have no effect.
secIndex : char or list of chars
For each volume, we need to specify along which index we would like
to subdivide the volume into sections. Entries in list can be 'i',
'j', or 'k'. This index will be designated as the transverse (2)
direction in terms of the direction of perturbation for the 'axis'
parameter.
orient0 : None, 'i', 'j', 'k', or numpy vector. Default is None.
Although secIndex defines the '2' axis, the '0' and '1' axes are still
free to rotate within the section plane. We will choose the orientation
of the '0' axis and let '1' be orthogonal. We have three options:
1. <None> (default) If nothing is prescribed, the 0 direction will
be the best fit line through the section points. In the case
of an airfoil, this would roughly align with the chord.
2. <'i','j' or 'k'> In this case, the '0' axis will be aligned
with the mean vector between the FFD edges corresponding to
this index. In the ascii art above, if 'j' were given for this
option, we would average the vectors between the points on the
top and bottom surfaces and project this vector on to the
section plane as the '0' axis. If a list is given, each index
will be applied to its corresponding volume in volList.
3. <[x, y, z]> If a numpy vector is given, the '0' axis
will be aligned with a projection of this vector onto the
section plane. If a numpy array of len(volList) x 3 is given,
each vector will apply to its corresponding volume.
orient2: 'svd' or 'ffd. Default is 'svd'
How to compute the orientation '2' axis. SVD is the
default bevaviour and is taken from the svd of the plane
points. 'ffd' Uses the vector along the FFD direction of
secIndex. This is requied to get consistent normals if you
have a circular-type FFD when the SVD will swap the
normals.
config : str or list
Define what configurations this design variable will be applied to
Use a string for a single configuration or a list for multiple
configurations. The default value of None implies that the design
variable appies to *ALL* configurations.
Returns
-------
N : int
The number of design variables added.
Examples
--------
>>> # Add all control points in FFD as local shape variables
>>> # moving in the 1 direction, within +/- 1.0 units
>>> DVGeo.addGeoDVSectionLocal('shape_vars', secIndex='k', lower=-1, upper=1, axis=1)
"""
if type(config) == str:
config = [config]
# Pick out control points
if pointSelect is not None:
if pointSelect.type != 'ijkBounds':
pts, ind = pointSelect.getPoints(self.FFD.coef)
volList = numpy.arange(self.FFD.nVol) # Select all volumes
else:
pts, ind = pointSelect.getPoints_ijk(self)
volList = pointSelect.ijkBounds.keys() # Select only volumes used by pointSelect
elif volList is not None:
if self.FFD.symmPlane is not None:
volListTmp = []
for vol in volList:
volListTmp.append(vol)
for vol in volList:
volListTmp.append(vol+self.FFD.nVol/2)
volList = volListTmp
volList = numpy.atleast_1d(volList).astype('int')
ind = []
for iVol in volList:
ind.extend(self.FFD.topo.lIndex[iVol].flatten()) # Get all indices from this block
ind = geo_utils.unique(ind)
else:
# Just take'em all
volList = numpy.arange(self.FFD.nVol)
ind = numpy.arange(len(self.FFD.coef))
secLink = numpy.zeros(self.FFD.coef.shape[0], dtype=int)
secTransform = [numpy.eye(3)]
if type(secIndex) is str:
secIndex = [secIndex]*len(volList)
elif type(secIndex) is list:
if len(secIndex) != len(volList):
raise Error('If a list is given for secIndex, the length must be'
' equal to the length of volList.')
if orient0 is not None:
# 'i', 'j', or 'k'
if type(orient0) is str:
orient0 = [orient0]*len(volList)
# ['k', 'k', 'i', etc.]
elif type(orient0) is list:
if len(orient0) != len(volList):
raise Error('If a list is given for orient0, the length must'
' be equal to the length of volList.')
# numpy.array([1.0, 0.0, 0.0])
elif type(orient0) is numpy.ndarray:
# vector
if len(orient0.shape) == 1:
orient0 = numpy.reshape(orient0, (1,3))
orient0 = numpy.repeat(orient0, len(volList), 0)
elif orient0.shape[0] == 1:
orient0 = numpy.repeat(orient0, len(volList), 0)
elif orient0.shape[0] != len(volList):
raise Error('If an array is given for orient0, the row dimension'
' must be equal to the length of volList.')
for i, iVol in enumerate(volList):
self.sectionFrame(secIndex[i], secTransform, secLink, iVol,
orient0[i], orient2=orient2)
else:
for i, iVol in enumerate(volList):
self.sectionFrame(secIndex[i], secTransform, secLink, iVol, orient2=orient2)
self.DV_listSectionLocal[dvName] = geoDVSectionLocal(dvName, lower, upper,
scale, axis, ind, self.masks,
config, secTransform, secLink)
return self.DV_listSectionLocal[dvName].nVal
def getSymmetricCoefList(self,volList=None, pointSelect=None, tol = 1e-8):
"""
Determine the pairs of coefs that need to be constrained for symmetry.
Parameters
----------
volList : list
Use the control points on the volume indicies given in volList
pointSelect : pointSelect object. Default is None Use a
pointSelect object to select a subset of the total number
of control points. See the documentation for the
pointSelect class in geo_utils.
tol : float
Tolerance for ignoring nodes around the symmetry plane. These should be
merged by the network/connectivity anyway
Returns
-------
indSetA : list of ints
One half of the coefs to be constrained
indSetB : list of ints
Other half of the coefs to be constrained
Examples
--------
"""
if self.FFD.symmPlane is None:
#nothing to be done
indSetA = []
indSetB = []
else:
# get the direction of the symmetry plane
if self.FFD.symmPlane.lower() == 'x':
index = 0
elif self.FFD.symmPlane.lower() == 'y':
index = 1
elif self.FFD.symmPlane.lower() == 'z':
index = 2
#get the points to be matched up
if pointSelect is not None:
pts, ind = pointSelect.getPoints(self.FFD.coef)
elif volList is not None:
volListTmp = []
for vol in volList:
volListTmp.append(vol)
for vol in volList:
volListTmp.append(vol+self.FFD.nVol/2)
volList = volListTmp
volList = numpy.atleast_1d(volList).astype('int')
ind = []
for iVol in volList:
ind.extend(self.FFD.topo.lIndex[iVol].flatten())
ind = geo_utils.unique(ind)
pts = self.FFD.coef[ind]
else:
# Just take'em all
ind = numpy.arange(len(self.FFD.coef))
pts = self.FFD.coef
# Create the base points for the KD tree search. We will take the abs
# value of the symmetry direction, that way when we search we will get
# back index pairs which is what we want.
baseCoords = copy.copy(pts)
baseCoords[:,index] = abs(baseCoords[:,index])
#now use the baseCoords to create a KD tree
try:
from scipy.spatial import cKDTree
except:
raise Error("scipy.spatial "
"must be available to use detect symmetry")
# Now make a KD-tree so we can use it to find the unique nodes
tree = cKDTree(baseCoords)
# Now search through the +ve half of the points, ignoring anything within
# tol of the symmetry plane to find pairs
indSetA = []
indSetB = []
for pt in pts:
if pt[index]>tol:
# Now find any matching nodes within tol. there should be 2 and
# only 2 if the mesh is symmtric
Ind =tree.query_ball_point(pt, tol)#should this be a separate tol
if not(len(Ind)==2):
raise Error("more than 2 coefs found that match pt")
else:
indSetA.append(Ind[0])
indSetB.append(Ind[1])
return indSetA,indSetB
def setDesignVars(self, dvDict):
"""
Standard routine for setting design variables from a design
variable dictionary.
Parameters
----------
dvDict : dict
Dictionary of design variables. The keys of the dictionary
must correspond to the design variable names. Any
additional keys in the dfvdictionary are simply ignored.
"""
# Coefficients must be complexifed from here on if complex
if self.complex:
self._finalize()