Cedar City Group

Saturday, January 24, 2009

Interpolate is available!

Several years ago, I worked for a company that sold some small hand held computers made by Sharp. They were pretty fascinating devices for the time. The PC-1262 was by far the most popular.

I wrote some small utilities for use by medical physicists and we sold quite a few of them. I had several ideas for products that would cater to engineers and scientists of all types, but we couldn't really get the ideas going into full fledged products.

David Hinson, is a friend of mine in Florida who is focused on iPhone development among other things. I ran an idea by him that I had way back when and in a matter of a few weeks, we have a product available for the iPhone called 'Interpolate'.

This application allows the user to store known data points for multiple datasets and then allows them to obtain values for unknown points. Believe it or not, there are people that need that sort of thing.

Here's a demo....



It is available on iTunes, buy it today!

Wednesday, January 14, 2009

Avoiding object aliasing....

Aliasing is a fancy term for referring to the same object by two different names. Sometimes it can be useful, most times it will causes some unintended consequences. As frameworks become more and more complex, with objects pointing to other objects (referred to as graphs) the potential for aliasing increases.

Sometimes, you want to create a totally new instance of an object graph, but programming something list this can be very tricky. Luckily, serialization gives us a very quick and easy way to perform a 'deep copy' of an object graph regardless of how complex it is.

Below is my DeepCopy class and its associated test...


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ccglib
{
public class DeepCopy<T>
{
// create a new graph with new instances of all objects
public static T Copy(T graph)
{
T newgraph;
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms,graph);
ms.Seek(0, SeekOrigin.Begin);
newgraph = (T)formatter.Deserialize(ms);
ms.Dispose();
return newgraph;
}
}
}

using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using ccglib;

namespace ccglibtests
{
[Serializable]
public class class1
{
public int x;
public int y;
public class2 z;
}

[Serializable]
public class class2
{
public int a;
public int b;
}

[TestFixture]
public class deepcopytest
{
[Test]
public void aliastest()
{
class1 obj1 = new class1();
class2 obj2 = new class2();
class1 alias;
class1 deepcopy;

// create a simple object graph
obj1.x = 1;
obj1.y = 2;
obj2.a = 3;
obj2.b = 4;
obj1.z = obj2;

alias = obj1;
deepcopy = DeepCopy.Copy(obj1);

alias.x = 10;
deepcopy.x = 100;
Assert.AreEqual(alias.x, obj1.x);
Assert.AreNotEqual(deepcopy.x, obj1.x);

alias.z.a = 40;
alias.z.a = 400;
deepcopy.z.a = 4000;

Assert.AreEqual(alias.z.a, obj1.z.a);
Assert.AreNotEqual(deepcopy.z.a, obj1.z.a);
}
}
}


Not to state the obvious, but all involved classes need to be serializable...

Abstraction...

One of the important basic principles of computer science is abstraction. Following is the text book definition....

abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.

Back in my college days, we studied this intently. The languages available at the time didn't support the concept as well as the languages do today. But we did the best we could using the languages that we had available.

One of my favorite courses was data structures, in that class we studied different ways to store data to achieve different goals. We studied, linked lists, stacks, queues and the like. We were given the opportunity to develop our own data structures based on the problem we were given.

The primary teaching language for teaching computer science at that time was Pascal, but we were exposed to many different languages. In my last semester, the teacher was pushing a class in the Ada language (a huge language developed by the DoD), on a whim I also took a class in an emerging language called C.

Although I've never heard of a job requesting experience in the Ada language, I'm grateful for the class. The Ada language was the first object oriented language we studied (this was 1986) and allowed advanced concepts like like operator overloading and generics. The Ada compilers were in beta testing at that time so actually developing a program in Ada was difficult, but the concepts were crucial.

Today, C# provides a lot of the same features that we studied back then, so I've taken a little bit of time to dig into generics. Generics are the ultimate level of abstraction because the algorithm is completely divorced from the data type. If you look at the concept of the simple List in System.Collections.Generic, you see what I mean. Even if you create your own class, you can easily create a type safe collection of them. If your class can be compared, the collection will even sort them for you. Very powerful if you ask me.

But simple collections are not the only application of generics, any data structure that you may want create can be created such that the data structure and its associated operations are completely divorced from the class that is stored in it.

I'm sure there are thousands of implementations of the mathematical concept of sets out there, but this was one of the first generic data structure that I decided to implement. Below is the code, the namespace is a reference to my roots in the Pascal language...

