# How to enforce constraints with SymbolicRegression.jl

**URL:** <https://discourse.julialang.org/t/how-to-enforce-constraints-with-symbolicregression-jl/112832>\
**Category:** General Usage\
**Tags:** symbolic-regression\
**Created:** [April 11, 2024, 2:35pm UTC](https://discourse.julialang.org/t/how-to-enforce-constraints-with-symbolicregression-jl/112832 "2024-04-11T14:35:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Christopher\_Fisher](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/christopher_fisher/32/26132_2.png) [@Christopher\_Fisher](https://discourse.julialang.org/u/Christopher_Fisher)\
**Post date:** [April 11, 2024, 2:35pm UTC](https://discourse.julialang.org/t/how-to-enforce-constraints-with-symbolicregression-jl/112832/1 "2024-04-11T14:35:19Z")

</div>

Hello,

I am interested in whether symbolic regression could be used to learn or approximate likelihood functions of simulation-based models. One approach might be approximate the pdf from simulated data using kernel density estimation, and use SymbolicRegression.jl to find a suitable equation. The code below shows that this can be done in a simple case with an exponential distribution.

I was wondering if it is possible to define constraints. In this particular case, an important constraint is that the function integrates to 1 with respect to the data input. I would image that adding constraints might be useful in a variety of applications.

> **Summary**
>
> ```julia
> using SymbolicRegression
> import MLJ: machine, fit!, predict, report
> using SymbolicUtils
> 
> # data input, rate parameter
> X = (x = rand(1000) * 5, λ = rand(1000) * 3)
> 
> # pdf of exponential distribution 
> y = @. X.λ * exp(-X.λ * X.x)
> 
> model = SRRegressor(
> niterations=100,
> binary_operators=[*,-],
> unary_operators=[exp],
> )
> 
> mach = machine(model, X, y)
> 
> fit!(mach)
> 
> r = report(mach)
> r.equations[r.best_idx]
> 
> eq = node_to_symbolic(r.equations[r.best_idx], model; variable_names=["x", "λ"])
> simplify(eq)
> 
> ```

---

<div class="post-metadata">

**Author:** ![tbeason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tbeason/32/15898_2.png) [@tbeason](https://discourse.julialang.org/u/tbeason)\
**Post date:** [April 11, 2024, 2:53pm UTC](https://discourse.julialang.org/t/how-to-enforce-constraints-with-symbolicregression-jl/112832/2 "2024-04-11T14:53:11Z")

</div>

pdfs are terribly hard to just cook up with random functions because of the positivity and integration constraints. I would suggest using something like kernel densities or maximum entropy densities if you want something flexible and data-driven. Could also try to adaptively fit mixtures of parametric distributions.
