ipython-books / cookbook-code

[DEPRECATED] See the new edition:

Home Page:http://ipython-books.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Chopped values in the energy-minimization example

moble opened this issue · comments

One of the featured recipes is this nice energy-minimization problem. But I think the final plot is missing some really interesting features. In particular, the function that plots the spring bar contains the line

color=plt.cm.copper(c*150))

This means that negative values (corresponding to compression of the spring, rather than extension) don't get any special coloring -- they get chopped. If you allow for negative values, you can see those compressed springs:

image

You can see that the lower springs near the wall are very compressed, and the diagonal ones get some compression as well. I think that's too interesting to ignore! :)

The simplest way to deal with this would just be

color=plt.cm.copper(abs(c*150)))

But that wouldn't show you which springs are compressed and which are extended. To get the plot above, I defined a new color function

def spring_color_map(c):
    min_c, max_c = -0.00635369422326, 0.00836362559722
    ratio = (max_c-c) / (max_c-min_c)
    color = plt.cm.coolwarm(ratio)
    shading = np.sqrt(abs(ratio-0.5)*2)
    return (shading*color[0], shading*color[1], shading*color[2], color[3])

and then in the plotting function, I did

color=spring_color_map(c)

@moble that's pretty cool! If ever you have time to do a PR (featured recipe and normal recipe) I'd love it :)

Well, I'm happy to do a PR. It's just that my plots are formatted very differently, so I'm not sure if it's easier for you to merge the PR, or just add the code yourself. Anyway, here goes...