For definition of some of the basic mathematical concepts check out Set theory basic concepts


using System;
using System.Collections.Generic;
using System.Text;

namespace ccg.paslib
{
public class Set<T>
{
List<T> _internallist = new List<T>();


// add a member
public void Add(T parm)
{
_internallist.Add(parm);
}


// remove a member
public void Remove(T parm)
{
_internallist.Remove(parm);
}


// is the supplied value a member of this set?
public bool Contains(T parm)
{
return _internallist.Contains(parm);
}

// returns the Union of two sets
public Set<T> Union(Set<T> parm)
{
Set<T> retval = new Set<T>();
foreach (T val in _internallist)
retval.Add(val);
foreach (T val in parm)
if (!retval.Contains(val))
retval.Add(val);
return retval;
}


// returns the intersection of two sets
public Set<T> Intersection(Set<T> parm)
{
Set<T> retval = new Set<T>();
foreach (T val in _internallist)
if (parm.Contains(val))
retval.Add(val);
return retval;
}


// returns the difference between two sets
public Set<T> Difference(Set<T> parm)
{
Set<T> retval = new Set<T>();
foreach (T val in _internallist)
if (!parm.Contains(val))
retval.Add(val);
return retval;
}

// return members that are in one set but not both
public Set<T> ExclusiveOr(Set<T> parm)
{
Set<T> retval = new Set<T>();
foreach (T s in this)
if (!parm.Contains(s))
retval += s;
foreach (T s in parm)
if (!this.Contains(s))
retval += s;
return retval;
}


// return an enumerator for the set
public List<T>.Enumerator GetEnumerator()
{
return _internallist.GetEnumerator();
}


// return the number of members in the set
public int Count
{
get { return _internallist.Count; }
}

#region operators
public static Set<T> operator +(Set<T> set, T value)
{
set.Add(value);
return set;
}

public static Set<T> operator +(Set<T> set1, Set<T> set2)
{
return set1.Union(set2);
}

public static Set<T> operator -(Set<T> set1, Set<T> set2)
{
return set1.Difference(set2);
}

public static Set<T> operator *(Set<T> set1, Set<T> set2)
{
return set1.Intersection(set2);
}

public static Set<T> operator ^(Set<T> set1, Set<T> set2)
{
return set1.ExclusiveOr(set2);
}
#endregion

}


// generic class to create an ordered pair of objects for the Catesian Product
public class OrderedPair<T, S>
{
public T A;
public S B;
}


// Generic static class to implement the catesian product
public class CartesianProduct<T,S>
{
public static Set<OrderedPair<T,S>> Product(Set<T> a,Set<S> b)
{
Set<OrderedPair<T,S>> retval = new Set<OrderedPair<T,S>>();
foreach(T i in a)
foreach(S j in b)
{
OrderedPair<T,S> value = new OrderedPair<T,S>();
value.A = i;
value.B = j;
retval.Add(value);
}
return retval;
}
}

}



So, how can this be used? Does the mathematical concept of a set have anything to do with software development? Absolutely....at its core, a relational database is based on set theory. Below are some of the NUnit tests that I wrote for testing this class.


[Test]
public void uniontest()
{
Set<Color> set1 = new Set<Color>();
Set<Color> set2 = new Set<Color>();

set1.Add(Color.Red);
set1.Add(Color.Blue);
set2.Add(Color.Green);
set2.Add(Color.White);

Set set3 = set1.Union(set2);
Assert.AreEqual(set3.Count, 4);
foreach (Color val in set3)
Assert.IsTrue(set1.Contains(val) || set2.Contains(val));
}

[Test]
public void intersectiontest()
{
Set<Color> set1 = new Set<Color>();
Set<Color> set2 = new Set<Color>();

set1.Add(Color.Red);
set1.Add(Color.Blue);
set2.Add(Color.Blue);
set2.Add(Color.Green);
set2.Add(Color.White);

Set<Color> set3 = set1.Intersection(set2);
Assert.IsTrue(set3.Count == 1);
foreach (Color val in set3)
Assert.IsTrue(val.Equals(Color.Blue));
}

[Test]
// test some of the operators
public void exclusiveortest()
{
Set<Color> set1 = new Set<Color>();
Set<Color> set2 = new Set<Color>();

set1 += Color.Red;
set1 += Color.Blue;
set2 += Color.Blue;
set2 += Color.Green;
set2 += Color.White;

Set<Color> set3 = set1 ^ set2;
Assert.IsTrue(set3.Count == 3);
Assert.IsTrue(set3.Contains(Color.Red));
Assert.IsTrue(set3.Contains(Color.Green));
Assert.IsTrue(set3.Contains(Color.White));
}


