2019-05-30 23:32:55 +05:30
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import re
|
|
|
|
import shlex
|
|
|
|
from collections import Iterable
|
2014-04-02 00:11:14 +05:30
|
|
|
|
2014-08-07 14:21:25 +05:30
|
|
|
import numpy as np
|
|
|
|
|
2016-07-02 16:58:32 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
# python 3 has no unicode object, this ensures that the code works on Python 2&3
|
|
|
|
try:
|
2018-09-27 23:49:10 +05:30
|
|
|
test = isinstance('test', unicode)
|
|
|
|
except NameError:
|
|
|
|
unicode = str
|
2016-07-02 16:58:32 +05:30
|
|
|
|
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
class ASCIItable():
|
2016-03-04 23:20:13 +05:30
|
|
|
"""Read and write to ASCII tables"""
|
2014-08-07 14:21:25 +05:30
|
|
|
|
2015-08-12 23:12:38 +05:30
|
|
|
tmpext = '_tmp' # filename extension for in-place access
|
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def __init__(self,
|
2015-08-12 23:12:38 +05:30
|
|
|
name = None,
|
2015-08-08 00:33:26 +05:30
|
|
|
outname = None,
|
|
|
|
buffered = False, # flush writes
|
|
|
|
labeled = True, # assume table has labels
|
|
|
|
readonly = False, # no reading from file
|
|
|
|
):
|
|
|
|
self.__IO__ = {'output': [],
|
2016-04-05 22:03:14 +05:30
|
|
|
'buffered': buffered,
|
2015-08-08 00:33:26 +05:30
|
|
|
'labeled': labeled, # header contains labels
|
2016-05-17 05:24:00 +05:30
|
|
|
'tags': [], # labels according to file info
|
2015-08-08 00:33:26 +05:30
|
|
|
'readBuffer': [], # buffer to hold non-advancing reads
|
2012-01-20 02:07:53 +05:30
|
|
|
'dataStart': 0,
|
2011-12-14 01:32:26 +05:30
|
|
|
}
|
|
|
|
|
2015-08-12 23:12:38 +05:30
|
|
|
self.__IO__['inPlace'] = not outname and name and not readonly
|
2015-08-13 00:11:44 +05:30
|
|
|
if self.__IO__['inPlace']: outname = name + self.tmpext # transparently create tmp file
|
2015-09-17 01:14:11 +05:30
|
|
|
try:
|
2016-04-05 22:03:14 +05:30
|
|
|
self.__IO__['in'] = (open( name,'r') if os.access( name, os.R_OK) else None) if name else sys.stdin
|
2015-09-17 01:14:11 +05:30
|
|
|
except TypeError:
|
|
|
|
self.__IO__['in'] = name
|
|
|
|
|
|
|
|
try:
|
2016-04-05 22:03:14 +05:30
|
|
|
self.__IO__['out'] = (open(outname,'w') if (not os.path.isfile(outname) or
|
|
|
|
os.access( outname, os.W_OK)
|
|
|
|
) and
|
|
|
|
(not self.__IO__['inPlace'] or
|
|
|
|
not os.path.isfile(name) or
|
|
|
|
os.access( name, os.W_OK)
|
|
|
|
) else None) if outname else sys.stdout
|
2015-09-17 01:14:11 +05:30
|
|
|
except TypeError:
|
|
|
|
self.__IO__['out'] = outname
|
2015-08-12 23:12:38 +05:30
|
|
|
|
2015-08-08 00:33:26 +05:30
|
|
|
self.info = []
|
2016-05-17 05:24:00 +05:30
|
|
|
self.tags = []
|
2015-08-08 00:33:26 +05:30
|
|
|
self.data = []
|
2015-08-21 01:08:06 +05:30
|
|
|
self.line = ''
|
2012-02-02 22:43:51 +05:30
|
|
|
|
2016-03-04 23:20:13 +05:30
|
|
|
if self.__IO__['in'] is None \
|
|
|
|
or self.__IO__['out'] is None: raise IOError # complain if any required file access not possible
|
2015-08-12 23:12:38 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-08-08 00:33:26 +05:30
|
|
|
def _transliterateToFloat(self,
|
|
|
|
x):
|
2012-02-02 22:43:51 +05:30
|
|
|
try:
|
|
|
|
return float(x)
|
2018-09-27 23:49:10 +05:30
|
|
|
except ValueError:
|
2012-02-02 22:43:51 +05:30
|
|
|
return 0.0
|
|
|
|
|
2016-04-21 01:16:39 +05:30
|
|
|
# ------------------------------------------------------------------
|
2016-04-24 20:37:37 +05:30
|
|
|
def _removeCRLF(self,
|
2018-09-27 23:49:10 +05:30
|
|
|
string):
|
2018-09-27 23:49:19 +05:30
|
|
|
"""Delete any carriage return and line feed from string"""
|
2016-04-21 01:16:39 +05:30
|
|
|
try:
|
|
|
|
return string.replace('\n','').replace('\r','')
|
2018-09-27 23:49:10 +05:30
|
|
|
except AttributeError:
|
|
|
|
return str(string)
|
2016-04-21 01:16:39 +05:30
|
|
|
|
2016-04-29 08:38:11 +05:30
|
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def _quote(self,
|
|
|
|
what):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Quote empty or white space-containing output"""
|
2016-04-29 08:38:11 +05:30
|
|
|
return '{quote}{content}{quote}'.format(
|
|
|
|
quote = ('"' if str(what)=='' or re.search(r"\s",str(what)) else ''),
|
|
|
|
content = what)
|
2015-08-08 00:33:26 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def close(self,
|
|
|
|
dismiss = False):
|
2015-05-20 02:41:49 +05:30
|
|
|
self.input_close()
|
2015-08-08 00:33:26 +05:30
|
|
|
self.output_flush()
|
2015-05-20 02:41:49 +05:30
|
|
|
self.output_close(dismiss)
|
2015-05-20 02:05:56 +05:30
|
|
|
|
2014-08-22 21:07:46 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def input_close(self):
|
2018-09-27 23:49:10 +05:30
|
|
|
# try:
|
2015-08-24 06:10:52 +05:30
|
|
|
if self.__IO__['in'] != sys.stdin: self.__IO__['in'].close()
|
2018-09-27 23:49:10 +05:30
|
|
|
# except:
|
|
|
|
# pass
|
2014-08-22 21:07:46 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def output_write(self,
|
|
|
|
what):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Aggregate a single row (string) or list of (possibly containing further lists of) rows into output"""
|
2018-09-27 23:49:10 +05:30
|
|
|
if isinstance(what, (str, unicode)):
|
|
|
|
self.__IO__['output'] += [what]
|
|
|
|
else:
|
2013-12-12 08:06:05 +05:30
|
|
|
try:
|
|
|
|
for item in what: self.output_write(item)
|
2018-09-27 23:49:10 +05:30
|
|
|
except TypeError:
|
2013-12-12 08:06:05 +05:30
|
|
|
self.__IO__['output'] += [str(what)]
|
|
|
|
|
|
|
|
return self.__IO__['buffered'] or self.output_flush()
|
2011-12-14 01:32:26 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def output_flush(self,
|
|
|
|
clear = True):
|
2012-02-17 00:12:04 +05:30
|
|
|
try:
|
|
|
|
self.__IO__['output'] == [] or self.__IO__['out'].write('\n'.join(self.__IO__['output']) + '\n')
|
2016-03-04 23:20:13 +05:30
|
|
|
except IOError:
|
2012-02-17 00:12:04 +05:30
|
|
|
return False
|
2011-12-14 01:32:26 +05:30
|
|
|
if clear: self.output_clear()
|
2012-02-17 00:12:04 +05:30
|
|
|
return True
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def output_clear(self):
|
|
|
|
self.__IO__['output'] = []
|
|
|
|
|
2014-08-22 21:07:46 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-08-08 00:33:26 +05:30
|
|
|
def output_close(self,
|
|
|
|
dismiss = False):
|
2018-09-27 23:49:10 +05:30
|
|
|
# try:
|
|
|
|
if self.__IO__['out'] != sys.stdout: self.__IO__['out'].close()
|
|
|
|
# except:
|
|
|
|
# pass
|
2015-10-15 03:05:56 +05:30
|
|
|
if dismiss and os.path.isfile(self.__IO__['out'].name):
|
|
|
|
os.remove(self.__IO__['out'].name)
|
|
|
|
elif self.__IO__['inPlace']:
|
|
|
|
os.rename(self.__IO__['out'].name, self.__IO__['out'].name[:-len(self.tmpext)])
|
2014-08-22 21:07:46 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def head_read(self):
|
2016-03-04 23:20:13 +05:30
|
|
|
"""
|
2016-10-25 00:46:29 +05:30
|
|
|
Get column labels
|
2016-05-17 05:39:00 +05:30
|
|
|
|
|
|
|
by either reading the first row or,
|
|
|
|
if keyword "head[*]" is present, the last line of the header
|
2016-03-04 23:20:13 +05:30
|
|
|
"""
|
2011-12-14 01:32:26 +05:30
|
|
|
try:
|
|
|
|
self.__IO__['in'].seek(0)
|
2018-09-27 23:49:10 +05:30
|
|
|
except IOError:
|
2011-12-14 01:32:26 +05:30
|
|
|
pass
|
2015-08-08 00:33:26 +05:30
|
|
|
|
2015-12-22 21:29:01 +05:30
|
|
|
firstline = self.__IO__['in'].readline().strip()
|
2015-08-08 00:33:26 +05:30
|
|
|
m = re.search('(\d+)\s+head', firstline.lower()) # search for "head" keyword
|
2015-11-04 02:44:45 +05:30
|
|
|
|
|
|
|
if m: # proper ASCIItable format
|
|
|
|
|
|
|
|
if self.__IO__['labeled']: # table features labels
|
|
|
|
|
2016-07-02 16:58:32 +05:30
|
|
|
self.info = [self.__IO__['in'].readline().strip() for i in range(1,int(m.group(1)))]
|
2016-05-17 05:24:00 +05:30
|
|
|
self.tags = shlex.split(self.__IO__['in'].readline()) # store tags found in last line
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2015-11-04 02:44:45 +05:30
|
|
|
else:
|
2013-06-30 05:51:51 +05:30
|
|
|
|
2016-07-02 16:58:32 +05:30
|
|
|
self.info = [self.__IO__['in'].readline().strip() for i in range(0,int(m.group(1)))] # all header is info ...
|
2015-11-04 02:44:45 +05:30
|
|
|
|
|
|
|
else: # other table format
|
|
|
|
try:
|
|
|
|
self.__IO__['in'].seek(0) # try to rewind
|
2018-09-27 23:49:10 +05:30
|
|
|
except IOError:
|
2015-11-04 02:44:45 +05:30
|
|
|
self.__IO__['readBuffer'] = [firstline] # or at least save data in buffer
|
|
|
|
|
|
|
|
while self.data_read(advance = False, respectLabels = False):
|
|
|
|
if self.line[0] in ['#','!','%','/','|','*','$']: # "typical" comment indicators
|
|
|
|
self.info_append(self.line) # store comment as info
|
|
|
|
self.data_read() # wind forward one line
|
|
|
|
else: break # last line of comments
|
|
|
|
|
|
|
|
if self.__IO__['labeled']: # table features labels
|
2016-05-17 05:24:00 +05:30
|
|
|
self.tags = self.data # get tags from last line in "header"...
|
2015-11-04 02:44:45 +05:30
|
|
|
self.data_read() # ...and remove from buffer
|
|
|
|
|
2016-05-17 05:24:00 +05:30
|
|
|
if self.__IO__['labeled']: # table features tags
|
|
|
|
self.__IO__['tags'] = list(self.tags) # backup tags (make COPY, not link)
|
2015-11-04 02:44:45 +05:30
|
|
|
|
2012-02-16 23:33:14 +05:30
|
|
|
try:
|
2013-06-30 05:51:51 +05:30
|
|
|
self.__IO__['dataStart'] = self.__IO__['in'].tell() # current file position is at start of data
|
2015-10-06 21:49:37 +05:30
|
|
|
except IOError:
|
2012-02-16 23:33:14 +05:30
|
|
|
pass
|
2011-12-14 01:32:26 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-08-08 00:33:26 +05:30
|
|
|
def head_write(self,
|
|
|
|
header = True):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Write current header information (info + labels)"""
|
2015-08-08 00:33:26 +05:30
|
|
|
head = ['{}\theader'.format(len(self.info)+self.__IO__['labeled'])] if header else []
|
|
|
|
head.append(self.info)
|
2018-09-27 23:49:10 +05:30
|
|
|
if self.__IO__['labeled']:
|
|
|
|
head.append('\t'.join(map(self._quote,self.tags)))
|
|
|
|
if len(self.tags) == 0: raise ValueError('no labels present.')
|
2015-08-08 00:33:26 +05:30
|
|
|
|
|
|
|
return self.output_write(head)
|
2011-12-14 01:32:26 +05:30
|
|
|
|
2015-08-08 00:33:26 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def head_getGeom(self):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Interpret geom header"""
|
2015-08-08 00:33:26 +05:30
|
|
|
identifiers = {
|
|
|
|
'grid': ['a','b','c'],
|
|
|
|
'size': ['x','y','z'],
|
|
|
|
'origin': ['x','y','z'],
|
|
|
|
}
|
|
|
|
mappings = {
|
|
|
|
'grid': lambda x: int(x),
|
|
|
|
'size': lambda x: float(x),
|
|
|
|
'origin': lambda x: float(x),
|
|
|
|
'homogenization': lambda x: int(x),
|
|
|
|
'microstructures': lambda x: int(x),
|
|
|
|
}
|
|
|
|
info = {
|
|
|
|
'grid': np.zeros(3,'i'),
|
|
|
|
'size': np.zeros(3,'d'),
|
|
|
|
'origin': np.zeros(3,'d'),
|
|
|
|
'homogenization': 0,
|
|
|
|
'microstructures': 0,
|
|
|
|
}
|
|
|
|
extra_header = []
|
|
|
|
|
|
|
|
for header in self.info:
|
2016-07-02 16:58:32 +05:30
|
|
|
headitems = list(map(str.lower,header.split()))
|
2015-08-08 00:33:26 +05:30
|
|
|
if len(headitems) == 0: continue # skip blank lines
|
2016-07-02 16:58:32 +05:30
|
|
|
if headitems[0] in list(mappings.keys()):
|
|
|
|
if headitems[0] in list(identifiers.keys()):
|
|
|
|
for i in range(len(identifiers[headitems[0]])):
|
2015-08-08 00:33:26 +05:30
|
|
|
info[headitems[0]][i] = \
|
|
|
|
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
|
|
|
|
else:
|
|
|
|
info[headitems[0]] = mappings[headitems[0]](headitems[1])
|
|
|
|
else:
|
|
|
|
extra_header.append(header)
|
|
|
|
|
|
|
|
return info,extra_header
|
2015-11-14 07:18:16 +05:30
|
|
|
|
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def labels_append(self,
|
2015-08-21 01:08:06 +05:30
|
|
|
what,
|
|
|
|
reset = False):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Add item or list to existing set of labels (and switch on labeling)"""
|
2018-09-27 23:49:10 +05:30
|
|
|
if isinstance(what, (str, unicode)):
|
|
|
|
self.tags += [self._removeCRLF(what)]
|
|
|
|
else:
|
2013-12-12 08:06:05 +05:30
|
|
|
try:
|
|
|
|
for item in what: self.labels_append(item)
|
2018-09-27 23:49:10 +05:30
|
|
|
except TypeError:
|
2016-05-17 05:24:00 +05:30
|
|
|
self.tags += [self._removeCRLF(str(what))]
|
2011-12-14 01:32:26 +05:30
|
|
|
|
2016-05-17 05:24:00 +05:30
|
|
|
self.__IO__['labeled'] = True # switch on processing (in particular writing) of tags
|
|
|
|
if reset: self.__IO__['tags'] = list(self.tags) # subsequent data_read uses current tags as data size
|
2013-10-08 19:24:13 +05:30
|
|
|
|
2013-06-30 05:51:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def labels_clear(self):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Delete existing labels and switch to no labeling"""
|
2016-05-17 05:24:00 +05:30
|
|
|
self.tags = []
|
2015-08-08 00:33:26 +05:30
|
|
|
self.__IO__['labeled'] = False
|
2013-06-30 05:51:51 +05:30
|
|
|
|
2016-05-17 05:24:00 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def labels(self,
|
|
|
|
tags = None,
|
2016-05-17 05:39:00 +05:30
|
|
|
raw = False):
|
2016-05-17 05:24:00 +05:30
|
|
|
"""
|
2016-10-25 00:46:29 +05:30
|
|
|
Tell abstract labels.
|
2016-05-17 05:39:00 +05:30
|
|
|
|
|
|
|
"x" for "1_x","2_x",... unless raw output is requested.
|
2016-05-17 05:24:00 +05:30
|
|
|
operates on object tags or given list.
|
|
|
|
"""
|
|
|
|
if tags is None: tags = self.tags
|
|
|
|
|
|
|
|
if isinstance(tags, Iterable) and not raw: # check whether list of tags is requested
|
|
|
|
id = 0
|
|
|
|
dim = 1
|
|
|
|
labelList = []
|
|
|
|
|
|
|
|
while id < len(tags):
|
|
|
|
if not tags[id].startswith('1_'):
|
|
|
|
labelList.append(tags[id])
|
|
|
|
else:
|
|
|
|
label = tags[id][2:] # get label
|
|
|
|
while id < len(tags) and tags[id] == '{}_{}'.format(dim,label): # check successors
|
|
|
|
id += 1 # next label...
|
|
|
|
dim += 1 # ...should be one higher dimension
|
2016-05-17 05:35:57 +05:30
|
|
|
labelList.append(label) # reached end --> store
|
2016-05-17 05:24:00 +05:30
|
|
|
id -= 1 # rewind one to consider again
|
|
|
|
|
|
|
|
id += 1
|
|
|
|
dim = 1
|
|
|
|
|
|
|
|
else:
|
|
|
|
labelList = self.tags
|
|
|
|
|
|
|
|
return labelList
|
|
|
|
|
2012-12-07 03:16:19 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-06-05 17:14:17 +05:30
|
|
|
def label_index(self,
|
|
|
|
labels):
|
2016-03-04 23:20:13 +05:30
|
|
|
"""
|
2016-10-25 00:46:29 +05:30
|
|
|
Tell index of column label(s).
|
2016-03-04 23:20:13 +05:30
|
|
|
|
|
|
|
return numpy array if asked for list of labels.
|
|
|
|
transparently deals with label positions implicitly given as numbers or their headings given as strings.
|
|
|
|
"""
|
2015-08-08 00:33:26 +05:30
|
|
|
if isinstance(labels, Iterable) and not isinstance(labels, str): # check whether list of labels is requested
|
2012-12-07 03:16:19 +05:30
|
|
|
idx = []
|
|
|
|
for label in labels:
|
2016-03-04 23:20:13 +05:30
|
|
|
if label is not None:
|
2013-12-09 21:15:18 +05:30
|
|
|
try:
|
2016-03-28 01:56:51 +05:30
|
|
|
idx.append(int(label)-1) # column given as integer number?
|
2013-12-09 21:15:18 +05:30
|
|
|
except ValueError:
|
2016-10-19 01:03:24 +05:30
|
|
|
label = label[1:-1] if label[0] == label[-1] and label[0] in ('"',"'") else label # remove outermost quotations
|
2015-05-22 03:23:54 +05:30
|
|
|
try:
|
2016-05-17 05:24:00 +05:30
|
|
|
idx.append(self.tags.index(label)) # locate string in label list
|
2015-05-22 03:23:54 +05:30
|
|
|
except ValueError:
|
2015-06-08 10:32:11 +05:30
|
|
|
try:
|
2016-05-17 05:24:00 +05:30
|
|
|
idx.append(self.tags.index('1_'+label)) # locate '1_'+string in label list
|
2015-06-08 10:32:11 +05:30
|
|
|
except ValueError:
|
2015-08-08 00:33:26 +05:30
|
|
|
idx.append(-1) # not found...
|
2012-12-07 03:16:19 +05:30
|
|
|
else:
|
|
|
|
try:
|
2016-03-28 01:56:51 +05:30
|
|
|
idx = int(labels)-1 # offset for python array indexing
|
2015-05-21 05:32:32 +05:30
|
|
|
except ValueError:
|
2013-12-09 21:15:18 +05:30
|
|
|
try:
|
2016-10-19 01:03:24 +05:30
|
|
|
labels = labels[1:-1] if labels[0] == labels[-1] and labels[0] in ('"',"'") else labels # remove outermost quotations
|
2016-05-17 05:24:00 +05:30
|
|
|
idx = self.tags.index(labels)
|
2015-06-08 10:32:11 +05:30
|
|
|
except ValueError:
|
|
|
|
try:
|
2016-05-17 05:24:00 +05:30
|
|
|
idx = self.tags.index('1_'+labels) # locate '1_'+string in label list
|
2015-06-08 10:32:11 +05:30
|
|
|
except ValueError:
|
2016-03-04 23:20:13 +05:30
|
|
|
idx = None if labels is None else -1
|
2012-12-07 03:16:19 +05:30
|
|
|
|
2016-03-28 01:56:51 +05:30
|
|
|
return np.array(idx) if isinstance(idx,Iterable) else idx
|
2012-12-07 03:16:19 +05:30
|
|
|
|
2015-06-05 17:14:17 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-06-08 10:32:11 +05:30
|
|
|
def label_dimension(self,
|
|
|
|
labels):
|
2016-03-04 23:20:13 +05:30
|
|
|
"""
|
2016-10-25 00:46:29 +05:30
|
|
|
Tell dimension (length) of column label(s).
|
2015-06-08 10:32:11 +05:30
|
|
|
|
2016-03-04 23:20:13 +05:30
|
|
|
return numpy array if asked for list of labels.
|
|
|
|
transparently deals with label positions implicitly given as numbers or their headings given as strings.
|
|
|
|
"""
|
2017-08-29 05:02:13 +05:30
|
|
|
listOfLabels = isinstance(labels, Iterable) and not isinstance(labels, str) # check whether list of labels is requested
|
|
|
|
if not listOfLabels: labels = [labels]
|
|
|
|
|
|
|
|
dim = []
|
|
|
|
for label in labels:
|
|
|
|
if label is not None:
|
|
|
|
myDim = -1
|
|
|
|
try: # column given as number?
|
|
|
|
idx = int(label)-1
|
|
|
|
myDim = 1 # if found treat as single column of dimension 1
|
|
|
|
except ValueError: # column has string label
|
|
|
|
label = label[1:-1] if label[0] == label[-1] and label[0] in ('"',"'") else label # remove outermost quotations
|
|
|
|
if label in self.tags: # can be directly found?
|
|
|
|
myDim = 1 # scalar by definition
|
|
|
|
elif '1_'+label in self.tags: # look for first entry of possible multidim object
|
|
|
|
idx = self.tags.index('1_'+label) # get starting column
|
|
|
|
myDim = 1 # (at least) one-dimensional
|
|
|
|
while idx+myDim < len(self.tags) and self.tags[idx+myDim].startswith("%i_"%(myDim+1)):
|
|
|
|
myDim += 1 # keep adding while going through object
|
|
|
|
|
|
|
|
dim.append(myDim)
|
|
|
|
|
|
|
|
return np.array(dim) if listOfLabels else dim[0]
|
2015-06-05 17:14:17 +05:30
|
|
|
|
2015-08-08 00:33:26 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def label_indexrange(self,
|
|
|
|
labels):
|
2016-03-04 23:20:13 +05:30
|
|
|
"""
|
2016-10-25 00:46:29 +05:30
|
|
|
Tell index range for given label(s).
|
2015-08-08 00:33:26 +05:30
|
|
|
|
2016-03-04 23:20:13 +05:30
|
|
|
return numpy array if asked for list of labels.
|
|
|
|
transparently deals with label positions implicitly given as numbers or their headings given as strings.
|
|
|
|
"""
|
2015-08-08 00:33:26 +05:30
|
|
|
start = self.label_index(labels)
|
|
|
|
dim = self.label_dimension(labels)
|
|
|
|
|
2016-11-30 01:05:30 +05:30
|
|
|
return np.hstack([range(s,s+d) for s,d in zip(start,dim)]).astype(int) \
|
|
|
|
if isinstance(labels, Iterable) and not isinstance(labels, str) \
|
2016-07-02 16:58:32 +05:30
|
|
|
else range(start,start+dim)
|
2016-03-28 01:56:51 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def info_append(self,
|
|
|
|
what):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Add item or list to existing set of infos"""
|
2018-09-27 23:49:10 +05:30
|
|
|
if isinstance(what, (str, unicode)):
|
|
|
|
self.info += [self._removeCRLF(what)]
|
|
|
|
else:
|
2013-12-12 08:06:05 +05:30
|
|
|
try:
|
|
|
|
for item in what: self.info_append(item)
|
2018-09-27 23:49:10 +05:30
|
|
|
except TypeError:
|
2016-04-24 20:37:37 +05:30
|
|
|
self.info += [self._removeCRLF(str(what))]
|
2011-12-14 01:32:26 +05:30
|
|
|
|
2012-02-23 19:24:38 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def info_clear(self):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Delete any info block"""
|
2012-02-23 19:24:38 +05:30
|
|
|
self.info = []
|
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2012-01-20 02:07:53 +05:30
|
|
|
def data_rewind(self):
|
2015-08-08 00:33:26 +05:30
|
|
|
self.__IO__['in'].seek(self.__IO__['dataStart']) # position file to start of data section
|
|
|
|
self.__IO__['readBuffer'] = [] # delete any non-advancing data reads
|
2016-05-17 05:24:00 +05:30
|
|
|
self.tags = list(self.__IO__['tags']) # restore label info found in header (as COPY, not link)
|
|
|
|
self.__IO__['labeled'] = len(self.tags) > 0
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2012-04-18 17:12:57 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-08-08 00:33:26 +05:30
|
|
|
def data_skipLines(self,
|
|
|
|
count):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Wind forward by count number of lines"""
|
2016-07-02 16:58:32 +05:30
|
|
|
for i in range(count):
|
2014-02-04 05:14:29 +05:30
|
|
|
alive = self.data_read()
|
|
|
|
|
|
|
|
return alive
|
2012-04-18 17:12:57 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-08-08 00:33:26 +05:30
|
|
|
def data_read(self,
|
2015-11-04 02:44:45 +05:30
|
|
|
advance = True,
|
|
|
|
respectLabels = True):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Read next line (possibly buffered) and parse it into data array"""
|
2015-10-07 06:33:26 +05:30
|
|
|
self.line = self.__IO__['readBuffer'].pop(0) if len(self.__IO__['readBuffer']) > 0 \
|
2015-12-23 03:47:15 +05:30
|
|
|
else self.__IO__['in'].readline().strip() # take buffered content or get next data row from file
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2014-02-04 05:14:29 +05:30
|
|
|
if not advance:
|
2015-08-21 01:08:06 +05:30
|
|
|
self.__IO__['readBuffer'].append(self.line) # keep line just read in buffer
|
|
|
|
|
|
|
|
self.line = self.line.rstrip('\n')
|
2014-02-04 05:14:29 +05:30
|
|
|
|
2015-11-04 02:44:45 +05:30
|
|
|
if self.__IO__['labeled'] and respectLabels: # if table has labels
|
2016-05-17 05:24:00 +05:30
|
|
|
items = shlex.split(self.line)[:len(self.__IO__['tags'])] # use up to label count (from original file info)
|
|
|
|
self.data = items if len(items) == len(self.__IO__['tags']) else [] # take entries if label count matches
|
2013-06-30 05:51:51 +05:30
|
|
|
else:
|
2016-04-29 08:38:11 +05:30
|
|
|
self.data = shlex.split(self.line) # otherwise take all
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
return self.data != []
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2013-12-14 09:21:22 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def data_readArray(self,
|
|
|
|
labels = []):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Read whole data of all (given) labels as numpy array"""
|
2018-09-27 23:49:10 +05:30
|
|
|
try: self.data_rewind() # try to wind back to start of data
|
|
|
|
except: pass # assume/hope we are at data start already...
|
2015-08-08 00:33:26 +05:30
|
|
|
|
2016-03-04 23:20:13 +05:30
|
|
|
if labels is None or labels == []:
|
2015-07-09 09:10:15 +05:30
|
|
|
use = None # use all columns (and keep labels intact)
|
2015-05-21 05:32:32 +05:30
|
|
|
labels_missing = []
|
2015-05-14 22:37:50 +05:30
|
|
|
else:
|
2015-08-24 04:48:34 +05:30
|
|
|
if isinstance(labels, str) or not isinstance(labels, Iterable): # check whether labels are a list or single item
|
|
|
|
labels = [labels]
|
2015-08-08 00:33:26 +05:30
|
|
|
indices = self.label_index(labels) # check requested labels ...
|
|
|
|
dimensions = self.label_dimension(labels) # ... and remember their dimension
|
2015-05-21 05:32:32 +05:30
|
|
|
present = np.where(indices >= 0)[0] # positions in request list of labels that are present ...
|
|
|
|
missing = np.where(indices < 0)[0] # ... and missing in table
|
2015-06-13 17:13:34 +05:30
|
|
|
labels_missing = np.array(labels)[missing] # labels of missing data
|
|
|
|
|
|
|
|
columns = []
|
2015-08-08 00:33:26 +05:30
|
|
|
for i,(c,d) in enumerate(zip(indices[present],dimensions[present])): # for all valid labels ...
|
2016-03-04 23:20:13 +05:30
|
|
|
# ... transparently add all components unless column referenced by number or with explicit dimension
|
2016-11-24 20:07:27 +05:30
|
|
|
columns += list(range(c,c +
|
|
|
|
(d if str(c) != str(labels[present[i]]) else
|
2016-07-02 16:58:32 +05:30
|
|
|
1)))
|
2016-08-11 23:52:07 +05:30
|
|
|
use = np.array(columns) if len(columns) > 0 else None
|
2018-12-08 08:36:47 +05:30
|
|
|
|
|
|
|
self.tags = list(np.array(self.__IO__['tags'])[use]) # update labels with valid subset
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2015-11-14 07:18:16 +05:30
|
|
|
self.data = np.loadtxt(self.__IO__['in'],usecols=use,ndmin=2)
|
2016-11-24 20:07:27 +05:30
|
|
|
# self.data = np.genfromtxt(self.__IO__['in'],dtype=None,names=self.tags,usecols=use)
|
2015-08-08 00:33:26 +05:30
|
|
|
|
2015-05-21 05:32:32 +05:30
|
|
|
return labels_missing
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-08-08 00:33:26 +05:30
|
|
|
def data_write(self,
|
|
|
|
delimiter = '\t'):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Write current data array and report alive output back"""
|
2014-02-04 05:14:29 +05:30
|
|
|
if len(self.data) == 0: return True
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2011-12-14 01:32:26 +05:30
|
|
|
if isinstance(self.data[0],list):
|
2016-04-29 08:38:11 +05:30
|
|
|
return self.output_write([delimiter.join(map(self._quote,items)) for items in self.data])
|
2011-12-14 01:32:26 +05:30
|
|
|
else:
|
2016-04-29 08:38:11 +05:30
|
|
|
return self.output_write( delimiter.join(map(self._quote,self.data)))
|
2011-12-14 01:32:26 +05:30
|
|
|
|
2013-06-30 05:51:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2015-10-01 00:14:54 +05:30
|
|
|
def data_writeArray(self,
|
|
|
|
fmt = None,
|
|
|
|
delimiter = '\t'):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Write whole numpy array data"""
|
2015-08-21 01:08:06 +05:30
|
|
|
for row in self.data:
|
2015-10-01 00:14:54 +05:30
|
|
|
try:
|
2016-07-02 16:58:32 +05:30
|
|
|
output = [fmt % value for value in row] if fmt else list(map(repr,row))
|
2015-10-01 00:14:54 +05:30
|
|
|
except:
|
|
|
|
output = [fmt % row] if fmt else [repr(row)]
|
|
|
|
|
2016-12-25 23:11:06 +05:30
|
|
|
try:
|
|
|
|
self.__IO__['out'].write(delimiter.join(output) + '\n')
|
|
|
|
except:
|
|
|
|
pass
|
2013-06-30 05:51:51 +05:30
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
2011-12-14 01:32:26 +05:30
|
|
|
def data_append(self,
|
|
|
|
what):
|
2018-09-27 23:49:10 +05:30
|
|
|
if isinstance(what, (str, unicode)):
|
|
|
|
self.data += [what]
|
|
|
|
else:
|
2013-12-12 08:06:05 +05:30
|
|
|
try:
|
|
|
|
for item in what: self.data_append(item)
|
2018-09-27 23:49:10 +05:30
|
|
|
except TypeError:
|
2013-12-12 08:06:05 +05:30
|
|
|
self.data += [str(what)]
|
2012-02-02 22:43:51 +05:30
|
|
|
|
2012-02-15 20:20:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def data_set(self,
|
2015-08-08 00:33:26 +05:30
|
|
|
what, where):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Update data entry in column "where". grows data array if needed."""
|
2012-02-15 20:20:51 +05:30
|
|
|
idx = -1
|
|
|
|
try:
|
2015-08-08 00:33:26 +05:30
|
|
|
idx = self.label_index(where)
|
2012-02-15 20:20:51 +05:30
|
|
|
if len(self.data) <= idx:
|
2016-07-02 16:58:32 +05:30
|
|
|
self.data_append(['n/a' for i in range(idx+1-len(self.data))]) # grow data if too short
|
2012-02-15 20:20:51 +05:30
|
|
|
self.data[idx] = str(what)
|
2013-09-14 16:22:02 +05:30
|
|
|
except(ValueError):
|
2012-02-15 20:20:51 +05:30
|
|
|
pass
|
|
|
|
|
|
|
|
return idx
|
2015-07-22 02:14:40 +05:30
|
|
|
|
2012-02-15 20:20:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def data_clear(self):
|
|
|
|
self.data = []
|
|
|
|
|
2012-02-02 22:43:51 +05:30
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def data_asFloat(self):
|
2016-07-02 16:58:32 +05:30
|
|
|
return list(map(self._transliterateToFloat,self.data))
|
2015-08-08 00:33:26 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def microstructure_read(self,
|
2016-03-18 03:10:40 +05:30
|
|
|
grid,
|
2016-03-21 02:16:35 +05:30
|
|
|
type = 'i',
|
|
|
|
strict = False):
|
2016-10-25 00:46:29 +05:30
|
|
|
"""Read microstructure data (from .geom format)"""
|
2016-03-18 03:10:40 +05:30
|
|
|
def datatype(item):
|
|
|
|
return int(item) if type.lower() == 'i' else float(item)
|
|
|
|
|
2016-05-17 05:24:00 +05:30
|
|
|
N = grid.prod() # expected number of microstructure indices in data
|
|
|
|
microstructure = np.zeros(N,type) # initialize as flat array
|
2015-08-08 00:33:26 +05:30
|
|
|
|
|
|
|
i = 0
|
|
|
|
while i < N and self.data_read():
|
|
|
|
items = self.data
|
|
|
|
if len(items) > 2:
|
2016-10-29 14:19:40 +05:30
|
|
|
if items[1].lower() == 'of':
|
|
|
|
items = np.ones(datatype(items[0]))*datatype(items[2])
|
2018-09-27 23:49:10 +05:30
|
|
|
elif items[1].lower() == 'to':
|
2016-10-29 14:19:40 +05:30
|
|
|
items = np.linspace(datatype(items[0]),datatype(items[2]),
|
|
|
|
abs(datatype(items[2])-datatype(items[0]))+1,dtype=int)
|
2016-07-02 16:58:32 +05:30
|
|
|
else: items = list(map(datatype,items))
|
|
|
|
else: items = list(map(datatype,items))
|
2015-08-08 00:33:26 +05:30
|
|
|
|
2016-05-17 05:24:00 +05:30
|
|
|
s = min(len(items), N-i) # prevent overflow of microstructure array
|
2015-08-08 00:33:26 +05:30
|
|
|
microstructure[i:i+s] = items[:s]
|
2016-03-21 02:16:35 +05:30
|
|
|
i += len(items)
|
2015-08-08 00:33:26 +05:30
|
|
|
|
2016-03-21 18:21:56 +05:30
|
|
|
return (microstructure, i == N and not self.data_read()) if strict else microstructure # check for proper point count and end of file
|