planetwater

ground- water, engineering, science, geo- statistics

Spaghetti Plots with LineSegments in Matplotlib

without comments

I recently found out about “LineSegments” in Matplotlib. They allow you to plot “Spaghetti-Plots” fairly easily, without looping in the figure and with comfortable assignment of properties such as color or line thickness.

Beispiel Spaghetti Plot

def plot_LineSegements(x, ys, ylim=[0.0,1.0], label_str='', linewidth=2.0, linestyle='solid', cm='copper' outOS=None):

# set the plot limits, they will not autoscale
ax = plt.axes()
ax.set_xlim((x.min(),x.max()))
ax.set_ylim(ylim)

# colors is sequence of rgba tuples
# linestyle is a string or dash tuple. Legal string values are
#          solid|dashed|dashdot|dotted.  The dash tuple is (offset, onoffseq)
#          where onoffseq is an even length tuple of on and off ink in points.
#          If linestyle is omitted, 'solid' is used
# See matplotlib.collections.LineCollection for more information
line_segments = LineCollection([zip(x,y) for y in ys], # Make a sequence of x,y pairs
                                linewidths    = linewidth,
                                linestyles = linestyle,
                                cmap=plt.get_cmap(cm))
line_segments.set_array(np.arange(np.array(ys).shape[0]))
ax.add_collection(line_segments)
fig = plt.gcf()
axcb = fig.colorbar(line_segments)
axcb.set_label(label_str)
ax.yaxis.grid(color='gray', linestyle='dashed')
ax.xaxis.grid(color='gray', linestyle='dashed')
ax.set_axisbelow(True)
plt.sci(line_segments) # This allows interactive changing of the colormap.
if outOS == None:
    plt.show()
else:
    plt.savefig(outOS)
    plt.clf()

Written by Claus

May 16th, 2012 at 2:49 pm

Posted in

Interesting Bits from ESRI / GIS

without comments

I just came across two interesting pieces related to GIS (from ESRI). The one shows how to use a National Geographic style representation of a somewhat combined political and geographical representation. The other one is a case study of a web-based tool (including some numerical groundwater modelling) for authorizing well permits.

 

- National Geographic style basemap: http://bit.ly/HAn3vb

Representation in National Geographic style of countries in Europe

-  Web-based Automated Well Permitting: http://bit.ly/HAndCM

- ESRI seems to have released some elevation data, and hydrology related data, mostly in the US, and I haven’t checked (just read the blog entry) – http://bit.ly/HzXSJu

 

 

Along similar lines, Microsoft seems to have created a space/time visualization tool called “layerscape” – http://bit.ly/HzXmLE

 

Written by Claus

April 11th, 2012 at 3:59 pm

Posted in

End of Abundance

without comments

“The End of Abundance: economic solutions to water scarcity” is another book about water, particularly drinking water, its shortages and associated problems. Do we need yet another book on that topic?

After I finally got around to read it, I think yes, because it offers some (to me) novel thoughts, that incorporate some basic economic thinking.

Water exists on earth in a constant amount. This amount cycles through the water-cycle at various rates. At some places the amount of available drinking water has been or is shrinking. David Zetland’s book tries to tackle this problem from an economic perspective.

… the real solution to the end of abundance requires that people abandon hard-won traditions that embody decades of distilled experience in exchange for novel ideas and unknown future benefits. A stable institution from one perspective may be rigid from another perspective, but institutions need to evolve with circumstances. In the case of water, good institutions prevent shortage, allowing valuable uses today while saving for tomorrow. Bad institutions make shortage more likely; they can turn abundance into scarcity faster than you can say empty reservoir. What forces a water manager to change the way his organization manages its water? Not much. In most parts of the world, water service is provided by a monopoly, which means each organization chooses how to serve its local customers without fear of competition. [...] The end of abundance means water managers [...] need to either increase supply or reduce demand. Although additional supply can be expensive, the bigger headache comes from allocating the cost of new supply among customers who claim others should pay more. Reducing demand is even harder, since it requires rationing.

End of Abundacne

Photo by VinothChandar – http://flic.kr/p/7Jcr9c

 

