Created
January 9, 2017 01:12
-
-
Save greeness/9b75a3ed3ac8179c4700328db2531dc0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#The input data should be in CSV format. | |
# Each row is a campaign. The columns are (description and variable name): | |
# Campaign id (id) | |
# Conversion rate (cvr) | |
# Bid price (price) | |
# Max allocated campaign budget (max_allocation) | |
import csv | |
import sys | |
class Campaign(object): | |
def __init__(self, row): | |
self.id = row['id'] | |
self.price = float(row['price']) | |
self.cvr = float(row['cvr']) | |
self.k = str(self.cvr / self.price) | |
self.max_allocation = float(row['max_allocation']) | |
self.row = row | |
self.x = ''.join(['x', self.id]) | |
def __str__(self): | |
return str(self.row) | |
def main(csvfile, total_budget): | |
campaigns = [] | |
with open(csvfile, 'r') as csvfile: | |
input_reader = csv.DictReader(csvfile, delimiter=',') | |
for row in input_reader: | |
c = Campaign(row) | |
campaigns.append(c) | |
code = '' | |
# add variables section | |
for c in campaigns: | |
code += ' '.join(['var', c.x]) | |
code += ';\n' | |
# add maximize obj | |
code += '\nmaximize obj: ' | |
linear_parts = [] | |
for c in campaigns: | |
linear_parts.append('*'.join([c.k, c.x])) | |
code += '+'.join(linear_parts) | |
code += ';\n' | |
# add constraint of total budget | |
xs = [] | |
for c in campaigns: | |
xs.append(c.x) | |
code += 's.t. budget: ' | |
code += str('+'.join(xs)) | |
code += ' <= %f;\n' % (total_budget) | |
# add constrains on each campaign | |
for c in campaigns: | |
code += 's.t. campaign_' + c.id + ': ' + '0 <= ' + c.x + " <= " + str(c.max_allocation) + ';\n' | |
code += '\nsolve;\n' | |
code += 'display ' + ','.join(xs) + ';\n' | |
code += 'end;\n' | |
print code | |
if __name__ == "__main__": | |
if len(sys.argv) != 3: | |
print "Usage: python budget.py input_csv total_budget" | |
csvfile = sys.argv[1] | |
total_budget = float(sys.argv[2]) | |
main(csvfile, total_budget) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment