def tstTravelFindHoles(
    tstFileName, phiFileName, debugOut=False, borderSize=2, nearbyDistance=4.):
  '''if debugout is set, additional files are created.
  bordersize can change the amount of extra space around the protein.
  nearbydistance changes the distance that nearby residues are gathered from.'''
  print "reading tst and phi files"
  tstD = tstdata.tstData(
      tstFileName, necessaryKeys=tstdata.tstData.necessaryKeysForHoles)
  phiData = phi(phiFileName)  # read in the phimap if possible
  gridSize = 1.0 / phiData.scale  # needed later
  numberHandles = tstD.countHandles()
  print "there are ", numberHandles, " holes in this structure"
  print "running travel depth now"
  phiTravelDepthGrid, phiTravelDepthData, meshData = tstTravelDepthMeshRun(
      tstD, phiData, tstFileName, borderSize=borderSize, threshold="auto")
  del phiData, phiTravelDepthGrid, phiTravelDepthData
  #not needed, reclaim memory
  print "calculating travel out distance"
  meshData.calculateTravelDistance("surfout", [3], [0, 2])
  print "finding holes"
  loopTrisSave, loopPointsSave, regLoopTris, regLoopPts, pointNeighbors, \
      pointNeighborsNodes, outsidePoints, outsidePointsNodes, possHoleStarts = \
      tstTopology.fillInHolesAndGrow(
          tstD.dict['TRIANGLE_POINT'], tstD.dict['POINT_TRIANGLE'],
          tstD.dict['POINT_XYZ'], tstD.dict['NORM_XYZ'], numberHandles,
          tstFileName, debugOut, meshData, "surfout")
  if debugOut:
    tstdebug.debugTriangleList(
        regLoopTris, tstD.dict['TRIANGLE_POINT'], tstD.dict['POINT_XYZ'],
        tstFileName + ".regular.loops.py")
  tstDPointXYZ = tstD.dict['POINT_XYZ']  # save for later
  tstDPdbRecord = tstD.dict['PDB_RECORD']  # save for later
  del tstD  # rest of tstD isn't needed, so free memory
  #output the possible places where HOLE could start... centers of regular plugs
  print "writing output files"
  paths.outputNodesText(possHoleStarts, tstFileName + ".HOLE.start.txt")
  pathsList = meshData.getPaths(
      "surfout", pointNeighbors, outsidePoints, possHoleStarts)
  del meshData  # deletes everything that has no other refs (from paths)
  #print len(pointNeighbors), len(outsidePoints), len(possHoleStarts),
  #print len(pathsList)
  allPoints, outsidePts = [], []
  for point in pointNeighborsNodes.keys():
    allPoints.append(point.pathXyz)
  for point in outsidePointsNodes:
    outsidePts.append(point.pathXyz)
  tstdebug.pointDebug(allPoints, filename=tstFileName+".tree.py")
  tstdebug.pointDebug(
      outsidePts, filename=tstFileName+".outside.py", mainColor=(.9, .1, .1),
      radius=0.55)
  #tstdebug.debugSetGridSpheres(
  #     pointNeighbors.keys(),, gridSize, tstFileName+".tree.radius.py",
  #     radius=True, mainColor=(0.01, 0.9, 0.05))
  #testing new output of tree with radius
  foundPaths = 0
  pathFile = string.replace(tstFileName, ".nocav.tst", ".py")
  #very very specific... probably bad but nice...
  #can always rerun standalone later.
  knownPathExists = os.path.isfile(pathFile)
  logName = tstFileName + ".findholes.log"
  logFile = open(logName, 'w')
  logFile.write(
      "number endNumOne endNumTwo plugs stepLength pathLength pathMinRadius " +
      "pathMaxInsideRadius endMinOne endMinTwo minimaCount travelDepthMax " +
      "windingMetric avgTheta ")
  if knownPathExists:
    logFile.write("pRMSD coverage span wrmsd less1 lessrad radiicomp")
  logFile.write("\n")
  if knownPathExists:
    bestStats = ["err", "err", "err", "err", "err", "err", "err"]
    bestStatsPaths = [0, 0, 0, 0, 0, 0, 0]
  sortedByMinRadiusPaths = []
  for pathIndex, (outsideOne, outsideTwo, plugs, nodePath) in enumerate(
      pathsList):
    pointPath, spheres = [], []
    for node in nodePath:
      pointPath.append(list(node.pathXyz))
      spheres.append(list(node.pathXyz))
      pointRadius = node.distances["surfout"]  # add 'radius' info
      if not pointRadius or pointRadius == 0.:
        pointRadius = .000000001  # very small number, on surface
      pointPath[-1].insert(0, pointRadius)
      spheres[-1].append(pointRadius)
    minRad = paths.pathMinRadius(pointPath)
    newTuple = (
        minRad, outsideOne, outsideTwo, plugs, nodePath, pointPath, spheres)
    #insertion sort into new list
    position = 0
    while position < len(sortedByMinRadiusPaths) and \
        sortedByMinRadiusPaths[position][0] > minRad:
      #only if list can handle it and already inserted are bigger
      position += 1
    sortedByMinRadiusPaths.insert(position, newTuple)
  print "output files for individual paths"
  for pathIndex, newTuple in enumerate(sortedByMinRadiusPaths):
    (minRad, outsideOne, outsideTwo, plugs, nodePath, pointPath, spheres) = \
        newTuple  # unpack the tuple into the various data
    throughTris, throughPts = paths.checkPath(
        pointPath, loopPointsSave, tstDPointXYZ)
    if throughTris:  # it worked... make some more debugging output
      foundPaths += 1
      outName = tstFileName + "." + str(foundPaths)
      if debugOut and throughTris:
        tstdebug.debugTrianglesNotOrig(
            throughTris, tstDPointXYZ, outName+".through.loop.py",
            ptList=throughPts)
      #always do these 2
      tstdebug.debugSetGridSpheres(
          pointPath, gridSize, outName + ".pore.py", radius=True,
          mainColor=(0.01, 0.9, 0.05))
      tstdebug.debugSetGridSpheres(
          pointPath, gridSize, outName + ".path.py", mainColor=(.01, 0.95, 0.9))
      #mesh.meshFromSpheres(spheres, 0.5, outName + ".points.py")
      paths.outputRadiiTxt(pointPath, outName + ".radii.txt")
      paths.outputNearbyResidues(
          pointPath, outName, tstDPdbRecord, nearbyDistance)
      pathLen = paths.pathLength(pointPath)
      minimaCount = paths.pathMinimaCount(pointPath)
      maxRad, endMinOne, endMinTwo = paths.insideTwoMinimaRadiusMax(pointPath)
      travelDepthMax = paths.pathMaxDistance(nodePath, 'traveldepth')
      windingMetric = paths.computeWindingMetric(pointPath)
      thetas, avgTheta = paths.averageTheta(pointPath)
      #print endMinOne, endMinTwo, minimaCount, travelDepthMax, windingMetric,
      #print avgTheta
      #attempt to do pRMSD if possible...
      prmsd, coverage, span, wrmsd, less1, lessrad, radiicomp = \
          "err", "err", "err", "err", "err", "err", "err"
      if knownPathExists:
        try:
          sourcePath, sourceRadii = [], []
          for pathPt in pointPath:
            sourcePath.append(pathPt[1:4])
            sourceRadii.append(pathPt[0])
          prmsd, coverage, span, wrmsd, less1, lessrad, radiicomp = \
              comparePathsManyMetrics(False, pathFile, sourcePath, sourceRadii)
          if bestStats[0] == 'err' or bestStats[0] > prmsd:
            bestStats[0] = prmsd
            bestStatsPaths[0] = foundPaths
          if bestStats[1] == 'err' or bestStats[1] < coverage:
            bestStats[1] = coverage
            bestStatsPaths[1] = foundPaths
          if bestStats[2] == 'err' or bestStats[2] < span:
            bestStats[2] = span
            bestStatsPaths[2] = foundPaths
          if bestStats[3] == 'err' or bestStats[3] > wrmsd:
            bestStats[3] = wrmsd
            bestStatsPaths[3] = foundPaths
          if bestStats[4] == 'err' or bestStats[4] < less1:
            bestStats[4] = less1
            bestStatsPaths[4] = foundPaths
          if bestStats[5] == 'err' or bestStats[5] < lessrad:
            bestStats[5] = lessrad
            bestStatsPaths[5] = foundPaths
          if bestStats[6] == 'err' or bestStats[6] < radiicomp:
            bestStats[6] = radiicomp
            bestStatsPaths[6] = foundPaths
        except (IOError, TypeError):
          #if there is no known path  file, this should be the error
          pass
      #now output data
      logFile.write(str(foundPaths) + " ")
      logFile.write(str(outsideOne) + " ")
      logFile.write(str(outsideTwo) + " ")
      logFile.write(str(plugs) + " ")
      logFile.write(str(len(pointPath)) + " ")
      logFile.write(str(pathLen) + " ")
      logFile.write(str(minRad) + " ")
      logFile.write(str(maxRad) + " ")
      logFile.write(str(endMinOne) + " ")
      logFile.write(str(endMinTwo) + " ")
      logFile.write(str(minimaCount) + " ")
      logFile.write(str(travelDepthMax) + " ")
      logFile.write(str(windingMetric) + " ")
      logFile.write(str(avgTheta) + " ")
      if knownPathExists:
        logFile.write(str(prmsd) + " ")
        logFile.write(str(coverage) + " ")
        logFile.write(str(span) + " ")
        logFile.write(str(wrmsd) + " ")
        logFile.write(str(less1) + " ")
        logFile.write(str(lessrad) + " ")
        logFile.write(str(radiicomp) + " ")
      logFile.write("\n")  # that's all
  logFile.close()
  if knownPathExists:  # output bestStats and bestStatsPaths
    bestName = tstFileName + ".known.best.txt"
    bestFile = open(bestName, 'w')
    bestFile.write("pRMSD coverage span wrmsd less1 lessrad radiicomp ")
    bestFile.write("pRMSD# coverage# span# wrmsd# less1# lessrad# radiicomp#\n")
    for stat in bestStats:
      bestFile.write(str(stat) + " ")
    for stat in bestStatsPaths:
      bestFile.write(str(stat) + " ")
    bestFile.write("\n")
    bestFile.close()
  print "done with chunnel"
def readOutputRadiiTxt(original, txtfile):
    """outputs a txtfile of distance vs radius"""
    origPath = comparePaths.readCGOPathWithRadius(original)  # 0 is radius
    outputRadiiTxt(origPath, txtfile)