Changing a current situation, or changing a current behaviour is difficult. The situation regarding availability of drinking water might be comparable to the problem of climate warming. Some people say capitalism is not useful to lead to necessary change or else the effects of climate change are too detrimental. David Zetland’s book offers some useful thoughts of how thinking along some economic principles might lead to change. I do think that it is not along “big” economic concepts such as free trade or financial speculation. Zetland’s thoughts are more along the lines of local economics.  I would even go as far as saying that his economic thoughts are as simple as thinking through scenarios of what could happen if I paid that amount or an extra amount on the good x at time t , and not a different amount on a different good. This approach gets interesting, when you’re trying to think about the effects on other goods or the same good at different times, at different locations.

David Zetland even writes that such a locally-based approach

[...] reflects water’s local origins and the difficulty of transporting water over long distances. Good water management requires that one understand local customs and solutions while looking for outside ideas that can  be modified and implemented with a creativity that drives at the goal while bending to social, economic and political realities.

This might be the reason why these economic principles are explained with fairly simple graphs. Still, this type of thinking helps to think into different directions that might be useful in the attempt to avoid shortages. When do such shortages occur? David Zetland defines the end of abundance multiple times:

  • The end of abundance is the same as the beginning of scarcity, but scarcity (falling supply and increasing demand) need not lead to shortage.
  • The end of abundance for freshwater means we have to pay more attention to protecting our drinking water and the environment. Our definition of dirty is changing, our rules for discharge are changing, and our perspectives on local and distant are changing. Europeans try to reduce dirty water with regulations. Americans put more emphasis on market solutions (cap and trade of emissions) while also relying heavily on regulations. The end of abundance has a stronger impact on people in developing countries because they have less money and worse institutions
  • The end of abundance (and rise of nasty chemicals) means sludge remaining after primary and secondary treatment is more of a liability than an asset.
  • The end of abundance means prices based on cost need to be upgraded to include scarcity charges. Scarcity-based prices may not keep people from wasting water on lifestyle habits, but they will prevent shortages and ensure that people pay the full cost of their choices.
  • The end of abundance means the supply side/cost recovery model of water management no longer delivers the results we want, but that model still dominates the business — from California to China, Florida to Fiji — and it will cause trouble until we change the way we manage
  • Perhaps the greatest irony in the water business is that the solution to shortage — more supply — often comes from somewhere else at someone else’s expense. The end of abundance results when somewhere else runs out of water.

 

There are many beautiful thoughts in this book that are well worth a discussion. I am going to list three concepts related to water pricing that have been new to me and that I found very interesting:

  • zero net tax (ZNT): consider, for example, an industry whose lobbyists argue against a tax on pollution — claiming that it will destroy jobs, kill babies, open the borders to invasion, and so on. Their lobbying can be overcome by replacing a tax per unit of pollutant with a “zero net tax” (ZNT) that works by measuring average pollution per unit of output, taxing companies that issue above-average pollution, and rebating those tax revenues to below-average polluters (taxes and rebates rise with distance from the average).
  • “Some for Free”. The idea is based on four steps. First, every household pays a service charge equal to the fixed cost of the water connection. Second, the number of people in the household determines how many units of cheap (or free) water the house receives. Third, the price of additional units is set high enough to reduce demand and prevent shortages, not cover costs. Fourth, excess revenue is rebated per capita.
  • Smart Meters: After installing meters, it’s important to think about how often customers see their bills. It’s hard to change behavior when water bills and usage statistics arrive quarterly or annually. Monthly billing is good, but real-time statistics on consumption and volumetric charges give the strongest signals to conserve. Smart meters that measure and display real-time consumption are more expensive to install and operate because they require wireless communications networks to relay data and replace older, simpler meters that last for 30–50 years

For this review I picked three examples that were interesting to me. The book is full of examples, that are worth reading, and would be worth discussing! The combination with the real-world water-related examples and some basic economic theory accomplishes the goal of  how to gain and maintain that balance [between supply and demand] using economic tools to allocate scarce water in a way that minimizes costs, maximizes value and reflects local values. If I had a wish, than it would be to deepen the economic concepts a little more.

Details on the book:

The End of Abundance: economic solutions to water scarcity

by David Zetland

homepage of the book

 


Written by Claus

February 27th, 2012 at 8:45 am

Posted in

Discussion Sites – Where to Find Answers

without comments

It seems not so long ago that I learned the basics of latex on comp.text.tex (btw. Unison is an awesome newsreader). Then came google.groups, and then came just google.

