polishing as a result of discussing merge request of branch 25 with Philip
This commit is contained in:
parent
20f70dc943
commit
1eb82b99da
|
@ -15,10 +15,7 @@ class Section():
|
||||||
}
|
}
|
||||||
self.parameters = {}
|
self.parameters = {}
|
||||||
for key in data:
|
for key in data:
|
||||||
if type(data[key]) is not list:
|
self.parameters[key] = data[key] if isinstance(data[key], list) else [data[key]]
|
||||||
self.parameters[key] = [data[key]] #this is creating a dictionary. So this is a way to create elements in a dictionary
|
|
||||||
else:
|
|
||||||
self.parameters[key] = data[key]
|
|
||||||
|
|
||||||
if '__order__' not in self.parameters:
|
if '__order__' not in self.parameters:
|
||||||
self.parameters['__order__'] = list(self.parameters.keys())
|
self.parameters['__order__'] = list(self.parameters.keys())
|
||||||
|
@ -30,8 +27,7 @@ class Section():
|
||||||
multiKey = '(%s)'%key
|
multiKey = '(%s)'%key
|
||||||
if multiKey not in self.parameters: self.parameters[multiKey] = []
|
if multiKey not in self.parameters: self.parameters[multiKey] = []
|
||||||
if multiKey not in self.parameters['__order__']: self.parameters['__order__'] += [multiKey]
|
if multiKey not in self.parameters['__order__']: self.parameters['__order__'] += [multiKey]
|
||||||
if type(data) == list: self.parameters[multiKey] += [[item] for item in data]
|
self.parameters[multiKey] += [[item] for item in data] if isinstance(data, list) else [[data]]
|
||||||
else: self.parameters[multiKey] += [[data]]
|
|
||||||
|
|
||||||
def data(self):
|
def data(self):
|
||||||
return self.parameters
|
return self.parameters
|
||||||
|
@ -63,14 +59,8 @@ class Texture(Section):
|
||||||
|
|
||||||
def add_component(self,theType,properties):
|
def add_component(self,theType,properties):
|
||||||
|
|
||||||
if 'scatter' not in list(map(str.lower,list(properties.keys()))):
|
scatter = properties['scatter'] if 'scatter' in list(map(str.lower,list(properties.keys()))) else 0.0
|
||||||
scatter = 0.0
|
fraction = properties['fraction'] if 'fraction' in list(map(str.lower,list(properties.keys()))) else 1.0
|
||||||
else:
|
|
||||||
scatter = properties['scatter']
|
|
||||||
if 'fraction' not in list(map(str.lower,list(properties.keys()))):
|
|
||||||
fraction = 1.0
|
|
||||||
else:
|
|
||||||
fraction = properties['fraction']
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
multiKey = theType.lower()
|
multiKey = theType.lower()
|
||||||
|
@ -122,22 +112,28 @@ class Material():
|
||||||
self.verbose = verbose
|
self.verbose = verbose
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
"""Returns current configuration to be used as material.config"""
|
"""Returns current data structure in material.config format"""
|
||||||
me = []
|
me = []
|
||||||
for part in self.parts:
|
for part in self.parts:
|
||||||
if self.verbose: print('doing '+part)
|
if self.verbose: print('processing <{}>'.format(part))
|
||||||
me += ['','#-----------------------------#','<%s>'%part,'#-----------------------------#',]
|
me += ['',
|
||||||
|
'#-----------------------------#',
|
||||||
|
'<{}>'.format(part),
|
||||||
|
'#-----------------------------#',
|
||||||
|
]
|
||||||
for section in self.data[part]['__order__']:
|
for section in self.data[part]['__order__']:
|
||||||
me += ['','[%s] %s'%(section,'-'*max(0,27-len(section))),'',]
|
me += ['',
|
||||||
|
'[{}] {}'.format(section,'#'*max(0,27-len(section))),
|
||||||
|
'',
|
||||||
|
]
|
||||||
for key in self.data[part][section]['__order__']:
|
for key in self.data[part][section]['__order__']:
|
||||||
if key.startswith('(') and key.endswith(')'): # multiple (key)
|
if key.startswith('(') and key.endswith(')'): # multiple (key)
|
||||||
me += ['%s\t%s'%(key,' '.join(values)) for values in self.data[part][section][key]]
|
me += ['{}\t{}'.format(key,' '.join(values)) for values in self.data[part][section][key]]
|
||||||
else: # plain key
|
else: # plain key
|
||||||
me += ['%s\t%s'%(key,' '.join(map(str,self.data[part][section][key])))]
|
me += ['{}\t{}'.format(key,' '.join(map(str,self.data[part][section][key])))]
|
||||||
|
return '\n'.join(me) + '\n'
|
||||||
|
|
||||||
return '\n'.join(me)
|
def parse(self, part=None, sections=[], content=None):
|
||||||
|
|
||||||
def parse_data(self, part=None, sections=[], content=None):
|
|
||||||
|
|
||||||
re_part = re.compile(r'^<(.+)>$') # pattern for part
|
re_part = re.compile(r'^<(.+)>$') # pattern for part
|
||||||
re_sec = re.compile(r'^\[(.+)\]$') # pattern for section
|
re_sec = re.compile(r'^\[(.+)\]$') # pattern for section
|
||||||
|
@ -149,10 +145,10 @@ class Material():
|
||||||
line = line.split('#')[0].strip() # kill comments and extra whitespace
|
line = line.split('#')[0].strip() # kill comments and extra whitespace
|
||||||
line = line.split('/echo/')[0].strip() # remove '/echo/' tags
|
line = line.split('/echo/')[0].strip() # remove '/echo/' tags
|
||||||
line = line.lower() # be case insensitive
|
line = line.lower() # be case insensitive
|
||||||
print(line)
|
|
||||||
if line: # content survives...
|
if line: # content survives...
|
||||||
match_part = re_part.match(line)
|
match_part = re_part.match(line)
|
||||||
if match_part: # found <part> separator
|
if match_part: # found <...> separator
|
||||||
active = (match_part.group(1) == part) # only active in <part>
|
active = (match_part.group(1) == part) # only active in <part>
|
||||||
continue
|
continue
|
||||||
if active:
|
if active:
|
||||||
|
@ -164,7 +160,7 @@ class Material():
|
||||||
self.data[part][name_section] = {'__order__':[]}
|
self.data[part][name_section] = {'__order__':[]}
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if sections == [] or name_section in sections: # respect subset
|
if sections == [] or name_section in sections: # possibly restrict to subset
|
||||||
items = line.split()
|
items = line.split()
|
||||||
if items[0] not in self.data[part][name_section]: # first encounter of key?
|
if items[0] not in self.data[part][name_section]: # first encounter of key?
|
||||||
self.data[part][name_section][items[0]] = [] # create item
|
self.data[part][name_section][items[0]] = [] # create item
|
||||||
|
@ -176,45 +172,41 @@ class Material():
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def read(self,file=None):
|
def read(self,filename=None):
|
||||||
|
|
||||||
def readInclude(filename):
|
def recursiveRead(filename):
|
||||||
result = []
|
result = []
|
||||||
re_include = re.compile(r'^{(.+)}$')
|
re_include = re.compile(r'^{(.+)}$')
|
||||||
with open(filename) as f: myData = f.readlines()
|
with open(filename) as f: lines = f.readlines()
|
||||||
for line in myData:
|
for line in lines:
|
||||||
match = re_include.match(line.split()[0]) if line.strip() else False
|
match = re_include.match(line.split()[0]) if line.strip() else False
|
||||||
if match:
|
result += [line] if match else recursiveRead(match.group(1) if match.group(1).startswith('/') else
|
||||||
result += readInclude(match.group(1) if match.group(1).startswith('/') else
|
os.path.normpath(os.path.join(os.path.dirname(filename),match.group(1))))
|
||||||
os.path.normpath(os.path.join(os.path.dirname(filename),match.group(1))))
|
|
||||||
else:
|
|
||||||
result.append(line)
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
c = readInclude(file)
|
c = recursiveRead(filename)
|
||||||
for p in self.parts:
|
for p in self.parts:
|
||||||
self.parse_data(part=p, content=c)
|
self.parse(part=p, content=c)
|
||||||
|
|
||||||
def write(self,file='material.config', overwrite=False):
|
def write(self,filename='material.config', overwrite=False):
|
||||||
i = 0
|
i = 0
|
||||||
saveFile = file
|
outname = filename
|
||||||
while not overwrite and os.path.exists(saveFile):
|
while os.path.exists(outname) and not overwrite:
|
||||||
i += 1
|
i += 1
|
||||||
saveFile = file+'_%i'%i
|
outname = '{}_{}'.format(filename,i)
|
||||||
|
|
||||||
if self.verbose: print('Writing material data to file %s'%saveFile)
|
if self.verbose: print('Writing material data to {}'.format(outname))
|
||||||
f=open(saveFile,'w')
|
with open(outname,'w') as f:
|
||||||
f.write(str(self)+'\n') #newline at end
|
f.write(str(self))
|
||||||
f.close()
|
return outname
|
||||||
return saveFile
|
|
||||||
|
|
||||||
def add_section(self, part=None, section=None, initialData=None, merge = False):
|
def add_section(self, part=None, section=None, initialData=None, merge=False):
|
||||||
"""adding/updating"""
|
"""adding/updating"""
|
||||||
part = part.lower()
|
part = part.lower()
|
||||||
section = section.lower()
|
section = section.lower()
|
||||||
if part not in self.parts: raise Exception('invalid part %s'%part)
|
if part not in self.parts: raise Exception('invalid part {}'.format(part))
|
||||||
|
|
||||||
if type(initialData) is not dict:
|
if not isinstance(initialData, dict):
|
||||||
initialData = initialData.data()
|
initialData = initialData.data()
|
||||||
|
|
||||||
if section not in self.data[part]: self.data[part]['__order__'] += [section]
|
if section not in self.data[part]: self.data[part]['__order__'] += [section]
|
||||||
|
@ -244,17 +236,17 @@ class Material():
|
||||||
components=dict((k.lower(), v) for k,v in components.items())
|
components=dict((k.lower(), v) for k,v in components.items())
|
||||||
|
|
||||||
for key in ['phase','texture','fraction','crystallite']:
|
for key in ['phase','texture','fraction','crystallite']:
|
||||||
if type(components[key]) is not list:
|
if isinstance(components[key], list):
|
||||||
try:
|
|
||||||
components[key] = [components[key].lower()]
|
|
||||||
except AttributeError:
|
|
||||||
components[key] = [components[key]]
|
|
||||||
else:
|
|
||||||
for i, x in enumerate(components[key]):
|
for i, x in enumerate(components[key]):
|
||||||
try:
|
try:
|
||||||
components[key][i] = x.lower()
|
components[key][i] = x.lower()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
pass
|
pass
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
components[key] = [components[key].lower()]
|
||||||
|
except AttributeError:
|
||||||
|
components[key] = [components[key]]
|
||||||
|
|
||||||
for (phase,texture,fraction,crystallite) in zip(components['phase'],components['texture'],
|
for (phase,texture,fraction,crystallite) in zip(components['phase'],components['texture'],
|
||||||
components['fraction'],components['crystallite']):
|
components['fraction'],components['crystallite']):
|
||||||
|
@ -283,3 +275,4 @@ class Material():
|
||||||
if newlen is not oldlen:
|
if newlen is not oldlen:
|
||||||
print('Length of value was changed from %i to %i!'%(oldlen,newlen))
|
print('Length of value was changed from %i to %i!'%(oldlen,newlen))
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue