crossz

Archive for November 28th, 2007

Symbolic Operations in Matlab

In howto, matlab on November 28, 2007 at 8:48 pm

Background Note:

Up to this point we have done purely numerical operations in Matlab. This is the traditional approach for solving problems on the computer, and much of the current computational work done in industry follows this approach. However, a relatively new capability (last 5-10 years or so) that is gaining popularity involves the use of symbolic operations directly on the computer. Computer programs that use these symbolic techniques are often referred to as computer algebra systems, and they are becoming quite powerful. In particular, Matlab’s Symbolic Math Toolbox offers this general capability within the Matlab environment by providing an interface to the Maple code (Maple is a commercial software package that emphasizes symbolic manipulations or computer algebra techniques). This set of labs will introduce some of the basic symbolic capability in Matlab, eventually leading up to the analytical solution of Ordinary Differential Equations directly on the computer. Many of the exercises given here are derived from the Matlab’s User’s Guide and you are encouraged to refer to that manual for further examples and guidance.

Define Some Symbolic Variables:

First define a bunch of symbolic variables: syms a1 b1 c1 a2 b2 c2 d2 A B C1 C2 x y t

Now let’s form some symbolic functions:

Mathematical Function
Matlab Syntax for Function

f1 = a1 + b1*x + c1*x^2

f2 = a2 + b2*x + c2*x^2 + d2*x^3

g = exp(A*t)*(C1*cos(B*t)+C2*sin(B*t))

u = 2*x*y^2 + sin(x+y)

Differentiation of Symbolic Functions:

Differentiate each of the above functions using Matlab’s diff command. For example, try diff(f1). What happened? Is the result correct? Do the same thing for the other functions. What happens when you type diff(u)? How do you get Matlab to take the partial derivative with respect to the variable y? Type help sym/diff to see the various options associated with taking symbolic derivatives.

We can also take higher order derivatives. For example diff(f1,2) takes the second derivative of f1(x). Try this for all the functions!

Can you show that the mixed partial derivatives of u(x,y) are equal? Take du/dx and du/dy as above and save the results as string variables. For example, try typing

dudx = diff(u,x); dudy = diff(u,y);.

Now take the first derivative of these symbolic variables, as follows:

uyx = diff(dudx,y); uxy = diff(dudy,x);

Are these latter two variables the same? They should be. Pretty neat stuff, don’t you think!!!

Integration of Symbolic Functions:

Using Matlab’s int function, perform the following integrals using f1(x):

Mathematical Operation
Matlab Syntax for Operation

I1 = int(f1)

I2 = int(f1, 0, 5)

Do these make sense? Check out the subs command. Now let a1 = 1, b1 = -2, and c1 = 1, and substitute these numerical constants into the symbolic expressions for I1 and I2, as follows:.

I1 = subs(I1,{a1 b1 c1},{1 -2 1}), I2 = subs(I2,{a1 b1 c1},{1 -2 1})

What are the values for the integrals I1 and I2? Why is I1 a function of x and I2 is simply a scalar number? Note also that the curly brackets in Matlab refer to cell arrays. The sequence given by the set, {a1 b1 c1},{1 -2 1}, replaces the numerical variables into the symbolic variables in sequence. The cell array simply let’s us make all three substitutions in one call to the subs command.

Try integrating and substituting values for the constants in the other functions. Note that with u(x,y), you can only integrate with respect to one variable at a time. For example,

Mathematical Operation
Matlab Syntax for Operation

Iu = int(int(u,x,0,pi),y,0,2*pi)

Pretty impressive!!! Could you do this integral by hand this fast? I certainly can’t…

Plotting Symbolic Functions:

Certainly we can also plot symbolic relationships. Since we have already defined the constants for use with f1(x), let’s use this function to do some simple plots. In particular, let’s plot f1(x), df1/dx, and over the range . We can do this as follows:

