File: ymport.py

package info (click to toggle)
yade 2025.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,308 kB
  • sloc: cpp: 93,298; python: 50,409; sh: 577; makefile: 162
file content (828 lines) | stat: -rw-r--r-- 30,443 bytes parent folder | download | duplicates (2)
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
"""
Import geometry from various formats ('import' is python keyword, hence the name 'ymport').
"""

from yade.wrapper import *
from yade import utils
from yade._ymport import *

from yade.minieigenHP import *


def textExt(fileName, format='x_y_z_r', shift=Vector3.Zero, scale=1.0, attrs=[], **kw):
	r"""Load sphere coordinates from file in a format selected by the ``format`` argument, returns a list of corresponding bodies; that may be inserted to the simulation with O.bodies.append().

	:param str filename: file name
	:param str format: selected input format. Supported ``'x_y_z_r'``(default), ``'x_y_z_r_matId'``, ``'x_y_z_r_attrs'``
	:param [float,float,float] shift: [X,Y,Z] parameter moves the specimen.
	:param float scale: factor scales the given data.
	:param list attrs: attrs read from file if export.textExt(format='x_y_z_r_attrs') were used ('passed by reference' style)
	:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.sphere`
	:returns: list of spheres.

	Lines starting with # are skipped
	"""
	infile = open(fileName, "r")
	lines = infile.readlines()
	infile.close()
	ret = []
	for line in lines:
		data = line.split()
		if (data[0] == "#format"):
			format = data[1]
			continue
		elif (data[0][0] == "#"):
			continue

		if (format == 'x_y_z_r'):
			pos = Vector3(float(data[0]), float(data[1]), float(data[2]))
			ret.append(utils.sphere(shift + scale * pos, scale * float(data[3]), **kw))
		elif (format == 'x_y_z_r_matId'):
			pos = Vector3(float(data[0]), float(data[1]), float(data[2]))
			ret.append(utils.sphere(shift + scale * pos, scale * float(data[3]), material=int(data[4]), **kw))

		elif (format == 'id_x_y_z_r_matId'):
			pos = Vector3(float(data[1]), float(data[2]), float(data[3]))
			ret.append(utils.sphere(shift + scale * pos, scale * float(data[4]), material=int(data[5]), **kw))

		elif (format == 'x_y_z_r_attrs'):
			pos = Vector3(float(data[0]), float(data[1]), float(data[2]))
			s = utils.sphere(shift + scale * pos, scale * float(data[3]), **kw)
			ret.append(s)
			attrs.append(data[4:])

		else:
			raise RuntimeError("Please, specify a correct format output!")
	return ret


def textFacets(fileName, format='x1_y1_z1_x2_y2_z2_x3_y3_z3', shift=Vector3.Zero, scale=1.0, attrs=[], **kw):
	r"""Load facet coordinates from file in a format selected by the ``format`` argument, returns a list of corresponding bodies; that may be inserted to the simulation with O.bodies.append().
	
	:param str filename: file name
	:param str format: selected input format. Supported ``'x1_y1_z1_x2_y2_z2_x3_y3_z3'``(default), ``'x1_y1_z1_x2_y2_z2_x3_y3_z3_matId'``, ``'id_x1_y1_z1_x2_y2_z2_x3_y3_z3_matId'`` or ``'x1_y1_z1_x2_y2_z2_x3_y3_z3_attrs'``
	:param [float,float,float] shift: [X,Y,Z] parameter moves the specimen.
	:param float scale: factor scales the given data.
	:param list attrs: attrs read from file ('passed by reference' style)
	:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.facet`
	:returns: list of facets.

	Lines starting with # are skipped
	"""
	infile = open(fileName, "r")
	lines = infile.readlines()
	infile.close()
	ret = []
	for line in lines:
		data = line.split()
		if (data[0] == "#format"):
			format = data[1]
			continue
		elif (data[0][0] == "#"):
			continue

		if (format == 'x1_y1_z1_x2_y2_z2_x3_y3_z3'):
			V1 = Vector3(float(data[0]), float(data[1]), float(data[2]))
			V2 = Vector3(float(data[3]), float(data[4]), float(data[5]))
			V3 = Vector3(float(data[6]), float(data[7]), float(data[8]))
			ret.append(utils.facet((shift + V1 * scale, shift + V2 * scale, shift + V3 * scale), **kw))

		elif (format == 'x1_y1_z1_x2_y2_z2_x3_y3_z3_matId'):
			V1 = Vector3(float(data[0]), float(data[1]), float(data[2]))
			V2 = Vector3(float(data[3]), float(data[4]), float(data[5]))
			V3 = Vector3(float(data[6]), float(data[7]), float(data[8]))
			ret.append(utils.facet((shift + V1 * scale, shift + V2 * scale, shift + V3 * scale), material=int(data[9]), **kw))

		elif (format == 'id_x1_y1_z1_x2_y2_z2_x3_y3_z3_matId'):
			V1 = Vector3(float(data[1]), float(data[2]), float(data[3]))
			V2 = Vector3(float(data[4]), float(data[5]), float(data[6]))
			V3 = Vector3(float(data[7]), float(data[8]), float(data[9]))
			ret.append(utils.facet((shift + V1 * scale, shift + V2 * scale, shift + V3 * scale), material=int(data[10]), **kw))

		elif (format == 'x1_y1_z1_x2_y2_z2_x3_y3_z3_attrs'):
			V1 = Vector3(float(data[0]), float(data[1]), float(data[2]))
			V2 = Vector3(float(data[3]), float(data[4]), float(data[5]))
			V3 = Vector3(float(data[6]), float(data[7]), float(data[8]))
			ret.append(utils.facet((shift + V1 * scale, shift + V2 * scale, shift + V3 * scale), **kw))
			attrs.append(data[4:])

		else:
			raise RuntimeError("Please, specify a correct format output!")
	return ret


