SlowGuess/NeurIPS_2023_OCR huggingface dataset:
We assess NeuralEF's accuracy by measuring its ability to predict portfolio weights, returns and volatility on  $\mathcal{D}_{\mathrm{test}}$ . We use Mean square error (MSE), mean absolute error (MAE), and quantiles to evaluate the error distribution for portfolios with varying numbers of assets. Additionally, we test NeuralEF's precision in ranking asset importance in the allocation, check the precision of our model to forecast volatility ( $\hat{\mathcal{V}}_{\mathrm{target}} = Z_{\mathrm{output}}^{\top} Q Z_{\mathrm{output}} \leq \max(\mathcal{V}_{\mathrm{target}}, \mathcal{V}_{\mathrm{min}})$ ), and check for feasibility of violating constraints. Table 3 summarizes the accuracy results for different numbers of assets considered. Overall, NeuralEF shows accurate performance on portfolio weight prediction with slight deviations only in the higher upper quantiles for all asset cases. The model also demonstrates a high level of accuracy on returns and volatility. The ability to rank assets in order of importance correlates with the ability to respect constraints not captured by DGAR. The optimality gap metrics (ranking precision,  $\zeta_{\mathrm{MAX}}$  and  $\mathcal{V}_{\mathrm{target}}$ ) are by design highly sensitive to a slight  $\epsilon$  deviation, which in practice wouldn't necessarily be impactful. However, this limitation is to be considered when considering NeuralEF in safety-critical scenarios. NeuralEF can easily be applied within MC simulations that targets  $\mathbb{E}(R)$ ,  $\mathbb{E}(V)$ , and/or  $\mathbb{E}(x)$  as failure to respect the unsupported constraints does not necessarily lead to large error on the allocation. With a sufficiently large  $N$ , these errors do not impact the derived distributional features of  $\mathbb{E}(g(Z))$ .
Asset case	Portfolio weights MSE	Portfolio weights MAE	95 quantile	99.865 quantile	99.997 quantile	Ranking precision
2	1.24e-06	1.11e-03	1.22e-02	3.39e-02	1.05e-01	91.122 %
3	2.37e-15	3.97e-08	1.50e-02	3.78e-02	1.06e-01	99.080 %
4	8.80e-07	6.03e-04	1.66e-02	4.57e-02	1.39e-01	98.421 %
5	2.95e-06	1.33e-03	1.47e-02	4.15e-02	1.75e-01	96.587 %
6	1.96e-05	2.02e-03	1.50e-02	4.35e-02	1.50e-01	93.896 %
7	2.82e-06	1.19e-03	1.68e-02	4.43e-02	2.00e-01	90.426 %
8	1.02e-05	2.35e-03	1.60e-02	4.59e-02	1.57e-01	87.861 %
9	7.81e-06	1.67e-03	1.98e-02	5.17e-02	1.93e-01	84.895 %
10	1.07e-05	2.15e-03	2.00e-02	5.23e-02	1.70e-01	81.519 %
11	1.21e-05	1.78e-03	2.22e-02	5.83e-02	2.30e-01	80.003 %
12	1.64e-08	1.04e-04	1.98e-02	5.28e-02	2.14e-01	78.067 %
Portfolio return MSE	Portfolio return MAE	95 quantile	99.865 quantile	99.997 quantile	\( \zeta_{MAX} \)precision
2	2.86e-06	1.69e-03	7.74e-03	2.20e-02	7.54e-02	100 %
3	8.84e-06	2.97e-03	1.22e-02	3.15e-02	1.12e-01	93.927 %
4	3.20e-06	1.79e-03	1.47e-02	4.10e-02	1.76e-01	90.221 %
5	8.70e-06	2.95e-03	1.49e-02	3.60e-02	9.09e-02	89.406 %
6	1.33e-10	1.15e-05	1.53e-02	3.63e-02	1.23e-01	88.690 %
7	3.31e-10	1.82e-05	1.66e-02	3.94e-02	1.49e-01	85.186 %
8	5.77e-06	2.40e-03	1.72e-02	4.22e-02	1.49e-01	83.326 %
9	1.79e-06	1.34e-03	2.12e-02	5.18e-02	1.72e-01	87.125 %
10	5.75e-10	2.40e-05	2.31e-02	5.33e-02	1.55e-01	83.003 %
11	1.35e-07	3.67e-04	2.48e-02	5.80e-02	1.71e-01	81.934 %
12	1.14e-06	1.07e-03	2.50e-02	5.72e-02	1.83e-01	83.999 %
Volatility return MSE	Volatility return MAE	95 quantile	99.865 quantile	99.997 quantile	\( V_{target} \)precision
2	2.86e-06	1.69e-03	7.74e-03	2.20e-02	7.54e-02	98.417 %
3	8.84e-06	2.97e-03	1.22e-02	3.15e-02	1.12e-01	95.115 %
4	3.20e-06	1.79e-03	1.47e-02	4.10e-02	1.76e-01	90.793 %
5	8.70e-06	2.95e-03	1.49e-02	3.60e-02	9.09e-02	87.406 %
6	1.33e-10	1.15e-05	1.53e-02	3.63e-02	1.23e-01	82.080 %
7	3.31e-10	1.82e-05	1.66e-02	3.94e-02	1.49e-01	80.465 %
8	5.77e-06	2.40e-03	1.72e-02	4.22e-02	1.49e-01	71.728 %
9	1.79e-06	1.34e-03	2.12e-02	5.18e-02	1.72e-01	69.426 %
10	5.75e-10	2.40e-05	2.31e-02	5.33e-02	1.55e-01	67.423 %
11	1.35e-07	3.67e-04	2.48e-02	5.80e-02	1.71e-01	70.261 %
12	1.14e-06	1.07e-03	2.50e-02	5.72e-02	1.83e-01	70.769 %
Table 3: Accuracy of portfolio weights, implied return and resulting volatility
We plot the error distribution per asset by displaying the cumulative distribution of the sum error for all  $x_{1}, \dots, x_{n}$ , the absolute error on the expected return and the portfolio volatility in Fig. 4. The total weight allocation error does not exceed  $1\%$  total deviation in around  $98\%$  of cases, but the impact on the resulting returns and volatility is only noticeable in  $1\%$  of cases. From the remaining tail exceeding the  $1\%$  total deviation, we measured no case violating the volatility constraint and only  $8\%$  exceeded the class constraint. The source of these errors was mainly found in regions with abrupt changes in the allocation due to the nature of the optimization.
NeuralEF accurately captures the qualitative behavior of the optimization in discontinuous regions, but instability in these areas exposes a weakness of approximating function with discontinuous behavior using DNNs. We illustrate this behavior using one example from the 99.997th quantile worst predictions of  $\mathcal{D}_{\mathrm{test}}$ , where we vary a single input parameter  $(r_{10} \in [-1.0, 2.0])$  while keeping the others constant, in Fig. 5. NeuralEF approximates discontinuities for most assets accurately, and errors on the portfolio returns are often attributed to ranking failure when NeuralEF transitions through these discontinuities. At the expense of always respecting constraints, DGAR can spread forecast errors to other assets with a poor  $\mathcal{K}$  ordering leading to a larger absolute error in the resulting forecast than not using DGAR. Despite some assets not being modeled properly, we observe often that for practical purposes, this doesn't impact the resulting portfolio return or the portfolio
Figure 5: Illustration of the behavior NeuralEF at discontinuous points of the optimization. The unstable regions on the allocation occurs where  $r_{10} \in [0, 0.5]$ . All assets change allocation either smoothly through that region or suddenly by a jump discontinuity.
volatility, as illustrated in fig. 6 (a-b). An ablation study motivating the different NeuralEF's components is presented in sec. C.2
(a) Return
(b) Volatility
Figure 6: Impact of the inflection point prediction failure using the same prediction shown in fig. 5 on the estimated return and volatility respectively (a,b). EF numerical calculation throughput per concurrent process and its emissions in  $\mathrm{kgCO_2e / kWh}$  (c). Emissions presented are for computing 1000 evaluations per concurrent process and are scaled by a factor of 1e3.
(c) EF CPU scaling with concurrent processes.
4.2 Throughput Evaluation and Carbon Footprint Impact
Figure 7: Throughput of the vectorized EF version on GPU (left), NeuralEF in FP16-precision (middle) and NeuralEF in FP32 precision (right) by batch size compared to the single-thread and multi-thread pricer.
We report a significant acceleration in the performance of NeuralEF compared to the single-tread baseline optimizer, with a 623X time improvement on a CPU (AMD 5950X achieving 559 eval./s). The main factors contributing to this improvement are running multiple optimizations in batches, the smaller computational cost of inferring the result compared to numerically solving the optimization using an interior-point solver, and the use of half-precision floating-point format. We demonstrate the scalability of NeuralEF on fig. 7 for
4We don't observe a significant impact on accuracy using half-precision floating-point precision. See sec. C.3
both GPUs and CPUs as well as the impact of the different components. The highest achieved throughput are presented on table. 4.
Parallelizing the execution on CPU through concurrent processes of the base pricer can increase throughput, but the scaling ability of this approach is inferior to NeuralEF. Fig. 7 (c) shows that the throughput scales linearly with the number of cores until the concurrent processes saturate the CPU usage and prevent further speedup. Considering the AMD 5950X CPU as an example, we achieved a maximum throughput of 10377.80 eval./sec. 5. It would take 26.77 hours to generate a billion evaluations, whereas it would only take 41 minutes or 1.25 hours with NeuralEF respectively on a A100 or on two ISR chips. When accelerated on GPU, impractical large batch sizes are needed to compete with a concurrent CPU setup. Pytorch-EF needs batches of 1.2 million request to reach a maximum throughput of 111479 eval./sec. In comparison, NeuralEF can achieve 343760 eval./sec. using batch size of 80k request. From an ease of use standpoint, the accelerated
throughput of NeuralEF on a few devices is more running multiple machines to achieve the same throu large batch size in practice. The scaling advantage reduce the carbon footprint of large-scale simulations
Figure 8: Scalability of DGAR throughput by number of assets and batch size.
A100:	Throughput (eval./sec.)	2080TI:	Throughput (eval./sec.)
Pytorch-EF	111479.39	Pytorch-EF	26452.06
NeuralEF (fp32)	128950.46	NeuralEF (fp32)	37821.05
NeuralEF (fp16)	343760.77	NeuralEF (fp16)	107259.29
NeuralEF (fp16) clean-only	366450.96	NeuralEF (fp16) clean-only	114160.65
NeuralEF (fp16) no preprocessing	401641.81	NeuralEF (fp16) no preprocessing	118711.91
Intel Xeon Platinum 8480+ (ISR)	3090:	Throughput (eval./sec.)
NeuralEF (fp32)	56050.39	Pytorch-EF	41035.23
NeuralEF (bf16 + AMX)	221787.48	NeuralEF (fp32)	77859.95
AMD 5950X (reference)	NeuralEF (fp16)	167594.15
singe-thread	559.15	NeuralEF (fp16) clean-only	173388.66
Concurrent processes (23)	10377.80	NeuralEF (fp16) no preprocessing	170650.62
Table 4: Maximum average throughput achieved. Note that two Intel Xeon Platinum 8480 CPUs were used simultaneously on a dual-socket machine to achieve the best throughput.
NeuralEF is less environmentally impactful than running the same optimization on CPU. For a single AMD Ryzen 9, if we consider the total time to generate our training dataset of 1 billion EF optimizations, the total simulation on CPU would approximate to  $1.39\mathrm{kgCO_2e}$ . Increasing the throughput by running concurrent processes increases the  $\mathrm{CO}_{2}$  emission on the chip as it requires more energy as show in fig. 6 (c). Training NeuralEF is more environmentally expensive due to a cumulative 336 hours of computation on a single A100 GPU with an AMD server-grade CPU server resulting in approximately  $5.71\mathrm{kgCO_2e}$ . At inference, the total emissions for forecasting a billion EF optimization using NeuralEF is estimated to be  $0.03\mathrm{kgCO_2e^6}$ . Hence, we can offset the total cost of training NeuralEF by running approximately 4.20 billions evaluations. Since MC error converges as  $\mathcal{O}(1 / \sqrt{N})$ , one could get a 4x more precise approximation to  $\mathbb{E}(g(Z))$  with NeuralEF in the time it would takes to obtain  $N$  simulations on a single CPU. Given that the EF problem is a cornerstone
${}^{5}$  CPUs of newer generations and with higher number of core are expected to perform better.
$^6\mathrm{CO}_2$  estimations were conducted using CODECARBON [43] for the throughput of NeuralEF and eq. 3. The "Machine Learning Impact calculator" [32] (MLIC) was used to estimate the cost of training. Both approaches were measured using a carbon efficiency of  $0.025\mathrm{kgCO_2e / kWh}$  to approximate its use in an environmentally friendly data center. Since we didn't track total amount of our emission during training, the estimate for model emission made with the MLIC is less accurate.
of multiple applications in finance, 4.20 billions evaluations is easily offset in less than a week by a single organization.
4.3 Out-of-domain Generalization
Figure 9: Cumulative distributions of the sum of absolute allocation error of allocations and portfolio returns per number of assets for  $\mathcal{D}_{\mathrm{odd}}$
The generalization ability of our model was measured by testing it on a larger input domain on a new dataset  $\mathcal{D}_{\mathrm{ood}}$  of 1 million samples using the same domain as in  $\mathcal{D}_{\mathrm{test}}$ , but instead considering  $\nu_{\mathrm{target}} \in [0.01, 0.3]$ ,  $R \in [0, 4]$ ,  $\alpha_{\mathrm{MIN}} \in [0.2, 1.0]$ . The accuracy of the model degrades significantly on the tail of the distribution, especially for larger asset cases, indicating that it is not recommended to use NeuralEF outside the training domain. However, scale invariance in eq. 3 when all returns have the same sign (e.g.,  $R = [0.3, 0.4, 0.5] \approx [3.3, 3.4, 3.5]$ ), allows the model to accurately estimate optimization even with returns outside the training domain by rescaling  $R$  by  $\lambda$  such that they fit within the training domain. One can revert to the base optimization in the rare cases that it goes out of the domain, e.g. where assets go above  $200\%$  returns or the  $200\%$  volatilities, both being highly unlikely cases. Otherwise, one can always train NeuralEF on a bigger domain than table. 1 with most likely more data. Because NeuralEF has been trained on synthetic data, we haven't observed behavior bias that arises directly from certain regime aside in cases where assets would oscillate in the inflection area of the optimization, i.e. when two "attractive" assets have returns/volatilities  $\epsilon$  close to each other and/or near 0 across a prolonged period of time.
In this work we introduce NeuralEF, a fast DNN-based model that approximates the solution of a convex optimization problem by treating it as a SEQ2SEQ problem. Using the Efficient Frontier, a highly discontinuous resource allocation problem, we demonstrate NeuralEF's accuracy and its ability to handle variable-length input optimization parameters while robustly respecting linear constraints by means of a novel dynamic greedy allocation rebalancing module. This positions NeuralEF as an attractive solution to reduce the computational footprint of running large scale simulations and offers a practical means to accelerate convex optimization problems in application that rely on MC simulation such as securities pricing, portfolio management and valuation of unit-linked insurance policies [6, 38].
More importantly, our reformulation of convex optimization as SEQ2SEQ offers a tangible step towards solving quantitative mathematical problems efficiently with DNNs [33, 15]. Whether it is easier to expedite optimization problems with heterogeneous constraints though a RL training paradigm [31, 35] or a SL paradigm like done with NeuralEF hinges on additional experimental insights. However, we know that current LLMs struggle to solve hard mathematical tasks [33] and simply scaling them is impractical for achieving strong mathematical reasoning [23]. Converting a quantitative mathematical problem into a sequence representation and then forecasting the results presents a more practical approach than solving it directly. This conceptually separate reasoning, i.e. how to formulate a mathematical problem given some inputs using a LLM, and solving it as two independent learning tasks that can be combined at inference.
[1] A. Agrawal, B. Amos, S. Barratt, S. Boyd, S. Diamond, and J. Z. Kolter. Differentiable convex optimization layers. Advances in neural information processing systems, 32, 2019.
[2] A. Agrawal, S. Barratt, and S. Boyd. Learning convex optimization models. IEEE/CAA Journal of Automatica Sinica, 8(8):1355-1364, 2021.
[3] I. Akkizidis and L. Kalyvas. Final basel III modelling: Implementation, impact and implications. Springer, 2018.
[4] B. Amos and J. Z. Kolter. Optnet: Differentiable optimization as a layer in neural networks. In International Conference on Machine Learning, pages 136-145. PMLR, 2017.
[5] D. F. Anderson, D. J. Higham, and Y. Sun. Computational complexity analysis for monte carlo approximations of classically scaled population processes. Multiscale Modeling & Simulation, 16(3):1206-1226, 2018.
[6] P. Boyle, M. Broadie, and P. Glasserman. Monte carlo methods for security pricing. Journal of economic dynamics and control, 21(8-9):1267-1321, 1997.
[7] P. Brandimarte. Handbook in Monte Carlo simulation: applications in financial engineering, risk management, and economics. John Wiley & Sons, 2014.
[8] T. Brown, B. Mann, N. Ryder, M. Subbiah, J. D. Kaplan, P. Dhariwal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell, et al. Language models are few-shot learners. Advances in neural information processing systems, 33:1877-1901, 2020.
[9] T. Brown, B. Mann, N. Ryder, M. Subbiah, J. D. Kaplan, P. Dhariwal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell, et al. Language models are few-shot learners. Advances in neural information processing systems, 33:1877-1901, 2020.
[10] R. E. Caflisch. Monte carlo and quasi-monte carlo methods. Acta numerica, 7:1-49, 1998.
[11] J. Charlton, S. Maddock, and P. Richmond. Two-dimensional batch linear programming on thegpu. Journal of Parallel and Distributed Computing, 126:152-160, 2019.
[12] P. Charoenphaibul and N. Juneam. Gpu-accelerated method for simulating efficient portfolios in the mean-variance analysis. In 2020 17th International Joint Conference on Computer Science and Software Engineering (JCSSE), pages 171-176. IEEE, 2020.
[13] D. Cole, S. Shin, F. Pacaud, V. M. Zavala, and M. Anitescu. Exploitinggpu/simd architectures for solving linear-quadratic mpc problems. arXiv preprint arXiv:2209.13049, 2022.
[14] S. Diamond and S. Boyd. Cvxpy: A python-embedded modeling language for convex optimization. The Journal of Machine Learning Research, 17(1):2909–2913, 2016.
[15] I. Drori, S. Zhang, R. Shuttleworth, L. Tang, A. Lu, E. Ke, K. Liu, L. Chen, S. Tran, N. Cheng, R. Wang, N. Singh, T. L. Patti, J. Lynch, A. Shporer, N. Verma, E. Wu, and G. Strang. A neural network solves, explains, and generates university math problems by program synthesis and few-shot learning at human level. Proceedings of the National Academy of Sciences, 119(32):e2123433119, 2022.
[16] E. J. Elton and M. J. Gruber. Modern portfolio theory, 1950 to date. Journal of banking & finance, 21(11-12):1743-1759, 1997.
[17] M. Estecahandy, L. Bordes, S. Collas, and C. Paroissin. Some acceleration methods for monte carlo simulation of rare events. Reliability Engineering & System Safety, 144: 296-310, 2015.
[37] O. McCullagh, M. Cummins, and S. Killian. The fundamental review of the trading book: implications for portfolio and risk management in the banking sector. Journal of Money, Credit and Banking, 2022.
[38] D. L. McLeish. Monte Carlo simulation and finance, volume 276. John Wiley & Sons, 2011.
[39] N. Metropolis and S. Ulam. The monte carlo method. Journal of the American statistical association, 44(247):335-341, 1949.
[40] H. Pan and R. Kondor. Permutation equivariant layers for higher order interactions. In International Conference on Artificial Intelligence and Statistics, pages 5987-6001. PMLR, 2022.
[41] C. R. Qi, H. Su, K. Mo, and L. J. Guibas. Pointnet: Deep learning on point sets for 3d classification and segmentation. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 652-660, 2017.
[42] P. Ramachandran, B. Zoph, and Q. V. Le. Searching for activation functions. In 6th International Conference on Learning Representations, ICLR 2018, Vancouver, BC, Canada, April 30 - May 3, 2018, Workshop Track Proceedings, 2018.
[43] V. Schmidt, K. Goyal, A. Joshi, B. Feld, L. Conell, N. Laskaris, D. Blank, J. Wilson, S. Friedler, and S. Luccioni. Codecarbon: estimate and track carbon emissions from machine learning computing. Cited on, page 20, 2021.
[44] M. Schubiger, G. Banjac, and J. Lygeros. Gpu acceleration of admm for large-scale quadratic programming. Journal of Parallel and Distributed Computing, 144:55-67, 2020.
[45] I. Sutskever, O. Vinyals, and Q. V. Le. Sequence to sequence learning with neural networks. Advances in neural information processing systems, 27, 2014.
[46] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, and I. Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017.
[47] O. Vinyals, S. Bengio, and M. Kudlur. Order matters: Sequence to sequence for sets. arXiv preprint arXiv:1511.06391, 2015.
[48] X. Warin. Deep learning for efficient frontier calculation in finance. Journal of Computational Finance, 26(1), 2022.
[49] M. Zaheer, S. Kottur, S. Ravanbakhsh, B. Poczos, R. R. Salakhutdinov, and A. J. Smola. Deep sets. Advances in neural information processing systems, 30, 2017.
A Numerical example of the EF problem
$$
\boldsymbol {A} = \left[ \begin{array}{c c c c} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ - 1 & 0 & 0 & 0 \\ 0 & - 1 & 0 & 0 \\ 0 & 0 & - 1 & 0 \\ 0 & 0 & 0 & - 1 \\ - 1 & - 1 & - 1 & - 1 \\ 1 & 1 & 1 & 1 \\ 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \end{array} \right] \boldsymbol {B} = \left[ \begin{array}{c} 0. 5 9 1 \\ 0. 7 4 9 \\ 0. 4 1 2 \\ 0. 5 4 5 \\ 0. \\ 0. \\ 0. \\ - 0. 8 1 \\ 1. \\ 0. 7 4 \\ 0. 5 8 \end{array} \right] (1
$$
$$
\begin{array}{l} \boldsymbol {C} = [ 0, 0, 1, 1 ]; \boldsymbol {\zeta} _ {\mathrm {M A X}} = [ 0. 7 4, 0. 5 8 ] \\ \boldsymbol {X} _ {\text {M A X}} = [ 0. 5 9 1 0. 7 4 9, 0. 4 1 2, 0. 5 4 5 ] \\ \boldsymbol {X} _ {\mathrm {M I N}} = [ 0, 0, 0, 0 ] \\ \alpha_ {\mathrm {M I N}} = 0. 8 1, \alpha_ {\mathrm {M A X}} = 1 \\ \end{array}
$$
We provide a numerical example of the EF problem in the case of a 4-asset problem with 2 classes and  $\alpha_{\mathrm{MIN}} < 1$  (see Eq.12). Only the constraints are presented here. It is important to note that the matrices  $A$  and  $B$  representing all  $w$  constraints grow in size by  $(2n + 2 + m)$  as  $n$  increases, where  $m$  is the number of distinct asset classes. If  $X_{\mathrm{MAX}}$  is not defined, then all entries of  $X_{\mathrm{MAX}}$  can be set to  $\alpha_{\mathrm{MAX}}$ . Solving Eq.1 is achieved by directly considering  $A$  and  $B$  and the covariance matrix  $Q = \mathrm{diag}(V)P\mathrm{diag}(V)$  obtained from the other inputs. If  $\mathcal{V}_{\mathrm{min}} = \boldsymbol{x}^{\top}\boldsymbol{Q}\boldsymbol{x}$ , then we solve a second-order cone program (SOCP) to increase the portfolio's volatility without exceeding  $\mathcal{V}_{\mathrm{target}}$  and get better returns.
We obtain the volatility constraint through the Cholesky decomposition of the covariance matrix  $Q' = L(Q)L(Q)^T$  where  $L$  is the lower-triangular operator.
$\pmb{E} \in \mathbb{R}^{[n + 1,n]}$  is built by stacking  $\pmb{Q}'$  and  $[0, \dots, 0]$  such that  $\pmb{F} \in \mathbb{R}^{[n + 1,1]} = [\sqrt{\mathcal{V}_{\mathrm{target}}}, 0, \dots]$ . Then, eq. 2 can be reformulated as follow:
$$
\phi := \operatorname {m i n i m i z e} - \boldsymbol {R} ^ {\top} \boldsymbol {x} \text {s u b j e c t t o} \boldsymbol {A} \leq \boldsymbol {B} \text {a n d} \boldsymbol {E} \leq \boldsymbol {F}. \tag {13}
$$
The complete optimal allocation of eq. 3 can be summarized by the following python script:
```
```
```
```
```
```
```
```
```
```
```
```
```
```
```
``
import cvxopt  
import numpy as np
scalar  $= 10000$
def cvxopt.solve_qp(P, q, G=None, h=None, **kwargs): P = 0.5 * (P + P.T) # make sure P is symmetric  
args = [cvxopt.matrix(P), cvxopt.matrix(q)]  
if G is not None: args.append([cvxopt.matrix(G), cvxopt.matrix(h)])  
sol = cvxopt.solvers.qp(*args, **kwargs)  
if sol["status"] != "optimal": raise ValueError("QP SOLVER: sol.status != 'optimal')  
return np.array(sol["x"].reshape((P.shape[1]),)), num_iterations
def cvxopt.solve_socp(c, Gl, hl, Gq, hq, **kwargs):  
    args = [cvxopt.matrix(c), cvxopt.matrix(Gl), cvxopt.matrix hl, [cvxopt.matrix(Gq)],  
     $\leftrightarrow$  [cvxopt.matrix(hq)]  
    sol = cvxopt.solvers.socp(*args, **kwargs)  
    num_iterations = sol["iterations"]  
    if sol["status"] != "optimal":  
        raise ValueError("SOCP SOLVER: sol.status != 'optimal')  
    return np.array(sol["x ]).reshape((Gl.shape[1]),)), num_iterations