F1 = subs(f1,{a1 b1 c1},{1 -2 1}); D1 = diff(F1); I1 = int(F1);
Nx = 51; xp = linspace(0,5,Nx);
F1p = double(subs(F1,x,xp));
D1p = double(subs(D1,x,xp));
I1p = double(subs(I1,x,xp));
plot(xp,F1p,’r-‘,xp,D1p,’g–’,xp,I1p,’b-.’),grid
title(‘Evaluating and Plotting Symbolic Functions’)
xlabel(‘X Values’),ylabel(‘Various Function Values’)
legend(‘Function’,’First Derivative’,’Integral’)

Solving Algebraic Equations:

We can also solve algebraic equations with Matlab. For example, what if we wanted to know the value of x where f1(x) = 3? With the above constants this problem becomes: find x such that

In Matlab, we can use the solve command: solve(x^2-2*x-2) or solve(F1 – 3).

We can also solve systems of algebraic equations. For example, the analytical solution to the following 2×2 system:

is given by:

S = solve(3*x + 2*y – 3,-2*x + y + 7); % this solves a simple set of 2×2 equations

S.x, S.y % this prints x and y to the screen

Solving Ordinary Differential Equations:

The real goal of the above discussion and examples with symbolic variables is to give enough background so that we can solve ODEs analytically on the computer. This will be pretty powerful capability if we can actually do this with a set of relatively simple commands. As a test, let’s give Matlab’s dsolve command a workout for a few different types of ODEs that we have treated thus far in the semester (be sure to type help dsolve to get a good idea of the various forms that can be used).

a. Solve the first order IVP:

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’x’) % this gives the general solution

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’y(1) = 0’,’x’) % this gives the unique solution

b. Solve the second order IVP:

Sh = dsolve(‘D2y – 4*y = 0′,’x'), pretty(simple(Sh)) % homogeneous soln
Sg = dsolve(‘D2y – 4*y = 4*x^2′,’x'), pretty(simple(Sg)) % general soln
Su = dsolve(‘D2y – 4*y = 4*x^2′,’y(0) = -1/2′,’Dy(0) = 4′,’x') % unique soln
pretty(simple(Su))

c. Solve the second order IVP:

Q1 = dsolve(‘D2y + 6*Dy +13*y = 10*sin(5*t)’, ’y(0) = 0’,’Dy(0) = 0’,’t’)
pretty(simple(Q1))

d. Re-solve the problem in Part c as a system of two 1st order ODEs, where z1 = y and z2 = dy/dt:

Q2 = dsolve(‘Dz1 =z2’,’Dz2 = -13*z1 -6*z2 + 10*sin(5*t)’, ’z1(0) = 0’,’z2(0) = 0’,’t’)
pretty(simple(Q2.z1)), pretty(simple(Q2.z2))

Final Note:

There is a lot of good stuff here. In particular, there are several examples that should make your life much easier in this course and in several of your other technical classes. You should do your best to understand the basic capability that is illustrated here — it represents some pretty powerful mathematical analysis capability. You should also note that some of the examples from earlier in the semester (the Two Salty Tanks problem for example) give other illustrations of the use of computer algebra to solve a coupled set of first order differential equations for a real problem of interest. Also, a final Matlab demo will be given at the end of the semester illustrating how to take Laplace transforms and inverse Laplace transforms analytically using Matlab’s symbolic processing capability.

########
from: http://www.tmt.ugal.ro/crios/Support/ANPT/Curs/deqn/labs/mlabex_symbolic/mlabex_symbolic.html

Scjp Study Guide 310-055

In java on November 28, 2007 at 3:04 pm

Science in Silico

In Blogged on November 28, 2007 at 2:53 pm
To download the full version visit vuze.com

Powered by ScribeFire.

Science in Silico

In Blogged on November 28, 2007 at 2:53 pm
To download the full version visit vuze.com

Powered by ScribeFire.

unittest模块

In howto, python on November 28, 2007 at 11:42 am
unittest模块是用python编写的,其功能与junit一样,都是为了方便单元测试用的测试框架。
unittest模块是从python
2.1引入标准库的。它包含几个类:TestCase,TestSuite,TestResult,TextTestRunner等等。要建立自动测试,
必须创建unittest.TestCase的子类。然后定义一连串的test测试函数。使用assertXXX来下断言。测试成功就ok,测试错误就
Error,测试失败就Fail,共3种状态。比如:

import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):

self.zd=ysfile.ZDYSFile(‘ysh1b1.09′)

def testGetYear(self):

self.assertEqual(self.zd.getYear(),2005)

def testGetLoca_bz(self):

self.assertEqual(self.zd.getLoca_bz(),4)

class TestPDYSZipFile(unittest.TestCase):

def setUp(self):

self.pd=ysfile.PDYSZipFile(‘pdysj09.zip’)

def testGetCdate(self):

self.assertEqual(self.pd.getCdate(),’20050117′)

if __name__ == ‘__main__’:

#unittest.main()

suite = unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestZDYSFile))

