Embedding IronPython

| | Comments (0)

In my current programming project, I've embedded IronPython in a C# program. I thought I would share the basics of embedding a scripting engine. I imagine the process would be the same for any language that uses the DLR (Dynamic Language Runtime), like IronRuby. Here is a sample using IronPython 2.0 Beta 5.

using System;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
 
public class Program
{
    // Delegate matching the signature of the factorial function
    delegate int FactorialDelegate(int n);
 
    static void Main(string[] args)
    {
        // Our factorial function
        string[] lines = {"def factorial(n):",
                          "  for i in range(1, n):",
                          "    n = n * i",
                          "  return n"};
 
        string code = String.Join("\r", lines);
 
        // Instantiate the IronPython environment
        ScriptEngine engine = Python.CreateEngine();
 
        // Create a scope/module to work in
        ScriptScope scope = engine.CreateScope();
 
        // A little preparation
        ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
 
        // Compile the code
        CompiledCode compiled = source.Compile();
 
        // Execute the code in the scope
        compiled.Execute(scope);
 
        //Now the factorial function exists in the IronPython environment. Let's use it.
 
        // Set x = 5
        scope.SetVariable("x", 5);
 
        // print factorial(x)
        ScriptSource print = engine.CreateScriptSourceFromString("print factorial(x)", SourceCodeKind.SingleStatement);
        print.Execute(scope);       //outputs 120
 
        // Get the result from IronPython
        int result1 = scope.Execute<int>("factorial(6)");
        Console.WriteLine(result1); //outputs 720
 
        // We can also call the function directly from C#
        FactorialDelegate factorial = scope.GetVariable<FactorialDelegate>("factorial");
        int result2 = factorial(7);
        Console.WriteLine(result2); //outputs 5040
 
        Console.Read();
    }
}

Math.BigMul Exposed

| | Comments (0)

Today a friend and I were reflecting through System.Math (courtesy of IronPython) and we noticed the BigMul method:

Math.BigMul(Int32, Int32) : Int64

Why have a method just for multiplication? It seems to be a trivial reason to add a method to the .NET framework. After all, multiplication with casting does the same thing:

(long)a * (long)b

Being optimistic, I suggested that perhaps Microsoft's BigMul is implementing a faster and more efficient multiplication algorithm. Maybe there is a clever way to multiply two 32 bit numbers without explicit casting to 64 bit. Naturally, I wrote a simple speed test.

static void Main(string[] args)
{
    int a = 40993;
    int b = 69872;
    long c = 0;
 
    DateTime start;
    TimeSpan length;
 
    Console.WriteLine("Inline multiplication");
    start = DateTime.Now;
    for (int i = 0; i < 1000000000; i++)
        c = (long)a * (long)b;
    length = DateTime.Now - start;
    Console.WriteLine(c);
    Console.WriteLine(length.ToString());
    Console.WriteLine();
 
    Console.WriteLine("Math.BigMul");
    start = DateTime.Now;
    for (int i = 0; i < 1000000000; i++)
        c = Math.BigMul(a, b);
    length = DateTime.Now - start;
    Console.WriteLine(c);
    Console.WriteLine(length.ToString());
    Console.WriteLine();
 
    Console.Read();
}

The results were not encouraging.

I prefer Firefox as my default web browser. For website development, Firefox with Firebug is a killer combination. But when I test a page in Internet Explorer, I sometimes get cryptic Javascript errors that are impossible to track down. It turns out that Internet Explorer needs some coaxing to play nice with Visual Studio.

Enable Javascript Debugging
Open Internet Options and head over to the Advanced tab. Uncheck Disable script debugging (Internet Explorer).

debugging-ie-1.jpg

That's all it takes; the next time you encounter a Javascript error, you will be prompted to debug. Select an instance of Visual Studio and you'll have interactive debugging.

Launch with Internet Explorer
When you run or debug a website, Visual Studio uses you default system browser. But maybe you prefer to debug in a different browser. To change this setting, right-click on an aspx file in Solution Explorer and select Browse With. Select the desired browser and set it as default.

Select a default browser

That's it! Do you have any tips or tools for website debugging?

Linguistic Networks

| | Comments (0)

The following is a report I wrote for my Artificial Intelligence course in November 2006. It discusses Franklin Chang's article entitled "Symbolically speaking: A connectionist model of sentence production."