The OrderedPair<T, S> and CartesianProduct<T,S> classes are pretty interesting. Below is a test that I wrote for that class.


[Test]
public void caresianproducttest()
{
Set<DateTime> set1 = new Set<DateTime>();
for (int i = 0; i < 10; i++)
set1.Add(new DateTime(2009, 1, 1).AddDays(i));

Set<Color> set2 = new Set<Color>();
set2.Add(Color.Blue);
set2.Add(Color.Red);
set2.Add(Color.Green);

Set<OrderedPair<DateTime, Color>> set3 = CartesianProduct<DateTime, Color>.Product(set1, set2);

Assert.AreEqual(set3.Count, set1.Count * set2.Count);
}


So, now what? Just like the List<T> generics, the Set<T> generic can be used with custom written classes. There is a caution here though. The default implementation of the Equals() method tests that the reference of two objects are equal. In other words, if you have two instances of a class that contain the same data, the default implementation of Equals() will return false because they are different instances. For the Set<T> generic to work as expected on custom classes, you must override the default implementation of Equals. Below is an example...


public class Customer
{
// public member variable violate the concept of abstraction,
// but this is just a test, not production code
public int ID;
public string Name;

public Customer(int id, string name)
{
ID = id;
Name = name;
}

public override bool Equals(object obj)
{
Customer objvalue = (Customer)obj;
return this.ID == objvalue.ID;
}

}

[Test]
public void CustomObjectTest()
{
Set<Customer> set1 = new Set<Customer>();
set1 += new Customer(1, "customer 1");
set1 += new Customer(2, "customer 2");
set1 += new Customer(3, "customer 3");

Set<Customer> set2 = new Set<Customer>();
set2 += new Customer(2, "customer 2");

// without overriding Equals() set3 contains all three members
Set<Customer> set3 = set1 - set2;
Assert.AreEqual(set3.Count, 2);
Assert.IsTrue(set3.Contains(new Customer(1,"customer 1")));
Assert.IsTrue(set3.Contains(new Customer(3,"customer 3")));
}


Combining custom objects with the concepts of Set Theory, allows some sophisticated operations to be performed using simple mathematical operators.

Tuesday, January 13, 2009

Geeks gone wild....

I have a friend named David Hinson who moved from the Nashville area to Florida some time last year. David and I worked together back when processor speeds were measured in mHz.

Anyway, Dave is seriously into developing applications for the iPhone and seemed to be searching for ideas for new applications. I ran an idea by him that I had thought of for years before never found a reasonable platform for developing it.

I sent Dave some code and he ran with it....this may be coming to iPhone app store soon.

If there were more than 6 people on the planet that would use something like this, we'd be rich.

Interpolate Demo

Thursday, January 8, 2009

New Resume....

This week, I spent a significant amount of time reformatting my resume. The previous format was confusing to some because the projects that I have completed were separated from the places I had worked. I did this in an effort to keep the resume short. This version provides a lot more detail and shows the projects that I have done in chronological order.

I am currently seeking new opportunities, if you are currently beginning new projects, or have any needs in the area of technology, I would appreciate your consideration.

Donnie

Sunday, January 4, 2009

A Time For Reflection (Factory Pattern in Action part 3)

For a preview of the application being discussed here please visit this page

The preceding portions of this series can be found here and here.

Setting properties on Factory Generated Objects
The grayscale and sepia objects were unique in that they do not require any parameters to operate. They know what they are supposed to do and can do it with no input provided by the controlling object. But, it should be obvious that to be useful, some objects will need to have some input provided. If the a factory returns only a base type, how can you set a property on a returned object without breaking the barrier of anonymity that the factory pattern provides?

Interfaces provide a possible solution, and possibly a better solution from a type safety perspective. However, in the interest of making the coupling as loose as possible, I have chosen to use reflection as the means of communicating with the object returned from the factory pattern.

For this portion, I selected to use a couple of filters that modify the colors in bitmap. The first filter can lighten or darken a photo using a gamma correction. The gamma value must be greater than 0. A gamma value of 1.0 leaves the image unchanged, values less than 1 lighten the images, values greater than 1.0 darken the image. Following is the code for my LightenDarken filter.

