#!/usr/bin/env pyXplor

#read in AFM map in .txt format, add Gaussian noise (with Gaussian width 10% of
# the pixel height), and write it back out.
# First line of file is read as header.
# Usage: pyXplor addNoise_uniform.py -noisePercent 0.10 -xscale 2 -yscale 2 -zscale 2 afm_file.txt

noisePercent=0.1
xscale=1
yscale=1
zscale=1

opts,args = xplor.parseArguments(("noisePercent:1",
                                  "xscale:1",
                                  "yscale:1",
                                  "zscale:1",)
                                  ,
#                                 minArgs=1,
#                                 maxArgs=1,
                                 cmdline=
  "[options] <.txt AFM height data file>",
                                   description="""
  Add noise to a .txt ADM height data file. The script creates a new file
  whose name is that of the input file, with a ".out" suffix appended. X, Y or
  Z values can be optionally scaled by specifying approprirate options.
                                   
""",
                                 usageString=f"""
Options are zero or more of::

  -noisePercent <val>        - noise to be added, as a percent of the pixel's 
                               (scaled) height value. Default: {noisePercent}

  -xscale <val>              - value to scale x-values by. Default: {xscale}
  -yscale <val>              - value to scale y-values by. Default: {yscale}
  -zscale <val>              - value to scale z-values by. Default: {zscale}

"""
                                 )


for opt in opts:
    if opt[0]=="noisePercent":
        noisePercent = float(opt[1])
        pass
    if opt[0]=="xscale":
        xscale = float(opt[1])
        pass
    if opt[0]=="yscale":
        yscale = float(opt[1])
        pass
    if opt[0]=="zscale":
        zscale = float(opt[1])
        pass
    pass



import trace
trace.suspend()
mapFile=args[0]
lines=open(mapFile).readlines()
header=lines[0]
xyzs=[line.split() for line in lines][1:]

ofile=open(mapFile+".out","w")

ofile.write(header)
for x,y,z in xyzs:
    x = xscale*float(x)
    y = yscale*float(y)
    z = zscale*float(z)
    w = noisePercent*z
    import random
    #g = random.gauss(0,w)
    g = random.uniform(-w,w)
    #print(z)
    if z > 0:
      z += g
    #print(g,z)
    ofile.write(f"{x:.2f} {y:.2f} {z:.2f}\n")
    pass
