-
Notifications
You must be signed in to change notification settings - Fork 3
/
FileProcessingService.py
213 lines (178 loc) · 9.98 KB
/
FileProcessingService.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import re
import os
import random
import csv
import numpy
from SupportedFileTypes import SupportedFileTypes
from SupportedDistributions import SupportedDistributions
from Utilities.OperatingSystemUtil import OperatingSystemUtil
from Utilities.SafeCastUtil import SafeCastUtil
import collections
class FileProcessingService(object):
GENERATED_FOLDER_NAME = "/GenomeFiles"
GENOMES_FILE_NAME = "Genomes.txt"
IDENTIFIER_REGEX = re.compile(r'\$.+?\$')
DEFAULT_GAUSSIAN_STANDARD_DEVIATION = 0.1
OUTPUT_FILE_NAME = "Sim0GenomesMatrix.csv"
DEFAULT_NUM_GENOMES = 10
num_generated_coefficients = 0
def __init__(self, data_file, file_type, number_of_genomes, path):
self.data_file = data_file
self.file_type = file_type
self.number_of_genomes = SafeCastUtil.safeCast(number_of_genomes, int, self.DEFAULT_NUM_GENOMES)
self.path = path
def createGenomes(self):
if self.file_type == SupportedFileTypes.MATLAB or self.file_type == SupportedFileTypes.OCTAVE:
return self.handleFile("%")
elif self.file_type == SupportedFileTypes.R:
return self.handleFile("#")
# Note - fn will need to be able to take in files containing booleans
def handleFile(self, comment_character, file_name_root="genome"):
genomes_file_list = []
path = self.maybeCreateNewFileDirectory()
genomes = collections.OrderedDict()
for genome in range(1, self.number_of_genomes + 1):
genome_name = file_name_root + str(genome) #Note - changed this to a parameter for SIM1
coefficient_map = collections.OrderedDict()
new_genome_file = open(path + "/" + genome_name + "." + self.file_type, "w")
genomes_file_list.append(genome_name + "." + self.file_type)
for line in self.data_file:
if line[0] == comment_character:
new_genome_file.write(line)
continue
new_line = self.maybeGenerateNewLineAndSaveCoefficientValues(coefficient_map, line)
new_genome_file.write(new_line)
new_genome_file.close()
self.data_file.seek(0)
self.num_generated_coefficients = 0
genomes[genome_name] = coefficient_map
self.writeGenomesKeyFilesToDirectory(genomes, path)
genomes_matrix = self.createGenomesMatrix(genomes)
self.writeDataFile(genomes_matrix)
return [genomes_file_list, genomes_matrix]
def maybeCreateNewFileDirectory(self):
target_directory = self.path + self.GENERATED_FOLDER_NAME
if os.getcwd() != "/":
if not os.path.isdir(target_directory):
os.mkdir(target_directory)
else:
raise ValueError('Provided path must not be root directory.')
return target_directory
def maybeGenerateNewLineAndSaveCoefficientValues(self, coefficient_map, line):
target_sequences = self.extractTargetSequences(line)
new_line = line
for i in range(0, len(target_sequences)):
target_sequence = target_sequences[i]
coefficient_name = self.extractCoefficientName(target_sequence)
distribution = self.extractDistributionName(target_sequence)
params = self.extractParameters(target_sequence)
coefficient_value = self.retrieveCoefficientValueFromDistribution(distribution, params)
# Replace $dollar sign contents$ with extracted coefficient value, write to file
new_line = new_line.replace("$" + target_sequence + "$", str(coefficient_value), 1)
if type(coefficient_value) is str:
coefficient_value = self.replaceCoefValue(coefficient_value)
coefficient_map[coefficient_name] = coefficient_value
return new_line
def extractTargetSequences(self, line):
return [target_sequence.replace("$", "") for target_sequence in self.IDENTIFIER_REGEX.findall(line)]
def extractCoefficientName(self, target_sequence):
if "name=" in target_sequence:
return target_sequence.split("name=")[1].strip()
else:
self.num_generated_coefficients += 1
return "coefficient" + str(self.num_generated_coefficients)
def extractDistributionName(self, target_sequence):
distribution_name = ''
if "name=" in target_sequence or ("(" in target_sequence and ")" in target_sequence):
distribution_name = re.findall(r'[a-z]*', target_sequence.split("name=")[0])[0]
elif "name=" not in target_sequence and ("(" in target_sequence and ")" in target_sequence):
distribution_name = re.findall(r'[a-z]*', target_sequence)[0]
if distribution_name == '':
return SupportedDistributions.GAUSS
else:
return distribution_name
def extractParameters(self, target_sequence):
pattern = re.compile('-? *\.?[0-9]+\.?[0-9]*(?:[Ee] *-? *[0-9]+)?') # now supports scientific notation
return [param.strip() for param in re.findall(pattern, target_sequence.split("name=")[0])]
def retrieveCoefficientValueFromDistribution(self, distribution, params):
# Selection from a series of both discrete and continuous probability distributions
if distribution == SupportedDistributions.UNIFORM:
return self.generateRandomValueFromUniformDistribution(params[0], params[1])
elif distribution == SupportedDistributions.GAUSS: # changed form GAUSSIAN TO GAUSS
if len(params) <= 1:
return self.generateRandomValueFromGaussianDistribution(params[0],
self.DEFAULT_GAUSSIAN_STANDARD_DEVIATION * float(params[0]))
else:
return self.generateRandomValueFromGaussianDistribution(params[0], params[1])
elif distribution == SupportedDistributions.DISCRETE:
return self.generateRandomValueFromDiscreteDistribution(params)
elif distribution == SupportedDistributions.GAMMA:
return self.generateRandomValueFromGammaDistribution(params[0], params[1])
elif distribution == SupportedDistributions.LOGNORMAL:
return self.generateRandomValueFromLogNormalDistribution(params[0], params[1])
elif distribution == SupportedDistributions.BINOMIAL:
return self.generateRandomValueFromBinomialDistribution(params[0], params[1])
elif distribution == SupportedDistributions.POISSON:
return self.generateRandomValueFromPoissonDistribution(params[0])
elif distribution == SupportedDistributions.BOOLEAN:
return self.pickBoolean(params[0])
else:
raise ValueError('Unsupported distribution: ' + distribution)
def generateRandomValueFromUniformDistribution(self, mini, maxi):
return random.uniform(SafeCastUtil.safeCast(mini, float, -1), SafeCastUtil.safeCast(maxi, float, 1))
def generateRandomValueFromGaussianDistribution(self, mu, sigma):
return random.gauss(SafeCastUtil.safeCast(mu, float, 0), SafeCastUtil.safeCast(sigma, float, 1))
def generateRandomValueFromDiscreteDistribution(self, values):
return SafeCastUtil.safeCast(random.choice(values), float, 0)
def generateRandomValueFromGammaDistribution(self, k, theta):
return random.gammavariate(SafeCastUtil.safeCast(k, float, 1), SafeCastUtil.safeCast(theta, float, 1))
def generateRandomValueFromLogNormalDistribution(self, mu, sigma):
return random.lognormvariate(SafeCastUtil.safeCast(mu, float, 0), SafeCastUtil.safeCast(sigma, float, 1))
def generateRandomValueFromBinomialDistribution(self, n, p):
return numpy.random.binomial(SafeCastUtil.safeCast(n, int, 100), SafeCastUtil.safeCast(p, float, 0.5))
def generateRandomValueFromPoissonDistribution(self, k):
return numpy.random.poisson(SafeCastUtil.safeCast(k, int, 1))
def pickBoolean(self, probability_of_zero):
val = random.uniform(0, 1)
if val < SafeCastUtil.safeCast(probability_of_zero, float, 0.6):
return 0
else:
return 1
def writeGenomesKeyFilesToDirectory(self, genomes, path):
for genome in genomes.keys():
key_file_extension = self.file_type
if key_file_extension == SupportedFileTypes.OCTAVE:
key_file_extension = SupportedFileTypes.MATLAB
new_genome_file = open(path + "/" + genome + "_key." + key_file_extension, "w")
for value in genomes[genome].keys():
if self.file_type == SupportedFileTypes.MATLAB or SupportedFileTypes.OCTAVE:
new_genome_file.write(str(value) + "=" + str(genomes[genome][value]) + ";" + "\n")
elif self.file_type == SupportedFileTypes.R:
new_genome_file.write(str(value) + "<-" + str(genomes[genome][value]) + "\n")
new_genome_file.close()
def createGenomesMatrix(self, genomes):
genomes_matrix = []
counter = 0
for genome in genomes.keys():
genomes_matrix.append([])
for value in genomes[genome].keys():
genomes_matrix[counter].append((genomes[genome][value]))
counter = counter + 1
return genomes_matrix
def replaceCoefValue(self, coefficient_string):
if coefficient_string == "":
return int(-1)
else:
pos = coefficient_string.index(")")
return int(coefficient_string[pos - 1])
def writeDataFile(self, genomes_matrix):
current_directory = os.getcwd()
OperatingSystemUtil.changeWorkingDirectory(self.path + "/GenomeFiles")
with open(self.OUTPUT_FILE_NAME, 'w') as csv_file:
try:
data_writer = csv.writer(csv_file, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for i in range(0, self.number_of_genomes):
data_writer.writerow(genomes_matrix[i])
finally:
csv_file.close()
OperatingSystemUtil.changeWorkingDirectory(current_directory)