Skip to content

Commit cb160fc

Browse files
committed
Add image self-test; postpone GSASIIctrlGUI import until needed in CIF export; clean-up a bad open/write use
1 parent b6ab75b commit cb160fc

File tree

4 files changed

+115
-2
lines changed

4 files changed

+115
-2
lines changed

GSASII/GSASIIscriptable.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,8 @@ def import_generic(filename, readerlist, fmthint=None, bank=None,
410410
G2fil.G2Print(f'Preparing to download {filename}')
411411
response = requests.get(filename)
412412
filename = os.path.join(download_loc,fname)
413-
open(filename,'wb').write(response.content)
413+
with open(filename,'wb') as fp:
414+
fp.write(response.content)
414415
G2fil.G2Print(f'File {filename} written')
415416
primaryReaders, secondaryReaders = [], []
416417
for reader in readerlist:

GSASII/exports/G2export_CIF.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import wx.lib.scrolledpanel as wxscroll
1818
import wx.lib.resizewidget as rw
1919
interactive = True
20-
from .. import GSASIIctrlGUI as G2G
2120
except ImportError:
2221
G2G = None
2322
# Avoid wx dependency for Scriptable
@@ -1381,6 +1380,7 @@ def ValidateAscii(self,checklist):
13811380
if msg: msg += '\n'
13821381
msg += lbl + " contains unicode characters: " + val
13831382
if msg:
1383+
from .. import GSASIIctrlGUI as G2G
13841384
G2G.G2MessageBox(self.G2frame,
13851385
'Error: CIFs can contain only ASCII characters. Please change item(s) below:\n\n'+msg,
13861386
'Unicode not valid for CIF')
@@ -2038,6 +2038,7 @@ def WriteDistances(phasenam):
20382038
if 'DisAglCtls' not in generalData:
20392039
# should not happen, since DisAglDialog should be called
20402040
# for all phases before getting here
2041+
from .. import GSASIIctrlGUI as G2G
20412042
dlg = G2G.DisAglDialog(
20422043
self.G2frame,
20432044
{},
@@ -3417,6 +3418,7 @@ def WriteSingleXtalData(histlbl):
34173418
def EditAuthor(event=None):
34183419
'dialog to edit the CIF author info'
34193420
'Edit the CIF author name'
3421+
from .. import GSASIIctrlGUI as G2G
34203422
dlg = G2G.SingleStringDialog(self.G2frame,
34213423
'Get CIF Author',
34223424
'Provide CIF Author name (Last, First)',
@@ -3435,6 +3437,7 @@ def EditAuthor(event=None):
34353437

34363438
def EditInstNames(event=None):
34373439
'Provide a dialog for editing instrument names; for sequential fit, only need one name'
3440+
from .. import GSASIIctrlGUI as G2G
34383441
dictlist = []
34393442
keylist = []
34403443
lbllist = []
@@ -3468,6 +3471,7 @@ def EditRanges(event):
34683471
'''
34693472
but = event.GetEventObject()
34703473
phasedict = but.phasedict
3474+
from .. import GSASIIctrlGUI as G2G
34713475
dlg = G2G.DisAglDialog(
34723476
self.G2frame,
34733477
phasedict['General']['DisAglCtls'], # edited
@@ -3489,6 +3493,7 @@ def EditCIFDefaults():
34893493
'''Fills the CIF Defaults window with controls for editing various CIF export
34903494
parameters (mostly related to templates).
34913495
'''
3496+
from .. import GSASIIctrlGUI as G2G
34923497
if len(self.cifdefs.GetChildren()) > 0:
34933498
saveSize = self.cifdefs.GetSize()
34943499
self.cifdefs.DestroyChildren()
@@ -3659,6 +3664,7 @@ def _ResetSelT(event):
36593664

36603665
def SelectDisAglFlags(event):
36613666
'Select Distance/Angle use flags for the selected phase'
3667+
from .. import GSASIIctrlGUI as G2G
36623668
phasenam = event.GetEventObject().phase
36633669
phasedict = self.Phases[phasenam]
36643670
SymOpList,offsetList,symOpList,G2oprList,G2opcodes = G2spc.AllOps(phasedict['General']['SGData'])
@@ -4059,6 +4065,7 @@ def SelectDisAglFlags(event):
40594065
#i = self.Phases[phasenam]['pId']
40604066
phasedict = self.Phases[phasenam] # pointer to current phase info
40614067
if 'DisAglCtls' not in phasedict['General']:
4068+
from .. import GSASIIctrlGUI as G2G
40624069
dlg = G2G.DisAglDialog(
40634070
self.G2frame,
40644071
{},
@@ -4709,6 +4716,7 @@ def __init__(self,G2frame):
47094716
self.author = ''
47104717

47114718
def mergeMag(self,G2frame,ChemPhase,MagPhase):
4719+
from .. import GSASIIctrlGUI as G2G
47124720
def onChange(*args,**kwargs):
47134721
wx.CallLater(100,showMergeMag)
47144722
def showMergeMag():
@@ -5246,6 +5254,7 @@ class EditCIFtemplate(wx.Dialog):
52465254
saving the CIF.
52475255
'''
52485256
def __init__(self,parent,cifblk,loopstructure,defaultname):
5257+
from .. import GSASIIctrlGUI as G2G
52495258
OKbuttons = []
52505259
self.cifblk = cifblk
52515260
self.loopstructure = loopstructure
@@ -5290,6 +5299,7 @@ def Post(self):
52905299
return (self.ShowModal() == wx.ID_OK)
52915300
def _onSave(self,event):
52925301
'Save CIF entries in a template file'
5302+
from .. import GSASIIctrlGUI as G2G
52935303
pth = G2G.GetExportPath(self.G2frame)
52945304
dlg = wx.FileDialog(
52955305
self, message="Save as CIF template",
@@ -5334,6 +5344,7 @@ class EditCIFpanel(wxscroll.ScrolledPanel):
53345344
:param (other): optional keyword parameters for wx.ScrolledPanel
53355345
'''
53365346
def __init__(self, parent, cifblk, loopstructure, cifdic={}, OKbuttons=[], **kw):
5347+
from .. import GSASIIctrlGUI as G2G
53375348
self.parent = parent
53385349
wxscroll.ScrolledPanel.__init__(self, parent, wx.ID_ANY, **kw)
53395350
self.vbox = None
@@ -5492,6 +5503,7 @@ def CIFEntryWidget(self,dct,item,dataname):
54925503
numerical values and highlights them as invalid.
54935504
Use a selection widget when there are specific enumerated values for a string.
54945505
'''
5506+
from .. import GSASIIctrlGUI as G2G
54955507
if self.cifdic.get(dataname):
54965508
if self.cifdic[dataname].get('_enumeration'):
54975509
values = ['?']+self.cifdic[dataname]['_enumeration']
@@ -5648,6 +5660,7 @@ def _onResetTemplate(event):
56485660
self.Add(hbox)
56495661
def _onGetTemplateFile(self,event):
56505662
'select a template file'
5663+
from .. import GSASIIctrlGUI as G2G
56515664
pth = G2G.GetImportPath(self.G2frame)
56525665
if not pth: pth = '.'
56535666
dlg = wx.FileDialog(

tests/test_image.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# perform a GSAS-II refinement using GSASIIscriptable and tutorial
2+
# data
3+
4+
import os
5+
import sys
6+
import tempfile
7+
import numpy.testing as npt
8+
home = os.path.dirname(__file__)
9+
work = tempfile.gettempdir()
10+
import importlib.util
11+
12+
G2loc = None
13+
try:
14+
G2loc = importlib.util.find_spec('GSASII.GSASIIscriptable')
15+
except ModuleNotFoundError:
16+
print('ModuleNotFound for GSASII.GSASIIscriptable')
17+
18+
if G2loc is None: # fixup path if GSASII not installed into Python
19+
print('GSAS-II not installed in Python; Hacking sys.path')
20+
sys.path.append(os.path.dirname(home))
21+
22+
import GSASII
23+
import GSASII.GSASIIscriptable as G2sc
24+
25+
def test_image():
26+
try:
27+
import requests
28+
except ModuleNotFoundError:
29+
print('Module requests not installed, test_image cannot be run')
30+
return
31+
workloc = lambda fil: os.path.join(work,fil)
32+
gpx = G2sc.G2Project(newgpx=workloc('test_image.gpx'))
33+
img = 'https://advancedphotonsource.github.io/GSAS-II-tutorials/2DStrain/data/nx09_strain_011.mar2300'
34+
img = gpx.add_image(img, fmthint='MAR', cacheImage=True, URL=True,
35+
download_loc=None)
36+
# img = gpx.add_image(fmthint='MAR', cacheImage=True,
37+
# imagefile='/tmp/download.mar2300')
38+
testdir = os.path.join(os.path.dirname(os.path.abspath( __file__ )),'testinp')
39+
img[0].loadControls(os.path.join(testdir,'nx09_strain_011.imctrl'))
40+
img[0].GeneratePixelMask()
41+
masked = sum(img[0].data['Masks']['SpotMask']['spotMask'].flatten())
42+
masked_ratio = masked/img[0].data['Masks']['SpotMask']['spotMask'].size
43+
msg = 'Confirm number of masked pixels is about the same'
44+
assert abs(masked_ratio - 0.02372608695652174) < 0.0001, msg #+ f" {masked_ratio}, 0.02372608695652174"
45+
#breakpoint()
46+
plist = img[0].Integrate()
47+
i = plist[0].getdata('yobs')
48+
x = plist[0].getdata('x')
49+
tt1,i1 = (x[233]+x[280])/2,sum(i[233:281])
50+
#print(tt1,i1)
51+
msg = 'Confirm 1st peak'
52+
assert abs(tt1 - 2.2695) < 0.0002, msg+' pos'
53+
assert abs(i1 - 4645.6850578694975) < 0.1, msg+' intensity'
54+
tt6,i6 = (x[780]+x[850])/2,sum(i[780:851])
55+
#print(tt6,i6)
56+
msg = 'Confirm 6th peak'
57+
assert abs(tt6 - 3.9450) < 0.0002, msg+' pos'
58+
assert abs(i6 - 26236.795563010724) < 0.1, msg+' intensity'
59+
print('OK')
60+
61+
if __name__ == '__main__':
62+
#import GSASII.GSASIIpath as GSASIIpath
63+
#GSASIIpath.InvokeDebugOpts()
64+
#import time
65+
#start = time.time()
66+
test_image()
67+
#print('elapsed=',time.time()-start)
68+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
type:PWDR
2+
color:GSPaired
3+
wavelength:0.12398
4+
calibrant:CeO2 SRM674b
5+
distance:1118.8555366950047
6+
center:[np.float64(168.59496999985376), np.float64(173.45708080489564)]
7+
Oblique:[0.5, False]
8+
tilt:1.2679918237395627
9+
rotation:94.80104622234859
10+
azmthOff:0.0
11+
fullIntegrate:True
12+
LRazimuth:[0.0, 360.0]
13+
setdist:100.0
14+
IOtth:[1.5, 9.0]
15+
outChannels:2500
16+
outAzimuths:1
17+
invert_x:False
18+
invert_y:True
19+
DetDepth:0.0
20+
calibskip:0
21+
pixLimit:2
22+
cutoff:1.0
23+
calibdmin:1.09
24+
Flat Bkg:0.0
25+
varyList:{'dist': True, 'det-X': True, 'det-Y': True, 'tilt': True, 'phi': True, 'dep': False, 'wave': False}
26+
binType:2-theta
27+
SampleShape:Cylinder
28+
PolaVal:[0.99, False]
29+
SampleAbs:[0.0, False]
30+
dark image:['', -1.0]
31+
background image:['', -1.0]

0 commit comments

Comments
 (0)