plotRegMaxSPerfVsNoise.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import os
  2. import json
  3. import numpy as np
  4. import pandas as pd
  5. from statsmodels.sandbox.descstats import sign_test
  6. from matplotlib import pyplot as plt
  7. from regmaxsn.core.matplotlibRCParams import mplPars
  8. import seaborn as sns
  9. sns.set(rc=mplPars)
  10. def regmaxsPerfVsNoise(parFile, anisoThresh):
  11. plt.ion()
  12. with open(parFile) as fle:
  13. parsList = json.load(fle)
  14. transErrs = pd.DataFrame()
  15. perfDF = pd.DataFrame()
  16. for parInd, par in enumerate(parsList):
  17. refSWC = par['refSWC']
  18. resFile = par['resFile']
  19. testSWC = par["testSWC"]
  20. if testSWC.find("NoiseStd") < 0:
  21. print("{} has testSWC {} without noise.Ignoring it!".format(parFile, testSWC))
  22. else:
  23. NoiseStdStrInd = testSWC.find("NoiseStd")
  24. RandTransStdInd = testSWC.find("RandTrans")
  25. noiseStd = int(testSWC[NoiseStdStrInd + 8: RandTransStdInd])
  26. origJSON = '{}{}.json'.format(testSWC[:NoiseStdStrInd], testSWC[RandTransStdInd:-4])
  27. if os.path.isfile(origJSON):
  28. with open(origJSON, 'r') as fle:
  29. pars = json.load(fle)
  30. scales = np.array(pars['scale'])
  31. else:
  32. raise (IOError('File not found: {}'.format(origJSON)))
  33. scalesOrdered = np.sort(scales)
  34. scalesRelative = np.mean([scalesOrdered[0] / scalesOrdered[1],
  35. scalesOrdered[0] / scalesOrdered[2],
  36. scalesOrdered[1] / scalesOrdered[2]])
  37. testName = resFile[:-4]
  38. thresh = par['gridSizes'][-1]
  39. print('Doing ' + repr((refSWC, resFile)))
  40. refPts = np.loadtxt(refSWC)[:, 2:5]
  41. testPtsFull = np.loadtxt(resFile)
  42. testPts = testPtsFull[:, 2:5]
  43. if refPts.shape[0] != testPts.shape[0]:
  44. print('Number of points do not match for ' + refSWC + 'and' + resFile)
  45. continue
  46. ptDiff = np.linalg.norm(refPts - testPts, axis=1)
  47. transErrs = transErrs.append(pd.DataFrame({'Pairwise Distance in $\mu$m': ptDiff,
  48. 'Exp. Name': testName,
  49. "Node ID": testPtsFull[:, 0],
  50. "Noise Std": noiseStd}),
  51. ignore_index=True)
  52. t, p = sign_test(ptDiff, thresh)
  53. oneSidedP = 0.5 * p
  54. signCloserThanSmallestVoxelSize = t < 0 and oneSidedP < 0.05
  55. notSignFartherThanSVS = not (t > 0 and oneSidedP < 0.01)
  56. tempDict = {"Job Number": parInd, "resFile": resFile, "refSWC": refSWC,
  57. "t Statistic": t, "One Sided p value": oneSidedP,
  58. "Pairwise distance significantly smaller than smallest voxel size":
  59. signCloserThanSmallestVoxelSize,
  60. "Pairwise distance not significantly larger than smallest voxel size":
  61. notSignFartherThanSVS,
  62. "Noise Std": noiseStd,
  63. "Level of Anisotropic scaling": scalesRelative}
  64. perfDF = perfDF.append(tempDict, ignore_index=True)
  65. perfDFAnisoFiltered = perfDF.loc[perfDF["Level of Anisotropic scaling"] > anisoThresh, :]
  66. perfNoiseDF = perfDFAnisoFiltered[["Noise Std", "Pairwise distance significantly smaller than smallest voxel size"]]
  67. perfVsNoise = perfNoiseDF.groupby("Noise Std").agg(lambda x: 100 * x.sum() / float(x.shape[0]))
  68. worstPerfNoiseDF = perfDFAnisoFiltered[["Noise Std", "Pairwise distance not significantly larger than smallest voxel size"]]
  69. worstPerfVsNoise = worstPerfNoiseDF.groupby("Noise Std").agg(lambda x: 100 * x.sum() / float(x.shape[0]))
  70. fig, ax = plt.subplots(figsize=(14, 11.2))
  71. # ax.bar(perfVsNoise.index.values, perfVsNoise.values, width=1.5)
  72. ax.plot(perfVsNoise.index.values, perfVsNoise.values, 'r-o')
  73. # ax.plot(worstPerfVsNoise.index.values, worstPerfVsNoise.values, 'b-s',
  74. # label="\% of tests with significant number \nof pairwise distances not greater than \nlowest voxel size")
  75. ax.set_ylabel("\% of tests with significant number \nof pairwise distances smaller than \nlowest voxel size")
  76. ax.set_xticks(perfVsNoise.index.values)
  77. ax.set_xlabel("Noise Standard deviation ($\mu$ m)")
  78. ax.legend(loc='best')
  79. ax.set_ylim(-10, 110)
  80. fig.tight_layout()
  81. return fig
  82. # ----------------------------------------------------------------------------------------------------------------------
  83. if __name__ == '__main__':
  84. import sys
  85. assert len(sys.argv) == 3, 'Improper usage! Please use as \n' \
  86. '\'python {} <parFile> <minimum allowed level of anisotropic scaling>\''.format(sys.argv[1])
  87. parFile = sys.argv[1]
  88. anisoThesh = float(sys.argv[2])
  89. fig = regmaxsPerfVsNoise(parFile, anisoThesh)
  90. raw_input("Press any key to close the figure and exit....")