Giter Club home page Giter Club logo

codable-model-optimizer's Introduction

Documentation Status

codable-model-optimizer

Optimization problem meta-heuristics solver for easy modeling.

Installation

Use pip

$ pip install codableopt

Use setup.py

# Master branch
$ git clone https://github.com/recruit-tech/codable-model-optimizer
$ python3 setup.py install

Example Usage

Sample1

import numpy as np
from codableopt import *

# set problem
problem = Problem(is_max_problem=True)

# define variables
x = IntVariable(name='x', lower=np.double(0), upper=np.double(5))
y = DoubleVariable(name='y', lower=np.double(0.0), upper=None)
z = CategoryVariable(name='z', categories=['a', 'b', 'c'])


# define objective function
def objective_function(var_x, var_y, var_z, parameters):
    obj_value = parameters['coef_x'] * var_x + parameters['coef_y'] * var_y

    if var_z == 'a':
        obj_value += 10.0
    elif var_z == 'b':
        obj_value += 8.0
    else:
        # var_z == 'c'
        obj_value -= 3.0

    return obj_value


# set objective function and its arguments
problem += Objective(objective=objective_function,
                     args_map={'var_x': x,
                               'var_y': y,
                               'var_z': z,
                               'parameters': {'coef_x': -3.0, 'coef_y': 4.0}})

# define constraint
problem += 2 * x + 4 * y + 2 * (z == 'a') + 3 * (z == ('b', 'c')) <= 8
problem += 2 * x - y + 2 * (z == 'b') > 3

print(problem)

solver = OptSolver()

# generate optimization methods to be used within the solver
method = PenaltyAdjustmentMethod(steps=40000)

answer, is_feasible = solver.solve(problem, method)
print(f'answer:{answer}, answer_is_feasible:{is_feasible}')

Sample2

import random
from itertools import combinations

from codableopt import Problem, Objective, CategoryVariable, OptSolver, PenaltyAdjustmentMethod


# define distance generating function
def generate_distances(args_place_names):
    generated_distances = {}
    for point_to_point in combinations(['start'] + args_place_names, 2):
        distance_value = random.randint(20, 40)
        generated_distances[point_to_point] = distance_value
        generated_distances[tuple(reversed(point_to_point))] = distance_value
    for x in ['start'] + args_place_names:
        generated_distances[(x, x)] = 0

    return generated_distances


# generate TSP problem
PLACE_NUM = 30
destination_names = [f'destination_{no}' for no in range(PLACE_NUM)]
place_names = [f'P{no}' for no in range(PLACE_NUM)]
distances = generate_distances(place_names)
destinations = [CategoryVariable(name=destination_name, categories=place_names)
                for destination_name in destination_names]

# set problem
problem = Problem(is_max_problem=False)


# define objective function
def calc_distance(var_destinations, para_distances):
    return sum([para_distances[(x, y)] for x, y in zip(
        ['start'] + var_destinations, var_destinations + ['start'])])


# set objective function and its arguments
problem += Objective(objective=calc_distance,
                     args_map={'var_destinations': destinations, 'para_distances': distances})

# define constraint
# constraint formula that always reaches all points at least once
for place_name in place_names:
    problem += sum([(destination == place_name) for destination in destinations]) >= 1

# optimization implementation
solver = OptSolver(round_times=4, debug=True, debug_unit_step=1000)
method = PenaltyAdjustmentMethod(steps=10000, delta_to_update_penalty_rate=0.9)
answer, is_feasible = solver.solve(problem, method, n_jobs=-1)

print(f'answer_is_feasible:{is_feasible}')
root = ['start'] + [answer[root] for root in destination_names] + ['start']
print(f'root: {" -> ".join(root)}')

codable-model-optimizer's People

Contributors

kotarotanahashi avatar tomomotofactory avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codable-model-optimizer's Issues

KeyError of _non_zero_coefficients_index_dict

KeyError occurs when I execute the following script.

  • MacOS v12.5.1
  • Python v3.9.13
  • codable-model-optimizer v0.1.3

script

from codableopt import *

# set problem
problem = Problem()

# define variables
n = 10
x = [DoubleVariable(name=f"x{i}") for i in range(10)]

# define objective function
def obj_func(x):
    print(x)
    return sum(x[i] * x[i] for i in range(n))

# set objective function and its arguments
problem += Objective(obj_func, args_map={'x': x})

solver = OptSolver()

# generate optimization methods to be used within the solver
method = PenaltyAdjustmentMethod(steps=40000)

answer, is_feasible = solver.solve(problem, method)
print(f'answer:{answer}, answer_is_feasible:{is_feasible}')

error

Traceback (most recent call last):
  File "/Users/hoge/cob_tmp.py", line 22, in <module>
    answer, is_feasible = solver.solve(problem, method)
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/opt_solver.py", line 88, in solve
    answer, is_feasible = opt_solver.solve(
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/optimizer/optimization_solver.py", line 85, in solve
    state = OptimizationSolver.__optimize(
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/optimizer/optimization_solver.py", line 151, in __optimize
    return optimizer.optimize(debug, debug_step_unit)
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/optimizer/optimizer.py", line 80, in optimize
    proposed_move_list = self._method.propose(self._state, step)
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/optimizer/method/penalty_adjustment_method.py", line 100, in propose
    self._proposal_list = variable.propose_low_penalty_move(state)
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/formulation/variable/solver_double_variable.py", line 58, in propose_low_penalty_move
    lower, upper = state.problem.constraints.liner_constraints.calc_var_range_in_feasible(
  File "/usr/local/lib/python3.9/site-packages/codableopt/solver/formulation/constraint/solver_liner_constraints.py", line 152, in calc_var_range_in_feasible
    non_zero_indexes = self._non_zero_coefficients_index_dict[var_index]
KeyError: 9

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.