However, recently, I found that a certain category of “search sites” has surfaced. Which seem to be more attractive than the good old usenet. Not sure why. Maybe it’s because you can collect “points”. There are two sites which I started to find interesting:
mathoverflow and stackExchange.

There are really interesting questions being asked and answered:

– What are the examples of situations where “randomizing” a problem (or some part of it) and analyzing it using probabilistic techniques yields some insight into its deterministic version? – see here

or

– What are the big problems in probability theory? – see here

At stackExchange there are even groups:

stats “Cross Validated”

scicomp “Computational Science” (Beta – that’s why it looks “sketchy”)

apple

tex (but don’t forget comp.text.tex!)

 

update Saturday; January 14, 2012:

Just shortly after I wrote this, I found out that there’s a little discussion taking place on math overflow about “the Gaussian”

 

update Sunday; February 12, 2012:

PyDev forums switched to StackOverflow

Written by Claus

January 11th, 2012 at 12:39 pm

Posted in

Identi.ca Weekly Updates for 2012-01-11

without comments

Written by Claus

January 11th, 2012 at 11:11 am

Posted in identi.ca

Identi.ca Weekly Updates for 2012-01-04

without comments

Written by Claus

January 4th, 2012 at 11:11 am

Posted in identi.ca

Pythonanywhere

without comments

What’s not to like about a website called “pythonanywhere“?

I found out about it today from themodernscientist. But does it hold the promise of its name? The deal is, they have python running on their servers, they give you a command shell of your liking (bash, python, ipython) online. Yes, that’s right, online. As in your browser.

This is a really awesome concept. Because it means you can program anywhere, as long as you have access to the internet. You can program on your iPad or your Nokia something. Your computations happen on their server, and you don’t have to worry about installing or updating your python distribution. They have currently numpy version 1.6.1 installed, which is the one currently available in the enthought python distribution.

 

cutout from browser window with a bash shell from python anywhere

 

This is already quite awesome. The next level of awesomeness was reached, when I found out how ridiculous simple it is to connect a dropbox folder to your account at pythonanywhere. That means that both your code as well as your results are synced pretty much immediately. Wow.

I played a little around and calculated a bunch of distance matrices between varying number of locations using scipy.spatial.distance.pdist(). And, alright, the bigger the vector of locations gets, the less efficient is pythonanywhere. However, there is the option of a pypy console.

comparison runtime on pythonanywhere vs. on local machine

So, alright. If you have lots of data and if you need serious computation, this might not be the development environment you’re looking for – yet. I guess the target audience at this stage (the thing is in beta I should note) are web developers.

I can imagine, and I’d like to imagine, that this sort of service is taking off really soon.

Written by Claus

December 30th, 2011 at 8:17 pm

Posted in

[talk] “On the Edge of Tomorrow” by Lester Brown

without comments

When I started studying environmental engineering, the annually released books “State of the Planet” (published by the Worldwatch Institute, there is one for 2011) were places where I derived some of the meaning why I am studying environmental engineering. They were the source from where I learned about reality and its problems.

So I was happy to read at Randy Olson’s blog “The Benshi” about a talk Lester Brown gave recently:

 

Despite Randy criticizing Lester’s rhethoric, I learned a few interesting things from Lester’s talk:

  • Adding nitrogen to soy beans doesn’t improve yields. If you want to increase the yield of soy beans, you have to plant more soy beans.
  • “Wind scales up”: a typical wind power plant produces ~5,000MW of energy, some are up to 10,000MW (which is about ten nuclear power plants). China started recently the development of seven wind power plants, each with a minimum of 10,000MW, the biggest one with 38,000MW. The energy produced by the biggest one would meet the needs of the country of Poland.
  • Lester Brown pieced three indicators which would tell him the status of the planet:
    • economic indicator: price of grain
    • social indicator: number of hungry people in the world
    • political indicator: number of failing states in the world

Written by Claus

December 29th, 2011 at 9:04 pm

Posted in

Identi.ca Weekly Updates for 2011-12-28

without comments

Written by Claus

December 28th, 2011 at 11:11 am

Posted in identi.ca

Merry Christmas 2011

without comments

I’d like to wish all my readers a Merry Christmas 2011!

