def main():
    parser = argparse.ArgumentParser()
    parser_io = parser.add_argument_group(description = "==== I/O parameters ====")
    parser_io.add_argument("-i","--infile",required = True)
    parser_io.add_argument("-o","--outfile",required = True)
    parser_io.add_argument("-v","--verbose",default=False,action="store_true")

    parser = gc.AddDilutionParameters(parser)
    parser = gc.AddLatticeParameters(parser)
    
    args = parser.parse_args()

    g           = gc.LoadGM(**vars(args))
    dlist       = gc.getDilutionList(**vars(args))
    axis1,axis2 = gc.getInoculumAxes(**vars(args)) # either (n,x) or [ (n1,n2) if args.AbsoluteCoordinates == True ]

    gm1 = g.growthmatrix[:,:,0]
    gm2 = g.growthmatrix[:,:,1]

    for dilution in dlist:
        if args.verbose:
            sys.stderr.write("# computing single step dynamics for D = {:e}\n".format(dilution))
            
        fp = open(args.outfile + "_D{:.3e}".format(dilution),"w")
        for i,a1 in enumerate(axis1):
            for j,a2 in enumerate(axis2):
                next1 = gc.SeedingAverage(gm1, gc.TransformInoculum([a1,a2],args.AbsoluteCoordinates,True)) * dilution
                next2 = gc.SeedingAverage(gm2, gc.TransformInoculum([a1,a2],args.AbsoluteCoordinates,True)) * dilution
                fp.write('{} {} {} {}\n'.format(a1,a2,*gc.TransformInoculum([next1,next2],True,args.AbsoluteCoordinates)))
            fp.write('\n')
        fp.close()
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--infile", default=None, required=True)
    parser.add_argument("-o", "--outfile", default=None)
    parser.add_argument("-q", "--quiet", default=False, action="store_true")
    args = parser.parse_args()

    g = gc.LoadGM(**vars(args))

    if not args.quiet:
        # output of all parameters
        # default to stderr
        fp_params = sys.stderr

        fp_params.write(
            "==================================================================\n"
        )
        fp_params.write("  growthmatrix file : {}\n".format(args.infile))
        fp_params.write("  dynamics type :     {}\n".format(type(g).__name__))
        fp_params.write("  GMshape :           {}\n".format(
            np.shape(g.growthmatrix)))
        fp_params.write("  GMgridX :           {}\n".format(
            g.growthmatrixgrid[0]))
        fp_params.write("  GMgridY :           {}\n".format(
            g.growthmatrixgrid[1]))
        fp_params.write(
            "==================================================================\n"
        )
        fp_params.write("\n")

        fp_params.write(str(g))
        fp_params.write("\n")
        fp_params.write(
            "==================================================================\n"
        )
        fp_params.write("\n")
        fp_params.write(
            "  command-line parameters to generate this dynamics:\n")

        generateString = "   -G '" + type(g).__name__[14:] + "'"
        # default parameters for strains
        excludeParameters = [
            'growthrates', 'yieldfactors', 'substrateconcentration',
            'mixingtime'
        ]
        # I/O parameters from computing growthmatrix
        excludeParameters += ['infile', 'outfile', 'verbose']
        # other parameters from computing GrowthMatrix
        excludeParameters += ['GrowthDynamics', 'maxsize', 'step']

        if 'growthrates' in g._GrowthDynamics__kwargs_for_pickle.keys():
            generateString += " -a " + array_to_str(g.growthrates)
        if 'yieldfactors' in g._GrowthDynamics__kwargs_for_pickle.keys():
            generateString += " -y " + array_to_str(g.yieldfactors)
        if 'substrateconcentration' in g._GrowthDynamics__kwargs_for_pickle.keys(
        ):
            generateString += " -S " + str(g.env.substrate)
        if 'mixingtime' in g._GrowthDynamics__kwargs_for_pickle.keys():
            generateString += " -T " + str(g.env.mixingtime)

        additionalParameters = ""
        for key, values in g._GrowthDynamics__kwargs_for_pickle.items():
            if not key in excludeParameters:
                if isinstance(values, (list, np.ndarray)):
                    additionalParameters += " {} ".format(key) + array_to_str(
                        values)
                else:
                    additionalParameters += " {} {}".format(key, values)
        if len(additionalParameters) > 0:
            generateString += " -P " + additionalParameters

        generateString += "\n"

        fp_params.write(generateString)
        fp_params.write("\n")
        fp_params.write(
            "==================================================================\n"
        )

    # output of all values
    if not args.outfile is None:
        try:
            fp_values = open(args.outfile, "w")
        except:
            raise IOError("could not open file '{}' to write.".format(
                args.outfile))
    else:
        fp_values = sys.stdout

    if isinstance(g.growthmatrixgrid, int):
        # old implementation, still here for these old growth matrices
        for x in range(g.growthmatrixgrid):
            for y in range(g.growthmatrixgrid):
                fp_values.write('{} {} {} {}\n'.format(x, y,
                                                       g.growthmatrix[x, y, 0],
                                                       g.growthmatrix[x, y,
                                                                      1]))
            fp_values.write('\n')
    elif isinstance(g.growthmatrixgrid, (tuple, list, np.ndarray)):
        # growthmatrixgrid is stored in pickle file
        for i, x in enumerate(g.growthmatrixgrid[0]):
            for j, y in enumerate(g.growthmatrixgrid[1]):
                fp_values.write('{} {} {} {}\n'.format(x, y,
                                                       g.growthmatrix[i, j, 0],
                                                       g.growthmatrix[i, j,
                                                                      1]))
            fp_values.write('\n')
    else:
        # should not happen
        raise NotImplementedError

    if not args.outfile is None:
        fp_values.close()
