Metadata-Version: 2.4
Name: lumix-opt
Version: 0.1.0
Summary: A type-safe, IDE-friendly wrapper for optimization solvers with automatic data-driven modeling
Author-email: Tolga BERBER <tolga.berber@fen.ktu.edu.tr>, Beyzanur SİYAH <beyzanursiyah@ktu.edu.tr>
License: Academic Free License ("AFL") v. 3.0
        
        This Academic Free License (the "License") applies to any original work of
        authorship (the "Original Work") whose owner (the "Licensor") has placed the
        following licensing notice adjacent to the copyright notice for the Original Work:
        
        Licensed under the Academic Free License version 3.0
        
        1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free,
        non-exclusive, sublicensable license, for the duration of the copyright, to do
        the following:
        
        a) to reproduce the Original Work in copies, either alone or as part of a
        collective work;
        
        b) to translate, adapt, alter, transform, modify, or arrange the Original Work,
        thereby creating derivative works ("Derivative Works") based upon the Original
        Work;
        
        c) to distribute or communicate copies of the Original Work and Derivative Works
        to the public, under any license of your choice that does not contradict the
        terms and conditions, including Licensor's reserved rights and remedies, in this
        Academic Free License;
        
        d) to perform the Original Work publicly; and
        
        e) to display the Original Work publicly.
        
        2) Grant of Patent License. Licensor grants You a worldwide, royalty-free,
        non-exclusive, sublicensable license, under patent claims owned or controlled by
        the Licensor that are embodied in the Original Work as furnished by the
        Licensor, for the duration of the patents, to make, use, sell, offer for sale,
        have made, and import the Original Work and Derivative Works.
        
        3) Grant of Source Code License. The term "Source Code" means the preferred form
        of the Original Work for making modifications to it and all available
        documentation describing how to modify the Original Work. Licensor agrees to
        provide a machine-readable copy of the Source Code of the Original Work along
        with each copy of the Original Work that Licensor distributes. Licensor reserves
        the right to satisfy this obligation by placing a machine-readable copy of the
        Source Code in an information repository reasonably calculated to permit
        inexpensive and convenient access by You for as long as Licensor continues to
        distribute the Original Work.
        
        4) Exclusions From License Grant. Neither the names of Licensor, nor the names
        of any contributors to the Original Work, nor any of their trademarks or service
        marks, may be used to endorse or promote products derived from this Original
        Work without express prior permission of the Licensor. Except as expressly
        stated herein, nothing in this License grants any license to Licensor's
        trademarks, copyrights, patents, trade secrets or any other intellectual
        property. No patent license is granted to make, use, sell, offer for sale, have
        made, or import embodiments of any patent claims other than the licensed claims
        defined in Section 2. No license is granted to the trademarks of Licensor even
        if such marks are included in the Original Work. Nothing in this License shall
        be interpreted to prohibit Licensor from licensing under terms different from
        this License any Original Work that Licensor otherwise would have a right to
        license.
        
        5) External Deployment. The term "External Deployment" means the use,
        distribution, or communication of the Original Work or Derivative Works in any
        way such that the Original Work or Derivative Works may be used by anyone other
        than You, whether those works are distributed or communicated to those persons
        or made available as an application intended for use over a network. As an
        express condition for the grants of license hereunder, You must treat any
        External Deployment by You of the Original Work or a Derivative Work as a
        distribution under section 1(c).
        
        6) Attribution Rights. You must retain, in the Source Code of any Derivative
        Works that You create, all copyright, patent, or trademark notices from the
        Source Code of the Original Work, as well as any notices of licensing and any
        descriptive text identified therein as an "Attribution Notice." You must cause
        the Source Code for any Derivative Works that You create to carry a prominent
        Attribution Notice reasonably calculated to inform recipients that You have
        modified the Original Work.
        
        7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the
        copyright in and to the Original Work and the patent rights granted herein by
        Licensor are owned by the Licensor or are sublicensed to You under the terms of
        this License with the permission of the contributor(s) of those copyrights and
        patent rights. Except as expressly stated in the immediately preceding sentence,
        the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT
        WARRANTY, either express or implied, including, without limitation, the
        warranties of non-infringement, merchantability or fitness for a particular
        purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU.
        This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No
        license to the Original Work is granted by this License except under this
        disclaimer.
        
        8) Limitation of Liability. Under no circumstances and under no legal theory,
        whether in tort (including negligence), contract, or otherwise, shall the
        Licensor be liable to anyone for any indirect, special, incidental, or
        consequential damages of any character arising as a result of this License or
        the use of the Original Work including, without limitation, damages for loss of
        goodwill, work stoppage, computer failure or malfunction, or any and all other
        commercial damages or losses. This limitation of liability shall not apply to
        the extent applicable law prohibits such limitation.
        
        9) Acceptance and Termination. If, at any time, You expressly assented to this
        License, that assent indicates your clear and irrevocable acceptance of this
        License and all of its terms and conditions. If You distribute or communicate
        copies of the Original Work or a Derivative Work, You must make a reasonable
        effort under the circumstances to obtain the express assent of recipients to the
        terms of this License. This License conditions your rights to undertake the
        activities listed in Section 1, including your right to create Derivative Works
        based upon the Original Work, and doing so without honoring these terms and
        conditions is prohibited by copyright law and international treaty. Nothing in
        this License is intended to affect copyright exceptions and limitations
        (including "fair use" or "fair dealing"). This License shall terminate
        immediately and You may no longer exercise any of the rights granted to You by
        this License upon your failure to honor the conditions in Section 1(c).
        
        10) Termination for Patent Action. This License shall terminate automatically
        and You may no longer exercise any of the rights granted to You by this License
        as of the date You commence an action, including a cross-claim or counterclaim,
        against Licensor or any licensee alleging that the Original Work infringes a
        patent. This termination provision shall not apply for an action alleging patent
        infringement by combinations of the Original Work with other software or
        hardware.
        
        11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this
        License may be brought only in the courts of a jurisdiction wherein the Licensor
        resides or in which Licensor conducts its primary business, and under the laws
        of that jurisdiction excluding its conflict-of-law provisions. The application
        of the United Nations Convention on Contracts for the International Sale of
        Goods is expressly excluded. Any use of the Original Work outside the scope of
        this License or after its termination shall be subject to the requirements and
        penalties of copyright or patent law in the appropriate jurisdiction. This
        section shall survive the termination of this License.
        
        12) Attorneys' Fees. In any action to enforce the terms of this License or
        seeking damages relating thereto, the prevailing party shall be entitled to
        recover its costs and expenses, including, without limitation, reasonable
        attorneys' fees and costs incurred in connection with such action, including any
        appeal of such action. This section shall survive the termination of this
        License.
        
        13) Miscellaneous. If any provision of this License is held to be unenforceable,
        such provision shall be reformed only to the extent necessary to make it
        enforceable.
        
        14) Definition of "You" in This License. "You" throughout this License, whether
        in upper or lower case, means an individual or a legal entity exercising rights
        under, and complying with all of the terms of, this License. For legal entities,
        "You" includes any entity that controls, is controlled by, or is under common
        control with you. For purposes of this definition, "control" means (i) the
        power, direct or indirect, to cause the direction or management of such entity,
        whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or
        more of the outstanding shares, or (iii) beneficial ownership of such entity.
        
        15) Right to Use. You may use the Original Work in all ways not otherwise
        restricted or conditioned by this License or by law, and Licensor promises not
        to interfere with or be responsible for such uses by You.
        
        16) Modification of This License. This License is Copyright © 2005 Lawrence
        Rosen. Permission is granted to copy, distribute, or communicate this License
        without modification. Nothing in this License permits You to modify this License
        as applied to the Original Work or to Derivative Works. However, You may modify
        the text of this License and copy, distribute or communicate your modified
        version (the "Modified License") and apply it to other original works of
        authorship subject to the following conditions: (i) You may not indicate in any
        way that your Modified License is the "Academic Free License" or "AFL" and you
        may not use those names in the name of your Modified License; (ii) You must
        replace the notice specified in the first paragraph above with the notice
        "Licensed under <insert your license name here>" or with a notice of your own
        that is not confusingly similar to the notice in this License; and (iii) You may
        not claim that your original works are open source software unless your Modified
        License has been approved by Open Source Initiative (OSI) and You comply with
        its license review and certification process.
        