def textClumps(fileName, shift=Vector3.Zero, discretization=0, orientation=Quaternion((0, 1, 0), 0.0), scale=1.0, **kw):
	r"""Load clumps-members from file in a format selected by the ``format`` argument, insert them to the simulation.

	:param str filename: file name
	:param str format: selected input format. Supported ``'x_y_z_r'``(default), ``'x_y_z_r_clumpId'``
	:param [float,float,float] shift: [X,Y,Z] parameter moves the specimen.
	:param float scale: factor scales the given data.
	:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.sphere`
	:returns: list of spheres.

	Lines starting with # are skipped
	"""
	infile = open(fileName, "r")
	lines = infile.readlines()
	infile.close()
	ret = []

	curClump = []
	newClumpId = -1

	for line in lines:
		data = line.split()
		if (data[0][0] == "#"):
			continue
		pos = orientation * Vector3(float(data[0]), float(data[1]), float(data[2]))

		if (newClumpId < 0 or newClumpId == int(data[4])):
			idD = curClump.append(utils.sphere(shift + scale * pos, scale * float(data[3]), **kw))
			newClumpId = int(data[4])
		else:
			newClumpId = int(data[4])
			ret.append(O.bodies.appendClumped(curClump, discretization=discretization))
			curClump = []
			idD = curClump.append(utils.sphere(shift + scale * pos, scale * float(data[3]), **kw))

	if (len(curClump) != 0):
		ret.append(O.bodies.appendClumped(curClump, discretization=discretization))

	# Set the mask to a clump the same as the first member of it
	for i in range(len(ret)):
		O.bodies[ret[i][0]].mask = O.bodies[ret[i][1][0]].mask
	return ret


def text(fileName, shift=Vector3.Zero, scale=1.0, **kw):
	r"""Load sphere coordinates from file, returns a list of corresponding bodies; that may be inserted to the simulation with O.bodies.append().

	:param string filename: file which has 4 colums [x, y, z, radius].
	:param [float,float,float] shift: [X,Y,Z] parameter moves the specimen.
	:param float scale: factor scales the given data.
	:param \*\*kw: (unused keyword arguments)	is passed to :yref:`yade.utils.sphere`
	:returns: list of spheres.

	Lines starting with # are skipped
	"""

	return textExt(fileName=fileName, format='x_y_z_r', shift=shift, scale=scale, **kw)