Exemple #3
0
def main():
    parser = argparse.ArgumentParser()
    parser_io = parser.add_argument_group(
        description="==== I/O parameters ====")
    parser_io.add_argument("-i", "--infile", required=True)
    parser_io.add_argument("-o", "--outfile", required=True)
    parser_io.add_argument("-v",
                           "--verbose",
                           default=False,
                           action="store_true")

    parser = gc.AddDilutionParameters(parser)

    parser_lattice = parser.add_argument_group(
        description="==== Lattice parameters ====")
    parser_lattice.add_argument(
        "-A",
        "--AbsoluteCoordinates",
        default=False,
        action="store_true",
        help="Use (n1,n2) instead of (n,x) as coordinates")
    parser_lattice_startingconditions = parser_lattice.add_mutually_exclusive_group(
    )
    parser_lattice_startingconditions.add_argument("-N",
                                                   "--maxInoculum",
                                                   type=float,
                                                   default=40)
    parser_lattice_startingconditions.add_argument("-I",
                                                   "--initialcoordinatesfile",
                                                   default=None)
    parser_lattice.add_argument("-n", "--stepInoculum", type=float, default=2)
    parser_lattice.add_argument("-x",
                                "--stepFraction",
                                type=float,
                                default=.05)
    parser_lattice.add_argument("-l",
                                "--trajectorylength",
                                type=int,
                                default=20)

    args = parser.parse_args()

    g = gc.LoadGM(**vars(args))
    dlist = gc.getDilutionList(**vars(args))

    if args.initialcoordinatesfile is None:
        axis1, axis2 = gc.getInoculumAxes(**vars(args))
        initialcoordinates = list(itertools.product(axis1, axis2))
    else:
        try:
            fp_coords = open(args.initialcoordinatesfile)
        except:
            raise IOError(
                "could not open file '{}' to load coordinates".format(
                    args.initialcoordinatesfile))
        initialcoordinates = list()
        for line in fp_coords.readlines():
            try:
                values = np.array(line.split(), dtype=np.float)
                if len(values) >= 2:
                    initialcoordinates.append(
                        gc.TransformInoculum(values[:2],
                                             args.AbsoluteCoordinates,
                                             args.AbsoluteCoordinates))
            except:
                continue
            fp_coords.close()

    mx, my = g.growthmatrixgrid
    gm1 = g.growthmatrix[:, :, 0]
    gm2 = g.growthmatrix[:, :, 1]

    if args.verbose:
        sys.stderr.write(str(g))

    for dilution in dlist:
        if args.verbose:
            sys.stderr.write(
                "# computing trajectories for D = {:e}\n".format(dilution))
        fp = open(args.outfile + "_D{:.3e}".format(dilution), "w")
        for ic1, ic2 in initialcoordinates:
            n1, n2 = gc.TransformInoculum([ic1, ic2], args.AbsoluteCoordinates,
                                          True)
            fp.write("{} {}\n".format(*gc.TransformInoculum(
                [n1, n2], True, args.AbsoluteCoordinates)))
            for i in range(args.trajectorylength):
                next1 = gc.SeedingAverage(gm1, [n1, n2]) * dilution
                next2 = gc.SeedingAverage(gm2, [n1, n2]) * dilution
                n1, n2 = next1, next2
                fp.write("{} {}\n".format(*gc.TransformInoculum(
                    [n1, n2], True, args.AbsoluteCoordinates)))
                if (n1 == 0) and (n2 == 0):
                    break
            fp.write("\n")
        fp.close()