Project-URL: Homepage, https://github.com/lumix/lumix
Project-URL: Documentation, https://lumix.readthedocs.io
Project-URL: Repository, https://github.com/lumix/lumix
Project-URL: Issues, https://github.com/lumix/lumix/issues
Keywords: optimization,mathematical-programming,linear-programming,solver,ortools,gurobi,cplex,academic
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Academic Free License (AFL)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typing-extensions>=4.5.0
Requires-Dist: numpy>=1.24.0
Provides-Extra: ortools
Requires-Dist: ortools>=9.8.0; extra == "ortools"
Provides-Extra: gurobi
Requires-Dist: gurobipy>=11.0.0; extra == "gurobi"
Provides-Extra: cplex
Requires-Dist: cplex>=22.1.0; extra == "cplex"
Provides-Extra: glpk
Requires-Dist: swiglpk>=5.0.0; extra == "glpk"
Provides-Extra: orm
Requires-Dist: sqlalchemy>=2.0.0; extra == "orm"
Provides-Extra: all-solvers
Requires-Dist: ortools>=9.8.0; extra == "all-solvers"
Requires-Dist: gurobipy>=11.0.0; extra == "all-solvers"
Requires-Dist: cplex>=22.1.0; extra == "all-solvers"
Requires-Dist: swiglpk>=5.0.0; extra == "all-solvers"
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: mypy>=1.5.0; extra == "dev"
Requires-Dist: black>=23.7.0; extra == "dev"
Requires-Dist: ruff>=0.0.285; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=7.0.0; extra == "docs"
Requires-Dist: furo>=2024.1.0; extra == "docs"
Requires-Dist: sphinxcontrib-mermaid>=0.9.0; extra == "docs"
Requires-Dist: sphinx-autodoc-typehints>=1.25.0; extra == "docs"
Dynamic: license-file

