Search code examples
pythondryorganizationreadabilitycomputation

How much is too much when being DRY in my engineering computations?


I am an engineering student and I have to turn in projects that run code for simulations. The calculations are all carried out in Python, but the derivations/ setup is done on paper and included in the report. I sometimes find myself copying and pasting code for repeat graphs or numerical simulations, so I want to write functions for these (trying to be better about DRY).

When writing functions to do these things, I'm worried that I'm "hiding" to much of the code behind the functions. For example, this function would plot two simulations differing only by tolerance level. This would be used to check for convergence in a numerical simulation of an ode.

def plot_visual_convergence_check(odefunc, time, reltol):
    sol_1 = solve_ivp(odefunc, time, (0,0), rtol=reltol)
    sol_2 = solve_ivp(odefunc, time, (0,0), rtol=reltol/100)
    
    plt.text('rtol is...')
    plt.text('rtol for the increased tolerance is...')
    plt.plot(<both plots together>)
    return plt.show()

Here, all the business with running solve_ivp for two scenarios that only differ by relative tolerance and plotting them is wrapped up into one. I don't imagine that people would want the specifics, just the output and the confirmation that "yes" the simulation has converged. I even write both rtol's on the graph to be more clear about what values were used without showing the code.

Is wrapping these types of operations up okay (because I think it looks cleaner that way), or would it be better as an engineer to have everything laid out for everyone to see without them having to scroll over to the function definition?


Solution

  • In my experience the dry principle is more important when writing libraries and code that you want to reuse. However my experience is that if you want to make a report then sometimes making things to dry can actually make things harder to maintain. I.e. sometimes you want to be able to change an individual graph/plot/piece of data in one place without it affecting the rest of the report. It takes a bit of practice and experience to find out what works best for you. In this particular use case be less focussed on following the DRY rule then when writing a library or an application.

    Additionally if I had to make such a report and the situation would allow it. I would make in in a Jupyter notebook. Here you can nicely mix code with text and graphical output.