suite.addTest(unittest.makeSuite(TestPDYSZipFile))

unittest.TextTestRunner(verbosity=2).run(suite)

unittest.main()是用来调用所有的测试实例,unittest.TestSuite()是用来组合相关的测
试实例的,用addTest方法添加测试实例。setUp和tearDown方法是用来建立必要的测试环境,例如变量,文件等。tearDown进行一些
扫尾工作。

Powered by ScribeFire.

unittest模块

In howto, python on November 28, 2007 at 11:42 am
unittest模块是用python编写的,其功能与junit一样,都是为了方便单元测试用的测试框架。
unittest模块是从python
2.1引入标准库的。它包含几个类:TestCase,TestSuite,TestResult,TextTestRunner等等。要建立自动测试,
必须创建unittest.TestCase的子类。然后定义一连串的test测试函数。使用assertXXX来下断言。测试成功就ok,测试错误就
Error,测试失败就Fail,共3种状态。比如:

import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):

self.zd=ysfile.ZDYSFile(‘ysh1b1.09′)

def testGetYear(self):

self.assertEqual(self.zd.getYear(),2005)

def testGetLoca_bz(self):

self.assertEqual(self.zd.getLoca_bz(),4)

class TestPDYSZipFile(unittest.TestCase):

def setUp(self):

self.pd=ysfile.PDYSZipFile(‘pdysj09.zip’)

def testGetCdate(self):

self.assertEqual(self.pd.getCdate(),’20050117′)

if __name__ == ‘__main__’:

#unittest.main()

suite = unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestZDYSFile))

suite.addTest(unittest.makeSuite(TestPDYSZipFile))

unittest.TextTestRunner(verbosity=2).run(suite)

unittest.main()是用来调用所有的测试实例,unittest.TestSuite()是用来组合相关的测
试实例的,用addTest方法添加测试实例。setUp和tearDown方法是用来建立必要的测试环境,例如变量,文件等。tearDown进行一些
扫尾工作。

Powered by ScribeFire.

unittest模块

In howto, python on November 28, 2007 at 11:42 am
unittest模块是用python编写的,其功能与junit一样,都是为了方便单元测试用的测试框架。
unittest模块是从python
2.1引入标准库的。它包含几个类:TestCase,TestSuite,TestResult,TextTestRunner等等。要建立自动测试,
必须创建unittest.TestCase的子类。然后定义一连串的test测试函数。使用assertXXX来下断言。测试成功就ok,测试错误就
Error,测试失败就Fail,共3种状态。比如:

import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):

self.zd=ysfile.ZDYSFile(‘ysh1b1.09′)

def testGetYear(self):

self.assertEqual(self.zd.getYear(),2005)

def testGetLoca_bz(self):

self.assertEqual(self.zd.getLoca_bz(),4)

class TestPDYSZipFile(unittest.TestCase):

def setUp(self):

self.pd=ysfile.PDYSZipFile(‘pdysj09.zip’)

def testGetCdate(self):

self.assertEqual(self.pd.getCdate(),’20050117′)

if __name__ == ‘__main__’:

#unittest.main()

suite = unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestZDYSFile))

suite.addTest(unittest.makeSuite(TestPDYSZipFile))

unittest.TextTestRunner(verbosity=2).run(suite)

