How to fit several linear models with linear intercept-slope constrain? I have a data where several groups exist: $i = 1, 2, 3...n$ ($n$ about 600 groups in total). 
For group $i$ theory predicts a linear relation $y = a_i + b_i * x$ with $a_i$ and $b_i$ intercept and slope, respectively.
Theory also predicts that $a_i$s and $b_i$s are linearly related: $a_i = A + B * b_i$ with $A$ and $B$ intercept and slope respectively.
How can I build a model, which represents this structure and returns $a_i$s, $b_i$s, $A$ and $B$ as regression parameters?
I am trying to look at it as a hierarchical model but not much success.
 A: Suppose there are $k$ groups. The $i$th group contains $n_i$ points, whose indices are stored in set $S_i$. The original model is:
$$y_{ij} = a_i + b_i x_{ij} + \epsilon_{ij}$$
where the subscript $i$ denotes the $i$th group and the subscript $ij$ denotes the $j$th point in the $i$th group. $\epsilon_{ij}$ represents noise.
The parameters are constrained such that $a_i = A + B b_i$, where $A$ and $B$ are unknown values that are shared for all groups. This constraint means that there are effectively fewer parameters. We can substitute in the expression for $a_i$ and rewrite the model as:
$$y_{ij} = A + b_i (x_{ij} + B) + \epsilon_{ij}$$
The parameters can be fit by least squares, which corresponds to maximum likelihood estimation under the assumption that the errors $\epsilon_{ij}$ are i.i.d. Gaussian. The optimization problem is:
$$\min_{A, B, b_1, \dots, b_k} \
\sum_{i=1}^k \sum_{j \in S_i}
\Big( A + b_i (x_{ij} + B) - y_{ij} \Big)^2$$
This is a nonlinear least squares problem, since the parameters $B$ and $b_i$ interact multiplicatively. It can be solved using a standard optimization solver. This problem may contain local minima. A simple heuristic for dealing with this is to solve multiple times with different initializations, then keep the best solution.
Once the parameters $A, B, b_1, \dots, b_k$ have been identified, then $a_1, \dots, a_k$ can be recovered as $a_i = A + B b_i$