def stl(file, dynamic=None, fixed=True, wire=True, color=None, highlight=False, noBound=False, material=-1, scale=1.0, shift=Vector3.Zero):
	""" Import a .stl geometry in the form of a set of :yref:`Facet`-shaped bodies.
	
	:param string file: the .stl file serving as geometry input
	:param bool dynamic: controls :yref:`Body.dynamic`
	:param bool fixed: controls :yref:`Body.dynamic` (with fixed = True imposing :yref:`Body.dynamic` = False) if *dynamic* attribute is not given
	:param bool wire: rendering option, passed to :yref:`Facet.wire`
	:param color: rendering option, passed to :yref:`Facet.color`
	:param bool highlight: rendering option, passed to :yref:`Facet.highlight`
	:param bool noBound: sets :yref:`Body.bounded` to False if True, preventing collision detection (and vice-versa)
	:param material: defines :yref:`material<Body.material>` properties, see :ref:`DefiningMaterials` for usage
	:param float scale: scaling factor to e.g. dilate the geometry if > 1
	:param Vector3 shift: for translating the geometry
	:returns: a corresponding list of :yref:`Facet`-shaped bodies"""
	imp = STLImporter()
	facets = imp.ymport(file)
	for b in facets:
		b.shape.setVertices(b.shape.vertices[0] * scale, b.shape.vertices[1] * scale, b.shape.vertices[2] * scale)
		b.shape.color = color if color else utils.randomColor()
		b.shape.wire = wire
		b.shape.highlight = highlight
		pos = b.state.pos * scale + shift
		utils._commonBodySetup(b, 0, Vector3(0, 0, 0), material=material, pos=pos, noBound=noBound, dynamic=dynamic, fixed=fixed)
		b.aspherical = False
	return facets


def gts(meshfile, shift=Vector3.Zero, scale=1.0, **kw):
	""" Read given meshfile in gts format.

	:Parameters:
		`meshfile`: string
			name of the input file.
		`shift`: [float,float,float]
			[X,Y,Z] parameter moves the specimen.
		`scale`: float
			factor scales the given data.
		`**kw`: (unused keyword arguments)
				is passed to :yref:`yade.utils.facet`
	:Returns: list of facets.
	"""
	import gts, yade.pack
	surf = gts.read(open(meshfile))
	surf.scale(scale, scale, scale)
	surf.translate(shift[0], shift[1], shift[2])
	yade.pack.gtsSurface2Facets(surf, **kw)


def gmsh(meshfile="file.mesh", shift=Vector3.Zero, scale=1.0, orientation=Quaternion((0, 1, 0), 0.0), **kw):
	""" Imports geometry from .mesh file and creates facets.

	:Parameters:
		`shift`: [float,float,float]
			[X,Y,Z] parameter moves the specimen.
		`scale`: float
			factor scales the given data.
		`orientation`: quaternion
			orientation of the imported mesh
		`**kw`: (unused keyword arguments)
				is passed to :yref:`yade.utils.facet`
	:Returns: list of facets forming the specimen.
	
	mesh files can easily be created with `GMSH <http://www.geuz.org/gmsh/>`_.
	Example added to :ysrc:`examples/packs/packs.py`
	
	Additional examples of mesh-files can be downloaded from 
	http://www-roc.inria.fr/gamma/download/download.php
	"""
	infile = open(meshfile, "r")
	lines = infile.readlines()
	infile.close()

	nodelistVector3 = []
	elementlistVector3 = []  # for deformable elements
	findVerticesString = 0

	while (lines[findVerticesString].split()[0] != 'Vertices'):  #Find the string with the number of Vertices
		findVerticesString += 1
	findVerticesString += 1
	numNodes = int(lines[findVerticesString].split()[0])

	for i in range(numNodes):
		nodelistVector3.append(Vector3(0.0, 0.0, 0.0))
	id = 0

	for line in lines[findVerticesString + 1:numNodes + findVerticesString + 1]:
		data = line.split()
		nodelistVector3[id] = orientation * Vector3(float(data[0]) * scale, float(data[1]) * scale, float(data[2]) * scale) + shift
		id += 1

	findTriangleString = findVerticesString + numNodes
	while (lines[findTriangleString].split()[0] != 'Triangles'):  #Find the string with the number of Triangles
		findTriangleString += 1
	findTriangleString += 1
	numTriangles = int(lines[findTriangleString].split()[0])

	triList = []
	for i in range(numTriangles):
		triList.append([0, 0, 0, 0])

	tid = 0
	for line in lines[findTriangleString + 1:findTriangleString + numTriangles + 1]:
		data = line.split()
		id1 = int(data[0]) - 1
		id2 = int(data[1]) - 1
		id3 = int(data[2]) - 1
		triList[tid][0] = tid
		triList[tid][1] = id1
		triList[tid][2] = id2
		triList[tid][3] = id3
		tid += 1
		ret = []
	for i in triList:
		a = nodelistVector3[i[1]]
		b = nodelistVector3[i[2]]
		c = nodelistVector3[i[3]]
		ret.append(utils.facet((nodelistVector3[i[1]], nodelistVector3[i[2]], nodelistVector3[i[3]]), **kw))
	return ret