using System;
using System.Collections;
using System.Runtime.Serialization;
using System.Drawing.Imaging;
using System.Drawing;

namespace ccg.imaging
{
///
/// Performs a gamma correction on the processed image
///

///
[Serializable]
[NameAttribute("Ligthens or Darkens an image")]
[DescriptionAttribute("Adjusts the brightness of the entire image.")]
public class LightenDarken: ImageProcessBase
{
public LightenDarken()
{

}

public LightenDarken(float gamma)
{
_gamma = gamma;
}

float _gamma = 1.0f;

public float Gamma
{
set { _gamma = value; }
get { return _gamma; }
}

protected override System.Drawing.Bitmap ProcessSafe(System.Drawing.Bitmap bitmapin)
{
System.Drawing.Bitmap outmap = new System.Drawing.Bitmap(bitmapin.Width,bitmapin.Height);
Graphics g = Graphics.FromImage(outmap);
ImageAttributes ia = new ImageAttributes();
ia.SetGamma(_gamma);
g.DrawImage(bitmapin,new Rectangle(0,0,outmap.Width, outmap.Height),0,0,
bitmapin.Width,bitmapin.Height,GraphicsUnit.Pixel,ia);
g.Dispose();

return outmap;
}
}
}


The class allows the gamma value to be set in the constructor, but also allows it to be set as a property. Since the factory returns an ImageProcessBase type, the Gamma property is not available directly. The property could be set directly, but to do that, the controlling code would need to know the name of the class returned by the factory. In my opinion, this forces the controlling code to know too much about the underlying implementation of the filter. The most loosely couple approach is to set the property using reflection. The controlling code can retrieve the Type information from the class and use that to set the property using reflection.


ImageProcessBase proc = filterfactory.ActivateFilter("lightendarken");
Type t = proc.GetType();
object[] parms = { gamma }; // gamma declared and initialized earlier
t.InvokeMember("Gamma", System.Reflection.BindingFlags.SetProperty,
null, proc, parms);
output = proc.Process(output);


This approach has its downfalls, the main one being that if the property name is changed on the LightenDarken class, then the problem will show up at run time instead of compile time. However, this approach requires the least amount of information to be known be the controlling code. Casting or using interfaces requires the controlling code to know the name of the class or interface and the name of the property. Using reflection requires only the name of the property to be known. Since loose coupling is my primary design goal, this is the approach I selected.

The second filter uses the ColorMap property of the ImageAttributes class in the .NET framework to modify the colors in the bitmap. The ColorMap property of the ImageAttribute class allows you to specify a 'from' color and a 'to' color. When the bitmap is regenerated in the DrawImage call, this color mapping is used. My original intentions was to use it to reduce the number of shades of grey in an image my mapping multiple 'from' colors to the same 'to' color. However, I found it to be much more useful than just that. By supplying different ColorMaps, this filter can achieve some pretty cool effects. To make this simpler, I created an abstract class called ColorMapper. The only abstract method is the protected initializecolormap method.


using System;
using System.Drawing;
using System.Collections;
using System.Drawing.Imaging;

namespace ccg.imaging
{
///
/// This is an abstract class to allow the creation of multiple colormapping
/// classes
///

///
[NameAttribute("ColorMapper")]
[DescriptionAttribute("Maps Colors within a bitmap to different colors")]
[Serializable]
public abstract class ColorMapper: ImageProcessBase
{

#region Constructors
public ColorMapper()
{
}

#endregion

//--- create the color mapping
protected abstract ColorMap[] initializecolormap(Bitmap bitmapin);

///
/// process the incoming image to map colors to different colors
///

protected override System.Drawing.Bitmap ProcessSafe(System.Drawing.Bitmap
bitmapin)
{
ImageAttributes ia = new ImageAttributes();
ia.SetRemapTable(initializecolormap(bitmapin));
Bitmap outimg = new Bitmap(bitmapin.Width,bitmapin.Height);
Graphics g = Graphics.FromImage(outimg);
g.DrawImage(bitmapin, new Rectangle(0, 0, outimg.Width,
outimg.Height), 0, 0, bitmapin.Width, bitmapin.Height,
GraphicsUnit.Pixel, ia);
g.Dispose();
return outimg;
}
}
}


With this base class, we can easily produce a couple of color mapping effects. ShadeReducer maps multiple 'from' colors to the same 'to' color to reduce the number of shades in a grayscale bitmap. ColorShift uses the specified BaseColor as the color to shade rather than Black.


