Exemple #1
0
def DemoJilaOrLocal(demoName, localPath):
    """
    Looks for the demo dir in the default (jila-hosted) space. If nothing is
    found, looks in the paths specified by localpath (where it puts input 
    and output directories according to its name) 
    
    Args:
        demoName: see GetDemoInOut

        localPath: equivalent of baseDir in GetDemoInOut. Where we put the input        and Output directories for the unit test if JILA can't be found.

    Returns:
        tuple of <inputDir>,<outputDir> 
    """
    inDir, outDir = GetDemoInOut(demoName, raiseOnError=False)
    if (not pGenUtil.dirExists(inDir)):
        print("Warning: Couldn't connect to JILA's Network. Using local data.")
        # get "sanitary paths" which as OS-indepdent (in theory..)
        localPath = pGenUtil.ensureEnds(localPath, "/")
        inDir = pGenUtil.getSanitaryPath(localPath)
        outDir = pGenUtil.getSanitaryPath(localPath + "Output" + demoName +
                                          "/")
        pGenUtil.ensureDirExists(outDir)
        if (not pGenUtil.dirExists(inDir)):
            # whoops...
            raise IOError("Demo Directory {:s} not found anywhere.".\
                          format(inDir))
    return inDir, outDir
Exemple #2
0
def GetDemoInOut(demoName, baseDir=DemoDir(), raiseOnError=True):
    """
    Returns the demo input and output directories, given a path baseDir and
    name demoName. Recquires files to exist at "<baseDir><demoName>". If
    encountering an error (e.g. permissions, something isn't mounted), raises
    an error. 
    
    Args:
        demoName: The name of the demo. Assumed to be the subdir under "basedir"
        we want to use 

        baseDir: the base directory. Input and output directories are
        "<baseDir><demoName>Input/" and "<baseDir><demoName>Output/", resp.

        raiseOnError : if true, raises an error on an OS. otherwise, just
        prints a warning that something went wrong. 
    Returns:
        tuple of <inputDir>,<outputDir> 
    """
    fullBase = baseDir + demoName
    inputV = pGenUtil.getSanitaryPath(fullBase + "/Input/")
    outputV = pGenUtil.getSanitaryPath(fullBase + "/Output/")
    try:
        pGenUtil.ensureDirExists(inputV)
        pGenUtil.ensureDirExists(outputV)
    except OSError as e:
        if (raiseOnError):
            raise (e)
        print("Warning, couldn't open demo directories based in " + fullBase +
              ". Most likely, not connected to JILA network")
    return inputV, outputV
Exemple #3
0
def GetLaneTrialsMatchingName(DataDirBase, FilePattern, ext=".xls"):
    FileNames = pGenUtil.getAllFiles(DataDirBase, ext)
    Copies = []
    for f in FileNames:
        if (re.match(FilePattern, f) is not None):
            print("si")
            Copies.append(f)
    assert len(Copies) > 0, "Couldn't find any files to load"
    # now get the lanes from the files
    Lanes = [ReadFileToOverhangObj(f) for f in Copies]
    # now convert the lanes to a single object, with the means and standard
    # deviations
    return OverhangTrialObject(Lanes)
Exemple #4
0
def getDatabaseFile(fileName, extension=".hdf"):
    """
    Returns the absolute path to a previously-saved file with the given filename
    Path is *not* guaranteed to exist, if the file hasn't been saved already.
    
    Args:
        fileName: the name of the file (usually according to the "TraceData" 
        table, field "FileTimSepFor")

        extension: the recquired extension
    Returns:
        Where the file is located, an absolute path. Doesn't guarantee the file
        *does* exist, just that *if* it does, it would be there.
    """
    fileWithExt = pGenUtil.ensureEnds(fileName, extension)
    return getDatabaseFolder() + fileWithExt
Exemple #5
0
def GetImageJData(DataDirBase, ext=".xls"):
    """
    Given a base data directory, finds all files with ext in each subdirectory

    Args:
        DataDirBase: base data directory. Each subdirectory has files with 
        extension 'ext'
       
        ext: file extension
    Returns:
        ordered dictionary of <subdir:fullpaths>
    """
    Voltages = OrderedDict()
    for f in sorted(os.listdir(DataDirBase)):
        PossibleSubDir = DataDirBase + f + "/"
        if (os.path.isdir(PossibleSubDir)):
            Files = pGenUtil.getAllFiles(PossibleSubDir, ".xls")
            Voltages[f] = Files
    return Voltages
def get_force_extension_curve(in_file, **kwargs):
    """
    given an input file and meta information, returns the associated force 
    extension curve

    Args:
         input_file: file name, must have time, separation, and force
         **kwargs: see run_feather
    Returns:
         force extension curve object which FEATHER can use
    """
    if (not GenUtilities.isfile(in_file)):
        assert False, "File {:s} doesn't exist".format(in_file)
    # # POST: input file exists
    # go ahead and read it
    if (in_file.endswith(".pxp")):
        RawData = PxpLoader.LoadPxp(in_file)
        names = RawData.keys()
        # POST: file read sucessfully. should just have the one
        if (len(names) != 1):
            write_and_close("Need exactly one Force/Separation in pxp".\
                            format(in_file))
        # POST: have one. Go ahead and use FEATHER to predict the locations
        name = names[0]
        data_needed = ['time', 'sep', 'force']
        for d in data_needed:
            assert d in RawData[name], "FEATHER .pxp needs {:s} wave".format(d)
        # POST: all the data we need exist
        time, separation, force = [RawData[name][d].DataY for d in data_needed]
    elif (in_file.endswith(".mat") or in_file.endswith(".m")):
        time, separation, force = read_matlab_file_into_fec(in_file)
    elif (in_file.endswith(".csv")):
        # assume just simple columns
        data = np.loadtxt(in_file, delimiter=',', skiprows=0)
        time, separation, force = data[:, 0], data[:, 1], data[:, 2]
    else:
        assert False, "FEATHER given file name it doesn't understand"
    # POST: have time, separation, and force
    return make_fec(time, separation, force, **kwargs)
