def example3(queue_id): params = Params( mu=3, lambda1=4, lambda2=4, servers_number=6, fragments_numbers=[3, 2], queues_capacities=[3, 3], ) all_states = get_all_states(params) states_with_policy = get_policed_states(all_states, params) selected_policy_vector = [queue_id] * len(states_with_policy) print("Current policy:") policy = Policy(selected_policy_vector, states_with_policy, params) for state in states_with_policy: print( f" state = {state}, action = {policy.get_action_for_state(state)}" ) calculations = Calculations(params) calculations.calculate(policy) performance_measures = calculations.performance_measures print(performance_measures, "\n")
class TestCalculations(unittest.TestCase): def setUp(self): self.nodes = [] for i in range(10): self.nodes.append(Node(random.randint(0, 20))) self.root = self.nodes[0] x = 1 while x < 10: add_rand(self.root, self.nodes[x]) x += 1 self.calc = Calculations(self.root) def test_calculate_sum_root(self): self.assertEqual(self.calc.calculate_sum(self.root), sum(n.value for n in self.nodes)) self.assertEqual(self.calc.count, len(self.nodes)) x = sorted(self.calc.nodes, key=lambda x: x.value) y = sorted(self.nodes, key=lambda x: x.value) for i in range(len(x)): self.assertEqual(x[i].value, y[i].value) def test_calculate_average(self): self.assertEqual(self.calc.calculate_average(), sum(n.value for n in self.nodes) / len(self.nodes)) def test_calculate_median(self): statistics.median(n.value for n in self.nodes)
def example1(policy_id): params = Params( mu=3, lambda1=4, lambda2=4, servers_number=5, fragments_numbers=[2, 3], queues_capacities=[3, 3], ) all_states = get_all_states(params) states_with_policy = get_policed_states(all_states, params) policies = get_all_possible_policies(states_with_policy) # print("All possible policies number: ", len(policies)) selected_policy_vector = None for idx, p in enumerate(policies): selected_policy_vector = p if idx == policy_id: break print("Current policy:") policy = Policy(selected_policy_vector, states_with_policy, params) for state in states_with_policy: print( f" state = {state}, action = {policy.get_action_for_state(state)}" ) calculations = Calculations(params) calculations.calculate(policy) performance_measures = calculations.performance_measures print(performance_measures, "\n")
def get_performance_measures(params): calculations = Calculations(params) strategy = (0, 0, 0, 0) all_states = calculations.get_all_states() states_with_policy = get_policed_states(all_states, params) states_policy = StatesPolicy(strategy, states_with_policy, params) calculations.calculate(states_policy) print(calculations.performance_measures) return calculations.performance_measures
def setUp(self): self.nodes = [] for i in range(10): self.nodes.append(Node(random.randint(0, 20))) self.root = self.nodes[0] x = 1 while x < 10: add_rand(self.root, self.nodes[x]) x += 1 self.calc = Calculations(self.root)
def respondrun(self, q): signal = q.text() if signal == 'BLUP': self.cal_widget = Calculations() self.setCentralWidget(self.cal_widget) if self.signal == 'txt': self.cal_widget.onlyshow(self.signal, self.txt_widget.datatxt, self.path) elif self.signal == 'csv': self.cal_widget.onlyshow(self.signal, self.csv_widget.datacsv, self.path)
def home(): form = BloodPressureForm() calculations = Calculations() if form.validate_on_submit(): flash(f'Info Submitted for calculation for {form.name.data}!', 'Success') flash(f'Your current blood pressure is:') systolic_level = int(request.form.get("systolic_level")) diastolic_level = int(request.form.get("diastolic_level")) gauge = generate_gauge(systolic_level, diastolic_level) result = calculations.calculate_blood_pressure(systolic_level, diastolic_level) return render_template('result.html', value=result, form=form, chart=gauge) return render_template('home.html', form=form)
def test_grouped_by_occurance(self): workbook = xlsxwriter.Workbook('/Users/mzakany/Desktop/demo.xlsx') worksheet = workbook.add_worksheet() trans = self.q.get_transactions_by_range('53',3,6) qs = Calculations(trans) row_count = 2 itemset = qs.grouped_by_occurance().to_dict().iteritems() # for x,y in itemset: # print x # for x in y['grouped_transaction']: # print x for x,y in itemset: worksheet.write("A%s" % str(row_count),x) row_count += 2 for row in y['grouped_transaction']: worksheet.write("B%s" % str(row_count),row[0]) worksheet.write("C%s" % str(row_count),row[1]) worksheet.write("D%s" % str(row_count),row[2]) row_count += 1 worksheet.write("E%s" % str(row_count),y['sum']) row_count += 1
def example2(): params = Params( mu=3, lambda1=5, lambda2=5, servers_number=6, fragments_numbers=[3, 2], queues_capacities=[1, 1], ) all_states = get_all_states(params) states_with_policy = get_policed_states(all_states, params) print("All states where policy is possible:") pprint(states_with_policy) strategies = get_all_possible_policies(states_with_policy) states_policy = Policy(tuple(), states_with_policy, params) states_policy.print_adjacent_states() storage = PerformanceMeasuresStorage() print() for strategy in strategies: states_policy.policy_vector = strategy print(strategy) calculations = Calculations(params) calculations.calculate(states_policy) performance_measures = calculations.performance_measures print(performance_measures, "\n") storage.append(strategy, performance_measures) print(storage) print() storage.show_difference() print("executed")
class TestRemainder(unittest.TestCase): class_inst = Calculations() # test that remainder_zero returns True for 20 % 5 def test_remainder_zero(self): self.assertTrue(self.class_inst.remainder_zero(20, 5)) # test that remainder_zero returns False for 17 % 2 def test_remainder_nonzero(self): self.assertFalse(self.class_inst.remainder_zero(17, 2)) # test that positive_values returns True for 10, 0.5, 0.1, 0.0001 def test_positive_values(self): self.assertTrue(self.class_inst.positive_values(10, 0.5, 0.1, 0.0001)) # test that positive_values returns False for 0, -1, -0.01 def test_negative_values(self): self.assertFalse(self.class_inst.positive_values(0)) self.assertFalse(self.class_inst.positive_values(-0.01)) self.assertFalse(self.class_inst.positive_values(0.01, 10, -5))
class CalculationsTest(unittest.TestCase): def setUp(self): self.calculations = Calculations() def tearDown(self): pass def test_low_bloodpressure(self): systolic = 89 diastolic = 59 response = self.calculations.calculate_blood_pressure(systolic, diastolic) self.assertEqual(response, "Low") def test_ideal_bloodpressure(self): systolic = 115 diastolic = 60 response = self.calculations.calculate_blood_pressure(systolic, diastolic) self.assertEqual(response, "Ideal") def test_pre_high_bloodpressure_with_lower_diastolic(self): systolic = 135 diastolic = 70 response = self.calculations.calculate_blood_pressure(systolic, diastolic) self.assertEqual(response, "Pre-High") def test_pre_high_bloodpressure_with_lower_systolic(self): systolic = 110 diastolic = 85 response = self.calculations.calculate_blood_pressure(systolic, diastolic) self.assertEqual(response, "Pre-High") def test_high_bloodpressure_with_lower_diastolic(self): systolic = 160 diastolic = 70 response = self.calculations.calculate_blood_pressure(systolic, diastolic) self.assertEqual(response, "High") def test_high_bloodpressure_with_lower_systolic(self): systolic = 120 diastolic = 95 response = self.calculations.calculate_blood_pressure(systolic, diastolic) self.assertEqual(response, "High")
def test_all_transaction_value_counts(self): queryset = self.q.all_transactions('53') qs = Calculations(queryset) assert qs.value_counts().__class__ == pandas.core.series.Series
def setUp(self): self.calculations = Calculations()
class PredoBreedMain(QMainWindow): def __init__(self): super().__init__() self.datatxt = () self.datacsv = () self.init_ui() def init_ui(self): # Set a menubar bar = self.menuBar() # Append bars to Menu file = bar.addMenu('File') run = bar.addMenu('Run') info = bar.addMenu('Info') # Create Actions and Shortcuts # File Actions new_menu = file.addMenu('New') new_csv_action = QAction('CSV file', self) new_txt_action = QAction('TXT file', self) save_action = QAction('&Save', self) save_action.setShortcut('Ctrl+S') open_action = QAction('&Open', self) quit_action = QAction('&Quit', self) # Run Actions BLUP_action = QAction('BLUP', self) # Info Actions how_to_action = QAction('Help', self) about_us_action = QAction('About us!', self) license_action = QAction('License', self) # Adding Actions into bars created # File Actions new_menu.addAction(new_csv_action) new_menu.addAction(new_txt_action) file.addAction(save_action) file.addAction(open_action) file.addSeparator() file.addAction(quit_action) # Run Actions run.addAction(BLUP_action) # Info Actions info.addAction(how_to_action) info.addAction(license_action) info.addAction(about_us_action) # What Actions would do quit_action.triggered.connect(self.quit_trigger) file.triggered.connect(self.respond) run.triggered.connect(self.respondrun) info.triggered.connect(self.respondinfo) self.setWindowTitle('PredoBreed') self.resize(1400, 800) self.show() def quit_trigger(self): reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: qApp.quit() else: pass def respondrun(self, q): signal = q.text() if signal == 'BLUP': self.cal_widget = Calculations() self.setCentralWidget(self.cal_widget) if self.signal == 'txt': self.cal_widget.onlyshow(self.signal, self.txt_widget.datatxt, self.path) elif self.signal == 'csv': self.cal_widget.onlyshow(self.signal, self.csv_widget.datacsv, self.path) def respond(self, q): signal = q.text() if signal == 'CSV file': self.signal = 'csv' self.csv_widget = PredoBreedCSV(10000, 10) self.setCentralWidget(self.csv_widget) self.csv_widget.new_sheet() elif signal == 'TXT file': self.signal = 'txt' self.txt_widget = PredoBreedTXT() self.setCentralWidget(self.txt_widget) self.txt_widget.new_text() elif signal == '&Open': self.open_text() elif signal == '&Save': self.save_text() def respondinfo(self, q): signal = q.text() self.lic_widget = PredoBreedInfo() self.setCentralWidget(self.lic_widget) if signal == 'License': self.lic_widget.license() elif signal == 'About us!': self.lic_widget.about_us() elif signal == 'Help': self.lic_widget.help() def open_text(self): path = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME')) self.path = path if path[0][-3:] == 'txt': self.signal = 'txt' self.txt_widget = PredoBreedTXT() self.setCentralWidget(self.txt_widget) self.txt_widget.open_text(path) elif path[0][-3:] == 'csv': self.signal = 'csv' self.csv_widget = PredoBreedCSV(10, 10) self.setCentralWidget(self.csv_widget) self.csv_widget.open_sheet(path) elif path[0][-3:] != 'csv' and path[0][-3:] != 'txt' and path[0] != '': reply = QMessageBox.question( self, 'File extension', "File should have .csv or .txt extension, want to open other file?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.open_text() else: pass else: pass def save_text(self): if self.signal == 'txt': self.txt_widget.save_text() if self.signal == 'csv': self.csv_widget.save_sheet() else: pass
if __name__ == '__main__': params = Params(mu=3, lambda1=.5, lambda2=1, servers_number=4, fragments_numbers=[3, 2], queues_capacities=[10, 30]) print("Dependence on the arrival flow rates:") rate_dep = RateDependency() for i, lam1 in enumerate(rate_dep.lambdas): for j, lam2 in enumerate(rate_dep.lambdas): params.lambda1 = lam1 params.lambda2 = lam2 calculations = Calculations(params) calculations.calculate(strategy) print( f"measures for {calculations} \n{calculations.performance_measures}" ) rate_dep.response_time[ i, j] = calculations.performance_measures.response_time rate_dep.response_time1[ i, j] = calculations.performance_measures.response_time1 rate_dep.response_time2[ i, j] = calculations.performance_measures.response_time2 rate_dep.failure_prob[ i, j] = calculations.performance_measures.failure_probability
def __init__(self): self.data = [] self.tax_rate = .35 self.calculations = Calculations()
class PrintStatements(object): def __init__(self): self.data = [] self.tax_rate = .35 self.calculations = Calculations() def run(self, account_info, chart_of_accounts): self.menu() while True: user_input = input("Please choose an option") if user_input == "1": self.option_one(account_info, chart_of_accounts) elif user_input == "2": self.option_two(account_info, chart_of_accounts) elif user_input == "3": self.option_three(account_info, chart_of_accounts) elif user_input == "4": self.option_four(account_info, chart_of_accounts) elif user_input == "5": pass # Print Statement of Cash Flows elif user_input == "6": self.option_six() elif user_input == "7": break else: self.menu() @staticmethod def menu(): print("Main Menu:") print("1 - View Chart of Accounts") print("2 - Add an Entry") print("3 - Print Balance Sheet") print("4 - Print Income Statement") print("5 - Print Statement of Cash Flows") print("6 - View Entries") print("7 - Re-configure Account") @staticmethod def option_one(company_name, chart_of_accounts): if chart_of_accounts == []: print("") print("No Chart of Accounts Available!") else: print("---------------------------------------") print("{} - {} - {} - {}".format("Account #", "Account Name", "Account Type", "Account Balance")) print("") for account in chart_of_accounts: print("{} - {} - {} - ${}".format( account.acc_num, account.acc_name, account.acc_type, round(account.acc_balance, 2))) print("---------------------------------------") def option_two(self, company_name: str, chart_of_accounts: List[Account]) -> int: while True: print("Debit or Credit? Type \"D\" for Debit or \"C\" for Credit") deb_or_cred = input("") if deb_or_cred.upper() == "D": entry_type = "DEBIT" elif deb_or_cred.upper() == "C": entry_type = "CREDIT" else: print("Not an option. Next time follow instructions.") break print("Which Account does it go in?") for account in chart_of_accounts: print(f'{account.acc_name}') entry_account = input("") entry_amount = input("What is the amount?") entry_day = input("What is the day of the transaction?") entry_month = input("Month?") entry_year = input("Year?") for account in chart_of_accounts: if account.acc_name == entry_account: if account.acc_type == "Asset" or account.acc_type == "Expense": if entry_type == "DEBIT": account.acc_balance += float(entry_amount) elif entry_type == "CREDIT": account.acc_balance -= float(entry_amount) elif account.acc_type == "Liability" or account.acc_type == "Equity" or account.acc_type == "Income": if entry_type == "DEBIT": account.acc_balance -= float(entry_amount) elif entry_type == "CREDIT": account.acc_balance += float(entry_amount) print(entry_type) print(entry_amount) print(entry_account.upper()) print("{}-{}-{}".format(entry_month, entry_day, entry_year)) entry_date = datetime.datetime.now() self.data.append( Entry(type=entry_type, amount=float(entry_amount), account=entry_account.upper(), day=entry_day, month=entry_month, year=entry_year, entry_date=entry_date.date())) entry_diff = self.calculations.total_debs_and_creds((self.data)) if entry_diff != 0: print( "Debits and Credits do not equal, add another entry? (The difference is {})" .format(entry_diff)) another_entry = input("Do you want to add more entries? Y/N") if another_entry.upper() == "Y": print("") elif another_entry.upper() == "N": break else: print("Wrong answer") break else: break def option_three(self, company_name, chart_of_accounts): print("") print("2018 Year End Balance Sheet for {}".format(company_name)) print("Balance Sheet as of March 31, 2018") print("------------------------------") print("Assets:") for account in chart_of_accounts: if account.acc_type == "Asset": print( f'{account.acc_name}: ${round(account.acc_balance, 2)}') print("-------------------") print("Total Assets: ${}".format( self.calculations.total_assets(chart_of_accounts))) print("") print("Liabilities:") for account in chart_of_accounts: if account.acc_type == "Liability": print( f'{account.acc_name}: ${round(account.acc_balance, 2)}') print("") print("Equity:") for account in chart_of_accounts: if account.acc_type == "Equity" and account.acc_name != "Retained Earnings": print( f'{account.acc_name}: ${round(account.acc_balance, 2)}') print( f"Retained Earnings: ${self.calculations.retained_earnings(chart_of_accounts)}" ) print("-------------------") print("Total Liabilities and Owners Equity: ${}".format( self.calculations.total_equity(chart_of_accounts) + self.calculations.total_liabilities(chart_of_accounts))) print("------------------------------") print("") def option_four(self, company_name, chart_of_accounts): print("2018 Income Statement for {}".format(company_name)) print("------------------------------") print("Income:") for account in chart_of_accounts: if account.acc_name == "Sales Revenue": print( f'{account.acc_name}: ${round(account.acc_balance, 2)}') elif account.acc_name == "Cost of Goods Sold": print( f'{account.acc_name}: ${round(account.acc_balance, 2)}') print( f'Gross Margin: ${self.calculations.gross_margin(chart_of_accounts)}' ) print("-------------------") print("Operating Expenses:") for account in chart_of_accounts: if account.acc_type == "Expense" and account.acc_name != "Cost of Goods Sold": print( f'{account.acc_name}: ${round(account.acc_balance, 2)}') print( f"Income Before Taxes: ${self.calculations.income_before_taxes(chart_of_accounts)}" ) print("Tax Expense: ${}".format( self.calculations.tax_expense(chart_of_accounts, self.tax_rate))) print("") print("Net Income: ${}".format( self.calculations.net_income(chart_of_accounts, self.tax_rate))) print("------------------------------") def option_six(self): if self.data == []: print("No Entries Available!") else: print("How would you like them Sorted?") print("1 - by date entered") print("2 - by amount") user_input = input("") if user_input == "1": for entry in self.data: print(" Date: {}-{}-{} Type: {} Amount: {} Account: {}". format(entry.month, entry.day, entry.year, entry.type, entry.amount, entry.account_id)) elif user_input == "2": sorted_amount_list = sorted(self.data, key=lambda Entry: Entry.amount, reverse=False) for entry in sorted_amount_list: print(" Date: {}-{}-{} Type: {} Amount: {} Account: {}". format(entry.month, entry.day, entry.year, entry.type, entry.amount, entry.account_id))
from calculations import Calculations while True: calculation = input("Calculator : ") try: result = Calculations.calculate(calculation) print(result) except: print('Error')
def test_date_range(self): june_transactions = self.q.get_transactions_by_range('53',3,6) qs = Calculations(june_transactions) assert qs.date_range().__class__ == list
def test_summary(self): june_transactions = self.q.get_transactions_by_range('53',3,6) qs = Calculations(june_transactions) assert qs.summary().__class__ == pandas.core.frame.DataFrame
from pprint import pprint from calculations import Calculations from network_params import Params from performance_measures_storage import PerformanceMeasuresStorage from states_policy import StatesPolicy from states_policy import get_policed_states, get_strategy if __name__ == '__main__': params = Params(mu=3, lambda1=.5, lambda2=1, servers_number=5, fragments_numbers=[2, 3], queues_capacities=[1, 1]) calculations = Calculations(params) all_states = calculations.get_all_states() states_with_policy = get_policed_states(all_states, params) print("All states where policy is possible:") pprint(states_with_policy) strategies = get_strategy(states_with_policy) states_policy = StatesPolicy(tuple(), states_with_policy, params) states_policy.print_adjacent_states() storage = PerformanceMeasuresStorage() print() for strategy in strategies: states_policy.strategy = strategy
class InvestmentPlan: # Pre-processed data for model construction data = ModelData() # Common model components to investment plan and operating sub-problems (sets) components = CommonComponents() # Object used to perform common calculations. E.g. discount factors. calculations = Calculations() def __init__(self): # Solver options self.keepfiles = False self.solver_options = {} # 'MIPGap': 0.0005 self.opt = SolverFactory('cplex', solver_io='mps') def define_sets(self, m): """Define investment plan sets""" pass def define_parameters(self, m): """Investment plan model parameters""" def solar_build_limits_rule(_m, z): """Solar build limits for each NEM zone""" return float( self.data.candidate_unit_build_limits_dict[z]['SOLAR']) # Maximum solar capacity allowed per zone m.SOLAR_BUILD_LIMITS = Param(m.Z, rule=solar_build_limits_rule) def wind_build_limits_rule(_m, z): """Wind build limits for each NEM zone""" return float(self.data.candidate_unit_build_limits_dict[z]['WIND']) # Maximum wind capacity allowed per zone m.WIND_BUILD_LIMITS = Param(m.Z, rule=wind_build_limits_rule) def storage_build_limits_rule(_m, z): """Storage build limits for each NEM zone""" return float( self.data.candidate_unit_build_limits_dict[z]['STORAGE']) # Maximum storage capacity allowed per zone m.STORAGE_BUILD_LIMITS = Param(m.Z, rule=storage_build_limits_rule) def candidate_unit_build_costs_rule(_m, g, y): """ Candidate unit build costs [$/MW] Note: build cost in $/MW. May need to scale if numerical conditioning problems. """ if g in m.G_C_STORAGE: return float(self.data.battery_build_costs_dict[y][g] * 1000) else: return float( self.data.candidate_units_dict[('BUILD_COST', y)][g] * 1000) # Candidate unit build cost m.I_C = Param(m.G_C, m.Y, rule=candidate_unit_build_costs_rule) def candidate_unit_life_rule(_m, g): """Asset life of candidate units [years]""" # TODO: Use data from NTNPD. Just making an assumption for now. return float(25) # Candidate unit life m.A = Param(m.G_C, rule=candidate_unit_life_rule) def amortisation_rate_rule(_m, g): """Amortisation rate for a given investment""" # Numerator for amortisation rate expression num = self.data.WACC * ((1 + self.data.WACC)**m.A[g]) # Denominator for amortisation rate expression den = ((1 + self.data.WACC)**m.A[g]) - 1 # Amortisation rate amortisation_rate = num / den return amortisation_rate # Amortisation rate for a given investment m.GAMMA = Param(m.G_C, rule=amortisation_rate_rule) def discount_factor_rule(_m, y): """Discount factor for each year in model horizon""" return self.calculations.discount_factor(y, m.Y.first()) # Discount factor m.DISCOUNT_FACTOR = Param(m.Y, rule=discount_factor_rule) def fixed_operations_and_maintenance_cost_rule(_m, g): """Fixed FOM cost [$/MW/year] Note: Data in NTNDP is in terms of $/kW/year. Must multiply by 1000 to convert to $/MW/year """ if g in m.G_E: return float( self.data.existing_units_dict[('PARAMETERS', 'FOM')][g] * 1000) elif g in m.G_C_THERM.union(m.G_C_WIND, m.G_C_SOLAR): return float( self.data.candidate_units_dict[('PARAMETERS', 'FOM')][g] * 1000) elif g in m.G_STORAGE: # TODO: Need to find reasonable FOM cost for storage units - setting = MEL-WIND for now return float( self.data.candidate_units_dict[('PARAMETERS', 'FOM')]['MEL-WIND'] * 1000) else: raise Exception(f'Unexpected generator encountered: {g}') # Fixed operations and maintenance cost m.C_FOM = Param(m.G, rule=fixed_operations_and_maintenance_cost_rule) # Weighted cost of capital - interest rate assumed in discounting + amortisation calculations m.WACC = Param(initialize=float(self.data.WACC)) # Candidate capacity dual variable obtained from sub-problem solution. Updated each iteration. m.PSI_FIXED = Param(m.G_C, m.Y, m.S, initialize=0, mutable=True) # Lower bound for Benders auxiliary variable m.ALPHA_LOWER_BOUND = Param(initialize=float(-10e9)) return m @staticmethod def define_variables(m): """Define investment plan variables""" # Investment in each time period m.x_c = Var(m.G_C, m.Y, within=NonNegativeReals, initialize=0) # Binary variable to select capacity size m.d = Var(m.G_C_THERM, m.Y, m.G_C_THERM_SIZE_OPTIONS, within=Binary, initialize=0) # Auxiliary variable - total capacity available at each time period m.a = Var(m.G_C, m.Y, initialize=0) # Auxiliary variable - gives lower bound for subproblem solution m.alpha = Var() return m def define_expressions(self, m): """Define investment plan expressions""" def investment_cost_rule(_m, y): """Total amortised investment cost for a given year [$]""" return sum(m.GAMMA[g] * m.I_C[g, y] * m.x_c[g, y] for g in m.G_C) # Investment cost in a given year m.INV = Expression(m.Y, rule=investment_cost_rule) def fom_cost_rule(_m, y): """Total fixed operations and maintenance cost for a given year (not discounted)""" # FOM costs for candidate units candidate_fom = sum(m.C_FOM[g] * m.a[g, y] for g in m.G_C) # FOM costs for existing units - note no FOM cost paid if unit retires existing_fom = sum(m.C_FOM[g] * m.P_MAX[g] * (1 - m.F[g, y]) for g in m.G_E) # Expression for total FOM cost total_fom = candidate_fom + existing_fom return total_fom # Fixed operating cost for candidate existing generators for each year in model horizon m.FOM = Expression(m.Y, rule=fom_cost_rule) def total_fom_cost_rule(_m): """Total discounted FOM cost over all years in model horizon""" return sum(m.DISCOUNT_FACTOR[y] * m.FOM[y] for y in m.Y) # Total discounted FOM cost over model horizon m.FOM_TOTAL = Expression(rule=total_fom_cost_rule) def total_fom_end_of_horizon_rule(_m): """FOM cost assumed to propagate beyond end of model horizon""" # Assumes discounted FOM cost in final year paid in perpetuity total_cost = (m.DISCOUNT_FACTOR[m.Y.last()] / m.WACC) * m.FOM[m.Y.last()] return total_cost # Accounting for FOM beyond end of model horizon (EOH) m.FOM_EOH = Expression(rule=total_fom_end_of_horizon_rule) def total_investment_cost_rule(_m): """Total discounted amortised investment cost""" # Total discounted amortised investment cost total_cost = sum( (m.DISCOUNT_FACTOR[y] / m.WACC) * m.INV[y] for y in m.Y) return total_cost # Total investment cost m.INV_TOTAL = Expression(rule=total_investment_cost_rule) # Total discounted investment and FOM cost (taking into account costs beyond end of model horizon) m.TOTAL_PLANNING_COST = Expression(expr=m.FOM_TOTAL + m.FOM_EOH + m.INV_TOTAL) return m @staticmethod def define_constraints(m): """Define feasible investment plan constraints""" def discrete_thermal_size_rule(_m, g, y): """Discrete sizing rule for candidate thermal units""" # Discrete size options for candidate thermal units size_options = {0: 0, 1: 100, 2: 400, 3: 400} return m.x_c[g, y] - sum(m.d[g, y, n] * float(size_options[n]) for n in m.G_C_THERM_SIZE_OPTIONS) == 0 # Discrete investment size for candidate thermal units m.DISCRETE_THERMAL_SIZE = Constraint(m.G_C_THERM, m.Y, rule=discrete_thermal_size_rule) def single_discrete_selection_rule(_m, g, y): """Can only select one size option per investment period""" return sum(m.d[g, y, n] for n in m.G_C_THERM_SIZE_OPTIONS) - float(1) == 0 # Single size selection constraint per investment period m.SINGLE_DISCRETE_SELECTION = Constraint( m.G_C_THERM, m.Y, rule=single_discrete_selection_rule) def total_capacity_rule(_m, g, y): """Total installed capacity in a given year""" return m.a[g, y] - sum(m.x_c[g, j] for j in m.Y if j <= y) == 0 # Total installed capacity for each candidate technology type at each point in model horizon m.TOTAL_CAPACITY = Constraint(m.G_C, m.Y, rule=total_capacity_rule) def solar_build_limits_cons_rule(_m, z, y): """Enforce solar build limits in each NEM zone""" # Solar generators belonging to zone 'z' gens = [g for g in m.G_C_SOLAR if g.split('-')[0] == z] if gens: return sum(m.a[g, y] for g in gens) - m.SOLAR_BUILD_LIMITS[z] <= 0 else: return Constraint.Skip # Storage build limit constraint for each NEM zone m.SOLAR_BUILD_LIMIT_CONS = Constraint( m.Z, m.Y, rule=solar_build_limits_cons_rule) def wind_build_limits_cons_rule(_m, z, y): """Enforce wind build limits in each NEM zone""" # Wind generators belonging to zone 'z' gens = [g for g in m.G_C_WIND if g.split('-')[0] == z] if gens: return sum(m.a[g, y] for g in gens) - m.WIND_BUILD_LIMITS[z] <= 0 else: return Constraint.Skip # Wind build limit constraint for each NEM zone m.WIND_BUILD_LIMIT_CONS = Constraint(m.Z, m.Y, rule=wind_build_limits_cons_rule) def storage_build_limits_cons_rule(_m, z, y): """Enforce storage build limits in each NEM zone""" # Storage generators belonging to zone 'z' gens = [g for g in m.G_C_STORAGE if g.split('-')[0] == z] if gens: return sum(m.a[g, y] for g in gens) - m.STORAGE_BUILD_LIMITS[z] <= 0 else: return Constraint.Skip # Storage build limit constraint for each NEM zone m.STORAGE_BUILD_LIMIT_CONS = Constraint( m.Z, m.Y, rule=storage_build_limits_cons_rule) # Bound on Benders decomposition lower-bound variable m.ALPHA_LOWER_BOUND_CONS = Constraint( expr=m.alpha >= m.ALPHA_LOWER_BOUND) # Container for benders cuts m.BENDERS_CUTS = ConstraintList() return m @staticmethod def define_objective(m): """Define objective function""" def objective_function_rule(_m): """Investment plan objective function""" # Objective function objective_function = m.TOTAL_PLANNING_COST + m.alpha return objective_function # Investment plan objective function m.OBJECTIVE = Objective(rule=objective_function_rule, sense=minimize) return m def construct_model(self): """Construct investment plan model""" # Initialise model object m = ConcreteModel() # Prepare to import dual variables m.dual = Suffix(direction=Suffix.IMPORT) # Define sets m = self.components.define_sets(m) # Define parameters common to all sub-problems m = self.components.define_parameters(m) # Define parameters m = self.define_parameters(m) # Define variables m = self.define_variables(m) # Define expressions m = self.define_expressions(m) # Define constraints m = self.define_constraints(m) # Define objective m = self.define_objective(m) return m def solve_model(self, m): """Solve model instance""" # Solve model self.opt.solve(m, tee=False, options=self.solver_options, keepfiles=self.keepfiles) # Log infeasible constraints if they exist log_infeasible_constraints(m) return m def get_cut_component(self, m, iteration, year, scenario, investment_solution_dir, uc_solution_dir): """Construct cut component""" # Discount factor discount = self.calculations.discount_factor(year, base_year=2016) # Duration duration = self.calculations.scenario_duration_days(year, scenario) with open( os.path.join( uc_solution_dir, f'uc-results_{iteration}_{year}_{scenario}.pickle'), 'rb') as f: uc_result = pickle.load(f) with open( os.path.join(investment_solution_dir, f'investment-results_{iteration}.pickle'), 'rb') as f: inv_result = pickle.load(f) # Construct cut component cut = discount * duration * sum( uc_result['PSI_FIXED'][g] * (m.a[g, year] - inv_result['a'][(g, year)]) for g in m.G_C) return cut def get_benders_cut(self, m, iteration, investment_solution_dir, uc_solution_dir): """Construct a Benders optimality cut""" # Cost accounting for total operating cost for each scenario over model horizon scenario_cost = self.calculations.get_total_discounted_operating_scenario_cost( iteration, uc_solution_dir) # Cost account for operating costs beyond end of model horizon scenario_cost_eoh = self.calculations.get_end_of_horizon_operating_cost( m, iteration, uc_solution_dir) # Total (fixed) cost to include in Benders cut total_cost = scenario_cost + scenario_cost_eoh # Cut components containing dual variables cut_components = sum( self.get_cut_component(m, iteration, y, s, investment_solution_dir, uc_solution_dir) for y in m.Y for s in m.S) # Benders cut cut = m.alpha >= total_cost + cut_components return cut def add_benders_cut(self, m, iteration, investment_solution_dir, uc_solution_dir): """Update model parameters""" # Construct Benders optimality cut cut = self.get_benders_cut(m, iteration, investment_solution_dir, uc_solution_dir) # Add Benders cut to constraint list m.BENDERS_CUTS.add(expr=cut) return m @staticmethod def fix_binary_variables(m): """Fix all binary variables""" for g in m.G_C_THERM: for y in m.Y: for n in m.G_C_THERM_SIZE_OPTIONS: # Fix binary variables related to discrete sizing decision for candidate thermal units m.d[g, y, n].fix() return m @staticmethod def unfix_binary_variables(m): """Unfix all binary variables""" for g in m.G_C_THERM: for y in m.Y: for n in m.G_C_THERM_SIZE_OPTIONS: # Unfix binary variables related to discrete sizing decision for candidate thermal units m.d[g, y, n].unfix() return m @staticmethod def save_solution(m, iteration, investment_solution_dir): """Save model solution""" # Save investment plan output = { 'a': m.a.get_values(), 'x_c': m.x_c.get_values(), 'OBJECTIVE': m.OBJECTIVE.expr() } # Save investment plan results with open( os.path.join(investment_solution_dir, f'investment-results_{iteration}.pickle'), 'wb') as f: pickle.dump(output, f) @staticmethod def initialise_investment_plan(m, iteration, solution_dir): """Initial values for investment plan - used in first iteration. Assume candidate capacity = 0""" # Feasible investment plan for first iteration plan = { 'a': {(g, y): float(0) for g in m.G_C for y in m.Y}, 'x_c': {(g, y): float(0) for g in m.G_C for y in m.Y}, 'OBJECTIVE': -1e9 } # Save investment plan with open( os.path.join(solution_dir, f'investment-results_{iteration}.pickle'), 'wb') as f: pickle.dump(plan, f) return plan
from Initialize_API import InitializeAPI from check import Check from calculations import Calculations from trade import Trade import time ## To Configureclient ## Only Works for BTC # To initialize API client = InitializeAPI() # Set Classes Trade = Trade(client) Cal = Calculations(client) Check = Check(client) def main(amountPercentage, altCoin, profitPercent, lossPercent): # SUPPORT BTC ONLY defaultCoin = "BTC" # Check BTC Balance balance = Check.CheckBalance(defaultCoin) exchange = altCoin + defaultCoin # Need to convert to count the no. of quantity to BUY since its required for the API estimatedquantity = Cal.ConvertToQuantityBaseOnMarket(
def request_to_response(self) -> list: # Jeśli są żadania, bierzemy pierwsze w kolejności i przetwarzamy je if not self.request_queue.empty(): request: Header = self.request_queue.get() # Obsługujemy wymagane błędy przepełnienia try: # Potwierdzamy utworzenie sesji if request.operation == Operation.CONNECTING: request.status = Status.OK elif request.operation == Operation.MODULO: request.a = Calculations.modulo(request.a, request.b) request.status = Status.OUTPUT request.b = None elif request.operation == Operation.MULTIPLY: request.a = Calculations.multiply(request.a, request.b) request.status = Status.OUTPUT request.b = None elif request.operation == Operation.RANDOM: request.a = Calculations.randomint_between( request.a, request.b) request.status = Status.OUTPUT request.b = None elif request.operation == Operation.ADD: request.a = Calculations.add(request.a, request.b) request.status = Status.OUTPUT request.b = None # Przyjmujemy naraz operacje sortowania w obie strony i obie flagi sortowania elif request.operation == Operation.SORT_A or request.operation == Operation.SORT_D: if request.status == Status.SENDING or request.status == Status.LAST: self.numbers_to_sort.append(request.a) last_sort = False sorted_nums = [] if request.operation == Operation.SORT_A: sorted_nums = Calculations.sort( self.numbers_to_sort) else: sorted_nums = Calculations.sort( self.numbers_to_sort, reverse=True) if request.status == Status.LAST: self.numbers_to_sort = [] last_sort = True request.status = Status.SENDING request.b = None request.timestamp = Header.create_timestamp() # Z posortowanych liczb tworzymy listę odpowiedzi message_list = [] for num in sorted_nums: request.a = num message_list.append(dc(request)) if last_sort: message_list[-1].status = Status.LAST return [(msg.to_send(), self.receiver_addr) for msg in message_list] except: self.numbers_to_sort = [] request.status = Status.ERROR request.a = Status.ERROR request.b = None # Wynik działań poza sortowaniem zwracamy tym samym sposobem request.timestamp = Header.create_timestamp() return [(request.to_send(), self.receiver_addr)]
def example1(lambdas, queue_id): storage = PerformanceMeasuresStorage() for lambd in lambdas: params = Params( mu=3, lambda1=lambd, lambda2=lambd, servers_number=5, fragments_numbers=[2, 3], queues_capacities=[3, 3], ) all_states = get_all_states(params) states_with_policy = get_policed_states(all_states, params) selected_policy_vector = [queue_id] * len(states_with_policy) policy = Policy(selected_policy_vector, states_with_policy, params) calculations = Calculations(params) calculations.calculate(policy) performance_measures = calculations.performance_measures print(performance_measures, "\n") storage.append(lambd, performance_measures) print(storage) print() storage.show_difference() plt.title("Зависимость T от интенсивности входящего потока") plt.xlabel("lambdas") plt.ylabel("T") plt.grid() plt.plot(lambdas, storage.response_times, "g", linewidth=2, markersize=12) plt.show() plt.title("Зависимость T1 и T2 от интенсивности входящего потока") plt.xlabel("lambdas") plt.ylabel("T") plt.grid() plt.plot(lambdas, storage.response_times1, "g", label="T1", linewidth=2, markersize=12) plt.plot(lambdas, storage.response_times2, "b", label="T2", linewidth=2, markersize=12) plt.legend() plt.show() plt.title("Зависимость pf от интенсивности входящего потока") plt.xlabel("lambdas") plt.ylabel("pf") plt.grid() plt.plot(lambdas, storage.blocked_all_queues_probability, "b", linewidth=2, markersize=12) plt.show() plt.title("Зависимость pf1 и pf2 от интенсивности входящего потока") plt.xlabel("lambdas") plt.ylabel("pf") plt.grid() plt.plot( lambdas, storage.failure_probabilities1, "g", label="pf1", linewidth=2, markersize=12, ) plt.plot( lambdas, storage.failure_probabilities2, "b", label="pf2", linewidth=2, markersize=12, ) plt.legend() plt.show()
return True if __name__ == '__main__': argument = Arguments(args[1:]) argument.get_arguments() database = Database("exams_data.sqlite") if database.is_empty() and argument.first != "--get_data": print( "First, you have to fill database with data! Command: --get_data") sys.exit() database.close() if argument.first_command(): first_command = Calculations("exams_data.sqlite", argument.second, argument.third, argument.fourth) first_command.check_gender() first_command.joined() first_command.sum() first_command.average() first_command.print() first_command.close() elif argument.second_command(): second_command = Calculations("exams_data.sqlite", argument.second, argument.third, argument.fourth) second_command.check_gender() second_command.joined() second_command.passed() second_command.sum() second_command.percent_passed()
def test_just_junes_value_counts(self): june_transactions = self.q.get_transactions_by_range('53',6,6) qs = Calculations(june_transactions) assert qs.value_counts().__class__ == pandas.core.series.Series
from graphics import Graphics from calculations import Calculations from PyQt4 import QtGui from PyQt4 import QtCore gui = Graphics() calc = Calculations() class Calculator(): def createWindow(self): self._window = gui.newWidget("Calculator") def createDisplay(self): self._lcd = gui.createLCD() self.setDisplayStyle(self._lcd) def createProgression(self): self._label = gui.addLabel("") self._label.setFixedHeight(10) self._label.setFont(QtGui.QFont("Gill Sans MT", 10)) def createLayouts(self): self._box = gui.createBoxLayout() self._grid = gui.createGridLayout() def defineWindow(self):
def test_sum(self): june_transactions = self.q.get_transactions_by_range('53',6,6) qs = Calculations(june_transactions) assert qs.sum()