diff --git a/.style.yapf b/.style.yapf new file mode 100644 index 0000000000000000000000000000000000000000..31c66473c6435a92ab0a0d2774aa138dcfeff9a9 --- /dev/null +++ b/.style.yapf @@ -0,0 +1,3 @@ +[style] +based_on_style = pep8 +column_limit = 85 diff --git a/Doc/FFCatalog/fig/ff2/bornplot.py b/Doc/FFCatalog/fig/ff2/bornplot.py index b5bd7d63d8d6f31934ac4976827bc071f17b6cd6..cecb5a8ac858410f822f25fce42ff2b6b6fa4318 100644 --- a/Doc/FFCatalog/fig/ff2/bornplot.py +++ b/Doc/FFCatalog/fig/ff2/bornplot.py @@ -5,7 +5,7 @@ import math, numpy import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import rc -rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) +rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) rc('image', cmap='inferno') @@ -20,7 +20,7 @@ class BinRange: self.n = n def central_index(self): - return int((0.-self.vmin)/(self.vmax-self.vmin)*self.n) + return int((0. - self.vmin) / (self.vmax - self.vmin) * self.n) class Detector: @@ -51,16 +51,16 @@ def make_plot(results, det, name, nrow=1): """ mpl.rcParams['image.interpolation'] = 'none' n = len(results) - ncol = 1+(n-1)//nrow + ncol = 1 + (n - 1) // nrow # Parameters as fraction of subfig size. yskip = 0.2 # +ncol*0.02 bottomskip = yskip - topskip = yskip/2 + topskip = yskip / 2 xskip = 0.18 leftskip = xskip - rightskip = 0.28+ncol*0.03 - xtot = ncol*1.0 + (ncol-1)*xskip + leftskip + rightskip - ytot = nrow*1.0 + (nrow-1)*yskip + bottomskip + topskip + rightskip = 0.28 + ncol * 0.03 + xtot = ncol * 1.0 + (ncol - 1) * xskip + leftskip + rightskip + ytot = nrow * 1.0 + (nrow - 1) * yskip + bottomskip + topskip # We need parameters as fraction of total fig size. xskip /= xtot leftskip /= xtot @@ -70,9 +70,9 @@ def make_plot(results, det, name, nrow=1): topskip /= ytot # Set total figure dimensions. ftot = 5 - fontsize = 18+36.0/(ncol+2) + fontsize = 18 + 36.0 / (ncol + 2) # Create the figure 'fig' and its subplots axes ('tmp'->'axes'). - fig, tmp = plt.subplots(nrow, ncol, figsize=(ftot*xtot, ftot*ytot)) + fig, tmp = plt.subplots(nrow, ncol, figsize=(ftot * xtot, ftot * ytot)) if n > 1: axes = tmp.flat else: @@ -82,33 +82,35 @@ def make_plot(results, det, name, nrow=1): # Plot the subfigures. for res in results: ax = axes[res.idx] - im = ax.imshow(res.data, - norm=norm, - extent=det.rectangle(), - aspect=1) + im = ax.imshow(res.data, norm=norm, extent=det.rectangle(), aspect=1) ax.set_xlabel(r'$\phi_{\rm f} (^{\circ})$', fontsize=fontsize) if res.idx % ncol == 0: ax.set_ylabel(r'$\alpha_{\rm f} (^{\circ})$', fontsize=fontsize) if res.title != "": ax.set_title(res.title, fontsize=fontsize) - ax.tick_params(axis='both', which='major', labelsize=fontsize*21/24) + ax.tick_params(axis='both', which='major', labelsize=fontsize * 21 / 24) # Adjust whitespace around and between subfigures. - plt.subplots_adjust(wspace=xskip, hspace=yskip, - left=leftskip, right=1-rightskip, - bottom=bottomskip, top=1-topskip) + plt.subplots_adjust(wspace=xskip, + hspace=yskip, + left=leftskip, + right=1 - rightskip, + bottom=bottomskip, + top=1 - topskip) # Plot the color scale. - cbar_ax = fig.add_axes([1-rightskip+0.4*xskip, bottomskip, - 0.25*xskip, 1-bottomskip-topskip]) + cbar_ax = fig.add_axes([ + 1 - rightskip + 0.4 * xskip, bottomskip, 0.25 * xskip, + 1 - bottomskip - topskip + ]) cb = fig.colorbar(im, cax=cbar_ax) cb.set_label(r'$\left|F(q)\right|^2/V^{\,2}$', fontsize=fontsize) # Output to data file, image file, and display. - nDigits = int(math.log10(len(results)))+1 + nDigits = int(math.log10(len(results))) + 1 formatN = "%" + str(nDigits) + "i" for i in range(len(results)): - fname = name+"."+(formatN % i)+".int" + fname = name + "." + (formatN % i) + ".int" print(fname) numpy.savetxt(fname, results[i].data) - plt.savefig(name+".pdf", format="pdf", bbox_inches='tight') + plt.savefig(name + ".pdf", format="pdf", bbox_inches='tight') # plt.show() @@ -146,10 +148,11 @@ def get_simulation(det): :param det: Detector limits """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters( - det.phi.n, det.phi.vmin*degree, det.phi.vmax*degree, - det.alpha.n, det.alpha.vmin*degree, det.alpha.vmax*degree ) - simulation.setBeamParameters(1.0*angstrom, 0, 0) + simulation.setDetectorParameters(det.phi.n, det.phi.vmin * degree, + det.phi.vmax * degree, det.alpha.n, + det.alpha.vmin * degree, + det.alpha.vmax * degree) + simulation.setBeamParameters(1.0 * angstrom, 0, 0) return simulation diff --git a/Doc/FFCatalog/fig/ff2/sim_AnisoPyramid.py b/Doc/FFCatalog/fig/ff2/sim_AnisoPyramid.py index 6f2619451017a32cf009c55c22691244e9e78bcf..b7865ffdf71a7609db8dce75fe349f44c594c83c 100644 --- a/Doc/FFCatalog/fig/ff2/sim_AnisoPyramid.py +++ b/Doc/FFCatalog/fig/ff2/sim_AnisoPyramid.py @@ -2,18 +2,19 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=90*i/(n-1) + omega = 90 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorAnisoPyramid(13*nanometer, 8*nanometer, 4.2*nanometer, 60.0*degree) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_AnisoPyramid" ) + ff = ba.FormFactorAnisoPyramid(13 * nanometer, 8 * nanometer, 4.2 * nanometer, + 60.0 * degree) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_AnisoPyramid") diff --git a/Doc/FFCatalog/fig/ff2/sim_Box.py b/Doc/FFCatalog/fig/ff2/sim_Box.py index 4390624dc1e42b280094f21081d099f4a417c34a..96e3b61d31d2705518ebd421ddcd515ade5ed997 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Box.py +++ b/Doc/FFCatalog/fig/ff2/sim_Box.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp det = bp.Detector(200, 0, 5, 0, 5) n = 4 results = [] for i in range(n): - omega = 90*i/(n-1) + omega = 90 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorBox(18*nanometer, 4.6*nanometer, 3*nanometer) - trafo = ba.RotationZ(omega*degree) + ff = ba.FormFactorBox(18 * nanometer, 4.6 * nanometer, 3 * nanometer) + trafo = ba.RotationZ(omega * degree) data = bp.run_simulation(det, ff, trafo) results.append(bp.Result(i, data, title)) - + bp.make_plot(results, det, "ff_Box") diff --git a/Doc/FFCatalog/fig/ff2/sim_CantellatedCube.py b/Doc/FFCatalog/fig/ff2/sim_CantellatedCube.py index e50cf83ff4d2683f90fd85580c25b2d7d751c4d7..8dbd6cad41751f01b094e2b9e3e853ca3df0a867 100644 --- a/Doc/FFCatalog/fig/ff2/sim_CantellatedCube.py +++ b/Doc/FFCatalog/fig/ff2/sim_CantellatedCube.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=45*i/(n-1) + omega = 45 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorTruncatedCube(6.4*nanometer, 1.5*nanometer) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_TruncatedCube" ) + ff = ba.FormFactorTruncatedCube(6.4 * nanometer, 1.5 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_TruncatedCube") diff --git a/Doc/FFCatalog/fig/ff2/sim_Cone.py b/Doc/FFCatalog/fig/ff2/sim_Cone.py index 1ba5f1c7f6a38ffe6069ece8020c416e8c364b64..7c3c343ad52023143cdca0819f413ae49ef5429f 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Cone.py +++ b/Doc/FFCatalog/fig/ff2/sim_Cone.py @@ -2,18 +2,18 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - theta=30*i/(n-1) + theta = 30 * i / (n - 1) title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorCone(4*nanometer, 11*nanometer, 75*degree) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Cone" ) + ff = ba.FormFactorCone(4 * nanometer, 11 * nanometer, 75 * degree) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Cone") diff --git a/Doc/FFCatalog/fig/ff2/sim_Cone6.py b/Doc/FFCatalog/fig/ff2/sim_Cone6.py index d9ef435c72576bedab3eeac41ccf815d729c0908..2dd0071693bbe47a1a4a8a9bbcdf2095c2d32929 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Cone6.py +++ b/Doc/FFCatalog/fig/ff2/sim_Cone6.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=30*i/(n-1) + omega = 30 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorCone6(6*nanometer, 5*nanometer, 60*degree) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Cone6" ) + ff = ba.FormFactorCone6(6 * nanometer, 5 * nanometer, 60 * degree) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Cone6") diff --git a/Doc/FFCatalog/fig/ff2/sim_CosineRipple.py b/Doc/FFCatalog/fig/ff2/sim_CosineRipple.py index 885213f9d095ca09386424c553f71eb52237512f..db0c740db8f01c1fdfbcf0b6f7174196ffe67de4 100644 --- a/Doc/FFCatalog/fig/ff2/sim_CosineRipple.py +++ b/Doc/FFCatalog/fig/ff2/sim_CosineRipple.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=90*i/(n-1) + omega = 90 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorCosineRipple(25*nanometer, 10*nanometer, 8*nanometer ) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_CosineRipple" ) + ff = ba.FormFactorCosineRipple(25 * nanometer, 10 * nanometer, 8 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_CosineRipple") diff --git a/Doc/FFCatalog/fig/ff2/sim_Cuboctahedron.py b/Doc/FFCatalog/fig/ff2/sim_Cuboctahedron.py index 5e75058386573fefbbed501a91c54ffa5e1f0bf6..58956e6c827a69a4186bd8c41adb6d80d8464492 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Cuboctahedron.py +++ b/Doc/FFCatalog/fig/ff2/sim_Cuboctahedron.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=45*i/(n-1) + omega = 45 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorCuboctahedron(8*nanometer, 5*nanometer, 0.5, 60.0*degree) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Cuboctahedron" ) + ff = ba.FormFactorCuboctahedron(8 * nanometer, 5 * nanometer, 0.5, 60.0 * degree) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Cuboctahedron") diff --git a/Doc/FFCatalog/fig/ff2/sim_Cylinder.py b/Doc/FFCatalog/fig/ff2/sim_Cylinder.py index f122da5c01e8e4c3dd7744f2caa3baf9c383e435..3ba3c824766f480d676a654de81b9151b871cab6 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Cylinder.py +++ b/Doc/FFCatalog/fig/ff2/sim_Cylinder.py @@ -2,18 +2,18 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 4 +det = bp.Detector(200, -5, 5, -5, 5) +n = 4 results = [] for i in range(n): - theta=135*i/(n-1) + theta = 135 * i / (n - 1) title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorCylinder(3*nanometer, 8.8*nanometer) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) + ff = ba.FormFactorCylinder(3 * nanometer, 8.8 * nanometer) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) -bp.make_plot( results, det, "ff_Cylinder" ) +bp.make_plot(results, det, "ff_Cylinder") diff --git a/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_asy.py b/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_asy.py index f5f07dd1afcd67931447e85c2deceafd408dc69c..47fba21ca170ec04044a6712975a29e197460a38 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_asy.py +++ b/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_asy.py @@ -2,30 +2,30 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp import math -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 3 +det = bp.Detector(200, -5, 5, -5, 5) +n = 3 results = [] edge = 3.2 title = 'default' -ff = ba.FormFactorDodecahedron(edge*nanometer) -data = bp.run_simulation(det,ff) -results.append( bp.Result(0, data, title) ) +ff = ba.FormFactorDodecahedron(edge * nanometer) +data = bp.run_simulation(det, ff) +results.append(bp.Result(0, data, title)) title = 'rotated' -trafo = ba.RotationZ(13*degree) -ff = ba.FormFactorDodecahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(1, data, title) ) +trafo = ba.RotationZ(13 * degree) +ff = ba.FormFactorDodecahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(1, data, title)) title = 'rotated, tilted' -trafo = ba.createProduct( ba.RotationX(9*degree), ba.RotationZ(13*degree)) -ff = ba.FormFactorDodecahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(2, data, title) ) +trafo = ba.createProduct(ba.RotationX(9 * degree), ba.RotationZ(13 * degree)) +ff = ba.FormFactorDodecahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(2, data, title)) -bp.make_plot( results, det, "ff_Dodecahedron_asy" ) +bp.make_plot(results, det, "ff_Dodecahedron_asy") diff --git a/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_sym.py b/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_sym.py index 159141f7a2a2fc838e6e574581d140c0242ad2b3..71b0a95565f729ae6a7dff4d1e0420bc12c91724 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_sym.py +++ b/Doc/FFCatalog/fig/ff2/sim_Dodecahedron_sym.py @@ -2,31 +2,31 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp import math -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 3 +det = bp.Detector(200, -5, 5, -5, 5) +n = 3 results = [] edge = 3.2 title = 'face normal' -trafo = ba.RotationY(26.5651*degree) -ff = ba.FormFactorDodecahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(0, data, title) ) +trafo = ba.RotationY(26.5651 * degree) +ff = ba.FormFactorDodecahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(0, data, title)) title = 'vertex normal' -trafo = ba.RotationY(-52.6226*degree) -ff = ba.FormFactorDodecahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(1, data, title) ) +trafo = ba.RotationY(-52.6226 * degree) +ff = ba.FormFactorDodecahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(1, data, title)) title = 'edge normal' -trafo = ba.RotationY(58.2825*degree) -ff = ba.FormFactorDodecahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(2, data, title) ) +trafo = ba.RotationY(58.2825 * degree) +ff = ba.FormFactorDodecahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(2, data, title)) -bp.make_plot( results, det, "ff_Dodecahedron_sym" ) +bp.make_plot(results, det, "ff_Dodecahedron_sym") diff --git a/Doc/FFCatalog/fig/ff2/sim_EllipsoidalCylinder.py b/Doc/FFCatalog/fig/ff2/sim_EllipsoidalCylinder.py index 24864d5d32e4d3b96a426ab91a8b055ebfb1abdf..b55eeccbb944c80d6f02b1e03ba87cefadb31379 100644 --- a/Doc/FFCatalog/fig/ff2/sim_EllipsoidalCylinder.py +++ b/Doc/FFCatalog/fig/ff2/sim_EllipsoidalCylinder.py @@ -2,18 +2,19 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=90*i/(n-1) + omega = 90 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorEllipsoidalCylinder(6.3*nanometer, 4.2*nanometer, 3*nanometer) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_EllipsoidalCylinder" ) + ff = ba.FormFactorEllipsoidalCylinder(6.3 * nanometer, 4.2 * nanometer, + 3 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_EllipsoidalCylinder") diff --git a/Doc/FFCatalog/fig/ff2/sim_FullSphere.py b/Doc/FFCatalog/fig/ff2/sim_FullSphere.py index cbef53a72d9eaf0db63b51061d87ecd4b38225df..33644736202b1e00c67cdd8c2b9fba66d5298833 100644 --- a/Doc/FFCatalog/fig/ff2/sim_FullSphere.py +++ b/Doc/FFCatalog/fig/ff2/sim_FullSphere.py @@ -2,15 +2,15 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 1 +det = bp.Detector(200, 0, 5, 0, 5) +n = 1 results = [] for i in range(n): - ff = ba.FormFactorFullSphere(3.9*nanometer) - data = bp.run_simulation(det,ff) - results.append( bp.Result(i, data) ) - -bp.make_plot( results, det, "ff_FullSphere" ) + ff = ba.FormFactorFullSphere(3.9 * nanometer) + data = bp.run_simulation(det, ff) + results.append(bp.Result(i, data)) + +bp.make_plot(results, det, "ff_FullSphere") diff --git a/Doc/FFCatalog/fig/ff2/sim_FullSpheroid.py b/Doc/FFCatalog/fig/ff2/sim_FullSpheroid.py index e67f9e7c649248036e910099d3078293d28855b7..c4ce6b75da1a11b15683984b1ab3136996dc550c 100644 --- a/Doc/FFCatalog/fig/ff2/sim_FullSpheroid.py +++ b/Doc/FFCatalog/fig/ff2/sim_FullSpheroid.py @@ -2,18 +2,18 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - theta=90*i/(n-1) + theta = 90 * i / (n - 1) title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorFullSpheroid(3*nanometer, 13*nanometer) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) + ff = ba.FormFactorFullSpheroid(3 * nanometer, 13 * nanometer) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) -bp.make_plot( results, det, "ff_FullSpheroid" ) +bp.make_plot(results, det, "ff_FullSpheroid") diff --git a/Doc/FFCatalog/fig/ff2/sim_HemiEllipsoid.py b/Doc/FFCatalog/fig/ff2/sim_HemiEllipsoid.py index 18d03a49b5b35d3a3669675fbb85563e1d13cfeb..a51ba9cfeaa38fa018448049a31382b52150cbd3 100644 --- a/Doc/FFCatalog/fig/ff2/sim_HemiEllipsoid.py +++ b/Doc/FFCatalog/fig/ff2/sim_HemiEllipsoid.py @@ -2,18 +2,18 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=90*i/(n-1) + omega = 90 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorHemiEllipsoid(10*nanometer, 3.8*nanometer, 3.2*nanometer) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_HemiEllipsoid" ) + ff = ba.FormFactorHemiEllipsoid(10 * nanometer, 3.8 * nanometer, 3.2 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_HemiEllipsoid") diff --git a/Doc/FFCatalog/fig/ff2/sim_Icosahedron_asy.py b/Doc/FFCatalog/fig/ff2/sim_Icosahedron_asy.py index fb68b7009058f9d66231b3cb89a1018a36d38ad9..38a72e6556ce0d09a1ff4bf52e5ce5d596b15fef 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Icosahedron_asy.py +++ b/Doc/FFCatalog/fig/ff2/sim_Icosahedron_asy.py @@ -2,30 +2,30 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp import math -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 3 +det = bp.Detector(200, -5, 5, -5, 5) +n = 3 results = [] edge = 4.8 title = 'default' -ff = ba.FormFactorIcosahedron(edge*nanometer) -data = bp.run_simulation(det,ff) -results.append( bp.Result(0, data, title) ) +ff = ba.FormFactorIcosahedron(edge * nanometer) +data = bp.run_simulation(det, ff) +results.append(bp.Result(0, data, title)) title = 'rotated' -trafo = ba.RotationZ(13*degree) -ff = ba.FormFactorIcosahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(1, data, title) ) +trafo = ba.RotationZ(13 * degree) +ff = ba.FormFactorIcosahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(1, data, title)) title = 'rotated, tilted' -trafo = ba.createProduct( ba.RotationX(9*degree), ba.RotationZ(13*degree)) -ff = ba.FormFactorIcosahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(2, data, title) ) +trafo = ba.createProduct(ba.RotationX(9 * degree), ba.RotationZ(13 * degree)) +ff = ba.FormFactorIcosahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(2, data, title)) -bp.make_plot( results, det, "ff_Icosahedron_asy" ) +bp.make_plot(results, det, "ff_Icosahedron_asy") diff --git a/Doc/FFCatalog/fig/ff2/sim_Icosahedron_sym.py b/Doc/FFCatalog/fig/ff2/sim_Icosahedron_sym.py index b8c908404c7edafaf9b6cd9a567ea5b4445142bb..035b8dba17b379365711bfbf5172f811e20a4dad 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Icosahedron_sym.py +++ b/Doc/FFCatalog/fig/ff2/sim_Icosahedron_sym.py @@ -2,31 +2,31 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp import math -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 3 +det = bp.Detector(200, -5, 5, -5, 5) +n = 3 results = [] edge = 4.8 title = 'face normal' -trafo = ba.RotationY(48.1897*degree) -ff = ba.FormFactorIcosahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(0, data, title) ) +trafo = ba.RotationY(48.1897 * degree) +ff = ba.FormFactorIcosahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(0, data, title)) title = 'vertex normal' -trafo = ba.RotationY(-52.6226*degree) -ff = ba.FormFactorIcosahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(1, data, title) ) +trafo = ba.RotationY(-52.6226 * degree) +ff = ba.FormFactorIcosahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(1, data, title)) title = 'edge normal' -trafo = ba.RotationY(69.0948*degree) -ff = ba.FormFactorIcosahedron(edge*nanometer) -data = bp.run_simulation(det,ff,trafo) -results.append( bp.Result(2, data, title) ) +trafo = ba.RotationY(69.0948 * degree) +ff = ba.FormFactorIcosahedron(edge * nanometer) +data = bp.run_simulation(det, ff, trafo) +results.append(bp.Result(2, data, title)) -bp.make_plot( results, det, "ff_Icosahedron_sym" ) +bp.make_plot(results, det, "ff_Icosahedron_sym") diff --git a/Doc/FFCatalog/fig/ff2/sim_Prism3.py b/Doc/FFCatalog/fig/ff2/sim_Prism3.py index e55217d8cc003985db281ab78bf7af65d706ec0a..3096f0c35dbe4c5c438ed04550eddb10722b49af 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Prism3.py +++ b/Doc/FFCatalog/fig/ff2/sim_Prism3.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=30*i/(n-1) + omega = 30 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorPrism3(13.8*nanometer, 3*nanometer) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Prism3" ) + ff = ba.FormFactorPrism3(13.8 * nanometer, 3 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Prism3") diff --git a/Doc/FFCatalog/fig/ff2/sim_Prism6.py b/Doc/FFCatalog/fig/ff2/sim_Prism6.py index 02997b725b9b4cabfaf074ec277d924fa803a63a..c63e4e5a5733a729c64f09b7b2c1cfa0da6b925c 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Prism6.py +++ b/Doc/FFCatalog/fig/ff2/sim_Prism6.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=30*i/(n-1) + omega = 30 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorPrism6(5.7*nanometer, 3*nanometer) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Prism6" ) + ff = ba.FormFactorPrism6(5.7 * nanometer, 3 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Prism6") diff --git a/Doc/FFCatalog/fig/ff2/sim_Pyramid.py b/Doc/FFCatalog/fig/ff2/sim_Pyramid.py index 79b0a128373e367b05138f1ba710caac37356969..99580c57f4b727c576b638aa5ae358fe7a0309a4 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Pyramid.py +++ b/Doc/FFCatalog/fig/ff2/sim_Pyramid.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=45*i/(n-1) + omega = 45 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorPyramid(10*nanometer, 4.2*nanometer, 60.0*degree) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Pyramid" ) + ff = ba.FormFactorPyramid(10 * nanometer, 4.2 * nanometer, 60.0 * degree) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Pyramid") diff --git a/Doc/FFCatalog/fig/ff2/sim_SawtoothRipple.py b/Doc/FFCatalog/fig/ff2/sim_SawtoothRipple.py index c255993694b34b30488afef40c609622275ba043..f682952aa82e0274a34358ed997621aacd4bac3e 100644 --- a/Doc/FFCatalog/fig/ff2/sim_SawtoothRipple.py +++ b/Doc/FFCatalog/fig/ff2/sim_SawtoothRipple.py @@ -2,18 +2,19 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 4 +det = bp.Detector(200, -5, 5, -5, 5) +n = 4 results = [] for i in range(n): - omega=90*i/(n-1) + omega = 90 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorSawtoothRippleBox(25*nanometer, 10*nanometer, 8*nanometer, 5*nanometer ) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) + ff = ba.FormFactorSawtoothRippleBox(25 * nanometer, 10 * nanometer, + 8 * nanometer, 5 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) -bp.make_plot( results, det, "ff_SawtoothRipple" ) +bp.make_plot(results, det, "ff_SawtoothRipple") diff --git a/Doc/FFCatalog/fig/ff2/sim_Tetrahedron.py b/Doc/FFCatalog/fig/ff2/sim_Tetrahedron.py index 197819ca024bc3019dd42b8603a0d3986e498cac..593c2bf47414b0933280e4fb03dcb2e8213f75a1 100644 --- a/Doc/FFCatalog/fig/ff2/sim_Tetrahedron.py +++ b/Doc/FFCatalog/fig/ff2/sim_Tetrahedron.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, -5, 5, -5, 5 ) -n = 4 +det = bp.Detector(200, -5, 5, -5, 5) +n = 4 results = [] for i in range(n): - omega=60*i/(n-1) + omega = 60 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorTetrahedron(12*nanometer, 8*nanometer, 75*degree) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_Tetrahedron" ) + ff = ba.FormFactorTetrahedron(12 * nanometer, 8 * nanometer, 75 * degree) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_Tetrahedron") diff --git a/Doc/FFCatalog/fig/ff2/sim_TruncatedCube.py b/Doc/FFCatalog/fig/ff2/sim_TruncatedCube.py index e50cf83ff4d2683f90fd85580c25b2d7d751c4d7..8dbd6cad41751f01b094e2b9e3e853ca3df0a867 100644 --- a/Doc/FFCatalog/fig/ff2/sim_TruncatedCube.py +++ b/Doc/FFCatalog/fig/ff2/sim_TruncatedCube.py @@ -2,18 +2,18 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - omega=45*i/(n-1) + omega = 45 * i / (n - 1) title = r'$\omega=%d^\circ$' % omega - ff = ba.FormFactorTruncatedCube(6.4*nanometer, 1.5*nanometer) - trafo = ba.RotationZ(omega*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_TruncatedCube" ) + ff = ba.FormFactorTruncatedCube(6.4 * nanometer, 1.5 * nanometer) + trafo = ba.RotationZ(omega * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_TruncatedCube") diff --git a/Doc/FFCatalog/fig/ff2/sim_TruncatedSphere.py b/Doc/FFCatalog/fig/ff2/sim_TruncatedSphere.py index d71e08a99a02af21f304e3f4702220889d305b20..17a4c33469cdd41362ad2c92a0bc4be6ec7d9473 100644 --- a/Doc/FFCatalog/fig/ff2/sim_TruncatedSphere.py +++ b/Doc/FFCatalog/fig/ff2/sim_TruncatedSphere.py @@ -2,18 +2,18 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - theta=30*i/(n-1) + theta = 30 * i / (n - 1) title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorTruncatedSphere(4.2*nanometer, 6.1*nanometer, 0) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_TruncatedSphere" ) + ff = ba.FormFactorTruncatedSphere(4.2 * nanometer, 6.1 * nanometer, 0) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_TruncatedSphere") diff --git a/Doc/FFCatalog/fig/ff2/sim_TruncatedSpheroid.py b/Doc/FFCatalog/fig/ff2/sim_TruncatedSpheroid.py index d5bcc1ad053ddcdf424c964846295329f1969424..5d872ac4f55543294d37b09d7b82091ed87654de 100644 --- a/Doc/FFCatalog/fig/ff2/sim_TruncatedSpheroid.py +++ b/Doc/FFCatalog/fig/ff2/sim_TruncatedSpheroid.py @@ -2,18 +2,18 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -n = 4 +det = bp.Detector(200, 0, 5, 0, 5) +n = 4 results = [] for i in range(n): - theta=30*i/(n-1) + theta = 30 * i / (n - 1) title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorTruncatedSpheroid(3.3*nanometer, 9.6*nanometer, 1.8, 0) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_TruncatedSpheroid" ) + ff = ba.FormFactorTruncatedSpheroid(3.3 * nanometer, 9.6 * nanometer, 1.8, 0) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_TruncatedSpheroid") diff --git a/Doc/FFCatalog/fig/ff2/sim_demo_1quadrants.py b/Doc/FFCatalog/fig/ff2/sim_demo_1quadrants.py index f441c201010fb255e66244595fe1a47c61afa72a..61cafe14d66089a57c123c2ef2d589f00b379ad7 100644 --- a/Doc/FFCatalog/fig/ff2/sim_demo_1quadrants.py +++ b/Doc/FFCatalog/fig/ff2/sim_demo_1quadrants.py @@ -2,19 +2,19 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, 0, 5, 0, 5 ) -pars = [0,5,10,20] +det = bp.Detector(200, 0, 5, 0, 5) +pars = [0, 5, 10, 20] n = len(pars) results = [] for i in range(n): - theta=pars[i] + theta = pars[i] title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorTruncatedSphere(4.2*nanometer, 6.1*nanometer, 0) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_demo_1quadrants" ) + ff = ba.FormFactorTruncatedSphere(4.2 * nanometer, 6.1 * nanometer, 0) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_demo_1quadrants") diff --git a/Doc/FFCatalog/fig/ff2/sim_demo_4quadrants.py b/Doc/FFCatalog/fig/ff2/sim_demo_4quadrants.py index 9214797e1be0cd7576cdff07b25dbf163db1c8d0..6663250d29c79fd9abecd85c32e3e5f95af3d9bc 100644 --- a/Doc/FFCatalog/fig/ff2/sim_demo_4quadrants.py +++ b/Doc/FFCatalog/fig/ff2/sim_demo_4quadrants.py @@ -2,19 +2,19 @@ Plot form factor. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp -det = bp.Detector( 200, -5, 5, -5, 5 ) -pars = [0,5,10,20] +det = bp.Detector(200, -5, 5, -5, 5) +pars = [0, 5, 10, 20] n = len(pars) results = [] for i in range(n): - theta=pars[i] + theta = pars[i] title = r'$\vartheta=%d^\circ$' % theta - ff = ba.FormFactorTruncatedSphere(4.2*nanometer, 6.1*nanometer, 0) - trafo = ba.RotationY(theta*degree) - data = bp.run_simulation(det,ff,trafo) - results.append( bp.Result(i, data, title) ) - -bp.make_plot( results, det, "ff_demo_4quadrants" ) + ff = ba.FormFactorTruncatedSphere(4.2 * nanometer, 6.1 * nanometer, 0) + trafo = ba.RotationY(theta * degree) + data = bp.run_simulation(det, ff, trafo) + results.append(bp.Result(i, data, title)) + +bp.make_plot(results, det, "ff_demo_4quadrants") diff --git a/Doc/FFCatalog/fig/ff2/sim_det_box.py b/Doc/FFCatalog/fig/ff2/sim_det_box.py index c32ba4232160e336d0de88748844b96cfe6024c8..69698aa9605187020d00405d2aef65edcf4a46e5 100644 --- a/Doc/FFCatalog/fig/ff2/sim_det_box.py +++ b/Doc/FFCatalog/fig/ff2/sim_det_box.py @@ -2,14 +2,14 @@ Plot form factors. """ import bornagain as ba -from bornagain import nanometer, degree +from bornagain import nanometer, degree import bornplot as bp det = bp.Detector(1000, 0, 5, 0, 5) n = 3 results = [] for i in range(n): - siz = [10,100,1000][i] + siz = [10, 100, 1000][i] title = r'$L_x = %d~nm$' % siz ff = ba.FormFactorBox(siz, 10, 10) data = bp.run_simulation(det, ff) diff --git a/Doc/PhysicsManual/fig/drawing/Green.py b/Doc/PhysicsManual/fig/drawing/Green.py index 0026ebed5c9a5c979476bd6c4d24968b736b67df..b3d5887da82c77869e445b8fb02df2f14a119176 100755 --- a/Doc/PhysicsManual/fig/drawing/Green.py +++ b/Doc/PhysicsManual/fig/drawing/Green.py @@ -1,44 +1,46 @@ #!/usr/bin/env python3 - ''' Compute radiation trajectories through multilayer sample for use in figure that explains the Green function. ''' xd = 52 -yd = 10 # detector -s = 3 # source located at -s -T = [ 6, 6 ] # layer thickness -sd = T[0]-s # distance from source to lower interface -DeltaLayer = [ .05, .1 ] # refractive index parameter delta, per layer -x0 = 4 -xtot = xd - x0 # determine angles so that sum dx matches this +yd = 10 # detector +s = 3 # source located at -s +T = [6, 6] # layer thickness +sd = T[0] - s # distance from source to lower interface +DeltaLayer = [.05, .1] # refractive index parameter delta, per layer +x0 = 4 +xtot = xd - x0 # determine angles so that sum dx matches this PP = [ - [ s, yd ], - [ -sd, T[0], yd ], - [ s, -T[0], T[0], yd ], - [ -sd, T[0], -T[0], T[0], yd ], - [ -sd, -T[1], T[1], T[0], yd ], - [ -sd, -T[1], T[1], -T[1], T[1], T[0], yd ], - [ -sd, -T[1], T[1], T[0], -T[0], T[0], yd ], + [s, yd], + [-sd, T[0], yd], + [s, -T[0], T[0], yd], + [-sd, T[0], -T[0], T[0], yd], + [-sd, -T[1], T[1], T[0], yd], + [-sd, -T[1], T[1], -T[1], T[1], T[0], yd], + [-sd, -T[1], T[1], T[0], -T[0], T[0], yd], ] import math, re, scipy.optimize, sys -def inside( y, mi, ma ): - return mi<=y and y<=ma -def xsum( a0, P, D ): +def inside(y, mi, ma): + return mi <= y and y <= ma + + +def xsum(a0, P, D): n = len(P) if len(D) != n: - sys.stderr.write( "Bug: inconsistent array lengths\n" ) + sys.stderr.write("Bug: inconsistent array lengths\n") exit(1) ret = 0 for i in range(n): - a = math.acos( min( .99, math.cos(a0) / (1-D[i]) ) ) - ret += abs(P[i])/math.tan(a) - return ret-xtot + a = math.acos(min(.99, math.cos(a0) / (1 - D[i]))) + ret += abs(P[i]) / math.tan(a) + return ret - xtot + cmd0 = "" cmd0 += "/xd %6.3g def\n" % xd @@ -53,55 +55,56 @@ for P in PP: for dy in P: yold = y y += dy - if yold>=0 and y>=0: - DeltaPath.append( 0 ) - elif inside(y,-T[0],0) and inside(yold,-T[0],0) : - DeltaPath.append( DeltaLayer[0] ) - elif inside(y,-T[0]-T[1],-T[0]) and inside(yold,-T[0]-T[1],-T[0]) : - DeltaPath.append( DeltaLayer[1] ) + if yold >= 0 and y >= 0: + DeltaPath.append(0) + elif inside(y, -T[0], 0) and inside(yold, -T[0], 0): + DeltaPath.append(DeltaLayer[0]) + elif inside(y, -T[0] - T[1], -T[0]) and inside(yold, -T[0] - T[1], -T[0]): + DeltaPath.append(DeltaLayer[1]) else: - sys.stderr.write( "Invalid input => layer ill defined\n" ) - if y!=yd: - sys.stderr.write( "Invalid input => detector not hit\n" ) + sys.stderr.write("Invalid input => layer ill defined\n") + if y != yd: + sys.stderr.write("Invalid input => detector not hit\n") exit(1) - a0 = scipy.optimize.newton( xsum, .5, args = ( P, DeltaPath ) ) - print( a0 ) + a0 = scipy.optimize.newton(xsum, .5, args=(P, DeltaPath)) + print(a0) y = -s - x1 = x0 - x2 = x0 - wgt = 5 - len(P)/2 + x1 = x0 + x2 = x0 + wgt = 5 - len(P) / 2 cmd1 += "%1i [] lset\n" % (wgt) cmd2 += "%1i [] lset\n" % (wgt) - cmd1 += "%6.3g %6.3g np mv\n" % ( x1, y ) - cmd2 += "%6.3g %6.3g np mv\n" % ( x2, y ) - for i in range(len(P)-1): - a = math.acos( math.cos(a0) / (1-DeltaPath[i]) ) - x1 += abs(P[i])/math.tan(a) - b = math.acos( math.cos(b0) / (1-DeltaPath[i]) ) - x2 += abs(P[i])/math.tan(b) + cmd1 += "%6.3g %6.3g np mv\n" % (x1, y) + cmd2 += "%6.3g %6.3g np mv\n" % (x2, y) + for i in range(len(P) - 1): + a = math.acos(math.cos(a0) / (1 - DeltaPath[i])) + x1 += abs(P[i]) / math.tan(a) + b = math.acos(math.cos(b0) / (1 - DeltaPath[i])) + x2 += abs(P[i]) / math.tan(b) y += P[i] - cmd1 += "%6.3g %6.3g li\n" % ( x1, y ) - cmd2 += "%6.3g %6.3g li\n" % ( x2, y ) + cmd1 += "%6.3g %6.3g li\n" % (x1, y) + cmd2 += "%6.3g %6.3g li\n" % (x2, y) cmd1 += "st\n" cmd2 += "st\n" - len1 = math.sqrt( (xtot+x0-x1)**2 + yd**2 ) - 8 - cmd1 += "%6.3g %6.3g %7.3g .8 %6.3g pfeiL\n" % ( x1, y, 180*a0/math.pi, len1 ) - cmd2 += "%6.3g %6.3g %7.3g .8 %6.3g pfeiL\n" % ( x2, y, 180*b0/math.pi, 7 ) + len1 = math.sqrt((xtot + x0 - x1)**2 + yd**2) - 8 + cmd1 += "%6.3g %6.3g %7.3g .8 %6.3g pfeiL\n" % (x1, y, 180 * a0 / math.pi, len1) + cmd2 += "%6.3g %6.3g %7.3g .8 %6.3g pfeiL\n" % (x2, y, 180 * b0 / math.pi, 7) cmd1 += "\n" cmd2 += "\n" #/pfeiL { % (arrow anchored at base) x y rot siz len -t = "% This file is automatically generated by script " + sys.argv[0] + "\n% DO NOT EDIT!\n\n" -fd = open( "Green1.ps.in", 'r' ) +t = "% This file is automatically generated by script " + sys.argv[ + 0] + "\n% DO NOT EDIT!\n\n" +fd = open("Green1.ps.in", 'r') t += fd.read() fd.close -cmd0 += "/b0 %7.3g def\n" % (180*b0/math.pi) -t = re.sub( r'%#0', cmd0, t ) -t = re.sub( r'%#1', cmd1, t ) -t = re.sub( r'%#2', cmd2, t ) +cmd0 += "/b0 %7.3g def\n" % (180 * b0 / math.pi) +t = re.sub(r'%#0', cmd0, t) +t = re.sub(r'%#1', cmd1, t) +t = re.sub(r'%#2', cmd2, t) -fd = open( "Green1.ps", 'w' ) -fd.write( t ) +fd = open("Green1.ps", 'w') +fd.write(t) fd.close diff --git a/Examples/Demos/FitCylindersPrisms_movie.py b/Examples/Demos/FitCylindersPrisms_movie.py index acd255944a14c87d47c1da59b92ebf5fff7945c7..c438217f09435c6fd3380589d5facacbecc22b29 100644 --- a/Examples/Demos/FitCylindersPrisms_movie.py +++ b/Examples/Demos/FitCylindersPrisms_movie.py @@ -21,7 +21,6 @@ minimization engine, with starting values cylinder_height = prism3_height = 4nm, cylinder_radius = prism3_length/2 = 6nm as initial fit parameter values. """ - import numpy import matplotlib import matplotlib.pyplot as plt @@ -35,10 +34,10 @@ fig = plt.figure(1) max_line_length = 30 -def get_sample(cylinder_height=1.0*nanometer, - cylinder_radius=1.0*nanometer, - prism_length=2.0*nanometer, - prism_height=1.0*nanometer): +def get_sample(cylinder_height=1.0 * nanometer, + cylinder_radius=1.0 * nanometer, + prism_length=2.0 * nanometer, + prism_height=1.0 * nanometer): """ Build the sample representing cylinders and pyramids on top of substrate without interference. @@ -75,7 +74,8 @@ def create_real_data(): This function has been used once to generate refdata_fitcylinderprisms.int """ # creating sample with set of parameters we will later try to find during the fit - sample = get_sample(5.0*nanometer, 5.0*nanometer, 5.0*nanometer, 5.0*nanometer) + sample = get_sample(5.0 * nanometer, 5.0 * nanometer, 5.0 * nanometer, + 5.0 * nanometer) simulation = get_simulation() simulation.setSample(sample) simulation.runSimulation() @@ -85,7 +85,7 @@ def create_real_data(): # random seed made as in FitSPheresInHexLattice_builder.py example np.random.seed(0) noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 IntensityDataIOFactory.writeIntensityData(ba.Histogram2D(noisy), 'refdata_fitcylinderprisms.int') @@ -96,8 +96,9 @@ def get_simulation(): Create GISAXS simulation with beam and detector defined """ simulation = GISASSimulation() - simulation.setDetectorParameters(100, -1.0*degree, 1.0*degree, 100, 0.0*degree, 2.0*degree) - simulation.setBeamParameters(1.0*angstrom, 0.2*degree, 0.0*degree) + simulation.setDetectorParameters(100, -1.0 * degree, 1.0 * degree, 100, + 0.0 * degree, 2.0 * degree) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) return simulation @@ -119,12 +120,16 @@ class DrawObserver(IFitObserver): real_data = fit_suite.getFitObjects().getRealData().getArray() simulated_data = fit_suite.getFitObjects().getSimulationData().getArray() plt.subplot(2, 2, 1) - im = plt.imshow(real_data + 1, norm=matplotlib.colors.LogNorm(),extent=[-1.0, 1.0, 0, 2.0]) + im = plt.imshow(real_data + 1, + norm=matplotlib.colors.LogNorm(), + extent=[-1.0, 1.0, 0, 2.0]) plt.colorbar(im) plt.title('\"Real\" data') # plotting real data plt.subplot(2, 2, 2) - im = plt.imshow(simulated_data + 1, norm=matplotlib.colors.LogNorm(),extent=[-1.0, 1.0, 0, 2.0]) + im = plt.imshow(simulated_data + 1, + norm=matplotlib.colors.LogNorm(), + extent=[-1.0, 1.0, 0, 2.0]) plt.colorbar(im) plt.title('Simulated data') # plotting parameter space @@ -185,7 +190,8 @@ def run_fitting(): simulation = get_simulation() simulation.setSample(sample) - real_data = IntensityDataIOFactory.readIntensityData('refdata_fitcylinderprisms.int.gz') + real_data = IntensityDataIOFactory.readIntensityData( + 'refdata_fitcylinderprisms.int.gz') fit_suite = FitSuite() fit_suite.addSimulationAndRealData(simulation, real_data) @@ -195,10 +201,14 @@ def run_fitting(): fit_suite.attachObserver(draw_observer) # setting fitting parameters with starting values - fit_suite.addFitParameter("*Cylinder/Height", 2.*nanometer, Limits.limited(0.01, 10.0)) - fit_suite.addFitParameter("*Cylinder/Radius", 2.*nanometer, Limits.limited(0.01, 10.0)) - fit_suite.addFitParameter("*Prism3/Height", 2.*nanometer, Limits.limited(0.01, 10.0)) - fit_suite.addFitParameter("*Prism3/Length", 2.*nanometer, Limits.limited(0.01, 10.0)) + fit_suite.addFitParameter("*Cylinder/Height", 2. * nanometer, + Limits.limited(0.01, 10.0)) + fit_suite.addFitParameter("*Cylinder/Radius", 2. * nanometer, + Limits.limited(0.01, 10.0)) + fit_suite.addFitParameter("*Prism3/Height", 2. * nanometer, + Limits.limited(0.01, 10.0)) + fit_suite.addFitParameter("*Prism3/Length", 2. * nanometer, + Limits.limited(0.01, 10.0)) # # Now we create first fig strategy which will run first minimization round using Genetic minimizer. # # Genetic minimizer is able to explore large parameter space without being trapped by some local minima. @@ -220,7 +230,9 @@ def run_fitting(): fitpars = fit_suite.getFitParameters() for i in range(0, fitpars.size()): print fitpars[i].getName(), fitpars[i].getValue(), fitpars[i].getError() - os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o fit_movie.mpg") + os.system( + "mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o fit_movie.mpg" + ) print 'Removing temporary files' os.system("rm _tmp*") diff --git a/Examples/Demos/simul_demo_cyl_SSCA.py b/Examples/Demos/simul_demo_cyl_SSCA.py index e469a40df3d7a1ca65df3be7abd8453930cfc2ac..f35435d2708797987ff8baff4412947f912dcfa1 100644 --- a/Examples/Demos/simul_demo_cyl_SSCA.py +++ b/Examples/Demos/simul_demo_cyl_SSCA.py @@ -7,6 +7,7 @@ import matplotlib import math from bornagain import * + # ---------------------------------- # describe sample and run simulation # ---------------------------------- @@ -14,7 +15,7 @@ def RunSimulation(): # defining materials mVacuum = HomogeneousMaterial("Vacuum", 0.0, 0.0) mSubstrate = HomogeneousMaterial("Substrate", 6e-6, 2e-8) - mParticle =HomogeneousMaterial("Particle", 6e-4, 2e-8) + mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8) mLayer = HomogeneousMaterial("Layer", 2e-5, 2e-8) # collection of particles @@ -46,7 +47,8 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, 0.0 * degree, 8.0 * degree) + simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, + 0.0 * degree, 8.0 * degree) simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setSample(multi_layer) simulation.runSimulation() @@ -58,9 +60,10 @@ def RunSimulation(): # main() #------------------------------------------------------------- if __name__ == '__main__': - result = RunSimulation() + 1 # for log scale - im = plt.imshow(result, norm=matplotlib.colors.LogNorm(), - extent=[-4.0, 4.0, 0, 8.0]) + result = RunSimulation() + 1 # for log scale + im = plt.imshow(result, + norm=matplotlib.colors.LogNorm(), + extent=[-4.0, 4.0, 0, 8.0]) plt.colorbar(im) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) diff --git a/Examples/Demos/simul_demo_cylsphere.py b/Examples/Demos/simul_demo_cylsphere.py index 1b7f60f258aa464c60d38ec027dae0aa15e1ee6c..ad458a483b32e70523e266f01a2a50ab00296bd4 100644 --- a/Examples/Demos/simul_demo_cylsphere.py +++ b/Examples/Demos/simul_demo_cylsphere.py @@ -7,6 +7,7 @@ import matplotlib import math from bornagain import * + # ---------------------------------- # describe sample and run simulation # ---------------------------------- @@ -39,7 +40,8 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, 0.0 * degree, 8.0 * degree) + simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, + 0.0 * degree, 8.0 * degree) simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setSample(multi_layer) simulation.runSimulation() @@ -51,10 +53,10 @@ def RunSimulation(): # main() #------------------------------------------------------------- if __name__ == '__main__': - result = RunSimulation() + 1 # for log scale + result = RunSimulation() + 1 # for log scale im = plt.imshow(result, - norm=matplotlib.colors.LogNorm(), - extent=[-4.0, 4.0, 0, 8.0]) + norm=matplotlib.colors.LogNorm(), + extent=[-4.0, 4.0, 0, 8.0]) plt.colorbar(im) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) diff --git a/Examples/Demos/simul_demo_lattice1.py b/Examples/Demos/simul_demo_lattice1.py index 2fc3a58d21ab56a8cd94674105bb837d010806f5..e44f4337356ecd23a43df86f6bff950b9e48c5fb 100644 --- a/Examples/Demos/simul_demo_lattice1.py +++ b/Examples/Demos/simul_demo_lattice1.py @@ -9,17 +9,18 @@ from bornagain import * M_PI = numpy.pi + # ---------------------------------- # describe sample and run simulation # ---------------------------------- def RunSimulation(): # defining materials - mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0 ) - mSubstrate = HomogeneousMaterial("Substrate", 6e-6, 2e-8 ) - mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8 ) + mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0) + mSubstrate = HomogeneousMaterial("Substrate", 6e-6, 2e-8) + mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8) # particle - cylinder_ff = FormFactorCylinder(5*nanometer, 5*nanometer) + cylinder_ff = FormFactorCylinder(5 * nanometer, 5 * nanometer) cylinder = Particle(mParticle, cylinder_ff.clone()) position = kvector_t(0.0, 0.0, 0.0) cylinder.setPosition(position) @@ -27,8 +28,10 @@ def RunSimulation(): particle_layout.addParticle(cylinder, 1.0) # interference function - interference = InterferenceFunction2DLattice(ba.SquareLattice2D(10.0*nanometer)) - pdf = FTDecayFunction2DCauchy(300.0*nanometer/2.0/M_PI, 100.0*nanometer/2.0/M_PI, 0) + interference = InterferenceFunction2DLattice(ba.SquareLattice2D(10.0 * + nanometer)) + pdf = FTDecayFunction2DCauchy(300.0 * nanometer / 2.0 / M_PI, + 100.0 * nanometer / 2.0 / M_PI, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -46,8 +49,9 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -2.0*degree, 2.0*degree, 100, 0.0*degree, 4.0*degree) - simulation.setBeamParameters(1.0*angstrom, 0.2*degree, 0.0*degree) + simulation.setDetectorParameters(100, -2.0 * degree, 2.0 * degree, 100, + 0.0 * degree, 4.0 * degree) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) # run simulation simulation.setSample(multi_layer) @@ -60,9 +64,9 @@ def RunSimulation(): #------------------------------------------------------------- if __name__ == '__main__': result = RunSimulation() - im = plt.imshow(result+1, - norm=matplotlib.colors.LogNorm(), - extent=[-2.0, 2.0, 0, 4.0]) + im = plt.imshow(result + 1, + norm=matplotlib.colors.LogNorm(), + extent=[-2.0, 2.0, 0, 4.0]) plt.colorbar(im) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) diff --git a/Examples/Demos/simul_demo_lattice2.py b/Examples/Demos/simul_demo_lattice2.py index b7dc1f7d1042aec7e1e27884135475123ff3ecde..22b369c5b9c214b96b2e8f5c1fa3c018b60cf771 100644 --- a/Examples/Demos/simul_demo_lattice2.py +++ b/Examples/Demos/simul_demo_lattice2.py @@ -9,31 +9,34 @@ from bornagain import * M_PI = numpy.pi + # ---------------------------------- # describe sample and run simulation # ---------------------------------- def RunSimulation(): # defining materials - mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0 ) - mSubstrate = HomogeneousMaterial("Substrate", 6e-6, 2e-8 ) - mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8 ) + mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0) + mSubstrate = HomogeneousMaterial("Substrate", 6e-6, 2e-8) + mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8) # particle 1 - cylinder_ff = FormFactorCylinder(5*nanometer, 5*nanometer) + cylinder_ff = FormFactorCylinder(5 * nanometer, 5 * nanometer) cylinder = Particle(mParticle, cylinder_ff) position = kvector_t(0.0, 0.0, 0.0) cylinder.setPosition(position) particle_layout1 = ParticleLayout() particle_layout1.addParticle(cylinder, 1.0) # particle 2 - position_2 = kvector_t(5.0*nanometer, 5.0*nanometer, 0.0) + position_2 = kvector_t(5.0 * nanometer, 5.0 * nanometer, 0.0) cylinder.setPosition(position_2) particle_layout2 = ParticleLayout() particle_layout2.addParticle(cylinder, 1.0) # interference function - interference = InterferenceFunction2DLattice(ba.SquareLattice2D(10.0*nanometer)) - pdf = FTDecayFunction2DCauchy(300.0*nanometer/2.0/M_PI, 100.0*nanometer/2.0/M_PI, 0) + interference = InterferenceFunction2DLattice(ba.SquareLattice2D(10.0 * + nanometer)) + pdf = FTDecayFunction2DCauchy(300.0 * nanometer / 2.0 / M_PI, + 100.0 * nanometer / 2.0 / M_PI, 0) interference.setDecayFunction(pdf) particle_layout1.setInterferenceFunction(interference) particle_layout2.setInterferenceFunction(interference) @@ -53,8 +56,9 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -2.0*degree, 2.0*degree, 100, 0.0*degree, 4.0*degree) - simulation.setBeamParameters(1.0*angstrom, 0.2*degree, 0.0*degree) + simulation.setDetectorParameters(100, -2.0 * degree, 2.0 * degree, 100, + 0.0 * degree, 4.0 * degree) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) # run simulation simulation.setSample(multi_layer) @@ -67,9 +71,9 @@ def RunSimulation(): #------------------------------------------------------------- if __name__ == '__main__': result = RunSimulation() - im = plt.imshow(result+1, - norm=matplotlib.colors.LogNorm(), - extent=[-2.0, 2.0, 0, 4.0]) + im = plt.imshow(result + 1, + norm=matplotlib.colors.LogNorm(), + extent=[-2.0, 2.0, 0, 4.0]) plt.colorbar(im) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) diff --git a/Examples/Demos/simul_demo_movie.py b/Examples/Demos/simul_demo_movie.py index dfb7de2e43d6de760e40bb5df3ff1bd33f0a081e..de1a31f701ee55bdc92efd73da1be7fe8e459b5b 100644 --- a/Examples/Demos/simul_demo_movie.py +++ b/Examples/Demos/simul_demo_movie.py @@ -14,6 +14,7 @@ radius = 1 height = 4 distance = 5 + # ---------------------------------- # describe sample and run simulation # ---------------------------------- @@ -45,46 +46,50 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, 0.0 * degree, 8.0 * degree) + simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, + 0.0 * degree, 8.0 * degree) simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setSample(multi_layer) simulation.runSimulation() # intensity data return simulation.result().array() - + def SetParameters(i): global radius global height global distance - radius = (1. + (3.0/Nframes)*i) * nanometer - height = (1. + (4.0/Nframes)*i) * nanometer - distance = (10. - (1.0/Nframes)*i) * nanometer + radius = (1. + (3.0 / Nframes) * i) * nanometer + height = (1. + (4.0 / Nframes) * i) * nanometer + distance = (10. - (1.0 / Nframes) * i) * nanometer + #------------------------------------------------------------- # main() #------------------------------------------------------------- if __name__ == '__main__': files = [] - fig = plt.figure(figsize=(5,5)) + fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(111) for i in range(Nframes): SetParameters(i) result = RunSimulation() + 1 # for log scale ax.cla() - im = ax.imshow(result, vmax=1e3, - norm=matplotlib.colors.LogNorm(), - extent=[-4.0, 4.0, 0, 8.0]) + im = ax.imshow(result, + vmax=1e3, + norm=matplotlib.colors.LogNorm(), + extent=[-4.0, 4.0, 0, 8.0]) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) - if i==0: + if i == 0: plt.colorbar(im) - fname = '_tmp%03d.png'%i + fname = '_tmp%03d.png' % i print 'Saving frame', fname try: fig.savefig(fname) except IOError as e: - print "Frame cannot be saved. I/O error({0}): {1}".format(e.errno, e.strerror) + print "Frame cannot be saved. I/O error({0}): {1}".format( + e.errno, e.strerror) print "Copy these examples to the directory where you have a write permission and enough free space to save the movie." sys.exit() except: @@ -94,10 +99,11 @@ if __name__ == '__main__': files.append(fname) try: - os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg") + os.system( + "mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg" + ) print 'Removing temporary files' os.system("rm _tmp*") except: print "Movie cannot be saved. Error:", sys.exc_info()[0] sys.exit() - diff --git a/Examples/Demos/simul_demo_movie2.py b/Examples/Demos/simul_demo_movie2.py index 72b73ae6537c23914c12b09ff4e64321fba7f3c8..5662269b8a9b5ce9483c4fb859db85ab8971d2de 100644 --- a/Examples/Demos/simul_demo_movie2.py +++ b/Examples/Demos/simul_demo_movie2.py @@ -13,6 +13,7 @@ layer_thickness = 1 Nframes = 100 Ngrowframes = 30 + # ---------------------------------- # describe sample and run simulation # ---------------------------------- @@ -46,7 +47,8 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, 0.0 * degree, 8.0 * degree) + simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, + 0.0 * degree, 8.0 * degree) simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setSample(multi_layer) simulation.runSimulation() @@ -57,37 +59,41 @@ def RunSimulation(): def SetParameters(i): global radius global layer_thickness - if i<Ngrowframes: - radius = (1. + (3.0/Ngrowframes)*i) * nanometer + if i < Ngrowframes: + radius = (1. + (3.0 / Ngrowframes) * i) * nanometer layer_thickness = 0.01 * nanometer else: radius = 4. * nanometer - layer_thickness = (0.01 + (0.5/(Nframes-Ngrowframes))*(i-Ngrowframes)) * nanometer + layer_thickness = (0.01 + (0.5 / (Nframes - Ngrowframes)) * + (i - Ngrowframes)) * nanometer + #------------------------------------------------------------- # main() #------------------------------------------------------------- if __name__ == '__main__': files = [] - fig = plt.figure(figsize=(5,5)) + fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(111) for i in range(Nframes): SetParameters(i) - result = RunSimulation() + 1 # for log scale + result = RunSimulation() + 1 # for log scale ax.cla() - im = ax.imshow(result, vmax=1e3, - norm=matplotlib.colors.LogNorm(), - extent=[-4.0, 4.0, 0, 8.0]) + im = ax.imshow(result, + vmax=1e3, + norm=matplotlib.colors.LogNorm(), + extent=[-4.0, 4.0, 0, 8.0]) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) - if i==0: + if i == 0: plt.colorbar(im) - fname = '_tmp%03d.png'%i + fname = '_tmp%03d.png' % i print 'Saving frame', fname try: fig.savefig(fname) except IOError as e: - print "Frame cannot be saved. I/O error({0}): {1}".format(e.errno, e.strerror) + print "Frame cannot be saved. I/O error({0}): {1}".format( + e.errno, e.strerror) print "Copy these examples to the directory where you have a write permission and enough free space to save the movie." sys.exit() except: @@ -96,10 +102,11 @@ if __name__ == '__main__': else: files.append(fname) try: - os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation2.mpg") + os.system( + "mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation2.mpg" + ) print 'Removing temporary files' os.system("rm _tmp*") except: print "Movie cannot be saved. Error:", sys.exc_info()[0] sys.exit() - diff --git a/Examples/Demos/simul_demo_movie3.py b/Examples/Demos/simul_demo_movie3.py index 0037480b61ed8e0b5de18e734746005381e4d40b..b6983fd1bceec13db3e03ed36e099e1725ad6ada 100644 --- a/Examples/Demos/simul_demo_movie3.py +++ b/Examples/Demos/simul_demo_movie3.py @@ -12,6 +12,7 @@ Nframes = 50 kappa = 0. + # ---------------------------------- # describe sample and run simulation # ---------------------------------- @@ -51,7 +52,8 @@ def RunSimulation(): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, 0.0 * degree, 8.0 * degree) + simulation.setDetectorParameters(100, -4.0 * degree, 4.0 * degree, 100, + 0.0 * degree, 8.0 * degree) simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setSample(multi_layer) simulation.runSimulation() @@ -61,32 +63,35 @@ def RunSimulation(): def SetParameters(i): global kappa - kappa = 0.01 + (2.0/Nframes)*i + kappa = 0.01 + (2.0 / Nframes) * i + #------------------------------------------------------------- # main() #------------------------------------------------------------- if __name__ == '__main__': files = [] - fig = plt.figure(figsize=(5,5)) + fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(111) for i in range(Nframes): SetParameters(i) result = RunSimulation() + 1 # for log scale ax.cla() - im = ax.imshow(result, vmax=1e3, - norm=matplotlib.colors.LogNorm(), - extent=[-4.0, 4.0, 0, 8.0]) + im = ax.imshow(result, + vmax=1e3, + norm=matplotlib.colors.LogNorm(), + extent=[-4.0, 4.0, 0, 8.0]) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) - if i==0: + if i == 0: plt.colorbar(im) - fname = '_tmp%03d.png'%i + fname = '_tmp%03d.png' % i print 'Saving frame', fname try: fig.savefig(fname) except IOError as e: - print "Frame cannot be saved. I/O error({0}): {1}".format(e.errno, e.strerror) + print "Frame cannot be saved. I/O error({0}): {1}".format( + e.errno, e.strerror) print "Copy these examples to the directory where you have a write permission and enough free space to save the movie." sys.exit() except: @@ -96,10 +101,11 @@ if __name__ == '__main__': files.append(fname) try: - os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation3.mpg") + os.system( + "mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation3.mpg" + ) print 'Removing temporary files' os.system("rm _tmp*") except: print "Movie cannot be saved. Error:", sys.exc_info()[0] sys.exit() - diff --git a/Examples/Python/fit51_Basic/basic_fitting_tutorial.py b/Examples/Python/fit51_Basic/basic_fitting_tutorial.py index 14b06998c3c902e665ef552fc568fa845fc1cff7..7cf45a418885f86a30ea47ff23c880b9d7102c03 100644 --- a/Examples/Python/fit51_Basic/basic_fitting_tutorial.py +++ b/Examples/Python/fit51_Basic/basic_fitting_tutorial.py @@ -47,9 +47,9 @@ def get_simulation(params): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation @@ -62,8 +62,12 @@ def create_real_data(): """ # default sample parameters - params = {'cylinder_height': 5.0*nm, 'cylinder_radius': 5.0*nm, - 'prism_height': 5.0*nm, 'prism_base_edge': 5.0*nm} + params = { + 'cylinder_height': 5.0 * nm, + 'cylinder_radius': 5.0 * nm, + 'prism_height': 5.0 * nm, + 'prism_base_edge': 5.0 * nm + } # retrieving simulated data in the form of numpy array simulation = get_simulation(params) @@ -73,7 +77,7 @@ def create_real_data(): # spoiling simulated data with noise to produce "real" data np.random.seed(0) noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 np.savetxt("basic_fitting_tutorial_data.txt.gz", real_data) @@ -103,10 +107,10 @@ def run_fitting(): fit_objective.initPlot(10) params = ba.Parameters() - params.add("cylinder_height", 4.*nm, min=0.01) - params.add("cylinder_radius", 6.*nm, min=0.01) - params.add("prism_height", 4.*nm, min=0.01) - params.add("prism_base_edge", 6.*nm, min=0.01) + params.add("cylinder_height", 4. * nm, min=0.01) + params.add("cylinder_radius", 6. * nm, min=0.01) + params.add("prism_height", 4. * nm, min=0.01) + params.add("prism_base_edge", 6. * nm, min=0.01) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit51_Basic/consecutive_fitting.py b/Examples/Python/fit51_Basic/consecutive_fitting.py index 56d5dc25bae9a3237717aa9901ea2de92ab93ed2..fa54e2100aabd7bad49c2e5ea0ba1d20bfbc53b8 100644 --- a/Examples/Python/fit51_Basic/consecutive_fitting.py +++ b/Examples/Python/fit51_Basic/consecutive_fitting.py @@ -44,9 +44,9 @@ def get_simulation(params): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, 0.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation @@ -56,7 +56,7 @@ def create_real_data(): """ Generating "real" data by adding noise to the simulated data. """ - params = {'radius': 5.0*nm, 'height': 5.0*nm} + params = {'radius': 5.0 * nm, 'height': 5.0 * nm} simulation = get_simulation(params) simulation.runSimulation() @@ -66,7 +66,7 @@ def create_real_data(): # spoiling simulated data with the noise to produce "real" data noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 return noisy @@ -81,16 +81,14 @@ def run_fitting(): fit_objective.addSimulationAndData(get_simulation, real_data, 1.0) fit_objective.initPrint(10) fit_objective.initPlot(10) - """ Setting fitting parameters with starting values. Here we select starting values being quite far from true values to puzzle our minimizer's as much as possible. """ params = ba.Parameters() - params.add("height", 1.*nm, min=0.01, max=30.0, step=0.05*nm) - params.add("radius", 20.*nm, min=0.01, max=30.0, step=0.05*nm) - + params.add("height", 1. * nm, min=0.01, max=30.0, step=0.05 * nm) + params.add("radius", 20. * nm, min=0.01, max=30.0, step=0.05 * nm) """ Now we run first minimization round using the Genetic minimizer. The Genetic minimizer is able to explore large parameter space @@ -102,7 +100,6 @@ def run_fitting(): fit_objective.finalize(result) best_params_so_far = result.parameters() - """ Second fit will use another minimizer. It starts from best parameters found in previous minimization diff --git a/Examples/Python/fit51_Basic/minimal_fit_example.py b/Examples/Python/fit51_Basic/minimal_fit_example.py index bc71decbb208f1a0ca7113f4848a33a3dc84c397..e5c68e14c5ef7e61a5f91eb0df0484185f44b7c2 100644 --- a/Examples/Python/fit51_Basic/minimal_fit_example.py +++ b/Examples/Python/fit51_Basic/minimal_fit_example.py @@ -20,9 +20,9 @@ def get_simulation(params): multi_layer.addLayer(layer) simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setSample(multi_layer) return simulation @@ -32,7 +32,7 @@ def real_data(): """ Generating "experimental" data by running simulation with default parameters. """ - simulation = get_simulation({'radius': 5.0*nm}) + simulation = get_simulation({'radius': 5.0 * nm}) simulation.runSimulation() return simulation.result().array() @@ -46,7 +46,7 @@ def run_fitting(): fit_objective.initPrint(10) params = ba.Parameters() - params.add("radius", 4.*nm, min=0.01) + params.add("radius", 4. * nm, min=0.01) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit51_Basic/minimizer_settings.py b/Examples/Python/fit51_Basic/minimizer_settings.py index 871368b4efcd5fbf1f9e65d75b9ae8d093a811fe..0b48597356b0caeef05f7e301ccde2936edd4718 100644 --- a/Examples/Python/fit51_Basic/minimizer_settings.py +++ b/Examples/Python/fit51_Basic/minimizer_settings.py @@ -45,9 +45,9 @@ def get_simulation(params): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation @@ -58,8 +58,12 @@ def create_real_data(): Generating "real" data from simulated image with default parameters. """ - params = {'cylinder_height': 5.0*nm, 'cylinder_radius': 5.0*nm, - 'prism_height': 5.0*nm, 'prism_base_edge': 5.0*nm} + params = { + 'cylinder_height': 5.0 * nm, + 'cylinder_radius': 5.0 * nm, + 'prism_height': 5.0 * nm, + 'prism_base_edge': 5.0 * nm + } simulation = get_simulation(params) simulation.runSimulation() @@ -85,32 +89,28 @@ def run_fitting(): fit_objective.initPrint(10) params = ba.Parameters() - params.add("cylinder_height", 4.*nm, min=0.01) - params.add("cylinder_radius", 6.*nm, min=0.01) - params.add("prism_height", 4.*nm, min=0.01) - params.add("prism_base_edge", 12.*nm, min=0.01) + params.add("cylinder_height", 4. * nm, min=0.01) + params.add("cylinder_radius", 6. * nm, min=0.01) + params.add("prism_height", 4. * nm, min=0.01) + params.add("prism_base_edge", 12. * nm, min=0.01) minimizer = ba.Minimizer() # Uncomment one of the line below to adjust minimizer settings - """ Setting Minuit2 minimizer with Migrad algorithm, limiting number of iterations. Minimization will try to respect MaxFunctionCalls value. """ # minimizer.setMinimizer("Minuit2", "Migrad", "MaxFunctionCalls=50") - """ Setting two options at once. Strategy=2 promises more accurate fit. """ # minimizer.setMinimizer("Minuit2", "Migrad", "MaxFunctionCalls=500;Strategy=2") - """ Setting Minuit2 minimizer with Fumili algorithm. """ # minimizer.setMinimizer("Minuit2", "Fumili") - """ Setting Levenberg-Marquardt algorithm. """ diff --git a/Examples/Python/fit52_Advanced/find_background.py b/Examples/Python/fit52_Advanced/find_background.py index 7c40fe97c105ee577baabc203ad4588346018a11..8a0b1f4442da19fef6d4fac52bc55f5d517556de 100644 --- a/Examples/Python/fit52_Advanced/find_background.py +++ b/Examples/Python/fit52_Advanced/find_background.py @@ -47,10 +47,10 @@ def get_simulation(params): scale = params["scale"] simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) - simulation.setBeamIntensity(1e12*scale) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) + simulation.setBeamIntensity(1e12 * scale) simulation.setBackground(ba.ConstantBackground(background)) simulation.setSample(get_sample(params)) @@ -66,7 +66,12 @@ def create_real_data(): scale, background factors. """ - params = {'radius': 5.0*nm, 'height': 10.0*nm, 'scale': 2.0, 'background': 1000} + params = { + 'radius': 5.0 * nm, + 'height': 10.0 * nm, + 'scale': 2.0, + 'background': 1000 + } simulation = get_simulation(params) simulation.runSimulation() @@ -88,8 +93,8 @@ def run_fitting(): fit_objective.initPlot(10) params = ba.Parameters() - params.add("radius", 5.*nm, vary=False) - params.add("height", 9.*nm, min=8.*nm, max=12.*nm) + params.add("radius", 5. * nm, vary=False) + params.add("height", 9. * nm, min=8. * nm, max=12. * nm) params.add("scale", 1.5, min=1.0, max=3.0) params.add("background", 200, min=100.0, max=2000.0, step=100.0) diff --git a/Examples/Python/fit52_Advanced/fit_along_slices.py b/Examples/Python/fit52_Advanced/fit_along_slices.py index 9124e731d9fa667b52a29a6adb1bc4fb1b81ba2d..9c22611daefaa5c5bcd4db20f5220e10970522c7 100644 --- a/Examples/Python/fit52_Advanced/fit_along_slices.py +++ b/Examples/Python/fit52_Advanced/fit_along_slices.py @@ -42,8 +42,9 @@ def get_simulation(params, add_masks=True): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) if add_masks: @@ -53,8 +54,8 @@ def get_simulation(params, add_masks=True): simulation/fitting to be performed along slices only. """ simulation.maskAll() - simulation.addMask(ba.HorizontalLine(alpha_slice_value*deg), False) - simulation.addMask(ba.VerticalLine(phi_slice_value*deg), False) + simulation.addMask(ba.HorizontalLine(alpha_slice_value * deg), False) + simulation.addMask(ba.VerticalLine(phi_slice_value * deg), False) return simulation @@ -63,7 +64,7 @@ def create_real_data(): Generating "real" data by adding noise to the simulated data. """ # initial values which we will have to find later during the fit - params = {'radius': 5.0*nm, 'height': 10.0*nm} + params = {'radius': 5.0 * nm, 'height': 10.0 * nm} # retrieving simulated data in the form of numpy array simulation = get_simulation(params, add_masks=False) @@ -78,7 +79,6 @@ class PlotObserver: Draws fit progress every nth iteration. Here we plot slices along real and simulated images to see fit progress. """ - def __init__(self): self.fig = plt.figure(figsize=(10.25, 7.69)) self.fig.canvas.draw() @@ -97,11 +97,15 @@ class PlotObserver: # line representing vertical slice plt.plot([phi_slice_value, phi_slice_value], [data.getYmin(), data.getYmax()], - color='gray', linestyle='-', linewidth=1) + color='gray', + linestyle='-', + linewidth=1) # line representing horizontal slice plt.plot([data.getXmin(), data.getXmax()], [alpha_slice_value, alpha_slice_value], - color='gray', linestyle='-', linewidth=1) + color='gray', + linestyle='-', + linewidth=1) @staticmethod def plot_slices(slices, title): @@ -110,10 +114,9 @@ class PlotObserver: """ plt.subplots_adjust(wspace=0.2, hspace=0.3) for label, slice in slices: - plt.semilogy(slice.binCenters(), - slice.binValues(), label=label) + plt.semilogy(slice.binCenters(), slice.binValues(), label=label) plt.xlim(slice.getXmin(), slice.getXmax()) - plt.ylim(1.0, slice.getMaximum()*10.0) + plt.ylim(1.0, slice.getMaximum() * 10.0) plt.legend(loc='upper right') plt.title(title) @@ -127,14 +130,13 @@ class PlotObserver: iteration_info = fit_objective.iterationInfo() - plt.text(0.01, 0.85, "Iterations " + '{:d}'. - format(iteration_info.iterationCount())) + plt.text(0.01, 0.85, + "Iterations " + '{:d}'.format(iteration_info.iterationCount())) plt.text(0.01, 0.75, "Chi2 " + '{:8.4f}'.format(iteration_info.chi2())) for index, params in enumerate(iteration_info.parameters()): plt.text(0.01, 0.55 - index * 0.1, '{:30.30s}: {:6.3f}'.format(params.name(), params.value)) - plt.tight_layout() plt.draw() plt.pause(0.01) @@ -153,19 +155,15 @@ class PlotObserver: self.plot_real_data(real_data) # horizontal slices - slices = [ - ("real", real_data.projectionX(alpha_slice_value)), - ("simul", simul_data.projectionX(alpha_slice_value)) - ] + slices = [("real", real_data.projectionX(alpha_slice_value)), + ("simul", simul_data.projectionX(alpha_slice_value))] title = ("Horizontal slice at alpha =" + '{:3.1f}'.format(alpha_slice_value)) plt.subplot(2, 2, 2) self.plot_slices(slices, title) # vertical slices - slices = [ - ("real", real_data.projectionY(phi_slice_value)), - ("simul", simul_data.projectionY(phi_slice_value)) - ] + slices = [("real", real_data.projectionY(phi_slice_value)), + ("simul", simul_data.projectionY(phi_slice_value))] title = "Vertical slice at phi =" + '{:3.1f}'.format(phi_slice_value) plt.subplot(2, 2, 3) self.plot_slices(slices, title) @@ -191,8 +189,8 @@ def run_fitting(): fit_objective.initPlot(10, plotter) params = ba.Parameters() - params.add("radius", 6.*nm, min=4.0, max=8.0) - params.add("height", 9.*nm, min=8.0, max=12.0) + params.add("radius", 6. * nm, min=4.0, max=8.0) + params.add("height", 9. * nm, min=8.0, max=12.0) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit52_Advanced/fit_with_masks.py b/Examples/Python/fit52_Advanced/fit_with_masks.py index 2306038950cec5ce99564304cab6865adacf8268..8226014c5551e145616b39d2dbd363a48b0114f9 100644 --- a/Examples/Python/fit52_Advanced/fit_with_masks.py +++ b/Examples/Python/fit52_Advanced/fit_with_masks.py @@ -41,9 +41,9 @@ def get_simulation(params, add_masks=True): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) @@ -57,7 +57,7 @@ def create_real_data(): """ Generating "real" data by adding noise to the simulated data. """ - params = {'radius': 5.0*nm, 'height': 10.0*nm} + params = {'radius': 5.0 * nm, 'height': 10.0 * nm} # retrieving simulated data in the form of numpy array simulation = get_simulation(params, add_masks=False) @@ -66,7 +66,7 @@ def create_real_data(): # spoiling simulated data with the noise to produce "real" data noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 return noisy @@ -89,25 +89,24 @@ def add_mask_to_simulation(simulation): simulation.maskAll() # set mask to simulate pacman's head - simulation.addMask( - ba.Ellipse(0.0*deg, 1.0*deg, 0.5*deg, 0.5*deg), False) + simulation.addMask(ba.Ellipse(0.0 * deg, 1.0 * deg, 0.5 * deg, 0.5 * deg), False) # set mask for pacman's eye - simulation.addMask( - ba.Ellipse(0.11*deg, 1.25*deg, 0.05*deg, 0.05*deg), True) + simulation.addMask(ba.Ellipse(0.11 * deg, 1.25 * deg, 0.05 * deg, 0.05 * deg), + True) # set mask for pacman's mouth - points = [[0.0*deg, 1.0*deg], [0.5*deg, 1.2*deg], - [0.5*deg, 0.8*deg], [0.0*deg, 1.0*deg]] + points = [[0.0 * deg, 1.0 * deg], [0.5 * deg, 1.2 * deg], [0.5 * deg, 0.8 * deg], + [0.0 * deg, 1.0 * deg]] simulation.addMask(ba.Polygon(points), True) # giving pacman something to eat - simulation.addMask( - ba.Rectangle(0.45*deg, 0.95*deg, 0.55*deg, 1.05*deg), False) - simulation.addMask( - ba.Rectangle(0.61*deg, 0.95*deg, 0.71*deg, 1.05*deg), False) - simulation.addMask( - ba.Rectangle(0.75*deg, 0.95*deg, 0.85*deg, 1.05*deg), False) + simulation.addMask(ba.Rectangle(0.45 * deg, 0.95 * deg, 0.55 * deg, 1.05 * deg), + False) + simulation.addMask(ba.Rectangle(0.61 * deg, 0.95 * deg, 0.71 * deg, 1.05 * deg), + False) + simulation.addMask(ba.Rectangle(0.75 * deg, 0.95 * deg, 0.85 * deg, 1.05 * deg), + False) # other mask's shapes are possible too # simulation.removeMasks() @@ -131,8 +130,8 @@ def run_fitting(): fit_objective.initPlot(10) params = ba.Parameters() - params.add("radius", 6.*nm, min=4.0, max=8.0) - params.add("height", 9.*nm, min=8.0, max=12.0) + params.add("radius", 6. * nm, min=4.0, max=8.0) + params.add("height", 9. * nm, min=8.0, max=12.0) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit52_Advanced/multiple_datasets.py b/Examples/Python/fit52_Advanced/multiple_datasets.py index ae0cb86e846ed5551ea168ba98e4a5d4a9571a6b..5ce7f94d250e20fd0df6706593b36f82a365e078 100644 --- a/Examples/Python/fit52_Advanced/multiple_datasets.py +++ b/Examples/Python/fit52_Advanced/multiple_datasets.py @@ -44,21 +44,21 @@ def get_simulation(params): incident_angle = params["incident_angle"] simulation = ba.GISASSimulation() - simulation.setDetectorParameters(50, -1.5*deg, 1.5*deg, - 50, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, incident_angle, 0.0*deg) + simulation.setDetectorParameters(50, -1.5 * deg, 1.5 * deg, 50, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, incident_angle, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation def simulation1(params): - params["incident_angle"] = 0.1*deg + params["incident_angle"] = 0.1 * deg return get_simulation(params) def simulation2(params): - params["incident_angle"] = 0.4*deg + params["incident_angle"] = 0.4 * deg return get_simulation(params) @@ -66,8 +66,12 @@ def create_real_data(incident_alpha): """ Generating "real" data by adding noise to the simulated data. """ - params = {'radius_a': 5.0*nm, 'radius_b': 6.0*nm, - 'height': 8.0*nm, "incident_angle": incident_alpha} + params = { + 'radius_a': 5.0 * nm, + 'radius_b': 6.0 * nm, + 'height': 8.0 * nm, + "incident_angle": incident_alpha + } simulation = get_simulation(params) simulation.runSimulation() @@ -77,7 +81,7 @@ def create_real_data(incident_alpha): # spoiling simulated data with the noise to produce "real" data noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 return noisy @@ -103,15 +107,24 @@ class PlotObserver(): zmax = real_data.histogram2d().getMaximum() - plt.subplot(canvas[i_dataset*3]) - ba.plot_colormap(real_data, title="\"Real\" data - #"+str(i_dataset+1), - zmin=1.0, zmax=zmax, zlabel="") - plt.subplot(canvas[1+i_dataset*3]) - ba.plot_colormap(simul_data, title="Simulated data - #"+str(i_dataset+1), - zmin=1.0, zmax=zmax, zlabel="") - plt.subplot(canvas[2+i_dataset*3]) - ba.plot_colormap(chi2_map, title="Chi2 map - #"+str(i_dataset+1), - zmin=0.001, zmax=10.0, zlabel="") + plt.subplot(canvas[i_dataset * 3]) + ba.plot_colormap(real_data, + title="\"Real\" data - #" + str(i_dataset + 1), + zmin=1.0, + zmax=zmax, + zlabel="") + plt.subplot(canvas[1 + i_dataset * 3]) + ba.plot_colormap(simul_data, + title="Simulated data - #" + str(i_dataset + 1), + zmin=1.0, + zmax=zmax, + zlabel="") + plt.subplot(canvas[2 + i_dataset * 3]) + ba.plot_colormap(chi2_map, + title="Chi2 map - #" + str(i_dataset + 1), + zmin=0.001, + zmax=10.0, + zlabel="") @staticmethod def display_fit_parameters(fit_objective): @@ -123,8 +136,8 @@ class PlotObserver(): iteration_info = fit_objective.iterationInfo() - plt.text(0.01, 0.85, "Iterations " + '{:d}'. - format(iteration_info.iterationCount())) + plt.text(0.01, 0.85, + "Iterations " + '{:d}'.format(iteration_info.iterationCount())) plt.text(0.01, 0.75, "Chi2 " + '{:8.4f}'.format(iteration_info.chi2())) for index, params in enumerate(iteration_info.parameters()): plt.text(0.01, 0.55 - index * 0.1, @@ -139,8 +152,8 @@ class PlotObserver(): iteration_info = fit_objective.iterationInfo() - plt.text(0.01, 0.95, "Iterations " + '{:d}'. - format(iteration_info.iterationCount())) + plt.text(0.01, 0.95, + "Iterations " + '{:d}'.format(iteration_info.iterationCount())) plt.text(0.01, 0.70, "Chi2 " + '{:8.4f}'.format(iteration_info.chi2())) for index, params in enumerate(iteration_info.parameters()): plt.text(0.01, 0.30 - index * 0.3, @@ -151,8 +164,10 @@ class PlotObserver(): # we divide figure to have 3x3 subplots, with two first rows occupying # most of the space - canvas = matplotlib.gridspec.GridSpec( - 3, 3, width_ratios=[1, 1, 1], height_ratios=[4, 4, 1]) + canvas = matplotlib.gridspec.GridSpec(3, + 3, + width_ratios=[1, 1, 1], + height_ratios=[4, 4, 1]) canvas.update(left=0.05, right=0.95, hspace=0.5, wspace=0.2) self.plot_dataset(fit_objective, canvas) @@ -181,9 +196,9 @@ def run_fitting(): fit_objective.initPlot(10, plotter.update) params = ba.Parameters() - params.add("radius_a", 4.*nm, min=2.0, max=10.0) - params.add("radius_b", 6.*nm, vary=False) - params.add("height", 4.*nm, min=2.0, max=10.0) + params.add("radius_a", 4. * nm, min=2.0, max=10.0) + params.add("radius_b", 6. * nm, vary=False) + params.add("height", 4. * nm, min=2.0, max=10.0) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit53_CustomObjective/custom_objective_function.py b/Examples/Python/fit53_CustomObjective/custom_objective_function.py index a72521bdb979627c0b206a9c81270a7e43a19b32..75d783e2f3942b116f153f870ed5e68414cf35a2 100644 --- a/Examples/Python/fit53_CustomObjective/custom_objective_function.py +++ b/Examples/Python/fit53_CustomObjective/custom_objective_function.py @@ -53,7 +53,7 @@ def get_sample(params): interference = ba.InterferenceFunction2DLattice( ba.HexagonalLattice2D(lattice_length)) - pdf = ba.FTDecayFunction2DCauchy(10*nm, 10*nm, 0) + pdf = ba.FTDecayFunction2DCauchy(10 * nm, 10 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -72,9 +72,9 @@ def get_simulation(params): Create and return GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation @@ -84,7 +84,7 @@ def create_real_data(): """ Generating "real" data by adding noise to the simulated data. """ - params = {'radius': 6*nm, 'length': 12*nm} + params = {'radius': 6 * nm, 'length': 12 * nm} simulation = get_simulation(params) simulation.runSimulation() @@ -94,7 +94,7 @@ def create_real_data(): # spoiling simulated data with noise to produce "real" data np.random.seed(0) noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 return noisy @@ -110,8 +110,8 @@ def run_fitting(): objective.initPrint(10) params = ba.Parameters() - params.add('radius', value=7*nm, min=5*nm, max=8*nm) - params.add('length', value=10*nm, min=8*nm, max=14*nm) + params.add('radius', value=7 * nm, min=5 * nm, max=8 * nm) + params.add('length', value=10 * nm, min=8 * nm, max=14 * nm) minimizer = ba.Minimizer() result = minimizer.minimize(objective.evaluate_residuals, params) diff --git a/Examples/Python/fit54_ExternalMinimizer/lmfit_basics.py b/Examples/Python/fit54_ExternalMinimizer/lmfit_basics.py index f0a22f72c68fe5f16ec536a4f92a4e1463514c0d..8933a0c99e97170b1b2f2b82a85a78ab170f03e1 100644 --- a/Examples/Python/fit54_ExternalMinimizer/lmfit_basics.py +++ b/Examples/Python/fit54_ExternalMinimizer/lmfit_basics.py @@ -27,7 +27,7 @@ def get_sample(params): interference = ba.InterferenceFunction2DLattice( ba.HexagonalLattice2D(lattice_length)) - pdf = ba.FTDecayFunction2DCauchy(10*nm, 10*nm, 0) + pdf = ba.FTDecayFunction2DCauchy(10 * nm, 10 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -46,9 +46,9 @@ def get_simulation(params): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation @@ -58,7 +58,7 @@ def create_real_data(): """ Generating "real" data by adding noise to the simulated data. """ - params = {'radius': 6*nm, 'length': 12*nm} + params = {'radius': 6 * nm, 'length': 12 * nm} simulation = get_simulation(params) simulation.runSimulation() @@ -68,7 +68,7 @@ def create_real_data(): # spoiling simulated data with noise to produce "real" data np.random.seed(0) noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 return noisy @@ -84,8 +84,8 @@ def run_fitting(): fit_objective.initPrint(10) params = lmfit.Parameters() - params.add('radius', value=7*nm, min=5*nm, max=8*nm) - params.add('length', value=10*nm, min=8*nm, max=14*nm) + params.add('radius', value=7 * nm, min=5 * nm, max=8 * nm) + params.add('length', value=10 * nm, min=8 * nm, max=14 * nm) result = lmfit.minimize(fit_objective.evaluate_residuals, params) fit_objective.finalize(result) diff --git a/Examples/Python/fit54_ExternalMinimizer/lmfit_with_plotting.py b/Examples/Python/fit54_ExternalMinimizer/lmfit_with_plotting.py index fc9514b085ea35b899a796d52848023f89f36223..18ed4558c932577aa1ad62044b1e8c5460d94673 100644 --- a/Examples/Python/fit54_ExternalMinimizer/lmfit_with_plotting.py +++ b/Examples/Python/fit54_ExternalMinimizer/lmfit_with_plotting.py @@ -28,7 +28,7 @@ def get_sample(params): interference = ba.InterferenceFunction2DLattice( ba.HexagonalLattice2D(lattice_length)) - pdf = ba.FTDecayFunction2DCauchy(10*nm, 10*nm, 0) + pdf = ba.FTDecayFunction2DCauchy(10 * nm, 10 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -47,9 +47,9 @@ def get_simulation(params): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.setSample(get_sample(params)) return simulation @@ -59,7 +59,7 @@ def create_real_data(): """ Generating "real" data by adding noise to the simulated data. """ - params = {'radius': 6*nm, 'length': 12*nm} + params = {'radius': 6 * nm, 'length': 12 * nm} simulation = get_simulation(params) simulation.runSimulation() @@ -69,7 +69,7 @@ def create_real_data(): # spoiling simulated data with noise to produce "real" data np.random.seed(0) noise_factor = 0.1 - noisy = np.random.normal(real_data, noise_factor*np.sqrt(real_data)) + noisy = np.random.normal(real_data, noise_factor * np.sqrt(real_data)) noisy[noisy < 0.1] = 0.1 return noisy @@ -78,13 +78,13 @@ class Plotter: """ Adapts standard plotter for lmfit minimizer. """ - def __init__(self, fit_objective, every_nth = 10): + def __init__(self, fit_objective, every_nth=10): self.fit_objective = fit_objective self.plotter_gisas = ba.PlotterGISAS() self.every_nth = every_nth def __call__(self, params, iter, resid): - if iter%self.every_nth == 0: + if iter % self.every_nth == 0: self.plotter_gisas.plot(self.fit_objective) @@ -99,17 +99,19 @@ def run_fitting(): fit_objective.initPrint(10) params = lmfit.Parameters() - params.add('radius', value=7*nm, min=5*nm, max=8*nm) - params.add('length', value=10*nm, min=8*nm, max=14*nm) + params.add('radius', value=7 * nm, min=5 * nm, max=8 * nm) + params.add('length', value=10 * nm, min=8 * nm, max=14 * nm) plotter = Plotter(fit_objective) - result = lmfit.minimize( - fit_objective.evaluate_residuals, params, iter_cb=plotter) + result = lmfit.minimize(fit_objective.evaluate_residuals, + params, + iter_cb=plotter) fit_objective.finalize(result) result.params.pretty_print() print(lmfit.fit_report(result)) + if __name__ == '__main__': run_fitting() plt.show() diff --git a/Examples/Python/fit55_Specular/FitSpecularBasics.py b/Examples/Python/fit55_Specular/FitSpecularBasics.py index d74b5ef0b1578898e5983253be64a2bea3ec0335..6dc55480be733db8a9683af4e395e2b098aaa8f4 100644 --- a/Examples/Python/fit55_Specular/FitSpecularBasics.py +++ b/Examples/Python/fit55_Specular/FitSpecularBasics.py @@ -21,7 +21,7 @@ def get_sample(params): # substrate (Si) si_sld_real = 2.0704e-06 # \AA^{-2} - density_si = 0.0499 / ba.angstrom ** 3 # Si atomic number density + density_si = 0.0499 / ba.angstrom**3 # Si atomic number density # layers' parameters n_repetitions = 10 @@ -115,8 +115,10 @@ def run_fitting(): fit_objective.initPlot(10, plot_observer) params = ba.Parameters() - params.add("ti_thickness", 50 * ba.angstrom, - min=10 * ba.angstrom, max=60 * ba.angstrom) + params.add("ti_thickness", + 50 * ba.angstrom, + min=10 * ba.angstrom, + max=60 * ba.angstrom) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit55_Specular/FitWithUncertainties.py b/Examples/Python/fit55_Specular/FitWithUncertainties.py index a03e63688548dac9cedcfab75d6e051d80f7136e..41f9322f5e083403e4c31d0a04801e5f69f49a43 100644 --- a/Examples/Python/fit55_Specular/FitWithUncertainties.py +++ b/Examples/Python/fit55_Specular/FitWithUncertainties.py @@ -26,7 +26,7 @@ def get_sample(params): # substrate (Si) si_sld_real = 2.0704e-06 # \AA^{-2} - density_si = 0.0499 / ba.angstrom ** 3 # Si atomic number density + density_si = 0.0499 / ba.angstrom**3 # Si atomic number density # layers' parameters n_repetitions = 10 @@ -124,8 +124,10 @@ def run_fitting(): fit_objective.setObjectiveMetric("Chi2", "L1") params = ba.Parameters() - params.add("ti_thickness", 50 * ba.angstrom, - min=10 * ba.angstrom, max=60 * ba.angstrom) + params.add("ti_thickness", + 50 * ba.angstrom, + min=10 * ba.angstrom, + max=60 * ba.angstrom) minimizer = ba.Minimizer() minimizer.setMinimizer("Genetic", "", "MaxIterations=40;PopSize=10") diff --git a/Examples/Python/fit55_Specular/RealLifeReflectometryFitting.py b/Examples/Python/fit55_Specular/RealLifeReflectometryFitting.py index 5ac85e84fd6f10383fa96e01117f031c0f58b436..a9e942166a439228383b00483f99255afbeeac06 100644 --- a/Examples/Python/fit55_Specular/RealLifeReflectometryFitting.py +++ b/Examples/Python/fit55_Specular/RealLifeReflectometryFitting.py @@ -93,8 +93,7 @@ def create_simulation(arg_dict, bin_start, bin_end): alpha_distr = ba.RangedDistributionGaussian(30, 3) footprint = ba.FootprintGauss(arg_dict["footprint_factor"]) - scan = ba.AngularSpecScan(wavelength, - get_real_data_axis(bin_start, bin_end)) + scan = ba.AngularSpecScan(wavelength, get_real_data_axis(bin_start, bin_end)) scan.setAbsoluteAngularResolution(alpha_distr, arg_dict["divergence"]) scan.setFootprintFactor(footprint) @@ -111,8 +110,8 @@ def buildSample(arg_dict): # defining materials m_vacuum = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0) m_si_o2 = ba.HomogeneousMaterial("SiO2", - 8.57040868e-06 * arg_dict["concentration"], - 1.11016654e-07 * arg_dict["concentration"]) + 8.57040868e-06 * arg_dict["concentration"], + 1.11016654e-07 * arg_dict["concentration"]) m_si = ba.HomogeneousMaterial("Si", 7.57211137e-06, 1.72728178e-07) # roughness @@ -152,7 +151,7 @@ def chi_2(real_data, sim_data, weights): sim_data_upsc[sim_data_upsc is 0] = 1e-30 real_data_upsc = np.multiply(weights, real_data) diff = real_data_upsc - sim_data_upsc - return np.sum(np.divide(np.multiply(diff,diff), sim_data_upsc)) + return np.sum(np.divide(np.multiply(diff, diff), sim_data_upsc)) def create_par_dict(*arg): @@ -160,13 +159,14 @@ def create_par_dict(*arg): Creates a dictionary with parameter names and values and returns it """ - return {'intensity': arg[0], - 'footprint_factor': arg[1], - 'divergence':arg[2], - 'concentration': arg[3], - 'thickness': arg[4], - 'roughness': arg[5] - } + return { + 'intensity': arg[0], + 'footprint_factor': arg[1], + 'divergence': arg[2], + 'concentration': arg[3], + 'thickness': arg[4], + 'roughness': arg[5] + } def objective_primary(args): @@ -180,8 +180,8 @@ def objective_primary(args): sim_result = run_simulation(arg_dict, bin_start, bin_end) sim_data = sim_result.array() - return chi_2(get_real_data_values(bin_start, bin_end), - sim_data, get_weights(bin_start, bin_end)) + return chi_2(get_real_data_values(bin_start, bin_end), sim_data, + get_weights(bin_start, bin_end)) def objective_fine(args, intensity, footprint_factor, divergence): @@ -195,8 +195,8 @@ def objective_fine(args, intensity, footprint_factor, divergence): sim_result = run_simulation(arg_dict, bin_start, bin_end) sim_data = sim_result.array() - return chi_2(get_real_data_values(bin_start, bin_end), - sim_data, get_weights(bin_start, bin_end)) + return chi_2(get_real_data_values(bin_start, bin_end), sim_data, + get_weights(bin_start, bin_end)) def run_fitting(): @@ -204,39 +204,51 @@ def run_fitting(): Runs fitting and returns its result """ # running preliminary optimization on the total range of experimental data. - bounds = [(1e6, 1e8), # beam intensity - (0.0, 0.1), # beam-to-sample width ratio - (0.0, 0.08 * ba.deg), # beam_divergence - (0.0, 1.0), # oxide_concentration - (0.0, 2.0 * ba.nm), # oxide_thickness - (0.0, 2.0 * ba.nm)] # roughness + bounds = [ + (1e6, 1e8), # beam intensity + (0.0, 0.1), # beam-to-sample width ratio + (0.0, 0.08 * ba.deg), # beam_divergence + (0.0, 1.0), # oxide_concentration + (0.0, 2.0 * ba.nm), # oxide_thickness + (0.0, 2.0 * ba.nm) + ] # roughness print("Start preliminary fitting of experimental data:\n") - preliminary_result = differential_evolution(objective_primary, bounds, - maxiter=20, popsize=60, + preliminary_result = differential_evolution(objective_primary, + bounds, + maxiter=20, + popsize=60, mutation=(0.5, 1.5), - disp=True, tol=1e-5) + disp=True, + tol=1e-5) - bounds = [(0.0, 1.0), # oxide_concentration - (0.0, 2.0 * ba.nm), # oxide_thickness - (0.0, 2.0 * ba.nm)] # roughness + bounds = [ + (0.0, 1.0), # oxide_concentration + (0.0, 2.0 * ba.nm), # oxide_thickness + (0.0, 2.0 * ba.nm) + ] # roughness - fixed_args = (preliminary_result.x[0], # beam intensity - preliminary_result.x[1], # beam-to-sample width ratio - preliminary_result.x[2] # beam divergence - ) + fixed_args = ( + preliminary_result.x[0], # beam intensity + preliminary_result.x[1], # beam-to-sample width ratio + preliminary_result.x[2] # beam divergence + ) print("\nStart fitting big incident angle part of experimental data:\n") - fine_tuning_result = differential_evolution(objective_fine, bounds, - fixed_args, maxiter=20, - popsize=40, mutation=(0.5, 1.5), - disp=True, tol=1e-5) + fine_tuning_result = differential_evolution(objective_fine, + bounds, + fixed_args, + maxiter=20, + popsize=40, + mutation=(0.5, 1.5), + disp=True, + tol=1e-5) result = create_par_dict(*fixed_args, *fine_tuning_result.x) print("\nFitting result:") - print(result,"\n") + print(result, "\n") return result @@ -248,27 +260,29 @@ def plot_result(sim_result, ref_result, bin_start=0, bin_end=-1): sim_data = sim_result.array() ref_data = ref_result.array() - plt.semilogy(get_real_data_axis(bin_start, bin_end) * 180 / np.pi, - get_real_data_values(bin_start, bin_end), - sim_result.axis(), sim_data, - ref_result.axis(), ref_data) + plt.semilogy( + get_real_data_axis(bin_start, bin_end) * 180 / np.pi, + get_real_data_values(bin_start, bin_end), sim_result.axis(), sim_data, + ref_result.axis(), ref_data) xlabel = ba.get_axes_labels(sim_result, ba.Axes.DEFAULT)[0] ylabel = "Intensity" plt.xlabel(xlabel, fontsize=16) plt.ylabel(ylabel, fontsize=16) plt.legend(['Experimental data', 'Simulation', 'Reference'], - loc='upper right', fontsize=16) + loc='upper right', + fontsize=16) plt.show() if __name__ == '__main__': fit_data = run_fitting() - ref_data = create_par_dict(3.78271438e+06, # beam intensity - 9.58009763e-04, # beam-to-sample width ratio - 2.30471294e-04, # beam angular divergence - 0.58721753, # oxide concentration - 1.25559347, # oxide thickness - 0.19281863) # roughness + ref_data = create_par_dict( + 3.78271438e+06, # beam intensity + 9.58009763e-04, # beam-to-sample width ratio + 2.30471294e-04, # beam angular divergence + 0.58721753, # oxide concentration + 1.25559347, # oxide thickness + 0.19281863) # roughness plot_result(run_simulation(fit_data), run_simulation(ref_data)) diff --git a/Examples/Python/fit61_Galaxi/fit_galaxi_data.py b/Examples/Python/fit61_Galaxi/fit_galaxi_data.py index f02b85a638485e91e4887371c57feb71990ab2ee..b50694c0ea77761723f2fdbaeff363b4469f7993 100644 --- a/Examples/Python/fit61_Galaxi/fit_galaxi_data.py +++ b/Examples/Python/fit61_Galaxi/fit_galaxi_data.py @@ -6,8 +6,8 @@ import bornagain as ba from bornagain import nm as nm from sample_builder import SampleBuilder -wavelength = 1.34*ba.angstrom -alpha_i = 0.463*ba.deg +wavelength = 1.34 * ba.angstrom +alpha_i = 0.463 * ba.deg # detector setup as given from instrument responsible pilatus_npx, pilatus_npy = 981, 1043 @@ -20,10 +20,10 @@ def create_detector(): """ Returns a model of the GALAXY detector """ - u0 = beam_xpos*pilatus_pixel_size # in mm - v0 = beam_ypos*pilatus_pixel_size # in mm - detector = ba.RectangularDetector(pilatus_npx, pilatus_npx*pilatus_pixel_size, - pilatus_npy, pilatus_npy*pilatus_pixel_size) + u0 = beam_xpos * pilatus_pixel_size # in mm + v0 = beam_ypos * pilatus_pixel_size # in mm + detector = ba.RectangularDetector(pilatus_npx, pilatus_npx * pilatus_pixel_size, + pilatus_npy, pilatus_npy * pilatus_pixel_size) detector.setPerpendicularToDirectBeam(detector_distance, u0, v0) return detector @@ -62,9 +62,9 @@ def run_fitting(): fit_objective.initPlot(10) params = ba.Parameters() - params.add("radius", 5.*nm, min=4.0, max=6.0, step=0.1*nm) + params.add("radius", 5. * nm, min=4.0, max=6.0, step=0.1 * nm) params.add("sigma", 0.55, min=0.2, max=0.8, step=0.01) - params.add("distance", 27.*nm, min=20.0, max=70.0) + params.add("distance", 27. * nm, min=20.0, max=70.0) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) diff --git a/Examples/Python/fit61_Galaxi/sample_builder.py b/Examples/Python/fit61_Galaxi/sample_builder.py index dffe9da447901f9a5ba9984e288e3ffb3eafde5f..9189516d30fe2fe2332b82e74d42b1bc44d4a8b4 100644 --- a/Examples/Python/fit61_Galaxi/sample_builder.py +++ b/Examples/Python/fit61_Galaxi/sample_builder.py @@ -13,13 +13,13 @@ class SampleBuilder: """ Init SampleBuilder with default sample parameters. """ - self.radius = 5.75*ba.nm + self.radius = 5.75 * ba.nm self.sigma = 0.4 - self.distance = 53.6*ba.nm - self.disorder = 10.5*ba.nm + self.distance = 53.6 * ba.nm + self.disorder = 10.5 * ba.nm self.kappa = 17.5 - self.ptfe_thickness = 22.1*ba.nm - self.hmdso_thickness = 18.5*ba.nm + self.ptfe_thickness = 22.1 * ba.nm + self.hmdso_thickness = 18.5 * ba.nm def create_sample(self, params): """ @@ -54,17 +54,17 @@ class SampleBuilder: sphere_ff = ba.FormFactorFullSphere(self.radius) sphere = ba.Particle(m_Ag, sphere_ff) - position = ba.kvector_t(0*ba.nm, 0*ba.nm,-1.0*self.hmdso_thickness) + position = ba.kvector_t(0 * ba.nm, 0 * ba.nm, -1.0 * self.hmdso_thickness) sphere.setPosition(position) ln_distr = ba.DistributionLogNormal(self.radius, self.sigma) par_distr = ba.ParameterDistribution( "/Particle/FullSphere/Radius", ln_distr, nparticles, nfwhm, - ba.RealLimits.limited(0.0, self.hmdso_thickness/2.0)) + ba.RealLimits.limited(0.0, self.hmdso_thickness / 2.0)) part_coll = ba.ParticleDistribution(sphere, par_distr) # interference function interference = ba.InterferenceFunctionRadialParaCrystal( - self.distance, 1e6*ba.nm) + self.distance, 1e6 * ba.nm) interference.setKappa(self.kappa) interference.setDomainSize(20000.0) pdf = ba.FTDistribution1DGauss(self.disorder) @@ -77,8 +77,8 @@ class SampleBuilder: layout.setTotalParticleSurfaceDensity(1) # roughness - r_ptfe = ba.LayerRoughness(2.3*ba.nm, 0.3, 5.0*ba.nm) - r_hmdso = ba.LayerRoughness(1.1*ba.nm, 0.3, 5.0*ba.nm) + r_ptfe = ba.LayerRoughness(2.3 * ba.nm, 0.3, 5.0 * ba.nm) + r_hmdso = ba.LayerRoughness(1.1 * ba.nm, 0.3, 5.0 * ba.nm) # layers vacuum_layer = ba.Layer(m_vacuum) diff --git a/Examples/Python/sim01_Particles/AllFormFactorsAvailable.py b/Examples/Python/sim01_Particles/AllFormFactorsAvailable.py index 43a6df116f31a5ebf7894753243cdd6b2ea31f27..d6bf4e26d945112025886cd900564efd6ea65335 100644 --- a/Examples/Python/sim01_Particles/AllFormFactorsAvailable.py +++ b/Examples/Python/sim01_Particles/AllFormFactorsAvailable.py @@ -9,14 +9,13 @@ from matplotlib import pyplot as plt phi_min, phi_max = -2.0, 2.0 alpha_min, alpha_max = 0.0, 2.0 - formfactors = [ - ba.FormFactorAnisoPyramid(20.0, 16.0, 13.0, 60.0*deg), + ba.FormFactorAnisoPyramid(20.0, 16.0, 13.0, 60.0 * deg), ba.FormFactorBox(20.0, 16.0, 13.0), ba.FormFactorCantellatedCube(15.0, 6.0), - ba.FormFactorCone(10.0, 13.0, 60.0*deg), - ba.FormFactorCone6(10.0, 13.0, 60.0*deg), - ba.FormFactorCuboctahedron(20.0, 13.0, 0.7, 60.0*deg), + ba.FormFactorCone(10.0, 13.0, 60.0 * deg), + ba.FormFactorCone6(10.0, 13.0, 60.0 * deg), + ba.FormFactorCuboctahedron(20.0, 13.0, 0.7, 60.0 * deg), ba.FormFactorCylinder(8.0, 16.0), ba.FormFactorDodecahedron(5.0), ba.FormFactorEllipsoidalCylinder(8.0, 13.0, 16.0), @@ -26,10 +25,10 @@ formfactors = [ ba.FormFactorIcosahedron(8.0), ba.FormFactorPrism3(10.0, 13.0), ba.FormFactorPrism6(5.0, 11.0), - ba.FormFactorPyramid(18.0, 13.0, 60.0*deg), + ba.FormFactorPyramid(18.0, 13.0, 60.0 * deg), ba.FormFactorCosineRippleBox(27.0, 20.0, 14.0), ba.FormFactorSawtoothRippleBox(36.0, 25.0, 14.0, 3.0), - ba.FormFactorTetrahedron(15.0, 6.0, 60.0*deg), + ba.FormFactorTetrahedron(15.0, 6.0, 60.0 * deg), ba.FormFactorTruncatedCube(15.0, 6.0), ba.FormFactorTruncatedSphere(5.0, 7.0, 0), ba.FormFactorTruncatedSpheroid(7.5, 9.0, 1.2, 0), @@ -62,9 +61,9 @@ def get_simulation(): Returns GISAXS simulation with standard beam and detector. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, phi_min*deg, phi_max*deg, - 100, alpha_min*deg, alpha_max*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, phi_min * deg, phi_max * deg, 100, + alpha_min * deg, alpha_max * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation @@ -95,17 +94,25 @@ def run_simulation(): result = simulate(ff) # showing the result - plt.subplot(5, 5, nplot+1) + plt.subplot(5, 5, nplot + 1) plt.subplots_adjust(wspace=0.3, hspace=0.3) - ba.plot_colormap(result, xlabel="", ylabel="", zlabel="", - cmap='jet', aspect='auto') + ba.plot_colormap(result, + xlabel="", + ylabel="", + zlabel="", + cmap='jet', + aspect='auto') plt.tick_params(axis='both', which='major', labelsize=8) plt.tick_params(axis='both', which='minor', labelsize=6) - plt.xticks(numpy.arange(phi_min, phi_max+0.0001, 1.0)) - plt.text(-0.1, 2.15, name, horizontalalignment='center', - verticalalignment='center', fontsize=9) + plt.xticks(numpy.arange(phi_min, phi_max + 0.0001, 1.0)) + plt.text(-0.1, + 2.15, + name, + horizontalalignment='center', + verticalalignment='center', + fontsize=9) if __name__ == '__main__': diff --git a/Examples/Python/sim01_Particles/CylindersAndPrisms.py b/Examples/Python/sim01_Particles/CylindersAndPrisms.py index 15acb9b6aec9e54fd902f4526406bd29eeef9b83..32cd6d2c3d72f9c3f64e4f582edb32ecdaac5e36 100644 --- a/Examples/Python/sim01_Particles/CylindersAndPrisms.py +++ b/Examples/Python/sim01_Particles/CylindersAndPrisms.py @@ -15,9 +15,9 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) - prism_ff = ba.FormFactorPrism3(10*nm, 5*nm) + prism_ff = ba.FormFactorPrism3(10 * nm, 5 * nm) prism = ba.Particle(m_particle, prism_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 0.5) @@ -41,9 +41,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim01_Particles/CylindersInBA.py b/Examples/Python/sim01_Particles/CylindersInBA.py index 9c43f4c7d73085fed32363bc94f9f7e313c24be9..0eda8e8d66a9c7b0a51181f304034f3a50a38cd0 100644 --- a/Examples/Python/sim01_Particles/CylindersInBA.py +++ b/Examples/Python/sim01_Particles/CylindersInBA.py @@ -15,7 +15,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -33,9 +33,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim01_Particles/CylindersInDWBA.py b/Examples/Python/sim01_Particles/CylindersInDWBA.py index 1563aef2afe9de3c00b88b4ed2498d64e76c4157..e0c8d7aa79acab20f29ba32edf3a9392dd3d429e 100644 --- a/Examples/Python/sim01_Particles/CylindersInDWBA.py +++ b/Examples/Python/sim01_Particles/CylindersInDWBA.py @@ -15,7 +15,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -35,9 +35,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim01_Particles/CylindersWithSizeDistribution.py b/Examples/Python/sim01_Particles/CylindersWithSizeDistribution.py index c268ad94e0be3a9b1e71595a65f0209ce7ba4e27..76dd916f3f7c7ed27a8b1498d0d50e98257071b1 100644 --- a/Examples/Python/sim01_Particles/CylindersWithSizeDistribution.py +++ b/Examples/Python/sim01_Particles/CylindersWithSizeDistribution.py @@ -14,20 +14,20 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # cylindrical particle - radius = 5*nm + radius = 5 * nm height = radius cylinder_ff = ba.FormFactorCylinder(radius, height) cylinder = ba.Particle(m_particle, cylinder_ff) # collection of particles with size distribution nparticles = 100 - sigma = 0.2*radius + sigma = 0.2 * radius gauss_distr = ba.DistributionGaussian(radius, sigma) sigma_factor = 2.0 - par_distr = ba.ParameterDistribution( - "/Particle/Cylinder/Radius", gauss_distr, nparticles, sigma_factor) + par_distr = ba.ParameterDistribution("/Particle/Cylinder/Radius", gauss_distr, + nparticles, sigma_factor) # by uncommenting the line below, the height of the cylinders # can be scaled proportionally to the radius: # par_distr.linkParameter("/Particle/Cylinder/Height") @@ -49,9 +49,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, 0.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, 0.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim01_Particles/RotatedPyramids.py b/Examples/Python/sim01_Particles/RotatedPyramids.py index 11e878ad70505259d9e7430598f2797b5aa2595c..ddfa36b47b009226fb7dd3180694ff712d490d2c 100644 --- a/Examples/Python/sim01_Particles/RotatedPyramids.py +++ b/Examples/Python/sim01_Particles/RotatedPyramids.py @@ -15,12 +15,11 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - pyramid_ff = ba.FormFactorPyramid(10*nm, 5*nm, 54.73*deg) + pyramid_ff = ba.FormFactorPyramid(10 * nm, 5 * nm, 54.73 * deg) pyramid = ba.Particle(m_particle, pyramid_ff) - transform = ba.RotationZ(45.*deg) + transform = ba.RotationZ(45. * deg) particle_layout = ba.ParticleLayout() - particle_layout.addParticle( - pyramid, 1.0, ba.kvector_t(0.0, 0.0, 0.0), transform) + particle_layout.addParticle(pyramid, 1.0, ba.kvector_t(0.0, 0.0, 0.0), transform) vacuum_layer = ba.Layer(m_vacuum) vacuum_layer.addLayout(particle_layout) @@ -37,9 +36,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim01_Particles/TwoTypesOfCylindersWithSizeDistribution.py b/Examples/Python/sim01_Particles/TwoTypesOfCylindersWithSizeDistribution.py index ca9c7f0aa246435212550ba4b9a7c6ebbc2896fc..dc02c404264251f910a5af060ab8231c14e192bb 100644 --- a/Examples/Python/sim01_Particles/TwoTypesOfCylindersWithSizeDistribution.py +++ b/Examples/Python/sim01_Particles/TwoTypesOfCylindersWithSizeDistribution.py @@ -15,9 +15,9 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles #1 - radius1 = 5.0*nm + radius1 = 5.0 * nm height1 = radius1 - sigma1 = radius1*0.2 + sigma1 = radius1 * 0.2 cylinder_ff1 = ba.FormFactorCylinder(radius1, height1) cylinder1 = ba.Particle(m_particle, cylinder_ff1) @@ -30,22 +30,22 @@ def get_sample(): # limits will assure, that generated Radius'es are >=0 limits = ba.RealLimits.nonnegative() - par_distr1 = ba.ParameterDistribution( - "/Particle/Cylinder/Radius", gauss_distr1, nparticles, sigma_factor, limits) + par_distr1 = ba.ParameterDistribution("/Particle/Cylinder/Radius", gauss_distr1, + nparticles, sigma_factor, limits) part_coll1 = ba.ParticleDistribution(cylinder1, par_distr1) # collection of particles #2 - radius2 = 10.0*nm + radius2 = 10.0 * nm height2 = radius2 - sigma2 = radius2*0.02 + sigma2 = radius2 * 0.02 cylinder_ff2 = ba.FormFactorCylinder(radius2, height2) cylinder2 = ba.Particle(m_particle, cylinder_ff2) gauss_distr2 = ba.DistributionGaussian(radius2, sigma2) - par_distr2 = ba.ParameterDistribution( - "/Particle/Cylinder/Radius", gauss_distr2, nparticles, sigma_factor, limits) + par_distr2 = ba.ParameterDistribution("/Particle/Cylinder/Radius", gauss_distr2, + nparticles, sigma_factor, limits) part_coll2 = ba.ParticleDistribution(cylinder2, par_distr2) # assembling the sample @@ -66,9 +66,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, 0.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, 0.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim02_Complexes/BiMaterialCylinders.py b/Examples/Python/sim02_Complexes/BiMaterialCylinders.py index 63e44dee9a2e9a8430dd1aa124f9f6a26fcbf2dc..38979c0ceaea9b15ecff6f33eea94de465bd857b 100644 --- a/Examples/Python/sim02_Complexes/BiMaterialCylinders.py +++ b/Examples/Python/sim02_Complexes/BiMaterialCylinders.py @@ -6,13 +6,15 @@ import bornagain as ba from bornagain import deg, angstrom, nm -def get_composition(top_material, bottom_material, - top_height=4.0, bottom_height=10.0): +def get_composition(top_material, + bottom_material, + top_height=4.0, + bottom_height=10.0): """ Returns cylindrical particle made of two different materials. """ - cylinder_radius = 10*nm + cylinder_radius = 10 * nm topPart = ba.Particle(top_material, ba.FormFactorCylinder(cylinder_radius, top_height)) @@ -41,7 +43,7 @@ def get_sample(): # collection of particles composition = get_composition(m_top_part, m_bottom_part) - shift = 10.0*nm + shift = 10.0 * nm composition.setPosition(0, 0, -shift) # will be shifted below interface particle_layout = ba.ParticleLayout() @@ -64,9 +66,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1.0e+08) return simulation diff --git a/Examples/Python/sim02_Complexes/CoreShellNanoparticles.py b/Examples/Python/sim02_Complexes/CoreShellNanoparticles.py index 5c62ecb333cf6f4fbee8a497282fdfcdedd2736d..ae1fe3aa5f826b7dc98e1d052b6bb7587e231bb2 100644 --- a/Examples/Python/sim02_Complexes/CoreShellNanoparticles.py +++ b/Examples/Python/sim02_Complexes/CoreShellNanoparticles.py @@ -10,13 +10,13 @@ def get_sample(): Returns a sample with box-shaped core-shell particles on a substrate. """ # defining materials - m_vacuum = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0 ) - m_shell = ba.HomogeneousMaterial("Shell", 1e-4, 2e-8 ) - m_core = ba.HomogeneousMaterial("Core", 6e-5, 2e-8 ) + m_vacuum = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0) + m_shell = ba.HomogeneousMaterial("Shell", 1e-4, 2e-8) + m_core = ba.HomogeneousMaterial("Core", 6e-5, 2e-8) # collection of particles - parallelepiped1_ff = ba.FormFactorBox(16*nm, 16*nm, 8*nm) - parallelepiped2_ff = ba.FormFactorBox(12*nm, 12*nm, 7*nm) + parallelepiped1_ff = ba.FormFactorBox(16 * nm, 16 * nm, 8 * nm) + parallelepiped2_ff = ba.FormFactorBox(12 * nm, 12 * nm, 7 * nm) shell_particle = ba.Particle(m_shell, parallelepiped1_ff) core_particle = ba.Particle(m_core, parallelepiped2_ff) core_position = ba.kvector_t(0.0, 0.0, 0.0) @@ -41,9 +41,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -1.0*deg, 1.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -1.0 * deg, 1.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim02_Complexes/CustomFormFactor.py b/Examples/Python/sim02_Complexes/CustomFormFactor.py index 68e31dff9cb0d59c15c28c4cad8b69c6687c9723..0c9a1cf146d16cc7138b76b9394447a447e44f2d 100644 --- a/Examples/Python/sim02_Complexes/CustomFormFactor.py +++ b/Examples/Python/sim02_Complexes/CustomFormFactor.py @@ -10,7 +10,7 @@ def sinc(x): if abs(x) == 0: return 1. else: - return cmath.sin(x)/x + return cmath.sin(x) / x class CustomFormFactor(ba.IBornFF): @@ -36,9 +36,9 @@ class CustomFormFactor(ba.IBornFF): return cloned_ff def evaluate_for_q(self, q): - qzhH = 0.5*q.z()*self.H - qxhL = 0.5*q.x()*self.L - qyhL = 0.5*q.y()*self.L + qzhH = 0.5 * q.z() * self.H + qxhL = 0.5 * q.x() * self.L + qyhL = 0.5 * q.y() * self.L return 0.5*self.H*self.L**2*cmath.exp(complex(0., 1.)*qzhH)*\ sinc(qzhH)*(sinc(0.5*qyhL)*(sinc(qxhL)-0.5*sinc(0.5*qxhL))+\ sinc(0.5*qxhL)*sinc(qyhL)) @@ -54,7 +54,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - ff = CustomFormFactor(20.0*nm, 15.0*nm) + ff = CustomFormFactor(20.0 * nm, 15.0 * nm) particle = ba.Particle(m_particle, ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(particle, 1.0) @@ -77,9 +77,9 @@ def get_simulation(): """ simulation = ba.GISASSimulation() simulation.getOptions().setNumberOfThreads(-1) - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim02_Complexes/HexagonalLatticesWithBasis.py b/Examples/Python/sim02_Complexes/HexagonalLatticesWithBasis.py index 1c2298a929dd8fa9d12de19d36ab40a9ce9e88f0..746b99ec6655113fd14e2ae1dfbecf83da0fe0e9 100644 --- a/Examples/Python/sim02_Complexes/HexagonalLatticesWithBasis.py +++ b/Examples/Python/sim02_Complexes/HexagonalLatticesWithBasis.py @@ -15,20 +15,20 @@ def get_sample(): m_substrate = ba.HomogeneousMaterial("Substrate", 6e-6, 2e-8) m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) - radius = 10.0*nm + radius = 10.0 * nm sphere_ff = ba.FormFactorFullSphere(radius) sphere = ba.Particle(m_particle, sphere_ff) particle_layout = ba.ParticleLayout() pos0 = ba.kvector_t(0.0, 0.0, 0.0) - pos1 = ba.kvector_t(radius, radius, numpy.sqrt(3.0)*radius) + pos1 = ba.kvector_t(radius, radius, numpy.sqrt(3.0) * radius) basis = ba.ParticleComposition() basis.addParticles(sphere, [pos0, pos1]) particle_layout.addParticle(basis) interference = ba.InterferenceFunction2DLattice( - ba.HexagonalLattice2D(radius*2.0, 0*deg)) - pdf = ba.FTDecayFunction2DCauchy(10*nm, 10*nm, 0) + ba.HexagonalLattice2D(radius * 2.0, 0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(10 * nm, 10 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -47,9 +47,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -1.0*deg, 1.0*deg, - 200, 0.0*deg, 1.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -1.0 * deg, 1.0 * deg, 200, 0.0 * deg, + 1.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim02_Complexes/LargeParticlesFormFactor.py b/Examples/Python/sim02_Complexes/LargeParticlesFormFactor.py index b2bbc6112b9121e670b7f095b8aa6d3d0d072a03..584ad11829d9d474af1ea6940b3c8285ca1873ac 100644 --- a/Examples/Python/sim02_Complexes/LargeParticlesFormFactor.py +++ b/Examples/Python/sim02_Complexes/LargeParticlesFormFactor.py @@ -10,8 +10,8 @@ import bornagain as ba from bornagain import deg, angstrom, nm from matplotlib import pyplot as plt -default_cylinder_radius = 10*nm -default_cylinder_height = 20*nm +default_cylinder_radius = 10 * nm +default_cylinder_height = 20 * nm def get_sample(cylinder_radius, cylinder_height): @@ -45,9 +45,9 @@ def get_simulation(integration_flag): If integration_flag=True, the simulation will integrate over detector bins. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.getOptions().setMonteCarloIntegration(integration_flag, 50) simulation.setTerminalProgressMonitor() return simulation @@ -62,42 +62,57 @@ def run_simulation(): fig = plt.figure(figsize=(12.80, 10.24)) # conditions to define cylinders scale factor and integration flag - conditions = [ - {'title': "Small cylinders, analytical calculations", - 'scale': 1, 'integration': False, 'zmin': 1e-5, 'zmax': 1e2}, - - {'title': "Small cylinders, Monte-Carlo integration", - 'scale': 1, 'integration': True, 'zmin': 1e-5, 'zmax': 1e2}, - - {'title': "Large cylinders, analytical calculations", - 'scale': 100, 'integration': False, 'zmin': 1e-5, 'zmax': 1e10}, - - {'title': "Large cylinders, Monte-Carlo integration", - 'scale': 100, 'integration': True, 'zmin': 1e-5, 'zmax': 1e10} - ] + conditions = [{ + 'title': "Small cylinders, analytical calculations", + 'scale': 1, + 'integration': False, + 'zmin': 1e-5, + 'zmax': 1e2 + }, { + 'title': "Small cylinders, Monte-Carlo integration", + 'scale': 1, + 'integration': True, + 'zmin': 1e-5, + 'zmax': 1e2 + }, { + 'title': "Large cylinders, analytical calculations", + 'scale': 100, + 'integration': False, + 'zmin': 1e-5, + 'zmax': 1e10 + }, { + 'title': "Large cylinders, Monte-Carlo integration", + 'scale': 100, + 'integration': True, + 'zmin': 1e-5, + 'zmax': 1e10 + }] # run simulation 4 times and plot results for i_plot, condition in enumerate(conditions): scale = condition['scale'] integration_flag = condition['integration'] - sample = get_sample(default_cylinder_radius*scale, - default_cylinder_height*scale) + sample = get_sample(default_cylinder_radius * scale, + default_cylinder_height * scale) simulation = get_simulation(integration_flag) simulation.setSample(sample) simulation.runSimulation() result = simulation.result() # plotting results - plt.subplot(2, 2, i_plot+1) + plt.subplot(2, 2, i_plot + 1) plt.subplots_adjust(wspace=0.3, hspace=0.3) zmin = condition['zmin'] zmax = condition['zmax'] ba.plot_colormap(result, zmin=zmin, zmax=zmax, cmap='jet', aspect='auto') - plt.text(0.0, 2.1, conditions[i_plot]['title'], - horizontalalignment='center', verticalalignment='center', + plt.text(0.0, + 2.1, + conditions[i_plot]['title'], + horizontalalignment='center', + verticalalignment='center', fontsize=12) diff --git a/Examples/Python/sim02_Complexes/MesoCrystal.py b/Examples/Python/sim02_Complexes/MesoCrystal.py index 857aa322b49142ee77059a220f40cc26790a6617..f7079719c71f02c2d4748077edf8366ad6b2e6d3 100644 --- a/Examples/Python/sim02_Complexes/MesoCrystal.py +++ b/Examples/Python/sim02_Complexes/MesoCrystal.py @@ -21,7 +21,7 @@ def get_sample(): lattice = ba.Lattice3D(lattice_basis_1, lattice_basis_2, lattice_basis_3) # spherical particle that forms the base of the mesocrystal - sphere_ff = ba.FormFactorFullSphere(2*nm) + sphere_ff = ba.FormFactorFullSphere(2 * nm) sphere = ba.Particle(m_particle, sphere_ff) # crystal structure @@ -49,9 +49,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim02_Complexes/ParticlesCrossingInterface.py b/Examples/Python/sim02_Complexes/ParticlesCrossingInterface.py index c9cb50390a330e13f640388143418b8ba25a9b1c..26d9abab1829bc81342f434bce1f812d27748487 100644 --- a/Examples/Python/sim02_Complexes/ParticlesCrossingInterface.py +++ b/Examples/Python/sim02_Complexes/ParticlesCrossingInterface.py @@ -32,14 +32,14 @@ def get_sample(): m_substrate = ba.HomogeneousMaterial("Substrate", 6e-6, 2e-8) m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) - shift_down = 3*nm + shift_down = 3 * nm # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) cylinder.setPosition(0, 0, -shift_down) - prism_ff = ba.FormFactorPrism3(10*nm, 5*nm) + prism_ff = ba.FormFactorPrism3(10 * nm, 5 * nm) prism = ba.Particle(m_particle, prism_ff) prism.setPosition(0, 0, -shift_down) @@ -65,9 +65,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, phi_min*deg, phi_max*deg, - 100, alpha_min*deg, alpha_max*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, phi_min * deg, phi_max * deg, 100, + alpha_min * deg, alpha_max * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/ApproximationDA.py b/Examples/Python/sim03_Structures/ApproximationDA.py index 8933892ba41e1bf6ace972bf1e47b7f8c8a3d5c6..86254096993c72371b61efc8f95b3cd8e096e439 100644 --- a/Examples/Python/sim03_Structures/ApproximationDA.py +++ b/Examples/Python/sim03_Structures/ApproximationDA.py @@ -15,20 +15,19 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # cylindrical particle 1 - radius1 = 5*nm + radius1 = 5 * nm height1 = radius1 cylinder_ff1 = ba.FormFactorCylinder(radius1, height1) cylinder1 = ba.Particle(m_particle, cylinder_ff1) # cylindrical particle 2 - radius2 = 8*nm + radius2 = 8 * nm height2 = radius2 cylinder_ff2 = ba.FormFactorCylinder(radius2, height2) cylinder2 = ba.Particle(m_particle, cylinder_ff2) # interference function - interference = ba.InterferenceFunctionRadialParaCrystal( - 18.0*nm, 1e3*nm) + interference = ba.InterferenceFunctionRadialParaCrystal(18.0 * nm, 1e3 * nm) pdf = ba.FTDistribution1DGauss(3 * nm) interference.setProbabilityDistribution(pdf) @@ -52,9 +51,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, 0.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, 0.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/ApproximationLMA.py b/Examples/Python/sim03_Structures/ApproximationLMA.py index bff8e67d92be2b247326de9c27ca38c4893f1124..e30d648732bd96e02d1c788354154a1f76ede220 100644 --- a/Examples/Python/sim03_Structures/ApproximationLMA.py +++ b/Examples/Python/sim03_Structures/ApproximationLMA.py @@ -15,26 +15,24 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # cylindrical particle 1 - radius1 = 5*nm + radius1 = 5 * nm height1 = radius1 cylinder_ff1 = ba.FormFactorCylinder(radius1, height1) cylinder1 = ba.Particle(m_particle, cylinder_ff1) # cylindrical particle 2 - radius2 = 8*nm + radius2 = 8 * nm height2 = radius2 cylinder_ff2 = ba.FormFactorCylinder(radius2, height2) cylinder2 = ba.Particle(m_particle, cylinder_ff2) # interference function1 - interference1 = ba.InterferenceFunctionRadialParaCrystal( - 16.8*nm, 1e3*nm) + interference1 = ba.InterferenceFunctionRadialParaCrystal(16.8 * nm, 1e3 * nm) pdf = ba.FTDistribution1DGauss(3 * nm) interference1.setProbabilityDistribution(pdf) # interference function2 - interference2 = ba.InterferenceFunctionRadialParaCrystal( - 22.8*nm, 1e3*nm) + interference2 = ba.InterferenceFunctionRadialParaCrystal(22.8 * nm, 1e3 * nm) interference2.setProbabilityDistribution(pdf) # assembling the sample @@ -61,9 +59,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, 0.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, 0.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/ApproximationSSCA.py b/Examples/Python/sim03_Structures/ApproximationSSCA.py index 1d6389d713b400b8156ae489b61c2a72d20fa5e8..9b4111580a80e2faa6e86215bdeb5db861a2521c 100644 --- a/Examples/Python/sim03_Structures/ApproximationSSCA.py +++ b/Examples/Python/sim03_Structures/ApproximationSSCA.py @@ -15,19 +15,19 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # cylindrical particle 1 - radius1 = 5*nm + radius1 = 5 * nm height1 = radius1 cylinder_ff1 = ba.FormFactorCylinder(radius1, height1) cylinder1 = ba.Particle(m_particle, cylinder_ff1) # cylindrical particle 2 - radius2 = 8*nm + radius2 = 8 * nm height2 = radius2 cylinder_ff2 = ba.FormFactorCylinder(radius2, height2) cylinder2 = ba.Particle(m_particle, cylinder_ff2) # interference function - interference = ba.InterferenceFunctionRadialParaCrystal(18.0*nm, 1e3*nm) + interference = ba.InterferenceFunctionRadialParaCrystal(18.0 * nm, 1e3 * nm) pdf = ba.FTDistribution1DGauss(3 * nm) interference.setProbabilityDistribution(pdf) interference.setKappa(1.0) @@ -52,9 +52,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, 0.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, 0.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/CosineRipplesAtRectLattice.py b/Examples/Python/sim03_Structures/CosineRipplesAtRectLattice.py index 5f482c78cae4be965e75378431bf526de6e6ff48..cf9250dff80af6013acd41ac3bc10f145860c98f 100644 --- a/Examples/Python/sim03_Structures/CosineRipplesAtRectLattice.py +++ b/Examples/Python/sim03_Structures/CosineRipplesAtRectLattice.py @@ -17,15 +17,16 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - ff = ba.FormFactorCosineRippleBox(100*nm, 20*nm, 4*nm) + ff = ba.FormFactorCosineRippleBox(100 * nm, 20 * nm, 4 * nm) particle = ba.Particle(m_particle, ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(particle, 1.0) interference = ba.InterferenceFunction2DLattice( - ba.BasicLattice2D(200.0*nm, 50.0*nm, 90.0*deg, 0.0*deg)) - pdf = ba.FTDecayFunction2DCauchy(1000.*nm/2./numpy.pi, 100.*nm/2./numpy.pi, 0) + ba.BasicLattice2D(200.0 * nm, 50.0 * nm, 90.0 * deg, 0.0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(1000. * nm / 2. / numpy.pi, + 100. * nm / 2. / numpy.pi, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -45,9 +46,9 @@ def get_simulation(): characterizing the input beam and output detector """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.5*deg, 1.5*deg, - 100, 0.0*deg, 2.5*deg) - simulation.setBeamParameters(1.6*angstrom, 0.3*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.5 * deg, 1.5 * deg, 100, 0.0 * deg, + 2.5 * deg) + simulation.setBeamParameters(1.6 * angstrom, 0.3 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/Interference1DLattice.py b/Examples/Python/sim03_Structures/Interference1DLattice.py index 20d98c6b4fdc6287278d2bc48918a24617afd82d..19c4e03e78cdf511bc83b7c2d2a4be14906d6739 100644 --- a/Examples/Python/sim03_Structures/Interference1DLattice.py +++ b/Examples/Python/sim03_Structures/Interference1DLattice.py @@ -7,7 +7,7 @@ import bornagain as ba from bornagain import deg, angstrom, nm -def get_sample(lattice_rotation_angle=45*deg): +def get_sample(lattice_rotation_angle=45 * deg): """ Returns a sample with a grating on a substrate, modelled by very long boxes forming a 1D lattice with Cauchy correlations. @@ -17,12 +17,12 @@ def get_sample(lattice_rotation_angle=45*deg): m_substrate = ba.HomogeneousMaterial("Substrate", 6e-6, 2e-8) m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) - box_length, box_width, box_height = 10*nm, 10000*nm, 10*nm - lattice_length = 30*nm + box_length, box_width, box_height = 10 * nm, 10000 * nm, 10 * nm + lattice_length = 30 * nm # collection of particles - interference = ba.InterferenceFunction1DLattice( - lattice_length, lattice_rotation_angle) + interference = ba.InterferenceFunction1DLattice(lattice_length, + lattice_rotation_angle) pdf = ba.FTDecayFunction1DCauchy(1000.0) interference.setDecayFunction(pdf) @@ -30,8 +30,8 @@ def get_sample(lattice_rotation_angle=45*deg): box = ba.Particle(m_particle, box_ff) particle_layout = ba.ParticleLayout() - particle_layout.addParticle( - box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), ba.RotationZ(lattice_rotation_angle)) + particle_layout.addParticle(box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), + ba.RotationZ(lattice_rotation_angle)) particle_layout.setInterferenceFunction(interference) # assembling the sample @@ -50,9 +50,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -1.0*deg, 1.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -1.0 * deg, 1.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.getOptions().setMonteCarloIntegration(True, 100) return simulation diff --git a/Examples/Python/sim03_Structures/Interference1DRadialParaCrystal.py b/Examples/Python/sim03_Structures/Interference1DRadialParaCrystal.py index 7a38f018a40d82a602a221cc34e8d651d1a1feb8..184727e7e2689abbff06904590addf296e70990c 100644 --- a/Examples/Python/sim03_Structures/Interference1DRadialParaCrystal.py +++ b/Examples/Python/sim03_Structures/Interference1DRadialParaCrystal.py @@ -18,11 +18,10 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) - interference = ba.InterferenceFunctionRadialParaCrystal( - 20.0*nm, 1e3*nm) + interference = ba.InterferenceFunctionRadialParaCrystal(20.0 * nm, 1e3 * nm) pdf = ba.FTDistribution1DGauss(7 * nm) interference.setProbabilityDistribution(pdf) @@ -47,9 +46,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/Interference2DCenteredSquareLattice.py b/Examples/Python/sim03_Structures/Interference2DCenteredSquareLattice.py index 7f8399e20aa156732952600b7146855d474568cc..ef88a994f4e5865b885c5c55713063938c2aa4a3 100644 --- a/Examples/Python/sim03_Structures/Interference2DCenteredSquareLattice.py +++ b/Examples/Python/sim03_Structures/Interference2DCenteredSquareLattice.py @@ -17,15 +17,15 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - interference = ba.InterferenceFunction2DLattice(ba.SquareLattice2D(25.0*nm, 0)) - pdf = ba.FTDecayFunction2DCauchy(300.0*nm/2.0/numpy.pi, - 100.0*nm/2.0/numpy.pi, 0) + interference = ba.InterferenceFunction2DLattice(ba.SquareLattice2D(25.0 * nm, 0)) + pdf = ba.FTDecayFunction2DCauchy(300.0 * nm / 2.0 / numpy.pi, + 100.0 * nm / 2.0 / numpy.pi, 0) interference.setDecayFunction(pdf) particle_layout = ba.ParticleLayout() position1 = ba.kvector_t(0.0, 0.0, 0.0) - position2 = ba.kvector_t(12.5*nm, 12.5*nm, 0.0) - cylinder_ff = ba.FormFactorCylinder(3.*nm, 3.*nm) + position2 = ba.kvector_t(12.5 * nm, 12.5 * nm, 0.0) + cylinder_ff = ba.FormFactorCylinder(3. * nm, 3. * nm) cylinder = ba.Particle(m_particle, cylinder_ff) basis = ba.ParticleComposition() basis.addParticles(cylinder, [position1, position2]) @@ -50,9 +50,9 @@ def get_simulation(): Create and return GISAS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/Interference2DLatticeSumOfRotated.py b/Examples/Python/sim03_Structures/Interference2DLatticeSumOfRotated.py index 6e5f5ba565290c68a090b09cdd06775872bcea65..3eb28944c96279094331aea5818483be2d95b893 100644 --- a/Examples/Python/sim03_Structures/Interference2DLatticeSumOfRotated.py +++ b/Examples/Python/sim03_Structures/Interference2DLatticeSumOfRotated.py @@ -18,12 +18,12 @@ def get_sample(): p_interference_function = \ ba.InterferenceFunction2DLattice(ba.SquareLattice2D(25.0*nm, 0)) - pdf = ba.FTDecayFunction2DCauchy(300.0*nm/2.0/numpy.pi, - 100.0*nm/2.0/numpy.pi, 0) + pdf = ba.FTDecayFunction2DCauchy(300.0 * nm / 2.0 / numpy.pi, + 100.0 * nm / 2.0 / numpy.pi, 0) p_interference_function.setDecayFunction(pdf) particle_layout = ba.ParticleLayout() - ff = ba.FormFactorCylinder(3.0*nm, 3.0*nm) + ff = ba.FormFactorCylinder(3.0 * nm, 3.0 * nm) position = ba.kvector_t(0.0, 0.0, 0.0) cylinder = ba.Particle(m_particle, ff.clone()) cylinder.setPosition(position) @@ -44,14 +44,14 @@ def get_simulation(): Assigns additional distribution to lattice rotation angle. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, 0.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setSample(get_sample()) - xi_min = 0.0*deg - xi_max = 240.0*deg + xi_min = 0.0 * deg + xi_max = 240.0 * deg xi_distr = ba.DistributionGate(xi_min, xi_max) # assigns distribution with 3 equidistant points to lattice rotation angle diff --git a/Examples/Python/sim03_Structures/Interference2DParaCrystal.py b/Examples/Python/sim03_Structures/Interference2DParaCrystal.py index ffee0d01b04cad63b9dc0fc892922634b0cf76fd..ca20c3529e41b51276ef6baf815059e737bf9895 100644 --- a/Examples/Python/sim03_Structures/Interference2DParaCrystal.py +++ b/Examples/Python/sim03_Structures/Interference2DParaCrystal.py @@ -14,13 +14,13 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(4*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(4 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) interference = ba.InterferenceFunction2DParaCrystal( - ba.SquareLattice2D(10.0*nm), 0.0, 20.0*micrometer, 20.0*micrometer) + ba.SquareLattice2D(10.0 * nm), 0.0, 20.0 * micrometer, 20.0 * micrometer) interference.setIntegrationOverXi(True) - pdf = ba.FTDistribution2DCauchy(1.0*nm, 1.0*nm, 0) + pdf = ba.FTDistribution2DCauchy(1.0 * nm, 1.0 * nm, 0) interference.setProbabilityDistributions(pdf, pdf) particle_layout = ba.ParticleLayout() @@ -47,9 +47,9 @@ def get_simulation(): """ simulation = ba.GISASSimulation() # coarse grid because this simulation takes rather long - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/Interference2DRotatedSquareLattice.py b/Examples/Python/sim03_Structures/Interference2DRotatedSquareLattice.py index e0f43a4beef0e44049a922d3c17d3cfe8e670946..e0d6655ed7eb4c6d902772dca6dbf6c1bfa5e0d9 100644 --- a/Examples/Python/sim03_Structures/Interference2DRotatedSquareLattice.py +++ b/Examples/Python/sim03_Structures/Interference2DRotatedSquareLattice.py @@ -17,12 +17,13 @@ def get_sample(): # collection of particles interference = ba.InterferenceFunction2DLattice( - ba.SquareLattice2D(25.0*nm, 30.0*deg)) - pdf = ba.FTDecayFunction2DCauchy(300.0*nm/2.0/numpy.pi, 100.0*nm/2.0/numpy.pi, 0) - pdf.setParameterValue("Gamma", 30.0*deg) + ba.SquareLattice2D(25.0 * nm, 30.0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(300.0 * nm / 2.0 / numpy.pi, + 100.0 * nm / 2.0 / numpy.pi, 0) + pdf.setParameterValue("Gamma", 30.0 * deg) interference.setDecayFunction(pdf) - cylinder_ff = ba.FormFactorCylinder(3.*nm, 3.*nm) + cylinder_ff = ba.FormFactorCylinder(3. * nm, 3. * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder) @@ -44,9 +45,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/Interference2DSquareFiniteLattice.py b/Examples/Python/sim03_Structures/Interference2DSquareFiniteLattice.py index 5e882bbf4d5c95f0b46dc8aef08afd32f7d42d44..75e4ddff0b9a40f98abcc0746f7f51a0b2529029 100644 --- a/Examples/Python/sim03_Structures/Interference2DSquareFiniteLattice.py +++ b/Examples/Python/sim03_Structures/Interference2DSquareFiniteLattice.py @@ -17,10 +17,10 @@ def get_sample(): # collection of particles interference = ba.InterferenceFunctionFinite2DLattice( - ba.SquareLattice2D(25.0*nm, 0.0), 40, 40) + ba.SquareLattice2D(25.0 * nm, 0.0), 40, 40) interference.setPositionVariance(1.0) - cylinder_ff = ba.FormFactorCylinder(3.*nm, 3.*nm) + cylinder_ff = ba.FormFactorCylinder(3. * nm, 3. * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder) @@ -44,9 +44,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/Interference2DSquareLattice.py b/Examples/Python/sim03_Structures/Interference2DSquareLattice.py index beee085dcfa8c42f2831c5a775ea28acfddc7217..599b3991ed7ce69037808b52d2856e471e113932 100644 --- a/Examples/Python/sim03_Structures/Interference2DSquareLattice.py +++ b/Examples/Python/sim03_Structures/Interference2DSquareLattice.py @@ -17,12 +17,12 @@ def get_sample(): # collection of particles interference = ba.InterferenceFunction2DLattice( - ba.SquareLattice2D(25.0*nm, 0*deg)) - pdf = ba.FTDecayFunction2DCauchy(300.0*nm/2.0/numpy.pi, - 100.0*nm/2.0/numpy.pi, 0) + ba.SquareLattice2D(25.0 * nm, 0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(300.0 * nm / 2.0 / numpy.pi, + 100.0 * nm / 2.0 / numpy.pi, 0) interference.setDecayFunction(pdf) - cylinder_ff = ba.FormFactorCylinder(3.*nm, 3.*nm) + cylinder_ff = ba.FormFactorCylinder(3. * nm, 3. * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder) @@ -46,9 +46,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -2.0*deg, 2.0*deg, - 200, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -2.0 * deg, 2.0 * deg, 200, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/RectangularGrating.py b/Examples/Python/sim03_Structures/RectangularGrating.py index b3765dcbcdede787317c8be2efb1dcdd68132ba2..26793f695f04c1f32caf7bcb19525e37010f33cc 100644 --- a/Examples/Python/sim03_Structures/RectangularGrating.py +++ b/Examples/Python/sim03_Structures/RectangularGrating.py @@ -7,7 +7,7 @@ import bornagain as ba from bornagain import deg, angstrom, nm, micrometer -def get_sample(lattice_rotation_angle=0.0*deg): +def get_sample(lattice_rotation_angle=0.0 * deg): """ Returns a sample with a grating on a substrate. lattice_rotation_angle = 0 - beam parallel to grating lines @@ -17,12 +17,12 @@ def get_sample(lattice_rotation_angle=0.0*deg): m_vacuum = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0) m_si = ba.HomogeneousMaterial("Si", 5.78164736e-6, 1.02294578e-7) - box_length, box_width, box_height = 50*micrometer, 70*nm, 50*nm - lattice_length = 150*nm + box_length, box_width, box_height = 50 * micrometer, 70 * nm, 50 * nm + lattice_length = 150 * nm # collection of particles interference = ba.InterferenceFunction1DLattice( - lattice_length, 90.0*deg - lattice_rotation_angle) + lattice_length, 90.0 * deg - lattice_rotation_angle) pdf = ba.ba.FTDecayFunction1DGauss(450.0) interference.setDecayFunction(pdf) @@ -31,8 +31,8 @@ def get_sample(lattice_rotation_angle=0.0*deg): box = ba.Particle(m_si, box_ff) particle_layout = ba.ParticleLayout() - particle_layout.addParticle( - box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), ba.RotationZ(lattice_rotation_angle)) + particle_layout.addParticle(box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), + ba.RotationZ(lattice_rotation_angle)) particle_layout.setInterferenceFunction(interference) # assembling the sample @@ -56,9 +56,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -0.5*deg, 0.5*deg, - 200, 0.0*deg, 0.6*deg) - simulation.setBeamParameters(1.34*angstrom, 0.4*deg, 0.0*deg) + simulation.setDetectorParameters(200, -0.5 * deg, 0.5 * deg, 200, 0.0 * deg, + 0.6 * deg) + simulation.setBeamParameters(1.34 * angstrom, 0.4 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.getOptions().setMonteCarloIntegration(True, 100) return simulation diff --git a/Examples/Python/sim03_Structures/SpheresAtHexLattice.py b/Examples/Python/sim03_Structures/SpheresAtHexLattice.py index 3aad9209640967aeeb40f84694b28260bf2c3768..822d8e916909ab9645476a914ac54b7dce1200a5 100644 --- a/Examples/Python/sim03_Structures/SpheresAtHexLattice.py +++ b/Examples/Python/sim03_Structures/SpheresAtHexLattice.py @@ -14,14 +14,14 @@ def get_sample(): m_substrate = ba.HomogeneousMaterial("Substrate", 6e-6, 2e-8) m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) - sphere_ff = ba.FormFactorFullSphere(10.0*nm) + sphere_ff = ba.FormFactorFullSphere(10.0 * nm) sphere = ba.Particle(m_particle, sphere_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(sphere) interference = ba.InterferenceFunction2DLattice( - ba.HexagonalLattice2D(20.0*nm, 0*deg)) - pdf = ba.FTDecayFunction2DCauchy(10*nm, 10*nm, 0) + ba.HexagonalLattice2D(20.0 * nm, 0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(10 * nm, 10 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -40,9 +40,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -1.0*deg, 1.0*deg, - 200, 0.0*deg, 1.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -1.0 * deg, 1.0 * deg, 200, 0.0 * deg, + 1.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim03_Structures/TriangularRipple.py b/Examples/Python/sim03_Structures/TriangularRipple.py index f70859eaa1c1656f5a866a7b63880b91f561c7bd..8798c0171243d1963fd63905a957f0cef1cbd45f 100644 --- a/Examples/Python/sim03_Structures/TriangularRipple.py +++ b/Examples/Python/sim03_Structures/TriangularRipple.py @@ -17,16 +17,16 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - ripple2_ff = ba.FormFactorSawtoothRippleBox( - 100*nm, 20*nm, 4*nm, -3.0*nm) + ripple2_ff = ba.FormFactorSawtoothRippleBox(100 * nm, 20 * nm, 4 * nm, -3.0 * nm) ripple = ba.Particle(m_particle, ripple2_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(ripple, 1.0) interference = ba.InterferenceFunction2DLattice( - ba.BasicLattice2D(200.0*nm, 50.0*nm, 90.0*deg, 0.0*deg)) - pdf = ba.FTDecayFunction2DGauss(1000.*nm/2./numpy.pi, 100.*nm/2./numpy.pi, 0) + ba.BasicLattice2D(200.0 * nm, 50.0 * nm, 90.0 * deg, 0.0 * deg)) + pdf = ba.FTDecayFunction2DGauss(1000. * nm / 2. / numpy.pi, + 100. * nm / 2. / numpy.pi, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -46,9 +46,9 @@ def get_simulation(): characterizing the input beam and output detector """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -1.5*deg, 1.5*deg, - 200, 0.0*deg, 2.5*deg) - simulation.setBeamParameters(1.6*angstrom, 0.3*deg, 0.0*deg) + simulation.setDetectorParameters(200, -1.5 * deg, 1.5 * deg, 200, 0.0 * deg, + 2.5 * deg) + simulation.setBeamParameters(1.6 * angstrom, 0.3 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim04_Multilayers/BuriedParticles.py b/Examples/Python/sim04_Multilayers/BuriedParticles.py index 64a9e3c72b5d035020ee3f7985a579930cc16073..3c636884466797904ba4c856062ea2eaf34bae83 100644 --- a/Examples/Python/sim04_Multilayers/BuriedParticles.py +++ b/Examples/Python/sim04_Multilayers/BuriedParticles.py @@ -17,7 +17,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 0.0, 0.0) # collection of particles - ff = ba.FormFactorFullSphere(10.2*nm) + ff = ba.FormFactorFullSphere(10.2 * nm) sphere = ba.Particle(m_particle, ff) sphere.setPosition(0.0, 0.0, -25.2) particle_layout = ba.ParticleLayout() @@ -25,7 +25,7 @@ def get_sample(): # assembling the sample vacuum_layer = ba.Layer(m_vacuum) - intermediate_layer = ba.Layer(m_interm_layer, 30.*nm) + intermediate_layer = ba.Layer(m_interm_layer, 30. * nm) intermediate_layer.addLayout(particle_layout) substrate_layer = ba.Layer(m_substrate, 0) @@ -42,8 +42,8 @@ def get_simulation(): """ simulation = ba.GISASSimulation() simulation.setSample(get_sample()) - simulation.setDetectorParameters(200, -1*deg, +1*deg, 200, 0*deg, +2*deg) - simulation.setBeamParameters(1.5*angstrom, 0.15*deg, 0.0*deg) + simulation.setDetectorParameters(200, -1 * deg, +1 * deg, 200, 0 * deg, +2 * deg) + simulation.setBeamParameters(1.5 * angstrom, 0.15 * deg, 0.0 * deg) return simulation diff --git a/Examples/Python/sim04_Multilayers/CorrelatedRoughness.py b/Examples/Python/sim04_Multilayers/CorrelatedRoughness.py index 36b80dd24b5049dc341b228802847522244cc64a..47cec84d5427bf4e4a4c5bdd093c442fdd087de5 100644 --- a/Examples/Python/sim04_Multilayers/CorrelatedRoughness.py +++ b/Examples/Python/sim04_Multilayers/CorrelatedRoughness.py @@ -17,14 +17,14 @@ def get_sample(): # defining layers l_ambience = ba.Layer(m_vacuum) - l_part_a = ba.Layer(m_part_a, 2.5*nm) - l_part_b = ba.Layer(m_part_b, 5.0*nm) + l_part_a = ba.Layer(m_part_a, 2.5 * nm) + l_part_b = ba.Layer(m_part_b, 5.0 * nm) l_substrate = ba.Layer(m_substrate) roughness = ba.LayerRoughness() - roughness.setSigma(1.0*nm) + roughness.setSigma(1.0 * nm) roughness.setHurstParameter(0.3) - roughness.setLatteralCorrLength(5.0*nm) + roughness.setLatteralCorrLength(5.0 * nm) my_sample = ba.MultiLayer() @@ -37,7 +37,7 @@ def get_sample(): my_sample.addLayerWithTopRoughness(l_part_b, roughness) my_sample.addLayerWithTopRoughness(l_substrate, roughness) - my_sample.setCrossCorrLength(10*nm) + my_sample.setCrossCorrLength(10 * nm) print(my_sample.treeToString()) @@ -49,9 +49,9 @@ def get_simulation(): Characterizing the input beam and output detector """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -0.5*deg, 0.5*deg, - 200, 0.0*deg, 1.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(200, -0.5 * deg, 0.5 * deg, 200, 0.0 * deg, + 1.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(5e11) return simulation diff --git a/Examples/Python/sim04_Multilayers/CylindersInAverageLayer.py b/Examples/Python/sim04_Multilayers/CylindersInAverageLayer.py index 90619a26b8bf62080197f1c51ac52c2a62aa90fb..86ae8b9f2e6ad4c4189f2eea62d910cc67c16fc2 100644 --- a/Examples/Python/sim04_Multilayers/CylindersInAverageLayer.py +++ b/Examples/Python/sim04_Multilayers/CylindersInAverageLayer.py @@ -5,7 +5,7 @@ import bornagain as ba from bornagain import deg, angstrom, nm -def get_sample(cyl_height=5*nm): +def get_sample(cyl_height=5 * nm): """ Returns a sample with cylinders on a substrate. """ @@ -16,20 +16,21 @@ def get_sample(cyl_height=5*nm): m_particle = ba.HomogeneousMaterial("Particle", 3e-5, 2e-8) # cylindrical particle - cylinder_ff = ba.FormFactorCylinder(5*nm, cyl_height) + cylinder_ff = ba.FormFactorCylinder(5 * nm, cyl_height) cylinder = ba.Particle(m_particle, cylinder_ff) position = ba.kvector_t(0.0, 0.0, -cyl_height) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0, position) # interference function - interference = ba.InterferenceFunction2DLattice(ba.SquareLattice2D(15*nm, 0*deg)) - pdf = ba.FTDecayFunction2DCauchy(300*nm, 300*nm, 0) + interference = ba.InterferenceFunction2DLattice( + ba.SquareLattice2D(15 * nm, 0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(300 * nm, 300 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) vacuum_layer = ba.Layer(m_vacuum) - intermediate_layer = ba.Layer(m_layer, 5*nm) + intermediate_layer = ba.Layer(m_layer, 5 * nm) intermediate_layer.addLayout(particle_layout) substrate_layer = ba.Layer(m_substrate) @@ -45,9 +46,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -2.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -2.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.getOptions().setUseAvgMaterials(True) return simulation diff --git a/Examples/Python/sim04_Multilayers/GratingMC.py b/Examples/Python/sim04_Multilayers/GratingMC.py index 67e819af38a7e163a3ddec33c1b5550762edf7e8..dc988a4171f2028ea8b2e682ca7ad10bf3ed5e1c 100644 --- a/Examples/Python/sim04_Multilayers/GratingMC.py +++ b/Examples/Python/sim04_Multilayers/GratingMC.py @@ -8,7 +8,7 @@ from bornagain import deg, angstrom, nm, micrometer from matplotlib import pyplot as plt -def get_sample(lattice_rotation_angle=0.0*deg): +def get_sample(lattice_rotation_angle=0.0 * deg): """ Returns a sample with a grating on a substrate. lattice_rotation_angle = 0 - beam parallel to grating lines @@ -18,12 +18,12 @@ def get_sample(lattice_rotation_angle=0.0*deg): m_vacuum = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0) m_si = ba.HomogeneousMaterial("Si", 5.78164736e-6, 1.02294578e-7) - box_length, box_width, box_height = 50*micrometer, 70*nm, 50*nm - lattice_length = 150*nm + box_length, box_width, box_height = 50 * micrometer, 70 * nm, 50 * nm + lattice_length = 150 * nm # collection of particles interference = ba.InterferenceFunction1DLattice( - lattice_length, 90.0*deg - lattice_rotation_angle) + lattice_length, 90.0 * deg - lattice_rotation_angle) pdf = ba.ba.FTDecayFunction1DGauss(450.0) interference.setDecayFunction(pdf) @@ -32,8 +32,8 @@ def get_sample(lattice_rotation_angle=0.0*deg): box = ba.Particle(m_si, box_ff) particle_layout = ba.ParticleLayout() - particle_layout.addParticle( - box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), ba.RotationZ(lattice_rotation_angle)) + particle_layout.addParticle(box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), + ba.RotationZ(lattice_rotation_angle)) particle_layout.setInterferenceFunction(interference) # assembling the sample @@ -57,9 +57,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -0.5*deg, 0.5*deg, - 200, 0.0*deg, 0.6*deg) - simulation.setBeamParameters(1.34*angstrom, 0.4*deg, 0.0*deg) + simulation.setDetectorParameters(200, -0.5 * deg, 0.5 * deg, 200, 0.0 * deg, + 0.6 * deg) + simulation.setBeamParameters(1.34 * angstrom, 0.4 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+08) simulation.getOptions().setMonteCarloIntegration(True, 100) return simulation @@ -84,7 +84,10 @@ if __name__ == '__main__': xpeaks = [peak[0] for peak in peaks] ypeaks = [peak[1] for peak in peaks] print(peaks) - plt.plot(xpeaks, ypeaks, linestyle='None', marker='x', color='white', + plt.plot(xpeaks, + ypeaks, + linestyle='None', + marker='x', + color='white', markersize=10) plt.show() - diff --git a/Examples/Python/sim04_Multilayers/HalfSpheresInAverageTopLayer.py b/Examples/Python/sim04_Multilayers/HalfSpheresInAverageTopLayer.py index a024491a7d5e3688e54195e4881e45d53b9966d9..379a44831b2ae6d490b1ea780b948ffda427ee54 100644 --- a/Examples/Python/sim04_Multilayers/HalfSpheresInAverageTopLayer.py +++ b/Examples/Python/sim04_Multilayers/HalfSpheresInAverageTopLayer.py @@ -5,7 +5,7 @@ and slicing import bornagain as ba from bornagain import deg, angstrom, nm -sphere_radius = 5*nm +sphere_radius = 5 * nm n_slices = 10 @@ -26,8 +26,9 @@ def get_sample(): particle_layout.addParticle(half_sphere) # interference function - interference = ba.InterferenceFunction2DLattice(ba.SquareLattice2D(10*nm, 0*deg)) - pdf = ba.FTDecayFunction2DCauchy(100*nm, 100*nm, 0) + interference = ba.InterferenceFunction2DLattice( + ba.SquareLattice2D(10 * nm, 0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(100 * nm, 100 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -47,9 +48,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -2.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -2.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.getOptions().setUseAvgMaterials(True) return simulation diff --git a/Examples/Python/sim05_Magnetism/MagneticSpheres.py b/Examples/Python/sim05_Magnetism/MagneticSpheres.py index a1a126cb466cdf9d95b32aaa5eacbf9f25932418..a41d49e2e036bd5bd6c73500972d1b2bae02e91f 100644 --- a/Examples/Python/sim05_Magnetism/MagneticSpheres.py +++ b/Examples/Python/sim05_Magnetism/MagneticSpheres.py @@ -4,7 +4,6 @@ Simulation demo: magnetic spheres in substrate import bornagain as ba from bornagain import deg, angstrom, nm - # Magnetization of the particle's material (A/m) magnetization_particle = ba.kvector_t(0.0, 0.0, 1e7) @@ -20,9 +19,9 @@ def get_sample(): substrate_material = ba.HomogeneousMaterial("Substrate", 7e-6, 1.8e-7) # spherical magnetic particle - sphere_ff = ba.FormFactorFullSphere(5*nm) + sphere_ff = ba.FormFactorFullSphere(5 * nm) sphere = ba.Particle(particle_material, sphere_ff) - position = ba.kvector_t(0.0, 0.0, -10.0*nm) + position = ba.kvector_t(0.0, 0.0, -10.0 * nm) particle_layout = ba.ParticleLayout() particle_layout.addParticle(sphere, 1.0, position) @@ -44,8 +43,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(200, -3.0*deg, 3.0*deg, 200, 0.0*deg, 6.0*deg) - simulation.setBeamParameters(1.*angstrom, 0.5*deg, 0.0*deg) + simulation.setDetectorParameters(200, -3.0 * deg, 3.0 * deg, 200, 0.0 * deg, + 6.0 * deg) + simulation.setBeamParameters(1. * angstrom, 0.5 * deg, 0.0 * deg) simulation.setBeamIntensity(1e12) analyzer_dir = ba.kvector_t(0.0, 0.0, -1.0) diff --git a/Examples/Python/sim11_Device/AxesInDifferentUnits.py b/Examples/Python/sim11_Device/AxesInDifferentUnits.py index 9c23535da866b402bd0d70df66ea077ab108b05d..9065945c49ee1dfa0ea2b05676834fc083810b97 100644 --- a/Examples/Python/sim11_Device/AxesInDifferentUnits.py +++ b/Examples/Python/sim11_Device/AxesInDifferentUnits.py @@ -18,7 +18,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -42,10 +42,10 @@ def get_rectangular_detector(): pilatus_pixel_size = 0.172 # in mm pilatus_npx, pilatus_npy = 981, 1043 # number of pixels - width = pilatus_npx*pilatus_pixel_size - height = pilatus_npy*pilatus_pixel_size + width = pilatus_npx * pilatus_pixel_size + height = pilatus_npy * pilatus_pixel_size detector = ba.RectangularDetector(pilatus_npx, width, pilatus_npy, height) - detector.setPerpendicularToSampleX(detector_distance, width/2., 0.0) + detector.setPerpendicularToSampleX(detector_distance, width / 2., 0.0) return detector @@ -54,7 +54,7 @@ def get_simulation(): Returns a GISAXS simulation with beam defined """ simulation = ba.GISASSimulation() - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setDetector(get_rectangular_detector()) return simulation @@ -80,27 +80,41 @@ def plot(result): # set plotting parameters rcParams['image.cmap'] = 'jet' rcParams['image.aspect'] = 'auto' - + fig = plt.figure(figsize=(12.80, 10.24)) plt.subplot(2, 2, 1) # default units for rectangular detector are millimeters - ba.plot_colormap(result, title="In default units", - xlabel=r'$X_{mm}$', ylabel=r'$Y_{mm}$', zlabel=None) + ba.plot_colormap(result, + title="In default units", + xlabel=r'$X_{mm}$', + ylabel=r'$Y_{mm}$', + zlabel=None) plt.subplot(2, 2, 2) - ba.plot_colormap(result, units=ba.Axes.NBINS, title="In number of bins", - xlabel=r'$X_{nbins}$', ylabel=r'$Y_{nbins}$', zlabel=None) + ba.plot_colormap(result, + units=ba.Axes.NBINS, + title="In number of bins", + xlabel=r'$X_{nbins}$', + ylabel=r'$Y_{nbins}$', + zlabel=None) plt.subplot(2, 2, 3) - ba.plot_colormap(result, units=ba.Axes.DEGREES, title="In degs", - xlabel=r'$\phi_f ^{\circ}$', ylabel=r'$\alpha_f ^{\circ}$', + ba.plot_colormap(result, + units=ba.Axes.DEGREES, + title="In degs", + xlabel=r'$\phi_f ^{\circ}$', + ylabel=r'$\alpha_f ^{\circ}$', zlabel=None) plt.subplot(2, 2, 4) - ba.plot_colormap(result, units=ba.Axes.QSPACE, title="Q-space", - xlabel=r'$Q_{y} [1/nm]$', ylabel=r'$Q_{z} [1/nm]$', zlabel=None) + ba.plot_colormap(result, + units=ba.Axes.QSPACE, + title="Q-space", + xlabel=r'$Q_{y} [1/nm]$', + ylabel=r'$Q_{z} [1/nm]$', + zlabel=None) plt.subplots_adjust(left=0.07, right=0.97, top=0.9, bottom=0.1, hspace=0.25) plt.show() diff --git a/Examples/Python/sim11_Device/BeamDivergence.py b/Examples/Python/sim11_Device/BeamDivergence.py index a0f9e73d1aefbb12dcef846b8fedf1c8cc38ad6c..bbbc64e2993498aa51490c743de35bbad376af4c 100644 --- a/Examples/Python/sim11_Device/BeamDivergence.py +++ b/Examples/Python/sim11_Device/BeamDivergence.py @@ -15,7 +15,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -36,12 +36,12 @@ def get_simulation(): Returns a GISAXS simulation with beam (+ divergence) and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) - wavelength_distr = ba.DistributionLogNormal(1.0*angstrom, 0.1) - alpha_distr = ba.DistributionGaussian(0.2*deg, 0.1*deg) - phi_distr = ba.DistributionGaussian(0.0*deg, 0.1*deg) + simulation.setDetectorParameters(100, 0.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) + wavelength_distr = ba.DistributionLogNormal(1.0 * angstrom, 0.1) + alpha_distr = ba.DistributionGaussian(0.2 * deg, 0.1 * deg) + phi_distr = ba.DistributionGaussian(0.0 * deg, 0.1 * deg) simulation.addParameterDistribution("*/Beam/Wavelength", wavelength_distr, 5) simulation.addParameterDistribution("*/Beam/InclinationAngle", alpha_distr, 5) simulation.addParameterDistribution("*/Beam/AzimuthalAngle", phi_distr, 5) diff --git a/Examples/Python/sim11_Device/ConstantBackground.py b/Examples/Python/sim11_Device/ConstantBackground.py index 5a0484c5b14a90167f7687878fd702d4727b51b8..e7ea35730a913d5bee293e70b95779bac265041e 100644 --- a/Examples/Python/sim11_Device/ConstantBackground.py +++ b/Examples/Python/sim11_Device/ConstantBackground.py @@ -15,7 +15,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -36,9 +36,9 @@ def get_simulation(): Returns a GISAXS simulation with a constant backround. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, 0.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e6) bg = ba.ConstantBackground(1e3) simulation.setBackground(bg) diff --git a/Examples/Python/sim11_Device/DetectorResolutionFunction.py b/Examples/Python/sim11_Device/DetectorResolutionFunction.py index d2735fa4cb4190462fc9eb1b3176fb75d84e06dd..ae9ec0e4be89bb1a04b52d258b9f64f3f343cfdc 100644 --- a/Examples/Python/sim11_Device/DetectorResolutionFunction.py +++ b/Examples/Python/sim11_Device/DetectorResolutionFunction.py @@ -15,7 +15,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -36,11 +36,11 @@ def get_simulation(): Returns a GISAXS simulation with detector resolution function defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0.0*deg, 2.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, 0.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setDetectorResolutionFunction( - ba.ResolutionFunction2DGaussian(0.02*deg, 0.02*deg)) + ba.ResolutionFunction2DGaussian(0.02 * deg, 0.02 * deg)) return simulation diff --git a/Examples/Python/sim11_Device/OffSpecularSimulation.py b/Examples/Python/sim11_Device/OffSpecularSimulation.py index 43fccdc77cb3b9f7d6b8cbe3394705890c6adfb2..a5db46bb3d5d1e0d3b35bdc126e69cab907a6fc3 100644 --- a/Examples/Python/sim11_Device/OffSpecularSimulation.py +++ b/Examples/Python/sim11_Device/OffSpecularSimulation.py @@ -20,16 +20,16 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - lattice_length = 100.0*nm - lattice_rotation_angle = 0.0*deg - interference = ba.InterferenceFunction1DLattice( - lattice_length, lattice_rotation_angle) + lattice_length = 100.0 * nm + lattice_rotation_angle = 0.0 * deg + interference = ba.InterferenceFunction1DLattice(lattice_length, + lattice_rotation_angle) pdf = ba.FTDecayFunction1DCauchy(1e+6) interference.setDecayFunction(pdf) - box_ff = ba.FormFactorBox(1000*nm, 20*nm, 10.0*nm) + box_ff = ba.FormFactorBox(1000 * nm, 20 * nm, 10.0 * nm) box = ba.Particle(m_particle, box_ff) - transform = ba.RotationZ(90.0*deg) + transform = ba.RotationZ(90.0 * deg) particle_layout = ba.ParticleLayout() particle_layout.addParticle(box, 1.0, ba.kvector_t(0.0, 0.0, 0.0), transform) particle_layout.setInterferenceFunction(interference) @@ -50,12 +50,12 @@ def get_simulation(): Returns an off-specular simulation with beam and detector defined. """ simulation = ba.OffSpecSimulation() - simulation.setDetectorParameters(20, phi_f_min*deg, phi_f_max*deg, - 200, alpha_f_min*deg, alpha_f_max*deg) + simulation.setDetectorParameters(20, phi_f_min * deg, phi_f_max * deg, 200, + alpha_f_min * deg, alpha_f_max * deg) # define the beam with alpha_i varied between alpha_i_min and alpha_i_max - alpha_i_axis = ba.FixedBinAxis( - "alpha_i", 200, alpha_i_min*deg, alpha_i_max*deg) - simulation.setBeamParameters(1.0*angstrom, alpha_i_axis, 0.0*deg) + alpha_i_axis = ba.FixedBinAxis("alpha_i", 200, alpha_i_min * deg, + alpha_i_max * deg) + simulation.setBeamParameters(1.0 * angstrom, alpha_i_axis, 0.0 * deg) simulation.setBeamIntensity(1e9) return simulation diff --git a/Examples/Python/sim11_Device/RectangularDetector.py b/Examples/Python/sim11_Device/RectangularDetector.py index 7bf9045b8811932c7fe99c611ccec180435f0348..91e683e115680ef969b7b3c3f3ee8362aff4b9d1 100644 --- a/Examples/Python/sim11_Device/RectangularDetector.py +++ b/Examples/Python/sim11_Device/RectangularDetector.py @@ -23,7 +23,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - edge = 40*nm + edge = 40 * nm ff = ba.FormFactorBox(edge, edge, edge) cylinder = ba.Particle(m_particle, ff) particle_layout = ba.ParticleLayout() @@ -45,24 +45,24 @@ def get_spherical_detector(): """ n_phi = pilatus_npx n_alpha = pilatus_npy - width = pilatus_npx*pilatus_pixel_size - height = pilatus_npy*pilatus_pixel_size - phi_min = numpy.arctan(-width/2./detector_distance) - phi_max = numpy.arctan(width/2./detector_distance) + width = pilatus_npx * pilatus_pixel_size + height = pilatus_npy * pilatus_pixel_size + phi_min = numpy.arctan(-width / 2. / detector_distance) + phi_max = numpy.arctan(width / 2. / detector_distance) alpha_min = 0.0 - alpha_max = numpy.arctan(height/detector_distance) - return ba.SphericalDetector( - n_phi, phi_min, phi_max, n_alpha, alpha_min, alpha_max) + alpha_max = numpy.arctan(height / detector_distance) + return ba.SphericalDetector(n_phi, phi_min, phi_max, n_alpha, alpha_min, + alpha_max) def get_rectangular_detector(): """ Returns a rectangular detector representing our PILATUS detector """ - width = pilatus_npx*pilatus_pixel_size - height = pilatus_npy*pilatus_pixel_size + width = pilatus_npx * pilatus_pixel_size + height = pilatus_npy * pilatus_pixel_size detector = ba.RectangularDetector(pilatus_npx, width, pilatus_npy, height) - detector.setPerpendicularToSampleX(detector_distance, width/2., 0.0) + detector.setPerpendicularToSampleX(detector_distance, width / 2., 0.0) return detector @@ -71,7 +71,7 @@ def get_simulation(): Return a GISAXS simulation with defined beam """ simulation = ba.GISASSimulation() - simulation.setBeamParameters(10*angstrom, 0.2*deg, 0.0*deg) + simulation.setBeamParameters(10 * angstrom, 0.2 * deg, 0.0 * deg) return simulation @@ -84,24 +84,34 @@ def plot(results): # showing result of spherical detector simulation plt.subplot(1, 3, 1) - ba.plot_colormap(results['spherical'], title="Spherical detector", - xlabel=r'$\phi_f ^{\circ}$', ylabel=r'$\alpha_f ^{\circ}$', - zlabel="", cmap='jet', aspect='auto') + ba.plot_colormap(results['spherical'], + title="Spherical detector", + xlabel=r'$\phi_f ^{\circ}$', + ylabel=r'$\alpha_f ^{\circ}$', + zlabel="", + cmap='jet', + aspect='auto') # showing result of rectangular detector simulation plt.subplot(1, 3, 2) - ba.plot_colormap(results['rectangular'], title="Rectangular detector", - xlabel='X, mm', ylabel='Y, mm', zlabel="", - cmap='jet', aspect='auto') + ba.plot_colormap(results['rectangular'], + title="Rectangular detector", + xlabel='X, mm', + ylabel='Y, mm', + zlabel="", + cmap='jet', + aspect='auto') # show relative difference between two plots (sph[i]-rect[i])/rect[i] # for every detector pixel sph_array = results['spherical'].array() rect_array = results['rectangular'].array() - rel_diff = 2.0 * numpy.abs(sph_array - rect_array)/(sph_array + rect_array) + rel_diff = 2.0 * numpy.abs(sph_array - rect_array) / (sph_array + rect_array) plt.subplot(1, 3, 3) - im = plt.imshow(rel_diff, norm=colors.LogNorm(1e-6, 1.0), - aspect='auto', cmap='jet') + im = plt.imshow(rel_diff, + norm=colors.LogNorm(1e-6, 1.0), + aspect='auto', + cmap='jet') cb = plt.colorbar(im, pad=0.025) plt.xlabel('X, bins', fontsize=14) plt.ylabel('Y, bins', fontsize=14) diff --git a/Examples/Python/sim11_Device/ResonatorOffSpecSetup.py b/Examples/Python/sim11_Device/ResonatorOffSpecSetup.py index a516764ad7275765450319d5ba7823fe36bd63f5..e9330b6033c025259e0af1e775568f673f171c7d 100644 --- a/Examples/Python/sim11_Device/ResonatorOffSpecSetup.py +++ b/Examples/Python/sim11_Device/ResonatorOffSpecSetup.py @@ -5,7 +5,7 @@ import bornagain as ba from bornagain import deg, nm, micrometer, angstrom -def get_sample(nlayers = 3): +def get_sample(nlayers=3): """ Construct resonator with given number of Ti/Pt double layers nlayers. """ @@ -18,18 +18,18 @@ def get_sample(nlayers = 3): m_D2O = ba.HomogeneousMaterial("D2O", 2.52897204573e-05, 4.5224432814e-13) # create layers - l_TiO2 = ba.Layer(m_TiO2, 3.0*nm) - l_Ti_top = ba.Layer(m_Ti, 10.0*nm) - l_Ti = ba.Layer(m_Ti, 13.0*nm) - l_Si = ba.Layer(m_Si) # consider it as an ambient layer - l_Pt = ba.Layer(m_Pt, 32.0*nm) + l_TiO2 = ba.Layer(m_TiO2, 3.0 * nm) + l_Ti_top = ba.Layer(m_Ti, 10.0 * nm) + l_Ti = ba.Layer(m_Ti, 13.0 * nm) + l_Si = ba.Layer(m_Si) # consider it as an ambient layer + l_Pt = ba.Layer(m_Pt, 32.0 * nm) l_D2O = ba.Layer(m_D2O) # thickness is not given, seems to be like a substrate # describe layer roughness roughness = ba.LayerRoughness() - roughness.setSigma(2.0*nm) + roughness.setSigma(2.0 * nm) roughness.setHurstParameter(0.8) - roughness.setLatteralCorrLength(10.0*micrometer) + roughness.setLatteralCorrLength(10.0 * micrometer) # assemble multilayer sample = ba.MultiLayer() @@ -43,7 +43,7 @@ def get_sample(nlayers = 3): sample.addLayerWithTopRoughness(l_TiO2, roughness) sample.addLayerWithTopRoughness(l_D2O, roughness) - sample.setCrossCorrLength(400*nm) + sample.setCrossCorrLength(400 * nm) return sample @@ -58,26 +58,27 @@ def get_offspec_simulation(): simulation.setTerminalProgressMonitor() # define detector parameters - n_alpha, alpha_min, alpha_max = 300, 0.0*deg, 4.0*deg - n_phi, phi_min, phi_max = 10, -0.1*deg, 0.1*deg - simulation.setDetectorParameters( - n_phi, phi_min, phi_max, n_alpha, alpha_min, alpha_max) + n_alpha, alpha_min, alpha_max = 300, 0.0 * deg, 4.0 * deg + n_phi, phi_min, phi_max = 10, -0.1 * deg, 0.1 * deg + simulation.setDetectorParameters(n_phi, phi_min, phi_max, n_alpha, alpha_min, + alpha_max) # define the beam with alpha_i varied between alpha_i_min and alpha_i_max n_scan_points, alpha_i_min, alpha_i_max = n_alpha, alpha_min, alpha_max - alpha_i_axis = ba.FixedBinAxis( - "alpha_i", n_scan_points, alpha_i_min, alpha_i_max) - simulation.setBeamParameters(5.0*angstrom, alpha_i_axis, 0.0) + alpha_i_axis = ba.FixedBinAxis("alpha_i", n_scan_points, alpha_i_min, + alpha_i_max) + simulation.setBeamParameters(5.0 * angstrom, alpha_i_axis, 0.0) simulation.setBeamIntensity(1e9) simulation.getOptions().setIncludeSpecular(True) # define detector resolution function with smearing depending on bin size - d_alpha = (alpha_max - alpha_min)/n_alpha - d_phi = (phi_max-phi_min)/n_phi + d_alpha = (alpha_max - alpha_min) / n_alpha + d_phi = (phi_max - phi_min) / n_phi sigma_factor = 1.0 simulation.setDetectorResolutionFunction( - ba.ResolutionFunction2DGaussian(sigma_factor*d_alpha, sigma_factor*d_phi)) + ba.ResolutionFunction2DGaussian(sigma_factor * d_alpha, + sigma_factor * d_phi)) return simulation diff --git a/Examples/Python/sim21_Reflectometry/BasicPolarizedReflectometry.py b/Examples/Python/sim21_Reflectometry/BasicPolarizedReflectometry.py index 32b55eff4e354744972b67e5bdc414356c85cf93..e8685ce27c7c01fa519bff0f7910f0e9b60946c9 100644 --- a/Examples/Python/sim21_Reflectometry/BasicPolarizedReflectometry.py +++ b/Examples/Python/sim21_Reflectometry/BasicPolarizedReflectometry.py @@ -8,6 +8,7 @@ from bornagain import deg, angstrom import matplotlib.pyplot as plt + def get_sample(): """ Defines sample and returns it @@ -15,8 +16,7 @@ def get_sample(): # creating materials m_ambient = ba.MaterialBySLD("Ambient", 0.0, 0.0) - m_layer_mat = ba.MaterialBySLD("Layer", 1e-4, 1e-8, - ba.kvector_t(0.0, 1e8, 0.0)) + m_layer_mat = ba.MaterialBySLD("Layer", 1e-4, 1e-8, ba.kvector_t(0.0, 1e8, 0.0)) m_substrate = ba.MaterialBySLD("Substrate", 7e-5, 2e-6) # creating layers @@ -38,8 +38,7 @@ def get_simulation(scan_size=500): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, - 0.0 * deg, 5.0 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, 0.0 * deg, 5.0 * deg) simulation.setScan(scan) return simulation @@ -62,27 +61,23 @@ def run_simulation(polarization=ba.kvector_t(0, 1, 0), def plot(data, labels): - + plt.figure() for d, l in zip(data, labels): - plt.semilogy( d.axis(), - d.array(), - label=l, linewidth=1) - - plt.legend( loc='upper right' ) + plt.semilogy(d.axis(), d.array(), label=l, linewidth=1) + + plt.legend(loc='upper right') plt.gca().yaxis.set_ticks_position('both') plt.gca().xaxis.set_ticks_position('both') - + plt.xlabel(r"$\alpha_i$ [deg]") plt.ylabel("Reflectivity") - + plt.tight_layout() plt.show() if __name__ == '__main__': - results_pp = run_simulation(ba.kvector_t(0, 1, 0), - ba.kvector_t(0, 1, 0)) - results_mm = run_simulation(ba.kvector_t(0, -1, 0), - ba.kvector_t(0, -1, 0)) + results_pp = run_simulation(ba.kvector_t(0, 1, 0), ba.kvector_t(0, 1, 0)) + results_mm = run_simulation(ba.kvector_t(0, -1, 0), ba.kvector_t(0, -1, 0)) plot([results_pp, results_mm], ["$++$", "$--$"]) diff --git a/Examples/Python/sim21_Reflectometry/BasicSpecularSimulation.py b/Examples/Python/sim21_Reflectometry/BasicSpecularSimulation.py index 17cf311218884224341f91a8f05b7b133a2dbf8d..ae9055c64212a6ed77d9ce70095a12afadc11f08 100644 --- a/Examples/Python/sim21_Reflectometry/BasicSpecularSimulation.py +++ b/Examples/Python/sim21_Reflectometry/BasicSpecularSimulation.py @@ -39,8 +39,7 @@ def get_simulation(scan_size=500): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, - 0.0 * deg, 2.0 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, 0.0 * deg, 2.0 * deg) simulation.setScan(scan) return simulation diff --git a/Examples/Python/sim21_Reflectometry/BeamAngularDivergence.py b/Examples/Python/sim21_Reflectometry/BeamAngularDivergence.py index 54392356753dd94851e76c40ff808b9bf3946192..05de2b19dc425bff7dff3da1964e343d7f09384e 100644 --- a/Examples/Python/sim21_Reflectometry/BeamAngularDivergence.py +++ b/Examples/Python/sim21_Reflectometry/BeamAngularDivergence.py @@ -56,9 +56,11 @@ def create_real_data(): Loading data from genx_angular_divergence.dat """ filepath = path.join(path.dirname(path.realpath(__file__)), - "genx_angular_divergence.dat.gz") + "genx_angular_divergence.dat.gz") ax_values, real_data = np.loadtxt(filepath, - usecols=(0, 1), skiprows=3, unpack=True) + usecols=(0, 1), + skiprows=3, + unpack=True) # translating axis values from double incident angle # to incident angle ax_values *= 0.5 @@ -107,9 +109,7 @@ def plot(results): genx_axis, genx_values = create_real_data() plt.semilogy(genx_axis, genx_values, 'ko', markevery=300) - plt.legend(['BornAgain', - 'GenX'], - loc='upper right') + plt.legend(['BornAgain', 'GenX'], loc='upper right') plt.show() diff --git a/Examples/Python/sim21_Reflectometry/FootprintCorrection.py b/Examples/Python/sim21_Reflectometry/FootprintCorrection.py index 1be10c62811243ac04efa656b7c1120e8ff4be46..73a9e4be335b62153c71444d611d325672d26bff 100644 --- a/Examples/Python/sim21_Reflectometry/FootprintCorrection.py +++ b/Examples/Python/sim21_Reflectometry/FootprintCorrection.py @@ -41,8 +41,7 @@ def get_simulation(footprint): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan( - 1.54 * angstrom, 500 , 0.0 * deg, 0.6 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, 500, 0.0 * deg, 0.6 * deg) scan.setFootprintFactor(footprint) simulation.setScan(scan) return simulation @@ -69,13 +68,11 @@ def plot(sim_result_1, sim_result_2): x1, y1 = get_plot_data(sim_result_1) x2, y2 = get_plot_data(sim_result_2) plt.semilogy(x1, y1, x2, y2) - + plt.xlabel(r'$\alpha_i \; (deg)$', fontsize=16) plt.ylabel(r'Intensity', fontsize=16) - plt.legend(['With footprint', - 'Without footprint'], - loc='upper right') + plt.legend(['With footprint', 'Without footprint'], loc='upper right') plt.show() @@ -83,9 +80,6 @@ def plot(sim_result_1, sim_result_2): if __name__ == '__main__': beam_sample_ratio = 0.01 # beam-to-sample size ratio result_with_fp = run_simulation( - get_simulation( - footprint=ba.FootprintSquare(beam_sample_ratio) - ) - ) + get_simulation(footprint=ba.FootprintSquare(beam_sample_ratio))) result_without_fp = run_simulation(get_simulation(footprint=None)) plot(result_with_fp, result_without_fp) diff --git a/Examples/Python/sim21_Reflectometry/PolarizedNoAnalyzer.py b/Examples/Python/sim21_Reflectometry/PolarizedNoAnalyzer.py index b001eb19fb0a5373048c591986ad76e5785f8b77..78a4e88e7dc133bf82841ad3f45c425a5515c19f 100644 --- a/Examples/Python/sim21_Reflectometry/PolarizedNoAnalyzer.py +++ b/Examples/Python/sim21_Reflectometry/PolarizedNoAnalyzer.py @@ -9,7 +9,6 @@ import bornagain as ba from bornagain import deg, angstrom - def get_sample(): """ Defines sample and returns it @@ -17,15 +16,12 @@ def get_sample(): # creating materials magnetizationMagnitude = 1e8 - angle = 30 * deg - magnetizationVector = ba.kvector_t( - magnetizationMagnitude * numpy.sin(angle), - magnetizationMagnitude * numpy.cos(angle), - 0) + angle = 30 * deg + magnetizationVector = ba.kvector_t(magnetizationMagnitude * numpy.sin(angle), + magnetizationMagnitude * numpy.cos(angle), 0) m_ambient = ba.MaterialBySLD("Ambient", 0.0, 0.0) - m_layer_mat = ba.MaterialBySLD("Layer", 1e-4, 1e-8, - magnetizationVector) + m_layer_mat = ba.MaterialBySLD("Layer", 1e-4, 1e-8, magnetizationVector) m_substrate = ba.MaterialBySLD("Substrate", 7e-5, 2e-6) # creating layers @@ -47,14 +43,12 @@ def get_simulation(scan_size=500): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, - 0.0 * deg, 5.0 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, 0.0 * deg, 5.0 * deg) simulation.setScan(scan) return simulation -def run_simulation(polarization=ba.kvector_t(0.0, 1.0, 0.0), - analyzer=None): +def run_simulation(polarization=ba.kvector_t(0.0, 1.0, 0.0), analyzer=None): """ Runs simulation and returns its result. """ @@ -64,7 +58,7 @@ def run_simulation(polarization=ba.kvector_t(0.0, 1.0, 0.0), # adding polarization and analyzer operator simulation.setBeamPolarization(polarization) if analyzer: - simulation.setAnalyzerProperties(analyzer, 1.0, 0.5) + simulation.setAnalyzerProperties(analyzer, 1.0, 0.5) simulation.setSample(sample) simulation.runSimulation() @@ -73,48 +67,36 @@ def run_simulation(polarization=ba.kvector_t(0.0, 1.0, 0.0), def plot(axis, data, labels): - + plt.figure() for d, l in zip(data, labels): - plt.semilogy( axis, - d, - label=l, linewidth=1) - - plt.legend( loc='upper right' ) + plt.semilogy(axis, d, label=l, linewidth=1) + + plt.legend(loc='upper right') plt.gca().yaxis.set_ticks_position('both') plt.gca().xaxis.set_ticks_position('both') - + plt.xlabel(r"$\alpha_i$ [deg]") plt.ylabel("Reflectivity") - + plt.tight_layout() if __name__ == '__main__': - q, results_pp = run_simulation(ba.kvector_t(0, 1, 0), - ba.kvector_t(0, 1, 0)) - q, results_mm = run_simulation(ba.kvector_t(0, -1, 0), - ba.kvector_t(0, -1, 0)) - - q, results_pm = run_simulation(ba.kvector_t(0, 1, 0), - ba.kvector_t(0, -1, 0)) - q, results_mp = run_simulation(ba.kvector_t(0, -1, 0), - ba.kvector_t(0, 1, 0)) - - r_plus = results_pp + results_pm + q, results_pp = run_simulation(ba.kvector_t(0, 1, 0), ba.kvector_t(0, 1, 0)) + q, results_mm = run_simulation(ba.kvector_t(0, -1, 0), ba.kvector_t(0, -1, 0)) + + q, results_pm = run_simulation(ba.kvector_t(0, 1, 0), ba.kvector_t(0, -1, 0)) + q, results_mp = run_simulation(ba.kvector_t(0, -1, 0), ba.kvector_t(0, 1, 0)) + + r_plus = results_pp + results_pm r_minus = results_mm + results_mp - plot(q, - [r_plus, r_minus], - ["$+$", "$-$"]) - + plot(q, [r_plus, r_minus], ["$+$", "$-$"]) + # same result, but need half the computational time - q, results_p = run_simulation(ba.kvector_t(0, 1, 0)) + q, results_p = run_simulation(ba.kvector_t(0, 1, 0)) q, results_m = run_simulation(ba.kvector_t(0, -1, 0)) - - plot(q, - [results_p, results_m], - ["$+$", "$-$"]) + + plot(q, [results_p, results_m], ["$+$", "$-$"]) plt.show() - - diff --git a/Examples/Python/sim21_Reflectometry/PolarizedNonperfectAnalyzerPolarizer.py b/Examples/Python/sim21_Reflectometry/PolarizedNonperfectAnalyzerPolarizer.py index e42e4f1d78cae590768d95f8cbf598aea3e36dad..f159c526c24ad649cd95213c5c76513bba83c0c7 100644 --- a/Examples/Python/sim21_Reflectometry/PolarizedNonperfectAnalyzerPolarizer.py +++ b/Examples/Python/sim21_Reflectometry/PolarizedNonperfectAnalyzerPolarizer.py @@ -5,21 +5,19 @@ following Devishvili et al., Rev. Sci. Instrum. 84, 025112 (2013) """ import numpy import matplotlib.pyplot as plt - + import bornagain as ba from bornagain import deg, angstrom - -sldFe = (8.0241e-06, 6.0448e-10) -sldPd = (4.0099e-6, 1.3019e-09) +sldFe = (8.0241e-06, 6.0448e-10) +sldPd = (4.0099e-6, 1.3019e-09) sldMgO = (5.9803e-06, 9.3996e-12) magnetizationMagnitude = 1.6e6 -angle = 0 -magnetizationVector = ba.kvector_t( - magnetizationMagnitude * numpy.sin(angle * deg), - magnetizationMagnitude * numpy.cos(angle * deg), - 0) +angle = 0 +magnetizationVector = ba.kvector_t(magnetizationMagnitude * numpy.sin(angle * deg), + magnetizationMagnitude * numpy.cos(angle * deg), + 0) def get_sample(*, magnetization=magnetizationVector): @@ -28,111 +26,113 @@ def get_sample(*, magnetization=magnetizationVector): """ # create materials - mat_vacuum = ba.MaterialBySLD("Vacuum", 0.0, 0.0) - mat_Pd = ba.MaterialBySLD("Pd", *sldPd) - mat_Fe = ba.MaterialBySLD("Fe", *sldFe, - magnetizationVector) + mat_vacuum = ba.MaterialBySLD("Vacuum", 0.0, 0.0) + mat_Pd = ba.MaterialBySLD("Pd", *sldPd) + mat_Fe = ba.MaterialBySLD("Fe", *sldFe, magnetizationVector) mat_substrate = ba.MaterialBySLD("MgO", *sldMgO) # create layers - layer_vacuum = ba.Layer( mat_vacuum ) - layer_Pd = ba.Layer( mat_Pd, 120 * angstrom ) - layer_Fe = ba.Layer( mat_Fe, 1000 * angstrom ) - layer_substrate = ba.Layer( mat_substrate ) + layer_vacuum = ba.Layer(mat_vacuum) + layer_Pd = ba.Layer(mat_Pd, 120 * angstrom) + layer_Fe = ba.Layer(mat_Fe, 1000 * angstrom) + layer_substrate = ba.Layer(mat_substrate) roughness = ba.LayerRoughness() - roughness.setSigma( 20 * angstrom) - + roughness.setSigma(20 * angstrom) + # create sample multi_layer = ba.MultiLayer() - + multi_layer.addLayer(layer_vacuum) multi_layer.addLayerWithTopRoughness(layer_Pd, roughness) multi_layer.addLayerWithTopRoughness(layer_Fe, roughness) multi_layer.addLayerWithTopRoughness(layer_substrate, roughness) - + return multi_layer -def get_simulation( scan_size=1500 ): +def get_simulation(scan_size=1500): """ Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() qzs = numpy.linspace(0.1, 1.5, scan_size) - + n_sig = 4.0 n_samples = 25 distr = ba.RangedDistributionGaussian(n_samples, n_sig) scan = ba.QSpecScan(qzs) scan.setAbsoluteQResolution(distr, 0.008) - + simulation.setScan(scan) return simulation -def run_simulation(*, polarization=ba.kvector_t(0, 1, 0), - polarizer_efficiency=1, - analyzer=ba.kvector_t(0, 1, 0), - analyzer_efficiency=1): +def run_simulation(*, + polarization=ba.kvector_t(0, 1, 0), + polarizer_efficiency=1, + analyzer=ba.kvector_t(0, 1, 0), + analyzer_efficiency=1): """ Runs simulation and returns its result. """ sample = get_sample() - + simulation = get_simulation() simulation.setBeamPolarization(polarization * polarizer_efficiency) simulation.setAnalyzerProperties(analyzer, analyzer_efficiency, 0.5) - - simulation.setBackground( ba.ConstantBackground( 1e-7 ) ) - + + simulation.setBackground(ba.ConstantBackground(1e-7)) + simulation.setSample(sample) simulation.runSimulation() return simulation.result() def plot(data, labels): - + plt.figure() for d, l in zip(data, labels): - plt.semilogy(numpy.array( d.axis(ba.Axes.QSPACE) ), - d.array(ba.Axes.QSPACE), label=l, linewidth=1) - - plt.legend( loc='upper right' ) + plt.semilogy(numpy.array(d.axis(ba.Axes.QSPACE)), + d.array(ba.Axes.QSPACE), + label=l, + linewidth=1) + + plt.legend(loc='upper right') plt.gca().yaxis.set_ticks_position('both') plt.gca().xaxis.set_ticks_position('both') - + plt.xlabel("$Q$ [nm${}^{-1}$]") plt.ylabel("Reflectivity") - + plt.tight_layout() plt.show() if __name__ == '__main__': - + polarizer_efficiency = 0.986 - analyzer_efficiency = 0.970 - - results_pp = run_simulation(polarization = ba.kvector_t(0, 1, 0), - analyzer = ba.kvector_t(0, 1, 0), - polarizer_efficiency = polarizer_efficiency, - analyzer_efficiency = analyzer_efficiency ) - results_mm = run_simulation(polarization = ba.kvector_t(0, -1, 0), - analyzer = ba.kvector_t(0, -1, 0), - polarizer_efficiency = polarizer_efficiency, - analyzer_efficiency = analyzer_efficiency ) - - results_pm = run_simulation(polarization = ba.kvector_t(0, 1, 0), - analyzer = ba.kvector_t(0, -1, 0), - polarizer_efficiency = polarizer_efficiency, - analyzer_efficiency = analyzer_efficiency ) - results_mp = run_simulation(polarization = ba.kvector_t(0, -1, 0), - analyzer = ba.kvector_t(0, 1, 0), - polarizer_efficiency = polarizer_efficiency, - analyzer_efficiency = analyzer_efficiency ) - - plot([results_pp, results_mm, results_pm, results_mp], + analyzer_efficiency = 0.970 + + results_pp = run_simulation(polarization=ba.kvector_t(0, 1, 0), + analyzer=ba.kvector_t(0, 1, 0), + polarizer_efficiency=polarizer_efficiency, + analyzer_efficiency=analyzer_efficiency) + results_mm = run_simulation(polarization=ba.kvector_t(0, -1, 0), + analyzer=ba.kvector_t(0, -1, 0), + polarizer_efficiency=polarizer_efficiency, + analyzer_efficiency=analyzer_efficiency) + + results_pm = run_simulation(polarization=ba.kvector_t(0, 1, 0), + analyzer=ba.kvector_t(0, -1, 0), + polarizer_efficiency=polarizer_efficiency, + analyzer_efficiency=analyzer_efficiency) + results_mp = run_simulation(polarization=ba.kvector_t(0, -1, 0), + analyzer=ba.kvector_t(0, 1, 0), + polarizer_efficiency=polarizer_efficiency, + analyzer_efficiency=analyzer_efficiency) + + plot([results_pp, results_mm, results_pm, results_mp], ["$++$", "$--$", "$+-$", "$-+$"]) diff --git a/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetry.py b/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetry.py index 6a6e15442313e458d2435ed8b85f56f3d433ceb4..247cde5ccc4f8c91c0490154663296b3b026edb4 100644 --- a/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetry.py +++ b/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetry.py @@ -28,57 +28,52 @@ qmin = 0.05997 qmax = 1.96 # number of points on which the computed result is plotted -scan_size=1500 +scan_size = 1500 # The SLD of the substrate is kept constant -sldMao = (5.377e-06, 0) +sldMao = (5.377e-06, 0) # constant to convert between magnetization and magnetic SLD RhoMconst = 2.910429812376859e-12 - - - - #################################################################### # Create Sample and Simulation # #################################################################### - - + + def get_sample(params): """ construct the sample with the given parameters """ magnetizationMagnitude = params["rhoM_Mafo"] * 1e-6 / RhoMconst - angle = 0 - magnetizationVector = ba.kvector_t( - magnetizationMagnitude * numpy.sin(angle * deg), - magnetizationMagnitude * numpy.cos(angle * deg), - 0) - - mat_vacuum = ba.MaterialBySLD("Vacuum", 0.0, 0.0) - mat_layer = ba.MaterialBySLD("(Mg,Al,Fe)3O4", - params["rho_Mafo"] * 1e-6, 0, magnetizationVector) + angle = 0 + magnetizationVector = ba.kvector_t( + magnetizationMagnitude * numpy.sin(angle * deg), + magnetizationMagnitude * numpy.cos(angle * deg), 0) + + mat_vacuum = ba.MaterialBySLD("Vacuum", 0.0, 0.0) + mat_layer = ba.MaterialBySLD("(Mg,Al,Fe)3O4", params["rho_Mafo"] * 1e-6, 0, + magnetizationVector) mat_substrate = ba.MaterialBySLD("MgAl2O4", *sldMao) - + ambient_layer = ba.Layer(mat_vacuum) layer = ba.Layer(mat_layer, params["t_Mafo"] * angstrom) substrate_layer = ba.Layer(mat_substrate) - + r_Mafo = ba.LayerRoughness() r_Mafo.setSigma(params["r_Mafo"] * angstrom) - + r_substrate = ba.LayerRoughness() r_substrate.setSigma(params["r_Mao"] * angstrom) - + multi_layer = ba.MultiLayer() multi_layer.addLayer(ambient_layer) multi_layer.addLayerWithTopRoughness(layer, r_Mafo) multi_layer.addLayerWithTopRoughness(substrate_layer, r_substrate) - + return multi_layer - - + + def get_simulation(q_axis, parameters, polarization, analyzer): """ Returns a simulation object. @@ -88,21 +83,21 @@ def get_simulation(q_axis, parameters, polarization, analyzer): simulation = ba.SpecularSimulation() q_axis = q_axis + parameters["q_offset"] scan = ba.QSpecScan(q_axis) - + dq = parameters["q_res"] * q_axis n_sig = 4.0 n_samples = 25 - + distr = ba.RangedDistributionGaussian(n_samples, n_sig) scan.setAbsoluteQResolution(distr, parameters["q_res"]) - + simulation.setBeamPolarization(polarization) simulation.setAnalyzerProperties(analyzer, 1.0, 0.5) - + simulation.setScan(scan) return simulation - - + + def run_simulation(q_axis, fitParams, *, polarization, analyzer): """ Run a simulation on the given q-axis, where the sample is @@ -110,10 +105,9 @@ def run_simulation(q_axis, fitParams, *, polarization, analyzer): Vectors for polarization and analyzer need to be provided """ parameters = dict(fitParams, **fixedParams) - + sample = get_sample(parameters) - simulation = get_simulation(q_axis, parameters, - polarization, analyzer) + simulation = get_simulation(q_axis, parameters, polarization, analyzer) simulation.setSample(sample) simulation.runSimulation() @@ -125,38 +119,42 @@ def qr(result): Returns two arrays that hold the q-values as well as the reflectivity from a given simulation result """ - q = numpy.array( result.result().axis(ba.Axes.QSPACE) ) - r = numpy.array( result.result().array(ba.Axes.QSPACE) ) - - return q, r - + q = numpy.array(result.result().axis(ba.Axes.QSPACE)) + r = numpy.array(result.result().array(ba.Axes.QSPACE)) + return q, r #################################################################### # Plot Handling # #################################################################### + def plot(qs, rs, exps, labels, filename): """ Plot the simulated result together with the experimental data """ fig = plt.figure() ax = fig.add_subplot(111) - + for q, r, exp, l in zip(qs, rs, exps, labels): - - ax.errorbar( exp[0], exp[1], xerr=exp[3], yerr=exp[2], - fmt='.', markersize=0.75, linewidth=0.5) - - ax.plot(q, r, label=l) - + + ax.errorbar(exp[0], + exp[1], + xerr=exp[3], + yerr=exp[2], + fmt='.', + markersize=0.75, + linewidth=0.5) + + ax.plot(q, r, label=l) + ax.set_yscale('log') plt.legend() - + plt.xlabel("Q [nm${}^{-1}$]") plt.ylabel("R") - + plt.tight_layout() plt.savefig(filename) @@ -166,32 +164,33 @@ def plotSpinAsymmetry(data_pp, data_mm, q, r_pp, r_mm, filename): Plot the simulated spin asymmetry as well its experimental counterpart with errorbars """ - + # compute the errorbars of the spin asymmetry delta = numpy.sqrt(4 * (data_pp[1]**2 * data_mm[2]**2 + \ - data_mm[1]**2 * data_pp[2]**2 ) / + data_mm[1]**2 * data_pp[2]**2 ) / ( data_pp[1] + data_mm[1] )**4 ) - + fig = plt.figure() ax = fig.add_subplot(111) - - ax.errorbar( data_pp[0], - (data_pp[1] - data_mm[1])/(data_pp[1] + data_mm[1]), - xerr = data_pp[3], yerr = delta, - fmt='.', markersize=0.75, linewidth=0.5 ) - - ax.plot(q, (r_pp - r_mm)/(r_pp + r_mm)) - + + ax.errorbar(data_pp[0], (data_pp[1] - data_mm[1]) / (data_pp[1] + data_mm[1]), + xerr=data_pp[3], + yerr=delta, + fmt='.', + markersize=0.75, + linewidth=0.5) + + ax.plot(q, (r_pp - r_mm) / (r_pp + r_mm)) + plt.gca().set_ylim((-0.3, 0.5)) - + plt.xlabel("Q [nm${}^{-1}$]") plt.ylabel("Spin asymmetry") - + plt.tight_layout() plt.savefig(filename) - #################################################################### # Data Handling # #################################################################### @@ -203,119 +202,109 @@ def normalizeData(data): normalizes it such that the maximum of the reflectivity is unity and rescales the q-axis to inverse nm """ - - r0 = numpy.where( data[0] - numpy.roll(data[0], 1) == 0) + + r0 = numpy.where(data[0] - numpy.roll(data[0], 1) == 0) data = numpy.delete(data, r0, 1) - + data[0] = data[0] / angstrom data[3] = data[3] / angstrom - - norm = numpy.max( data[1] ) - data[1] = data[1] / norm - data[2] = data[2] / norm - - so = numpy.argsort( data[0] ) - data = data[:,so] - + + norm = numpy.max(data[1]) + data[1] = data[1] / norm + data[2] = data[2] / norm + + so = numpy.argsort(data[0]) + data = data[:, so] + return data + def filterData(data, qmin, qmax): - minIndex = numpy.argmin( numpy.abs( data[0] - qmin ) ) - maxIndex = numpy.argmin( numpy.abs( data[0] - qmax ) ) - - return data[:,minIndex:maxIndex+1] + minIndex = numpy.argmin(numpy.abs(data[0] - qmin)) + maxIndex = numpy.argmin(numpy.abs(data[0] - qmax)) + + return data[:, minIndex:maxIndex + 1] + def get_Experimental_data(qmin, qmax): if hasattr(get_Experimental_data, "raw_data"): data_pp = get_Experimental_data.raw_data_pp data_mm = get_Experimental_data.raw_data_mm - + else: input_Data = downloadAndExtractData() data_pp = normalizeData(input_Data[0]) data_mm = normalizeData(input_Data[1]) - + get_Experimental_data.data_pp = data_pp get_Experimental_data.data_mm = data_mm get_Experimental_data.raw_data = True - - return ( filterData( data_pp, qmin, qmax) , - filterData( data_mm, qmin, qmax) ) + return (filterData(data_pp, qmin, qmax), filterData(data_mm, qmin, qmax)) def downloadAndExtractData(): url = "https://www.nist.gov/document/spinelfilmzip" - + if not isfile("spinelfilm.zip"): - downloadfile = urlopen(url) - with open("spinelfilm.zip", 'wb') as outfile: - outfile.write(downloadfile.read()) - + downloadfile = urlopen(url) + with open("spinelfilm.zip", 'wb') as outfile: + outfile.write(downloadfile.read()) + zipfile = ZipFile("spinelfilm.zip") rawdata = zipfile.open("MAFO_Saturated.refl").\ read().decode("utf-8") - - table_pp = match( - r'.*# "polarization": "\+\+"\n#.*?\n# "units".*?\n(.*?)#.*', - rawdata, DOTALL).group(1) - table_mm = match( - r'.*# "polarization": "\-\-"\n#.*?\n# "units".*?\n(.*?)#.*', - rawdata, DOTALL).group(1) - - data_pp = numpy.genfromtxt(BytesIO(table_pp.encode()), - unpack=True) - data_mm = numpy.genfromtxt(BytesIO(table_mm.encode()), - unpack=True) - - return (data_pp, data_mm) + table_pp = match(r'.*# "polarization": "\+\+"\n#.*?\n# "units".*?\n(.*?)#.*', + rawdata, DOTALL).group(1) + table_mm = match(r'.*# "polarization": "\-\-"\n#.*?\n# "units".*?\n(.*?)#.*', + rawdata, DOTALL).group(1) + + data_pp = numpy.genfromtxt(BytesIO(table_pp.encode()), unpack=True) + data_mm = numpy.genfromtxt(BytesIO(table_mm.encode()), unpack=True) + + return (data_pp, data_mm) #################################################################### # Main Function # #################################################################### - if __name__ == '__main__': fixedParams = { - # parameters from our own fit run - 'q_res': (0.01027065792503683, ), - 'q_offset': (8.977754679340925e-05, ), - - 'rho_Mafo': (6.373962950920891, ), - 'rhoM_Mafo': (0.2383070807371731, ), - 't_Mafo': (137.73795730237237, ), - - 'r_Mao': (7.004715629445297, ), - 'r_Mafo': (3.8860835236521702, ), - } - - fixedParams = { d:v[0] for d, v in fixedParams.items() } - - def run_Simulation_pp( qzs, params ): - return run_simulation(qzs, params, - polarization = ba.kvector_t(0, 1, 0), - analyzer = ba.kvector_t(0, 1, 0)) - - def run_Simulation_mm( qzs, params ): - return run_simulation(qzs, params, - polarization = ba.kvector_t(0, -1, 0), - analyzer = ba.kvector_t(0, -1, 0)) + # parameters from our own fit run + 'q_res': (0.01027065792503683, ), + 'q_offset': (8.977754679340925e-05, ), + 'rho_Mafo': (6.373962950920891, ), + 'rhoM_Mafo': (0.2383070807371731, ), + 't_Mafo': (137.73795730237237, ), + 'r_Mao': (7.004715629445297, ), + 'r_Mafo': (3.8860835236521702, ), + } + + fixedParams = {d: v[0] for d, v in fixedParams.items()} + + def run_Simulation_pp(qzs, params): + return run_simulation(qzs, + params, + polarization=ba.kvector_t(0, 1, 0), + analyzer=ba.kvector_t(0, 1, 0)) + + def run_Simulation_mm(qzs, params): + return run_simulation(qzs, + params, + polarization=ba.kvector_t(0, -1, 0), + analyzer=ba.kvector_t(0, -1, 0)) qzs = numpy.linspace(qmin, qmax, scan_size) - q_pp, r_pp = qr( run_Simulation_pp( qzs, fixedParams ) ) - q_mm, r_mm = qr( run_Simulation_mm( qzs, fixedParams ) ) - + q_pp, r_pp = qr(run_Simulation_pp(qzs, fixedParams)) + q_mm, r_mm = qr(run_Simulation_mm(qzs, fixedParams)) + data_pp, data_mm = get_Experimental_data(qmin, qmax) - - plot([q_pp, q_mm], [r_pp, r_mm], - [data_pp, data_mm], ["$++$", "$--$"], - f'MAFO_Saturated.pdf' ) - - plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm, + + plot([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm], ["$++$", "$--$"], + f'MAFO_Saturated.pdf') + + plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm, "MAFO_Saturated_spin_asymmetry.pdf") - - - diff --git a/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetryFit.py b/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetryFit.py index 3e193e00606552d88ffb3580cf3a031964e6d6a1..ab5b87d582b1c80d4a3c3c1fbbabb84f1638976a 100644 --- a/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetryFit.py +++ b/Examples/Python/sim21_Reflectometry/PolarizedSpinAsymmetryFit.py @@ -28,18 +28,14 @@ qmin = 0.05997 qmax = 1.96 # number of points on which the computed result is plotted -scan_size=1500 +scan_size = 1500 # The SLD of the substrate is kept constant -sldMao = (5.377e-06, 0) +sldMao = (5.377e-06, 0) # constant to convert between magnetization and magnetic SLD RhoMconst = 2.910429812376859e-12 - - - - #################################################################### # Create Sample and Simulation # #################################################################### @@ -50,15 +46,14 @@ def get_sample(params): construct the sample with the given parameters """ magnetizationMagnitude = params["rhoM_Mafo"] * 1e-6 / RhoMconst - angle = 0 - magnetizationVector = ba.kvector_t( - magnetizationMagnitude * numpy.sin(angle * deg), - magnetizationMagnitude * numpy.cos(angle * deg), - 0) - - mat_vacuum = ba.MaterialBySLD("Vacuum", 0.0, 0.0) - mat_layer = ba.MaterialBySLD("(Mg,Al,Fe)3O4", - params["rho_Mafo"] * 1e-6, 0, magnetizationVector) + angle = 0 + magnetizationVector = ba.kvector_t( + magnetizationMagnitude * numpy.sin(angle * deg), + magnetizationMagnitude * numpy.cos(angle * deg), 0) + + mat_vacuum = ba.MaterialBySLD("Vacuum", 0.0, 0.0) + mat_layer = ba.MaterialBySLD("(Mg,Al,Fe)3O4", params["rho_Mafo"] * 1e-6, 0, + magnetizationVector) mat_substrate = ba.MaterialBySLD("MgAl2O4", *sldMao) ambient_layer = ba.Layer(mat_vacuum) @@ -67,15 +62,15 @@ def get_sample(params): r_Mafo = ba.LayerRoughness() r_Mafo.setSigma(params["r_Mafo"] * angstrom) - + r_substrate = ba.LayerRoughness() r_substrate.setSigma(params["r_Mao"] * angstrom) - + multi_layer = ba.MultiLayer() multi_layer.addLayer(ambient_layer) multi_layer.addLayerWithTopRoughness(layer, r_Mafo) multi_layer.addLayerWithTopRoughness(substrate_layer, r_substrate) - + return multi_layer @@ -88,7 +83,7 @@ def get_simulation(q_axis, parameters, polarization, analyzer): simulation = ba.SpecularSimulation() q_axis = q_axis + parameters["q_offset"] scan = ba.QSpecScan(q_axis) - + dq = parameters["q_res"] * q_axis n_sig = 4.0 n_samples = 25 @@ -98,7 +93,7 @@ def get_simulation(q_axis, parameters, polarization, analyzer): simulation.setBeamPolarization(polarization) simulation.setAnalyzerProperties(analyzer, 1.0, 0.5) - + simulation.setScan(scan) return simulation @@ -110,10 +105,9 @@ def run_simulation(q_axis, fitParams, *, polarization, analyzer): Vectors for polarization and analyzer need to be provided """ parameters = dict(fitParams, **fixedParams) - + sample = get_sample(parameters) - simulation = get_simulation(q_axis, parameters, - polarization, analyzer) + simulation = get_simulation(q_axis, parameters, polarization, analyzer) simulation.setSample(sample) simulation.runSimulation() @@ -125,9 +119,9 @@ def qr(result): Returns two arrays that hold the q-values as well as the reflectivity from a given simulation result """ - q = numpy.array( result.result().axis(ba.Axes.QSPACE) ) - r = numpy.array( result.result().array(ba.Axes.QSPACE) ) - + q = numpy.array(result.result().axis(ba.Axes.QSPACE)) + r = numpy.array(result.result().array(ba.Axes.QSPACE)) + return q, r @@ -136,27 +130,31 @@ def qr(result): #################################################################### - def plot(qs, rs, exps, labels, filename): """ Plot the simulated result together with the experimental data """ fig = plt.figure() ax = fig.add_subplot(111) - + for q, r, exp, l in zip(qs, rs, exps, labels): - - ax.errorbar( exp[0], exp[1], xerr=exp[3], yerr=exp[2], - fmt='.', markersize=0.75, linewidth=0.5) - - ax.plot(q, r, label=l) - + + ax.errorbar(exp[0], + exp[1], + xerr=exp[3], + yerr=exp[2], + fmt='.', + markersize=0.75, + linewidth=0.5) + + ax.plot(q, r, label=l) + ax.set_yscale('log') plt.legend() - + plt.xlabel("Q [nm${}^{-1}$]") plt.ylabel("R") - + plt.tight_layout() plt.savefig(filename) @@ -166,27 +164,29 @@ def plotSpinAsymmetry(data_pp, data_mm, q, r_pp, r_mm, filename): Plot the simulated spin asymmetry as well its experimental counterpart with errorbars """ - + # compute the errorbars of the spin asymmetry delta = numpy.sqrt(4 * (data_pp[1]**2 * data_mm[2]**2 + \ - data_mm[1]**2 * data_pp[2]**2 ) / + data_mm[1]**2 * data_pp[2]**2 ) / ( data_pp[1] + data_mm[1] )**4 ) - + fig = plt.figure() ax = fig.add_subplot(111) - - ax.errorbar( data_pp[0], - (data_pp[1] - data_mm[1])/(data_pp[1] + data_mm[1]), - xerr = data_pp[3], yerr = delta, - fmt='.', markersize=0.75, linewidth=0.5 ) - - ax.plot(q, (r_pp - r_mm)/(r_pp + r_mm)) - + + ax.errorbar(data_pp[0], (data_pp[1] - data_mm[1]) / (data_pp[1] + data_mm[1]), + xerr=data_pp[3], + yerr=delta, + fmt='.', + markersize=0.75, + linewidth=0.5) + + ax.plot(q, (r_pp - r_mm) / (r_pp + r_mm)) + plt.gca().set_ylim((-0.3, 0.5)) - + plt.xlabel("Q [nm${}^{-1}$]") plt.ylabel("Spin asymmetry") - + plt.tight_layout() plt.savefig(filename) @@ -202,74 +202,68 @@ def normalizeData(data): normalizes it such that the maximum of the reflectivity is unity and rescales the q-axis to inverse nm """ - - r0 = numpy.where( data[0] - numpy.roll(data[0], 1) == 0) + + r0 = numpy.where(data[0] - numpy.roll(data[0], 1) == 0) data = numpy.delete(data, r0, 1) - + data[0] = data[0] / angstrom data[3] = data[3] / angstrom - - norm = numpy.max( data[1] ) - data[1] = data[1] / norm - data[2] = data[2] / norm - - so = numpy.argsort( data[0] ) - data = data[:,so] - + + norm = numpy.max(data[1]) + data[1] = data[1] / norm + data[2] = data[2] / norm + + so = numpy.argsort(data[0]) + data = data[:, so] + return data + def filterData(data, qmin, qmax): - minIndex = numpy.argmin( numpy.abs( data[0] - qmin ) ) - maxIndex = numpy.argmin( numpy.abs( data[0] - qmax ) ) - - return data[:,minIndex:maxIndex+1] + minIndex = numpy.argmin(numpy.abs(data[0] - qmin)) + maxIndex = numpy.argmin(numpy.abs(data[0] - qmax)) + + return data[:, minIndex:maxIndex + 1] + def get_Experimental_data(qmin, qmax): if hasattr(get_Experimental_data, "raw_data"): data_pp = get_Experimental_data.raw_data_pp data_mm = get_Experimental_data.raw_data_mm - + else: input_Data = downloadAndExtractData() data_pp = normalizeData(input_Data[0]) data_mm = normalizeData(input_Data[1]) - + get_Experimental_data.data_pp = data_pp get_Experimental_data.data_mm = data_mm get_Experimental_data.raw_data = True - - return ( filterData( data_pp, qmin, qmax) , - filterData( data_mm, qmin, qmax) ) + return (filterData(data_pp, qmin, qmax), filterData(data_mm, qmin, qmax)) def downloadAndExtractData(): url = "https://www.nist.gov/document/spinelfilmzip" - + if not isfile("spinelfilm.zip"): - downloadfile = urlopen(url) - with open("spinelfilm.zip", 'wb') as outfile: - outfile.write(downloadfile.read()) - + downloadfile = urlopen(url) + with open("spinelfilm.zip", 'wb') as outfile: + outfile.write(downloadfile.read()) + zipfile = ZipFile("spinelfilm.zip") - + rawdata = zipfile.open("MAFO_Saturated.refl").read().decode("utf-8") - - table_pp = match( - r'.*# "polarization": "\+\+"\n#.*?\n# "units".*?\n(.*?)#.*', - rawdata, DOTALL).group(1) - table_mm = match( - r'.*# "polarization": "\-\-"\n#.*?\n# "units".*?\n(.*?)#.*', - rawdata, DOTALL).group(1) - - data_pp = numpy.genfromtxt(BytesIO(table_pp.encode()), - unpack=True) - data_mm = numpy.genfromtxt(BytesIO(table_mm.encode()), - unpack=True) - - return (data_pp, data_mm) + table_pp = match(r'.*# "polarization": "\+\+"\n#.*?\n# "units".*?\n(.*?)#.*', + rawdata, DOTALL).group(1) + table_mm = match(r'.*# "polarization": "\-\-"\n#.*?\n# "units".*?\n(.*?)#.*', + rawdata, DOTALL).group(1) + + data_pp = numpy.genfromtxt(BytesIO(table_pp.encode()), unpack=True) + data_mm = numpy.genfromtxt(BytesIO(table_mm.encode()), unpack=True) + return (data_pp, data_mm) #################################################################### @@ -278,118 +272,104 @@ def downloadAndExtractData(): def run_fit_ba(q_axis, rdata, simulationFactory, startParams): - + fit_objective = ba.FitObjective() fit_objective.setObjectiveMetric("reldiff") - - fit_objective.addSimulationAndData( - lambda params: simulationFactory[0](q_axis[0], params), - rdata[0], 1.0) - fit_objective.addSimulationAndData( - lambda params: simulationFactory[1](q_axis[1], params), - rdata[1], 1.0) - + + fit_objective.addSimulationAndData( + lambda params: simulationFactory[0](q_axis[0], params), rdata[0], 1.0) + fit_objective.addSimulationAndData( + lambda params: simulationFactory[1](q_axis[1], params), rdata[1], 1.0) + fit_objective.initPrint(10) - + params = ba.Parameters() for name, p in startParams.items(): params.add(name, p[0], min=p[1], max=p[2]) - + minimizer = ba.Minimizer() - + result = minimizer.minimize(fit_objective.evaluate, params) fit_objective.finalize(result) - - return { r.name():r.value for r in result.parameters() } - - + return {r.name(): r.value for r in result.parameters()} #################################################################### # Main Function # #################################################################### - if __name__ == '__main__': if len(argv) > 1 and argv[1] == "fit": fixedParams = { - # parameters can be moved here to keep them fixed - } + # parameters can be moved here to keep them fixed + } startParams = { - # own starting values - "q_res":(0.0, 0, 0.1), - "q_offset":(0, -0.002, 0.002), - - "rho_Mafo":(6.3649, 2, 7), - "rhoM_Mafo":(0, 0, 2), - "t_Mafo":(150, 60, 180), - - "r_Mao":( 1, 0, 12), - "r_Mafo":(1, 0, 12), - } + # own starting values + "q_res": (0.0, 0, 0.1), + "q_offset": (0, -0.002, 0.002), + "rho_Mafo": (6.3649, 2, 7), + "rhoM_Mafo": (0, 0, 2), + "t_Mafo": (150, 60, 180), + "r_Mao": (1, 0, 12), + "r_Mafo": (1, 0, 12), + } fit = True - + else: startParams = {} fixedParams = { - # parameters from our own fit run - 'q_res': (0.01027065792503683, ), - 'q_offset': (8.977754679340925e-05, ), - - 'rho_Mafo': (6.373962950920891, ), - 'rhoM_Mafo': (0.2383070807371731, ), - 't_Mafo': (137.73795730237237, ), - - 'r_Mao': (7.004715629445297, ), - 'r_Mafo': (3.8860835236521702, ), - } + # parameters from our own fit run + 'q_res': (0.01027065792503683, ), + 'q_offset': (8.977754679340925e-05, ), + 'rho_Mafo': (6.373962950920891, ), + 'rhoM_Mafo': (0.2383070807371731, ), + 't_Mafo': (137.73795730237237, ), + 'r_Mao': (7.004715629445297, ), + 'r_Mafo': (3.8860835236521702, ), + } fit = False - - fixedParams = { d:v[0] for d, v in fixedParams.items() } - paramsInitial = {d:v[0] for d, v in startParams.items()} - - def run_Simulation_pp( qzs, params ): - return run_simulation(qzs, params, - polarization = ba.kvector_t(0, 1, 0), - analyzer = ba.kvector_t(0, 1, 0)) + fixedParams = {d: v[0] for d, v in fixedParams.items()} + paramsInitial = {d: v[0] for d, v in startParams.items()} + + def run_Simulation_pp(qzs, params): + return run_simulation(qzs, + params, + polarization=ba.kvector_t(0, 1, 0), + analyzer=ba.kvector_t(0, 1, 0)) - def run_Simulation_mm( qzs, params ): - return run_simulation(qzs, params, - polarization = ba.kvector_t(0, -1, 0), - analyzer = ba.kvector_t(0, -1, 0)) + def run_Simulation_mm(qzs, params): + return run_simulation(qzs, + params, + polarization=ba.kvector_t(0, -1, 0), + analyzer=ba.kvector_t(0, -1, 0)) qzs = numpy.linspace(qmin, qmax, scan_size) - q_pp, r_pp = qr( run_Simulation_pp( qzs, paramsInitial ) ) - q_mm, r_mm = qr( run_Simulation_mm( qzs, paramsInitial ) ) - + q_pp, r_pp = qr(run_Simulation_pp(qzs, paramsInitial)) + q_mm, r_mm = qr(run_Simulation_mm(qzs, paramsInitial)) + data_pp, data_mm = get_Experimental_data(qmin, qmax) - - plot([q_pp, q_mm], [r_pp, r_mm], - [data_pp, data_mm], ["$++$", "$--$"], - f'MAFO_Saturated_initial.pdf' ) - - plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm, + + plot([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm], ["$++$", "$--$"], + f'MAFO_Saturated_initial.pdf') + + plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm, "MAFO_Saturated_spin_asymmetry_initial.pdf") - + if fit: - fitResult = run_fit_ba([data_pp[0], data_mm[0]], - [data_pp[1], data_mm[1]], - [run_Simulation_pp, run_Simulation_mm], startParams) + fitResult = run_fit_ba([data_pp[0], data_mm[0]], [data_pp[1], data_mm[1]], + [run_Simulation_pp, run_Simulation_mm], startParams) print("Fit Result:") print(fitResult) - - q_pp, r_pp = qr( run_Simulation_pp( qzs, fitResult ) ) - q_mm, r_mm = qr( run_Simulation_mm( qzs, fitResult ) ) - - plot([q_pp, q_mm], [r_pp, r_mm], - [data_pp, data_mm], ["$++$", "$--$"], - f'MAFO_Saturated_fit.pdf' ) - - plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm, + + q_pp, r_pp = qr(run_Simulation_pp(qzs, fitResult)) + q_mm, r_mm = qr(run_Simulation_mm(qzs, fitResult)) + + plot([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm], ["$++$", "$--$"], + f'MAFO_Saturated_fit.pdf') + + plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm, "MAFO_Saturated_spin_asymmetry_fit.pdf") - - diff --git a/Examples/Python/sim21_Reflectometry/PolarizedSpinFlip.py b/Examples/Python/sim21_Reflectometry/PolarizedSpinFlip.py index 86799d8a01209c410ad2b131447be72b76f1f27d..f0d732b4480b3f0c7ba93caa809778640842ae1b 100644 --- a/Examples/Python/sim21_Reflectometry/PolarizedSpinFlip.py +++ b/Examples/Python/sim21_Reflectometry/PolarizedSpinFlip.py @@ -9,23 +9,21 @@ from bornagain import deg, angstrom import matplotlib.pyplot as plt + def get_sample(): """ Defines sample and returns it """ - + # parametrize the magnetization magnetizationMagnitude = 1e8 - angle = 30 * deg - magnetizationVector = ba.kvector_t( - magnetizationMagnitude * numpy.sin(angle), - magnetizationMagnitude * numpy.cos(angle), - 0) + angle = 30 * deg + magnetizationVector = ba.kvector_t(magnetizationMagnitude * numpy.sin(angle), + magnetizationMagnitude * numpy.cos(angle), 0) # creating materials m_ambient = ba.MaterialBySLD("Ambient", 0.0, 0.0) - m_layer_mat = ba.MaterialBySLD("Layer", 1e-4, 1e-8, - magnetizationVector) + m_layer_mat = ba.MaterialBySLD("Layer", 1e-4, 1e-8, magnetizationVector) m_substrate = ba.MaterialBySLD("Substrate", 7e-5, 2e-6) # creating layers @@ -47,8 +45,7 @@ def get_simulation(scan_size=500): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, - 0.0 * deg, 5.0 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, 0.0 * deg, 5.0 * deg) simulation.setScan(scan) return simulation @@ -71,34 +68,28 @@ def run_simulation(polarization=ba.kvector_t(0, 1, 0), def plot(data, labels): - + plt.figure() for d, l in zip(data, labels): - plt.semilogy( d.axis(), - d.array(), - label=l, linewidth=1) - - plt.legend( loc='upper right' ) + plt.semilogy(d.axis(), d.array(), label=l, linewidth=1) + + plt.legend(loc='upper right') plt.gca().yaxis.set_ticks_position('both') plt.gca().xaxis.set_ticks_position('both') - + plt.xlabel(r"$\alpha_i$ [deg]") plt.ylabel("Reflectivity") - + plt.tight_layout() plt.show() if __name__ == '__main__': - results_pp = run_simulation(ba.kvector_t(0, 1, 0), - ba.kvector_t(0, 1, 0)) - results_mm = run_simulation(ba.kvector_t(0, -1, 0), - ba.kvector_t(0, -1, 0)) + results_pp = run_simulation(ba.kvector_t(0, 1, 0), ba.kvector_t(0, 1, 0)) + results_mm = run_simulation(ba.kvector_t(0, -1, 0), ba.kvector_t(0, -1, 0)) - results_pm = run_simulation(ba.kvector_t(0, 1, 0), - ba.kvector_t(0, -1, 0)) - results_mp = run_simulation(ba.kvector_t(0, -1, 0), - ba.kvector_t(0, 1, 0)) + results_pm = run_simulation(ba.kvector_t(0, 1, 0), ba.kvector_t(0, -1, 0)) + results_mp = run_simulation(ba.kvector_t(0, -1, 0), ba.kvector_t(0, 1, 0)) - plot([results_pp, results_mm, results_pm, results_mp], + plot([results_pp, results_mm, results_pm, results_mp], ["$++$", "$--$", "$+-$", "$-+$"]) diff --git a/Examples/Python/sim21_Reflectometry/RoughnessModel.py b/Examples/Python/sim21_Reflectometry/RoughnessModel.py index fc05f5a3129cda72ba502fe68fca87638392e611..59f3d14324b037e3acefd34c3b176c8bb2b2be02 100644 --- a/Examples/Python/sim21_Reflectometry/RoughnessModel.py +++ b/Examples/Python/sim21_Reflectometry/RoughnessModel.py @@ -8,6 +8,7 @@ from matplotlib import pyplot as plt import bornagain as ba from bornagain import deg, angstrom, nm + def get_sample(roughness_model): """ Defines sample and returns it @@ -36,7 +37,7 @@ def get_sample(roughness_model): multi_layer.addLayerWithTopRoughness(ti_layer, roughness) multi_layer.addLayerWithTopRoughness(ni_layer, roughness) multi_layer.addLayerWithTopRoughness(substrate_layer, roughness) - + multi_layer.setRoughnessModel(roughness_model) return multi_layer @@ -47,8 +48,7 @@ def get_simulation(scan_size=500): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, - 0.0 * deg, 2.0 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, 0.0 * deg, 2.0 * deg) simulation.setScan(scan) return simulation @@ -65,20 +65,21 @@ def run_simulation(roughness_model=ba.RoughnessModel.TANH): def plot(result_tanh, result_nevot_croce): - - plt.semilogy(result_nevot_croce.axis(), result_nevot_croce.array(), + + plt.semilogy(result_nevot_croce.axis(), + result_nevot_croce.array(), label="Névot-Croce") plt.semilogy(result_tanh.axis(), result_tanh.array(), label="Tanh") - + plt.xlabel(r'$\alpha_i \; (deg)$', fontsize=12) plt.ylabel(r'Intensity', fontsize=12) - + plt.legend() plt.show() if __name__ == '__main__': result_tanh = run_simulation(roughness_model=ba.RoughnessModel.TANH) - result_nevot_croce = run_simulation( + result_nevot_croce = run_simulation( roughness_model=ba.RoughnessModel.NEVOT_CROCE) plot(result_tanh, result_nevot_croce) diff --git a/Examples/Python/sim21_Reflectometry/SpecularSimulationWithRoughness.py b/Examples/Python/sim21_Reflectometry/SpecularSimulationWithRoughness.py index 461545a99b24003715b181112b5b8d8af9f800a8..b3e8863138bd6cf095cc42ae947c1586a321151f 100644 --- a/Examples/Python/sim21_Reflectometry/SpecularSimulationWithRoughness.py +++ b/Examples/Python/sim21_Reflectometry/SpecularSimulationWithRoughness.py @@ -44,8 +44,7 @@ def get_simulation(scan_size=500): Defines and returns a specular simulation. """ simulation = ba.SpecularSimulation() - scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, - 0.0 * deg, 2.0 * deg) + scan = ba.AngularSpecScan(1.54 * angstrom, scan_size, 0.0 * deg, 2.0 * deg) simulation.setScan(scan) return simulation diff --git a/Examples/Python/sim22_OffSpecular/BoxesWithSpecularPeak.py b/Examples/Python/sim22_OffSpecular/BoxesWithSpecularPeak.py index c401213ac521c676c2660c1de80d17726a549c72..640b83dceca0b0e7828ab42f6ae4b3d123668506 100644 --- a/Examples/Python/sim22_OffSpecular/BoxesWithSpecularPeak.py +++ b/Examples/Python/sim22_OffSpecular/BoxesWithSpecularPeak.py @@ -15,14 +15,15 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 3e-5, 2e-8) # cylindrical particle - box_ff = ba.FormFactorBox(5*nm, 5*nm, 10*nm) + box_ff = ba.FormFactorBox(5 * nm, 5 * nm, 10 * nm) box = ba.Particle(m_particle, box_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(box) # interference function - interference = ba.InterferenceFunction2DLattice(ba.SquareLattice2D(8*nm, 0*deg)) - pdf = ba.FTDecayFunction2DCauchy(100*nm, 100*nm, 0) + interference = ba.InterferenceFunction2DLattice( + ba.SquareLattice2D(8 * nm, 0 * deg)) + pdf = ba.FTDecayFunction2DCauchy(100 * nm, 100 * nm, 0) interference.setDecayFunction(pdf) particle_layout.setInterferenceFunction(interference) @@ -41,9 +42,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(101, -2.0*deg, 2.0*deg, - 101, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(101, -2.0 * deg, 2.0 * deg, 101, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.getOptions().setUseAvgMaterials(True) simulation.getOptions().setIncludeSpecular(True) return simulation diff --git a/Examples/Python/sim23_SAS/PolarizedSANS.py b/Examples/Python/sim23_SAS/PolarizedSANS.py index ce4f30ebc72f482284c6dd61f2c16f00f47ec93f..6620a09bd01d2799584827ce4220c9654d10065d 100644 --- a/Examples/Python/sim23_SAS/PolarizedSANS.py +++ b/Examples/Python/sim23_SAS/PolarizedSANS.py @@ -16,8 +16,7 @@ def get_sample(): """ # Defining Materials mat_solvent = ba.HomogeneousMaterial("Solvent", 5e-6, 0.0) - mat_core = ba.HomogeneousMaterial("Core", 6e-6, 2e-8, - magnetization_core) + mat_core = ba.HomogeneousMaterial("Core", 6e-6, 2e-8, magnetization_core) mat_shell = ba.HomogeneousMaterial("Shell", 1e-7, 2e-8) # Defining Layer @@ -25,8 +24,8 @@ def get_sample(): # Defining particle layout with a core-shell particle layout = ba.ParticleLayout() - core_sphere_ff = ba.FormFactorFullSphere(10*nm) - shell_sphere_ff = ba.FormFactorFullSphere(12*nm) + core_sphere_ff = ba.FormFactorFullSphere(10 * nm) + shell_sphere_ff = ba.FormFactorFullSphere(12 * nm) core = ba.Particle(mat_core, core_sphere_ff) shell = ba.Particle(mat_shell, shell_sphere_ff) position = kvector_t(0.0, 0.0, 2.0) @@ -49,10 +48,11 @@ def get_simulation(): simulation = ba.GISASSimulation() # Defining detector - simulation.setDetectorParameters(200, -3.0*deg, 3.0*deg, 200, -3.0*deg, 3.0*deg) + simulation.setDetectorParameters(200, -3.0 * deg, 3.0 * deg, 200, -3.0 * deg, + 3.0 * deg) # Defining beam parameters - simulation.setBeamParameters(0.5*nm, 0.0*deg, 0.0*deg) + simulation.setBeamParameters(0.5 * nm, 0.0 * deg, 0.0 * deg) simulation.setBeamIntensity(1e12) # Defining beam polarization and polarization analysis for spin-flip channel @@ -74,7 +74,9 @@ def run_simulation(): return simulation.result() -if __name__ == '__main__': +if __name__ == '__main__': result = run_simulation() - ba.plot_simulation_result(result, cmap='jet', units=ba.Axes.QSPACE, + ba.plot_simulation_result(result, + cmap='jet', + units=ba.Axes.QSPACE, aspect='auto') diff --git a/Examples/Python/sim29_DepthProbe/DepthProbe.py b/Examples/Python/sim29_DepthProbe/DepthProbe.py index 577293610a824546b5f3b6fa69937cfbf90cf3f6..7126872e21364e67fd442e3f3dec21e88c342b93 100644 --- a/Examples/Python/sim29_DepthProbe/DepthProbe.py +++ b/Examples/Python/sim29_DepthProbe/DepthProbe.py @@ -35,7 +35,7 @@ t_TiO2 = 30.0 * angstrom # beam data ai_min = 0.0 * deg # minimum incident angle ai_max = 1.0 * deg # maximum incident angle -n_ai_bins = 5000 # number of bins in incident angle axis +n_ai_bins = 5000 # number of bins in incident angle axis beam_sample_ratio = 0.01 # beam-to-sample size ratio wl = 10 * angstrom # wavelength in angstroms diff --git a/Examples/Python/sim31_Parameterization/AccessingSimulationResults.py b/Examples/Python/sim31_Parameterization/AccessingSimulationResults.py index 3f923e86ee0a35726522912458fbe5e36e9d9291..dfa3d4d93b4e8e122aff2787b665f72dbd57d7ae 100644 --- a/Examples/Python/sim31_Parameterization/AccessingSimulationResults.py +++ b/Examples/Python/sim31_Parameterization/AccessingSimulationResults.py @@ -20,7 +20,7 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) particle_layout = ba.ParticleLayout() particle_layout.addParticle(cylinder, 1.0) @@ -40,9 +40,9 @@ def get_simulation(): Returns a GISAXS simulation with beam and detector defined. """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(201, -2.0*deg, 2.0*deg, - 201, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(201, -2.0 * deg, 2.0 * deg, 201, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) simulation.setBeamIntensity(1e+05) return simulation @@ -55,17 +55,21 @@ def get_noisy_image(hist): noise_factor = 2.0 for i in range(0, result.getTotalNumberOfBins()): amplitude = result.binContent(i) - sigma = noise_factor*math.sqrt(amplitude) + sigma = noise_factor * math.sqrt(amplitude) noisy_amplitude = random.gauss(amplitude, sigma) result.setBinContent(i, noisy_amplitude) return result def plot_histogram(hist, zmin=None, zmax=None): - ba.plot_histogram(hist, xlabel=r'$\varphi_f ^{\circ}$', + ba.plot_histogram(hist, + xlabel=r'$\varphi_f ^{\circ}$', ylabel=r'$\alpha_f ^{\circ}$', - zlabel="", zmin=zmin, zmax=zmax, - cmap='jet', aspect='auto') + zlabel="", + zmin=zmin, + zmax=zmax, + cmap='jet', + aspect='auto') def get_relative_difference(hist): @@ -85,15 +89,11 @@ def plot_slices(hist): # projection along Y, slice at fixed x-value proj1 = noisy.projectionY(0.0) - plt.semilogy(proj1.binCenters(), - proj1.binValues(), - label=r'$\phi=0.0^{\circ}$') + plt.semilogy(proj1.binCenters(), proj1.binValues(), label=r'$\phi=0.0^{\circ}$') # projection along Y, slice at fixed x-value proj2 = noisy.projectionY(0.5) # slice at fixed value - plt.semilogy(proj2.binCenters(), - proj2.binValues(), - label=r'$\phi=0.5^{\circ}$') + plt.semilogy(proj2.binCenters(), proj2.binValues(), label=r'$\phi=0.5^{\circ}$') # projection along Y for all X values between [xlow, xup], averaged proj3 = noisy.projectionY(0.41, 0.59) @@ -102,7 +102,7 @@ def plot_slices(hist): label=r'$<\phi>=0.5^{\circ}$') plt.xlim(proj1.getXmin(), proj1.getXmax()) - plt.ylim(proj2.getMinimum(), proj1.getMaximum()*10.0) + plt.ylim(proj2.getMinimum(), proj1.getMaximum() * 10.0) plt.xlabel(r'$\alpha_f ^{\circ}$', fontsize=16) plt.legend(loc='upper right') plt.tight_layout() diff --git a/Examples/Python/sim31_Parameterization/SimulationParameters.py b/Examples/Python/sim31_Parameterization/SimulationParameters.py index ad5586ffc84dcf63131da45934648dd00c38c30a..58ce805d58cf59ff2330e1ba217379637893b6aa 100644 --- a/Examples/Python/sim31_Parameterization/SimulationParameters.py +++ b/Examples/Python/sim31_Parameterization/SimulationParameters.py @@ -21,9 +21,9 @@ def get_sample(): m_particle = ba.HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nm, 5*nm) + cylinder_ff = ba.FormFactorCylinder(5 * nm, 5 * nm) cylinder = ba.Particle(m_particle, cylinder_ff) - prism_ff = ba.FormFactorPrism3(5*nm, 5*nm) + prism_ff = ba.FormFactorPrism3(5 * nm, 5 * nm) prism = ba.Particle(m_particle, prism_ff) layout = ba.ParticleLayout() @@ -47,9 +47,9 @@ def get_simulation(): Create and return GISAXS simulation with beam and detector defined """ simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, -1.0*deg, 1.0*deg, - 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, -1.0 * deg, 1.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) return simulation @@ -77,21 +77,22 @@ def run_simulation(): # simulation #2 # one sample parameter (cylinder height) is changed using exact parameter name - simulation.setParameterValue("/GISASSimulation/MultiLayer/Layer0/ParticleLayout" - "/Particle0/Cylinder/Height", 10.0*nm) + simulation.setParameterValue( + "/GISASSimulation/MultiLayer/Layer0/ParticleLayout" + "/Particle0/Cylinder/Height", 10.0 * nm) simulation.runSimulation() results[1] = simulation.result() # simulation #3 # all parameters matching criteria will be changed (cylinder height in this case) - simulation.setParameterValue("*/Cylinder/Height", 100.0*nm) + simulation.setParameterValue("*/Cylinder/Height", 100.0 * nm) simulation.runSimulation() results[2] = simulation.result() # simulation #4 # all parameters which are matching criteria will be changed - simulation.setParameterValue("*/Cylinder/Height", 10.0*nm) - simulation.setParameterValue("*/Prism3/*", 10.0*nm) + simulation.setParameterValue("*/Cylinder/Height", 10.0 * nm) + simulation.setParameterValue("*/Prism3/*", 10.0 * nm) simulation.runSimulation() results[3] = simulation.result() @@ -107,7 +108,7 @@ def plot(results): plt.figure(figsize=(12.80, 10.24)) for nplot, hist in results.items(): - plt.subplot(2, 2, nplot+1) + plt.subplot(2, 2, nplot + 1) ba.plot_colormap(hist, zlabel="", cmap='jet', aspect='auto') plt.tight_layout() plt.show() diff --git a/Examples/Python/utils/plot_intensity_data.py b/Examples/Python/utils/plot_intensity_data.py index 077bdbc2c014527463b4760296f77a0089eeadc2..8f8e8ee8e7a14cfe6593f017b179c80cd7b18145 100755 --- a/Examples/Python/utils/plot_intensity_data.py +++ b/Examples/Python/utils/plot_intensity_data.py @@ -10,7 +10,7 @@ import numpy as np import bornagain as ba from matplotlib import pyplot as plt from matplotlib import rc, colors -rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) +rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) @@ -27,10 +27,12 @@ def plot_intensity_data(file_name, intensity_max=None): def plot_intensity_data_2d(histogram, intensity_max): - plot_raw_data_2d(histogram.array(), - [histogram.getXmin() / ba.deg, histogram.getXmax() / ba.deg, - histogram.getYmin() / ba.deg, histogram.getYmax() / ba.deg], - intensity_max) + plot_raw_data_2d(histogram.array(), [ + histogram.getXmin() / ba.deg, + histogram.getXmax() / ba.deg, + histogram.getYmin() / ba.deg, + histogram.getYmax() / ba.deg + ], intensity_max) def plot_raw_data_2d(values, extent_array, intensity_max): @@ -62,10 +64,10 @@ def plot_raw_data_1d(axis, values, log_y=True): if __name__ == '__main__': - if len(sys.argv)<2 or len(sys.argv)>3: + if len(sys.argv) < 2 or len(sys.argv) > 3: exit("Usage: plot_intensity_data.py intensity_file.int.gz [intensity_max]") - if len(sys.argv)==2: + if len(sys.argv) == 2: plot_intensity_data(sys.argv[1]) else: plot_intensity_data(sys.argv[1], float(sys.argv[2])) diff --git a/Examples/Python/utils/plot_intensity_data_diff.py b/Examples/Python/utils/plot_intensity_data_diff.py index d79dd4ce5c13b5c329df0cd6e21f18f305585175..ceed9162b4aba4a25dbf71fecef97f16ace5247c 100755 --- a/Examples/Python/utils/plot_intensity_data_diff.py +++ b/Examples/Python/utils/plot_intensity_data_diff.py @@ -19,12 +19,12 @@ def plot_intensity_data_diff(filename1, filename2): exit("Both data sets are equal, there is nothing to plot.") rank = intensity_ref.rank() if rank == 2: - pid.plot_raw_data_2d(data, - [intensity_ref.getXmin() / ba.deg, - intensity_ref.getXmax() / ba.deg, - intensity_ref.getYmin() / ba.deg, - intensity_ref.getYmax() / ba.deg], - data.max()) + pid.plot_raw_data_2d(data, [ + intensity_ref.getXmin() / ba.deg, + intensity_ref.getXmax() / ba.deg, + intensity_ref.getYmin() / ba.deg, + intensity_ref.getYmax() / ba.deg + ], data.max()) elif rank == 1: axis_values = np.asarray(intensity_ref.xAxis().binCenters()) / ba.deg pid.plot_raw_data_1d(axis_values, data, log_y=False) @@ -33,7 +33,7 @@ def plot_intensity_data_diff(filename1, filename2): if __name__ == '__main__': - if len(sys.argv)!=3: + if len(sys.argv) != 3: exit("Usage: plot_intensity_data_diff.py reference.int.gz other.int.gz") plot_intensity_data_diff(sys.argv[1], sys.argv[2]) diff --git a/Examples/Python/utils/show2d.py b/Examples/Python/utils/show2d.py index 73a3d4ec22bcb2ba7dd54af37ec4b1384981565d..1b5bfea82f91403ca231b76ffe71403d3ff4c43f 100755 --- a/Examples/Python/utils/show2d.py +++ b/Examples/Python/utils/show2d.py @@ -8,26 +8,27 @@ from matplotlib.colors import LogNorm import argparse import os - # Define a nice colormap -cdict = {'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)), - 'green': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)), - 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0))} +cdict = { + 'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)), + 'green': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)), + 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)) +} blue_cmap = matplotlib.colors.LinearSegmentedColormap('blue_map', cdict, 256) -def PlotNumpyArray(a, zmin = 1, zmax = None): +def PlotNumpyArray(a, zmin=1, zmax=None): # Make a plot of the data #print( "plotting..." ) - amax=a.flatten().max() - amean=np.sum(a)/a.size - aminplot=amean**2/amax - a=np.maximum(a, zmin) - dataarray=np.flipud(np.transpose(a)) + amax = a.flatten().max() + amean = np.sum(a) / a.size + aminplot = amean**2 / amax + a = np.maximum(a, zmin) + dataarray = np.flipud(np.transpose(a)) plt.xlabel(r'$\phi_f$', fontsize=20) plt.ylabel(r'$\alpha_f$', fontsize=20) # Use one of the predefined colormaps or the above defined 'blue_cmap': - im=plt.imshow(dataarray, norm=LogNorm(), vmax=zmax, cmap=cm.jet) + im = plt.imshow(dataarray, norm=LogNorm(), vmax=zmax, cmap=cm.jet) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) plt.colorbar(im) @@ -46,14 +47,22 @@ def PlotNumpyArray(a, zmin = 1, zmax = None): if __name__ == '__main__': # Define the arguments to the script parser = argparse.ArgumentParser(description='Plot 2D data table on log scale.') - parser.add_argument('-m', '--minz', dest='zmin', metavar='MINZ', - help='minimum z-value to display [default: 1]', - default='1') - parser.add_argument('-M', '--maxz', dest='zmax', metavar='MAXZ', + parser.add_argument('-m', + '--minz', + dest='zmin', + metavar='MINZ', + help='minimum z-value to display [default: 1]', + default='1') + parser.add_argument( + '-M', + '--maxz', + dest='zmax', + metavar='MAXZ', help='maximum z-value to display [default: maximum value of data set]', default=None) - parser.add_argument('filename', metavar='filename', - help='filename of the data file') + parser.add_argument('filename', + metavar='filename', + help='filename of the data file') # Parse the script's arguments args = parser.parse_args() @@ -65,8 +74,8 @@ if __name__ == '__main__': filename = args.filename # Load the file's data - print( "loading..." ) - a=np.loadtxt(filename) + print("loading...") + a = np.loadtxt(filename) file_no_prefix = os.path.splitext(os.path.basename(filename))[0] print('Filename: ', file_no_prefix) print('Data shape: ', a.shape) diff --git a/Examples/Python/utils/show2d_root.py b/Examples/Python/utils/show2d_root.py index 10252373a0e67eac77021cf7f118136a6e6208af..777f65f9c441c2a547c8bb48c097e7f42d885627 100755 --- a/Examples/Python/utils/show2d_root.py +++ b/Examples/Python/utils/show2d_root.py @@ -10,14 +10,14 @@ import ROOT from pylab import * -def PlotNumpyArrayWithROOT(a, zmin = 1, zmax = None): +def PlotNumpyArrayWithROOT(a, zmin=1, zmax=None): nx = a.shape[0] ny = a.shape[1] - hist = ROOT.TH2D("hist","hist",nx,0,nx, ny, 0, ny) - for (x,y), value in numpy.ndenumerate(a): - hist.Fill(x,y,value) + hist = ROOT.TH2D("hist", "hist", nx, 0, nx, ny, 0, ny) + for (x, y), value in numpy.ndenumerate(a): + hist.Fill(x, y, value) - c1 = ROOT.TCanvas("c1","numpy array", 1024,768) + c1 = ROOT.TCanvas("c1", "numpy array", 1024, 768) c1.SetLogz() hist.SetMinimum(zmin) hist.Draw("CONT4Z") @@ -25,8 +25,8 @@ def PlotNumpyArrayWithROOT(a, zmin = 1, zmax = None): ROOT.gApplication.Run() #Interrupt = False #while not Interrupt: - #Interrupt = ROOT.gSystem.ProcessEvents() - #ROOT.gSystem.Sleep(10) + #Interrupt = ROOT.gSystem.ProcessEvents() + #ROOT.gSystem.Sleep(10) #------------------------------------------------------------- @@ -35,14 +35,22 @@ def PlotNumpyArrayWithROOT(a, zmin = 1, zmax = None): if __name__ == '__main__': # Define the arguments to the script parser = argparse.ArgumentParser(description='Plot 2D data table on log scale.') - parser.add_argument('-m', '--minz', dest='zmin', metavar='MINZ', - help='minimum z-value to display [default: 1]', - default='1') - parser.add_argument('-M', '--maxz', dest='zmax', metavar='MAXZ', + parser.add_argument('-m', + '--minz', + dest='zmin', + metavar='MINZ', + help='minimum z-value to display [default: 1]', + default='1') + parser.add_argument( + '-M', + '--maxz', + dest='zmax', + metavar='MAXZ', help='maximum z-value to display [default: maximum value of data set]', default=None) - parser.add_argument('filename', metavar='filename', - help='filename of the data file') + parser.add_argument('filename', + metavar='filename', + help='filename of the data file') # Parse the script's arguments args = parser.parse_args() @@ -54,8 +62,8 @@ if __name__ == '__main__': filename = args.filename # Load the file's data - print( "loading..." ) - a=np.loadtxt(filename) + print("loading...") + a = np.loadtxt(filename) file_no_prefix = os.path.splitext(os.path.basename(filename))[0] print('Filename: ', file_no_prefix) print('Data shape: ', a.shape) @@ -63,5 +71,3 @@ if __name__ == '__main__': print('Maximum value of data: ', a.flatten().max()) PlotNumpyArrayWithROOT(a, zmin, zmax) - - diff --git a/Tests/Functional/Python/PyCore/histogram2d.py b/Tests/Functional/Python/PyCore/histogram2d.py index 6249360b0ae94037d455d908a10d1e6865a0facc..b1756c525e970b86b9c508a2033dcd591e507060 100644 --- a/Tests/Functional/Python/PyCore/histogram2d.py +++ b/Tests/Functional/Python/PyCore/histogram2d.py @@ -3,16 +3,15 @@ import numpy, os, sys, unittest sys.path.append("@CMAKE_LIBRARY_OUTPUT_DIRECTORY@") import bornagain as ba -class Histogram2DTest(unittest.TestCase): +class Histogram2DTest(unittest.TestCase): def test_constructFromNumpyInt(self): """ Testing construction of 2D histogram from numpy array. Automatic conversion under Python3 is not working, that's why it is float64 and not int64 """ - arr = numpy.array([[ 1, 2, 3, 4, 5], - [ 6, 7, 8, 9, 10], - [11, 12, 13, 14, 15]], numpy.float64) + arr = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], + numpy.float64) hist = ba.Histogram2D(arr) self.assertEqual(hist.getNbinsX(), 5) @@ -36,9 +35,9 @@ class Histogram2DTest(unittest.TestCase): """ Testing construction of 2D histogram from numpy array """ - arr = numpy.array([[ 1.0, 2.0, 3.0, 4.0, 5.0], - [ 6.0, 7.0, 8.0, 9.0, 10.0], - [11.0, 12.0, 13.0, 14.0, 15.0]], dtype=numpy.float64) + arr = numpy.array([[1.0, 2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0, 10.0], + [11.0, 12.0, 13.0, 14.0, 15.0]], + dtype=numpy.float64) hist = ba.Histogram2D(arr) self.assertEqual(hist.getNbinsX(), 5) @@ -62,9 +61,8 @@ class Histogram2DTest(unittest.TestCase): """ Adding to the histogram content from numpy array """ - arr = numpy.array([[ 1, 2, 3, 4, 5], - [ 6, 7, 8, 9, 10], - [11, 12, 13, 14, 15]], dtype=numpy.float64) + arr = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], + dtype=numpy.float64) print(type(arr)) hist = ba.Histogram2D(arr) # adding same content once again @@ -72,22 +70,22 @@ class Histogram2DTest(unittest.TestCase): arr_from_hist = hist.getArray() for (x, y), element in numpy.ndenumerate(arr): - self.assertEqual(element*2.0, arr_from_hist[x][y]) + self.assertEqual(element * 2.0, arr_from_hist[x][y]) def test_constructAndAddFromNumpyDouble(self): """ Adding to the histogram content from numpy array """ - arr = numpy.array([[ 1.0, 2.0, 3.0, 4.0, 5.0], - [ 6.0, 7.0, 8.0, 9.0, 10.0], - [11.0, 12.0, 13.0, 14.0, 15.0]], dtype=numpy.float64) + arr = numpy.array([[1.0, 2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0, 10.0], + [11.0, 12.0, 13.0, 14.0, 15.0]], + dtype=numpy.float64) hist = ba.Histogram2D(arr) # adding same content once again hist.addContent(arr) arr_from_hist = hist.getArray() for (x, y), element in numpy.ndenumerate(arr): - self.assertEqual(element*2.0, arr_from_hist[x][y]) + self.assertEqual(element * 2.0, arr_from_hist[x][y]) def create_histogram(self, arr): """ @@ -99,9 +97,8 @@ class Histogram2DTest(unittest.TestCase): """ Testing newly create object """ - arr = numpy.array([[ 1, 2, 3, 4, 5], - [ 6, 7, 8, 9, 10], - [11, 12, 13, 14, 15]], dtype=numpy.float64) + arr = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], + dtype=numpy.float64) hist = self.create_histogram(arr) arr_from_hist = hist.getArray() @@ -112,9 +109,9 @@ class Histogram2DTest(unittest.TestCase): """ Testing newly create object """ - arr = numpy.array([[ 1.0, 2.0, 3.0, 4.0, 5.0], - [ 6.0, 7.0, 8.0, 9.0, 10.0], - [11.0, 12.0, 13.0, 14.0, 15.0]], dtype=numpy.float64) + arr = numpy.array([[1.0, 2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0, 10.0], + [11.0, 12.0, 13.0, 14.0, 15.0]], + dtype=numpy.float64) hist = self.create_histogram(arr) arr_from_hist = hist.getArray() diff --git a/Tests/Functional/Python/PyCore/intensitydata.py b/Tests/Functional/Python/PyCore/intensitydata.py index 9aef58b5ea8aae44c908a0e977fe4630c7a634d9..2b52c4e84830a758aec53537335e20210bf0ae94 100644 --- a/Tests/Functional/Python/PyCore/intensitydata.py +++ b/Tests/Functional/Python/PyCore/intensitydata.py @@ -51,7 +51,7 @@ class IntensityDataTest(unittest.TestCase): data.setAllTo(1.0) self.assertEqual(200.0, data.totalSum()) for i in range(0, data.getAllocatedSize()): - data[i] = data[i]*-1.0 + data[i] = data[i] * -1.0 self.assertEqual(-200.0, data.totalSum()) def test_access_simulation_intensity(self): diff --git a/Tests/Functional/Python/PyCore/intensitydata_io.py b/Tests/Functional/Python/PyCore/intensitydata_io.py index f764771c8484075f7d83d0eebb197507748dff93..13e804c6d66c4d154387d546298ab66272c9949d 100644 --- a/Tests/Functional/Python/PyCore/intensitydata_io.py +++ b/Tests/Functional/Python/PyCore/intensitydata_io.py @@ -6,6 +6,7 @@ sys.path.append("@CMAKE_LIBRARY_OUTPUT_DIRECTORY@") import bornagain as ba from bornagain import degree, deg2rad, rad2deg + def fill_data(data): """ Fills intensity data with some numbers @@ -13,6 +14,7 @@ def fill_data(data): for i in range(0, data.getAllocatedSize()): data[i] = i + def is_the_same_data(data1, data2): """ Checks if two data are identical @@ -29,16 +31,17 @@ def is_the_same_data(data1, data2): return False return True + def get_boundaries_flat_in_sin(nbins, start, end): """ Returns flat_in_sin binning of angle axis """ result = [] - start_sin = math.sin( deg2rad(start)) - end_sin = math.sin( deg2rad(end)) - step = (end_sin - start_sin)/nbins - for i in range(0, nbins+1): - result.append( rad2deg(math.asin(start_sin + step*i))) + start_sin = math.sin(deg2rad(start)) + end_sin = math.sin(deg2rad(end)) + step = (end_sin - start_sin) / nbins + for i in range(0, nbins + 1): + result.append(rad2deg(math.asin(start_sin + step * i))) return result @@ -75,7 +78,9 @@ class OutputDataIOTest(unittest.TestCase): def test_04_VariableBinAxis_1D(self): data = ba.IntensityData() - data.addAxis(ba.VariableBinAxis("axis0", 10, get_boundaries_flat_in_sin(10, -5.0, 5.0))) + data.addAxis( + ba.VariableBinAxis("axis0", 10, + get_boundaries_flat_in_sin(10, -5.0, 5.0))) fill_data(data) ba.IntensityDataIOFactory.writeOutputData(data, "tmp.int") newdata = ba.IntensityDataIOFactory.readOutputData("tmp.int") @@ -83,8 +88,11 @@ class OutputDataIOTest(unittest.TestCase): def test_05_VariableBinAxis_2D(self): data = ba.IntensityData() - data.addAxis(ba.VariableBinAxis("axis0", 10, get_boundaries_flat_in_sin(10, -5.0, 5.0))) - data.addAxis(ba.VariableBinAxis("axis1", 3, get_boundaries_flat_in_sin(3, 0.0, 2.0))) + data.addAxis( + ba.VariableBinAxis("axis0", 10, + get_boundaries_flat_in_sin(10, -5.0, 5.0))) + data.addAxis( + ba.VariableBinAxis("axis1", 3, get_boundaries_flat_in_sin(3, 0.0, 2.0))) fill_data(data) ba.IntensityDataIOFactory.writeOutputData(data, "tmp.int") newdata = ba.IntensityDataIOFactory.readOutputData("tmp.int") @@ -93,7 +101,8 @@ class OutputDataIOTest(unittest.TestCase): def test_06_VariableAndFixedMix(self): data = ba.IntensityData() data.addAxis(ba.FixedBinAxis("axis0", 10, -5.0, 5.0)) - data.addAxis(ba.VariableBinAxis("axis1", 3, get_boundaries_flat_in_sin(3, 0.0, 2.0))) + data.addAxis( + ba.VariableBinAxis("axis1", 3, get_boundaries_flat_in_sin(3, 0.0, 2.0))) fill_data(data) ba.IntensityDataIOFactory.writeOutputData(data, "tmp.int") newdata = ba.IntensityDataIOFactory.readOutputData("tmp.int") @@ -101,8 +110,9 @@ class OutputDataIOTest(unittest.TestCase): def test_07_ConstKBinAxis_2D(self): data = ba.IntensityData() - data.addAxis(ba.ConstKBinAxis("axis0", 9, -1.00000001*degree, 1.0*degree)) - data.addAxis(ba.ConstKBinAxis("axis1", 3, -4.0*degree, 5.0*degree)) + data.addAxis(ba.ConstKBinAxis("axis0", 9, -1.00000001 * degree, + 1.0 * degree)) + data.addAxis(ba.ConstKBinAxis("axis1", 3, -4.0 * degree, 5.0 * degree)) fill_data(data) ba.IntensityDataIOFactory.writeOutputData(data, "tmp.int") newdata = ba.IntensityDataIOFactory.readOutputData("tmp.int") @@ -110,8 +120,9 @@ class OutputDataIOTest(unittest.TestCase): def test_08_CustomBinAxis_2D(self): data = ba.IntensityData() - data.addAxis(ba.CustomBinAxis("axis0", 9, -1.00000001*degree, 1.0*degree)) - data.addAxis(ba.CustomBinAxis("axis1", 3, -4.0*degree, 5.0*degree)) + data.addAxis(ba.CustomBinAxis("axis0", 9, -1.00000001 * degree, + 1.0 * degree)) + data.addAxis(ba.CustomBinAxis("axis1", 3, -4.0 * degree, 5.0 * degree)) fill_data(data) ba.IntensityDataIOFactory.writeOutputData(data, "tmp.int") newdata = ba.IntensityDataIOFactory.readOutputData("tmp.int") @@ -146,25 +157,20 @@ class OutputDataIOTest(unittest.TestCase): self.assertTrue(is_the_same_data(data, newdata)) def test_SaveNumpyArray_ReadOutputData(self): - arr = numpy.array([ - [0.0, 1.0, 2.0, 3.0], - [4.0, 5.0, 6.0, 7.0], - [8.0, 9.0, 10.0, 11.0] - ]) + arr = numpy.array([[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], + [8.0, 9.0, 10.0, 11.0]]) numpy.savetxt('tmp.txt', arr) newdata = ba.IntensityDataIOFactory.readOutputData("tmp.txt") - self.assertTrue(numpy.array_equal(newdata.getArray(),arr)) + self.assertTrue(numpy.array_equal(newdata.getArray(), arr)) def test_SaveNumpyArray_ReadRawDataVector(self): - arr = numpy.array([ - [0.0, 1.0, 2.0, 3.0], - [4.0, 5.0, 6.0, 7.0], - [8.0, 9.0, 10.0, 11.0] - ]) + arr = numpy.array([[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], + [8.0, 9.0, 10.0, 11.0]]) numpy.savetxt('tmp.txt', arr) - newdata = numpy.array(ba.IntensityDataIOFactory.readOutputData("tmp.txt").getRawDataVector()) - expected = numpy.array([8.,4.,0.,9.,5.,1.,10.,6.,2.,11.,7.,3.]) - self.assertTrue(numpy.array_equal(newdata,expected)) + newdata = numpy.array( + ba.IntensityDataIOFactory.readOutputData("tmp.txt").getRawDataVector()) + expected = numpy.array([8., 4., 0., 9., 5., 1., 10., 6., 2., 11., 7., 3.]) + self.assertTrue(numpy.array_equal(newdata, expected)) def test_SaveOutputData_ReadNumpyArray(self): data = ba.IntensityData() @@ -175,7 +181,7 @@ class OutputDataIOTest(unittest.TestCase): ba.IntensityDataIOFactory.writeOutputData(data, "tmp.txt") arr = numpy.loadtxt("tmp.txt") - self.assertTrue(numpy.array_equal(data.getArray(),arr)) + self.assertTrue(numpy.array_equal(data.getArray(), arr)) if __name__ == '__main__': diff --git a/Tests/Functional/Python/PyCore/mesocrystal1.py b/Tests/Functional/Python/PyCore/mesocrystal1.py index 484bee4064e93f63782db68c8419e808dd27e894..a2ee892f8a56680656fe37628926f6b925267def 100644 --- a/Tests/Functional/Python/PyCore/mesocrystal1.py +++ b/Tests/Functional/Python/PyCore/mesocrystal1.py @@ -7,6 +7,7 @@ import ctypes, math, numpy, os, sys, time import utils from bornagain import * + # ---------------------------------------------------------------------------- # Sample builder to build mixture of cylinders and prisms on top of substrate # ---------------------------------------------------------------------------- @@ -15,41 +16,60 @@ class MySampleBuilder(ISampleBuilder): ISampleBuilder.__init__(self) self.sample = None # parameters describing the sample - self.lattice_length_a = ctypes.c_double(6.2091e+00*nm) - self.lattice_length_c = ctypes.c_double(6.5677e+00*nm) - self.nanoparticle_radius = ctypes.c_double(4.6976e+00*nm) - self.sigma_nanoparticle_radius = ctypes.c_double(3.6720e-01*nm) - self.meso_height = ctypes.c_double(1.1221e+02*nm) - self.meso_radius = ctypes.c_double(9.4567e+02*nm) - self.sigma_lattice_length_a = ctypes.c_double(1.1601e+00*nm) + self.lattice_length_a = ctypes.c_double(6.2091e+00 * nm) + self.lattice_length_c = ctypes.c_double(6.5677e+00 * nm) + self.nanoparticle_radius = ctypes.c_double(4.6976e+00 * nm) + self.sigma_nanoparticle_radius = ctypes.c_double(3.6720e-01 * nm) + self.meso_height = ctypes.c_double(1.1221e+02 * nm) + self.meso_radius = ctypes.c_double(9.4567e+02 * nm) + self.sigma_lattice_length_a = ctypes.c_double(1.1601e+00 * nm) self.surface_filling_ratio = ctypes.c_double(1.7286e-01) - self.roughness = ctypes.c_double(2.8746e+01*nm) + self.roughness = ctypes.c_double(2.8746e+01 * nm) # register parameters - self.registerParameter("lattice_length_a", ctypes.addressof(self.lattice_length_a)).setUnit("nm").setNonnegative() - self.registerParameter("lattice_length_c", ctypes.addressof(self.lattice_length_c)).setUnit("nm").setNonnegative() - self.registerParameter("nanoparticle_radius", ctypes.addressof(self.nanoparticle_radius)).setUnit("nm").setNonnegative() - self.registerParameter("sigma_nanoparticle_radius", ctypes.addressof(self.sigma_nanoparticle_radius)).setUnit("nm").setNonnegative() - self.registerParameter("meso_height", ctypes.addressof(self.meso_height)).setUnit("nm").setNonnegative() - self.registerParameter("meso_radius", ctypes.addressof(self.meso_radius)).setUnit("nm").setNonnegative() - self.registerParameter("sigma_lattice_length_a", ctypes.addressof(self.sigma_lattice_length_a)).setUnit("nm").setNonnegative() - self.registerParameter("surface_filling_ratio", ctypes.addressof(self.surface_filling_ratio) ).setNonnegative() - self.registerParameter("roughness", ctypes.addressof(self.roughness)).setUnit("nm").setNonnegative() + self.registerParameter( + "lattice_length_a", + ctypes.addressof(self.lattice_length_a)).setUnit("nm").setNonnegative() + self.registerParameter( + "lattice_length_c", + ctypes.addressof(self.lattice_length_c)).setUnit("nm").setNonnegative() + self.registerParameter( + "nanoparticle_radius", ctypes.addressof( + self.nanoparticle_radius)).setUnit("nm").setNonnegative() + self.registerParameter( + "sigma_nanoparticle_radius", + ctypes.addressof( + self.sigma_nanoparticle_radius)).setUnit("nm").setNonnegative() + self.registerParameter("meso_height", ctypes.addressof( + self.meso_height)).setUnit("nm").setNonnegative() + self.registerParameter("meso_radius", ctypes.addressof( + self.meso_radius)).setUnit("nm").setNonnegative() + self.registerParameter( + "sigma_lattice_length_a", ctypes.addressof( + self.sigma_lattice_length_a)).setUnit("nm").setNonnegative() + self.registerParameter("surface_filling_ratio", + ctypes.addressof( + self.surface_filling_ratio)).setNonnegative() + self.registerParameter("roughness", ctypes.addressof( + self.roughness)).setUnit("nm").setNonnegative() # ------------------------------------------------------------------------- # constructs the sample for current values of parameters # ------------------------------------------------------------------------- def buildSample(self): - surface_density = self.surface_filling_ratio.value/numpy.pi/self.meso_radius.value/self.meso_radius.value - n_particle = complex(1.0-2.84e-5, 4.7e-7) - avg_n_squared_meso = complex(0.7886*n_particle*n_particle + 0.2114) - n_avg = complex(numpy.sqrt(self.surface_filling_ratio.value*avg_n_squared_meso + 1.0 - self.surface_filling_ratio.value)) - n_particle_adapted = complex(numpy.sqrt(n_avg*n_avg + n_particle*n_particle - 1.0)) + surface_density = self.surface_filling_ratio.value / numpy.pi / self.meso_radius.value / self.meso_radius.value + n_particle = complex(1.0 - 2.84e-5, 4.7e-7) + avg_n_squared_meso = complex(0.7886 * n_particle * n_particle + 0.2114) + n_avg = complex( + numpy.sqrt(self.surface_filling_ratio.value * avg_n_squared_meso + 1.0 - + self.surface_filling_ratio.value)) + n_particle_adapted = complex( + numpy.sqrt(n_avg * n_avg + n_particle * n_particle - 1.0)) ff = FormFactorCylinder(self.meso_radius.value, self.meso_height.value) # Create multilayer p_multi_layer = MultiLayer() n_air = complex(1.0, 0.0) - n_substrate = complex(1.0-7.57e-6, 1.73e-7) + n_substrate = complex(1.0 - 7.57e-6, 1.73e-7) p_vacuum_material = HomogeneousMaterial("Vacuum", n_air) p_average_layer_material = HomogeneousMaterial("Averagelayer", n_avg) @@ -62,25 +82,28 @@ class MySampleBuilder(ISampleBuilder): n_max_phi_rotation_steps = 2 n_alpha_rotation_steps = 1 - alpha_step = 5.0*deg/n_alpha_rotation_steps - alpha_start = - (n_alpha_rotation_steps/2.0)*alpha_step + alpha_step = 5.0 * deg / n_alpha_rotation_steps + alpha_start = -(n_alpha_rotation_steps / 2.0) * alpha_step - phi_step = 2*numpy.pi/3.0/n_max_phi_rotation_steps + phi_step = 2 * numpy.pi / 3.0 / n_max_phi_rotation_steps phi_start = 0.0 for i in range(0, n_max_phi_rotation_steps): for j in range(0, n_alpha_rotation_steps): - total_transform = RotationZ(phi_start + i*phi_step) - meso = self.createMesoCrystal(self.lattice_length_a.value, self.lattice_length_c.value, n_particle_adapted, ff) + total_transform = RotationZ(phi_start + i * phi_step) + meso = self.createMesoCrystal(self.lattice_length_a.value, + self.lattice_length_c.value, + n_particle_adapted, ff) meso.setPosition(0.0, 0.0, -self.meso_height.value) - particle_layout.addParticle(meso, 1.0, kvector_t(0,0,0), total_transform) + particle_layout.addParticle(meso, 1.0, kvector_t(0, 0, 0), + total_transform) particle_layout.setTotalParticleSurfaceDensity(surface_density) particle_layout.setInterferenceFunction(p_interference_function) avg_layer.addLayout(particle_layout) - roughness = LayerRoughness(self.roughness.value, 0.3, 500.0*nm) + roughness = LayerRoughness(self.roughness.value, 0.3, 500.0 * nm) p_multi_layer.addLayer(vacuum_layer) p_multi_layer.addLayer(avg_layer) @@ -91,24 +114,26 @@ class MySampleBuilder(ISampleBuilder): # ------------------------------------------------------------------------- # building meso crystal # ------------------------------------------------------------------------- - def createMesoCrystal(self,stacking_radius_a, stacking_radius_c, n_particle, p_meso_form_factor): + def createMesoCrystal(self, stacking_radius_a, stacking_radius_c, n_particle, + p_meso_form_factor): - mParticle = HomogeneousMaterial("Particle", n_particle ) + mParticle = HomogeneousMaterial("Particle", n_particle) p_lat = self.createLattice(stacking_radius_a, stacking_radius_c) bas_a = p_lat.getBasisVectorA() bas_b = p_lat.getBasisVectorB() bas_c = p_lat.getBasisVectorC() - ff = FormFactorSphereGaussianRadius(self.nanoparticle_radius.value, self.sigma_nanoparticle_radius.value) - particle = Particle(mParticle, ff ) + ff = FormFactorSphereGaussianRadius(self.nanoparticle_radius.value, + self.sigma_nanoparticle_radius.value) + particle = Particle(mParticle, ff) position_0 = kvector_t(0.0, 0.0, 0.0) - position_1 = 1.0/3.0*(2.0*bas_a + bas_b + bas_c) - position_2 = 1.0/3.0*(bas_a + 2.0*bas_b + 2.0*bas_c) - positions = [ position_0, position_1, position_2 ] + position_1 = 1.0 / 3.0 * (2.0 * bas_a + bas_b + bas_c) + position_2 = 1.0 / 3.0 * (bas_a + 2.0 * bas_b + 2.0 * bas_c) + positions = [position_0, position_1, position_2] basis = ParticleComposition() basis.addParticles(particle, positions) - position_variance = self.sigma_lattice_length_a.value*self.sigma_lattice_length_a.value/3.0 + position_variance = self.sigma_lattice_length_a.value * self.sigma_lattice_length_a.value / 3.0 npc = Crystal(basis, p_lat, position_variance) meso = MesoCrystal(npc, p_meso_form_factor) return meso @@ -117,7 +142,8 @@ class MySampleBuilder(ISampleBuilder): # create lattice # ------------------------------------------------------------------------- def createLattice(self, stacking_radius_a, stacking_radius_c): - result = HexagonalLattice(stacking_radius_a*2.0, stacking_radius_c*2.0*2.3) + result = HexagonalLattice(stacking_radius_a * 2.0, + stacking_radius_c * 2.0 * 2.3) result.setSelectionRule(SimpleSelectionRule(-1, 1, 1, 3)) return result @@ -129,7 +155,7 @@ def runTest(): # setting simulation sample_builder = MySampleBuilder() simulation = createSimulation() - simulation.setSampleBuilder( sample_builder ) + simulation.setSampleBuilder(sample_builder) reference = utils.get_reference_data("mesocrystal01_reference.int.gz") @@ -147,9 +173,10 @@ def runTest(): # create simulation def createSimulation(): simulation = GISASSimulation() - simulation.setBeamParameters(1.77*angstrom, 0.4*deg, 0.0*deg) + simulation.setBeamParameters(1.77 * angstrom, 0.4 * deg, 0.0 * deg) simulation.setBeamIntensity(5.0090e+12) - simulation.setDetectorParameters(50, 0.2*deg, 2.5*deg, 50, 0.0*deg, 2.5*deg) + simulation.setDetectorParameters(50, 0.2 * deg, 2.5 * deg, 50, 0.0 * deg, + 2.5 * deg) return simulation diff --git a/Tests/Functional/Python/PyCore/parameterpool.py b/Tests/Functional/Python/PyCore/parameterpool.py index 6f03869afe9d9983f15b39befe87b9396a85905f..3afeae72925d82db8d1c3693417a3009e619bb20 100644 --- a/Tests/Functional/Python/PyCore/parameterpool.py +++ b/Tests/Functional/Python/PyCore/parameterpool.py @@ -6,12 +6,11 @@ from bornagain import nm class ParameterPoolTest(unittest.TestCase): - def test_parameterPoolAccess(self): """ Checks values in particle's parameter pool """ - ff = ba.FormFactorCylinder(5*nm, 6*nm) + ff = ba.FormFactorCylinder(5 * nm, 6 * nm) particle = ba.Particle(ba.HomogeneousMaterial("Vacuum", 0.0, 0.0), ff) particle.setAbundance(1.0) particle.setPosition(2.0, 3.0, 4.0) @@ -21,9 +20,15 @@ class ParameterPoolTest(unittest.TestCase): pool = particle.parameterPool() self.assertEqual(pool.size(), 4) - self.assertEqual(pool.parameterNames(), ('Abundance', 'PositionX', 'PositionY', 'PositionZ')) - - expected = {'Abundance': 1.0, 'PositionX': 2.0, 'PositionY': 3.0, 'PositionZ': 4.0} + self.assertEqual(pool.parameterNames(), + ('Abundance', 'PositionX', 'PositionY', 'PositionZ')) + + expected = { + 'Abundance': 1.0, + 'PositionX': 2.0, + 'PositionY': 3.0, + 'PositionZ': 4.0 + } for par in pool: print(par.value(), par.getName(), par.limits().toString()) self.assertEqual(par.value(), expected[par.getName()]) @@ -32,7 +37,7 @@ class ParameterPoolTest(unittest.TestCase): """ Modification of particle parameters via parameter pool """ - ff = ba.FormFactorCylinder(5*nm, 6*nm) + ff = ba.FormFactorCylinder(5 * nm, 6 * nm) particle = ba.Particle(ba.HomogeneousMaterial("Vacuum", 0.0, 0.0), ff) particle.setAbundance(1.0) particle.setPosition(2.0, 3.0, 4.0) @@ -42,7 +47,12 @@ class ParameterPoolTest(unittest.TestCase): pool[1].setValue(20.0) # PositionX pool.parameter('PositionY').setValue(30.0) - expected = {'Abundance': 10.0, 'PositionX': 20.0, 'PositionY': 30.0, 'PositionZ': 4.0} + expected = { + 'Abundance': 10.0, + 'PositionX': 20.0, + 'PositionY': 30.0, + 'PositionZ': 4.0 + } for par in pool: self.assertEqual(par.value(), expected[par.getName()]) @@ -52,16 +62,21 @@ class ParameterPoolTest(unittest.TestCase): Checks values in particle's parameter tree. Parameter tree is a pool with parameters of particle and its children (in given case, form factor of cylinder) """ - ff = ba.FormFactorCylinder(5*nm, 6*nm) + ff = ba.FormFactorCylinder(5 * nm, 6 * nm) particle = ba.Particle(ba.HomogeneousMaterial("Vacuum", 0.0, 0.0), ff) particle.setAbundance(1.0) particle.setPosition(2.0, 3.0, 4.0) pool = particle.createParameterTree() - expected = {'/Particle/Abundance': 1.0, '/Particle/PositionX': 2.0, - '/Particle/PositionY': 3.0, '/Particle/PositionZ': 4.0, - '/Particle/Cylinder/Radius': 5.0, '/Particle/Cylinder/Height': 6.0} + expected = { + '/Particle/Abundance': 1.0, + '/Particle/PositionX': 2.0, + '/Particle/PositionY': 3.0, + '/Particle/PositionZ': 4.0, + '/Particle/Cylinder/Radius': 5.0, + '/Particle/Cylinder/Height': 6.0 + } for par in pool: self.assertEqual(par.value(), expected[par.getName()]) @@ -70,7 +85,7 @@ class ParameterPoolTest(unittest.TestCase): """ Modifies values of particle's parameter tree. """ - ff = ba.FormFactorCylinder(5*nm, 6*nm) + ff = ba.FormFactorCylinder(5 * nm, 6 * nm) particle = ba.Particle(ba.HomogeneousMaterial("Vacuum", 0.0, 0.0), ff) particle.setAbundance(1.0) particle.setPosition(2.0, 3.0, 4.0) @@ -84,9 +99,14 @@ class ParameterPoolTest(unittest.TestCase): pool.parameter('/Particle/PositionY').setValue(30.0) pool.setMatchedParametersValue('*Cylinder*', 50.0) - expected = {'/Particle/Abundance': 10.0, '/Particle/PositionX': 20.0, - '/Particle/PositionY': 30.0, '/Particle/PositionZ': 4.0, - '/Particle/Cylinder/Radius': 50.0, '/Particle/Cylinder/Height': 50.0} + expected = { + '/Particle/Abundance': 10.0, + '/Particle/PositionX': 20.0, + '/Particle/PositionY': 30.0, + '/Particle/PositionZ': 4.0, + '/Particle/Cylinder/Radius': 50.0, + '/Particle/Cylinder/Height': 50.0 + } for par in pool: self.assertEqual(par.value(), expected[par.getName()]) @@ -95,7 +115,7 @@ class ParameterPoolTest(unittest.TestCase): """ Modification of particle's parameters without intermediate access to parameter pool """ - ff = ba.FormFactorCylinder(5*nm, 6*nm) + ff = ba.FormFactorCylinder(5 * nm, 6 * nm) particle = ba.Particle(ba.HomogeneousMaterial("Vacuum", 0.0, 0.0), ff) particle.setAbundance(1.0) particle.setPosition(2.0, 3.0, 4.0) diff --git a/Tests/Functional/Python/PyCore/polmagcylinders1.py b/Tests/Functional/Python/PyCore/polmagcylinders1.py index e848cf6d29754314e4d5728d1f0723eefc564a66..2e315e3aebd1143dec0c4a6234927aa25d311c8c 100644 --- a/Tests/Functional/Python/PyCore/polmagcylinders1.py +++ b/Tests/Functional/Python/PyCore/polmagcylinders1.py @@ -16,9 +16,9 @@ def runSimulation(): magnetic_field = ba.kvector_t(0, 0, 0) - magParticle = ba.HomogeneousMaterial("magParticle", 6e-4, 2e-8, magnetic_field ) + magParticle = ba.HomogeneousMaterial("magParticle", 6e-4, 2e-8, magnetic_field) # collection of particles - cylinder_ff = ba.FormFactorCylinder(5*nanometer, 5*nanometer) + cylinder_ff = ba.FormFactorCylinder(5 * nanometer, 5 * nanometer) cylinder = ba.Particle(magParticle, cylinder_ff) particle_layout = ba.ParticleLayout() @@ -36,8 +36,9 @@ def runSimulation(): # build and run experiment simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0*degree, 2.0*degree, 100, 0.0*degree, 2.0*degree) - simulation.setBeamParameters(1.0*angstrom, 0.2*degree, 0.0*degree) + simulation.setDetectorParameters(100, 0 * degree, 2.0 * degree, 100, + 0.0 * degree, 2.0 * degree) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setSample(multi_layer) simulation.setBeamIntensity(1e2) simulation.runSimulation() @@ -65,5 +66,5 @@ def run_test(): if __name__ == '__main__': name, description, diff, status = run_test() print(name, description, diff, status) - if("FAILED" in status): + if ("FAILED" in status): exit(1) diff --git a/Tests/Functional/Python/PyCore/polmagcylinders2.py b/Tests/Functional/Python/PyCore/polmagcylinders2.py index 6864e65b63e4a0c93b760f322639e907c7bc6af9..097fa5b618c441510ed4e43bbe6f2a81124c8f8d 100644 --- a/Tests/Functional/Python/PyCore/polmagcylinders2.py +++ b/Tests/Functional/Python/PyCore/polmagcylinders2.py @@ -10,6 +10,7 @@ from bornagain import * REFERENCE_DIR = "@TEST_REFERENCE_DIR@/Python" + # ---------------------------------- # describe sample and run simulation # ---------------------------------- @@ -21,9 +22,9 @@ def getSimulationIntensity(rho_beam, efficiency): magnetization = kvector_t(0, 1e6, 0) - magParticle = HomogeneousMaterial("magParticle", 5e-6, 0.0, magnetization ) + magParticle = HomogeneousMaterial("magParticle", 5e-6, 0.0, magnetization) # collection of particles - cylinder_ff = FormFactorCylinder(5*nanometer, 5*nanometer) + cylinder_ff = FormFactorCylinder(5 * nanometer, 5 * nanometer) cylinder = Particle(magParticle, cylinder_ff) particle_layout = ParticleLayout() @@ -41,10 +42,11 @@ def getSimulationIntensity(rho_beam, efficiency): # build and run experiment simulation = GISASSimulation() - simulation.setDetectorParameters(100, -1*degree, 1.0*degree, 100, 0.0*degree, 2.0*degree) + simulation.setDetectorParameters(100, -1 * degree, 1.0 * degree, 100, + 0.0 * degree, 2.0 * degree) zplus = kvector_t(0.0, 0.0, 1.0) simulation.setAnalyzerProperties(zplus, efficiency, 0.5) - simulation.setBeamParameters(1.0*angstrom, 0.2*degree, 0.0*degree) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) simulation.setBeamPolarization(rho_beam) simulation.setSample(multi_layer) simulation.setBeamIntensity(1e9) @@ -58,12 +60,13 @@ def get_reference_data(filename): """ read and return reference data from file """ - path = os.path.join(REFERENCE_DIR,filename) + path = os.path.join(REFERENCE_DIR, filename) print("- read reference from", path, flush=True) ret = IntensityDataIOFactory.readIntensityData(path) print("- - reference read", flush=True) return ret + # -------------------------------------------------------------- # run test and analyse test results # -------------------------------------------------------------- @@ -77,14 +80,18 @@ def run_test(): # IntensityDataIOFactory.writeIntensityData(getSimulationIntensity(zmin, 1.0), 'polmagcylinders2_reference_10.int') # IntensityDataIOFactory.writeIntensityData(getSimulationIntensity(zmin, -1.0), 'polmagcylinders2_reference_11.int') diff = 0.0 - diff += get_difference(getSimulationIntensity(zplus, 1.0).array(), - get_reference_data('polmagcylinders2_reference_00.int.gz').getArray()) - diff += get_difference(getSimulationIntensity(zplus, -1.0).array(), - get_reference_data('polmagcylinders2_reference_01.int.gz').getArray()) - diff += get_difference(getSimulationIntensity(zmin, 1.0).array(), - get_reference_data('polmagcylinders2_reference_10.int.gz').getArray()) - diff += get_difference(getSimulationIntensity(zmin, -1.0).array(), - get_reference_data('polmagcylinders2_reference_11.int.gz').getArray()) + diff += get_difference( + getSimulationIntensity(zplus, 1.0).array(), + get_reference_data('polmagcylinders2_reference_00.int.gz').getArray()) + diff += get_difference( + getSimulationIntensity(zplus, -1.0).array(), + get_reference_data('polmagcylinders2_reference_01.int.gz').getArray()) + diff += get_difference( + getSimulationIntensity(zmin, 1.0).array(), + get_reference_data('polmagcylinders2_reference_10.int.gz').getArray()) + diff += get_difference( + getSimulationIntensity(zmin, -1.0).array(), + get_reference_data('polmagcylinders2_reference_11.int.gz').getArray()) diff /= 4.0 status = "OK" @@ -96,5 +103,5 @@ def run_test(): if __name__ == '__main__': name, description, diff, status = run_test() print(name, description, diff, status) - if("FAILED" in status): + if ("FAILED" in status): exit(1) diff --git a/Tests/Functional/Python/PyCore/samplebuilder.py b/Tests/Functional/Python/PyCore/samplebuilder.py index 83c9d8d8dc43058bb5af1ad2c05a49dcdc42d80f..0333dc8abe316ea747ad74b272579e4ef84930d8 100644 --- a/Tests/Functional/Python/PyCore/samplebuilder.py +++ b/Tests/Functional/Python/PyCore/samplebuilder.py @@ -4,7 +4,6 @@ import inspect sys.path.append("@CMAKE_LIBRARY_OUTPUT_DIRECTORY@") import bornagain as ba - initial_width = 42 initial_length = 42 @@ -48,16 +47,17 @@ class BuilderPrototype(ba.ISampleBuilder): def register_prototype(self, par_name, var_key): var_key = var_key.split("self.", 1).pop() if not var_key in self.__dict__: - raise Exception("Can't find variable self."+var_key+" in given class") + raise Exception("Can't find variable self." + var_key + + " in given class") # defining the name for new ctype variable and creating dynamic attribute - wrapper_key = "wrapper_"+var_key + wrapper_key = "wrapper_" + var_key setattr(self, wrapper_key, ctypes.c_double(self.__dict__.get(var_key))) # registering new attribute in BornAgain - self.registerParameter(par_name, ctypes.addressof(getattr(self, wrapper_key))) + self.registerParameter(par_name, ctypes.addressof(getattr(self, + wrapper_key))) class SampleBuilderTest(unittest.TestCase): - def test_registerParameters(self): """ Checking parameter registration and setting the value. diff --git a/Tests/Functional/Python/PyCore/shape2d.py b/Tests/Functional/Python/PyCore/shape2d.py index 3501f6bf849796ef26df8ddb667060da8027e576..e7afb21b2abf8fda799452f4e0735822d21ae9e6 100644 --- a/Tests/Functional/Python/PyCore/shape2d.py +++ b/Tests/Functional/Python/PyCore/shape2d.py @@ -3,8 +3,8 @@ import numpy, os, sys, unittest sys.path.append("@CMAKE_LIBRARY_OUTPUT_DIRECTORY@") import bornagain as ba -class Shape2DTest(unittest.TestCase): +class Shape2DTest(unittest.TestCase): def test_constructPolygonFromList(self): """ Testing construction of polygon from two Numpy arrays diff --git a/Tests/Functional/Python/PyCore/sliced_composition.py b/Tests/Functional/Python/PyCore/sliced_composition.py index a4e9b46bd8509b02709dfeb9057d0b475c70a00d..9664566c0c3a627f00acd707b9e0fb9612c1a139 100644 --- a/Tests/Functional/Python/PyCore/sliced_composition.py +++ b/Tests/Functional/Python/PyCore/sliced_composition.py @@ -18,7 +18,6 @@ bottom_cup_height = 4.0 class SlicedSpheresTest(unittest.TestCase): - def get_sample(self, particle_to_air=None, particle_to_substrate=None): """ Helper function returning a multilayer (air, substrate) using particles provided @@ -54,8 +53,14 @@ class SlicedSpheresTest(unittest.TestCase): Origin of new object is at the bottom of resulting sphere. """ - topCup = ba.Particle(top_material, ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius*2 - bottom_cup_height, 0)) - bottomCup = ba.Particle(bottom_material, ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius*2, sphere_radius*2 - bottom_cup_height)) + topCup = ba.Particle( + top_material, + ba.FormFactorTruncatedSphere(sphere_radius, + sphere_radius * 2 - bottom_cup_height, 0)) + bottomCup = ba.Particle( + bottom_material, + ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius * 2, + sphere_radius * 2 - bottom_cup_height)) # origin of resulting sphere will be at the bottom result = ba.ParticleComposition() @@ -71,9 +76,14 @@ class SlicedSpheresTest(unittest.TestCase): Rotation is used to get bottom part """ - topCup = ba.Particle(top_material, ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius*2 - bottom_cup_height, 0)) - bottomCup = ba.Particle(bottom_material, ba.FormFactorTruncatedSphere(sphere_radius, bottom_cup_height, 0)) - bottomCup.setRotation(ba.RotationX(180*deg)) + topCup = ba.Particle( + top_material, + ba.FormFactorTruncatedSphere(sphere_radius, + sphere_radius * 2 - bottom_cup_height, 0)) + bottomCup = ba.Particle( + bottom_material, + ba.FormFactorTruncatedSphere(sphere_radius, bottom_cup_height, 0)) + bottomCup.setRotation(ba.RotationX(180 * deg)) # origin of resulting sphere will be at the bottom result = ba.ParticleComposition() @@ -119,7 +129,6 @@ class SlicedSpheresTest(unittest.TestCase): print(diff) self.assertLess(diff, 1e-10) - def testInvisibleComposition(self): """ Compares two simulation intended to provide identical results. @@ -150,7 +159,7 @@ class SlicedSpheresTest(unittest.TestCase): Both particles are inserted in vacuum layer with shift to go below interface """ - shift = 3*nm + shift = 3 * nm # spherical particle sphere = ba.Particle(mParticle, ba.FormFactorFullSphere(sphere_radius)) @@ -176,7 +185,10 @@ class SlicedSpheresTest(unittest.TestCase): """ # truncated sphere on top of substrate with height 16nm - truncatedSphere = ba.Particle(mParticle, ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius*2 - bottom_cup_height, 0)) + truncatedSphere = ba.Particle( + mParticle, + ba.FormFactorTruncatedSphere(sphere_radius, + sphere_radius * 2 - bottom_cup_height, 0)) reference = self.get_result(truncatedSphere) # Particle composition, top part made of same material, as particle. Bottom part made of same material as substrate. diff --git a/Tests/Functional/Python/PyCore/sliced_spheres.py b/Tests/Functional/Python/PyCore/sliced_spheres.py index 1195f1df170735d0ded43919fc0ce1a8cbafbb3b..4e2b89aba3aa5167d9e1f37fa9286f555355e1d4 100644 --- a/Tests/Functional/Python/PyCore/sliced_spheres.py +++ b/Tests/Functional/Python/PyCore/sliced_spheres.py @@ -13,8 +13,8 @@ from bornagain import deg, kvector_t mSubstrate = ba.HomogeneousMaterial("Substrate", 3.212e-6, 3.244e-8) mAmbience = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0) -class SlicedSpheresTest(unittest.TestCase): +class SlicedSpheresTest(unittest.TestCase): def get_sample(self, particle_to_air=None, particle_to_substrate=None): """ Helper function returning a multilayer (air, substrate) using particles provided @@ -57,7 +57,10 @@ class SlicedSpheresTest(unittest.TestCase): sphere_shift = 4.0 # shift beneath interface in absolute units # truncated sphere on top of substrate with height 16nm - truncatedSphere = ba.Particle(mSubstrate, ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius*2 - sphere_shift, 0)) + truncatedSphere = ba.Particle( + mSubstrate, + ba.FormFactorTruncatedSphere(sphere_radius, + sphere_radius * 2 - sphere_shift, 0)) reference = self.get_result(truncatedSphere) # sphere crossing interface to look like truncated sphere above @@ -79,7 +82,10 @@ class SlicedSpheresTest(unittest.TestCase): sphere_shift = 4.0 # shift beneath interface in absolute units # Sphere truncated from top. Intended to go below interface. - truncatedSphere = ba.Particle(mAmbience, ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius*2, sphere_radius*2 - sphere_shift)) + truncatedSphere = ba.Particle( + mAmbience, + ba.FormFactorTruncatedSphere(sphere_radius, sphere_radius * 2, + sphere_radius * 2 - sphere_shift)) truncatedSphere.setPosition(0, 0, -sphere_shift) reference = self.get_result(truncatedSphere) diff --git a/Tests/Functional/Python/PyCore/transform_BoxComposition.py b/Tests/Functional/Python/PyCore/transform_BoxComposition.py index bc2f1c7e65e9b664812a42d6da331d99954c8230..1e92af9215b87576ae286971027d66448834cb8d 100644 --- a/Tests/Functional/Python/PyCore/transform_BoxComposition.py +++ b/Tests/Functional/Python/PyCore/transform_BoxComposition.py @@ -19,11 +19,11 @@ com_width = 20.0 com_height = 10.0 particle_material = HomogeneousMaterial("Ag", 1.245e-5, 5.419e-7) -class TransformBoxCompositionTest(unittest.TestCase): +class TransformBoxCompositionTest(unittest.TestCase): def get_sample(self, particle): mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0) - mMiddle= HomogeneousMaterial("Teflon", 2.900e-6, 6.019e-9) + mMiddle = HomogeneousMaterial("Teflon", 2.900e-6, 6.019e-9) mSubstrate = HomogeneousMaterial("Substrate", 3.212e-6, 3.244e-8) layout = ParticleLayout() @@ -56,18 +56,20 @@ class TransformBoxCompositionTest(unittest.TestCase): width = 20.0 height = 10.0 particle = Particle(particle_material, FormFactorBox(length, width, height)) - particle.setPosition(kvector_t(0, 0, -layer_thickness/2.0 - height/2.0)) + particle.setPosition(kvector_t(0, 0, -layer_thickness / 2.0 - height / 2.0)) reference_data = self.get_result(particle) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_BoxComposition.int") # composition - box = Particle(particle_material, FormFactorBox(com_length/2.0, com_width, com_height)) + box = Particle(particle_material, + FormFactorBox(com_length / 2.0, com_width, com_height)) composition = ParticleComposition() # composition = ParticleComposition(box, positions) composition.addParticle(box, kvector_t(0.0, 0.0, 0.0)) - composition.addParticle(box, kvector_t(com_length/2.0, 0.0, 0.0)) - composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - com_height/2.0)) + composition.addParticle(box, kvector_t(com_length / 2.0, 0.0, 0.0)) + composition.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - com_height / 2.0)) data = self.get_result(composition) @@ -85,18 +87,19 @@ class TransformBoxCompositionTest(unittest.TestCase): width = 10.0 height = 20.0 particle = Particle(particle_material, FormFactorBox(length, width, height)) - particle.setPosition(kvector_t(0, 0, -layer_thickness/2.0 - height/2.0)) + particle.setPosition(kvector_t(0, 0, -layer_thickness / 2.0 - height / 2.0)) reference_data = self.get_result(particle) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_BoxCompositionRotateX.int") # composition - box = Particle(particle_material, FormFactorBox(com_length/2.0, com_width, com_height)) + box = Particle(particle_material, + FormFactorBox(com_length / 2.0, com_width, com_height)) composition = ParticleComposition() composition.addParticle(box, kvector_t(0.0, 0.0, 0.0)) - composition.addParticle(box, kvector_t(com_length/2.0, 0.0, 0.0)) - composition.setRotation(RotationX(90*deg)) - composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.)) + composition.addParticle(box, kvector_t(com_length / 2.0, 0.0, 0.0)) + composition.setRotation(RotationX(90 * deg)) + composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness / 2.)) data = self.get_result(composition) @@ -114,18 +117,20 @@ class TransformBoxCompositionTest(unittest.TestCase): width = 20.0 height = 50.0 particle = Particle(particle_material, FormFactorBox(length, width, height)) - particle.setPosition(kvector_t(0, 0, -layer_thickness/2.0 - height/2.0)) + particle.setPosition(kvector_t(0, 0, -layer_thickness / 2.0 - height / 2.0)) reference_data = self.get_result(particle) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_BoxCompositionRotateY.int") # composition - box = Particle(particle_material, FormFactorBox(com_length/2.0, com_width, com_height)) + box = Particle(particle_material, + FormFactorBox(com_length / 2.0, com_width, com_height)) composition = ParticleComposition() composition.addParticle(box, kvector_t(0.0, 0.0, 0.0)) - composition.addParticle(box, kvector_t(com_length/2.0, 0.0, 0.0)) - composition.setRotation(RotationY(90*deg)) - composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2. + com_length/4.)) + composition.addParticle(box, kvector_t(com_length / 2.0, 0.0, 0.0)) + composition.setRotation(RotationY(90 * deg)) + composition.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2. + com_length / 4.)) data = self.get_result(composition) @@ -143,18 +148,21 @@ class TransformBoxCompositionTest(unittest.TestCase): width = 50.0 height = 10.0 particle = Particle(particle_material, FormFactorBox(length, width, height)) - particle.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - height/2.0)) + particle.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - height / 2.0)) reference_data = self.get_result(particle) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_BoxCompositionRotateZ.int") # composition - box = Particle(particle_material, FormFactorBox(com_length/2.0, com_width, com_height)) + box = Particle(particle_material, + FormFactorBox(com_length / 2.0, com_width, com_height)) composition = ParticleComposition() composition.addParticle(box, kvector_t(0.0, 0.0, 0.0)) - composition.addParticle(box, kvector_t(com_length/2.0, 0.0, 0.0)) - composition.setRotation(RotationZ(90*deg)) - composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - com_height/2.0)) + composition.addParticle(box, kvector_t(com_length / 2.0, 0.0, 0.0)) + composition.setRotation(RotationZ(90 * deg)) + composition.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - com_height / 2.0)) data = self.get_result(composition) @@ -172,19 +180,21 @@ class TransformBoxCompositionTest(unittest.TestCase): width = 50.0 height = 20.0 particle = Particle(particle_material, FormFactorBox(length, width, height)) - particle.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - height/2.0)) + particle.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - height / 2.0)) reference_data = self.get_result(particle) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_BoxCompositionRotateZandY.int") # composition - box = Particle(particle_material, FormFactorBox(com_length/2.0, com_width, com_height)) + box = Particle(particle_material, + FormFactorBox(com_length / 2.0, com_width, com_height)) composition = ParticleComposition() composition.addParticle(box, kvector_t(0.0, 0.0, 0.0)) - composition.addParticle(box, kvector_t(com_length/2.0, 0.0, 0.0)) - composition.setRotation(RotationZ(90*deg)) - composition.rotate(RotationY(90*deg)) - composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.)) + composition.addParticle(box, kvector_t(com_length / 2.0, 0.0, 0.0)) + composition.setRotation(RotationZ(90 * deg)) + composition.rotate(RotationY(90 * deg)) + composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness / 2.)) data = self.get_result(composition) @@ -202,7 +212,8 @@ class TransformBoxCompositionTest(unittest.TestCase): width = 20.0 height = 50.0 particle = Particle(particle_material, FormFactorBox(length, width, height)) - particle.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - height/2.0)) + particle.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - height / 2.0)) reference_data = self.get_result(particle) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_BoxStackComposition.int") @@ -213,21 +224,23 @@ class TransformBoxCompositionTest(unittest.TestCase): box1_length = 20.0 box1_width = 50.0 box1_height = 5.0 - box1 = Particle(particle_material, FormFactorBox(box1_length, box1_width, box1_height)) - box1.setRotation(RotationZ(90*deg)) + box1 = Particle(particle_material, + FormFactorBox(box1_length, box1_width, box1_height)) + box1.setRotation(RotationZ(90 * deg)) # box2 (5,20,50), rotatedY box2_length = 5.0 box2_width = 20.0 box2_height = 50.0 - box2 = Particle(particle_material, FormFactorBox(box2_length, box2_width, box2_height)) - box2.setRotation(RotationY(90*deg)) - box2.setPosition(kvector_t(-box2_height/2.0, 0.0, box2_length/2.0)) + box2 = Particle(particle_material, + FormFactorBox(box2_length, box2_width, box2_height)) + box2.setRotation(RotationY(90 * deg)) + box2.setPosition(kvector_t(-box2_height / 2.0, 0.0, box2_length / 2.0)) composition.addParticle(box1, kvector_t(0.0, 0.0, 0.0)) composition.addParticle(box2, kvector_t(0.0, 0.0, box1_height)) - composition.setRotation(RotationY(90*deg)) - composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.)) + composition.setRotation(RotationY(90 * deg)) + composition.setPosition(kvector_t(0.0, 0.0, -layer_thickness / 2.)) data = self.get_result(composition) diff --git a/Tests/Functional/Python/PyCore/transform_CoreShellBox.py b/Tests/Functional/Python/PyCore/transform_CoreShellBox.py index 008bd3aba92da3e11bc5d33c20188e1438150ca0..e505f2d065e790d0f7e708f66d9a16f13d1b0369 100644 --- a/Tests/Functional/Python/PyCore/transform_CoreShellBox.py +++ b/Tests/Functional/Python/PyCore/transform_CoreShellBox.py @@ -14,11 +14,11 @@ from bornagain import * layer_thickness = 100.0 -class TransformCoreShellBoxTest(unittest.TestCase): +class TransformCoreShellBoxTest(unittest.TestCase): def get_sample(self, particle): mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0) - mMiddle= HomogeneousMaterial("Teflon", 2.900e-6, 6.019e-9) + mMiddle = HomogeneousMaterial("Teflon", 2.900e-6, 6.019e-9) mSubstrate = HomogeneousMaterial("Substrate", 3.212e-6, 3.244e-8) layout = ParticleLayout() @@ -51,18 +51,23 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 50.0 shell_width = 20.0 shell_height = 10.0 - particle = Particle(mCore, FormFactorBox(shell_length, shell_width, shell_height)) - particle.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - shell_height/2.0)) + particle = Particle(mCore, + FormFactorBox(shell_length, shell_width, shell_height)) + particle.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - shell_height / 2.0)) reference_data = self.get_result(particle) - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 - shell = Particle(mCore, FormFactorBox(shell_length, shell_width, shell_height)) + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 + shell = Particle(mCore, FormFactorBox(shell_length, shell_width, + shell_height)) core = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - coreshell = ParticleCoreShell(shell, core, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - shell_height/2.0)) + coreshell = ParticleCoreShell( + shell, core, kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell.setPosition( + kvector_t(0.0, 0.0, -layer_thickness / 2.0 - shell_height / 2.0)) data = self.get_result(coreshell) @@ -83,14 +88,21 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 20.0 shell_width = 50.0 shell_height = 10.0 - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 - - core_ref = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - shell_ref = Particle(mShell, FormFactorBox(shell_length, shell_width, shell_height)) - coreshell_ref = ParticleCoreShell(shell_ref, core_ref, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell_ref.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - shell_height/2.0)) # center of coreshell in center of the layer + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 + + core_ref = Particle(mCore, FormFactorBox(core_length, core_width, + core_height)) + shell_ref = Particle(mShell, + FormFactorBox(shell_length, shell_width, shell_height)) + coreshell_ref = ParticleCoreShell( + shell_ref, core_ref, + kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell_ref.setPosition( + kvector_t( + 0.0, 0.0, -layer_thickness / 2.0 - + shell_height / 2.0)) # center of coreshell in center of the layer reference_data = self.get_result(coreshell_ref) @@ -98,15 +110,20 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 50.0 shell_width = 20.0 shell_height = 10.0 - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 core = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - shell = Particle(mShell, FormFactorBox(shell_length, shell_width, shell_height)) - coreshell = ParticleCoreShell(shell, core, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell.setRotation(RotationZ(90.0*degree)) - coreshell.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - shell_height/2.0)) # center of coreshell in center of the layer + shell = Particle(mShell, + FormFactorBox(shell_length, shell_width, shell_height)) + coreshell = ParticleCoreShell( + shell, core, kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell.setRotation(RotationZ(90.0 * degree)) + coreshell.setPosition( + kvector_t( + 0.0, 0.0, -layer_thickness / 2.0 - + shell_height / 2.0)) # center of coreshell in center of the layer data = self.get_result(coreshell) @@ -127,14 +144,21 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 10.0 shell_width = 20.0 shell_height = 50.0 - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 - - core_ref = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - shell_ref = Particle(mShell, FormFactorBox(shell_length, shell_width, shell_height)) - coreshell_ref = ParticleCoreShell(shell_ref, core_ref, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell_ref.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - shell_height/2.0)) # center of coreshell in center of the layer + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 + + core_ref = Particle(mCore, FormFactorBox(core_length, core_width, + core_height)) + shell_ref = Particle(mShell, + FormFactorBox(shell_length, shell_width, shell_height)) + coreshell_ref = ParticleCoreShell( + shell_ref, core_ref, + kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell_ref.setPosition( + kvector_t( + 0.0, 0.0, -layer_thickness / 2.0 - + shell_height / 2.0)) # center of coreshell in center of the layer reference_data = self.get_result(coreshell_ref) @@ -142,15 +166,19 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 50.0 shell_width = 20.0 shell_height = 10.0 - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 core = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - shell = Particle(mShell, FormFactorBox(shell_length, shell_width, shell_height)) - coreshell = ParticleCoreShell(shell, core, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell.setRotation(RotationY(90.*degree)) - coreshell.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0)) # center of coreshell in center of the layer + shell = Particle(mShell, + FormFactorBox(shell_length, shell_width, shell_height)) + coreshell = ParticleCoreShell( + shell, core, kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell.setRotation(RotationY(90. * degree)) + coreshell.setPosition(kvector_t( + 0.0, 0.0, + -layer_thickness / 2.0)) # center of coreshell in center of the layer data = self.get_result(coreshell) @@ -171,14 +199,21 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 10.0 shell_width = 50.0 shell_height = 20.0 - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 - - core_ref = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - shell_ref = Particle(mShell, FormFactorBox(shell_length, shell_width, shell_height)) - coreshell_ref = ParticleCoreShell(shell_ref, core_ref, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell_ref.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0 - shell_height/2.0)) # center of coreshell in center of the layer + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 + + core_ref = Particle(mCore, FormFactorBox(core_length, core_width, + core_height)) + shell_ref = Particle(mShell, + FormFactorBox(shell_length, shell_width, shell_height)) + coreshell_ref = ParticleCoreShell( + shell_ref, core_ref, + kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell_ref.setPosition( + kvector_t( + 0.0, 0.0, -layer_thickness / 2.0 - + shell_height / 2.0)) # center of coreshell in center of the layer reference_data = self.get_result(coreshell_ref) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_CoreShellBoxRotateZandY.int") @@ -187,17 +222,21 @@ class TransformCoreShellBoxTest(unittest.TestCase): shell_length = 50.0 shell_width = 20.0 shell_height = 10.0 - core_length = shell_length/2.0 - core_width = shell_width/2.0 - core_height = shell_height/2.0 + core_length = shell_length / 2.0 + core_width = shell_width / 2.0 + core_height = shell_height / 2.0 core = Particle(mCore, FormFactorBox(core_length, core_width, core_height)) - shell = Particle(mShell, FormFactorBox(shell_length, shell_width, shell_height)) - coreshell = ParticleCoreShell(shell, core, kvector_t(0.0, 0.0, (shell_height-core_height)/2.0)) - coreshell.setRotation(RotationZ(90.0*degree)) - coreshell.rotate(RotationY(90.0*degree)) + shell = Particle(mShell, + FormFactorBox(shell_length, shell_width, shell_height)) + coreshell = ParticleCoreShell( + shell, core, kvector_t(0.0, 0.0, (shell_height - core_height) / 2.0)) + coreshell.setRotation(RotationZ(90.0 * degree)) + coreshell.rotate(RotationY(90.0 * degree)) # rotation changes reference point, which now coincide with center of the volume - coreshell.setPosition(kvector_t(0.0, 0.0, -layer_thickness/2.0)) # center of coreshell in center of the layer + coreshell.setPosition(kvector_t( + 0.0, 0.0, + -layer_thickness / 2.0)) # center of coreshell in center of the layer data = self.get_result(coreshell) diff --git a/Tests/Functional/Python/PyCore/transform_box.py b/Tests/Functional/Python/PyCore/transform_box.py index 6090c6a7564919d927a3842a5bd46979601152cb..0813cd702f9c47245a6791dbcffbaf498d3749fe 100644 --- a/Tests/Functional/Python/PyCore/transform_box.py +++ b/Tests/Functional/Python/PyCore/transform_box.py @@ -13,11 +13,11 @@ from bornagain import deg, kvector_t layer_thickness = 100 -class BoxTransformationsTest(unittest.TestCase): +class BoxTransformationsTest(unittest.TestCase): def get_sample(self, particle): mAmbience = ba.HomogeneousMaterial("Vacuum", 0.0, 0.0) - mMiddle= ba.HomogeneousMaterial("Teflon", 2.900e-6, 6.019e-9) + mMiddle = ba.HomogeneousMaterial("Teflon", 2.900e-6, 6.019e-9) mSubstrate = ba.HomogeneousMaterial("Substrate", 3.212e-6, 3.244e-8) layout = ba.ParticleLayout() @@ -53,7 +53,7 @@ class BoxTransformationsTest(unittest.TestCase): height = 20 box = ba.Particle(mParticle, ba.FormFactorBox(length, width, height)) - box.setPosition(kvector_t(0, 0, -layer_thickness/2 - height/2)) + box.setPosition(kvector_t(0, 0, -layer_thickness / 2 - height / 2)) reference_data = self.get_result(box) #IntensityDataIOFactory.writeIntensityData(reference_data, "ref_TransformBox.int") @@ -62,9 +62,9 @@ class BoxTransformationsTest(unittest.TestCase): width = 20 height = 10 box = ba.Particle(mParticle, ba.FormFactorBox(length, width, height)) - box.setRotation(ba.RotationZ(90*deg)) - box.rotate(ba.RotationY(90*deg)) - box.setPosition(kvector_t(0, 0, -layer_thickness/2)) + box.setRotation(ba.RotationZ(90 * deg)) + box.rotate(ba.RotationY(90 * deg)) + box.setPosition(kvector_t(0, 0, -layer_thickness / 2)) data = self.get_result(box) diff --git a/Tests/Functional/Python/PyCore/transform_cube.py b/Tests/Functional/Python/PyCore/transform_cube.py index cd586e043ac3bae411163e75e193ace46503ae4c..eb59168c419e5f645e02df11de1084bb7bb0033c 100644 --- a/Tests/Functional/Python/PyCore/transform_cube.py +++ b/Tests/Functional/Python/PyCore/transform_cube.py @@ -13,10 +13,16 @@ class RotationsCubeTest(unittest.TestCase): """ Test of rotations and translations of simple cube in three layers system """ - def get_sample(self, formfactor, rot = None, pos = None, layout_rot = None, layout_pos = None, add_to="Vacuum"): + def get_sample(self, + formfactor, + rot=None, + pos=None, + layout_rot=None, + layout_pos=None, + add_to="Vacuum"): mAmbience = HomogeneousMaterial("Vacuum", 0.0, 0.0) mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8) - mMiddle= HomogeneousMaterial("MidleLayer", 5e-5, 2e-8) + mMiddle = HomogeneousMaterial("MidleLayer", 5e-5, 2e-8) mSubstrate = HomogeneousMaterial("Substrate", 6e-6, 2e-8) particle = Particle(mParticle, formfactor) @@ -75,12 +81,14 @@ class RotationsCubeTest(unittest.TestCase): data_to_test = [ # ff rot pos layout_rot layout_pos - (box, None, None, None, None), # reference - (box, RotationZ(90.*degree), None, None, None), # rotating particle - (box, RotationZ(-90.*degree), None, None, None), - (box, RotationZ(180.*degree), None, None, None), - (box, None, None, RotationZ(90.*degree), None), # rotating through layout - (box, RotationZ(45.*degree), None, RotationZ(45.*degree), None), # cumulative rotation + (box, None, None, None, None), # reference + (box, RotationZ(90. * degree), None, None, None), # rotating particle + (box, RotationZ(-90. * degree), None, None, None), + (box, RotationZ(180. * degree), None, None, None), + (box, None, None, RotationZ(90. * degree), + None), # rotating through layout + (box, RotationZ(45. * degree), None, RotationZ(45. * degree), + None), # cumulative rotation ] reference_data = self.get_result(data_to_test[0]) @@ -88,8 +96,9 @@ class RotationsCubeTest(unittest.TestCase): isSuccess = True for i in range(1, len(data_to_test)): diff = self.get_difference(reference_data, data_to_test[i]) - print("{0} #{1} diff {2:.2e}".format(self.testRotationZ.__name__, i, diff)) - if(diff > 1e-10) : isSuccess=False + print("{0} #{1} diff {2:.2e}".format(self.testRotationZ.__name__, i, + diff)) + if (diff > 1e-10): isSuccess = False self.assertTrue(isSuccess) @@ -102,11 +111,16 @@ class RotationsCubeTest(unittest.TestCase): data_to_test = [ # ff rot pos layout_rot layout_pos - (box, None, None, None, None), # reference - (box, RotationY(90.*degree), kvector_t(0,0,5.0), None, None), # rotating and translating - (box, None, None, RotationY(90.*degree), kvector_t(0,0,5.0)), # rotating and translating - (box, RotationY(90.*degree), None, None, kvector_t(0,0,5.0)), # rotating and translating - (box, RotationY(45.*degree), kvector_t(0,0,0.0), RotationY(45.*degree), kvector_t(0,0,5.0)), # rotating and translating + (box, None, None, None, None), # reference + (box, RotationY(90. * degree), kvector_t(0, 0, 5.0), None, + None), # rotating and translating + (box, None, None, RotationY(90. * degree), + kvector_t(0, 0, 5.0)), # rotating and translating + (box, RotationY(90. * degree), None, None, + kvector_t(0, 0, 5.0)), # rotating and translating + (box, RotationY(45. * degree), kvector_t(0, 0, 0.0), + RotationY(45. * degree), kvector_t(0, 0, + 5.0)), # rotating and translating ] reference_data = self.get_result(data_to_test[0]) @@ -114,8 +128,9 @@ class RotationsCubeTest(unittest.TestCase): isSuccess = True for i in range(1, len(data_to_test)): diff = self.get_difference(reference_data, data_to_test[i]) - print("{0} #{1} diff {2:.2e}".format(self.testRotationY.__name__, i, diff)) - if(diff > 1e-10) : isSuccess=False + print("{0} #{1} diff {2:.2e}".format(self.testRotationY.__name__, i, + diff)) + if (diff > 1e-10): isSuccess = False self.assertTrue(isSuccess) @@ -128,11 +143,16 @@ class RotationsCubeTest(unittest.TestCase): data_to_test = [ # ff rot pos layout_rot layout_pos - (box, None, None, None, None), # reference - (box, RotationX(90.*degree), kvector_t(0,0,5.0), None, None), # rotating and translating - (box, None, None, RotationX(90.*degree), kvector_t(0,0,5.0)), # rotating and translating - (box, RotationX(90.*degree), None, None, kvector_t(0,0,5.0)), # rotating and translating - (box, RotationX(45.*degree), kvector_t(0,0,0.0), RotationX(45.*degree), kvector_t(0,0,5.0)), # rotating and translating + (box, None, None, None, None), # reference + (box, RotationX(90. * degree), kvector_t(0, 0, 5.0), None, + None), # rotating and translating + (box, None, None, RotationX(90. * degree), + kvector_t(0, 0, 5.0)), # rotating and translating + (box, RotationX(90. * degree), None, None, + kvector_t(0, 0, 5.0)), # rotating and translating + (box, RotationX(45. * degree), kvector_t(0, 0, 0.0), + RotationX(45. * degree), kvector_t(0, 0, + 5.0)), # rotating and translating ] reference_data = self.get_result(data_to_test[0]) @@ -140,8 +160,9 @@ class RotationsCubeTest(unittest.TestCase): isSuccess = True for i in range(1, len(data_to_test)): diff = self.get_difference(reference_data, data_to_test[i]) - print("{0} #{1} diff {2:.2e}".format(self.testRotationX.__name__, i, diff)) - if(diff > 1e-10) : isSuccess=False + print("{0} #{1} diff {2:.2e}".format(self.testRotationX.__name__, i, + diff)) + if (diff > 1e-10): isSuccess = False self.assertTrue(isSuccess) @@ -152,17 +173,20 @@ class RotationsCubeTest(unittest.TestCase): data_to_test = [ # ff rot pos layout_rot layout_pos - (box, None, kvector_t(0,0,-25.0), None, None), # reference - (box, RotationX(90.*degree), kvector_t(0,0,-20.0), None, None), # rotating and translating + (box, None, kvector_t(0, 0, -25.0), None, None), # reference + (box, RotationX(90. * degree), kvector_t(0, 0, -20.0), None, + None), # rotating and translating ] reference_data = self.get_result(data_to_test[0], "add_to_middle") isSuccess = True for i in range(1, len(data_to_test)): - diff = self.get_difference(reference_data, data_to_test[i], "add_to_middle") - print("{0} #{1} diff {2:.2e}".format(self.testRotationX.__name__, i, diff)) - if(diff > 1e-10) : isSuccess=False + diff = self.get_difference(reference_data, data_to_test[i], + "add_to_middle") + print("{0} #{1} diff {2:.2e}".format(self.testRotationX.__name__, i, + diff)) + if (diff > 1e-10): isSuccess = False self.assertTrue(isSuccess) diff --git a/Tests/Functional/Python/PyCore/utils.py b/Tests/Functional/Python/PyCore/utils.py index e92450f978e91b5f3d251d1aef6b40fc2dc3855b..2d7551b69f0d735216b5c01b9195248455d34345 100644 --- a/Tests/Functional/Python/PyCore/utils.py +++ b/Tests/Functional/Python/PyCore/utils.py @@ -10,6 +10,7 @@ from bornagain import deg, angstrom REFERENCE_DIR = "@PYCORE_REFERENCE_DIR@" + def get_difference(data, reference): """ calculate numeric difference between result and reference data @@ -24,36 +25,43 @@ def get_difference(data, reference): if v1 <= epsilon and v2 <= epsilon: diff += 0.0 elif v2 <= epsilon: - diff += abs(v1/epsilon) + diff += abs(v1 / epsilon) else: - diff += abs(v1/v2) - diff = diff/data.size + diff += abs(v1 / v2) + diff = diff / data.size if numpy.isnan(diff): raise ba.Exception("get_difference", "isnan") return diff + def get_reference_data(filename): """ read and return reference data from file """ - return ba.IntensityDataIOFactory.readIntensityData(os.path.join(REFERENCE_DIR, filename)) + return ba.IntensityDataIOFactory.readIntensityData( + os.path.join(REFERENCE_DIR, filename)) + -def get_simulation_MiniGISAS(sample = None): +def get_simulation_MiniGISAS(sample=None): simulation = ba.GISASSimulation() - simulation.setDetectorParameters(25, -2.0*deg, 2.0*deg, 25, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(25, -2.0 * deg, 2.0 * deg, 25, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) if sample: simulation.setSample(sample) return simulation -def get_simulation_BasicGISAS(sample = None): + +def get_simulation_BasicGISAS(sample=None): simulation = ba.GISASSimulation() - simulation.setDetectorParameters(100, 0.0*deg, 2.0*deg, 100, 0.0*deg, 2.0*deg) - simulation.setBeamParameters(1.0*angstrom, 0.2*deg, 0.0*deg) + simulation.setDetectorParameters(100, 0.0 * deg, 2.0 * deg, 100, 0.0 * deg, + 2.0 * deg) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * deg, 0.0 * deg) if sample: simulation.setSample(sample) return simulation + def plot_intensity_data(intensity): import matplotlib, pylab data = intensity.getArray() + 1 @@ -62,7 +70,8 @@ def plot_intensity_data(intensity): phi_max = rad2deg(intensity.axis(0).upperBound()) alpha_min = rad2deg(intensity.axis(1).lowerBound()) alpha_max = rad2deg(intensity.axis(1).upperBound()) - im = pylab.imshow(data, norm=matplotlib.colors.LogNorm(), + im = pylab.imshow(data, + norm=matplotlib.colors.LogNorm(), extent=[phi_min, phi_max, alpha_min, alpha_max]) cb = pylab.colorbar(im) cb.set_label(r'Intensity (arb. u.)', size=16) diff --git a/Tests/Functional/Python/PyExamples/check_functionality.py b/Tests/Functional/Python/PyExamples/check_functionality.py index 067316c751b0d558973cf8feef3b9a0d16c61a2d..ac3cae2123ef489f708844fc07d77fda1e711e4d 100644 --- a/Tests/Functional/Python/PyExamples/check_functionality.py +++ b/Tests/Functional/Python/PyExamples/check_functionality.py @@ -17,6 +17,7 @@ sys.path.append("@CMAKE_LIBRARY_OUTPUT_DIRECTORY@") output_dir = "@output_dir@" + def get_figure(filename): """ Returns pyplot figure of appropriate size @@ -27,7 +28,7 @@ def get_figure(filename): xsize, ysize = 640, 480 dpi = 72. - return plt.figure(figsize=(xsize/dpi, ysize/dpi)) + return plt.figure(figsize=(xsize / dpi, ysize / dpi)) def exec_full(filepath): @@ -50,17 +51,18 @@ def run_example(filename): Tries to run python example and produce a *.png image """ if not os.path.exists(filename): - raise Exception("Example script '"+filename+"' not found") + raise Exception("Example script '" + filename + "' not found") - print("Input script: "+filename) + print("Input script: " + filename) fig = get_figure(filename) exec_full(filename) - plot_file_name = os.path.join(output_dir, - os.path.splitext(os.path.basename(filename))[0] + ".png") - print("Output image: "+plot_file_name) + plot_file_name = os.path.join( + output_dir, + os.path.splitext(os.path.basename(filename))[0] + ".png") + print("Output image: " + plot_file_name) plt.savefig(plot_file_name, bbox_inches='tight') plt.close(fig) @@ -74,6 +76,8 @@ def run_example(filename): if __name__ == '__main__': if len(sys.argv) != 2: - exit("Auxiliary script check_functionality called with wrong number of arguments") + exit( + "Auxiliary script check_functionality called with wrong number of arguments" + ) run_example(sys.argv[1]) diff --git a/Tests/Functional/Python/PyFit/fitobjective_api.py b/Tests/Functional/Python/PyFit/fitobjective_api.py index 3de3426e85309b6b493c7aa5fa7f151e3f741395..d65fee8e078e7e16da4b1f6bcf48a30f570f181c 100644 --- a/Tests/Functional/Python/PyFit/fitobjective_api.py +++ b/Tests/Functional/Python/PyFit/fitobjective_api.py @@ -18,7 +18,7 @@ class SimulationBuilder: self.m_ncol = 4 def size(self): - return self.m_nrow*self.m_ncol + return self.m_nrow * self.m_ncol def build_simulation(self, pars): self.m_ncalls += 1 @@ -31,7 +31,8 @@ class SimulationBuilder: simulation = ba.GISASSimulation() simulation.setSample(ml) - simulation.setDetectorParameters(self.m_ncol, 0.0, 1.0, self.m_nrow, 0.0, 1.0) + simulation.setDetectorParameters(self.m_ncol, 0.0, 1.0, self.m_nrow, 0.0, + 1.0) return simulation def create_data(self): @@ -49,7 +50,6 @@ class FitObserver: class FitObjectiveAPITest(unittest.TestCase): - def test_SimulationBuilderCallback(self): """ Testing simulation construction using Python callback @@ -76,7 +76,7 @@ class FitObjectiveAPITest(unittest.TestCase): # checking arrays of experimental and simulated data expected_sim = [] - expected_data=[] + expected_data = [] for i in range(0, builder.size()): expected_sim.append(0.0) expected_data.append(1.0) diff --git a/Tests/Functional/Python/PyFit/minimizer_api.py b/Tests/Functional/Python/PyFit/minimizer_api.py index b04126ba6cefbcabe07b8cbcf48ddf7bccaa7bc9..8eabce41be48ae779115c228a7f641801afda22e 100644 --- a/Tests/Functional/Python/PyFit/minimizer_api.py +++ b/Tests/Functional/Python/PyFit/minimizer_api.py @@ -21,7 +21,6 @@ class TestMinimizerHelper: class MinimizerAPITest(unittest.TestCase): - def test_ParameterAttribute(self): """ Testing p.value attribute @@ -69,7 +68,6 @@ class MinimizerAPITest(unittest.TestCase): self.assertTrue(params["par4"].limits().isFixed()) - def test_SimpleMinimizer(self): minimizer = ba.Minimizer() minimizer.setMinimizer("Test") diff --git a/Tests/Functional/Python/PyFit/standalone_fits.py b/Tests/Functional/Python/PyFit/standalone_fits.py index e74e97725322338db965596ddd6e10c7a5dacf88..531285aebbd238faaa63e2f8c91785deb48182b6 100644 --- a/Tests/Functional/Python/PyFit/standalone_fits.py +++ b/Tests/Functional/Python/PyFit/standalone_fits.py @@ -32,7 +32,7 @@ def decaying_sin(params, x): phaseshift = params['phase'].value freq = params['frequency'].value decay = params['decay'].value - return amp * np.sin(x*freq + phaseshift) * np.exp(-x*x*decay) + return amp * np.sin(x * freq + phaseshift) * np.exp(-x * x * decay) class DecayingSin: @@ -53,7 +53,6 @@ class DecayingSin: class StandaloneFitTest(unittest.TestCase): - def test_RosenbrockFit(self): """ Testing fit of rosenbrock function @@ -73,9 +72,8 @@ class StandaloneFitTest(unittest.TestCase): model.m_expected_params, 3) # check found minimum - np.testing.assert_almost_equal(result.minValue(), - model.m_expected_minimum, 3) - + np.testing.assert_almost_equal(result.minValue(), model.m_expected_minimum, + 3) def test_DecayingSinFit(self): params = ba.Parameters() @@ -88,12 +86,12 @@ class StandaloneFitTest(unittest.TestCase): minimizer = ba.Minimizer() result = minimizer.minimize(model.objective_function, params) - print(result.toString()) # check found parameter values np.testing.assert_almost_equal(result.parameters().values(), model.m_params.values(), 3) + if __name__ == '__main__': unittest.main() diff --git a/Tests/Performance/Python/test_performance.py b/Tests/Performance/Python/test_performance.py index 165765cfcc9d0103d22bf515ef9d3284fdfcb19e..b4eb0b9c40a8ddac414c6a4961301e1119d80a67 100755 --- a/Tests/Performance/Python/test_performance.py +++ b/Tests/Performance/Python/test_performance.py @@ -1,5 +1,5 @@ #!/usr/bin/python - # -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- ## ************************************************************************** ## ## @@ -41,11 +41,11 @@ except: record_cpu_time = False get_cpu_time = lambda: None - # globals used in custom form factor phi_min, phi_max = -1.0, 1.0 alpha_min, alpha_max = 0.0, 2.0 + # user-defined custom form factor class CustomFormFactor(IBornFF): """ @@ -71,7 +71,8 @@ class CustomFormFactor(IBornFF): return cloned_ff def evaluate_for_q(self, q): - return self.V*1.0/math.cosh(q.mag()*self.L) + return self.V * 1.0 / math.cosh(q.mag() * self.L) + # class for performance test, constructed using sample factories class FactoryTest: @@ -88,8 +89,10 @@ class FactoryTest: if simulation_name != None and sample_builder != None: self.m_sample_factory = SampleBuilderFactory() self.m_simulation_factory = SimulationFactory() - self.m_simulation = self.m_simulation_factory.createItem(self.m_simulation_name) - self.m_sample = self.m_sample_factory.createSampleByName(self.m_sample_builder_name) + self.m_simulation = self.m_simulation_factory.createItem( + self.m_simulation_name) + self.m_sample = self.m_sample_factory.createSampleByName( + self.m_sample_builder_name) else: self.m_sample_factory = None self.m_simulation_factory = None @@ -127,12 +130,12 @@ class FactoryTest: if record_cpu_time: self.m_cpu_time = end_cpu_time - start_cpu_time - logfile.write("OK: %-6.3f (wall sec), %-6.3f (cpu sec) \n" % (self.m_wall_time, self.m_cpu_time)) + logfile.write("OK: %-6.3f (wall sec), %-6.3f (cpu sec) \n" % + (self.m_wall_time, self.m_cpu_time)) else: logfile.write("OK: %-6.3f (wall sec)\n" % (self.m_wall_time)) - # special performance test case: custom form factor class CustomTest(FactoryTest): def __init__(self, name, nrepetitions): @@ -160,7 +163,7 @@ class CustomTest(FactoryTest): m_particle = HomogeneousMaterial("Particle", 6e-4, 2e-8) # collection of particles - ff = CustomFormFactor(343.0*nanometer, 7.0*nanometer) + ff = CustomFormFactor(343.0 * nanometer, 7.0 * nanometer) particle = Particle(m_particle, ff) particle_layout = ParticleLayout() particle_layout.addParticle(particle, 1.0) @@ -182,8 +185,9 @@ class CustomTest(FactoryTest): """ simulation = GISASSimulation() simulation.getOptions().setNumberOfThreads(-1) - simulation.setDetectorParameters(100, phi_min*degree, phi_max*degree, 100, alpha_min*degree, alpha_max*degree) - simulation.setBeamParameters(1.0*angstrom, 0.2*degree, 0.0*degree) + simulation.setDetectorParameters(100, phi_min * degree, phi_max * degree, + 100, alpha_min * degree, alpha_max * degree) + simulation.setBeamParameters(1.0 * angstrom, 0.2 * degree, 0.0 * degree) return simulation @@ -197,40 +201,44 @@ class PerformanceTests: self.m_pyversion = "" self.m_filename = filename - self.add("MultiLayer", "MaxiGISAS", "MultiLayerWithRoughnessBuilder", 1) - self.add("CylindersInDWBA", "MaxiGISAS", "CylindersInDWBABuilder", 10) - self.add("RotatedPyramids", "MaxiGISAS", "RotatedPyramidsBuilder", 10) - self.add("CoreShell", "MaxiGISAS", "CoreShellParticleBuilder", 10) - self.add("SquareLattice2D", "MaxiGISAS", "SquareLattice2DBuilder", 10) - self.add("RadialParaCrystal", "MaxiGISAS", "RadialParaCrystalBuilder", 10) - self.add("HexParaCrystal", "BasicGISAS", "HexParaCrystalBuilder", 1) - self.add("SSCA", "MaxiGISAS", "SizeDistributionSSCAModelBuilder", 10) - self.add("Mesocrystal", "MaxiGISAS", "MesoCrystalBuilder", 2) - self.add("PolMagCyl", "MaxiGISAS00", "MagneticCylindersBuilder", 10) + self.add("MultiLayer", "MaxiGISAS", "MultiLayerWithRoughnessBuilder", 1) + self.add("CylindersInDWBA", "MaxiGISAS", "CylindersInDWBABuilder", 10) + self.add("RotatedPyramids", "MaxiGISAS", "RotatedPyramidsBuilder", 10) + self.add("CoreShell", "MaxiGISAS", "CoreShellParticleBuilder", 10) + self.add("SquareLattice2D", "MaxiGISAS", "SquareLattice2DBuilder", 10) + self.add("RadialParaCrystal", "MaxiGISAS", "RadialParaCrystalBuilder", 10) + self.add("HexParaCrystal", "BasicGISAS", "HexParaCrystalBuilder", 1) + self.add("SSCA", "MaxiGISAS", "SizeDistributionSSCAModelBuilder", 10) + self.add("Mesocrystal", "MaxiGISAS", "MesoCrystalBuilder", 2) + self.add("PolMagCyl", "MaxiGISAS00", "MagneticCylindersBuilder", 10) # custom form factor is a special case since it's not in the registry self.m_tests.append(CustomTest("Custom FF", 10)) - logfile.write("\nPreparing to run %d performance tests.\n\n" % len(self.m_tests)) + logfile.write("\nPreparing to run %d performance tests.\n\n" % + len(self.m_tests)) def add(self, name, simulation_name, sample_builder, nrepetitions): - self.m_tests.append(FactoryTest(name, simulation_name, sample_builder, nrepetitions)) + self.m_tests.append( + FactoryTest(name, simulation_name, sample_builder, nrepetitions)) # execute all performance tests def execute(self): self.init_sysinfo() - for test in self.m_tests: test.run() + for test in self.m_tests: + test.run() self.write_results() - # write out system information and test results to file def write_results(self): - if ( self.m_filename != None ): + if (self.m_filename != None): try: write_file = open(self.m_filename, "a") except: - sys.stderr.write("Could not open filed '%' for writing. Writing to stdout instead.\n" % self.m_filename) + sys.stderr.write( + "Could not open filed '%' for writing. Writing to stdout instead.\n" + % self.m_filename) write_file = sys.stdout self.m_filename = None @@ -265,17 +273,19 @@ class PerformanceTests: write_file.write("\n") write_file.flush() - if ( self.m_filename != None ): + if (self.m_filename != None): write_file.close() # determine platform, architecture, python version, etc. def init_sysinfo(self): system, node, release, version, machine, processor = platform.uname() - self.m_datime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') + self.m_datime = datetime.datetime.strftime(datetime.datetime.now(), + '%Y-%m-%d %H:%M:%S') self.m_hostname = node self.m_sysinfo = "%s %s" % (system, machine) self.m_pyversion = "%d.%d" % (sys.version_info[:2]) + # used for writing the summary with proper formatting def pretty_write(dictionary, file): header = "|" @@ -291,9 +301,10 @@ def pretty_write(dictionary, file): file.write(header + "\n") file.write(footer + "\n") + if __name__ == '__main__': - if ( len(sys.argv) > 2 ): + if (len(sys.argv) > 2): print("Usage: test_performance.py [output file]") exit(0) diff --git a/Wrap/Python/bornagain_python_install.py b/Wrap/Python/bornagain_python_install.py index ed50aea5d77b09684fdb3f4fc76a77b8264eb6b1..f0f39b41233074c3321d2252e771998d82ec0e43 100644 --- a/Wrap/Python/bornagain_python_install.py +++ b/Wrap/Python/bornagain_python_install.py @@ -31,36 +31,41 @@ import site import subprocess from distutils.sysconfig import get_python_lib - BORNAGAIN_VERSION = "0.0" + def is_python3(): if (sys.version_info > (3, 0)): return True else: return False + def python_version_string(): return str(sys.version_info[0]) + "." + str(sys.version_info[1]) def add_rpath(newpath, filename): print("add_rpath ", newpath, filename) - p = subprocess.Popen(['install_name_tool', '-add_rpath', newpath, filename], stdout=subprocess.PIPE) + p = subprocess.Popen(['install_name_tool', '-add_rpath', newpath, filename], + stdout=subprocess.PIPE) p.communicate() return def change_rpath(oldpath, newpath, filename): print("change_rpath ", oldpath, newpath, filename) - p = subprocess.Popen(['install_name_tool', '-change', oldpath, newpath, filename], stdout=subprocess.PIPE) + p = subprocess.Popen( + ['install_name_tool', '-change', oldpath, newpath, filename], + stdout=subprocess.PIPE) p.communicate() return def delete_rpath(todelete, filename): print("delete_rpath ", todelete, filename) - p = subprocess.Popen(['install_name_tool', '-delete_rpath', todelete, filename], stdout=subprocess.PIPE) + p = subprocess.Popen(['install_name_tool', '-delete_rpath', todelete, filename], + stdout=subprocess.PIPE) p.communicate() return @@ -84,8 +89,9 @@ def get_python_shared_library(): Returns full path to the python shared library on which current interpreter is relying """ prefix = sys.prefix - suffix = sysconfig.get_config_var('LDVERSION') or sysconfig.get_config_var('VERSION') - result = sys.prefix+"/lib/libpython"+suffix+".dylib" + suffix = sysconfig.get_config_var('LDVERSION') or sysconfig.get_config_var( + 'VERSION') + result = sys.prefix + "/lib/libpython" + suffix + ".dylib" return result @@ -109,9 +115,9 @@ def get_application_dir(): app_dir = os.path.abspath(os.path.join(script_dir, "..", "..", "..")) # getting version number - lib_dir = glob.glob( os.path.join(app_dir, "Contents", "lib", "BornAgain-*")) + lib_dir = glob.glob(os.path.join(app_dir, "Contents", "lib", "BornAgain-*")) if len(lib_dir) != 1: - exit("Can't find BornAgain libraries in "+app_dir) + exit("Can't find BornAgain libraries in " + app_dir) BORNAGAIN_VERSION = lib_dir[0].split("BornAgain-")[1] return app_dir @@ -185,7 +191,8 @@ setup(name='bornagain', def prepare_init_module(app_dir, bundle_dir): source_dir = os.path.join(app_dir, "Contents", "libexec") - libexec_dir = os.path.join(source_dir, "BornAgain-"+BORNAGAIN_VERSION, "bornagain") + libexec_dir = os.path.join(source_dir, "BornAgain-" + BORNAGAIN_VERSION, + "bornagain") package_dir = os.path.join(bundle_dir, "bornagain") print("--> Copying modules from '{0}' to '{1}'".format(libexec_dir, package_dir)) shutil.copytree(libexec_dir, package_dir) @@ -197,11 +204,13 @@ def copy_libraries(app_dir, destination_dir): Copy libraries from BornAgain.app into corresponding BornAgain Python package directory """ print("--> Copying libraries from '{0}'".format(app_dir)) - app_bornagainlib_dir = os.path.join(app_dir, "Contents", "lib", "BornAgain-"+BORNAGAIN_VERSION) + app_bornagainlib_dir = os.path.join(app_dir, "Contents", "lib", + "BornAgain-" + BORNAGAIN_VERSION) app_frameworks_dir = os.path.join(app_dir, "Contents", "Frameworks") # copying BornAgain libraries - shutil.copytree(app_bornagainlib_dir, os.path.join(destination_dir, "BornAgain-"+BORNAGAIN_VERSION)) + shutil.copytree(app_bornagainlib_dir, + os.path.join(destination_dir, "BornAgain-" + BORNAGAIN_VERSION)) # cleaning unnecessary files libfiles = glob.glob(os.path.join(destination_dir, '*/libBornAgainGUI*')) @@ -222,11 +231,12 @@ def patch_libraries(dir_name): """ Patches libraries depending on Python to point on the same shared libpython2.7.dylib which current interpreter is using """ - print("--> Patching libraries to rely on '{0}'".format(get_python_shared_library())) + print("--> Patching libraries to rely on '{0}'".format( + get_python_shared_library())) libfiles = glob.glob(os.path.join(dir_name, '*/_libBornAgain*')) for f in libfiles: for lib in ["Base", "Fit", "Param", "Sample", "Device", "Core"]: - if "libBornAgain"+lib in f: + if "libBornAgain" + lib in f: delete_rpath("@loader_path/../../Frameworks", f) add_rpath("@loader_path/../Frameworks", f) if "libBornAgainCore" in f: @@ -234,8 +244,9 @@ def patch_libraries(dir_name): libfiles += glob.glob(os.path.join(dir_name, '*/libboost_python*')) for f in libfiles: - change_rpath("@rpath/Python.framework/Versions/"+python_version_string()+"/Python", get_python_shared_library(), f) - + change_rpath( + "@rpath/Python.framework/Versions/" + python_version_string() + + "/Python", get_python_shared_library(), f) pass @@ -245,9 +256,9 @@ def create_bundle(app_dir): Creates ready to install BornAgain Python bundle package """ bundle_dir = create_bundle_tem_dir() - print('-'*80) + print('-' * 80) print("Generating Python bundle in temporary '{0}'".format(bundle_dir)) - print('-'*80) + print('-' * 80) print("--> Generating bundle setup files") @@ -260,8 +271,12 @@ def create_bundle(app_dir): patch_libraries(library_dir) - print("\nBornAgain Python bundle is successfully created in temporary directory '{0}'".format(bundle_dir)) - print("Run 'python setup.py install' from there to install it into your Python's site-packages") + print( + "\nBornAgain Python bundle is successfully created in temporary directory '{0}'" + .format(bundle_dir)) + print( + "Run 'python setup.py install' from there to install it into your Python's site-packages" + ) return bundle_dir @@ -269,14 +284,15 @@ def install_bundle(dir_name): """ Installs BornAgain Python bundle previously generated in the directory dir_name """ - print('-'*80) + print('-' * 80) print("Installing bundle in Python site-packages '{0}'".format(get_python_lib())) - print('-'*80) + print('-' * 80) os.chdir(bundle_dir) sys.argv = ['setup.py', 'install'] exec_full('setup.py') - print("\nBornAgain Python bundle is successfully installed in '{0}'".format(get_python_lib())) + print("\nBornAgain Python bundle is successfully installed in '{0}'".format( + get_python_lib())) print("Congratulations!") @@ -286,9 +302,11 @@ if __name__ == '__main__': app_dir = get_application_dir() - print('-'*80) - print("Installation of BornAgain-{0} libraries into site-packages of your Python".format(BORNAGAIN_VERSION)) - print('-'*80) + print('-' * 80) + print( + "Installation of BornAgain-{0} libraries into site-packages of your Python". + format(BORNAGAIN_VERSION)) + print('-' * 80) print("From :", app_dir) print("To :", get_python_lib()) print(" ") diff --git a/Wrap/Python/plot_utils.py b/Wrap/Python/plot_utils.py index f21d57b1c379beb7b030a2e39de49a766704944d..654dd8170686e6fd39e6b5b6e10b31986130df57 100644 --- a/Wrap/Python/plot_utils.py +++ b/Wrap/Python/plot_utils.py @@ -22,7 +22,6 @@ try: # workaround for build servers except Exception as e: print("In plot_utils.py: {:s}".format(str(e))) - label_fontsize = 16 @@ -34,8 +33,9 @@ def get_axes_limits(result, units): :return: axes ranges as a flat list """ axis_infos = result.axisInfo(units) - limits = [ [axis_infos[i].m_min, axis_infos[i].m_max] for i in range(len(axis_infos)) ] - flat_limits = [ v for sublist in limits for v in sublist ] + limits = [[axis_infos[i].m_min, axis_infos[i].m_max] + for i in range(len(axis_infos))] + flat_limits = [v for sublist in limits for v in sublist] return flat_limits @@ -47,23 +47,22 @@ def translate_axis_label(label): :return: LaTeX representation """ label_dict = { - 'X [nbins]' : r'$X \; $(bins)', - 'phi_f [rad]' : r'$\varphi_f \; $(rad)', - 'phi_f [deg]' : r'$\varphi_f \; $(deg)', - 'alpha_i [rad]' : r'$\alpha_i \; $(rad)', - 'alpha_i [deg]' : r'$\alpha_i \; $(deg)', - 'X [mm]' : r'$X \; $(mm)', - 'Qx [1/nm]' : r'$Q_x \; $(nm$^{-1}$)', - 'Qy [1/nm]' : r'$Q_y \; $(nm$^{-1}$)', - 'Q [1/nm]' : r'$Q \; $(nm$^{-1}$)', - - 'Y [nbins]' : r'$Y \; $(bins)', - 'alpha_f [rad]' : r'$\alpha_f \; $(rad)', - 'alpha_f [deg]' : r'$\alpha_f \; $(deg)', - 'Y [mm]' : r'$Y \; $(mm)', - 'Qz [1/nm]' : r'$Q_z \; $(nm$^{-1}$)', - 'Position [nm]' : r'$Position \; $(nm)' - } + 'X [nbins]': r'$X \; $(bins)', + 'phi_f [rad]': r'$\varphi_f \; $(rad)', + 'phi_f [deg]': r'$\varphi_f \; $(deg)', + 'alpha_i [rad]': r'$\alpha_i \; $(rad)', + 'alpha_i [deg]': r'$\alpha_i \; $(deg)', + 'X [mm]': r'$X \; $(mm)', + 'Qx [1/nm]': r'$Q_x \; $(nm$^{-1}$)', + 'Qy [1/nm]': r'$Q_y \; $(nm$^{-1}$)', + 'Q [1/nm]': r'$Q \; $(nm$^{-1}$)', + 'Y [nbins]': r'$Y \; $(bins)', + 'alpha_f [rad]': r'$\alpha_f \; $(rad)', + 'alpha_f [deg]': r'$\alpha_f \; $(deg)', + 'Y [mm]': r'$Y \; $(mm)', + 'Qz [1/nm]': r'$Q_z \; $(nm$^{-1}$)', + 'Position [nm]': r'$Position \; $(nm)' + } if label in label_dict.keys(): return label_dict[label] else: @@ -78,13 +77,22 @@ def get_axes_labels(result, units): :return: axes ranges as a flat list """ axis_infos = result.axisInfo(units) - labels = [ translate_axis_label(axis_infos[i].m_name) for i in range(len(axis_infos)) ] + labels = [ + translate_axis_label(axis_infos[i].m_name) for i in range(len(axis_infos)) + ] return labels -def plot_array(array, zmin=None, zmax=None, xlabel=None, ylabel=None, zlabel=None, - title=None, axes_limits=None, **kwargs): +def plot_array(array, + zmin=None, + zmax=None, + xlabel=None, + ylabel=None, + zlabel=None, + title=None, + axes_limits=None, + **kwargs): """ Plots numpy array as a colormap in log scale. """ @@ -92,7 +100,7 @@ def plot_array(array, zmin=None, zmax=None, xlabel=None, ylabel=None, zlabel=Non zlabel = "Intensity" if zlabel is None else zlabel zmax = np.amax(array) if zmax is None else zmax - zmin = 1e-6*zmax if zmin is None else zmin + zmin = 1e-6 * zmax if zmin is None else zmin if zmin == zmax == 0.0: norm = colors.Normalize(0, 1) @@ -115,8 +123,14 @@ def plot_array(array, zmin=None, zmax=None, xlabel=None, ylabel=None, zlabel=Non plt.title(title) -def plot_histogram(hist, zmin=None, zmax=None, xlabel=None, ylabel=None, zlabel=None, - title=None, **kwargs): +def plot_histogram(hist, + zmin=None, + zmax=None, + xlabel=None, + ylabel=None, + zlabel=None, + title=None, + **kwargs): """ Plots intensity data as color map :param intensity: Histogram2D object obtained from GISASSimulation @@ -130,16 +144,28 @@ def plot_histogram(hist, zmin=None, zmax=None, xlabel=None, ylabel=None, zlabel= if not ylabel: ylabel = translate_axis_label(hist.yAxis().getName()) - axes_limits = [hist.getXmin(), hist.getXmax(), - hist.getYmin(), hist.getYmax()] - - plot_array(hist.array(), zmin=zmin, zmax=zmax, xlabel=xlabel, ylabel=ylabel, - zlabel=zlabel, title=title, axes_limits=axes_limits, **kwargs) - - -def plot_colormap(result, zmin=None, zmax=None, units=ba.Axes.DEFAULT, - xlabel=None, ylabel=None, zlabel=None, - title=None, **kwargs): + axes_limits = [hist.getXmin(), hist.getXmax(), hist.getYmin(), hist.getYmax()] + + plot_array(hist.array(), + zmin=zmin, + zmax=zmax, + xlabel=xlabel, + ylabel=ylabel, + zlabel=zlabel, + title=title, + axes_limits=axes_limits, + **kwargs) + + +def plot_colormap(result, + zmin=None, + zmax=None, + units=ba.Axes.DEFAULT, + xlabel=None, + ylabel=None, + zlabel=None, + title=None, + **kwargs): """ Plots intensity data as color map :param result: SimulationResult from GISAS/OffSpecSimulation @@ -152,12 +178,25 @@ def plot_colormap(result, zmin=None, zmax=None, units=ba.Axes.DEFAULT, xlabel = axes_labels[0] if xlabel is None else xlabel ylabel = axes_labels[1] if ylabel is None else ylabel - plot_array(result.array(), zmin=zmin, zmax=zmax, xlabel=xlabel, ylabel=ylabel, - zlabel=zlabel, title=title, axes_limits=axes_limits, **kwargs) - - -def plot_specular_simulation_result(result, ymin=None, ymax=None, units=ba.Axes.DEFAULT, - xlabel=None, ylabel=None, title=None, **kwargs): + plot_array(result.array(), + zmin=zmin, + zmax=zmax, + xlabel=xlabel, + ylabel=ylabel, + zlabel=zlabel, + title=title, + axes_limits=axes_limits, + **kwargs) + + +def plot_specular_simulation_result(result, + ymin=None, + ymax=None, + units=ba.Axes.DEFAULT, + xlabel=None, + ylabel=None, + title=None, + **kwargs): """ Plots intensity data for specular simulation result :param result: SimulationResult from SpecularSimulation @@ -188,8 +227,15 @@ def plot_specular_simulation_result(result, ymin=None, ymax=None, units=ba.Axes. plt.title(title) -def plot_simulation_result(result, intensity_min=None, intensity_max=None, units=ba.Axes.DEFAULT, - xlabel=None, ylabel=None, postpone_show=False, title=None, **kwargs): +def plot_simulation_result(result, + intensity_min=None, + intensity_max=None, + units=ba.Axes.DEFAULT, + xlabel=None, + ylabel=None, + postpone_show=False, + title=None, + **kwargs): """ Draws simulation result and (optionally) shows the plot. :param result_: SimulationResult object obtained from GISAS/OffSpec/SpecularSimulation @@ -199,18 +245,30 @@ def plot_simulation_result(result, intensity_min=None, intensity_max=None, units :param postpone_show: postpone showing the plot for later tuning (False by default) """ if len(result.array().shape) == 1: # 1D data, specular simulation assumed - plot_specular_simulation_result(result, intensity_min, intensity_max, units, **kwargs) + plot_specular_simulation_result(result, intensity_min, intensity_max, units, + **kwargs) else: - plot_colormap(result, intensity_min, intensity_max, units, xlabel, ylabel, - title=title, **kwargs) + plot_colormap(result, + intensity_min, + intensity_max, + units, + xlabel, + ylabel, + title=title, + **kwargs) plt.tight_layout() if not postpone_show: plt.show() class Plotter: - def __init__(self, zmin=None, zmax=None, xlabel=None, ylabel=None, - units=ba.Axes.DEFAULT, aspect=None): + def __init__(self, + zmin=None, + zmax=None, + xlabel=None, + ylabel=None, + units=ba.Axes.DEFAULT, + aspect=None): self._fig = plt.figure(figsize=(10.25, 7.69)) self._fig.canvas.draw() @@ -230,8 +288,13 @@ class Plotter: class PlotterGISAS(Plotter): - def __init__(self, zmin=None, zmax=None, xlabel=None, ylabel=None, - units=ba.Axes.DEFAULT, aspect=None): + def __init__(self, + zmin=None, + zmax=None, + xlabel=None, + ylabel=None, + units=ba.Axes.DEFAULT, + aspect=None): Plotter.__init__(self, zmin, zmax, xlabel, ylabel, units, aspect) @staticmethod @@ -251,21 +314,39 @@ class PlotterGISAS(Plotter): # same limits for both plots arr = real_data.array() zmax = np.amax(arr) if self._zmax is None else self._zmax - zmin = zmax*1e-6 if self._zmin is None else self._zmin - - ba.plot_colormap(real_data, title="Experimental data", zmin=zmin, zmax=zmax, - units=self._units, xlabel=self._xlabel, ylabel=self._ylabel, - zlabel='', aspect=self._aspect) + zmin = zmax * 1e-6 if self._zmin is None else self._zmin + + ba.plot_colormap(real_data, + title="Experimental data", + zmin=zmin, + zmax=zmax, + units=self._units, + xlabel=self._xlabel, + ylabel=self._ylabel, + zlabel='', + aspect=self._aspect) self.make_subplot(2) - ba.plot_colormap(sim_data, title="Simulated data", zmin=zmin, zmax=zmax, - units=self._units, xlabel=self._xlabel, ylabel=self._ylabel, - zlabel='', aspect=self._aspect) + ba.plot_colormap(sim_data, + title="Simulated data", + zmin=zmin, + zmax=zmax, + units=self._units, + xlabel=self._xlabel, + ylabel=self._ylabel, + zlabel='', + aspect=self._aspect) self.make_subplot(3) - ba.plot_colormap(diff, title="Difference", zmin=zmin, zmax=zmax, - units=self._units, xlabel=self._xlabel, ylabel=self._ylabel, - zlabel='', aspect=self._aspect) + ba.plot_colormap(diff, + title="Difference", + zmin=zmin, + zmax=zmax, + units=self._units, + xlabel=self._xlabel, + ylabel=self._ylabel, + zlabel='', + aspect=self._aspect) self.make_subplot(4) plt.title('Parameters') @@ -273,13 +354,14 @@ class PlotterGISAS(Plotter): iteration_info = fit_objective.iterationInfo() - plt.text(0.01, 0.85, "Iterations " + '{:d}'. - format(iteration_info.iterationCount())) + plt.text(0.01, 0.85, + "Iterations " + '{:d}'.format(iteration_info.iterationCount())) plt.text(0.01, 0.75, "Chi2 " + '{:8.4f}'.format(iteration_info.chi2())) index = 0 params = iteration_info.parameterMap() for key in params: - plt.text(0.01, 0.55 - index * 0.1, '{:30.30s}: {:6.3f}'.format(key, params[key])) + plt.text(0.01, 0.55 - index * 0.1, + '{:30.30s}: {:6.3f}'.format(key, params[key])) index = index + 1 Plotter.plot(self) @@ -290,7 +372,6 @@ class PlotterSpecular(Plotter): Draws fit progress. Intended specifically for observing specular data fit. """ - def __init__(self, units=ba.Axes.DEFAULT): Plotter.__init__(self) self.gs = gridspec.GridSpec(1, 2, width_ratios=[2.5, 1], wspace=0) @@ -334,24 +415,34 @@ class PlotterSpecular(Plotter): trunc_length = 9 # max string field width in the table n_digits = 1 # number of decimal digits to print - n_iterations = iteration_info.iterationCount() # current number of iterations passed - rel_dif = fit_objective.relativeDifference().array().max() # maximum relative difference + n_iterations = iteration_info.iterationCount( + ) # current number of iterations passed + rel_dif = fit_objective.relativeDifference().array().max( + ) # maximum relative difference fitted_parameters = iteration_info.parameterMap() # creating table content labels = ("Parameter", "Value") table_data = [["Iteration", '${:d}$'.format(n_iterations)], - ["$d_{r, max}$", '${:s}$'.format(self.as_si(rel_dif, n_digits))]] + [ + "$d_{r, max}$", + '${:s}$'.format(self.as_si(rel_dif, n_digits)) + ]] for key, value in fitted_parameters.iteritems(): - table_data.append(['{:s}'.format(self.trunc_str(key, trunc_length)), - '${:s}$'.format(self.as_si(value, n_digits))]) + table_data.append([ + '{:s}'.format(self.trunc_str(key, trunc_length)), + '${:s}$'.format(self.as_si(value, n_digits)) + ]) # creating table axs = plt.subplot(self.gs[1]) axs.axis('tight') axs.axis('off') - table = plt.table(cellText=table_data, colLabels=labels, cellLoc='center', - loc='bottom left', bbox=[0.0, 0.0, 1.0, 1.0]) + table = plt.table(cellText=table_data, + colLabels=labels, + cellLoc='center', + loc='bottom left', + bbox=[0.0, 0.0, 1.0, 1.0]) def plot_graph(self, fit_objective): # retrieving data from fit suite @@ -365,16 +456,20 @@ class PlotterSpecular(Plotter): unc_values = None if unc_data is None else unc_data.array(self.units) # default font properties dictionary to use - font = {'family': 'serif', - 'weight': 'normal', - 'size': label_fontsize} + font = {'family': 'serif', 'weight': 'normal', 'size': label_fontsize} plt.subplot(self.gs[0]) - plt.semilogy(sim_data.axis(), sim_values, 'b', - real_data.axis(), real_values, 'k--') + plt.semilogy(sim_data.axis(), sim_values, 'b', real_data.axis(), real_values, + 'k--') if unc_values is not None: - plt.semilogy(real_data.axis(), real_values - unc_values, 'xkcd:grey', alpha=0.6) - plt.semilogy(real_data.axis(), real_values + unc_values, 'xkcd:grey', alpha=0.6) + plt.semilogy(real_data.axis(), + real_values - unc_values, + 'xkcd:grey', + alpha=0.6) + plt.semilogy(real_data.axis(), + real_values + unc_values, + 'xkcd:grey', + alpha=0.6) plt.ylim((0.5 * np.min(real_values), 5 * np.max(real_values))) xlabel = get_axes_labels(real_data, self.units)[0] diff --git a/Wrap/swig/doxy2swig.py b/Wrap/swig/doxy2swig.py index 0491aff06fbc38bbb0fb8a63fa74dce156ae34a6..1ef67ec7b474dbfdaaf882f97eb158a3b6cfd772 100755 --- a/Wrap/swig/doxy2swig.py +++ b/Wrap/swig/doxy2swig.py @@ -34,6 +34,7 @@ def my_open_read(source): else: return open(source) + def my_open_write(dest, mode='w'): if hasattr(dest, "write"): return dest @@ -47,7 +48,6 @@ class Doxy2SWIG: is stored in self.pieces. """ - def __init__(self, src): """Initialize the instance given a source object (file or filename). @@ -67,10 +67,9 @@ class Doxy2SWIG: self.multi = 0 self.ignores = ('inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', - 'invincdepgraph', 'programlisting', 'type', - 'references', 'referencedby', 'location', - 'collaborationgraph', 'reimplements', - 'reimplementedby', 'derivedcompoundref', + 'invincdepgraph', 'programlisting', 'type', 'references', + 'referencedby', 'location', 'collaborationgraph', + 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref') #self.generics = [] @@ -87,7 +86,7 @@ class Doxy2SWIG: nodes. """ - pm = getattr(self, "parse_%s"%node.__class__.__name__) + pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): @@ -181,7 +180,7 @@ class Doxy2SWIG: def do_compoundname(self, node): self.add_text('\n\n') data = node.firstChild.data - self.add_text('%%feature("docstring") %s "\n'%data) + self.add_text('%%feature("docstring") %s "\n' % data) def do_compounddef(self, node): kind = node.attributes['kind'].value @@ -189,14 +188,14 @@ class Doxy2SWIG: prot = node.attributes['prot'].value if prot != 'public': return - names = ('compoundname', 'briefdescription', - 'detaileddescription', 'includes') + names = ('compoundname', 'briefdescription', 'detaileddescription', + 'includes') first = self.get_specific_nodes(node, names) for n in names: #if first.has_key(n): if n in first: self.parse(first[n]) - self.add_text(['";','\n']) + self.add_text(['";', '\n']) for n in node.childNodes: if n not in first.values(): self.parse(n) @@ -219,7 +218,7 @@ class Doxy2SWIG: def do_parametername(self, node): self.add_text('\n') - self.add_text("%s: "%node.firstChild.data) + self.add_text("%s: " % node.firstChild.data) def do_parameterdefinition(self, node): self.generic_parse(node, pad=1) @@ -241,7 +240,7 @@ class Doxy2SWIG: if prot == 'public': first = self.get_specific_nodes(node, ('definition', 'name')) name = first['name'].firstChild.data - if name[:8] == 'operator': # Don't handle operators yet. + if name[:8] == 'operator': # Don't handle operators yet. return defn = first['definition'].firstChild.data @@ -255,14 +254,14 @@ class Doxy2SWIG: ns_node = anc.getElementsByTagName('compoundname') if ns_node: ns = ns_node[0].firstChild.data - self.add_text(' %s::%s "\n%s'%(ns, name, defn)) + self.add_text(' %s::%s "\n%s' % (ns, name, defn)) else: - self.add_text(' %s "\n%s'%(name, defn)) + self.add_text(' %s "\n%s' % (name, defn)) elif cdef_kind in ('class', 'struct'): # Get the full function name. anc_node = anc.getElementsByTagName('compoundname') cname = anc_node[0].firstChild.data - self.add_text(' %s::%s "\n%s'%(cname, name, defn)) + self.add_text(' %s::%s "\n%s' % (cname, name, defn)) for n in node.childNodes: if n not in first.values(): @@ -271,7 +270,7 @@ class Doxy2SWIG: def do_definition(self, node): data = node.firstChild.data - self.add_text('%s "\n%s'%(data, data)) + self.add_text('%s "\n%s' % (data, data)) def do_sectiondef(self, node): kind = node.attributes['kind'].value @@ -308,7 +307,7 @@ class Doxy2SWIG: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): - fname = os.path.join(self.my_dir, fname) + fname = os.path.join(self.my_dir, fname) # print("parsing file: %s"%fname) p = Doxy2SWIG(fname) p.generate() @@ -340,7 +339,7 @@ class Doxy2SWIG: elif count > 2: ret.append('\n\n') elif count: - ret.append('\n'*count) + ret.append('\n' * count) count = 0 ret.append(i) @@ -349,7 +348,7 @@ class Doxy2SWIG: for i in _data.split('\n\n'): if i == 'Parameters:': ret.extend(['Parameters:\n-----------', '\n\n']) - elif i.find('// File:') > -1: # leave comments alone. + elif i.find('// File:') > -1: # leave comments alone. ret.extend([i, '\n']) else: #_tmp = textwrap.fill(i.strip()) diff --git a/Wrap/swig/tweaks.py b/Wrap/swig/tweaks.py index 2d8bf7b80c4b001e23e9a3e7e9fd098588e4238b..35994c153c4626706ba9004bc19fb87ebb3a533c 100644 --- a/Wrap/swig/tweaks.py +++ b/Wrap/swig/tweaks.py @@ -5,15 +5,17 @@ import sys import os import string + # compatibility with windows filename conventions def windowsify(filename): - if ( sys.platform == "win32" ): + if (sys.platform == "win32"): new_filename = filename.replace("/", "\\") else: new_filename = filename return os.path.abspath(new_filename) + if len(sys.argv) != 3: print("Usage: tweaks.py inputfile outputfile") exit(1) @@ -29,13 +31,17 @@ fd.close() text_out = [] for line in text_in: - line = line.replace("_libBornAgainBase.ICloneable_transferToCPP(self)", "self.__disown__()") - line = line.replace("_libBornAgainCore.Histogram1D_binCenters(self)", "self.binCentersNumpy()") - line = line.replace("_libBornAgainCore.Histogram1D_binErrors(self)", "self.binErrorsNumpy()") - line = line.replace("_libBornAgainCore.Histogram1D_binValues(self)", "self.binValuesNumpy()") + line = line.replace("_libBornAgainBase.ICloneable_transferToCPP(self)", + "self.__disown__()") + line = line.replace("_libBornAgainCore.Histogram1D_binCenters(self)", + "self.binCentersNumpy()") + line = line.replace("_libBornAgainCore.Histogram1D_binErrors(self)", + "self.binErrorsNumpy()") + line = line.replace("_libBornAgainCore.Histogram1D_binValues(self)", + "self.binValuesNumpy()") text_out.append(line) # done the search/replace fd = open(out_name, "w") -fd.write( "\n".join( text_out ) ) +fd.write("\n".join(text_out)) fd.close() diff --git a/cmake/pack/fix_apple_bundle.py b/cmake/pack/fix_apple_bundle.py index f40cc3e32f118d9f77396a3064f069e22e94591c..415e7119cbdaffc75b7c6ce64cd5d91c41d1b4e9 100644 --- a/cmake/pack/fix_apple_bundle.py +++ b/cmake/pack/fix_apple_bundle.py @@ -18,6 +18,7 @@ BUNDLE_DIR = "" # Locations # ----------------------------------------------------------------------------- + def is_python3(): if (sys.version_info > (3, 0)): return True @@ -52,7 +53,8 @@ def bundle_main_executables(): def bundle_python_library(): - return os.path.join("Python.framework", "Versions", python_version_string(), "Python") + return os.path.join("Python.framework", "Versions", python_version_string(), + "Python") def qtlibs_path(): @@ -64,7 +66,8 @@ def qtplugins_path(): def bundle_libraries(): - return glob.glob(os.path.join(bundle_dir(), "Contents", "lib", "BornAgain-*", "*")) + return glob.glob( + os.path.join(bundle_dir(), "Contents", "lib", "BornAgain-*", "*")) def bundle_plugins(): @@ -82,7 +85,7 @@ def get_list_of_files(dirname): result = [] for root, directories, filenames in os.walk(dirname): for filename in filenames: - result.append(os.path.join(root,filename)) + result.append(os.path.join(root, filename)) return result @@ -131,7 +134,8 @@ def setId(filename, newId): """ Sets new id for binary file """ - p = subprocess.Popen(['install_name_tool', '-id', newId, filename], stdout=subprocess.PIPE) + p = subprocess.Popen(['install_name_tool', '-id', newId, filename], + stdout=subprocess.PIPE) p.communicate() return @@ -141,7 +145,8 @@ def fixDependency(filename, old, new): Replaces old dependency with new one for given binary file """ print(" fixDependency(filename, old, new)", filename, old, new) - p = subprocess.Popen(['install_name_tool', '-change', old, new, filename], stdout=subprocess.PIPE) + p = subprocess.Popen(['install_name_tool', '-change', old, new, filename], + stdout=subprocess.PIPE) p.communicate() return @@ -213,7 +218,7 @@ def get_dependency_libId(dependency): return "@rpath/" + bundle_python_library() if is_qt_framework_dependency(dependency): - return "@rpath/" + libname +".framework/Versions/5/"+libname + return "@rpath/" + libname + ".framework/Versions/5/" + libname # all other libraries return "@rpath/" + libname @@ -235,7 +240,7 @@ def get_dependency_orig_location(dependency): elif is_qt_framework_dependency(dependency): libname = os.path.basename(dependency) - libpath = os.path.join(libname+".framework", "Versions", "5") + libpath = os.path.join(libname + ".framework", "Versions", "5") result = os.path.join(qtlibs_path(), libpath, libname) return result @@ -251,7 +256,7 @@ def get_dependency_dest_location(dependency): return os.path.join(bundle_frameworks_path(), bundle_python_library()) if is_qt_framework_dependency(dependency): - libpath = os.path.join(libname+".framework", "Versions", "5") + libpath = os.path.join(libname + ".framework", "Versions", "5") return os.path.join(bundle_frameworks_path(), libpath, libname) return os.path.join(bundle_frameworks_path(), libname) @@ -266,7 +271,7 @@ def get_special_dependency_id(dependency): if is_qt_framework_dependency(dependency) and not "@rpath" in dependency: libname = os.path.basename(dependency) - return "@rpath/" + libname +".framework/Versions/5/"+libname + return "@rpath/" + libname + ".framework/Versions/5/" + libname return None @@ -283,8 +288,9 @@ def get_python_library_location(): # Let's try to find library directly prefix = sys.prefix - suffix = sysconfig.get_config_var('LDVERSION') or sysconfig.get_config_var('VERSION') - result = sys.prefix+"/lib/libpython"+suffix+".dylib" + suffix = sysconfig.get_config_var('LDVERSION') or sysconfig.get_config_var( + 'VERSION') + result = sys.prefix + "/lib/libpython" + suffix + ".dylib" if os.path.exists(result): return result @@ -313,11 +319,14 @@ def copy_python_framework(): def copy_qt_libraries(): print("--> Copying Qt libraries") - libs = ['QtCore', 'QtDBus', 'QtDesigner', 'QtGui', 'QtPrintSupport', 'QtWidgets', 'QtXml', 'QtSvg', 'QtNetwork', 'QtOpenGL'] + libs = [ + 'QtCore', 'QtDBus', 'QtDesigner', 'QtGui', 'QtPrintSupport', 'QtWidgets', + 'QtXml', 'QtSvg', 'QtNetwork', 'QtOpenGL' + ] print(" ", end="") for libname in libs: print(libname, end="") - libpath = os.path.join(libname+".framework", "Versions", "5") + libpath = os.path.join(libname + ".framework", "Versions", "5") srcfile = os.path.join(qtlibs_path(), libpath, libname) if os.path.exists(srcfile): dstdir = os.path.join(bundle_frameworks_path(), libpath) @@ -326,8 +335,11 @@ def copy_qt_libraries(): def copy_qt_plugins(): print("--> Copying Qt plugins") - plugins = ['platforms/libqcocoa.dylib', 'iconengines/libqsvgicon.dylib', - 'imageformats/libqjpeg.dylib', 'imageformats/libqsvg.dylib', 'styles/libqmacstyle.dylib'] + plugins = [ + 'platforms/libqcocoa.dylib', 'iconengines/libqsvgicon.dylib', + 'imageformats/libqjpeg.dylib', 'imageformats/libqsvg.dylib', + 'styles/libqmacstyle.dylib' + ] print(" ", end="") for name in plugins: print(name, end="") @@ -344,7 +356,7 @@ def process_dependency(dependency): """ libId = get_dependency_libId(dependency) - origLocation = get_dependency_orig_location(dependency) + origLocation = get_dependency_orig_location(dependency) destLocation = get_dependency_dest_location(dependency) print(" ------") @@ -394,7 +406,7 @@ def validate_dependencies(): """ binaries = bornagain_binaries() libraries = get_list_of_files(bundle_frameworks_path()) - file_list = binaries+libraries + file_list = binaries + libraries files_with_missed_dependencies = [] for file_name in file_list: for dependency in otool(file_name): @@ -413,9 +425,9 @@ def validate_dependencies(): def fix_apple_bundle(): - print('-'*80) + print('-' * 80) print("Fixing OS X bundle at '{0}'".format(bundle_dir())) - print('-'*80) + print('-' * 80) # # copy_python_framework() # FIXME provide automatic recognition of Qt dependency type (@rpath or hard coded) # copy_qt_libraries() # this line should be uncommented for macport based builds