Python Over Other Languages

Found this interesting Infographics on Python over other languages. There is no mention of fortran, but everything said for c++ applies to fortran

python over other languages

via Intellipaat

Only a fool learns from his own mistakes…

Risk_savvy_book
Here are some of the notes from the book Risk Savvy: How to Make Good Decisions by Gigerenzer, Gerd.

Loved the book. Many useful rules of thumbs!!

  • If reason conflicts with a strong emotion, don’t try to argue. Enlist a conflicting and stronger emotion.
  • Always ask: What is the absolute risk increase?
  • Always ask for the reference class: Percent of what?
  • When making decisions, so the argument continues, rules of thumb are always second best. Yet that is only true in a world of known risk, not in an uncertain world. To make good decisions in an uncertain world, one has to ignore part of the information, which is exactly what rules of thumb do. Doing so can save time and effort and lead to better decisions.
  • Such a climate is not a good one for innovation, because originality requires taking risks and making errors along the way. No risks, no errors, no innovation.
  • An old clattery auto is to drive a stretch of 2 miles, up and down a hill, /\. Because it is so old, it cannot drive the first mile—the ascent—faster than with an average speed of 15 miles per hour. Question: How fast does it have to drive the second mile—on going down, it can, of course, go faster—in order to obtain an average speed (for the whole distance) of 30 miles an hour?
  • Good errors help us to learn and to discover. A system that makes no errors will learn little and discover even less.
  • Let us compare two professions with opposing error cultures: commercial aviation and medicine. The error culture of Lufthansa’s and other international air companies’ pilots tends to be a positive one and the reason why flying has become so safe.
  • Ask whether checklists are used; if the answer is no or not forthcoming, choose a different hospital.
  • Don’t ask your doctors what they recommend to you, ask them what they would do if it were their mother, brother, or child.
  • Only a fool learns from his own mistakes. The wise man learns from the mistakes of others. – Otto von Bismarck
  • We may have no control about whether people find our clothes or skills or appearance attractive. But we do have control over internal goals such as acquiring languages, mastering a musical instrument, or taking responsibility for small children or our grandparents. The shift toward external goals is not a biological fact engraved in stone; it is possible for all of us to refocus on internal goals and shed excessive anxiety about everyday risks and uncertainties.
  • Solving a problem simply means representing it so as to make the solution transparent. -Herbert A. Simon
  • I believe in the power of simple rules in the real, messy world. They may not always help, but the first question should nevertheless be: Can we find a simple solution for a complex problem? This question is rarely asked. The reflex is to look for complex solutions first and, if they don’t work, to make them even more complex. The same is true in investment. In the wake of financial turmoil that even specialists were not able to predict, simple rules of thumb provide an alternative. Let’s take one complex problem that many of us face. Assume you have a chunk of money and want to invest it. You do not want to put all your eggs into one basket and are considering a number of stocks. You want to diversify. But how? Allocate your money equally to each of N funds.
  • Make everything as simple as possible, but not simpler.
  • Don’t buy financial products you don’t understand.
  • When someone offers her an investment option, she responds: “You have fifteen minutes’ time to explain how it works. If I still don’t understand it, I won’t buy it.” A simple rule like that can reduce global spread of damage.
  • Save 20 percent, spend 80 percent. Saving does not mean hiding money under your pillow, but rather investing it in the future.
  • The intuitive mind is a sacred gift and the rational mind is a faithful servant. We have created a society that honors the servant and has forgotten the gift. -Albert Einstein
  • Not every rule works all the time, just as a hammer does not work for all home repairs. This is why every CEO needs to have a wide range of “tools.”
  • First listen, then speak. If a person is not honest and trustworthy, the rest doesn’t matter. Encourage people to take risks and empower them to make decisions and take ownership.
  • Innovation drives success. You can’t play it safe and win. Analysis will not reduce uncertainty. When judging a plan, put as much stock in the people as in the plan.
  • Many industries, businesses, and restaurants use simple rules for pricing (“Take the cost of raw food and multiply by three”) and for decision making in general (“Don’t build a building without a tenant”).
  • If everything on earth were rational, nothing would happen. -Fyodor Dostoevsky
  • If you are highly proficient at a sport, don’t think too long about the next move. If you are a beginner, take your time in deciding what to do.
  • Make your expert opponents think rather than follow their gut.
  • Ask the waiter: What would you eat here this evening?
  • Keep your eyes wide open before marriage, half shut afterward. -Benjamin Franklin
  • Find the most important reason and ignore the rest.
  • Marry when most of your peers have gotten married.
  • Try to get the partner that your peers desire.
  • Set your aspiration level. 2. Choose the first alternative that meets your aspiration level and then stop searching. This strategy can help you find a spouse, a house, or other important things. Unless the aspiration level is too high, it will lead to fast decisions. If it proves to be too high, it can be lowered, step by step.
  • Avoid Dietary Supplements. Vitamins, minerals, and other nutrients should be consumed through food and drinks, not supplements. Supplements might have unexpected adverse effects causing cancer. Supplements are only needed for people who have diseases that make it difficult to absorb naturally occurring vitamins.
  • Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius—and a lot of courage to move in the opposite direction. -E. F. Schumacher
  • You have to work hard to get your thinking clean to make it simple. -Steve Jobs
  • A leverage ratio is a rule of thumb that aims at being roughly right instead of precisely wrong.
  • I want to encourage people to form and trust their opinions and to express doubts.
  • The more the media report on a health risk, the smaller the danger for you.
  • Becoming informed and speaking out are important steps toward a participatory democracy.
  • The most interesting information comes from children, for they tell all they know and then stop. -Mark Twain
  • Perhaps the most important feature is that the Finnish system places responsibility before accountability. Part of its success is based on a rule of thumb that we encountered in the toolbox of successful leaders:
  • Hire well and let them do their jobs.
  • Don’t just test last month’s topic; include what was learned before and what has not yet been learned.