Exemple #4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-i",
        "--infile",
        help="Pickle-file with stored parameters and growthmatrix")

    parser = gc.AddDilutionParameters(parser)

    parser_algorithm = parser.add_argument_group(
        description="==== Algorithm parameters ====")
    parser_algorithm.add_argument(
        "-N",
        "--newtonraphson",
        action="store_true",
        default=False,
        help=
        "Plain iteration of dynamics or try to use NR to estimate fixed point")
    parser_algorithm.add_argument(
        "-p",
        "--precision",
        type=float,
        default=1e-20,
        help=
        "relative precision as premature stopping condition, computed as sum( (dn/n)^2 ) [default: 1e-20]"
    )
    parser_algorithm.add_argument(
        "-M",
        "--maxiterations",
        type=int,
        default=None,
        help=
        "maximum number of iterations [default: None, iterate until precision is reached]"
    )
    parser_algorithm.add_argument(
        "-A",
        "--alpha",
        type=float,
        default=1.,
        help="convergence parameter for NR [default: 1.0]")
    parser_algorithm.add_argument(
        "-c",
        "--cutoff",
        type=float,
        default=1e-100,
        help="cutoff probabilities lower than this value [default: 1e-100]")

    parser_general = parser.add_argument_group(
        description="==== General and I/O parameters ====")
    parser_general.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        default=False,
        help="output current values every iteration step")
    parser_general.add_argument(
        "-V",
        "--printeigenvectors",
        default=False,
        action="store_true",
        help="print eigenvectors of linearized iteration map")
    parser_general.add_argument("-I",
                                "--initialconditions",
                                default=None,
                                nargs="*",
                                help="Override initial conditions when set")
    parser_general.add_argument(
        "-S",
        "--stayonfixedpoint",
        default=False,
        action="store_true",
        help="Keep fixed point from previous dilution as initial conditions")
    parser_general.add_argument(
        "-C",
        "--complexOutput",
        default=False,
        action="store_true",
        help=
        "Print real and imaginary parts of eigenvalues (and eigenvectors) [default: only real]"
    )
    args = parser.parse_args()

    g = gc.LoadGM(**vars(args))
    dlist = gc.getDilutionList(**vars(args))

    gm1 = g.growthmatrix[:, :, 0]
    gm2 = g.growthmatrix[:, :, 1]
    mx, my = g.growthmatrixgrid

    for i, dilution in enumerate(dlist):

        if args.initialconditions is None:
            # initial condition are the respective (approximated) fixed points on the axis
            g.setDilution(dilution)
            n = g.getSingleStrainFixedPointsApproximate()
        elif (not args.stayonfixedpoint) or (i == 0):
            n = np.array(args.initialconditions, dtype=float)
            assert len(n) == g.numstrains
        else:
            # n is already defined from previous dilution
            pass

        dn = n  # increase in one step
        j = np.zeros((2, 2))  # jacobian
        stepcount = 0  # number of steps for debugging

        while np.sum((dn[n > 0] / n[n > 0])**2) > args.precision:
            if args.verbose:
                sys.stderr.write("{:4d} {:13.6e} {:13.6e}\n".format(
                    stepcount, n[0], n[1]))

            # probabilities for seeding new droplets, assumed to be poissonian
            px, dpx = gc.PoissonSeedingVectors(mx, [n[0]],
                                               cutoff=args.cutoff,
                                               diff=True)
            py, dpy = gc.PoissonSeedingVectors(my, [n[1]],
                                               cutoff=args.cutoff,
                                               diff=True)

            # construct iteration function for growth and dilution
            # by weighting growth with the probability of how droplets are seeded
            growth1 = np.dot(py[0], np.dot(px[0], gm1 * dilution))
            growth2 = np.dot(py[0], np.dot(px[0], gm2 * dilution))
            fn = np.array([growth1, growth2]) - n

            if args.newtonraphson:
                # NR iterations

                # get jacobian of dynamics
                j[0, 0] = np.dot(py[0], np.dot(dpx[0], gm1 * dilution)) - 1.
                j[0, 1] = np.dot(dpy[0], np.dot(px[0], gm1 * dilution))
                j[1, 0] = np.dot(py[0], np.dot(dpx[0], gm2 * dilution))
                j[1, 1] = np.dot(dpy[0], np.dot(px[0], gm2 * dilution)) - 1.

                # calculate step in NR iteration
                dn = -args.alpha * np.dot(np.linalg.inv(j), fn)

            else:
                # simple iteration of the function, hoping it converges at some point
                dn = fn

            # apply changes
            n += dn
            n[n < 0] = 0

            if not args.maxiterations is None:
                if stepcount > args.maxiterations:
                    break
            stepcount += 1

        # stability of fixed point is checked with jacobian
        px, dpx = gc.PoissonSeedingVectors(mx, [n[0]],
                                           cutoff=args.cutoff,
                                           diff=True)
        py, dpy = gc.PoissonSeedingVectors(my, [n[1]],
                                           cutoff=args.cutoff,
                                           diff=True)

        j[0, 0] = np.dot(py[0], np.dot(dpx[0], gm1 * dilution))
        j[0, 1] = np.dot(dpy[0], np.dot(px[0], gm1 * dilution))
        j[1, 0] = np.dot(py[0], np.dot(dpx[0], gm2 * dilution))
        j[1, 1] = np.dot(dpy[0], np.dot(px[0], gm2 * dilution))

        w, v = np.linalg.eig(j)

        # final output

        outputstring = "{:13.6e} {:8.6f} {:8.6f} {:13.6e} {:13.6e} {:4d}".format(
            dilution, g.growthrates[1] / g.growthrates[0],
            g.yieldfactors[1] / g.yieldfactors[0], n[0], n[1], stepcount)
        outputstring += " {:13.6e} {:13.6e}".format(re(w[0]), re(w[1]))
        if args.complexOutput:
            # have yet to find complex eigenvalues (NB: they exist for antibiotics dynamics)
            outputstring += " {:13.6e} {:13.6e}".format(im(w[0]), im(w[1]))

        if args.printeigenvectors:
            outputstring += " {:13.6e} {:13.6e} {:13.6e} {:13.6e}".format(
                re(v[0, 0]), re(v[1, 0]), re(v[0, 1]), re(v[1, 1]))
            if args.complexOutput:
                outputstring += " {:13.6e} {:13.6e} {:13.6e} {:13.6e}".format(
                    im(v[0][0]), im(v[0][1]), im(v[1][0]), im(v[1][1]))
        sys.stdout.write(outputstring + "\n")
