-
Notifications
You must be signed in to change notification settings - Fork 81
/
plyfile.py
1515 lines (1246 loc) · 41.7 KB
/
plyfile.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
# Copyright 2014-2023 Darsh Ranjan and plyfile authors.
#
# This file is part of python-plyfile.
#
# python-plyfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# python-plyfile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with python-plyfile. If not, see
# <http://www.gnu.org/licenses/>.
"""
NumPy-based PLY format input and output for Python.
"""
import io as _io
from itertools import islice as _islice
import numpy as _np
from sys import byteorder as _byteorder
class PlyData(object):
"""
PLY file header and data.
A `PlyData` instance is created in one of two ways: by the static
method `PlyData.read` (to read a PLY file), or directly from
`__init__` given a sequence of elements (which can then be written
to a PLY file).
Attributes
----------
elements : list of PlyElement
comments : list of str
obj_info : list of str
text : bool
byte_order : {'<', '>', '='}
header : str
"""
def __init__(self, elements=[], text=False, byte_order='=',
comments=[], obj_info=[]):
"""
Parameters
----------
elements : iterable of PlyElement
text : bool, optional
Whether the resulting PLY file will be text (True) or
binary (False).
byte_order : {'<', '>', '='}, optional
`'<'` for little-endian, `'>'` for big-endian, or `'='`
for native. This is only relevant if `text` is False.
comments : iterable of str, optional
Comment lines between "ply" and "format" lines.
obj_info : iterable of str, optional
like comments, but will be placed in the header with
"obj_info ..." instead of "comment ...".
"""
self.byte_order = byte_order
self.text = text
self.comments = comments
self.obj_info = obj_info
self.elements = elements
def _get_elements(self):
return self._elements
def _set_elements(self, elements):
self._elements = tuple(elements)
self._index()
elements = property(_get_elements, _set_elements)
def _get_byte_order(self):
if not self.text and self._byte_order == '=':
return _native_byte_order
return self._byte_order
def _set_byte_order(self, byte_order):
if byte_order not in ['<', '>', '=']:
raise ValueError("byte order must be '<', '>', or '='")
self._byte_order = byte_order
byte_order = property(_get_byte_order, _set_byte_order)
def _index(self):
self._element_lookup = dict((elt.name, elt) for elt in
self._elements)
if len(self._element_lookup) != len(self._elements):
raise ValueError("two elements with same name")
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _get_obj_info(self):
return list(self._obj_info)
def _set_obj_info(self, obj_info):
_check_comments(obj_info)
self._obj_info = list(obj_info)
obj_info = property(_get_obj_info, _set_obj_info)
@staticmethod
def _parse_header(stream):
parser = _PlyHeaderParser(_PlyHeaderLines(stream))
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
)
@staticmethod
def read(stream, mmap='c', known_list_len={}):
"""
Read PLY data from a readable file-like object or filename.
Parameters
----------
stream : str or readable open file
mmap : {'c', 'r', 'r+'} or bool, optional (default='c')
Configures memory-mapping. Any falsy value disables
memory mapping, and any non-string truthy value is
equivalent to 'c', for copy-on-write mapping.
known_list_len : dict, optional
Mapping from element names to mappings from list property
names to their fixed lengths. This optional argument is
necessary to enable memory mapping of elements that contain
list properties. (Note that elements with variable-length
list properties cannot be memory-mapped.)
Raises
------
PlyParseError
If the file cannot be parsed for any reason.
ValueError
If `stream` is open in text mode but the PLY header
indicates binary encoding.
"""
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
if isinstance(stream.read(0), str):
if data.text:
data_stream = stream
else:
raise ValueError("can't read binary-format PLY "
"from text stream")
else:
if data.text:
data_stream = _io.TextIOWrapper(stream, 'ascii')
else:
data_stream = stream
for elt in data:
elt._read(data_stream, data.text, data.byte_order, mmap,
known_list_len=known_list_len.get(elt.name, {}))
finally:
if must_close:
stream.close()
return data
def write(self, stream):
"""
Write PLY data to a writeable file-like object or filename.
Parameters
----------
stream : str or writeable open file
Raises
------
ValueError
If `stream` is open in text mode and the file to be written
is binary-format.
"""
(must_close, stream) = _open_stream(stream, 'write')
try:
try:
stream.write(b'')
binary_stream = True
except TypeError:
binary_stream = False
if binary_stream:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
else:
if not self.text:
raise ValueError("can't write binary-format PLY to "
"text stream")
stream.write(self.header)
stream.write('\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close()
@property
def header(self):
"""
PLY-formatted metadata for the instance.
"""
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines)
def __iter__(self):
"""
Iterate over the elements.
"""
return iter(self.elements)
def __len__(self):
"""
Return the number of elements.
"""
return len(self.elements)
def __contains__(self, name):
"""
Check if an element with the given name exists.
"""
return name in self._element_lookup
def __getitem__(self, name):
"""
Retrieve an element by name.
Parameters
----------
name : str
Returns
-------
PlyElement
Raises
------
KeyError
If the element can't be found.
"""
return self._element_lookup[name]
def __str__(self):
return self.header
def __repr__(self):
return ('PlyData(%r, text=%r, byte_order=%r, '
'comments=%r, obj_info=%r)' %
(self.elements, self.text, self.byte_order,
self.comments, self.obj_info))
class PlyElement(object):
"""
PLY file element.
Creating a `PlyElement` instance is generally done in one of two
ways: as a byproduct of `PlyData.read` (when reading a PLY file) and
by `PlyElement.describe` (before writing a PLY file).
Attributes
----------
name : str
count : int
data : numpy.ndarray
properties : list of PlyProperty
comments : list of str
header : str
PLY header block for this element.
"""
def __init__(self, name, properties, count, comments=[]):
"""
This is not part of the public interface. The preferred methods
of obtaining `PlyElement` instances are `PlyData.read` (to read
from a file) and `PlyElement.describe` (to construct from a
`numpy` array).
Parameters
----------
name : str
properties : list of PlyProperty
count : str
comments : list of str
"""
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
"""
Look up property by name.
Parameters
----------
name : str
Returns
-------
PlyProperty
Raises
------
KeyError
If the property can't be found.
"""
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
"""
Return the `numpy.dtype` description of the in-memory
representation of the data. (If there are no list properties,
and the PLY format is binary, then this also accurately
describes the on-disk representation of the element.)
Parameters
----------
byte_order : {'<', '>', '='}
Returns
-------
numpy.dtype
"""
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
"""
Construct a `PlyElement` instance from an array's metadata.
Parameters
----------
data : numpy.ndarray
Structured `numpy` array.
len_types : dict, optional
Mapping from list property names to type strings
(`numpy`-style like `'u1'`, `'f4'`, etc., or PLY-style like
`'int8'`, `'float32'`, etc.), which will be used to encode
the length of the list in binary-format PLY files. Defaults
to `'u1'` (8-bit integer) for all list properties.
val_types : dict, optional
Mapping from list property names to type strings as for
`len_types`, but is used to encode the list elements in
binary-format PLY files. Defaults to `'i4'` (32-bit
integer) for all list properties.
comments : list of str
Comments between the "element" line and first property
definition in the header.
Returns
-------
PlyElement
Raises
------
TypeError, ValueError
"""
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order, mmap,
known_list_len={}):
"""
Read the actual data from a PLY file.
Parameters
----------
stream : readable open file
text : bool
byte_order : {'<', '>', '='}
mmap : {'c', 'r', 'r+'} or bool
known_list_len : dict
"""
if text:
self._read_txt(stream)
else:
list_prop_names = set(p.name for p in self.properties
if isinstance(p, PlyListProperty))
can_mmap_lists = list_prop_names <= set(known_list_len)
if mmap and _can_mmap(stream) and can_mmap_lists:
# Loading the data is straightforward. We will memory
# map the file in copy-on-write mode.
mmap_mode = mmap if isinstance(mmap, str) else 'c'
self._read_mmap(stream, byte_order, mmap_mode,
known_list_len)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
"""
Write the data to a PLY file.
Parameters
----------
stream : writeable open file
text : bool
byte_order : {'<', '>', '='}
"""
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_mmap(self, stream, byte_order, mmap_mode, known_list_len):
"""
Memory-map an input file as `self.data`.
Parameters
----------
stream : readable open file
byte_order : {'<', '>', '='}
mmap_mode: str
known_list_len : dict
"""
list_len_props = {}
# update the dtype to include the list length and list dtype
new_dtype = []
for p in self.properties:
if isinstance(p, PlyListProperty):
len_dtype, val_dtype = p.list_dtype(byte_order)
# create new dtype for the list length
new_dtype.append((p.name + "\nlen", len_dtype))
# a new dtype with size for the list values themselves
new_dtype.append((p.name, val_dtype,
(known_list_len[p.name],)))
list_len_props[p.name] = p.name + "\nlen"
else:
new_dtype.append((p.name, p.dtype(byte_order)))
dtype = _np.dtype(new_dtype)
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype, mmap_mode, offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
# remove any extra properties added
for prop in list_len_props:
field = list_len_props[prop]
len_check = self._data[field] == known_list_len[prop]
if not len_check.all():
row = _np.flatnonzero(len_check ^ True)[0]
raise PlyElementParseError(
"unexpected list length",
self, row, self.ply_property(prop))
props = [p.name for p in self.properties]
self._data = self._data[props]
def _read_txt(self, stream):
"""
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
Parameters
----------
stream : readable open file
"""
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, ''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
"""
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
Parameters
----------
stream : writeable open file
"""
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
"""
Load a PLY element from a binary PLY file. The element may
contain list properties.
Parameters
----------
stream : readable open file
byte_order : {'<', '>', '='}
"""
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
"""
Save a PLY element to a binary PLY file. The element may
contain list properties.
Parameters
----------
stream : writeable open file
byte_order : {'<', '>', '='}
"""
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __len__(self):
"""
Return the number of rows in the element.
"""
return self.count
def __contains__(self, name):
"""
Determine if a property with the given name exists.
"""
return name in self._property_lookup
def __getitem__(self, key):
"""
Proxy to `self.data.__getitem__` for convenience.
"""
return self.data[key]
def __setitem__(self, key, value):
"""
Proxy to `self.data.__setitem__` for convenience.
"""
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
class PlyProperty(object):
"""
PLY property description.
This class is pure metadata. The data itself is contained in
`PlyElement` instances.
Attributes
----------
name : str
val_dtype : str
`numpy.dtype` description for the property's data.
"""
def __init__(self, name, val_dtype):
"""
Parameters
----------
name : str
val_dtype : str
"""
_check_name(name)
self._name = str(name)
self.val_dtype = val_dtype
def _get_val_dtype(self):
return self._val_dtype
def _set_val_dtype(self, val_dtype):
self._val_dtype = _data_types[_lookup_type(val_dtype)]
val_dtype = property(_get_val_dtype, _set_val_dtype)
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
"""
Return the `numpy.dtype` description for this property.
Parameters
----------
byte_order : {'<', '>', '='}, default='='
Returns
-------
tuple of str
"""
return byte_order + self.val_dtype
def _from_fields(self, fields):
"""
Parse data from generator.
Parameters
----------
fields : iterator of str
Returns
-------
data
Parsed data of the correct type.
Raises
------
StopIteration
if the property's data could not be read.
"""
return _np.dtype(self.dtype()).type(next(fields))
def _to_fields(self, data):
"""
Parameters
----------
data
Property data to encode.
Yields
------
encoded_data
Data with type consistent with `self.val_dtype`.
"""
yield _np.dtype(self.dtype()).type(data)
def _read_bin(self, stream, byte_order):
"""
Read data from a binary stream.
Parameters
----------
stream : readable open binary file
byte_order : {'<'. '>', '='}
Raises
------
StopIteration
If the property data could not be read.
"""
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration
def _write_bin(self, data, stream, byte_order):
"""
Write data to a binary stream.
Parameters
----------
data
Property data to encode.
stream : writeable open binary file
byte_order : {'<', '>', '='}
"""
_write_array(stream, _np.dtype(self.dtype(byte_order)).type(data))
def __str__(self):
val_str = _data_type_reverse[self.val_dtype]
return 'property %s %s' % (val_str, self.name)
def __repr__(self):
return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype))
class PlyListProperty(PlyProperty):
"""
PLY list property description.
Attributes
----------
name
val_dtype
len_dtype : str
`numpy.dtype` description for the property's length field.
"""
def __init__(self, name, len_dtype, val_dtype):
"""
Parameters
----------
name : str
len_dtype : str
val_dtype : str
"""
PlyProperty.__init__(self, name, val_dtype)
self.len_dtype = len_dtype
def _get_len_dtype(self):
return self._len_dtype
def _set_len_dtype(self, len_dtype):
self._len_dtype = _data_types[_lookup_type(len_dtype)]
len_dtype = property(_get_len_dtype, _set_len_dtype)
def dtype(self, byte_order='='):
"""
`numpy.dtype` name for the property's field in the element.
List properties always have a numpy dtype of "object".
Parameters
----------
byte_order : {'<', '>', '='}
Returns
-------
dtype : str
Always `'|O'`.
"""
return '|O'
def list_dtype(self, byte_order='='):
"""
Return the pair `(len_dtype, val_dtype)` (both numpy-friendly
strings).
Parameters
----------
byte_order : {'<', '>', '='}
Returns
-------
len_dtype : str
val_dtype : str
"""
return (byte_order + self.len_dtype,
byte_order + self.val_dtype)
def _from_fields(self, fields):
"""
Parse data from generator.
Parameters
----------
fields : iterator of str
Returns
-------
data : numpy.ndarray
Parsed list data for the property.
Raises
------
StopIteration
if the property's data could not be read.
"""
(len_t, val_t) = self.list_dtype()
n = int(_np.dtype(len_t).type(next(fields)))
data = _np.loadtxt(list(_islice(fields, n)), val_t, ndmin=1)
if len(data) < n:
raise StopIteration
return data
def _to_fields(self, data):
"""
Return generator over the (numerical) PLY representation of the
list data (length followed by actual data).
Parameters
----------
data : numpy.ndarray
Property data to encode.
Yields
------
Length followed by each list element.
"""
(len_t, val_t) = self.list_dtype()
data = _np.asarray(data, dtype=val_t).ravel()
yield _np.dtype(len_t).type(data.size)
for x in data:
yield x
def _read_bin(self, stream, byte_order):
"""
Read data from a binary stream.
Parameters
----------
stream : readable open binary file
byte_order : {'<', '>', '='}
Returns
-------
data : numpy.ndarray
Raises
------
StopIteration
If data could not be read.
"""
(len_t, val_t) = self.list_dtype(byte_order)
try:
n = _read_array(stream, _np.dtype(len_t), 1)[0]
except IndexError:
raise StopIteration