Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 21 additions & 20 deletions src/diffpy/srxplanar/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
##############################################################################

import numpy as np
import scipy.sparse as ssp

try:
import fabio
Expand All @@ -23,15 +22,15 @@ def openImage(im):
rv = fabio.openimage.openimage(im)
return rv.data

except:
except ImportError:
import tifffile

print("Only tiff or .npy mask is support since fabio is not available")

def openImage(im):
try:
rv = tifffile.imread(im)
except:
except (ValueError, OSError):
rv = 0
return rv

Expand Down Expand Up @@ -74,12 +73,14 @@ def staticMask(self, maskfile=None):
remain unchanged for different images.

:param maskfile: string, file name of mask,
mask file supported: .npy, .tif file, ATTN: mask in .npy form should be already flipped,
and 1 (or larger) stands for masked pixels, 0(<0) stands for unmasked pixels
mask file supported: .npy, .tif file, ATTN: mask in .npy form
should be already flipped,
and 1 (or larger) stands for masked pixels,
0(<0) stands for unmasked pixels

:return: 2d array of boolean, 1 stands for masked pixel
"""
maskfile = self.maskfile if maskfile == None else maskfile
maskfile = self.maskfile if maskfile is None else maskfile

if os.path.exists(maskfile):
if maskfile.endswith(".npy"):
Expand Down Expand Up @@ -117,13 +118,13 @@ def dynamicMask(

brightpixelmask = (
self.brightpixelmask
if brightpixelmask == None
if brightpixelmask is None
else brightpixelmask
)
darkpixelmask = (
self.darkpixelmask if darkpixelmask == None else darkpixelmask
self.darkpixelmask if darkpixelmask is None else darkpixelmask
)
avgmask = self.avgmask if avgmask == None else avgmask
avgmask = self.avgmask if avgmask is None else avgmask

if darkpixelmask or brightpixelmask or avgmask:
rv = np.zeros((self.ydimension, self.xdimension))
Expand All @@ -145,7 +146,7 @@ def edgeMask(self, cropedges=None):
edge (left, right, top, bottom), must larger than 0, if
None, use self.corpedges
"""
ce = self.cropedges if cropedges == None else cropedges
ce = self.cropedges if cropedges is None else cropedges
mask = np.ones((self.ydimension, self.xdimension), dtype=bool)
mask[ce[2] : -ce[3], ce[0] : -ce[1]] = 0
return mask
Expand All @@ -167,10 +168,10 @@ def avgMask(self, image, high=None, low=None, dymask=None, cropedges=None):
None, use self.config.corpedges :return 2d bool array, True
for masked pixel, edgemake included, dymask not included
"""
if dymask == None:
if dymask is None:
dymask = self.staticmask
high = self.config.avgmaskhigh if high == None else high
low = self.config.avgmasklow if low == None else low
high = self.config.avgmaskhigh if high is None else high
low = self.config.avgmasklow if low is None else low

self.calculate.genIntegrationInds(dymask)
chi = self.calculate.intensity(image)
Expand All @@ -180,7 +181,7 @@ def avgMask(self, image, high=None, low=None, dymask=None, cropedges=None):
index[index >= len(chi[1]) - 1] = len(chi[1]) - 1
avgimage = chi[1][index.ravel()].reshape(index.shape)
mask = np.ones((self.ydimension, self.xdimension), dtype=bool)
ce = self.cropedges if cropedges == None else cropedges
ce = self.cropedges if cropedges is None else cropedges
mask[ce[2] : -ce[3], ce[0] : -ce[1]] = np.logical_or(
image[ce[2] : -ce[3], ce[0] : -ce[1]] < avgimage * low,
image[ce[2] : -ce[3], ce[0] : -ce[1]] > avgimage * high,
Expand All @@ -195,7 +196,7 @@ def darkPixelMask(self, pic, r=None):
:param r: float, a threshold for masked pixels
:return: 2d array of boolean, 1 stands for masked pixel
"""
r = self.config.darkpixelr if r == None else r # 0.1
r = self.config.darkpixelr if r is None else r # 0.1

avgpic = np.average(pic)
ks = np.ones((5, 5))
Expand All @@ -222,8 +223,8 @@ def brightPixelMask(self, pic, size=None, r=None):
:param r: float, a threshold for masked pixels
:return: 2d array of boolean, 1 stands for masked pixel
"""
size = self.config.brightpixelsize if size == None else size # 5
r = self.config.brightpixelr if r == None else r # 1.2
size = self.config.brightpixelsize if size is None else size # 5
r = self.config.brightpixelr if r is None else r # 1.2

rank = snf.rank_filter(pic, -size, size)
ind = snm.binary_dilation(pic > rank * r, np.ones((3, 3)))
Expand Down Expand Up @@ -266,14 +267,14 @@ def saveMask(self, filename, pic=None, addmask=None):
"""
if not hasattr(self, "mask"):
self.normalMask(addmask)
if (not hasattr(self, "dynamicmask")) and (pic != None):
if (not hasattr(self, "dynamicmask")) and (pic is not None):
self.dynamicMask(pic, addmask=addmask)
tmask = self.mask
if hasattr(self, "dynamicmask"):
if self.dynamicmask != None:
if self.dynamicmask is not None:
tmask = (
np.logical_or(self.mask, self.dynamicmask)
if pic != None
if pic is not None
else self.mask
)
np.save(filename, tmask)
Expand Down
15 changes: 7 additions & 8 deletions src/diffpy/srxplanar/saveresults.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import os