Exemple #5
0
def main():
    parser = argparse.ArgumentParser()
    parser_io = parser.add_argument_group(
        description="==== I/O parameters ====")
    parser_io.add_argument("-i", "--infile", required=True)
    parser_io.add_argument("-o", "--baseoutfilename", default="out")
    parser_io.add_argument("-v",
                           "--verbose",
                           action="store_true",
                           default=False)
    parser_io.add_argument("-S",
                           "--OutputSinglestrainNullclines",
                           action="store_true",
                           default=False)

    parser = gc.AddLatticeParameters(parser)
    parser = gc.AddDilutionParameters(parser)

    args = parser.parse_args()

    g = gc.LoadGM(**vars(args))
    dlist = gc.getDilutionList(**vars(args))

    # get new axes, which depends on parameters above (in lattice parameter group)
    axis1, axis2 = gc.getInoculumAxes(
        **vars(args)
    )  # either (n,x) or [ (n1,n2) if args.AbsoluteCoordinates == True ]
    shape = (len(axis1), len(axis2))

    # loaded from pickle file
    m1, m2 = g.growthmatrixgrid
    gm1 = g.growthmatrix[:, :, 0]
    gm2 = g.growthmatrix[:, :, 1]

    # matrices to store averages
    g1 = np.zeros(shape, dtype=np.float64)  # avg'd growth strain 1
    g2 = np.zeros(shape, dtype=np.float64)  # avg'd growth strain 2
    rr1 = np.zeros(shape, dtype=np.float64)  # avg'd ratio of strains at end
    r1 = np.zeros(shape,
                  dtype=np.float64)  # avg'd ratio of strains at beginning
    sn1 = np.zeros(
        shape,
        dtype=np.float64)  # number of cells of strain 1 in new matrix shape
    sn2 = np.zeros(
        shape,
        dtype=np.float64)  # number of cells of strain 1 in new matrix shape

    # get all averages and store them in the appropriate matrices
    for i, a1 in enumerate(axis1):
        for j, a2 in enumerate(axis2):
            sn1[i, j], sn2[i, j] = gc.TransformInoculum(
                [a1, a2], inabs=args.AbsoluteCoordinates, outabs=True)
            g1[i, j] = gc.SeedingAverage(gm1, [sn1[i, j], sn2[i, j]])
            g2[i, j] = gc.SeedingAverage(gm2, [sn1[i, j], sn2[i, j]])

    rr1[g1 + g2 > 0] = (g1[g1 + g2 > 0]) / ((g1 + g2)[g1 + g2 > 0])
    r1[sn1 + sn2 > 0] = (sn1[sn1 + sn2 > 0]) / ((sn1 + sn2)[sn1 + sn2 > 0])

    # output
    if args.verbose:
        sys.stdout.write('\n computing nullcline for fraction of strains\n')
    cont_xx = measure.find_contours(rr1 - r1, 0)
    write_contours_to_file(cont_xx, args.baseoutfilename + '_X', axis1, axis2)

    for dilution in dlist:
        if args.verbose:
            sys.stdout.write(
                ' computing nullclines for dilution D = {:.4e}\n'.format(
                    dilution))
        cont_nn = measure.find_contours((g1 + g2) * dilution - sn1 - sn2, 0)
        write_contours_to_file(
            cont_nn, args.baseoutfilename + '_N_D{:.3e}'.format(dilution),
            axis1, axis2)
        if args.OutputSinglestrainNullclines:
            cont_n1 = measure.find_contours(g1 * dilution - sn1, 0)
            cont_n2 = measure.find_contours(g2 * dilution - sn2, 0)
            write_contours_to_file(
                cont_n1, args.baseoutfilename + '_1_D{:.3e}'.format(dilution),
                axis1, axis2)
            write_contours_to_file(
                cont_n2, args.baseoutfilename + '_2_D{:.3e}'.format(dilution),
                axis1, axis2)
