def normal():
    wanted = json.loads(open("wanted.json").read())
    original_path = os.path.abspath(os.getcwd())
    for d, v in wanted.items():
        for subdir, lins in v.items():
            path = os.path.abspath(os.path.join(d, subdir))
            print("Processing path:", path)
            os.chdir(path)

            for lin in lins:
                lineage_num = int(lin)
                target_file = os.path.join(
                    "data",
                    "cell_lines",
                    "lineage{0:02d}.npy".format(lineage_num)
                )
                cell_line = np.load(target_file)
                spot_plot.plot_images(cell_line, lineage_num)
                try:
                    spot_plot.plot_graphs(cell_line, lineage_num)
                except AttributeError:
                    print("ParA data missing")
                    get_parA.main()
                    cell_line = np.load(target_file)
                    spot_plot.plot_graphs(cell_line, lineage_num)

                print("Generated plots for lineage {0}".format(lineage_num))

            os.chdir(original_path)
    def end(self, discard=False):
        if discard:
            plt.close()
            return

        # backup previous lineage file
        previous_file = "data/cell_lines/lineage{0:02d}.npy".format(self.lineage_num)
        if os.path.exists(previous_file):
            if not os.path.exists("data/cell_lines/backups"):
                os.mkdir("data/cell_lines/backups")
            backup_file = "data/cell_lines/backups/{0}-lineage{1:02d}.npy".format(
                datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d-%H%M"),
                self.lineage_num
            )
            attempt = 2
            while os.path.exists(backup_file):
                first = backup_file.split(".npy")[0]
                backup_file = "{0}.npy-{1}".format(first, attempt)
                attempt += 1
            print("Backing up previous lineage file to {0}".format(backup_file))
            os.rename(previous_file, backup_file)

        print("Saving new lineage file")
        np.save(
            "data/cell_lines/lineage{0:02d}".format(self.lineage_num),
            self.cell_line
        )

        if self.GEN_PLOTS:
            print("Saving new PDFs")
            spot_plot.plot_images(self.cell_line, int(self.lineage_num))
            spot_plot.plot_graphs(self.cell_line, int(self.lineage_num), um=True)

        spot_spread.gen_xl(self.cell_line, int(self.lineage_num))

        plt.close(self.fig)
def plot_lineages(bonly=False):
    if not os.path.exists("ancestry.json"):
        cells = init()
    else:
        cells = json.loads(open("ancestry.json").read())
    inverse_cells = {cells[k]: k for k in cells}

    lineage = track.Lineage()

    already_plotted = []
    for lineage_num in sorted(inverse_cells.keys()):
        if lineage_num in already_plotted:
            continue

        print("Processing lineage {0}".format(lineage_num))
        cell_line_nums = []
#        cell_line_positions = {}
        cell_lines = {}
        cell_parents = {}
#        designations = {
#            lineage_num: "",
#        }
        current_num = int(lineage_num)
        buff = []
        generations = {}
        max_len = 0

        labels = {}

        while True:
            if current_num:
                mother_line = np.load("data/cell_lines/lineage{0:02d}.npy".format(current_num))
                max_len_ = max([x.length[0][0] * PX for x in mother_line])
                if max_len_ > max_len:
                    max_len = float(max_len_)
                cell_lines[current_num] = mother_line
                cell_line_nums.append(current_num)
                daughters = mother_line[-1].children

                gen = 0
#                designation = ""
                _temp_num = int(current_num)
                while True:
                    if _temp_num not in cell_parents:
                        break
                    _temp_num = cell_parents[_temp_num]
                    gen += 1
                generations[current_num] = gen

                labels[mother_line[-1].id] = current_num

                if daughters:
                    d1 = lineage.frames.cell(daughters[0]).length[0][0] * PX
                    d2 = lineage.frames.cell(daughters[1]).length[0][0] * PX
                    max_len_ = max([max_len_, d1 + d2])
                    if max_len_ > max_len:
                        max_len = float(max_len_)

                    d1n = cells[daughters[0]]
                    d2n = cells[daughters[1]]
                    buff.append(d1n)
                    buff.append(d2n)