import numpy as np
import scipy.io

from diffpy.srxplanar.srxplanarconfig import _configPropertyR

Expand Down Expand Up @@ -48,7 +47,7 @@ def getFilePathWithoutExt(self, filename):
:return: string, full normalized path of file without extension
"""
filebase = os.path.splitext(os.path.split(filename)[1])[0]
if self.filenameplus != "" and self.filenameplus != None:
if self.filenameplus != "" and self.filenameplus is not None:
filenamep = "_".join(
[filebase, self.filenameplus, self.integrationspace]
)
Expand Down Expand Up @@ -99,15 +98,15 @@ def saveGSAS(self, xrd, filename):
f.write("#### start data\n")
if xrd.shape[0] == 3:
s = writeGSASStr(
os.path.splitext(path)[0],
os.path.splitext(filepath)[0],
self.gsasoutput,
xrd[0],
xrd[1],
xrd[2],
)
elif xrd.shape[0] == 2:
s = writeGSASStr(
os.path.splitext(path)[0], self.gsasoutput, xrd[0], xrd[1]
os.path.splitext(filepath)[0], self.gsasoutput, xrd[0], xrd[1]
)
f.write(s)
f.close()
Expand All @@ -124,7 +123,7 @@ def writeGSASStr(name, mode, tth, iobs, esd=None):
:return: string, a string to be saved to file
"""
maxintensity = 999999
logscale = numpy.floor(numpy.log10(maxintensity / numpy.max(iobs)))
logscale = np.floor(np.log10(maxintensity / np.max(iobs)))
logscale = min(logscale, 0)
scale = 10 ** int(logscale)
lines = []
Expand All @@ -139,10 +138,10 @@ def writeGSASStr(name, mode, tth, iobs, esd=None):
# two-theta0 and dtwo-theta in centidegrees
tth0_cdg = tth[0] * 100
dtth_cdg = (tth[-1] - tth[0]) / (len(tth) - 1) * 100
if esd == None:
if esd is None:
mode = "std"
if mode == "std":
nrec = int(numpy.ceil(nchan / 10.0))
nrec = int(np.ceil(nchan / 10.0))
lbank = "BANK %5i %8i %8i CONST %9.5f %9.5f %9.5f %9.5f STD" % (
ibank,
nchan,
Expand All @@ -157,7 +156,7 @@ def writeGSASStr(name, mode, tth, iobs, esd=None):
for i in range(0, len(lrecs), 10):
lines.append("".join(lrecs[i : i + 10]))
if mode == "esd":
nrec = int(numpy.ceil(nchan / 5.0))
nrec = int(np.ceil(nchan / 5.0))
lbank = "BANK %5i %8i %8i CONST %9.5f %9.5f %9.5f %9.5f ESD" % (
ibank,
nchan,
Expand Down
30 changes: 7 additions & 23 deletions src/diffpy/srxplanar/selfcalibrate.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,23 @@
import os
from functools import partial

import numpy as np
import scipy as sp
from matplotlib import rcParams
from scipy.optimize import (
brent,
fmin_bfgs,
fmin_cg,
fmin_l_bfgs_b,
fmin_powell,
fmin_slsqp,
fmin_tnc,
golden,
leastsq,
minimize,
minimize_scalar,
)
from scipy.optimize import leastsq, minimize

rcParams["backend"] = "Qt4Agg"
try:
import PySide
import PySide # noqa: F401
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why #noqa in these lines?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because flake8 gives F401 error here, but actually I think it is implicitly used in the next line rcParams["backend.qt4"] = "PySide". Therefore, we should not delete it, that's why I make #noqa here.


rcParams["backend.qt4"] = "PySide"
import matplotlib.pyplot as plt

mplenabled = True
except:
except ImportError:
try:
import matplotlib.pyplot as plt
import PyQt4

mplenabled = True
except:
except ImportError:
mplenabled = False


Expand Down Expand Up @@ -233,13 +218,13 @@ def selfCalibrateX(
qind = [None, None]
qind[0] = (
int(qrange[0] / qstep)
if qrange[0] != None
if qrange[0] is not None
else srx.config.xdimension / 20
)
qind[0] = 0 if qind[0] < 0 else qind[0]
qind[1] = (
int(qrange[1] / qstep)
if qrange[1] != None
if qrange[1] is not None
else srx.config.xdimension / 2
)
qind[1] = (
Expand Down Expand Up @@ -316,7 +301,6 @@ def selfCalibrateX(
print(p)
if mode == "x":
srx.updateConfig(xbeamcenter=p[0], **bak)
prv = p[0]
elif mode == "y":
srx.updateConfig(ybeamcenter=p[0], **bak)
elif mode == "tilt":
Expand Down Expand Up @@ -395,7 +379,7 @@ def selfCalibrate(
elif cropedges == "x" or (cropedges == "auto" and mode == "x"):
ce = [xd / 100, xd / 100, int(yc - 50), int(yd - yc - 50)]
elif cropedges == "box" or (
cropedges == "auto" and (not mode in ["x", "y"])
cropedges == "auto" and (mode not in ["x", "y"])
):
ce = [
int(xc - xd / 6),
Expand Down
Loading