-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcyprecice.pyx
More file actions
1284 lines (1008 loc) · 46.8 KB
/
cyprecice.pyx
File metadata and controls
1284 lines (1008 loc) · 46.8 KB
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
# distutils: language = c++
"""precice
The python module precice offers python language bindings to the C++ coupling library precice. Please refer to precice.org for further information.
"""
cimport cyprecice
cimport numpy
import numpy as np
from mpi4py import MPI
import warnings
from libcpp.string cimport string
from libcpp.vector cimport vector
from cpython.version cimport PY_MAJOR_VERSION # important for determining python version in order to properly normalize string input. See http://docs.cython.org/en/latest/src/tutorial/strings.html#general-notes-about-c-strings and https://github.com/precice/precice/issues/68 .
cdef bytes convert(s):
"""
source code from http://docs.cython.org/en/latest/src/tutorial/strings.html#general-notes-about-c-strings
"""
if type(s) is bytes:
return s
elif type(s) is str:
return s.encode()
else:
raise TypeError("Could not convert.")
def check_array_like(argument, argument_name, function_name):
try:
argument.__len__
argument.__getitem__
except AttributeError:
raise TypeError("{} requires array_like input for {}, but was provided the following input type: {}".format(
function_name, argument_name, type(argument))) from None
cdef class Participant:
"""
Main Application Programming Interface of preCICE.
To adapt a solver to preCICE, follow the following main structure:
- Create an object of Participant with Participant()
- Initialize preCICE with Participant::initialize()
- Advance to the next (time)step with Participant::advance()
- Finalize preCICE with Participant::finalize()
- We use solver, simulation code, and participant as synonyms.
- The preferred name in the documentation is participant.
"""
# fake __init__ needed to display docstring for __cinit__ (see https://stackoverflow.com/a/42733794/5158031)
def __init__(self, solver_name, configuration_file_name, solver_process_index, solver_process_size, communicator=None):
"""
Constructor of Participant class.
Parameters
----------
solver_name : string
Name of the solver
configuration_file_name : string
Name of the preCICE config file
solver_process_index : int
Rank of the process
solver_process_size : int
Size of the process
communicator: mpi4py.MPI.Comm, optional
Custom MPI communicator to use
Returns
-------
Participant : object
Object pointing to the defined participant
Example
-------
>>> participant = precice.Participant("SolverOne", "precice-config.xml", 0, 1)
preCICE: This is preCICE version X.X.X
preCICE: Revision info: vX.X.X-X-XXXXXXXXX
preCICE: Configuring preCICE with configuration: "precice-config.xml"
"""
pass
def __cinit__ (self, solver_name, configuration_file_name, solver_process_index, solver_process_size, communicator=None):
cdef size_t c_comm_addr;
if communicator:
c_comm_addr = MPI._addressof(communicator)
self.thisptr = new CppParticipant.Participant (convert(solver_name), convert(configuration_file_name), solver_process_index, solver_process_size, <void*>c_comm_addr)
else:
self.thisptr = new CppParticipant.Participant (convert(solver_name), convert(configuration_file_name), solver_process_index, solver_process_size)
pass
def __dealloc__ (self):
"""
Destructor of Participant class
"""
del self.thisptr
# steering methods
def initialize (self):
"""
Fully initializes preCICE and initializes coupling data. The starting values for coupling data are zero by
default. To provide custom values, first set the data using the Data Access methods before calling this
method to finally exchange the data.
This function handles:
- Parallel communication to the coupling partner/s is setup.
- Meshes are exchanged between coupling partners and the parallel partitions are created.
- [Serial Coupling Scheme] If the solver is not starting the simulation, coupling data is received from the coupling partner's first computation.
Returns
-------
max_timestep : double
Maximum length of first timestep to be computed by the solver.
"""
self.thisptr.initialize ()
def advance (self, double computed_timestep_length):
"""
Advances preCICE after the solver has computed one timestep.
Parameters
----------
computed_timestep_length : double
Length of timestep used by the solver.
Notes
-----
Previous calls:
initialize() has been called successfully.
The solver has computed one timestep.
The solver has written all coupling data.
finalize() has not yet been called.
Tasks completed:
Coupling data values specified in the configuration are exchanged.
Coupling scheme state (computed time, computed timesteps, ...) is updated.
The coupling state is logged.
Configured data mapping schemes are applied.
[Second Participant] Configured post processing schemes are applied.
Meshes with data are exported to files if configured.
"""
self.thisptr.advance (computed_timestep_length)
def finalize (self):
"""
Finalizes preCICE.
Notes
-----
Previous calls:
initialize() has been called successfully.
Tasks completed:
Communication channels are closed.
Meshes and data are deallocated.
"""
self.thisptr.finalize ()
# status queries
def get_mesh_dimensions (self, mesh_name):
"""
Returns the spatial dimensionality of the given mesh.
Parameters
----------
mesh_name : string
Name of the mesh.
Returns
-------
dimension : int
The dimensions of the given mesh.
"""
return self.thisptr.getMeshDimensions (convert(mesh_name))
def get_data_dimensions (self, mesh_name, data_name):
"""
Returns the spatial dimensionality of the given data on the given mesh.
Parameters
----------
mesh_name : string
Name of the mesh.
data_name : string
Name of the data.
Returns
-------
dimension : int
The dimensions of the given data.
"""
return self.thisptr.getDataDimensions (convert(mesh_name), convert(data_name))
def is_coupling_ongoing (self):
"""
Checks if the coupled simulation is still ongoing.
A coupling is ongoing as long as
- the maximum number of timesteps has not been reached, and
- the final time has not been reached.
The user should call finalize() after this function returns false.
Returns
-------
tag : bool
Whether the coupling is ongoing.
Notes
-----
Previous calls:
initialize() has been called successfully.
"""
return self.thisptr.isCouplingOngoing ()
def is_time_window_complete (self):
"""
Checks if the current coupling timewindow is completed.
The following reasons require several solver time steps per coupling time step:
- A solver chooses to perform subcycling.
- An implicit coupling timestep iteration is not yet converged.
Returns
-------
tag : bool
Whether the timestep is complete.
Notes
-----
Previous calls:
initialize() has been called successfully.
"""
return self.thisptr.isTimeWindowComplete ()
def get_max_time_step_size (self):
"""
Get the maximum allowed time step size of the current window.
Allows the user to query the maximum allowed time step size in the current window.
This should be used to compute the actual time step that the solver uses.
Returns
-------
tag : double
Maximum size of time step to be computed by solver.
Notes
-----
Previous calls:
initialize() has been called successfully.
"""
return self.thisptr.getMaxTimeStepSize ()
def requires_initial_data (self):
"""
Checks if the participant is required to provide initial data.
If true, then the participant needs to write initial data to defined vertices
prior to calling initialize().
Returns
-------
tag : bool
Returns True if initial data is required.
Notes
-----
Previous calls:
initialize() has not yet been called
"""
return self.thisptr.requiresInitialData ()
def requires_writing_checkpoint (self):
"""
Checks if the participant is required to write an iteration checkpoint.
If true, the participant is required to write an iteration checkpoint before
calling advance().
preCICE refuses to proceed if writing a checkpoint is required,
but this method isn't called prior to advance().
Notes
-----
Previous calls:
initialize() has been called
"""
return self.thisptr.requiresWritingCheckpoint ()
def requires_reading_checkpoint (self):
"""
Checks if the participant is required to read an iteration checkpoint.
If true, the participant is required to read an iteration checkpoint before
calling advance().
preCICE refuses to proceed if reading a checkpoint is required,
but this method isn't called prior to advance().
Notes
-----
This function returns false before the first call to advance().
Previous calls:
initialize() has been called
"""
return self.thisptr.requiresReadingCheckpoint ()
# mesh access
def requires_mesh_connectivity_for (self, mesh_name):
"""
Checks if the given mesh requires connectivity.
Parameters
----------
mesh_name : string
Name of the mesh.
Returns
-------
tag : bool
True if mesh connectivity is required.
"""
return self.thisptr.requiresMeshConnectivityFor(convert(mesh_name))
def set_mesh_vertex(self, mesh_name, position):
"""
Creates a mesh vertex
Parameters
----------
mesh_name : str
Name of the mesh to add the vertex to.
position : array_like
The coordinates of the vertex.
Returns
-------
vertex_id : int
ID of the vertex which is set.
Notes
-----
Previous calls:
Count of available elements at position matches the configured dimension
"""
check_array_like(position, "position", "set_mesh_vertex")
if len(position) > 0:
dimensions = len(position)
assert dimensions == self.get_mesh_dimensions(mesh_name), "Dimensions of vertex coordinate in set_mesh_vertex does not match with dimensions in problem definition. Provided dimensions: {}, expected dimensions: {}".format(dimensions, self.get_mesh_dimensions(mesh_name))
elif len(position) == 0:
dimensions = self.get_mesh_dimensions(mesh_name)
cdef vector[double] cpp_position = position
vertex_id = self.thisptr.setMeshVertex(convert(mesh_name), cpp_position)
return vertex_id
def get_mesh_vertex_size (self, mesh_name):
"""
Returns the number of vertices of a mesh
Parameters
----------
mesh_name : str
Name of the mesh.
Returns
-------
sum : int
Number of vertices of the mesh.
"""
return self.thisptr.getMeshVertexSize(convert(mesh_name))
def set_mesh_vertices (self, mesh_name, positions):
"""
Creates multiple mesh vertices
Parameters
----------
mesh_name : str
Name of the mesh to add the vertices to.
positions : array_like
The coordinates of the vertices in a numpy array [N x D] where
N = number of vertices and D = dimensions of geometry.
A list of the same shape is also accepted.
Returns
-------
vertex_ids : numpy.ndarray
IDs of the created vertices.
Notes
-----
Previous calls:
initialize() has not yet been called
count of available elements at positions matches the configured dimension * size
count of available elements at ids matches size
Examples
--------
Set mesh vertices for a 2D problem with 5 mesh vertices.
>>> positions = np.array([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
>>> positions.shape
(5, 2)
>>> mesh_name = "MeshOne"
>>> vertex_ids = participant.set_mesh_vertices(mesh_name, positions)
>>> vertex_ids.shape
(5,)
Set mesh vertices for a 3D problem with 5 mesh vertices.
>>> positions = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]])
>>> positions.shape
(5, 3)
>>> mesh_name = "MeshOne"
>>> vertex_ids = participant.set_mesh_vertices(mesh_name, positions)
>>> vertex_ids.shape
(5,)
Set mesh vertices for a 3D problem with 5 mesh vertices, where the positions are a list of tuples.
>>> positions = [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5)]
>>> positions.shape
(5, 3)
>>> mesh_name = "MeshOne"
>>> vertex_ids = participant.set_mesh_vertices(mesh_name, positions)
>>> vertex_ids.shape
(5,)
"""
check_array_like(positions, "positions", "set_mesh_vertices")
if not isinstance(positions, np.ndarray):
positions = np.asarray(positions)
if len(positions) > 0:
size, dimensions = positions.shape
assert dimensions == self.get_mesh_dimensions(mesh_name), "Dimensions of vertex coordinates in set_mesh_vertices does not match with dimensions in problem definition. Provided dimensions: {}, expected dimensions: {}".format(dimensions, self.get_mesh_dimensions(mesh_name))
elif len(positions) == 0:
size = 0
dimensions = self.get_mesh_dimensions(mesh_name)
cdef vector[double] cpp_positions = positions.flatten()
cdef vector[int] cpp_ids = [-1 for _ in range(size)]
self.thisptr.setMeshVertices (convert(mesh_name), cpp_positions, cpp_ids)
cdef np.ndarray[int, ndim=1] np_ids = np.array(cpp_ids, dtype=np.int32)
return np_ids
def set_mesh_edge (self, mesh_name, first_vertex_id, second_vertex_id):
"""
Sets mesh edge from vertex IDs, returns edge ID.
Parameters
----------
mesh_name : str
Name of the mesh to add the edge to.
first_vertex_id : int
ID of the first vertex of the edge.
second_vertex_id : int
ID of the second vertex of the edge.
Returns
-------
edge_id : int
ID of the edge.
Notes
-----
Previous calls:
vertices with firstVertexID and secondVertexID were added to the mesh with name mesh_name
"""
self.thisptr.setMeshEdge (convert(mesh_name), first_vertex_id, second_vertex_id)
def set_mesh_edges (self, mesh_name, vertices):
"""
Creates multiple mesh edges
Parameters
----------
mesh_name : str
Name of the mesh to add the vertices to.
vertices : array_like
The IDs of the vertices in a numpy array [N x 2] where
N = number of edges and D = dimensions of geometry.
A list of the same shape is also accepted.
Examples
--------
Set mesh edges for a problem with 4 mesh vertices in the form of a square with both diagonals which are fully interconnected.
>>> vertices = np.array([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]])
>>> vertices.shape
(6, 2)
>>> participant.set_mesh_edges(mesh_name, vertices)
"""
check_array_like(vertices, "vertices", "set_mesh_edges")
if not isinstance(vertices, np.ndarray):
vertices = np.asarray(vertices)
if len(vertices) > 0:
_, n = vertices.shape
assert n == 2, "Provided vertices are not of a [N x 2] format, but instead of a [N x {}]".format(n)
elif len(vertices) == 0:
dimensions = self.get_mesh_dimensions(mesh_name)
cdef vector[int] cpp_vertices = vertices.flatten()
self.thisptr.setMeshEdges (convert(mesh_name), cpp_vertices)
def set_mesh_triangle (self, mesh_name, first_vertex_id, second_vertex_id, third_vertex_id):
"""
Set a mesh triangle from edge IDs
Parameters
----------
mesh_name : str
Name of the mesh to add the triangle to.
first_vertex_id : int
ID of the first vertex of the triangle.
second_vertex_id : int
ID of the second vertex of the triangle.
third_vertex_id : int
ID of the third vertex of the triangle.
Notes
-----
Previous calls:
vertices with first_vertex_id, second_vertex_id, and third_vertex_id were added to the mesh with the name mesh_name
"""
self.thisptr.setMeshTriangle (convert(mesh_name), first_vertex_id, second_vertex_id, third_vertex_id)
def set_mesh_triangles (self, mesh_name, vertices):
"""
Creates multiple mesh triangles
Parameters
----------
mesh_name : str
Name of the mesh to add the triangles to.
vertices : array_like
The IDs of the vertices in a numpy array [N x 3] where
N = number of triangles and D = dimensions of geometry.
A list of the same shape is also accepted.
Examples
--------
Set mesh triangles for a problem with 4 mesh vertices in the form of a square with both diagonals which are fully interconnected.
>>> vertices = np.array([[1, 2, 3], [1, 3, 4], [1, 2, 4], [1, 3, 4]])
>>> vertices.shape
(4, 2)
>>> participant.set_mesh_triangles(mesh_name, vertices)
"""
check_array_like(vertices, "vertices", "set_mesh_triangles")
if not isinstance(vertices, np.ndarray):
vertices = np.asarray(vertices)
if len(vertices) > 0:
_, n = vertices.shape
assert n == self.get_mesh_dimensions(mesh_name), "Provided vertices are not of a [N x {}] format, but instead of a [N x {}]".format(self.get_mesh_dimensions(mesh_name), n)
elif len(vertices) == 0:
dimensions = self.get_mesh_dimensions(mesh_name)
cdef vector[int] cpp_vertices = vertices.flatten()
self.thisptr.setMeshTriangles (convert(mesh_name), cpp_vertices)
def set_mesh_quad (self, mesh_name, first_vertex_id, second_vertex_id, third_vertex_id, fourth_vertex_id):
"""
Set a mesh Quad from vertex IDs.
Parameters
----------
mesh_name : str
Name of the mesh to add the quad to.
first_vertex_id : int
ID of the first vertex of the quad.
second_vertex_id : int
ID of the second vertex of the quad.
third_vertex_id : int
ID of the third vertex of the quad.
fourth_vertex_id : int
ID of the third vertex of the quad.
Notes
-----
Previous calls:
vertices with first_vertex_id, second_vertex_id, third_vertex_id, and fourth_vertex_id were added
to the mesh with the name mesh_name
"""
self.thisptr.setMeshQuad (convert(mesh_name), first_vertex_id, second_vertex_id, third_vertex_id, fourth_vertex_id)
def set_mesh_quads (self, mesh_name, vertices):
"""
Creates multiple mesh quads
Parameters
----------
mesh_name : str
Name of the mesh to add the quads to.
vertices : array_like
The IDs of the vertices in a numpy array [N x 4] where
N = number of quads and D = dimensions of geometry.
A list of the same shape is also accepted.
Examples
--------
Set mesh quads for a problem with 4 mesh vertices in the form of a square with both diagonals which are fully interconnected.
>>> vertices = np.array([[1, 2, 3, 4]])
>>> vertices.shape
(1, 2)
>>> participant.set_mesh_quads(mesh_name, vertices)
"""
check_array_like(vertices, "vertices", "set_mesh_quads")
if not isinstance(vertices, np.ndarray):
vertices = np.asarray(vertices)
if len(vertices) > 0:
_, n = vertices.shape
assert n == 4, "Provided vertices are not of a [N x 4] format, but instead of a [N x {}]".format(n)
elif len(vertices) == 0:
dimensions = self.get_mesh_dimensions(mesh_name)
cdef vector[int] cpp_vertices = vertices.flatten()
self.thisptr.setMeshQuads (convert(mesh_name), cpp_vertices)
def set_mesh_tetrahedron (self, mesh_name, first_vertex_id, second_vertex_id, third_vertex_id, fourth_vertex_id):
"""
Sets a mesh tetrahedron from vertex IDs.
Parameters
----------
mesh_name : str
Name of the mesh to add the tetrahedron to.
first_vertex_id : int
ID of the first vertex of the tetrahedron.
second_vertex_id : int
ID of the second vertex of the tetrahedron.
third_vertex_id : int
ID of the third vertex of the tetrahedron.
fourth_vertex_id : int
ID of the third vertex of the tetrahedron.
Notes
-----
Previous calls:
vertices with first_vertex_id, second_vertex_id, third_vertex_id, and fourth_vertex_id were added
to the mesh with the name mesh_name
"""
self.thisptr.setMeshTetrahedron (convert(mesh_name), first_vertex_id, second_vertex_id, third_vertex_id, fourth_vertex_id)
def set_mesh_tetrahedra (self, mesh_name, vertices):
"""
Creates multiple mesh tetdrahedrons
Parameters
----------
mesh_name : str
Name of the mesh to add the tetrahedrons to.
vertices : array_like
The IDs of the vertices in a numpy array [N x 4] where
N = number of quads and D = dimensions of geometry.
A list of the same shape is also accepted.
Examples
--------
Set mesh tetrahedrons for a problem with 4 mesh vertices.
>>> vertices = np.array([[1, 2, 3, 4]])
>>> vertices.shape
(1, 2)
>>> participant.set_mesh_tetradehra(mesh_name, vertices)
"""
check_array_like(vertices, "vertices", "set_mesh_tetrahedra")
if not isinstance(vertices, np.ndarray):
vertices = np.asarray(vertices)
if len(vertices) > 0:
_, n = vertices.shape
assert n == 4, "Provided vertices are not of a [N x 4] format, but instead of a [N x {}]".format(n)
elif len(vertices) == 0:
dimensions = self.get_mesh_dimensions(mesh_name)
cdef vector[int] cpp_vertices = vertices.flatten()
self.thisptr.setMeshTetrahedra (convert(mesh_name), cpp_vertices)
# remeshing
def reset_mesh (self, mesh_name):
"""
Resets a mesh and allows setting it using set_mesh functions again.
Parameters
----------
mesh_name : str
Name of the mesh to reset.
Notes
-----
This function is still experimental.
Please refer to the documentation on how to enable and use it.
Previous calls:
advance() has been called
Examples
--------
Reset a mesh with 5 vertices to have 3 vertices.
>>> positions = np.array([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
>>> mesh_name = "MeshOne"
>>> vertex_ids = participant.set_mesh_vertices(mesh_name, positions)
>>> # later in the coupling loop
>>> if remeshing_required():
>>> participant.reset_mesh(mesh_name)
>>> positions = np.array([[1, 1], [3, 3], [5, 5]])
>>> vertex_ids = participant.set_mesh_vertices(mesh_name, positions)
"""
self.thisptr.resetMesh (convert(mesh_name))
# data access
def write_data (self, mesh_name, data_name, vertex_ids, values):
"""
This function writes values of specified vertices to data of a mesh.
Values are provided as a block of continuous memory defined by values. Values are stored in a numpy array [N x D] where N = number of vertices and D = dimensions of geometry.
The order of the provided data follows the order specified by vertices.
Parameters
----------
mesh_name : str
name of the mesh to write to.
data_name : str
Data name to write to.
vertex_ids : array_like
Indices of the vertices.
values : array_like
Values of data
Notes
-----
Previous calls:
count of available elements at values matches the configured dimension * size
count of available elements at vertex_ids matches the given size
initialize() has been called
Examples
--------
Write scalar data for a 2D problem with 5 vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> values = np.array([v1, v2, v3, v4, v5])
>>> participant.write_data(mesh_name, data_name, vertex_ids, values)
Write vector data for a 2D problem with 5 vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> values = np.array([[v1_x, v1_y], [v2_x, v2_y], [v3_x, v3_y], [v4_x, v4_y], [v5_x, v5_y]])
>>> participant.write_data(mesh_name, data_name, vertex_ids, values)
Write vector data for a 3D (D=3) problem with 5 (N=5) vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> values = np.array([[v1_x, v1_y, v1_z], [v2_x, v2_y, v2_z], [v3_x, v3_y, v3_z], [v4_x, v4_y, v4_z], [v5_x, v5_y, v5_z]])
>>> participant.write_data(mesh_name, data_name, vertex_ids, values)
Write vector data for a 3D (D=3) problem with 5 (N=5) vertices, where the values are provided as a list of tuples:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> values = [(v1_x, v1_y, v1_z), (v2_x, v2_y, v2_z), (v3_x, v3_y, v3_z), (v4_x, v4_y, v4_z), (v5_x, v5_y, v5_z)]
>>> participant.write_data(mesh_name, data_name, vertex_ids, values)
"""
check_array_like(vertex_ids, "vertex_ids", "write_data")
check_array_like(values, "values", "write_data")
if not isinstance(values, np.ndarray):
values = np.asarray(values)
if len(values) == 0:
size = 0
elif self.get_data_dimensions(mesh_name, data_name) == 1:
size = values.flatten().shape[0]
dimensions = 1
else:
assert len(values.shape) == 2, "Vector valued data has to be provided as a numpy array of shape [N x D] where N = number of vertices and D = number of dimensions."
size, dimensions = values.shape
assert dimensions == self.get_data_dimensions(mesh_name, data_name), "Dimensions of vector data in write_data do not match with dimensions in problem definition. Provided dimensions: {}, expected dimensions: {}".format(dimensions, self.get_data_dimensions(mesh_name, data_name))
assert len(vertex_ids) == size, "Vertex IDs are of incorrect length in write_data. Check length of vertex ids input. Provided size: {}, expected size: {}".format(vertex_ids.size, size)
cdef vector[int] cpp_ids = vertex_ids
cdef vector[double] cpp_values = values.flatten()
self.thisptr.writeData (convert(mesh_name), convert(data_name), cpp_ids, cpp_values)
def read_data (self, mesh_name, data_name, vertex_ids, relative_read_time):
"""
Reads data into a provided block. This function reads values of specified vertices
from a dataID. Values are read into a block of continuous memory.
Parameters
----------
mesh_name : str
Name of the mesh to write to.
data_name : str
Name of the data to read from.
vertex_ids : array_like
Indices of the vertices.
relative_read_time : double
Point in time where data is read relative to the beginning of the current time step
Returns
-------
values : numpy.ndarray
Contains the read data.
Notes
-----
Previous calls:
count of available elements at values matches the configured dimension * size
count of available elements at vertex_ids matches the given size
initialize() has been called
Examples
--------
Read scalar data for a 2D problem with 5 vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> dt = 1.0
>>> values = read_data(mesh_name, data_name, vertex_ids, dt)
>>> values.shape
>>> (5, )
Read vector data for a 2D problem with 5 vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> dt = 1.0
>>> values = read_data(mesh_name, data_name, vertex_ids, dt)
>>> values.shape
>>> (5, 2)
Read vector data for a 3D system with 5 vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> vertex_ids = [1, 2, 3, 4, 5]
>>> dt = 1.0
>>> values = read_data(mesh_name, data_name, vertex_ids, dt)
>>> values.shape
>>> (5, 3)
"""
check_array_like(vertex_ids, "vertex_ids", "read_data")
if len(vertex_ids) == 0:
size = 0
dimensions = self.get_data_dimensions(mesh_name, data_name)
elif self.get_data_dimensions(mesh_name, data_name) == 1:
size = len(vertex_ids)
dimensions = 1
else:
size = len(vertex_ids)
dimensions = self.get_data_dimensions(mesh_name, data_name)
cdef vector[int] cpp_ids = vertex_ids
cdef vector[double] cpp_values = [-1 for _ in range(size * dimensions)]
self.thisptr.readData (convert(mesh_name), convert(data_name), cpp_ids, relative_read_time, cpp_values)
cdef np.ndarray[double, ndim=1] np_values = np.array(cpp_values, dtype=np.double)
if len(vertex_ids) == 0:
return np_values.reshape((size))
elif self.get_data_dimensions(mesh_name, data_name) == 1:
return np_values.reshape((size))
else:
return np_values.reshape((size, dimensions))
def write_and_map_data (self, mesh_name, data_name, coordinates, values):
"""
This function writes values at temporary locations to data of a mesh.
As opposed to the writeData function using VertexIDs, this function allows to write data via coordinates,
which don't have to be specified during the initialization. This is particularly useful for meshes, which
vary over time. Note that using this function comes at a performance cost, since the specified mapping
needs to be computed locally for the given locations, whereas the other variant (writeData) can typically
exploit the static interface mesh and pre-compute data structures more efficiently.
Values are passed identically to write_data.
Parameters
----------
mesh_name : str
name of the mesh to write to.
data_name : str
Data name to write to.
coordinates : array_like
The coordinates of the vertices in a numpy array [N x D] where
N = number of vertices and D = dimensions of geometry.
values : array_like
Values of data
Examples
--------
Write scalar data for a 2D problem with 5 vertices:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> coordinates = np.array([[c1_x, c1_y], [c2_x, c2_y], [c3_x, c3_y], [c4_x, c4_y], [c5_x, c5_y]])
>>> values = np.array([v1, v2, v3, v4, v5])
>>> participant.write_and_map_data(mesh_name, data_name, coordinates, values)
Write scalar data for a 2D problem with 5 vertices, where the coordinates are provided as a list of tuples, and the values are provided as a list of scalars:
>>> mesh_name = "MeshOne"
>>> data_name = "DataOne"
>>> coordinates = [(c1_x, c1_y), (c2_x, c2_y), (c3_x, c3_y), (c4_x, c4_y), (c5_x, c5_y)]
>>> values = [v1, v2, v3, v4, v5]
>>> participant.write_and_map_data(mesh_name, data_name, coordinates, values)
"""
check_array_like(coordinates, "coordinates", "write_and_map_data")
check_array_like(values, "values", "write_and_map_data")
if not isinstance(coordinates, np.ndarray):
coordinates = np.asarray(coordinates)
if not isinstance(values, np.ndarray):
values = np.asarray(values)
cdef vector[double] cpp_coordinates = coordinates.flatten()
cdef vector[double] cpp_values = values.flatten()
self.thisptr.writeAndMapData (convert(mesh_name), convert(data_name), cpp_coordinates, cpp_values)
def map_and_read_data (self, mesh_name, data_name, coordinates, relative_read_time):
"""
This function reads values at temporary locations from data of a mesh.
As opposed to the readData function using VertexIDs, this function allows reading data via coordinates,
which don't have to be specified during the initialization. This is particularly useful for meshes, which
vary over time. Note that using this function comes at a performance cost, since the specified mapping
needs to be computed locally for the given locations, whereas the other variant (readData) can typically