def gengeoFile(fileName="file.geo", shift=Vector3.Zero, scale=1.0, orientation=Quaternion((0, 1, 0), 0.0), **kw):
	""" Imports geometry from LSMGenGeo .geo file and creates spheres. 
	Since 2012 the package is available in Debian/Ubuntu and known as python-demgengeo
	http://packages.qa.debian.org/p/python-demgengeo.html
	
	:Parameters:
		`filename`: string
			file which has 4 colums [x, y, z, radius].
		`shift`: Vector3
			Vector3(X,Y,Z) parameter moves the specimen.
		`scale`: float
			factor scales the given data.
		`orientation`: quaternion
			orientation of the imported geometry
		`**kw`: (unused keyword arguments)
				is passed to :yref:`yade.utils.sphere`
	:Returns: list of spheres.
	
	LSMGenGeo library allows one to create pack of spheres
	with given [Rmin:Rmax] with null stress inside the specimen.
	Can be useful for Mining Rock simulation.
	
	Example: :ysrc:`examples/packs/packs.py`, usage of LSMGenGeo library in :ysrc:`examples/test/genCylLSM.py`.
	
	* https://answers.launchpad.net/esys-particle/+faq/877
	* http://www.access.edu.au/lsmgengeo_python_doc/current/pythonapi/html/GenGeo-module.html
	* https://svn.esscc.uq.edu.au/svn/esys3/lsm/contrib/LSMGenGeo/"""
	from yade.utils import sphere

	infile = open(fileName, "r")
	lines = infile.readlines()
	infile.close()

	numSpheres = int(lines[6].split()[0])
	ret = []
	for line in lines[7:numSpheres + 7]:
		data = line.split()
		pos = orientation * Vector3(float(data[0]), float(data[1]), float(data[2]))
		ret.append(utils.sphere(shift + scale * pos, scale * float(data[3]), **kw))
	return ret


def gengeo(mntable, shift=Vector3.Zero, scale=1.0, **kw):
	""" Imports geometry from LSMGenGeo library and creates spheres.
	Since 2012 the package is available in Debian/Ubuntu and known as python-demgengeo
	http://packages.qa.debian.org/p/python-demgengeo.html

	:Parameters:
		`mntable`: mntable
			object, which creates by LSMGenGeo library, see example
		`shift`: [float,float,float]
			[X,Y,Z] parameter moves the specimen.
		`scale`: float
			factor scales the given data.
		`**kw`: (unused keyword arguments)
				is passed to :yref:`yade.utils.sphere`
	
	LSMGenGeo library allows one to create pack of spheres
	with given [Rmin:Rmax] with null stress inside the specimen.
	Can be useful for Mining Rock simulation.
	
	Example: :ysrc:`examples/packs/packs.py`, usage of LSMGenGeo library in :ysrc:`examples/test/genCylLSM.py`.
	
	* https://answers.launchpad.net/esys-particle/+faq/877
	* http://www.access.edu.au/lsmgengeo_python_doc/current/pythonapi/html/GenGeo-module.html
	* https://svn.esscc.uq.edu.au/svn/esys3/lsm/contrib/LSMGenGeo/"""
	try:
		from GenGeo import MNTable3D, Sphere
	except ImportError:
		from gengeo import MNTable3D, Sphere
	ret = []
	sphereList = mntable.getSphereListFromGroup(0)
	for i in range(0, len(sphereList)):
		r = sphereList[i].Radius()
		c = sphereList[i].Centre()
		ret.append(
		        utils.sphere(
		                [shift[0] + scale * float(c.X()), shift[1] + scale * float(c.Y()), shift[2] + scale * float(c.Z())], scale * float(r), **kw
		        )
		)
	return ret


