-
Notifications
You must be signed in to change notification settings - Fork 48
/
topology.py
3291 lines (2753 loc) · 151 KB
/
topology.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
"""
The topology module defines the topology objects, notably the
:class:`StructuredTopology`. Maintaining strict separation of topological and
geometrical information, the topology represents a set of elements and their
interconnectivity, boundaries, refinements, subtopologies etc, but not their
positioning in physical space. The dimension of the topology represents the
dimension of its elements, not that of the the space they are embedded in.
The primary role of topologies is to form a domain for :mod:`nutils.function`
objects, like the geometry function and function bases for analysis, as well as
provide tools for their construction. It also offers methods for integration and
sampling, thus providing a high level interface to operations otherwise written
out in element loops. For lower level operations topologies can be used as
:mod:`nutils.element` iterators.
"""
from . import element, function, evaluable, _util as util, parallel, numeric, cache, transform, transformseq, warnings, types, points, sparse
from ._util import single_or_multiple
from ._backports import cached_property
from .elementseq import References
from .pointsseq import PointsSequence
from .sample import Sample
from dataclasses import dataclass
from functools import reduce
from os import environ
from typing import Any, FrozenSet, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple, Union, Sequence
import itertools
import numpy
import nutils_poly as poly
import operator
import treelog as log
_ = numpy.newaxis
_identity = lambda x: x
_ArgDict = Mapping[str, numpy.ndarray]
class Topology:
'''topology base class
Parameters
----------
spaces : :class:`tuple` of :class:`str`
The unique, ordered list of spaces on which this topology is defined.
space_dims : :class:`tuple` of :class:`int`
The dimension of each space in :attr:`spaces`.
references : :class:`nutils.elementseq.References`
The references.
Attributes
----------
spaces : :class:`tuple` of :class:`str`
The unique, ordered list of spaces on which this topology is defined.
space_dims : :class:`tuple` of :class:`int`
The dimension of each space in :attr:`spaces`.
references : :class:`nutils.elementseq.References`
The references.
ndims : :class:`int`
The dimension of this topology.
'''
@staticmethod
def empty(spaces: Iterable[str], space_dims: Iterable[int], ndims: int) -> 'Topology':
'''Return an empty topology.
Parameters
----------
spaces : :class:`tuple` of :class:`str`
The unique, ordered list of spaces on which the empty topology is defined.
space_dims : :class:`tuple` of :class:`int`
The dimension of each space in :attr:`spaces`.
ndims : :class:`int`
The dimension of the empty topology.
Returns
-------
:class:`Topology`
The empty topology.
See Also
--------
:meth:`empty_like` : create an empty topology with spaces and dimension copied from another topology
'''
return _Empty(tuple(spaces), tuple(space_dims), ndims)
def empty_like(self) -> 'Topology':
'''Return an empty topology with the same spaces and dimensions as this topology.
Returns
-------
:class:`Topology`
The empty topology.
See Also
--------
:meth:`empty_like` : create an empty topology with custom spaces and dimension
'''
return Topology.empty(self.spaces, self.space_dims, self.ndims)
def disjoint_union(*topos: 'Topology') -> 'Topology':
'''Return the union of the given disjoint topologies.
Parameters
----------
*topos : :class:`Topology`
The disjoint parts.
Returns
-------
:class:`Topology`
The union.
'''
if len(topos) == 0:
raise ValueError('Cannot take the disjoint union of zero topologies. \
Suggestion: include an empty topology (see \
`Topology.empty_like`).')
empty = Topology.empty_like(topos[0])
if not all(topo.spaces == empty.spaces and topo.space_dims == empty.space_dims and topo.ndims == empty.ndims for topo in topos):
raise ValueError('The topologies must have the same spaces and dimensions.')
unempty = tuple(filter(None, topos))
if unempty:
return reduce(_DisjointUnion, unempty)
else:
return empty
def __init__(self, spaces: Sequence[str], space_dims: Sequence[int], references: References) -> None:
assert isinstance(spaces, Sequence) and all(isinstance(space, str) for space in spaces), f'spaces={spaces!r}'
assert isinstance(space_dims, Sequence) and all(isinstance(space_dim, int) for space_dim in space_dims), f'space_dims={space_dims!r}'
assert isinstance(references, References), f'references={references!r}'
self.spaces = tuple(spaces)
self.space_dims = tuple(space_dims)
self.references = references
self.ndims = references.ndims
super().__init__()
def __str__(self) -> str:
'string representation'
return '{}(#{})'.format(self.__class__.__name__, len(self))
def __len__(self) -> int:
return len(self.references)
def get_groups(self, *groups: str) -> 'Topology':
'''Return the union of the given groups.
Parameters
----------
*groups : :class:`str`
The identifiers of the groups.
Returns
-------
:class:`Topology`
The union of the given groups.
'''
return self.empty_like()
def take(self, __indices: Union[numpy.ndarray, Sequence[int]]) -> 'Topology':
'''Return the selected elements as a disconnected topology.
The indices refer to the raveled list of elements in this topology. The
indices are treated as a set: duplicate indices are silently ignored and
the returned elements have the same order as in this topology.
Parameters
----------
indices : integer :class:`numpy.ndarray` or similar
The one-dimensional array of element indices.
Returns
-------
:class:`Topology`
The selected elements.
See Also
--------
:meth:`compress` : select elements using a mask
'''
indices = numpy.asarray(__indices)
if indices.ndim != 1:
raise ValueError('expected a one-dimensional array')
if not indices.size:
return self.empty_like()
indices = numpy.unique(indices.astype(int, casting='same_kind'))
if indices[0] < 0 or indices[-1] >= len(self):
raise IndexError('element index out of range')
return self.take_unchecked(indices)
def take_unchecked(self, __indices: numpy.ndarray) -> 'Topology':
return _Take(self, __indices)
def compress(self, __mask: Union[numpy.ndarray, Sequence[bool]]) -> 'Topology':
'''Return the selected elements as a disconnected topology.
The mask refers to the raveled list of elements in this topology.
Parameters
----------
mask : boolean :class:`numpy.ndarray` or similar
The one-dimensional array of elements to select.
Returns
-------
:class:`Topology`
The selected elements.
See Also
--------
:meth:`take` : select elements by index
'''
mask = numpy.asarray(__mask)
if mask.ndim != 1:
raise ValueError('expected a one-dimensional array')
if len(mask) != len(self):
raise ValueError('length of mask does not match number of elements')
indices, = numpy.where(__mask)
if len(indices):
return self.take_unchecked(indices)
else:
return self.empty_like()
def slice(self, __s: slice, __idim: int) -> 'Topology':
'''Return a slice of the given dimension index.
Parameters
----------
s : :class:`slice`
The slice.
idim : :class:`int`
The dimension index.
Returns
-------
:class:`Topology`
The slice.
'''
if not 0 <= __idim < self.ndims:
raise IndexError('dimension index out of range')
return self.slice_unchecked(__s, __idim)
def slice_unchecked(self, __s: slice, __idim: int) -> 'Topology':
raise ValueError('cannot slice an unstructured topology')
def __getitem__(self, item: Any) -> 'Topology':
if isinstance(item, str):
topo = self.get_groups(*item.split(','))
elif isinstance(item, Sequence) and all(isinstance(i, str) for i in item):
topo = self.get_groups(*item) if item else self
elif isinstance(item, slice):
if item == slice(None):
return self
else:
return self.slice(item, 0)
elif isinstance(item, Sequence) and all(i == ... or isinstance(i, slice) for i in item):
if ... in item:
item = list(item)
i = item.index(...)
if ... in item[i+1:]:
raise ValueError('only one ellipsis is allowed')
item[i:i+1] = [slice(None)] * max(0, self.ndims - len(item) + 1)
if len(item) > self.ndims:
raise ValueError('too many indices: topology is {}-dimension, but {} were indexed'.format(self.ndims, len(item)))
topo = self
for idim, indices in enumerate(item):
if indices != slice(None):
topo = topo.slice(indices, idim)
return topo
elif numeric.isintarray(item) and item.ndim == 1 or isinstance(item, Sequence) and all(isinstance(i, int) for i in item):
return self.take(item)
elif numeric.isboolarray(item) and item.ndim == 1 and len(item) == len(self):
return self.compress(item)
else:
raise NotImplementedError
if not topo:
raise KeyError(item)
return topo
def __mul__(self, other: Any) -> 'Topology':
if isinstance(other, Topology):
return _Mul(self, other)
else:
return NotImplemented
def __and__(self, other: Any) -> 'Topology':
if not isinstance(other, Topology):
return NotImplemented
elif self.spaces != other.spaces or self.space_dims != other.space_dims or self.ndims != other.ndims:
raise ValueError('The topologies must have the same spaces and dimensions.')
elif not self or not other:
return self.empty_like()
else:
return NotImplemented
__rand__ = __and__
def __or__(self, other: Any) -> 'Topology':
if not isinstance(other, Topology):
return NotImplemented
elif self.spaces != other.spaces or self.space_dims != other.space_dims or self.ndims != other.ndims:
raise ValueError('The topologies must have the same spaces and dimensions.')
elif not self:
return other
elif not other:
return self
else:
return NotImplemented
__ror__ = __or__
@property
def border_transforms(self) -> transformseq.Transforms:
raise NotImplementedError
@property
def refine_iter(self) -> 'Topology':
topo = self
while True:
yield topo
topo = topo.refined
@property
def f_index(self) -> function.Array:
'''The evaluable index of the element in this topology.'''
raise NotImplementedError
@property
def f_coords(self) -> function.Array:
'''The evaluable element local coordinates.'''
raise NotImplementedError
def basis(self, name: str, *args, **kwargs) -> function.Basis:
'''
Create a basis.
'''
if self.ndims == 0:
return function.PlainBasis([[[1]]], [[0]], 1, self.f_index, self.f_coords)
split = name.split('-', 1)
if len(split) == 2 and split[0] in ('h', 'th'):
name = split[1] # default to non-hierarchical bases
if split[0] == 'th':
kwargs.pop('truncation_tolerance', None)
f = getattr(self, 'basis_' + name)
return f(*args, **kwargs)
def sample(self, ischeme: str, degree: int) -> Sample:
'Create sample.'
raise NotImplementedError
@single_or_multiple
def integrate_elementwise(self, funcs: Iterable[function.Array], *, degree: int, asfunction: bool = False, ischeme: str = 'gauss', arguments: Optional[_ArgDict] = None) -> Union[List[numpy.ndarray], List[function.Array]]:
'element-wise integration'
retvals = [sparse.toarray(retval) for retval in self.sample(ischeme, degree).integrate_sparse(
[function.kronecker(func, pos=self.f_index, length=len(self), axis=0) for func in funcs], arguments=arguments)]
if asfunction:
return [function.get(retval, 0, self.f_index) for retval in retvals]
else:
return retvals
@single_or_multiple
def elem_mean(self, funcs: Iterable[function.Array], geometry: Optional[function.Array] = None, ischeme: str = 'gauss', degree: Optional[int] = None, **kwargs) -> List[numpy.ndarray]:
ischeme, degree = element.parse_legacy_ischeme(ischeme if degree is None else ischeme + str(degree))
funcs = (1,)+funcs
if geometry is not None:
funcs = [func * function.J(geometry) for func in funcs]
area, *integrals = self.integrate_elementwise(funcs, ischeme=ischeme, degree=degree, **kwargs)
return [integral / area[(slice(None),)+(_,)*(integral.ndim-1)] for integral in integrals]
@single_or_multiple
def integrate(self, funcs: Iterable[function.IntoArray], ischeme: str = 'gauss', degree: Optional[int] = None, edit=None, *, arguments: Optional[_ArgDict] = None) -> Tuple[numpy.ndarray, ...]:
'integrate functions'
ischeme, degree = element.parse_legacy_ischeme(ischeme if degree is None else ischeme + str(degree))
if edit is not None:
funcs = [edit(func) for func in funcs]
return self.sample(ischeme, degree).integrate(funcs, **arguments or {})
def integral(self, func: function.IntoArray, ischeme: str = 'gauss', degree: Optional[int] = None, edit=None) -> function.Array:
'integral'
ischeme, degree = element.parse_legacy_ischeme(ischeme if degree is None else ischeme + str(degree))
if edit is not None:
funcs = edit(func)
return self.sample(ischeme, degree).integral(func)
def projection(self, fun: function.Array, onto: function.Array, geometry: function.Array, **kwargs) -> function.Array:
'project and return as function'
return self.project(fun, onto, geometry, **kwargs) @ onto
@log.withcontext
def project(self, fun: function.Array, onto: function.Array, geometry: function.Array, ischeme: str = 'gauss', degree: Optional[int] = None, droptol: float = 1e-12, exact_boundaries: bool = False, constrain=None, verify=None, ptype='lsqr', edit=None, *, arguments: Optional[_ArgDict] = None, **solverargs) -> numpy.ndarray:
'L2 projection of function onto function space'
log.debug('projection type:', ptype)
if degree is not None:
ischeme += str(degree)
if constrain is None:
constrain = util.NanVec(onto.shape[0])
else:
constrain = constrain.copy()
if exact_boundaries:
constrain |= self.boundary.project(fun, onto, geometry, constrain=constrain, ischeme=ischeme, droptol=droptol, ptype=ptype, edit=edit, arguments=arguments)
assert isinstance(constrain, util.NanVec)
assert constrain.shape == onto.shape[:1]
avg_error = None # setting this depends on projection type
if ptype == 'lsqr':
assert ischeme is not None, 'please specify an integration scheme for lsqr-projection'
fun2 = function.asarray(fun)**2
if len(onto.shape) == 1:
Afun = function.outer(onto)
bfun = onto * fun
elif len(onto.shape) == 2:
Afun = function.outer(onto).sum(2)
bfun = function.sum(onto * fun, -1)
if fun2.ndim:
fun2 = fun2.sum(-1)
else:
raise Exception
assert fun2.ndim == 0
J = function.J(geometry)
A, b, f2, area = self.integrate([Afun*J, bfun*J, fun2*J, J], ischeme=ischeme, edit=edit, arguments=arguments)
N = A.rowsupp(droptol)
if numpy.equal(b, 0).all():
constrain[~constrain.where & N] = 0
avg_error = 0.
else:
solvecons = constrain.copy()
solvecons[~(constrain.where | N)] = 0
u = A.solve(b, constrain=solvecons, **solverargs)
constrain[N] = u[N]
err2 = f2 - numpy.dot(2 * b - A @ u, u) # can be negative ~zero due to rounding errors
avg_error = numpy.sqrt(err2) / area if err2 > 0 else 0
elif ptype == 'convolute':
assert ischeme is not None, 'please specify an integration scheme for convolute-projection'
if len(onto.shape) == 1:
ufun = onto * fun
afun = onto
elif len(onto.shape) == 2:
ufun = function.sum(onto * fun, axis=-1)
afun = function.norm2(onto)
else:
raise Exception
J = function.J(geometry)
u, scale = self.integrate([ufun*J, afun*J], ischeme=ischeme, edit=edit, arguments=arguments)
N = ~constrain.where & (scale > droptol)
constrain[N] = u[N] / scale[N]
elif ptype == 'nodal':
bezier = self.sample('bezier', 2)
W, F = bezier.integrate([onto, fun * onto])
I = ~constrain.where
constrain[I] = F[I] / W[I]
else:
raise Exception('invalid projection {!r}'.format(ptype))
numcons = constrain.where.sum()
info = 'constrained {}/{} dofs'.format(numcons, constrain.size)
if avg_error is not None:
info += ', error {:.2e}/area'.format(avg_error)
log.info(info)
if verify is not None:
assert numcons == verify, 'number of constraints does not meet expectation: {} != {}'.format(numcons, verify)
return constrain
def refined_by(self, refine: Union['Topology', Iterable[int], Iterable[Tuple[transform.TransformItem,...]]]) -> 'Topology':
'''Create hierarchically refined topology by selectively refining
elements.
Parameters
----------
refine : :class:`Topology` or iterable of :class:`int` or transformation chains
The elements to refine, specified either as a subtopology or by
their indices or locations in the topology.
Returns
-------
:class:`Topology`
The refined topology.
'''
if isinstance(refine, Topology):
refine = refine.transforms
elif not isinstance(refine, numpy.ndarray):
# We convert refine to a tuple below both as a test for iterability
# and to account for the possibility that it is a generator
try:
refine = tuple(refine)
except:
raise ValueError('refined_by expects an iterable argument') from None
if len(refine) == 0:
return self
if isinstance(refine[0], tuple): # use first element for detection
try:
transforms = self.transforms
except:
raise TypeError('topology supports only refinement by element indices') from None
refine = [transforms.index_with_tail(item)[0] for item in refine]
refine = numpy.asarray(refine)
if refine.dtype != int:
raise ValueError(f'expected an array of dtype int, got {refine.dtype}')
return self._refined_by(numpy.unique(refine))
def _refined_by(self, refine: Iterable[int]) -> 'Topology':
raise NotImplementedError
@cached_property
def refined(self) -> 'Topology':
return self.refine_spaces(self.spaces)
def refine(self, __arg: Union[int, Iterable[str], Mapping[str, int]]) -> 'Topology':
'''Return the refined topology.
If the argument is an :class:`int`, then this method behaves like
:meth:`refine_count`. If the argument is a sequence of :class:`str`, then
this method behaves like :meth:`refine_spaces`. If the argument is a
dictionary of :class:`str` and :class:`int`, then this method behaves like
:meth:`refine_spaces_count`.
Returns
-------
:class:`Topology`
The refined topology.
See Also
--------
:meth:`refine_count` : refine a topology the given amount times
:meth:`refine_spaces` : refine the given spaces of the topology
:meth:`refine_spaces_count` : refine the given spaces the given amount times
'''
if isinstance(__arg, int):
return self.refine_count(__arg)
elif isinstance(__arg, Mapping):
return self.refine_spaces_count(__arg)
elif isinstance(__arg, Iterable):
return self.refine_spaces(__arg)
else:
raise ValueError
def refine_count(self, count: int) -> 'Topology':
'''Return the topology refined `count` times.
Parameters
----------
count : :class:`int`
The number of times to refine. `count` is allowed to be zero, in which
case the original topology is returned, but not negative.
Returns
-------
:class:`Topology`
The refined topology.
See Also
--------
:meth:`refine_spaces` : refine the given spaces of the topology
:meth:`refine_spaces_count` : refine the given spaces the given amount times
'''
if count < 0:
raise ValueError('Negative counts are invalid.')
topo = self
for i in range(count):
topo = topo.refined
return topo
def refine_spaces(self, __spaces: Iterable[str]) -> 'Topology':
'''Return the topology with the given spaces refined once.
Parameters
----------
spaces : iterable of :class:`str`
The spaces to refine. It is an error to specify spaces that do not
exist in this topology. It is allowed to specify no spaces, in which
case the original topology is returned.
Returns
-------
:class:`Topology`
The refined topology.
See Also
--------
:meth:`refine_count` : refine a topology the given amount times
:meth:`refine_spaces_count` : refine the given spaces the given amount times
'''
spaces = frozenset(__spaces)
for space in sorted(spaces):
if space not in self.spaces:
raise ValueError('This topology does not have space {}.'.format(space))
return self.refine_spaces_unchecked(spaces)
def refine_spaces_unchecked(self, __spaces: FrozenSet[str]) -> 'Topology':
'''Return the topology with the given spaces refined once.
Parameters
----------
spaces : iterable of :class:`str`
The spaces to refine. It is an error to specify spaces that do not
exist in this topology. It is allowed to specify no spaces, in which
case the original topology is returned.
Returns
-------
:class:`Topology`
The refined topology.
Notes
-----
This method does not check the validity of the arguments. Use
:meth:`refine_spaces` instead unless you're absolutely sure what you are
doing.
'''
raise NotImplementedError
def refine_spaces_count(self, count: Mapping[str, int]) -> 'Topology':
'''Return the topology with the given spaces refined the given amount times.
Parameters
----------
spaces : mapping of :class:`str` to :class:`int`
The spaces to refine together with the count. It is an error to specify
spaces that do not exist in this topology. It is allowed to specify no
spaces, in which case the original topology is returned.
Returns
-------
:class:`Topology`
The refined topology.
See Also
--------
:meth:`refine_count` : refine a topology the given amount times
:meth:`refine_spaces` : refine the given spaces of the topology
'''
if not all(n >= 0 for n in count.values()):
raise ValueError('Negative counts are invalid.')
topo = self
for i in itertools.count():
spaces = tuple(space for space, n in count.items() if n > i)
if not spaces:
break
topo = topo.refine_spaces(spaces)
return topo
def trim(self, levelset: function.Array, maxrefine: int, ndivisions: int = 8, name: str = 'trimmed', leveltopo: Optional['Topology'] = None, *, arguments: Optional[_ArgDict] = None) -> 'Topology':
'trim element along levelset'
raise NotImplementedError
def subset(self, topo: 'Topology', newboundary: Optional[Union[str, 'Topology']] = None, strict: bool = False) -> 'Topology':
'intersection'
raise NotImplementedError
def withgroups(self, vgroups: Mapping[str, Union[str, 'Topology']] = {}, bgroups: Mapping[str, Union[str, 'Topology']] = {}, igroups: Mapping[str, Union[str, 'Topology']] = {}, pgroups: Mapping[str, Union[str, 'Topology']] = {}) -> 'Topology':
if all(isinstance(v, str) for g in (vgroups, bgroups, igroups) for v in g.values()) and not pgroups:
return _WithGroupAliases(self, types.frozendict(vgroups), types.frozendict(bgroups), types.frozendict(igroups))
else:
raise NotImplementedError
def withsubdomain(self, **kwargs: 'Topology') -> 'Topology':
return self.withgroups(vgroups=kwargs)
def withboundary(self, **kwargs: 'Topology') -> 'Topology':
return self.withgroups(bgroups=kwargs)
def withinterfaces(self, **kwargs: 'Topology') -> 'Topology':
return self.withgroups(igroups=kwargs)
def withpoints(self, **kwargs: 'Topology') -> 'Topology':
return self.withgroups(pgroups=kwargs)
@log.withcontext
def volume(self, geometry: function.Array, ischeme: str = 'gauss', degree: int = 1, *, arguments: Optional[_ArgDict] = None) -> numpy.ndarray:
return self.integrate(function.J(geometry), ischeme=ischeme, degree=degree, arguments=arguments)
@log.withcontext
def check_boundary(self, geometry: function.Array, elemwise: bool = False, ischeme: str = 'gauss', degree: int = 1, tol: float = 1e-15, print=print, *, arguments: Optional[_ArgDict] = None) -> None:
if elemwise:
for ref in self.references:
ref.check_edges(tol=tol, print=print)
volume = self.volume(geometry, ischeme=ischeme, degree=degree, arguments=arguments)
J = function.J(geometry)
zeros, volumes = self.boundary.integrate([geometry.normal()*J, geometry*geometry.normal()*J], ischeme=ischeme, degree=degree, arguments=arguments)
if numpy.greater(abs(zeros), tol).any():
print('divergence check failed: {} != 0'.format(zeros))
if numpy.greater(abs(volumes - volume), tol).any():
print('divergence check failed: {} != {}'.format(volumes, volume))
def indicator(self, subtopo: Union[str, 'Topology']) -> 'Topology':
'''Create an indicator function for a subtopology.'''
raise NotImplementedError
def select(self, indicator: function.Array, ischeme: str = 'bezier2', **kwargs: numpy.ndarray) -> 'Topology':
# Select elements where `indicator` is strict positive at any of the
# integration points defined by `ischeme`. We sample `indicator > 0`
# together with the element index (`self.f_index`) and keep all indices
# with at least one positive result.
sample = self.sample(*element.parse_legacy_ischeme(ischeme))
isactive, ielem = sample.eval([indicator > 0, self.f_index], **kwargs)
selected = types.frozenarray(numpy.unique(ielem[isactive]))
return self[selected]
def locate(self, geom, coords, *, tol=0, eps=0, maxiter=0, arguments=None, weights=None, maxdist=None, ischeme=None, scale=None, skip_missing=False) -> Sample:
'''Create a sample based on physical coordinates.
In a finite element application, functions are commonly evaluated in points
that are defined on the topology. The reverse, finding a point on the
topology based on a function value, is often a nonlinear process and as
such involves Newton iterations. The ``locate`` function facilitates this
search process and produces a :class:`nutils.sample.Sample` instance that
can be used for the subsequent evaluation of any function in the given
physical points.
Example:
>>> from . import mesh
>>> domain, geom = mesh.unitsquare(nelems=3, etype='mixed')
>>> sample = domain.locate(geom, [[.9, .4]], tol=1e-12)
>>> sample.eval(geom).round(5).tolist()
[[0.9, 0.4]]
Locate requires a geometry function, an array of coordinates, and at least
one of ``tol`` and ``eps`` to set the tolerance in physical of element
space, respectively; if both are specified the least restrictive takes
precedence.
Args
----
geom : 1-dimensional :class:`nutils.function.Array`
Geometry function of length ``ndims``.
coords : 2-dimensional :class:`float` array
Array of coordinates with ``ndims`` columns.
tol : :class:`float` (default: 0)
Maximum allowed distance in physical coordinates between target and
located point.
eps : :class:`float` (default: 0)
Maximum allowed distance in element coordinates between target and
located point.
maxiter : :class:`int` (default: 0)
Maximum allowed number of Newton iterations, or 0 for unlimited.
arguments : :class:`dict` (default: None)
Arguments for function evaluation.
weights : :class:`float` array (default: None)
Optional weights, in case ``coords`` are quadrature points, making the
resulting sample suitable for integration.
maxdist : :class:`float` (default: None)
Speed up failure by setting a physical distance between point and
element centroid above which the element is rejected immediately. If
all points are expected to be located then this can safely be left
unspecified.
skip_missing : :class:`bool` (default: False)
When set to true, skip points that are not found (for instance because
they fall outside the domain) in the returned sample. When set to false
(the default) missing points raise a ``LocateError``.
Returns
-------
located : :class:`nutils.sample.Sample`
'''
raise NotImplementedError
@cached_property
def boundary(self) -> 'Topology':
'''
:class:`Topology`:
The boundary of this topology.
'''
return self.boundary_spaces(self.spaces)
def boundary_spaces(self, __spaces: Iterable[str]) -> 'Topology':
'''Return the boundary in the given spaces.
Parameters
----------
spaces : iterable of :class:`str`
Nonstrict subset of :attr:`spaces`. Duplicates are silently ignored.
Returns
-------
:class:`Topology`
The boundary in the given spaces.
Raises
------
:class:`ValueError`
If the topology is 0D or the set of spaces is empty or not a subset of :attr:`spaces`.
'''
spaces = frozenset(__spaces)
for space in sorted(spaces):
if space not in self.spaces:
raise ValueError('This topology does not have space {}.'.format(space))
if self.ndims == 0 or sum(self.space_dims[self.spaces.index(space)] for space in spaces) == 0:
raise ValueError('A 0D topology has no boundary.')
return self.boundary_spaces_unchecked(spaces)
def boundary_spaces_unchecked(self, __spaces: FrozenSet[str]) -> 'Topology':
'''Return the boundary in the given spaces.
The topology must be at least one-dimensional.
Parameters
----------
spaces : :class:`frozenset` of :class:`str`
Unempty, nonstrict subset of :attr:`spaces`.
Returns
-------
:class:`Topology`
The boundary in the given spaces.
Notes
-----
This method does not check the validity of the arguments or the dimension
of the topology. Use :meth:`boundary_spaces` instead unless you're
absolutely sure what you are doing.
'''
raise NotImplementedError
@cached_property
def interfaces(self) -> 'Topology':
return self.interfaces_spaces(self.spaces)
def interfaces_spaces(self, __spaces: Iterable[str]) -> 'Topology':
'''Return the interfaces in the given spaces.
Parameters
----------
spaces : iterable of :class:`str`
Nonstrict subset of :attr:`spaces`. Duplicates are silently ignored.
Returns
-------
:class:`Topology`
The interfaces in the given spaces.
Raises
------
:class:`ValueError`
If the topology is 0D or the set of spaces is empty or not a subset of :attr:`spaces`.
'''
spaces = frozenset(__spaces)
for space in sorted(spaces):
if space not in self.spaces:
raise ValueError('This topology does not have space {}.'.format(space))
if self.ndims == 0 or sum(self.space_dims[self.spaces.index(space)] for space in spaces) == 0:
raise ValueError('A 0D topology has no interfaces.')
return self.interfaces_spaces_unchecked(spaces)
def interfaces_spaces_unchecked(self, __spaces: FrozenSet[str]) -> 'Topology':
'''Return the interfaces in the given spaces.
The topology must be at least one-dimensional.
Parameters
----------
spaces : :class:`frozenset` of :class:`str`
Unempty, nonstrict subset of :attr:`spaces`.
Returns
-------
:class:`Topology`
The interfaces in the given spaces.
Notes
-----
This method does not check the validity of the arguments or the dimension
of the topology. Use :meth:`interfaces_spaces` instead unless you're
absolutely sure what you are doing.
'''
raise NotImplementedError
def basis_discont(self, degree: int) -> function.Basis:
'discontinuous shape functions'
assert numeric.isint(degree) and degree >= 0
if self.references.isuniform:
coeffs = [self.references[0].get_poly_coeffs('bernstein', degree=degree)]*len(self.references)
else:
coeffs = [ref.get_poly_coeffs('bernstein', degree=degree) for ref in self.references]
return function.DiscontBasis(coeffs, self.f_index, self.f_coords)
if environ.get('NUTILS_TENSORIAL', None) == 'test': # pragma: nocover
from unittest import SkipTest
class _TensorialTopology(Topology):
def __and__(self, other: Any) -> Topology:
result = super().__and__(other)
if type(self) == type(other) and result is NotImplemented:
raise SkipTest('`{}` does not implement `Topology.__and__`'.format(type(self).__qualname__))
return result
def __rand__(self, other: Any) -> Topology:
result = super().__and__(other)
if result is NotImplemented:
raise SkipTest('`{}` does not implement `Topology.__and__`'.format(type(self).__qualname__))
return result
def __sub__(self, other: Any) -> Topology:
if type(self) == type(other):
raise SkipTest('`{}` does not implement `Topology.__sub__`'.format(type(self).__qualname__))
else:
return NotImplemented
def __rsub__(self, other: Any) -> Topology:
if isinstance(other, Topology):
raise SkipTest('`{}` does not implement `Topology.__sub__`'.format(type(self).__qualname__))
else:
return NotImplemented
@property
def space(self) -> str:
raise SkipTest('`{}` does not implement `Topology.space`'.format(type(self).__qualname__))
@property
def transforms(self) -> transformseq.Transforms:
raise SkipTest('`{}` does not implement `Topology.transforms`'.format(type(self).__qualname__))
@property
def opposites(self) -> transformseq.Transforms:
raise SkipTest('`{}` does not implement `Topology.opposites`'.format(type(self).__qualname__))
@property
def border_transforms(self) -> transformseq.Transforms:
raise SkipTest('`{}` does not implement `Topology.border_transforms`'.format(type(self).__qualname__))
@property
def f_index(self) -> function.Array:
raise SkipTest('`{}` does not implement `Topology.f_index`'.format(type(self).__qualname__))
@property
def f_coords(self) -> function.Array:
raise SkipTest('`{}` does not implement `Topology.f_coords`'.format(type(self).__qualname__))
def refined_by(self, refine: Iterable[int]) -> Topology:
raise SkipTest('`{}` does not implement `Topology.refined_by`'.format(type(self).__qualname__))
def trim(self, levelset: function.Array, maxrefine: int, ndivisions: int = 8, name: str = 'trimmed', leveltopo: Optional[Topology] = None, *, arguments: Optional[_ArgDict] = None) -> Topology:
raise SkipTest('`{}` does not implement `Topology.trim`'.format(type(self).__qualname__))
def subset(self, topo: Topology, newboundary: Optional[Union[str, Topology]] = None, strict: bool = False) -> Topology:
raise SkipTest('`{}` does not implement `Topology.subset`'.format(type(self).__qualname__))
def withgroups(self, vgroups: Mapping[str, Union[str, Topology]] = {}, bgroups: Mapping[str, Union[str, Topology]] = {}, igroups: Mapping[str, Union[str, Topology]] = {}, pgroups: Mapping[str, Union[str, Topology]] = {}) -> Topology:
try:
return super().withgroups(vgroups, bgroups, igroups, pgroups)
except NotImplementedError:
raise SkipTest('`{}` does not implement `Topology.withgroups`'.format(type(self).__qualname__))
def indicator(self, subtopo: Union[str, Topology]) -> Topology:
raise SkipTest('`{}` does not implement `Topology.indicator`'.format(type(self).__qualname__))
def locate(self, geom, coords, *, tol=0, eps=0, maxiter=0, arguments=None, weights=None, maxdist=None, ischeme=None, scale=None, skip_missing=False) -> Sample:
raise SkipTest('`{}` does not implement `Topology.locate`'.format(type(self).__qualname__))
else:
_TensorialTopology = Topology
class _EmptyUnlowerable(function.Array):
def lower(self, args: function.LowerArgs) -> evaluable.Array:
raise ValueError('cannot lower')