using System;
using System.Drawing;
using System.Collections;
using System.Drawing.Imaging;

namespace ccg.imaging
{
///
/// Summary description for ShadeReducer
///

///
[NameAttribute("Shade Reducer")]
[DescriptionAttribute("Reduces the image to the specified number of shades")]
[Serializable]
public class ShadeReducer: ColorMapper
{
//--- default number of shades of no value is provided
int _numberofshades = 255;

#region Constructors
public ShadeReducer()
{
}

public ShadeReducer(int numberofshades)
{
_numberofshades = numberofshades;
}
#endregion

///
/// Property to set the number of shades to use
///

public int NumberOfShades
{
get { return this._numberofshades; }
set { this._numberofshades = value; }
}

//--- create the color mapping
protected override ColorMap[] initializecolormap(Bitmap bitmapin)
{
ColorMap[] cmarray = new ColorMap[255];
int newvalue;
int shadeincrement = (255 / _numberofshades);
for (int i = 254; i >= 0; i--)
{
ColorMap cm = new ColorMap();
cm.OldColor = Color.FromArgb(i, i, i);
newvalue = 255-(shadeincrement * ((254-i) / shadeincrement));
cm.NewColor = Color.FromArgb(newvalue, newvalue, newvalue);
cmarray[i] = cm;
}
return cmarray;
}
}
}



using System;
using System.Drawing;
using System.Collections;
using System.Drawing.Imaging;

namespace ccg.imaging
{
///
/// Summary description for ShadeReducer
///

///
[NameAttribute("Color Shifter")]
[DescriptionAttribute("Converts a grayscale bitmap to shades of the specified Base Color")]
[Serializable]
public class ColorShifter: ColorMapper
{
Color _basecolor = Color.FromArgb(0x000000);

#region Constructors
public ColorShifter()
{
}
#endregion

public Color BaseColor
{
get { return _basecolor; }
set { _basecolor = value; }
}

///
/// This method produces as many shades of the basecolor as possible
/// The BaseColor will be the darkest color in the bitmap.
/// The method will produce as many shades as possible of the color
/// without changing it
///

private Color GetColorShade(Color colortoshade, int shadevalue)
{
int redvalue = colortoshade.R + shadevalue;
int greenvalue = colortoshade.G + shadevalue;
int bluevalue = colortoshade.B + shadevalue;

if (redvalue > 255)
{
greenvalue -= redvalue - 255;
bluevalue -= redvalue - 255;
redvalue = 255;
}

if (greenvalue > 255)
{
bluevalue -= greenvalue - 255;
redvalue -= greenvalue - 255;
greenvalue = 255;
}

if (bluevalue > 255)
{
redvalue -= bluevalue - 255;
greenvalue -= bluevalue - 255;
bluevalue = 255;
}
return Color.FromArgb(redvalue, greenvalue, bluevalue);
}

//--- create the color mapping
protected override ColorMap[] initializecolormap(Bitmap bitmapin)
{
ColorMap[] cmarray = new ColorMap[255];
int newvalue;
int shadeincrement = (255 / _numberofshades);
for (int i = 0; i < 255; i++)
{
ColorMap cm = new ColorMap();
cm.OldColor = Color.FromArgb(i, i, i);
cm.NewColor = GetColorShade(_basecolor, i);
cmarray[i] = cm;
}
return cmarray;
}
}
}


The controlling code can use reflection to set the NumberOfShades and BaseColor properties as needed.

The example of these filters in action is available at http://www.cedarcitygroup.com/digitaldarkroom/uncolormyworld.aspx. The .NET framework provides a tremendous amount of flexibility in processing images. Breaking different operations down into filters allows them to be mixed and matched into a processing pipeline that can be applied to a large number of images easily.

I hope that this series has been beneficial. Be on the lookout for an image processing utility for webmasters available here soon.

I just got my hands on some numerical analysis code that I wrote 20 years ago in Pascal. I'm dying to convert it to C#, there will be some posts about it soon as well.

Thursday, January 1, 2009

First attempt at flash training....

I put this flash movie together as a follow up to a post that I did on my personal blog. Like a lot of computer guys, I'm a frustrated musician. Flash is pretty cool because I can utilize my hobbies and profession into one medium. I used audactity to record and process the audio, Flash CS3 to put it all together. I learned a ton by doing it. I need to figure out the synchronization of audio and animation thing though. It's synchronized during development, but one seems to get ahead of the other after publishing. I'm going to figure that out...Any comments or tips are appreciated...