#                    designations[d1n] = designations[current_num] + "A"
#                    designations[d2n] = designations[current_num] + "B"
                    cell_parents[d1n] = current_num
                    cell_parents[d2n] = current_num
                    print("{0} => {1}, {2}".format(current_num, d1n, d2n))
                else:
                    buff.append(None)
                    buff.append(None)
                    print("{0} => None".format(current_num))
            else:
                cell_line_nums.append(None)
            try:
                current_num = buff.pop(0)
            except IndexError:
                break

#        max_gen = max(generations.values())
#
#        last_xpos = None
#        count = 0
#        specs = []
#        gridspec = matplotlib.gridspec.GridSpec(2 ** max_gen, max_gen + 1)
#
#        for num in cell_line_nums:
#            if not num:
#                count += 1
#                continue
#            # get generation
#            xpos = generations[num]
#            if xpos == last_xpos:
#                count += 1
#            else:
#                last_xpos = int(xpos)
#                count = 0
#            yinterval = 2 ** (max_gen - xpos)
#            ypos = count * yinterval
#            specs.append(gridspec[ypos, xpos])
#
#        fig = plt.figure(
#            figsize=(
#                (20 * (max_gen + 1)) / 6,
#                (5 * (2 ** max_gen)) / 2
#            )
#        )
#
#        i = 0
#        for cell_line_num in cell_line_nums:
#            if not cell_line_num:
#                continue
#
#            cell_line = cell_lines[cell_line_num]
#            print("Plotting lineage {0}".format(cell_line_num))
#
#            ax = fig.add_subplot(specs[i])
#            spot_plot._despine(ax)
#            ax.set_title("Lineage {0}".format(cell_line_num))
#            spot_plot.plot_graphs_parB_only(cell_line, cell_line_num, ax_parB=ax, save=False)
#            ylim = (max_len + 5) / 2
#            ax.set_ylim([ylim, -ylim])
#
#            already_plotted.append(cell_line_num)
#            i += 1
#

        num_rows = int(round(np.sqrt(len(cell_lines))))
        if num_rows ** 2 < len(cell_lines):
            gridspec = matplotlib.gridspec.GridSpec(num_rows + 1, num_rows)
        else:
            gridspec = matplotlib.gridspec.GridSpec(num_rows, num_rows)
        fig = plt.figure(
            figsize=(
                (10 * num_rows) / 3,
                (5 * num_rows) / 2
            )
        )
        fig.patch.set_alpha(0)

        i = 0
        for cell_line_num in cell_line_nums:
            if not cell_line_num:
                continue
#            designation = designations[cell_line_num]
            # title = "{0} ({1})".format(designation, cell_line_num)
            title = "Cell {0}".format(cell_line_num)

            cell_line = cell_lines[cell_line_num]
            print("Plotting lineage {0}".format(cell_line_num))

            sp = matplotlib.gridspec.SubplotSpec(gridspec, i)
            ax = fig.add_subplot(sp)
            ax.set_title(title)
            if cell_line_num == 1:
                ax.set_ylabel(r"Distance from mid-cell (\si{\micro\metre})")
                ax.set_xlabel(r"Time (\si{\minute})")
            spot_plot._despine(ax)
            if bonly:
                spot_plot.plot_graphs_parB_only(cell_line, cell_line_num, ax_parB=ax, save=False, labels=labels, um=True)
            else:
                spot_plot.plot_graphs(cell_line, cell_line_num, parA_heatmap=ax, save=False, num_plots=1, labels=labels, um=True)

            ylim = (max_len + (5 * PX)) / 2
            ax.set_ylim([-ylim, ylim])

            already_plotted.append(cell_line_num)
            i += 1

        plt.tight_layout()

        os.makedirs("data/full_lineages", exist_ok=True)
        plt.savefig("data/full_lineages/lineage{0:02d}.pdf".format(lineage_num))

        print("Done with tree starting from {0}".format(lineage_num))