def generate_triad_type_transition_matlab_code(data, definition, def_args):
    f = open(OUT_DIR.DIR + 'triad-matlab-code.txt', 'w')

    for (A, B, C) in combinations(data.countries(), 3):
        f.write("%s-%s-%s:y=%s\n" % (file_safe(A), file_safe(B), file_safe(C),
                                     str([traid_plot_value(
                                         triad_type(data, year, A, B, C, definition, def_args))
                                          for year in data.all_years]).replace(",", " ")))
    f.write("x=%s;\n" % str([year for year in data.all_years]).replace(",", " "))
    f.write("plot(x,y,'b-o',[2000 2000],[0 8],'b.');\n")
    f.write("set(gca,'YTick',[0 1 2 3 4 5 6 7 8 9]);\n")
    f.write("set(gca,'YTickLabel',{'T003','T012','T102','T021','T111','T201','T030','T120','T210','T300'});\n")

    f.close()
def get_run_lengths(data, definition, def_args, randomize=False):
    runLengths = RunLength()
    # 1373701
    count = 0
    start = 9
    end = 10
    total = 203 * 202 * 201 / 6 / 10

    for (A, B, C) in combinations(data.countries(), 3):
        if total * start < count < total * end:
            running_traid = triad_type(data, 1963, A, B, C, definition, def_args)
            running_count = 1
            for year in range(1964, 2001):
                current_traid = triad_type(data, year, A, B, C, definition, def_args)
                if current_traid != running_traid:
                    runLengths.record(running_traid, running_count)
                    running_traid = current_traid
                    running_count = 1
                else:
                    running_count += 1
            if running_count == 38 and running_traid == 'T300': print "(%s,%s,%s)" % (A, B, C)
            runLengths.record(running_traid, running_count)
        count += 1
    return runLengths
def print_traid_transitions(data, definition, def_args, years_range):
    for year in years_range:
        for traid in ['T0', 'T1', 'T2', 'T3']:
            this_year_count = 0
            next_year_counts = {'T0': 0, 'T1': 0, 'T2': 0, 'T3': 0}
            for (A, B, C) in get_traids(data, year, definition, def_args, traid):
                this_year_count += 1
                if is_traid(data, year, A, B, C, definition, def_args):
                    t_type = triad_type(data, year + 1, A, B, C, definition, def_args)[:2]
                    if t_type == 'T0': next_year_counts['T0'] += 1
                    if t_type == 'T1': next_year_counts['T1'] += 1
                    if t_type == 'T2': next_year_counts['T2'] += 1
                    if t_type == 'T3': next_year_counts['T3'] += 1
            for next_traid in ['T0', 'T1', 'T2', 'T3']:
                print "%d:%s->%s=%.2f" % (year, traid, next_traid, next_year_counts[next_traid] * 1.0 / this_year_count)