Who could tell a better christmas narration than Heribert Prantl, published today in the Süddeutsche Zeitung? Interestingly, its theme is “counting”, a big part of statistics. In the german language, the words “counting” and “narration” have the same root. According to Prantl, the one is symbolic for “modern” times, effectivity or accountability; the other is related to human beings.

 

Vor der großen Erzählung kommt die große Zählung. Die Weihnachtsgeschichte beginnt nicht weihnachtlich, sondern staatlich. Sie beginnt mit der Geschichte von der Erfassung des Lebens, sie beginnt mit der Unterwerfung des Lebens unter die Zahl: Alle aufschreiben, alle erfassen, alles aufzeichnen. Der Gottkaiser Augustus hat allen Bewohnern seines Reiches befohlen, sich in ihren jeweiligen Geburtsstädten registrieren zu lassen. Er setzt damit, zu seinen Zwecken, die ganze Welt in Bewegung. Wie diese Geschichte ausgeht, um wie viel die Steuereinnahmen des Imperiums gestiegen sind – das erfahren wir nicht mehr, weil der Evangelist Lukas diese Zählgeschichte abbricht und eine Gegengeschichte beginnt: die Weihnachtsgeschichte. Zählen ist Macht Sie handelt von kleinen Leuten, von Maria und Josef, einem Kind in der Krippe und von Hirten; es ist eine Geschichte über Leute, die zwar gezählt werden, die aber eigentlich nichts zählen. Vordergründig folgen sie dem Gebot. Sie sind gehorsam, machen sich auf den Weg; aber der mündet ganz woanders, nicht bei der Zählung, sondern in einer großen Erzählung.

Es beginnt eine Befreiungsgeschichte, in der eine Botschaft „vom Himmel“ kommt und der Kontroll-Befehl des Augustus von oben, von Engeln und himmlischen Heerscharen, durchlöchert und abgelöst wird. Abgelöst wird die höchste Instanz, diejenige, die mit Zahlen regiert. Auch wenn man das Ganze nur für ein aberwitzig schönes Märchen hält – das Wahre an dieser Gegengeschichte ist: Sie hat die Welt verändert. Aus der Gegengeschichte über die kleinen Leute ist große Geschichte geworden. Kein Mensch würde von der Zählung des Augustus wissen, wenn mit ihr nicht die Weihnachtsgeschichte beginnen würde – die als Beginn einer Befreiungsgeschichte gedeutet wird. Sie stellt nicht weniger als einen neuen Himmel und eine neue Erde in Aussicht. Sie hat eine klare Botschaft: Höchstes Wesen ist nicht ein Kaiser, sondern ein Mensch, der ohne Obdach zur Welt kommt. Sie ist die Geschichte von der großen Umkehrung. Im Himmel und auf Erden zählt letztlich nur eine Währung. Die heißt nicht Sesterz, Euro oder Dollar, sondern – Entschuldigung – Liebe. Wer das nicht kapiert, ist ein Schaf, auch wenn er Nobelpreisträger wäre. Und wer das zu gefühlig findet oder sich selber nicht mag, der kann es für sich ja so übersetzen: Man muss den Menschen neben sich nicht mögen, braucht sich keine falschen Gefühle einreden, muss ihn aber respektieren – ihn also so behandeln, wie man selber behandelt werden will. Dann braucht man nicht die sarrazineske Angst vor den Unterschieden zu haben.