<p align="center">
  <img src="docs/source/_static/Lumix_Logo_1024.png" alt="LumiX Logo" width="200"/>
</p>

# LumiX

[![Python Version](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-AFL--3.0-green.svg)](https://opensource.org/licenses/AFL-3.0)
[![Documentation](https://img.shields.io/badge/docs-latest-brightgreen.svg)](https://lumix.readthedocs.io)

**A modern, type-safe wrapper for optimization solvers with automatic data-driven modeling**

LumiX makes mathematical programming accessible, maintainable, and enjoyable by providing a unified, type-safe interface to multiple optimization solvers.

## ✨ Key Features

- 🎯 **Type-Safe & IDE-Friendly** — Full type hints and autocomplete support for a superior development experience
- 🔌 **Multi-Solver Support** — Seamlessly switch between OR-Tools, Gurobi, CPLEX, GLPK, and CP-SAT
- 📊 **Data-Driven Modeling** — Build models directly from your data with automatic indexing and mapping
- 🔄 **Automatic Linearization** — Automatically linearize non-linear constraints (bilinear, absolute value, piecewise)
- 📈 **Advanced Analysis** — Built-in sensitivity analysis, scenario analysis, and what-if analysis tools
- 🎯 **Goal Programming** — Native support for multi-objective optimization with priorities and weights
- ⚡ **ORM Integration** — Map solutions directly to your ORM models for seamless data flow

## 🚀 Quick Start

### Installation

```bash
# Install core library
pip install lumix

# Install with a solver (e.g., OR-Tools - free and open-source)
pip install lumix[ortools]

# Or install with multiple solvers
pip install lumix[ortools,gurobi,cplex]
```

### Simple Example

```python
from dataclasses import dataclass
from lumix import (
    LXModel,
    LXVariable,
    LXConstraint,
    LXLinearExpression,
    LXOptimizer,
)

# Define your data
@dataclass
class Product:
    id: str
    name: str
    profit: float
    resource_usage: float

products = [
    Product("A", "Product A", profit=30, resource_usage=2),
    Product("B", "Product B", profit=40, resource_usage=3),
]

# Define decision variables
production = (
    LXVariable[Product, float]("production")
    .continuous()
    .bounds(lower=0)
    .indexed_by(lambda p: p.id)
    .from_data(products)
)

# Build the model
model = (
    LXModel("production_plan")
    .add_variable(production)
    .maximize(
        LXLinearExpression()
        .add_term(production, lambda p: p.profit)
    )
)

# Add constraints
model.add_constraint(
    LXConstraint("resource_limit")
    .expression(
        LXLinearExpression()
        .add_term(production, lambda p: p.resource_usage)
    )
    .le()
    .rhs(100)  # Resource capacity
)

# Solve
optimizer = LXOptimizer().use_solver("ortools")
solution = optimizer.solve(model)

# Access results
if solution.is_optimal():
    print(f"Optimal profit: ${solution.objective_value:,.2f}")
    for product in products:
        qty = solution.variables["production"][product.id]
        print(f"Produce {qty:.2f} units of {product.name}")
```

## 🔧 Supported Solvers

LumiX provides a unified interface to multiple solvers:

| Solver | Linear | Integer | Quadratic | Advanced Features | License | Best For |
|--------|--------|---------|-----------|-------------------|---------|----------|
| **OR-Tools** | ✓ | ✓ | ✗ | SOS, Indicator | Apache 2.0 (Free) | General LP/MIP, Learning |
| **Gurobi** | ✓ | ✓ | ✓ | SOCP, PWL, Callbacks | Commercial/Academic | Large-scale, Production |
| **CPLEX** | ✓ | ✓ | ✓ | SOCP, PWL, Callbacks | Commercial/Academic | Large-scale, Production |
| **GLPK** | ✓ | ✓ | ✗ | Basic | GPL (Free) | Small problems, Teaching |
| **CP-SAT** | ✗ | ✓ | ✗ | Constraint Programming | Apache 2.0 (Free) | Scheduling, Assignment |

### Switching Solvers

```python
# Just change one line to switch solvers
optimizer = LXOptimizer().use_solver("ortools")   # Free
optimizer = LXOptimizer().use_solver("gurobi")    # Requires license
optimizer = LXOptimizer().use_solver("cplex")     # Requires license
optimizer = LXOptimizer().use_solver("glpk")      # Free
optimizer = LXOptimizer().use_solver("cpsat")     # Free
```

## 📚 Core Capabilities

### Variables with Automatic Indexing

```python
# Single-dimension indexing
production = (
    LXVariable[Product, float]("production")
    .continuous()
    .indexed_by(lambda p: p.id)
    .from_data(products)
)

# Multi-dimension indexing
from lumix import LXCartesianProduct

assignment = (
    LXVariable[tuple[Driver, Date, Shift], int]("assignment")
    .binary()
    .indexed_by(lambda t: (t[0].id, t[1].id, t[2].id))
    .from_data(LXCartesianProduct(drivers, dates, shifts))
)
```

### Type-Safe Expressions

```python
# Linear expressions with automatic coefficient extraction
profit_expr = (
    LXLinearExpression()
    .add_term(production, lambda p: p.profit)
)

# Quadratic expressions
quadratic_expr = (
    LXQuadraticExpression()
    .add_quadratic_term(x, y, coefficient=0.5)
)
```

### Automatic Linearization

LumiX can automatically linearize non-linear terms:

```python
from lumix import LXBilinearTerm, LXAbsoluteTerm, LXPiecewiseLinearTerm

# Bilinear products (x * y)
bilinear = LXBilinearTerm(x, y, bounds_x=(0, 10), bounds_y=(0, 5))

# Absolute values |x|
absolute = LXAbsoluteTerm(x)

# Piecewise-linear functions
piecewise = LXPiecewiseLinearTerm(
    variable=x,
    breakpoints=[0, 10, 20, 30],
    slopes=[1.0, 0.5, 0.2]
)
```

### Advanced Analysis

```python
from lumix import (
    LXSensitivityAnalyzer,
    LXScenarioAnalyzer,
    LXWhatIfAnalyzer,
)

# Sensitivity analysis
sens = LXSensitivityAnalyzer(model, solution)
report = sens.generate_report()
print(report)

# Scenario analysis
scenario_analyzer = LXScenarioAnalyzer(model, optimizer)
scenario_analyzer.add_scenario("base", {})
scenario_analyzer.add_scenario("high_demand", {"demand": 150})
results = scenario_analyzer.solve_all()

# What-if analysis
whatif = LXWhatIfAnalyzer(model, optimizer)
result = whatif.increase_constraint_rhs("capacity", by=10)
print(f"Impact: ${result.delta_objective:,.2f}")
```

### Goal Programming

```python
from lumix import (
    LXGoal,
    LXGoalMode,
    solve_goal_programming,
)

# Define multiple goals with priorities
goals = [
    LXGoal(
        name="profit",
        target=1000,
        priority=1,
        weight=1.0,
        is_minimization=False,
    ),
    LXGoal(
        name="quality",
        target=95,
        priority=2,
        weight=0.8,
    ),
]

# Solve with goal programming
solution = solve_goal_programming(
    model,
    goals,
    mode=LXGoalMode.SEQUENTIAL,
    solver="gurobi",
)
```

## 📖 Documentation

- **[Installation Guide](docs/source/getting-started/installation.rst)** — Install LumiX and solvers
- **[Quick Start](docs/source/getting-started/quickstart.rst)** — Build your first model
- **[Solver Guide](docs/source/getting-started/solvers.rst)** — Choose the right solver
- **[Examples](examples/)** — 11 comprehensive examples

### Examples

The repository includes 11 examples demonstrating various features:

1. **Production Planning** — Single-model indexing, data-driven modeling
2. **Driver Scheduling** — Multi-dimensional indexing, scheduling
3. **Facility Location** — Binary variables, fixed costs
4. **Basic LP** — Simple linear programming
5. **CP-SAT Assignment** — Constraint programming solver
6. **McCormick Bilinear** — Bilinear term linearization
7. **Piecewise Functions** — Piecewise-linear approximations
8. **Scenario Analysis** — Multiple scenario comparison
9. **Sensitivity Analysis** — Parameter sensitivity
10. **What-If Analysis** — Decision support
11. **Goal Programming** — Multi-objective optimization

## 🎯 Why LumiX?

### Before (Traditional Approach)

```python
# Manual indexing, no type safety
x = {}
for i in range(len(products)):
    x[i] = model.addVar(name=f"x_{i}")

# String-based error-prone expressions
model.addConstr(
    sum(x[i] * data[i] for i in range(len(products))) <= capacity
)
```

### After (LumiX)

```python
# Type-safe, data-driven, IDE-friendly
production = (
    LXVariable[Product, float]("production")
    .continuous()
    .indexed_by(lambda p: p.id)
    .from_data(products)
)

model.add_constraint(
    LXConstraint("capacity")
    .expression(
        LXLinearExpression()
        .add_term(production, lambda p: p.usage)
    )
    .le()
    .rhs(capacity)
)
```

**Benefits:**
- ✓ Full IDE autocomplete
- ✓ Type checking catches errors early
- ✓ No manual indexing
- ✓ Data-driven coefficients
- ✓ Readable, maintainable code
- ✓ Easy to refactor

## 🛠️ Development

### Setup Development Environment

```bash
git clone https://github.com/lumix/lumix.git
cd lumix
pip install -e .[dev]
```

### Run Tests

```bash
pytest
```

### Type Checking

```bash
mypy src/lumix
```

### Code Formatting

```bash
black src/lumix
ruff check src/lumix
```

## 📦 Project Structure

```
lumix/
├── src/lumix/
│   ├── core/              # Core model building (variables, constraints, expressions)
│   ├── solvers/           # Solver interfaces (OR-Tools, Gurobi, CPLEX, GLPK, CP-SAT)
│   ├── analysis/          # Analysis tools (sensitivity, scenario, what-if)
│   ├── linearization/     # Automatic linearization engine
│   ├── goal_programming/  # Goal programming support
│   ├── indexing/          # Multi-dimensional indexing
│   ├── nonlinear/         # Non-linear terms
│   ├── solution/          # Solution handling and mapping
│   └── utils/             # Utilities (logger, ORM, rational converter)
├── examples/              # 11 comprehensive examples
├── tests/                 # Test suite
└── docs/                  # Sphinx documentation
```

## 🤝 Contributing

Contributions are welcome! Please:

1. Open an issue to discuss your idea
2. Fork the repository
3. Create a feature branch
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request

## 📄 License

LumiX is licensed under the [Academic Free License v3.0](LICENSE).

This is a permissive open-source license that:
- ✓ Allows commercial use
- ✓ Allows modification and distribution
- ✓ Provides patent protection
- ✓ Is OSI-approved

## 🙏 Acknowledgments

LumiX builds upon the excellent work of:

- [OR-Tools](https://developers.google.com/optimization) by Google
- [Gurobi](https://www.gurobi.com/) Optimization
- [CPLEX](https://www.ibm.com/products/ilog-cplex-optimization-studio) by IBM
- [GLPK](https://www.gnu.org/software/glpk/) by GNU

## 📞 Support

- **Documentation**: https://lumix.readthedocs.io
- **Issues**: https://github.com/lumix/lumix/issues
- **Discussions**: https://github.com/lumix/lumix/discussions

## 🗺️ Roadmap

- [ ] Additional solver support (HiGHS, SCIP)
- [ ] Jupyter notebook integration
- [ ] Interactive visualization tools
- [ ] Cloud solver integration
- [ ] Extended ORM support (SQLAlchemy, Django)
- [ ] Advanced constraint programming features
- [ ] Parallel scenario evaluation
- [ ] Model versioning and serialization

---

**Made with ❤️ by the LumiX Contributors**