Exemple #7
0
def parse_and_run():
    parser = argparse.ArgumentParser(description='IWT of a .pxp ')
    common = dict(required=True)
    parser.add_argument('-number_of_pairs',
                        metavar='number_of_pairs',
                        type=int,
                        help='number of approach/retract pairs',
                        **common)
    parser.add_argument('-flip_forces',
                        metavar="flip_forces",
                        type=int,
                        help="if true, multiplies all the forces by -1",
                        **common)
    parser.add_argument('-number_of_bins',
                        metavar='number_of_bins',
                        type=int,
                        help='number of separation bins',
                        **common)
    parser.add_argument('-f_one_half',
                        metavar='f_one_half',
                        type=float,
                        help='force at which half the pop is folded/unfolded',
                        **common)
    parser.add_argument('-k_T',
                        metavar="k_T",
                        type=float,
                        help="Boltzmann energy, in joules",
                        required=False,
                        default=4.1e-21)
    parser.add_argument('-z_0',
                        metavar="z_0",
                        type=float,
                        help="Stage position offset from surface, in meters",
                        required=False,
                        default=0)
    parser.add_argument('-file_input',
                        metavar="file_input",
                        type=str,
                        help="path to the '.pxp' with the force, separation",
                        **common)
    parser.add_argument('-file_output',
                        metavar="file_output",
                        type=str,
                        help="path to output the associated data",
                        **common)
    vel_help = "optional manually-specified velocity (m/s). If this is" + \
               " present, then it is used to determing the velocity instead" +\
               " of fraction_velocity_fit"
    parser.add_argument('-velocity',
                        metavar="velocity",
                        type=float,
                        default=0,
                        help=vel_help,
                        required=True)
    parser.add_argument('-unfold_only',
                        metavar="unfold_only",
                        type=int,
                        default=False,
                        help="If true, data is only unfolding (default: both)",
                        required=False)
    parser.add_argument('-refold_only',
                        metavar="refold_only",
                        type=int,
                        default=False,
                        help="If true, data is only refolding (default: both)",
                        required=False)
    args = parser.parse_args()
    out_file = os.path.normpath(args.file_output)
    in_file = os.path.normpath(args.file_input)
    f_one_half = args.f_one_half
    if (not GenUtilities.isfile(in_file)):
        raise RuntimeError("File {:s} doesn't exist".format(in_file))
    # # POST: input file exists
    # go ahead and read it
    validation_function = PxpLoader.valid_fec_allow_endings
    valid_name_pattern = re.compile(
        r"""
                                     (?:b')?     # optional non-capturing bytes 
                                     (\D*)       # optional non-digits preamble
                                     (\d+)?      # optional digits (for the ID)
                                     (sep|force) # literal sep or force (req.) 
                                     (?:')?      # possible, non-capturing bytes                                      """,
        re.X | re.I)
    RawData = IWT_Util.ReadInAllFiles([in_file],
                                      Limit=1,
                                      ValidFunc=validation_function,
                                      name_pattern=valid_name_pattern)
    # POST: file read sucessfully. should just have the one
    if (not len(RawData) == 1):
        raise RuntimeError(("Need exactly one Force/Separation".\
                            format(in_file)))
    # POST: have just one. Go ahead and break it up
    iwt_kwargs = dict(
        number_of_pairs=args.number_of_pairs,
        v=args.velocity,
        flip_forces=args.flip_forces,
        kT=args.k_T,
        z_0=args.z_0,
        refold_only=(args.refold_only > 0),
        unfold_only=(args.unfold_only > 0),
    )
    LandscapeObj = WeierstrassUtil.iwt_ramping_experiment(
        RawData[0], **iwt_kwargs)
    # filter the landscape object
    LandscapeObj = WeierstrassUtil._bin_landscape(landscape_obj=LandscapeObj,
                                                  n_bins=args.number_of_bins)
    # get the distance to the transition state etc
    all_landscape = [-np.inf, np.inf]
    Obj = IWT_Util.TiltedLandscape(LandscapeObj, f_one_half_N=f_one_half)
    # write out the file we need
    extension_meters = Obj.landscape_ext_nm / 1e9
    landscape_joules = Obj.Landscape_kT * Obj.kT
    landscape_tilted_joules = Obj.Tilted_kT * Obj.kT
    data = np.array(
        (extension_meters, landscape_joules, landscape_tilted_joules))
    # done with the log file...
    np.savetxt(fname=out_file,
               delimiter=",",
               newline="\n",
               header="(C) PRH 2017\n extension(m),landscape(J),tilted(J)",
               X=data.T)