Analysing Trusses – a python program

truss_in_python

Was digging into my laptop and found this Truss program written in python. Computes, displacement, stresses and reactions.


"""
Created on Thu May 08 07:07:24 2014

@author: Sukhbinder Singh

Truss FEM

"""
from __future__ import division
import numpy as np

modE=30.0e6
Area=2.0


#numElem=3
#numNodes=4

elemNodes=np.array([[0,1],[0,2],[0,3]])
nodeCords=np.array([[0.0,0.0],[0.0,120.0],[120.0,120.0],[120.0,0]])

#'''
elemNodes=np.array([[0,1],[0,2],[1,2],[1,3],
                    [0,3],[2,3],[2,5],[3,4],[3,5],[2,4],[4,5]])

nodeCords=np.array([
[0.0,0.0],[0.0,3000.0],
[3000.0,0.0],[3000.0,3000.0],
[6000.0,0.0],[6000.0,3000.0]
])


modE=70000
Area=300
#'''

numElem=elemNodes.shape[0]
numNodes=nodeCords.shape[0]

xx=nodeCords[:,0]
yy=nodeCords[:,1]

EA=modE*Area
tdof = 2*numNodes #total number of degrees of freedom
disps=np.zeros((tdof,1))
force=np.zeros((tdof,1))
sigma=np.zeros((numElem,1))
stiffness=np.zeros((tdof,tdof))
np.set_printoptions(precision=3)

'''
force[1]=-10000.0
presDof=np.arange(2,9)

'''
force[3]=-50000.0
force[7]=-100000.0
force[11]=-50000.0

presDof=np.array([0,1,9])
#'''

for e in xrange(numElem):
    indice= elemNodes[e,:]
    elemDof=np.array([indice[0]*2, indice[0]*2+1, indice[1]*2, indice[1]*2+1 ])
    xa=xx[indice[1]]-xx[indice[0]]
    ya=yy[indice[1]]-yy[indice[0]]
    len_elem=np.sqrt(xa*xa+ya*ya)
    c=xa/len_elem
    s=ya/len_elem
    k1=(EA/len_elem)* np.array([[c*c,c*s,-c*c, -c*s],
                                [c*s,s*s,-c*s ,-s*s],
                                [-c*c,-c*s,c*c,c*s],
                                [-c*s,-s*s,c*s,s*s]])
    stiffness[np.ix_(elemDof,elemDof)] +=k1


actDof=np.setdiff1d(np.arange(tdof),presDof)

disp1=np.linalg.solve(stiffness[np.ix_(actDof,actDof)],force[np.ix_(actDof)]);
disps[np.ix_(actDof)]=disp1


# stresses at elements

for e in xrange(numElem):
    indice= elemNodes[e,:]
    elemDof=np.array([indice[0]*2, indice[0]*2+1, indice[1]*2, indice[1]*2+1 ])
    xa=xx[indice[1]]-xx[indice[0]]
    ya=yy[indice[1]]-yy[indice[0]]
    len_elem=np.sqrt(xa*xa+ya*ya)
    c=xa/len_elem
    s=ya/len_elem
    sigma[e] = (modE/len_elem) * np.dot(np.array([-c,-s,c,s]),disps[np.ix_(elemDof)])

        
print disps
print sigma

react = np.dot(stiffness,disps)
print react.reshape((numNodes,2))



Why Things Catch On …..

margin_notes_book