Wer die Weihnachtsgeschichte versteht, der sieht den Mensch hinter der Zahl. Das ist Liebe. Die Kaiser heißen heute anders, sie heißen Markt, Rendite, Effektivität und Sicherheit. In ihrem Namen wird so viel gezählt wie nie zuvor. Es wird gezählt, was die Leute wann und wo kaufen, es werden zu Werbezwecken Profile von ihren Vorlieben angelegt, sie werden zur Einschätzung von Finanzkraft und Kreditwürdigkeit sortiert, ihre Kaufwünsche werden vorausberechnet – im Internet so akribisch und treffsicher wie noch nie. Persönlichste Daten werden umfassend erfasst. Vom Staat, im Interesse der Sicherheit; und von der Wirtschaft, im Interesse guter Geschäfte. Es wird gerankt, evaluiert und angeblich Qualität analysiert, die dann oft wiederum an der Quantität, also an der Zahl, gemessen wird. Gezählt werden auch die Dienste der Menschlichkeit. Pflege wird in Module getaktet; die Krankenschwestern in der häuslichen Pflege sind mit Zeiterfassungsgeräten unterwegs. Die halten fest, ob die vorgeschriebenen knappen Zeiten für die Alten eingehalten werden. Waschen, füttern, Windeln wechseln – alles nach Minuten und Sekunden. Menschliche Begegnung wird aufgefressen von der Zähl- und Nachweisbürokratie. Bei der Betreuung von Suchtkranken, von psychisch Kranken und Wohnungslosen werden „face-to-face“-Kontakte gezählt, sie müssen von den „Betroffenen“ unterschrieben werden, und nur dafür wird gezahlt. In Sozialdiensten, Medizin und Altenpflege ist es so wie auf dem öffentlichen Klo. Dort hängen die Listen aus, auf denen die Reinigungskräfte eintragen müssen, wann sie geputzt haben. Eine solche Erfassung scheint für Ordnung in einer unordentlichen Gegenwart zu sorgen. Sie sorgt aber vor allem für Effizienz und Gewinn. Die heutige Allgegenwart der Erfassung ist Kennzeichen und Symbol für eine Gesellschaft in ihrem Übergang von der festen zur flüchtigen Phase der Moderne: Aus Arbeit wird Leiharbeit, aus dem Beruf werden Jobs auf Zeit, aus dem Leben eine Aneinanderreihung von Situationen, wechselnden Rollen, Projekten und Episoden. Arbeit und Leben werden zerlegt in immer kleinere Stücke; stabile Gemeinschaften und soziale Bindungen werden abgelöst von Netzwerken und wechselnden Patchwork-Konstellationen. Früher gab es Identitätszwänge, aber es gab immerhin Identität; diese Identität wird von Flexibilität abgelöst, und Lebensplanung zu einem Wort aus der Vergangenheit.

Das Leben von immer mehr Menschen verliert seinen Faden. Daraus resultieren mehr Ängste als aus den Turbulenzen um den Euro. Der Mensch wird, und das macht Angst, dem Geld immer ähnlicher: Geld treibt dahin, ist flüchtig, ballt sich zusammen. Es muss nicht wundern, dass die Flüchtlingsströme den Geldströmen folgen. Die Existenz dieser Flüchtlinge wird allenfalls als Zahl registriert, ihre Geschichte interessiert niemanden. Erzählen heilt Leben wird aber nicht durch Zahlen erfasst, sondern durch Erzählung beschrieben. Eine Lebensgeschichte ist nicht Addition und Subtraktion bestimmter Zahlen und Daten, sondern Erzählung des nicht Be- und Verrechenbaren. Die Weltreligionen wissen davon. Sie stellen den Menschen große Geschichten bereit, in die sie ihre kleinen Lebensgeschichten einschreiben können. Es sind dies allgemein anerkannte Grunderzählungen, in denen die Menschen ihre eigenen Lebenserzählungen miterzählt wissen. Diese großen Geschichten, in der Bibel heißen sie oft Gleichnisse, handeln vom Alltag kleiner Leute, die dem Leben der Bedeutungslosen Bedeutung geben und dabei Krankheit, Verlorenheit, Angst, Verzweiflung und Tod nicht auslassen. Die Weihnachtsgeschichte ist ein Beispiel. Sie ist Ouvertüre zu vielen anderen Geschichten, in denen gespeist, gerettet, geheilt und von den Toten auferweckt wird. Es sind Hoffnungsgeschichten. Jahrhundertelang haben sich die Menschen darin wiedergefunden. Das funktioniert nicht mehr so richtig, nicht nur wegen der Säkularisierung. Auch deshalb, weil die Menschen in der getakteten Welt das Erzählen und Zuhören verlernt haben. Um zu erzählen, braucht man ein Gegenüber, das die Geschichte hören will und sich die Zeit nimmt. Mit dem Erzählen beginnt die Gegengeschichte zur flüchtigen Moderne, beginnt der Widerspruch. Erzählen schützt davor, im Gefühl der Sinnlosigkeit zu versinken. Erzählen heilt. Zuhören auch. Man nimmt dabei den anderen wahr – als Mensch, nicht als Gefahr. Das ist Weihnachten.

Written by Claus

December 24th, 2011 at 5:58 pm

Posted in