unittest.main()是用来调用所有的测试实例,unittest.TestSuite()是用来组合相关的测
试实例的,用addTest方法添加测试实例。setUp和tearDown方法是用来建立必要的测试环境,例如变量,文件等。tearDown进行一些
扫尾工作。

Powered by ScribeFire.

Compiling Python(Jython) and for Java

In howto on November 28, 2007 at 12:19 am

Another view: Jython is the extension language for Java.

Use jythonc. What is jythonc and what is its status?

jythonc transforms Python source code into Java source code then invokes a Java compiler to turn it into .class files. This allows Python to be integrated into Java in several places that regular Jython currently doesn’t support. It also processes special annotations in docstrings on methods in Python code to determine the static type information to expose when turning a dynmically typed Python method into a statically typed Java method.

jythonc is unmaintained and will not be present in Jython-2.3. While jythonc handles all of the language features present in Jython 2.2, it doesn’t support 2.3 features such as generators. As such, it is not recommended that new Jython projects make use of jythonc. It is only included in Jython-2.2 to support older users of jythonc and to allow access to a few features that are only provided by jythonc at the moment:

  1. Running in a JVM with a classloader that will not load dynamically created classes
  2. Declaring Java method signatures in Python code
  3. Loading Python classes dynamically from Java with Class.forName

While all of these features are planned for Jython-2.3, they are currently only available from jythonc. Most uses of the second feature, adding method declarations to docstrings, can be handled by declaring a Java interface to implement with a Python class. Each method in the Python implementation takes the types of the Java method it implements. Exposing the Python class as an instance of that type to Java code can be done as explained in Accessing Jython from Java Without Using jythonc and its followup, Simple and Efficient Jython Object Factories.

