initialize()
{
    setSeed(23);
    defineConstant("OUTFILE", "recipe_nonWF_selfing.trees");
    defineConstant("PEDIGREE", paste0(c(OUTFILE, ".pedigree")));
    initializeSLiMModelType("nonWF");
    initializeSLiMOptions(keepPedigrees=T);
    initializeTreeSeq();
    initializeMutationRate(1e-2);
    initializeMutationType("m1", 0.5, "f", -0.1);
    initializeGenomicElementType("g1", m1, 1.0);
    initializeGenomicElement(g1, 0, 99);
    initializeRecombinationRate(1e-2);
    defineConstant("K", 10);
}

reproduction() {
    if (runif(1) < 0.25) {
        mate = subpop.sampleIndividuals(1);
    } else {
        mate = individual;
    }
    for (_ in seqLen(rpois(1, 2))) {
      subpop.addCrossed(individual, mate);
    }
}

1 early() {
    sim.addSubpop("p1", 10);
}

early() {
    p1.fitnessScaling = K / p1.individualCount;
}

10 late() {
    sim.treeSeqOutput(OUTFILE);
    catn("Done.");
    sim.simulationFinished();
}

// PEDIGREE OUTPUT
1 early() {
    writeFile(PEDIGREE,
       paste(c("generation", "stage", "individual", "age", "parent1", "parent2"),
             sep="\t"));
}

1: early() {
    for (pop in sim.subpopulations) {
        for (ind in pop.individuals) {
            age = sim.modelType == "nonWF" ? ind.age else -1;
            writeFile(PEDIGREE,
             paste(c(sim.generation, 'early', ind.pedigreeID, age, ind.pedigreeParentIDs),
                   sep='\t'),
             append=T);
        }
    }
}

1: late() {
    for (pop in sim.subpopulations) {
        for (ind in pop.individuals) {
            age = sim.modelType == "nonWF" ? ind.age else -1;
            writeFile(PEDIGREE,
             paste(c(sim.generation, 'late', ind.pedigreeID, age, ind.pedigreeParentIDs),
                   sep='\t'),
             append=T);
        }
    }
}

