Skip to content

Commit c46f1c7

Browse files
committed
New scripting option to read in named HDF5 images; Add error message for New Var browser if no used phases
1 parent db2aede commit c46f1c7

4 files changed

Lines changed: 58 additions & 16 deletions

File tree

GSASII/GSASIIconstrGUI.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4461,6 +4461,11 @@ def saveCloseWindow(event):
44614461
# get parameter values and initialize and prepare constraints
44624462
from . import GSASIImiscGUI as G2IO
44634463
parmDict = G2IO.mkParmDictfromTree(G2frame)
4464+
if not parmDict:
4465+
G2G.G2MessageBox(G2frame,
4466+
'No parameters values were loaded. Are histogram(s) defined and linked to phase(s)?',
4467+
'No parameters')
4468+
return
44644469
# get the variables dependent on the New Vars
44654470
depVars = [] # find the dependent variables
44664471
for key in constrDict:

GSASII/GSASIImiscGUI.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1318,8 +1318,9 @@ def mkParmDictfromTree(G2frame,sigDict=None):
13181318
covDict = {}
13191319
consDict = {}
13201320

1321-
Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
13221321
if G2frame.GPXtree.IsEmpty(): return # nothing to do
1322+
Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
1323+
if not Phases or not Histograms: return # nothing to do
13231324
rigidbodyDict = G2frame.GPXtree.GetItemPyData(
13241325
G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Rigid bodies'))
13251326
covDict = G2frame.GPXtree.GetItemPyData(

GSASII/GSASIIscriptable.py

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -434,10 +434,16 @@ def downloadFile(URL,download_loc=None):
434434

435435
def import_generic(filename, readerlist, fmthint=None, bank=None,
436436
URL=False, download_loc=None, useNet=True,
437-
buffer=None):
437+
buffer=None,imageKey=None):
438438
"""Attempt to import a filename, using a list of reader objects.
439+
440+
This is not intended to be called directly in scripting, only by
441+
routines like G2Project.add_phase() and G2Project.add_image but
442+
this may be used to read CIFs, as is done with OnISODISTORT_kvec
443+
in GSASIIpwdGUI.
439444
440-
Returns the first reader object which worked."""
445+
Returns the first reader object which is read successfully.
446+
"""
441447
if URL is True:
442448
filename = downloadFile(filename,download_loc)
443449
# Translated from OnImportGeneric method in GSASIIGUI.py
@@ -506,14 +512,20 @@ def import_generic(filename, readerlist, fmthint=None, bank=None,
506512
repeat = False
507513
block += 1
508514
rd.objname = os.path.basename(filename)
515+
if imageKey:
516+
blockKey = imageKey
517+
else:
518+
blockKey = block
509519
if GSASIIpath.GetConfigValue('debug'):
510-
flag = rd.Reader(filename,buffer=rdbuffer, blocknum=block)
520+
# don't use try/except so we see errors
521+
flag = rd.Reader(filename,buffer=rdbuffer, blocknum=blockKey)
511522
else:
512523
try:
513-
flag = rd.Reader(filename,buffer=rdbuffer, blocknum=block)
524+
flag = rd.Reader(filename,buffer=rdbuffer, blocknum=blockKey)
514525
#except Exception as msg:
515526
except Exception:
516527
flag = False
528+
if imageKey: rd.repeat = False # only read one image
517529
if flag:
518530
# Omitting image loading special cases
519531
rd.readfilename = filename
@@ -525,12 +537,12 @@ def import_generic(filename, readerlist, fmthint=None, bank=None,
525537
if rd.warnings:
526538
G2fil.G2Print("Read warning by", rd.formatName, "reader:",
527539
rd.warnings)
540+
elif imageKey is not None:
541+
G2fil.G2Print(f"{filename} block {imageKey} read by Reader {rd.formatName}")
528542
elif bank is None:
529-
G2fil.G2Print("{} read by Reader {}"
530-
.format(filename,rd.formatName))
543+
G2fil.G2Print(f"{filename} read by Reader {rd.formatName}")
531544
else:
532-
G2fil.G2Print("{} block # {} read by Reader {}"
533-
.format(filename,bank,rd.formatName))
545+
G2fil.G2Print(f"{filename} block # {bank} read by Reader {rd.formatName}")
534546
return rd_list
535547
raise G2ImportException(f"No reader could read file: {filename}")
536548

@@ -2655,7 +2667,7 @@ def make_var_obj(self, phase=None, hist=None, varname=None, atomId=None,
26552667

26562668
def add_image(self, imagefile, fmthint=None, defaultImage=None,
26572669
indexList=None, cacheImage=False,
2658-
URL=False, download_loc=None):
2670+
URL=False, download_loc=None,imageKey=None):
26592671
"""Load an image into a project
26602672
26612673
:param str imagefile: The image file to read, a filename.
@@ -2669,7 +2681,9 @@ def add_image(self, imagefile, fmthint=None, defaultImage=None,
26692681
:param list indexList: specifies the image numbers (counting from zero)
26702682
to be used from the file when a file has multiple images. A value of
26712683
``[0,2,3]`` will cause the only first, third and fourth images in the file
2672-
to be included in the project.
2684+
to be included in the project. Note that with this option, all images
2685+
are read from the file, but only the specified image(s) are retained.
2686+
Do not use imageKey and indexList together.
26732687
:param bool cacheImage: When True, the image is cached to save
26742688
in rereading it later. Default is False (no caching).
26752689
:param bool URL: if True, the contents of imagefile is a URL
@@ -2694,14 +2708,24 @@ def add_image(self, imagefile, fmthint=None, defaultImage=None,
26942708
If URL is specified and the default download_loc
26952709
value is used (None), the image will be saved in a temporary
26962710
location that will persist until the OS removes it.
2711+
:param imageKey: This can be a single image number (int) to read
2712+
a specific image (numbered starting with 1) or for files
2713+
that have images in named sections, (right now this is only HDF5),
2714+
it can be a tuple of form ('section',0) where 'section' is
2715+
the section name (such as '/exchange/data') and 0 is the image
2716+
number in that section. If imageKey is specified, only one image
2717+
is read.
2718+
Do not use imageKey and indexList together.
26972719
:returns: a list of :class:`G2Image` object(s) for the added image(s)
26982720
"""
26992721
LoadG2fil()
27002722
if not URL: imagefile = os.path.abspath(os.path.expanduser(imagefile))
27012723
rdbuffer = {}
2724+
if imageKey and indexList:
2725+
raise Exception("add_image Error: Do not use imageKey and indexList together.")
27022726
readers = import_generic(imagefile, Readers['Image'],
27032727
fmthint=fmthint, URL=URL, download_loc=download_loc,
2704-
buffer=rdbuffer)
2728+
buffer=rdbuffer,imageKey=imageKey)
27052729
objlist = []
27062730
for i,rd in enumerate(readers):
27072731
if indexList is not None and i not in indexList:
@@ -2713,7 +2737,13 @@ def add_image(self, imagefile, fmthint=None, defaultImage=None,
27132737
rd.SciPy = False
27142738
rd.readfilename = imagefile
27152739
TreeLbl = 'IMG '+os.path.basename(imagefile)
2716-
if rd.repeatcount == 1 and not rd.repeat: # skip image number if only one in set
2740+
if 'ImageTag' in rd.Data: # HDF5 quickread by tag
2741+
TreeLbl += f' {rd.Data['ImageTag'][0]}-{rd.Data['ImageTag'][1]}'
2742+
rd.Data['ImageTag'] = (rd.Data['ImageTag'][0],
2743+
rd.Data['ImageTag'][1],
2744+
rd.Image.shape)
2745+
imageInfo = (imagefile,rd.Data.get('ImageTag'))
2746+
elif rd.repeatcount == 1 and not rd.repeat and not imageKey: # skip image number if only one in set
27172747
imageInfo = imagefile
27182748
elif 'imagemap' in rdbuffer:
27192749
# if there is an image map, save the entry there rather than

GSASII/imports/G2img_HDF5.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,12 @@ def Reader(self, filename, ParentFrame=None, **kwarg):
7979
if imagenum is None: imagenum = 1
8080
quick = False
8181
# do we have a image number or a map to the section with the image?
82+
imageTag = None
8283
try:
8384
int(imagenum) # test if image # is a tuple
8485
except: # pull the section name and number out from the imagenum value
85-
kwargs = {'name':imagenum[0],'num':imagenum[1]}
86+
readargs = {'name':imagenum[0],'num':imagenum[1]}
87+
imageTag = imagenum
8688
quick = True
8789
# set up an index as to where images are found
8890
self.buffer = kwarg.get('buffer',{})
@@ -138,10 +140,14 @@ def Reader(self, filename, ParentFrame=None, **kwarg):
138140
self.errors = 'No images selected from file'
139141
fp.close()
140142
return False
141-
kwargs = {'imagenum':imagenum}
142-
self.Data,self.Npix,self.Image = self.readDataset(fp,**kwargs)
143+
readargs = {'imagenum':imagenum}
144+
self.Data,self.Npix,self.Image = self.readDataset(fp,**readargs)
143145
if quick:
144146
fp.close()
147+
if GSASIIpath.GetConfigValue('debug'): print(f'Read image {imagenum} from file {filename}')
148+
# pointer to section of file & image number here
149+
if imageTag:
150+
self.Data['ImageTag'] = imageTag
145151
return True
146152
if self.Npix == 0:
147153
self.errors = 'No valid images found in file'

0 commit comments

Comments
 (0)