def unv(fileName, shift=(0, 0, 0), scale=1.0, returnConnectivityTable=False, **kw):
	r""" Import geometry from unv file, return list of created facets.

		:param string fileName: name of unv file
		:param (float,float,float)|Vector3 shift: (X,Y,Z) parameter moves the specimen.
		:param float scale: factor scales the given data.
		:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.facet`
		:param bool returnConnectivityTable: if True, apart from facets returns also nodes (list of (x,y,z) nodes coordinates) and elements (list of (id1,id2,id3) element nodes ids). If False (default), returns only facets
	
	unv files are mainly used for FEM analyses (are used by `OOFEM <http://www.oofem.org/>`_ and `Abaqus <http://www.simulia.com/products/abaqus_fea.html>`_), but triangular elements can be imported as facets.
	These files cen be created e.g. with open-source free software `Salome <http://salome-platform.org>`_.
	
	Example: :ysrc:`examples/test/unv-read/unvRead.py`."""

	class UNVReader(object):
		# class used in ymport.unv function
		# reads and evaluate given unv file and extracts all triangles
		# can be extended to read tetrahedrons as well
		def __init__(self, fileName, shift=(0, 0, 0), scale=1.0, returnConnectivityTable=False, **kw):
			self.shift = shift
			self.scale = scale
			self.unvFile = open(fileName, 'r')
			self.flag = 0
			self.line = self.unvFile.readline()
			self.lineSplit = self.line.split()
			self.nodes = []
			self.elements = []
			self.read(**kw)

		def readLine(self):
			self.line = self.unvFile.readline()
			self.lineSplit = self.line.split()

		def read(self, **kw):
			while self.line:
				self.evalLine()
				self.line = self.unvFile.readline()
			self.unvFile.close()
			self.createFacets(**kw)

		def evalLine(self):
			self.lineSplit = self.line.split()
			if len(self.lineSplit) <= 1:  # eval special unv format
				if self.lineSplit[0] == '-1':
					pass
				elif self.lineSplit[0] == '2411':
					self.flag = 1
					# nodes
				elif self.lineSplit[0] == '2412':
					self.flag = 2
					# edges (lines)
				else:
					self.flag = 4
					# volume elements or other, not interesting for us (at least yet)
			elif self.flag == 1:
				self.evalNodes()
			elif self.flag == 2:
				self.evalEdge()
			elif self.flag == 3:
				self.evalFacet()
			#elif self.flag == 4: self.evalGroup()
		def evalNodes(self):
			self.readLine()
			self.nodes.append(
			        (
			                self.shift[0] + self.scale * float(self.lineSplit[0]), self.shift[1] + self.scale * float(self.lineSplit[1]),
			                self.shift[2] + self.scale * float(self.lineSplit[2])
			        )
			)

		def evalEdge(self):
			if self.lineSplit[1] == '41':
				self.flag = 3
				self.evalFacet()
			else:
				self.readLine()
				self.readLine()

		def evalFacet(self):
			if self.lineSplit[1] == '41':  # triangle
				self.readLine()
				self.elements.append((int(self.lineSplit[0]) - 1, int(self.lineSplit[1]) - 1, int(self.lineSplit[2]) - 1))
			else:  # is not triangle
				self.readLine()
				self.flag = 4
				# can be added function to handle tetrahedrons
		def createFacets(self, **kw):
			self.facets = [utils.facet(tuple(self.nodes[i] for i in e), **kw) for e in self.elements]

	#
	unvReader = UNVReader(fileName, shift, scale, returnConnectivityTable, **kw)
	if returnConnectivityTable:
		return unvReader.facets, unvReader.nodes, unvReader.elements
	return unvReader.facets


def iges(fileName, shift=(0, 0, 0), scale=1.0, returnConnectivityTable=False, **kw):
	r""" Import triangular mesh from .igs file, return list of created facets.

		:param string fileName: name of iges file
		:param (float,float,float)|Vector3 shift: (X,Y,Z) parameter moves the specimen.
		:param float scale: factor scales the given data.
		:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.facet`
		:param bool returnConnectivityTable: if True, apart from facets returns also nodes (list of (x,y,z) nodes coordinates) and elements (list of (id1,id2,id3) element nodes ids). If False (default), returns only facets
	"""
	nodes, elems = [], []
	f = open(fileName)
	for line in f:
		if line.startswith('134,'):  # read nodes coordinates
			ls = line.split(',')
			v = Vector3(float(ls[1]) * scale + shift[0], float(ls[2]) * scale + shift[1], float(ls[3]) * scale + shift[2])
			nodes.append(v)
		if line.startswith('136,'):  # read elements
			ls = line.split(',')
			i1, i2, i3 = int(ls[3]) / 2, int(ls[4]) / 2, int(ls[5]) / 2  # the numbering of nodes is 1,3,5,7,..., hence this int(ls[*])/2
			elems.append((i1, i2, i3))
	facets = [utils.facet((nodes[e[0]], nodes[e[1]], nodes[e[2]]), **kw) for e in elems]
	if returnConnectivityTable:
		return facets, nodes, elems
	return facets


