-
Notifications
You must be signed in to change notification settings - Fork 12
/
field.py
3796 lines (3041 loc) · 121 KB
/
field.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
import collections
import math
import numbers
import struct
import warnings
import h5py
import numpy as np
import pandas as pd
import ubermagutil.typesystem as ts
import vtk
import vtk.util.numpy_support as vns
import xarray as xr
import discretisedfield as df
import discretisedfield.plotting as dfp
import discretisedfield.util as dfu
from . import html
from .mesh import Mesh
# TODO: tutorials, line operations
@ts.typesystem(mesh=ts.Typed(expected_type=Mesh, const=True),
dim=ts.Scalar(expected_type=int, positive=True, const=True))
class Field(collections.abc.Callable): # could be avoided by using type hints
"""Finite-difference field.
This class specifies a finite-difference field and defines operations for
its analysis and visualisation. The field is defined on a finite-difference
mesh (`discretisedfield.Mesh`) passed using ``mesh``. Another value that
must be passed is the dimension of the field's value using ``dim``. For
instance, for a scalar field, ``dim=1`` and for a three-dimensional vector
field ``dim=3`` must be passed. The value of the field can be set by
passing ``value``. For details on how the value can be defined, refer to
``discretisedfield.Field.value``. Similarly, if the field has ``dim>1``,
the field can be normalised by passing ``norm``. For details on setting the
norm, please refer to ``discretisedfield.Field.norm``.
Parameters
----------
mesh : discretisedfield.Mesh
Finite-difference rectangular mesh.
dim : int
Dimension of the field's value. For instance, if `dim=3` the field is a
three-dimensional vector field and for `dim=1` the field is a scalar
field.
value : array_like, callable, dict, optional
Please refer to ``discretisedfield.Field.value`` property. Defaults to
0, meaning that if the value is not provided in the initialisation,
"zero-field" will be defined.
norm : numbers.Real, callable, optional
Please refer to ``discretisedfield.Field.norm`` property. Defaults to
``None`` (``norm=None`` defines no norm).
dtype : str, type, np.dtype, optional
Data type of the underlying numpy array. If not specified the best data
type is automatically determined if ``value`` is array_like, for
callable and dict ``value`` the numpy default (currently
``float64``) is used. Defaults to ``None``.
Examples
--------
1. Defining a uniform three-dimensional vector field on a nano-sized thin
film.
>>> import discretisedfield as df
...
>>> p1 = (-50e-9, -25e-9, 0)
>>> p2 = (50e-9, 25e-9, 5e-9)
>>> cell = (1e-9, 1e-9, 0.1e-9)
>>> mesh = df.Mesh(region=df.Region(p1=p1, p2=p2), cell=cell)
>>> dim = 3
>>> value = (0, 0, 1)
...
>>> field = df.Field(mesh=mesh, dim=dim, value=value)
>>> field
Field(...)
>>> field.average
(0.0, 0.0, 1.0)
2. Defining a scalar field.
>>> p1 = (-10, -10, -10)
>>> p2 = (10, 10, 10)
>>> n = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, n=n)
>>> dim = 1
>>> value = 3.14
...
>>> field = df.Field(mesh=mesh, dim=dim, value=value)
>>> field
Field(...)
>>> field.average
3.14
3. Defining a uniform three-dimensional normalised vector field.
>>> import discretisedfield as df
...
>>> p1 = (-50e9, -25e9, 0)
>>> p2 = (50e9, 25e9, 5e9)
>>> cell = (1e9, 1e9, 0.1e9)
>>> mesh = df.Mesh(region=df.Region(p1=p1, p2=p2), cell=cell)
>>> dim = 3
>>> value = (0, 0, 8)
>>> norm = 1
...
>>> field = df.Field(mesh=mesh, dim=dim, value=value, norm=norm)
>>> field
Field(...)
>>> field.average
(0.0, 0.0, 1.0)
.. seealso:: :py:func:`~discretisedfield.Mesh`
"""
def __init__(self, mesh, dim, value=0., norm=None, components=None,
dtype=None):
self.mesh = mesh
self.dim = dim
self.dtype = dtype
self.value = value
self.norm = norm
self._components = None # required in here for correct initialisation
self.components = components
@property
def value(self):
"""Field value representation.
This property returns a representation of the field value if it exists.
Otherwise, ``discretisedfield.Field.array`` containing all field values
is returned.
The value of the field can be set using a scalar value for ``dim=1``
fields (e.g. ``value=3``) or ``array_like`` value for ``dim>1`` fields
(e.g. ``value=(1, 2, 3)``). Alternatively, the value can be defined
using a callable object, which takes a point tuple as an input argument
and returns a value of appropriate dimension. Internally, callable
object is called for every point in the mesh on which the field is
defined. For instance, callable object can be a Python function or
another ``discretisedfield.Field``. Finally, ``numpy.ndarray`` with
shape ``(*self.mesh.n, dim)`` can be passed.
Parameters
----------
value : numbers.Real, array_like, callable, dict
For scalar fields (``dim=1``) ``numbers.Real`` values are allowed.
In the case of vector fields, ``array_like`` (list, tuple,
numpy.ndarray) value with length equal to `dim` should be used.
Finally, the value can also be a callable (e.g. Python function or
another field), which for every coordinate in the mesh returns a
valid value. If ``value=0``, all values in the field will be set to
zero independent of the field dimension.
If subregions are defined value can be initialised with a dict.
Allowed keys are names of all subregions and ``default``. Items
must be either ``numbers.Real`` for ``dim=1`` or ``array_like``
for ``dim=3``. If subregion names are missing, the value of
``default`` is used if given. If parts of the region are not
contained within one subregion ``default`` is used if specified,
else these values are set to 0.
Returns
-------
array_like, callable, numbers.Real, numpy.ndarray
The value used (representation) for setting the field is returned.
However, if the actual value of the field does not correspond to
the initially used value anymore, a ``numpy.ndarray`` is returned
containing all field values.
Raises
------
ValueError
If unsupported type is passed.
Examples
--------
1. Different ways of setting and getting the field value.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (2, 2, 1)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
>>> value = (0, 0, 1)
...
>>> # if value is not specified, zero-field is defined
>>> field = df.Field(mesh=mesh, dim=3)
>>> field.value
0.0
>>> field.value = (0, 0, 1)
>>> field.value
(0, 0, 1)
>>> # Setting the field value using a Python function (callable).
>>> def value_function(point):
... x, y, z = point
... if x <= 1:
... return (0, 0, 1)
... else:
... return (0, 0, -1)
>>> field.value = value_function
>>> field.value
<function value_function at ...>
>>> # We now change the value of a single cell so that the
>>> # representation used for initialising field is not valid
>>> # anymore.
>>> field.array[0, 0, 0, :] = (0, 0, 0)
>>> field.value
array(...)
>>> field.value.shape
(2, 2, 1, 3)
2. Field with subregions in mesh
>>> import discretisedfield as df
...
>>> p1 = (0,0,0)
>>> p2 = (2,2,2)
>>> cell = (1,1,1)
>>> sub1 = df.Region(p1=(0,0,0), p2=(2,2,1))
>>> sub2 = df.Region(p1=(0,0,1), p2=(2,2,2))
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell,\
subregions={'s1': sub1, 's2': sub2})
>>> field = df.Field(mesh, dim=1, value={'s1': 1, 's2': 1})
>>> (field.array == 1).all()
True
>>> field = df.Field(mesh, dim=1, value={'s1': 1})
Traceback (most recent call last):
...
KeyError: ...
>>> field = df.Field(mesh, dim=1, value={'s1': 2, 'default': 1})
>>> (field.array == 1).all()
False
>>> (field.array == 0).any()
False
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell, subregions={'s': sub1})
>>> field = df.Field(mesh, dim=1, value={'s': 1})
Traceback (most recent call last):
...
KeyError: ...
>>> field = df.Field(mesh, dim=1, value={'default': 1})
>>> (field.array == 1).all()
True
.. seealso:: :py:func:`~discretisedfield.Field.array`
"""
value_array = dfu.as_array(self._value, self.mesh, self.dim,
dtype=self.dtype)
if np.array_equal(self.array, value_array):
return self._value
else:
return self.array
@value.setter
def value(self, val):
self._value = val
self.array = dfu.as_array(val, self.mesh, self.dim, dtype=self.dtype)
@property
def components(self):
"""Vector components of the field."""
return self._components
@components.setter
def components(self, components):
if components is not None:
if len(components) != self.dim:
raise ValueError('Number of components does not match'
f' {self.dim=}.')
if len(components) != len(set(components)):
raise ValueError('Components must be unique.')
for c in components:
if hasattr(self, c):
# redefining component labels is okay.
if self._components is None or c not in self._components:
raise ValueError(
f'Component name {c} is already '
'used by a different method/property.')
self._components = list(components)
else:
if 2 <= self.dim <= 3:
components = ['x', 'y', 'z'][:self.dim]
elif self.dim > 3:
warnings.warn(f'Component labels must be specified for '
f'{self.dim=} fields to get access to individual'
' vector components.')
self._components = components
@property
def array(self):
"""Field value as ``numpy.ndarray``.
The shape of the array is ``(*mesh.n, dim)``.
Parameters
----------
array : numpy.ndarray
Array with shape ``(*mesh.n, dim)``.
Returns
-------
numpy.ndarray
Field values array.
Raises
------
ValueError
If unsupported type or shape is passed.
Examples
--------
1. Accessing and setting the field array.
>>> import discretisedfield as df
>>> import numpy as np
...
>>> p1 = (0, 0, 0)
>>> p2 = (1, 1, 1)
>>> cell = (0.5, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
>>> value = (0, 0, 1)
...
>>> field = df.Field(mesh=mesh, dim=3, value=value)
>>> field.array
array(...)
>>> field.average
(0.0, 0.0, 1.0)
>>> field.array.shape
(2, 1, 1, 3)
>>> field.array = np.ones_like(field.array)
>>> field.array
array(...)
>>> field.average
(1.0, 1.0, 1.0)
.. seealso:: :py:func:`~discretisedfield.Field.value`
"""
return self._array
@array.setter
def array(self, val):
self._array = dfu.as_array(val, self.mesh, self.dim, dtype=self.dtype)
@property
def norm(self):
"""Norm of the field.
Computes the norm of the field and returns ``discretisedfield.Field``
with ``dim=1``. Norm of a scalar field is interpreted as an absolute
value of the field. Alternatively, ``discretisedfield.Field.__abs__``
can be called for obtaining the norm of the field.
The field norm can be set by passing ``numbers.Real``,
``numpy.ndarray``, or callable. If the field has ``dim=1`` or it
contains zero values, norm cannot be set and ``ValueError`` is raised.
Parameters
----------
numbers.Real, numpy.ndarray, callable
Norm value.
Returns
-------
discretisedfield.Field
Norm of the field if ``dim>1`` or absolute value for ``dim=1``.
Raises
------
ValueError
If the norm is set with wrong type, shape, or value. In addition,
if the field is scalar (``dim=1``) or the field contains zero
values.
Examples
--------
1. Manipulating the field norm.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (1, 1, 1)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(region=df.Region(p1=p1, p2=p2), cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=3, value=(0, 0, 1))
>>> field.norm
Field(...)
>>> field.norm.average
1.0
>>> field.norm = 2
>>> field.average
(0.0, 0.0, 2.0)
>>> field.value = (1, 0, 0)
>>> field.norm.average
1.0
>>> # An attempt to set the norm for a zero field.
>>> field.value = 0
>>> field.average
(0.0, 0.0, 0.0)
>>> field.norm = 1
Traceback (most recent call last):
...
ValueError: ...
.. seealso:: :py:func:`~discretisedfield.Field.__abs__`
"""
if self.dim == 1:
res = abs(self.value)
else:
res = np.linalg.norm(self.array, axis=-1)[..., np.newaxis]
return self.__class__(self.mesh, dim=1, value=res)
@norm.setter
def norm(self, val):
if val is not None:
if self.dim == 1:
msg = f'Cannot set norm for field with dim={self.dim}.'
raise ValueError(msg)
if not np.all(self.norm.array):
msg = 'Cannot normalise field with zero values.'
raise ValueError(msg)
self.array /= self.norm.array # normalise to 1
self.array *= dfu.as_array(val, self.mesh, dim=1, dtype=None)
def __abs__(self):
"""Field norm.
This is a convenience operator and it returns
``discretisedfield.Field.norm``. For details, please refer to
``discretisedfield.Field.norm``.
Returns
-------
discretisedfield.Field
Norm of the field if ``dim>1`` or absolute value for ``dim=1``.
Examples
--------
1. Computing the absolute value of a scalar field.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (5, 10, 13)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(region=df.Region(p1=p1, p2=p2), cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=1, value=-5)
>>> abs(field).average
5.0
.. seealso:: :py:func:`~discretisedfield.Field.norm`
"""
return self.norm
@property
def zero(self):
"""Zero field.
This method returns a zero field defined on the same mesh and with the
same value dimension.
Returns
-------
discretisedfield.Field
Zero field.
Examples
--------
1. Getting the zero-field.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (5, 10, 13)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(region=df.Region(p1=p1, p2=p2), cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=3, value=(3, -1, 1))
>>> zero_field = field.zero
>>> zero_field.average
(0.0, 0.0, 0.0)
"""
return self.__class__(self.mesh, dim=self.dim, value=0,
components=self.components)
@property
def orientation(self):
"""Orientation field.
This method computes the orientation (direction) of a vector field and
returns ``discretisedfield.Field`` with the same dimension. More
precisely, at every mesh discretisation cell, the vector is divided by
its norm, so that a unit vector is obtained. However, if the vector at
a discretisation cell is a zero-vector, it remains unchanged. In the
case of a scalar (``dim=1``) field, ``ValueError`` is raised.
Returns
-------
discretisedfield.Field
Orientation field.
Raises
------
ValueError
If the field is has ``dim=1``.
Examples
--------
1. Computing the orientation field.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (10, 10, 10)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=3, value=(6, 0, 8))
>>> field.orientation
Field(...)
>>> field.orientation.norm.average
1.0
"""
if self.dim == 1:
msg = (f'Cannot compute orientation field for a '
f'dim={self.dim} field.')
raise ValueError(msg)
orientation_array = np.divide(self.array,
self.norm.array,
where=(self.norm.array != 0))
return self.__class__(self.mesh, dim=self.dim, value=orientation_array,
components=self.components)
@property
def average(self):
"""Field average.
It computes the average of the field over the entire volume of the
mesh. It returns a tuple with the length same as the dimension
(``dim``) of the field.
Returns
-------
tuple
Field average tuple, whose length equals to the field's dimension.
Examples
--------
1. Computing the vector field average.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (5, 5, 5)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=3, value=(0, 0, 1))
>>> field.average
(0.0, 0.0, 1.0)
2. Computing the scalar field average.
>>> field = df.Field(mesh=mesh, dim=1, value=55)
>>> field.average
55.0
"""
return dfu.array2tuple(self.array.mean(axis=(0, 1, 2)))
def __repr__(self):
"""Representation string.
Internally `self._repr_html_()` is called and all html tags are removed
from this string.
Returns
-------
str
Representation string.
Example
-------
1. Getting representation string.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (2, 2, 1)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
...
>>> field = df.Field(mesh, dim=1, value=1)
>>> field
Field(...)
"""
return html.strip_tags(self._repr_html_())
def _repr_html_(self):
"""Show HTML-based representation in Jupyter notebook."""
return html.get_template('field').render(field=self)
def __call__(self, point):
r"""Sample the field value at ``point``.
It returns the value of the field in the discretisation cell to which
``point`` belongs to. It returns a tuple, whose length is the same as
the dimension (``dim``) of the field.
Parameters
----------
point : (3,) array_like
The mesh point coordinate :math:`\\mathbf{p} = (p_{x}, p_{y},
p_{z})`.
Returns
-------
tuple
A tuple, whose length is the same as the dimension of the field.
Example
-------
1. Sampling the field value.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (20, 20, 20)
>>> n = (20, 20, 20)
>>> mesh = df.Mesh(region=df.Region(p1=p1, p2=p2), n=n)
...
>>> field = df.Field(mesh, dim=3, value=(1, 3, 4))
>>> point = (10, 2, 3)
>>> field(point)
(1.0, 3.0, 4.0)
"""
return dfu.array2tuple(self.array[self.mesh.point2index(point)])
def __getattr__(self, attr):
"""Extract the component of the vector field.
This method provides access to individual field components for fields
with dimension > 1. Component labels are defined in the ``components``
attribute. For dimension 2 and 3 default values ``'x'``, ``'y'``, and
``'z'`` are used if no custom component labels are provided. For fields
with ``dim>3`` component labels must be specified manually to get
access to individual vector components.
Parameters
----------
attr : str
Vector field component defined in ``components``.
Returns
-------
discretisedfield.Field
Scalar field with vector field component values.
Examples
--------
1. Accessing the default vector field components.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (2, 2, 2)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=3, value=(0, 0, 1))
>>> field.x
Field(...)
>>> field.x.average
0.0
>>> field.y
Field(...)
>>> field.y.average
0.0
>>> field.z
Field(...)
>>> field.z.average
1.0
>>> field.z.dim
1
2. Accessing custom vector field components.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (2, 2, 2)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
...
>>> field = df.Field(mesh=mesh, dim=3, value=(0, 0, 1),
... components=['mx', 'my', 'mz'])
>>> field.mx
Field(...)
>>> field.mx.average
0.0
>>> field.my
Field(...)
>>> field.my.average
0.0
>>> field.mz
Field(...)
>>> field.mz.average
1.0
>>> field.mz.dim
1
"""
if self.components is not None and attr in self.components:
attr_array = self.array[..., self.components.index(attr),
np.newaxis]
return self.__class__(mesh=self.mesh, dim=1, value=attr_array)
else:
msg = f'Object has no attribute {attr}.'
raise AttributeError(msg)
def __dir__(self):
"""Extension of the ``dir(self)`` list.
Adds component labels to the ``dir(self)`` list. Similarly, adds or
removes methods (``grad``, ``div``,...) depending on the dimension of
the field.
Returns
-------
list
Avalilable attributes.
"""
dirlist = dir(self.__class__)
if self.components is not None:
dirlist += self.components
if self.dim == 1:
need_removing = ['div', 'curl', 'orientation']
if self.dim == 2:
need_removing = ['grad', 'curl', 'k3d']
if self.dim == 3:
need_removing = ['grad']
for attr in need_removing:
dirlist.remove(attr)
return dirlist
def __iter__(self):
r"""Generator yielding coordinates and values of all mesh
discretisation cells.
Yields
------
tuple (2,)
The first value is the mesh cell coordinates :math:`\\mathbf{p} =
(p_{x}, p_{y}, p_{z})`, whereas the second one is the field value.
Examples
--------
1. Iterating through the field coordinates and values
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (2, 2, 1)
>>> cell = (1, 1, 1)
>>> mesh = df.Mesh(p1=p1, p2=p2, cell=cell)
...
>>> field = df.Field(mesh, dim=3, value=(0, 0, 1))
>>> for coord, value in field:
... print (coord, value)
(0.5, 0.5, 0.5) (0.0, 0.0, 1.0)
(1.5, 0.5, 0.5) (0.0, 0.0, 1.0)
(0.5, 1.5, 0.5) (0.0, 0.0, 1.0)
(1.5, 1.5, 0.5) (0.0, 0.0, 1.0)
.. seealso:: :py:func:`~discretisedfield.Mesh.indices`
"""
for point in self.mesh:
yield point, self(point)
def __eq__(self, other):
"""Relational operator ``==``.
Two fields are considered to be equal if:
1. They are defined on the same mesh.
2. They have the same dimension (``dim``).
3. They both contain the same values in ``array``.
Parameters
----------
other : discretisedfield.Field
Second operand.
Returns
-------
bool
``True`` if two fields are equal, ``False`` otherwise.
Examples
--------
1. Check if two fields are (not) equal.
>>> import discretisedfield as df
...
>>> mesh = df.Mesh(p1=(0, 0, 0), p2=(5, 5, 5), cell=(1, 1, 1))
...
>>> f1 = df.Field(mesh, dim=1, value=3)
>>> f2 = df.Field(mesh, dim=1, value=4-1)
>>> f3 = df.Field(mesh, dim=3, value=(1, 4, 3))
>>> f1 == f2
True
>>> f1 != f2
False
>>> f1 == f3
False
>>> f1 != f3
True
>>> f2 == f3
False
>>> f1 == 'a'
False
"""
if not isinstance(other, self.__class__):
return False
elif (self.mesh == other.mesh and self.dim == other.dim and
np.array_equal(self.array, other.array)):
return True
else:
return False
# TODO The mesh comparison has no tolerance.
def allclose(self, other, rtol=1e-5, atol=1e-8):
"""Allclose method.
This method determines whether two fields are:
1. Defined on the same mesh.
2. Have the same dimension (``dim``).
3. All values in are within relative (``rtol``) and absolute
(``atol``) tolerances.
Parameters
----------
other : discretisedfield.Field
Field to be compared to.
rtol : numbers.Real
Relative tolerance. Defaults to 1e-5.
atol : numbers.Real
Absolute tolerance. Defaults to 1e-8.
Returns
-------
bool
``True`` if two fields are within tolerance, ``False`` otherwise.
Raises
------
TypeError
If a non field object is passed.
Examples
--------
1. Check if two fields are within a tolerance.
>>> import discretisedfield as df
...
>>> mesh = df.Mesh(p1=(0, 0, 0), p2=(5, 5, 5), cell=(1, 1, 1))
...
>>> f1 = df.Field(mesh, dim=1, value=3)
>>> f2 = df.Field(mesh, dim=1, value=3+1e-9)
>>> f3 = df.Field(mesh, dim=1, value=3.1)
>>> f1.allclose(f2)
True
>>> f1.allclose(f3)
False
>>> f1.allclose(f3, atol=1e-2)
False
"""
if not isinstance(other, self.__class__):
msg = (f'Cannot apply allclose method between '
f'{type(self)=} and {type(other)=} objects.')
raise TypeError(msg)
if (self.mesh == other.mesh and self.dim == other.dim):
return np.allclose(self.array, other.array, rtol=rtol, atol=atol)
else:
return False
def __pos__(self):
"""Unary ``+`` operator.
This method defines the unary operator ``+``. It returns the field
itself:
.. math::
+f(x, y, z) = f(x, y, z)
Returns
-------
discretisedfield.Field
Field itself.
Example
-------
1. Applying unary ``+`` operator on a field.
>>> import discretisedfield as df
...
>>> p1 = (0, 0, 0)
>>> p2 = (5e-9, 5e-9, 5e-9)
>>> n = (10, 10, 10)
>>> mesh = df.Mesh(p1=p1, p2=p2, n=n)
...
>>> f = df.Field(mesh, dim=3, value=(0, -1000, -3))
>>> res = +f
>>> res.average
(0.0, -1000.0, -3.0)
>>> res == f
True
>>> +(+f) == f
True
"""
return self
def __neg__(self):
r"""Unary ``-`` operator.
This method negates the value of each discretisation cell. It is
equivalent to multiplication with -1: