Metadata-Version: 2.5
Name: accelerated_weighting
Version: 0.7.0
Summary: Fast and sparsity-aware implementations of EBW and GREG weighting routines.
Author-email: Carl Sanders <carl.e.sanders@census.gov>
License-File: LICENSE.md
Requires-Python: >=3.9
Requires-Dist: numexpr
Requires-Dist: numpy
Requires-Dist: pypardiso
Requires-Dist: scipy
Requires-Dist: sparse-dot-mkl
Description-Content-Type: text/markdown

Accelerated Weighting
------------------------------------
Author: Carl Sanders

Email: carl.e.sanders@census.gov

This package implements routines for fast, easy, and sparse-data-aware weighting, using either
 Entropy Balancing Weighting (EBW) or Generalized REGression (GREG) approaches.
The goal of this package was to scale weighting algorithms to allow them to work with large, complicated data
sets. A particular focus is then on allowing sparse inputs, colinearity, and potential 
infeasibility without additional front-end data manipulation by the user.

Scaling up weighting problems is largely possible due to the sparsity of naturally-occuring data, e.g. models with group-specific moments. Utilizing sparsity of datasets, models with millions of observations and hundreds of thousands of constraints have successfully converged in minutes. In addition, extensions like bound constraints and handling colinear and inconsistent moments have been added to the standard approach.

Requirements:
-------------
- Python 3.9+
- Required packages (tested versions listed, should work on most others):
  - numpy (2.2, 1.26)
  - scipy (1.15.1, 1.13.1)
  - pypardiso (0.4.6)
  - sparse_dot_mkl (0.9.7)
  - numexpr (2.10.2)


Problem and Usage:
-------------------
The primary function in this package is ```accelerated_weighting.weight```, which takes a set of base weights
and gives a new set of weights that match a set of externally-given moments.

The weighting problem solved here considers a set of $N$ sampled units, with initial unit weights $w_0$, an $N\times K$ matrix of observable characteristics at the unit level $X$, and a $K\times 1$ vector of known external unit-level mean "targets" $m$ that the reweighted moments should match. Distance between the new weights and old weights is calculated one of two ways:
(a) the Entropy Balance method, using the Kullback-Leibler divergence, or (b) Generalized REGression (GREG), using a squared-loss distance function. For EB (the default case), call the criterion function $\phi$, and the problem can be written in terms of the ratio $r \equiv w_{1}/w_{0}$ between the new weights and the old weights:

$$\phi(r; w_0)=\sum w_{0,i} (\log(r_{i}) - r_{i} + 1).$$

The opimization problem can then be written

$$\min_{r\in \mathbb{R}^N} \phi(r; w_0)$$


$$\text{s.t. } (\text{Diag}({w_{i,0})}X)^T r = m \cdot \sum_{i=1}^N w_{i,0}, \hspace{3pt} r\geq 0.$$


The ```weight``` function takes three required keyword arguments: ```x_sample```, the $N\times K$ array dense or sparse matrix (numpy.array or scipy.sparse.csc_array/csr_array) of unit-level observations; ```weights0```, a numpy vector of the initial weights, best scaled to have mean 1; and ```mean_population_moments```, a numpy vector of the exterally-known unit-level mean of each column of $X$. As written above, the algorithm matches the aggregate moments, so keeping the relative scaling of $X$, $m$, and $w_{i,0}$ consistent with the formulation above makes the algorithm more stable, even if not theoretically necessary. 

The function returns an ```WeightingResults``` object, which has a property ```WeightingResults.new_weights```, the new weights that match the moments (if possible) while being minimum distance from the initial weights.

The algorithm default to Entropy Balance Weighting; the ```method="greg"``` kwarg can be used to use GREG instead.

Passing in optional argments to ```weight``` can allow for setting bounds in the resulting ratios and dealing with infeasibility of the linear system; see the section "Bounded and Infeasible" below.


```weight``` Example:
--------

```
>>> import numpy as np
>>> import accelerated_weighting as aw
>>> import scipy.sparse as sp
>>> 
>>> sample_size = 5
>>> x = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]])
>>> mean_population_moments = np.array([.35, .30, .33])
>>> weights0 = np.ones(sample_size)
>>> x.T.dot(weights0) - sample_size * mean_population_moments  # Calculate miss in weighted aggregate moments.
array([-0.75,  0.5 ,  0.35])
>>>
>>> res_ebw = aw.weight(x_sample = x, weights0 = weights0, mean_population_moments = mean_population_moments)
>>> res_ebw.new_weights
array([1.75 , 0.75 , 0.75 , 0.825, 0.825])
>>> x.T.dot(res_ebw.new_weights) - sample_size * mean_population_moments # Aggregate weighted moments now matched exactly.
array([6.72795153e-14, 1.28785871e-14, 4.66293670e-15])
>>>
>>> x_sparse = sp.csr_array(x) # Can use sparse matrices for memory/computation savings
>>> res_sparse_ebw = ebw.entropy_balance(x_sample = x_sparse, weights0 = weights0, mean_population_moments = mean_population_moments)
>>> assert np.allclose(res_ebw.new_weights, res_sparse_ebw.new_weights)
```

Bounded and Infeasible:
-----------------------
Passing the kwarg ```options={"bounds": (lbound, ubound)}``` for scalar `lbound` and `ubound` will solve the problem above with $\text{lbound} \leq r_i \leq \text{ubound }\forall i$. For no upper bound, pass `None` for `ubound`. 

There is a tradeoff between bound constraints and feasibility of the linear system matching the moments. To make bounds generally useful, the bounded `weight` algorithm runs "elastic mode", a variant problem that has the following properties:

1. If the bounded problem is feasible, `weight(..., options={"bounds": ...})` returns the feasible solution.
2. If the problem is infeasible, `weight` returns a point $r^\star$ that is feasible with respect to the bounds. This $r^\star$ minimizes the $L^1$ norm of the moment violations over the other feasible $r$ that satisfy $\phi(r) \leq \phi(r^\star)$; that is, the only way to make the moments match any better would be to increase the criterion. In practce, this matches as many moments exactly as possible, making it possible to identify which moments are impossible to simultaneously match.

The bounded problem is necessarily slower than the unbounded problem, but in theory should converge in every run. After running with bounds, the ```WeightingResults.constraint_violations``` property can be used to judge if the original problem was feasible or not. The feasibility of the unconstrained problem can be checked by passing `{"bounds": (0, None)}`.

Bounds and Elastic Mode Example:
--------------------------------
```
<continued from above>
>>> res_bounded_ebw= aw.weight(x_sample = x, weights0 = weights0, mean_population_moments = mean_population_moments, options={"bounds": (0.5, 1.5)})
>>> res_bounded_ebw.new_weights
array([1.5 , 0.75 , 0.75 , 0.825, 0.825])
>>> res_bounded_ebw.constraint_violations # New bounds make problem infeasible, so return new weights that give "best fit" of moments.
array([-2.50000000e-01, -8.58102478e-11, -5.19522203e-11])

```


Disclaimers:
------------
This work was performed as part of the [National Experimental Wellbeing Statistics](https://census.gov/data/experimental-data-products/national-experimental-wellbeing-statistics.html) project at the U.S. Census Bureau.
The views expressed are those of the authors and not those of the U.S. Census Bureau. The U.S. Census Bureau has reviewed this data product to ensure appropriate access, use, and disclosure avoidance protection of the confidential source data used to produce this product (Data Management System (DMS) number: P-6000725; Disclosure Review Board (DRB) approval number: CBDRB-FY25-SEHSD003-037).