def ele(nodeFileName, eleFileName, shift=(0, 0, 0), scale=1.0, **kw):
	r""" Import tetrahedral mesh from .ele file, return list of created tetrahedrons.

		:param string nodeFileName: name of .node file
		:param string eleFileName: name of .ele file
		:param (float,float,float)|Vector3 shift: (X,Y,Z) parameter moves the specimen.
		:param float scale: factor scales the given data.
		:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.polyhedron`
	"""
	f = open(nodeFileName)
	line = f.readline()
	while line.startswith('#'):
		line = f.readline()
	ls = line.split()
	nVertices = int(ls[0])
	if int(ls[1]) != 3:
		raise RuntimeError("wrong .node file, number of dimensions should be 3")
	vertices = [None for i in range(nVertices)]
	shift = Vector3(shift)
	for i in range(nVertices):
		line = f.readline()
		while line.startswith('#'):
			line = f.readline()
		ls = line.split()
		if not ls:
			continue
		v = shift + scale * Vector3(tuple(float(ls[j]) for j in (1, 2, 3)))
		vertices[int(ls[0]) - 1] = v
	f.close()
	#
	f = open(eleFileName)
	line = f.readline()
	while line.startswith('#'):
		line = f.readline()
	ls = line.split()
	if int(ls[1]) != 4:
		raise RuntimeError("wrong .ele file, unsupported tetrahedra's number of nodes")
	nTetras = int(ls[0])
	tetras = [None for i in range(nTetras)]
	for i in range(nTetras):
		ls = f.readline().split()
		tetras[int(ls[0]) - 1] = utils.polyhedron([vertices[int(ls[j]) - 1] for j in (1, 2, 3, 4)], **kw)
	f.close()
	return tetras


def textPolyhedra(fileName, material, shift=Vector3.Zero, scale=1.0, orientation=Quaternion((0, 1, 0), 0.0), **kw):
	r"""Load polyhedra from a text file.
	
	:param str filename: file name. Expected file format is the one output by export.textPolyhedra.
	:param [float,float,float] shift: [X,Y,Z] parameter moves the specimen.
	:param float scale: factor scales the given data.
	:param quaternion orientation:  orientation of the imported polyhedra
	:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.polyhedra_utils.polyhedra`
	:returns: list of polyhedras.

	Lines starting with # are skipped
	"""
	from yade import polyhedra_utils
	infile = open(fileName, "r")
	lines = infile.readlines()
	infile.close()
	ret = []
	i = -1
	while (i < (len(lines) - 1)):
		i += 1
		line = lines[i]
		data = line.split()
		if (data[0][0] == "#"):
			continue

		if (len(data) != 3):
			raise RuntimeError("Check polyhedra input file! Number of parameters in the first line is not 3!")
		else:
			vertLoad = []
			#			ids = int(data[0])
			verts = int(data[1])
			surfs = int(data[2])
			i += 1
			for d in range(verts):
				dataV = lines[i].split()
				pos = orientation * Vector3(float(dataV[0]) * scale, float(dataV[1]) * scale, float(dataV[2]) * scale) + shift
				vertLoad.append(pos)
				i += 1
			polR = polyhedra_utils.polyhedra(material=material, v=vertLoad, **kw)
			if (polR != -1):
				ret.append(polR)
			i = i + surfs - 1
	return ret