Linguistic Networks F. Chang developed neural networks to produce proper sentences from basic messages. His networks were implemented on LENS neural network software. This research was performed around the year 2000 and a paper detailing his research and findings was published as an article in Cognitive Science in 2002. In this paper, I will explain, summarize, and analyze his article.

Background

Because Chang's models are neural networks mimicking human linguistic abilities, comprehension of his work relies on familiarity with linguistics and connectionist models. Linguistics will be addressed as necessary throughout this paper. A neural network is a computing model comprised of nodes (also called units) grouped into layers. The nodes between two layers are connected by weights. As nodes are activated, the activations of each layer are passed forward to the next layer by the connecting weights. Layers are connected in a forward-feeding fashion so that there are no loops. The value of a weight determines how much of the activation from the sending node is transferred to the receiving node. The total of all the activations received by a node determines its activation value. The result is a network of nodes that pass activations forward through the network. Activations originate from the input layers, which serve as the input for the network. These activations feed-forward to the output layers, whose activations serve as the output of the network. Learning occurs as weights are adjusted to correct the actual output values to match the desired output values.

The following is a report on my C# program, WinOthello. I designed it for my Artificial Intelligence course in November 2006.

Download (57 KB) the game or the source code (85 KB).
Provided under a permissive open source license.
.NET Framework 2.0 required.


Abstract
WinOthello ScreenshotAs an exploration of artificial intelligence and particularly game state space search, I developed WinOthello to simulate Othello games. This application allows human and computer players to interact with a virtual game board displayed on the user's screen. The primary objective of WinOthello was to devise an adept computer player that proves challenging to average human players. This goal was achieved via a depth-limited minimax search of the game space and quickened with the application of alpha-beta pruning.

What is Othello?
Othello is a strategic two-person board game. Players take turns placing pieces on an eight-by-eight board. Each piece has two distinct faces: a light face and a dark face. The first player is designated the dark player and places pieces on the board dark side up. The second player is the light player and places pieces light side up. Pieces can only be placed in positions that outflank the opponent's pieces. Outflanking occurs when a player places a piece that causes a contiguous line of one or more of the opponent's pieces to be bounded by the player's pieces. All of the opponent's outflanked pieces are then flipped over, and the turn ends. If a player can not place a piece, then play passes to the other player. The game ends when neither player can place any more pieces. The player with the most corresponding pieces on the board at the end of the game wins.

Genius - Made or Born?

| | Comments (3)
The following is a report I wrote for my Artificial Intelligence course in September 2006. It discusses an article by David Dobbs entitled "How to be a genius." This report also references an email exchange (source not available) between Douglas Hofstadter and David Dobbs.

In the email conversation between Howard Rutiezer and Douglas Hofstadter, Rutiezer presents an article by David Dobbs while Hofstadter rebuttals it with his own observations. The topic of discourse is the relationship between innate intelligence or talent, and greatness in terms of success or recognition. Dobbs contends that although some people are inherently smarter or more talented than other people, their gifts do not guarantee their greatness in terms of success. Furthermore, people who achieve greatness are not necessarily more gifted than usual. Dobbs argues that greatness is achieved by fervent and lengthy hard work, and is not dependant on a person's inherent traits. Hofstadter strikes back, presenting his personal observations and experiences as counterexamples to Dobbs' viewpoint. Hofstadter asserts that hard work alone can not achieve greatness; it is necessary to also be specially gifted.
The following is a report I wrote for my Artificial Intelligence course in September 2006. It discusses Pat Langley's article entitled "Cognitive Architectures and General Intelligent Systems."

In his article, Langley claims that artificial intelligence is a fragmented field that has lost sight of its original goal: to create general intelligent systems. Such a system would resemble humans in their ability to reason and make intelligent decisions, and be applicable in various environments. But because of the difficulty in designing such a system, much of the artificial intelligence field has become focused on much more specific tasks, such as computational linguistics or computer vision. Langley asserts that more attention should be refocused on the development of general intelligent systems.

There are three primary paradigms that attempt to achieve general intelligent systems: multi-agent systems, blackboard systems, and cognitive architecture. Multi-user agent systems resemble object-orientated programming; each agent has a role and defined interfaces for communicating with other agents, much like objects in a programming language like Java. The next paradigm, the blackboard system, is similar to multi-user systems in that modular agents are used. However, they communicate indirectly via a shared resource, which makes the agents less directly dependent upon each other. Because it allows for greater flexibility than a multi-user agent system, the blackboard system is thought to be more similar to cognitive thought.