(See http://www.jython.org/Project/jythonc.html)

You can extend Java classes.

You can add (J)Python protocols to Java classes.

You will need to describe the signature of methods in order to make them callable from Java (in addition to Jython).

What jythonc does — jythonc translates .py files into .java source code files, then compiles these to .class files.

With jythonc, you can also:

  • Compile Jython (.py) to Java class files (.class).

  • Compile Jython to Java source, then stop without compiling to .class files.

  • Use a Java compiler different from the default: javac. See the help from jythonc:

    --compiler path-C path    Use a different compiler than `standard' javac.  If this is set to    `NONE' then compile ends with .java.  Alternatively, you can set the    property python.jpythonc.compiler in the registry.

    This option can also be set in your Jython registry file.

Java compatible classes – In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

  • Inherit from a Java class or interface.
  • Include only one class per module.
  • Give the Jython class and the source file that contains it the same name.
  • Place all code inside that Jython class.
  • Include method signature hints (called sig-strings) — Add a @sig line in the doc-string for each method.

How to use jythonc:

  • Type jythonc --help for help.

  • Compile your Jython code with:

    jythonc mymodule.py
  • To get help for jythonc, type:

    $ jythonc --help

Some notes:

  • When your run jythonc, by default, the .java files are placed in a sub-directory ./jpywork. You can override this with the --workdir command line option. From jythonc --help:

    --workdir directory-w directory    Specify working directory for compiler (default is ./jpywork)
  • When you run this resulting code from Java, the directory ./jpywork and the Jython jar file must be on your classpath.

Example — The following Jython code extends a Java class. Compile it with jythonc:

# Foo.py

import java

class Foo(java.util.Date):    def __init__(self):        self.count = 0    def bar(self, incr=1):        """@sig void bar(int incr)"""        self.count += incr        return self.count    def toString(self):        cnt = self.bar()        return "Foo[" + java.util.Date.toString(self) + " " + `cnt` + "]"

Example, continued — Here is Java code to test the above. Compile it with javac and run it:

// FooTest.java

import Foo;

public class FooTest {     public static void main(String[] args) {         Foo foo = new Foo();         System.out.println(foo);         foo.bar();         foo.bar(43);         System.out.println(foo);     }}

Notes:

  • Compile and run:

    $ javac FooTest.java$ java FooTest
  • You will need jpywork on your classpath. So, you can compile and run it as follows:

    $ ../../Jython-2.2a/jythonc Foo.py$ javac -classpath ../../Jython-2.2a/jython.jar:./jpywork FooTest.java$ java -classpath ../../Jython-2.2a/jython.jar:./jpywork FooTest

In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

  • Inherit from a Java class or interface.
  • Include method signature hints (called sig-strings).
  • Give the Jython class and the source file it is in the same name.

Here is another simple example:

"""simpleclass.py

This is a simple class to demonstrate the use of jythonc."""

import java.lang.Object

class simpleclass(java.lang.Object):    def __init__(self, name='The Horse With No Name'):        """public simpleclass(String name)        """        self.name = name        self.size = -1    def set_name(self, name):        """@sig public void set_name(String name)        """        self.name = name    def set_size(self, size):        """@sig public void set_size(int size)        """        self.size = size    def show(self):        """@sig public String show()        """        return 'name: %s  size: %s' % (self.name, self.size, )

And, a Java test harness for this simple example:

// simpleclasstest.java

import simpleclass;

public class simpleclasstest {    public static void main(String[] args) {    String s1;    simpleclass sc = new simpleclass();    s1 = sc.show();    System.out.println("1. " + s1);    sc.set_name("dave");    sc.set_size(4321);    s1 = sc.show();    System.out.println("2. " + s1);    }}

Notes:

  • In order to produce a Java compatible class, our Jython class must inherit from a Java class. In this case, we use java.lang.Object, because we do not need to inherit any behavior.
  • The methods set_name, set_size, and show each have sig-strings.

Put jpywork on your CLASSPATH, then use the following to compile and test the above:

$ jythonc simpleclass.py$ javac simpleclasstest.java$ java simpleclasstest1. name: The Horse With No Name  size: -12. name: dave  size: 4321

In the following example, we create a stand-alone Jar file, that is, one that can be executed as a script on a machine where Jython is not installed. Here is the Jython script:

# test_jythonc.py

import sys

def test(words):    msgs = ['hi', 'bye']    for word in words:        msgs.append(word)    for msg in msgs:        print msg

def main():    args = sys.argv[1:]    test(args)

if __name__ == '__main__':    main()

Compile and build a Jar file with the following:

$ jythonc --all --jar mytest.jar test_jythonc.py

Run it as follows:

$ java -jar mytest.jar hello goodbyehibyehellogoodbye

Notes:

  • Note that our Jython script contains no class. jythonc will create a public class and a public static main function for us.
  • The --jar flag tells jythonc that we want the results placed in a Jar file (as opposed to placing it in the work directory ./jpywork).
  • The --all flag tells jythonc to include all Jython support in the Jar file, making it stand-alone. This enables us to run it on a system where Java is installed but Jython is not.

16.1   Calling Jython Code from Jython

From Jython, you can run Jython and Python code. When you do so, you may run Java code that is in a super-class or is used by the Jython code.

But, notice that, from Jython, you cannot call Python code that has been extended with C.

16.2   Calling Jython Code from Java

Must compile Jython/Python to Java with jythonc.

Must pay attention to method signatures. Define method signature in Jython in a doc string with @sig. Then look at the generated .java file.

Other things to be aware of:

  • Must set classpath to include jpywork.
  • Must write a Java compatible class. See above.

16.3   Another example — Jython-2.2a/Demo/javaclasses

What this example shows:

  • How to write a class that can be compiled (with jythonc) and then called from Java.
  • How to write method signatures for Jython methods.
  • How to compile the the Jython code and the Java code.

For example, I compiled and ran the example in Jython-2.2a/Demo/javaclasses with the following:

$ rm -rf jpywork/$ ../../jythonc --package pygraph Graph.py$ javac -classpath .:../../jython.jar pygraph/PythonGraph.java$ java -classpath .:../../jython.jar:jpywork pygraph.PythonGraph

For more information, see Jython-2.2a/Demo/javaclasses/readme.txt.

From:http://www.rexx.com/~dkuhlman/jython_course_01.html#another-example-jython-2-2a-demo-javaclasses

Blogged with Flock