def blockMeshDict(path, patchasWall=True, emptyasWall=True, **kw):
	r"""Load openfoam's blockMeshDict file's "boundary" section as facets.

	:param str path: file name. Typical value is: "system/blockMeshDict".
	:param bool patchasWall: load "patch"-es as walls.
	:param bool emptyasWall: load "empty"-es as walls.
	:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.facet`
	:returns: list of facets.
    """

	BOUNDARY_ERROR = 0
	BOUNDARY_PATCH = 1
	BOUNDARY_WALL = 2
	BOUNDARY_EMPTY = 3

	class Boundary:

		def __init__(self):
			self.name = ""
			self.typ = BOUNDARY_ERROR
			self.faces4 = []

	def tryParseFloat(x, n):
		val = 0.0
		try:
			val = float(x)
		except ValueError:
			assert False, "{}: Expected 'float', got: {}".format(n, x)

		return val

	def tryParseInt(x, n):
		val = 0
		try:
			val = int(x)
		except ValueError:
			assert False, "{}: Expected 'int', got: {}".format(n, x)

		return val

	def tryParseArg(l, n):
		parts = l.split()

		assert len(parts) == 2, "{}: Wrong argument format, expected 'key value;', got '{}'".format(n, l)
		arg = parts[1].strip()
		assert arg[-1] == ';', "{}: Wrong argument format: '{}', missing ';'".format(n, l)

		return arg[:-1]

	convertToMeters = 1.0

	foamFileBlock = False
	verticesBlock = False
	vertices = []
	boundariesBlock = False
	boundaries = []
	facesBlock = False
	facets = []

	lines = []
	with open(path) as fp:
		lines = fp.readlines()

	lineNumber = 0
	blockDepth = 0

	currentBoundary = Boundary()

	for line in lines:
		line = line.split("//")[0]
		line = line.strip()
		lineNumber += 1

		if len(line) == 0:
			continue

		if line.startswith("FoamFile") and blockDepth == 0:
			foamFileBlock = True
		elif line.startswith("convertToMeters") and blockDepth == 0:
			convertToMetersStr = tryParseArg(line, lineNumber)
			convertToMeters = tryParseFloat(convertToMetersStr, lineNumber)
		elif line.startswith("vertices") and blockDepth == 0:
			verticesBlock = True
		elif line.startswith("boundary") and blockDepth == 0:
			boundariesBlock = True
		elif line == "(" or line == "{":
			blockDepth += 1
			continue
		elif line.endswith(");"):
			blockDepth -= 1

			if blockDepth == 0:
				verticesBlock = False
				boundariesBlock = False
			elif facesBlock == 2:
				facesBlock = False

			continue
		elif line.endswith("}"):
			blockDepth -= 1

			if blockDepth == 0:
				foamFileBlock = False
			elif blockDepth == 1:
				assert boundariesBlock, "{}: Parser error, only boundaries are supported.".format(lineNumber)
				assert currentBoundary.name != "", "{}: Empty name for boundary.".format(lineNumber)
				assert currentBoundary.typ != BOUNDARY_ERROR, "{}: Invalid type for boundary, supported: patch, wall, empty".format(lineNumber)
				assert len(currentBoundary.faces4) > 0, "{}: Boundary must contain at least one face.".format(lineNumber)

				boundaries.append(currentBoundary)

				currentBoundary = Boundary()

			continue
		else:
			if foamFileBlock:
				if blockDepth == 1:
					if (line.startswith("version")):
						foamVersion = tryParseArg(line, lineNumber)
						assert foamVersion == "2.0", "{}: Only version '2.0' is supported, got: '{}'".format(lineNumber, foamVersion)
					elif (line.startswith("format")):
						foamFormat = tryParseArg(line, lineNumber)
						assert foamFormat == "ascii", "{}: Only 'ascii' format is supported, got: '{}'".format(lineNumber, foamFormat)
					elif (line.startswith("class")):
						foamClass = tryParseArg(line, lineNumber)
						assert foamClass == "dictionary", "{}: Class must be 'dictionary' not '{}'".format(lineNumber, foamClass)
					elif (line.startswith("object")):
						foamObject = tryParseArg(line, lineNumber)
						assert foamObject == "blockMeshDict", "{}: Object must be 'blockMeshDict' not '{}'".format(
						        lineNumber, foamObject
						)
					else:
						assert False, "{}: Unknown FoamFile-header field: {}".format(lineNumber, line)
				else:
					assert False, "{}: FoamFile-block must be in the top level".format(lineNumber)
			elif verticesBlock:
				if line.find("(") != -1 and line.find(")") != -1:
					vStr = line[1:-1]
					vStrs = vStr.split()
					assert len(vStrs) == 3, "{}: Vertex format expected: (x y z), got: {}".format(lineNumber, vStr)
					x = tryParseFloat(vStrs[0], lineNumber)
					y = tryParseFloat(vStrs[1], lineNumber)
					z = tryParseFloat(vStrs[2], lineNumber)

					vertices.append((x, y, z))
				else:
					assert False, "{}: Vertex format expected: (x y z), got: {}".format(lineNumber, line)
			elif boundariesBlock:
				if blockDepth == 1:
					assert len(line.split(" ")) == 1, "{}: Expected surface name, got: {}".format(lineNumber, line)

					currentBoundary.name = line
				elif blockDepth == 2:
					if line.startswith("type"):
						typStrs = line.split()
						assert len(typStrs) == 2, "{}: Expected boundary type definition, got: {}".format(lineNumber, line)
						assert typStrs[1][-1] == ';', "{}: Expected ';' at the end of boundary type".format(lineNumber)

						typStr = typStrs[1][:-1]
						if typStr == "patch":
							currentBoundary.typ = BOUNDARY_PATCH
						elif typStr == "wall":
							currentBoundary.typ = BOUNDARY_WALL
						elif typStr == "empty":
							currentBoundary.typ = BOUNDARY_EMPTY
						else:
							assert False, "{}: Unknown boundary type: {}".format(lineNumber, typStr)

					elif line.startswith("faces"):
						facesBlock = True
					else:
						assert False, "{}: Expected 'type' or 'faces', got: {}".format(lineNumber, line)
				elif blockDepth == 3:
					assert facesBlock, "{}: Parser error, only faces supported at level 3".format(lineNumber)

					if line.find("(") != -1 and line.find(")") != -1:
						fStr = line[1:-1]
						fStrs = fStr.split()
						assert len(fStrs) == 4, "{}: Face format expected: (v0 v1 v2 v3), got: {}".format(lineNumber, fStr)

						v0 = tryParseInt(fStrs[0], lineNumber)
						v1 = tryParseInt(fStrs[1], lineNumber)
						v2 = tryParseInt(fStrs[2], lineNumber)
						v3 = tryParseInt(fStrs[3], lineNumber)

						assert v0 >= 0, "{}: Face index must be greater or equal to 0, not {}".format(lineNumber, v0)
						assert v1 >= 0, "{}: Face index must be greater or equal to 0, not {}".format(lineNumber, v1)
						assert v2 >= 0, "{}: Face index must be greater or equal to 0, not {}".format(lineNumber, v2)
						assert v3 >= 0, "{}: Face index must be greater or equal to 0, not {}".format(lineNumber, v3)

						currentBoundary.faces4.append((v0, v1, v2, v3))
					else:
						assert False, "{}: Face format expected: (v0 v1 v2 v3), got: {}".format(lineNumber, line)
				else:
					assert blockDepth == 0, "{}: Parser error, only block-levels 0, 1, 2 and 3 are supported".format(lineNumber)

	assert blockDepth == 0, "Unmatched parentheses."
	assert len(boundaries) != 0, "'{}' must contain at least one boundary.".format(path)
	for b in boundaries:
		if b.typ == BOUNDARY_PATCH and patchasWall == False:
			continue

		if b.typ == BOUNDARY_EMPTY and emptyasWall == False:
			continue

		for f4 in b.faces4:
			f0 = (f4[0], f4[1], f4[2])
			f1 = (f4[2], f4[3], f4[0])

			f0v0 = tuple([x * convertToMeters for x in vertices[f0[0]]])
			f0v1 = tuple([x * convertToMeters for x in vertices[f0[1]]])
			f0v2 = tuple([x * convertToMeters for x in vertices[f0[2]]])

			f1v0 = tuple([x * convertToMeters for x in vertices[f1[0]]])
			f1v1 = tuple([x * convertToMeters for x in vertices[f1[1]]])
			f1v2 = tuple([x * convertToMeters for x in vertices[f1[2]]])

			facets.append(utils.facet((f0v0, f0v1, f0v2), **kw))
			facets.append(utils.facet((f1v0, f1v1, f1v2), **kw))

	return facets


def polyMesh(path, patchasWall=True, emptyasWall=True, **kw):
	r"""Load openfoam's polyMesh directory as facets.

	:param str path: directory path. Typical value is: "constant/polyMesh".
	:param bool patchAsWall: load "patch"-es as walls.
	:param bool emptyAsWall: load "empty"-es as walls.
	:param \*\*kw: (unused keyword arguments) is passed to :yref:`yade.utils.facet`
	:returns: list of facets.
    """

	facetCoords = readPolyMesh(path, patchasWall, emptyasWall)

	facets = []
	for fc in facetCoords:
		facets.append(utils.facet(fc, **kw))

	return facets