import os, sys import time import pandas as pd import numpy as np import matplotlib.pyplot as plt import pandas as pd import pylab n = 1 #количество итераций current_path = os.getcwd() #определяю путь до папки в которой лежит этот скрипт if not os.path.exists(current_path + '\Results'):#создаю папку Results os.makedirs(current_path + '\Results') if not os.path.exists(current_path + '\Common'):#создаю папку Common os.makedirs(current_path + '\Common') if not os.path.exists(current_path + '\Pictures'):#создаю папку Pictures os.makedirs(current_path + '\Pictures') pass_to_scenario = current_path + '\Scenario' #эта переменная хранит путь до папки Scenario for filename in os.listdir(pass_to_scenario): #читаю файл за файлом в директории Scenario, т.е. поочередно иду по каждому сценарию scenario = filename[0:-4] if not os.path.exists(current_path + '\Pictures' + '\\' + scenario):#создаю в папке Pictures папки с названиями сценариев, для удобства os.makedirs(current_path + '\Pictures' + '\\' + scenario) for i in range (n): #количесво запусков текущего сценария timestr = time.strftime("%Y%m%d-%H%M%S") #переменная, которая хранит текущее время для задания имени файла выдачи os.chdir(current_path + '\Results') #меняю директорию на ту, куда будут попадать файлы выдачи os.system(current_path + '\Deaf2.0.exe ' + pass_to_scenario + '\\' + filename) #запускаю exe'шник и подаю ему на вход текущий файл-сценарий с параметрами print(current_path + '\Deaf2.0.exe ' + pass_to_scenario + '\\' + filename) os.rename('output.deaf2.0.csv', filename[0:-4] + '_' + str(i) + '_' + timestr + '.txt') #переименовываю файл output.txt на текущую датуи время, учитывая номер сценария и итерации #print(current_path + '\Deaf2.0.exe ' + pass_to_scenario + '\\' + filename + ' ' + '1>out.txt ' + '2>err.txt') #----------- Объединение в датафреймы pass_to_results = current_path + '\Results' list_of_scenario = [] for filename in os.listdir(pass_to_results): pos_end = filename.find("_") list_of_scenario.append(filename[0:pos_end]) count_scenario = set(list_of_scenario) os.chdir(current_path + '\Common') for l in count_scenario: data = pd.DataFrame(columns=('Generation', 'TotalPopulation', 'Men', 'Women', 'Deaf', 'DD marriages', 'DD children', 'DH marriages', 'DH children', 'HH marriages', 'HH children', 'DA frequency', 'DA homozygotes frequency')) for filename in os.listdir(pass_to_results): pos_end = filename.find("_") if l == filename[0:pos_end]: data = data.append(pd.read_csv(pass_to_results +'\\'+ filename, sep='\t')) data.sort_values(by=['Generation']).to_csv('commonSort' + l + '.txt', sep='\t') print(list_of_scenario) #----------- Построение графиков data = pd.DataFrame(columns=('Generation', 'TotalPopulation', 'Men', 'Women', 'Deaf', 'DD marriages', 'DD children', 'DH marriages', 'DH children', 'HH marriages', 'HH children', 'DA frequency', 'DA homozygotes frequency')) pass_to_common = current_path + '\Common' list_of_columns = [] os.chdir(current_path + '\Pictures') for filename in os.listdir(pass_to_common): #Идем по всем файлам из папки Common, то есть по сценариям os.chdir(current_path + '\Pictures' + '\\' + filename[10:-4])#переход в папку с названием спенария в Pictures data = pd.read_csv(pass_to_common +'\\'+ filename, sep='\t') #Создаю dataFrame с данными по текущему сценарию del data['Unnamed: 0'] #Удаляю лишний столбец (особенности создания датафрейма) list_of_columns = data.columns.values #получаю список из названий столбцов list_of_clmn = list(list_of_columns) list_of_clmn.remove('Generation') #удаляю generation так как для него не надо строить боксплот for i in list_of_clmn: #беру по одному название столбца и строю для него боксплот data.boxplot(column = i, by='Generation') #то, что по оси Х это "by", а что, что боксплочу это в 'colomn' записываю' plt.savefig(filename[10:-4] + '_' + i + '.png', dpi=400) #сохраняю график и даю название <имя сценария> + <имя столбца> plt.grid(True)