def main():
    parser = argparse.ArgumentParser()
    parser_io = parser.add_argument_group(description = "==== I/O ====")
    parser_io.add_argument("-i","--infile",required=True)
    parser_io.add_argument("-o","--baseoutfilename",default=None)
    parser_io.add_argument("-v","--verbose",action="store_true",default=False)
    parser_io.add_argument("-X","--write_xi_file",action="store_true",default=False)

    parser = gc.AddLatticeParameters(parser)
    
    args = parser.parse_args()

    g = gc.LoadGM(**vars(args))

    a1_list,a2_list = gc.getInoculumAxes(**vars(args))

    # extract data from pickle object
    m1,m2 = g.growthmatrixgrid
    gm1   = g.growthmatrix[:,:,0]
    gm2   = g.growthmatrix[:,:,1]

    mm1   = np.repeat([m1],len(m2),axis=0).T
    mm2   = np.repeat([m2],len(m1),axis=0)

    alpha = np.mean(g.growthrates)
    da    = g.growthrates[0]/alpha - 1.


    # wd = within-deme
    # compute quantities at first for each deme separately
    wd_N_fin             = np.zeros(gm1.shape,dtype=np.float)
    wd_N_ini             = np.zeros(gm1.shape,dtype=np.float)
    wd_X_fin             = np.zeros(gm1.shape,dtype=np.float)
    wd_X_ini             = np.zeros(gm1.shape,dtype=np.float)

    wd_N_fin             = gm1 + gm2
    wd_N_ini             = mm1 + mm2

    wd_X_fin[wd_N_fin>0] = (1.*gm1[wd_N_fin>0])/(1.*wd_N_fin[wd_N_fin>0])
    wd_X_ini[wd_N_ini>0] = (1.*mm1[wd_N_ini>0])/(1.*wd_N_ini[wd_N_ini>0])

    wd_dX                = wd_X_fin - wd_X_ini

    wd_Xi                = g.GetXiMatrix()
    mask                 = np.array(wd_Xi == 0)
    wd_logXi             = np.zeros(np.shape(wd_Xi))
    wd_logXi[wd_Xi > 0]  = np.log(wd_Xi[wd_Xi > 0])

    if args.write_xi_file:
        fp = open('xi.txt','w')
        for i,n1 in enumerate(m1):
            for j,n2 in enumerate(m2):
                fp.write("{} {} {}\n".format(n1,n2,wd_Xi[i,j]))
            fp.write("\n")
        fp.close()

    if not args.baseoutfilename is None:
        fp = open(args.baseoutfilename,'w')
    else:
        fp = sys.stdout

    # compute averages for all inocula given by the two axes
    for i,a1 in enumerate(a1_list):
        for j,a2 in enumerate(a2_list):
            
            inoc      = gc.TransformInoculum([a1,a2],inabs = args.AbsoluteCoordinates, outabs = True)
            
            avg_N1    = gc.SeedingAverage(gm1,       inoc)
            avg_N2    = gc.SeedingAverage(gm2,       inoc)
            avg_N1N1  = gc.SeedingAverage(gm1 * gm1, inoc)
            avg_N1N2  = gc.SeedingAverage(gm1 * gm2, inoc)

            avg_dX    = gc.SeedingAverage(wd_dX,     inoc)
            avg_X     = gc.SeedingAverage(wd_X_fin,  inoc)
            
            
            avg_nXi   = gc.SeedingAverage(wd_N_ini * wd_Xi, inoc)
            if avg_nXi > 0: omega = wd_N_ini * wd_Xi / avg_nXi
            else:           omega = 0
            
            var_N1    = avg_N1N1 - avg_N1 * avg_N1
            cov_N1N2  = avg_N1N2 - avg_N1 * avg_N2
                    
            if avg_N1 + avg_N2 > 0:
                cov_XrelN = avg_N1/(avg_N1 + avg_N2) - avg_X
            else:
                cov_XrelN = 0
            
            avg_Xi    = gc.SeedingAverage(wd_Xi,    inoc)
            avg_LogXi = gc.SeedingAverage(wd_logXi, inoc)
            
            # individual 4 terms for 2 strains in the expansion of Cov[X,N/<N>] up to O(da), weak selection limit
            avg_exp1   =      gc.SeedingAverage(wd_X_ini * (omega - 1),               inoc)
            avg_exp2   = da * gc.SeedingAverage(wd_X_ini * (omega - 1) * wd_logXi,    inoc)
            avg_exp3A  = da * gc.SeedingAverage(wd_X_ini * (2*wd_X_ini-1) * wd_logXi, inoc)
            avg_exp3B1 =      gc.SeedingAverage(wd_X_ini * omega,                     inoc)
            avg_exp3B2 =      gc.SeedingAverage((2*wd_X_ini-1) * omega * wd_logXi,    inoc)
            avg_exp3B  = da * avg_exp3B1 * avg_exp3B2
            
            # output                                                                                             1   2   3       4          5         6         7                      8       9      
            fp.write("{:14.6e} {:14.6e} {:14.6e} {:14.6e} {:14.6e} {:14.6e} {:14.6e} {:14.6e} {:14.6e}\n".format(a1, a2, avg_dX, cov_XrelN, avg_exp1, avg_exp2, avg_exp3A - avg_exp3B, avg_Xi, avg_LogXi))
        fp.write("\n")

    if not args.baseoutfilename is None:
        fp.close()