These are some of margin notes and snippets from the book  Contagious Why Things Catch On by Jonah Berger

  • Did you know that frowning burns more calories than smiling? That an ant can lift fifty times its own weight? You probably didn’t. But people share these and similar Snapple facts because they are remarkable. And talking about remarkable things provides social currency.
  • Often we’re not even trying to exaggerate; we just can’t recall all the details of the story. Our memories aren’t perfect records of what happened. They’re more like dinosaur skeletons patched together by archeologists. We have the main chunks, but some of the pieces are missing, so we fill them in as best we can. We make an educated guess.
  • The key to finding inner remarkability is to think about what makes something interesting, surprising, or novel.
  • People don’t just care about how they are doing, they care about their performance in relation to others.
  • Scarcity and exclusivity help products catch on by making them seem more desirable. Foursquare doesn’t pay users to check in to bars, and airlines don’t give discounts to frequent flier members.
  • Pathfinder’s destination? Mars. Mars bars are named after the company’s founder, Franklin Mars, not the planet. But the media attention the planet received acted as a trigger that reminded people of the candy and increased sales. Perhaps the makers of Sunny Delight should encourage NASA to explore the sun.
  • When French music was playing, most customers bought French wine. When German music was playing most customers bought German wine. By triggering consumers to think of different countries, the music affected sales. By triggering consumers to think of different countries, the music affected sales. The music made ideas related to those countries more accessible, and those accessible ideas spilled over to affect behavior.
  • So rather than just going for a catchy message, consider the context. Think about whether the message will be triggered by the everyday environments of the target audience. Going for interesting is our default tendency. Whether running for class president or selling soda, we think that catchy or clever slogans will get us where we need to go.
  • As we discussed, one key factor is how frequently the stimulus occurs. Hot chocolate would also have fitted really well with Kit Kat, and the sweet beverage might have even complemented the chocolate bar’s flavor better than coffee.
  • Compare that with how many people think “jelly” when you say “peanut butter” and it will be clear why stronger, more unusual links are better. Linking a product or idea with a stimulus that is already associated with many things isn’t as effective as forging a fresher, more original link.
  • Triggers and cues lead people to talk, choose, and use. Social currency gets people talking, but Triggers keep them talking. Top of mind means tip of tongue.
  • In their wonderful book Made to Stick, Chip and Dan Heath talk about using the “Three Whys” to find the emotional core of an idea. Write down why you think people are doing something. Then ask “Why is this important?” three times. Each time you do this, note your answer, and you’ll notice that you drill down further and further toward uncovering not only the core of an idea, but the emotion behind it.
  • Because shirts are public and socks are private. They’re harder to see.
  • A simple way to figure out which discount frame seems larger is by using something called the Rule of 100.
  • Useful information, then, is another form of practical value. Helping people do things they want to do, or encouraging them to do things they should do. Faster, better, and easier.
  • Piper’s video, entitled “Evolution,” gives a behind-the-scenes look at what goes into making the images we are bombarded with every day. It reminds people that these stunning-looking women are not real. They are fantasies, fictions only loosely based on actual people.

LS-DYNA Examples

LsDynaBirdStrike.avi

Well this one will be a short post.

If you are into analysis and by any chance use LS-Dyna analysis software tool, then I have a site to recommend to you all.

It’s www.dynaexamples.com !!

Yes as the name suggest there are numerous downloadable ls-dyna examples on this website.

Even if you are not into Ls-dyna, but are in analysis, I suggest you take a tour of this website. You will come out by learning something useful.

That’s it, if you know about other sites that might be helpful to other users of this blog, please do name it in comments.

Simple Python code to Extract Fortran Routines and its Argument

fortranRoutinesWithPython
Suppose you got a long fortran file full of code, and want to parse it and get the subroutine/functions defined in the file along with its argument.

Here’s a simple python code to extract all this info in one go

import re
from collections import defaultdict

def processsubroutine(line):
    if ')' in line:
        return line.split("(")[1].split(')')[0].split(',')
    

def collectsubroutines(fname):
    procnam=defaultdict()
    fort_proc_def = re.compile(r'\s*(RECURSIVE)?\s*(SUBROUTINE|FUNCTION)\s+\S+\(*', re.IGNORECASE)
    fp = open(fname,"r")
    datalines=fp.readlines()
    fp.close()
    for i,line in enumerate(datalines):
        if fort_proc_def.match(line):
            procnam[(line.split()[1].split('(')[0])]=processsubroutine(line)
    return procnam

def main():
    for key,item  in procnam.items():
        print key,item

A Simple but useful Python tip.

Want to convert a numpy arrays containing coords from

x1,y1,z1
x2,y2,z2
.
.
.
xn,yn,zn

to

x1
y1
z1
x2
y2
z2
….
xn
yn
zn

Example


print coords
[[ 0.    0.    0.  ]
 [ 0.25  0.    0.  ]
 [ 0.5   0.    0.  ]
 [ 0.75  0.    0.  ]
 [ 1.    0.    0.  ]
 [ 0.    0.25  0.  ]
 [ 0.25  0.25  0.  ]
 [ 0.5   0.25  0.  ]
 [ 0.75  0.25  0.  ]
 [ 1.    0.25  0.  ]
 [ 0.    0.5   0.  ]
 [ 0.25  0.5   0.  ]
 [ 0.5   0.5   0.  ]
 [ 0.75  0.5   0.  ]
 [ 1.    0.5   0.  ]
 [ 0.    0.75  0.  ]
 [ 0.25  0.75  0.  ]
 [ 0.5   0.75  0.  ]
 [ 0.75  0.75  0.  ]
 [ 1.    0.75  0.  ]
 [ 0.    1.    0.  ]
 [ 0.25  1.    0.  ]
 [ 0.5   1.    0.  ]
 [ 0.75  1.    0.  ]
 [ 1.    1.    0.  ]]


change = coords.reshape((-1,1))

print change
[[ 0.  ]
 [ 0.  ]
 [ 0.  ]
 [ 0.25]
 [ 0.  ]
 [ 0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