//File clustering.aspx.cs
using System;
using System.Text;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using Microsoft.AnalysisServices.AdomdClient;
public partial class Clustering : System.Web.UI.Page {
//Array of points to be analyzed
List<ClusterPoint> points = new List<ClusterPoint>();
double NoiseDensity = Common.BaseNoiseDensity;
const int MAXCLUSTER = 20;
Color[] colors = {Color.Blue, Color.Green, Color.Red, Color.Chocolate, Color.Purple,
Color.Yellow, Color.Maroon, Color.Chartreuse, Color.Aqua, Color.Bisque,
Color.Fuchsia, Color.Coral, Color.Black, Color.Sienna, Color.Orange,
Color.Indigo, Color.DarkBlue, Color.DarkGray, Color.CornflowerBlue, Color.Turquoise };
double[,] rgbMatrix = new double[3, MAXCLUSTER];
//all the parameters for the clustering algorithm string clusteringAlg;
string targetClusterNum;
string clusterSeed;
string minSupport;
string modelingCard;
string sampleSize;
string stopTolerance;
int clusterShading;
bool drawEllipses;
static string DMConnectionString = "DM Connection String";
private void GetClusteringParameters() {
clusteringAlg = Request.Params["clusteringAlg"].ToString();
targetClusterNum = Request.Params["targetClusterNum"].ToString();
clusterSeed = Request.Params["clusterSeed"].ToString();
minSupport = Request.Params["minSupport"].ToString();
modelingCard = Request.Params["modelingCard"].ToString();
sampleSize = Request.Params["sampleSize"].ToString();
stopTolerance = Request.Params["stopTolerance"].ToString();
clusterShading =
Convert.ToInt32(Request.Params["clusterShading"].ToString());
drawEllipses =
Convert.ToBoolean(Request.Params["drawEllipses"].ToString());
}
protected void Page_Load(object sender, EventArgs e) {
int i;
float factor = Common.ShadingFactor;
try {
int clusterNumber =
Convert.ToInt32(Request.Params["ellipseNumber"].ToString());
List<Cluster> clusters = new List<Cluster>();
Rectangle clustersBoundary = new Rectangle();
NoiseDensity = Common.BaseNoiseDensity *
Convert.ToDouble(Request.Params["noiseLevel"].ToString());
GetClusteringParameters();
if (clusterShading == 2) {
factor = Common.ClusteringFactor;
}
// Since we are outputting a Jpeg, set the ContentType appropriately
Response.ContentType = "image/jpeg";
Bitmap objBitmap = new Bitmap(Common.TOTOALGRAPHICSWIDTH, Common.TOTOALGRAPHICSHEIGHT);
Graphics graphics = Graphics.FromImage(objBitmap);
graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, Common.TOTOALGRAPHICSWIDTH, Common.TOTOALGRAPHICSHEIGHT);
graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, Common.TOTOALGRAPHICSWIDTH, Common.TOTOALGRAPHICSHEIGHT);
Cluster theCluster = new Cluster();
for (i = 0; i < clusterNumber; i++) {
int location = i * Common.EllipseControlNumber;
Common.GetCluster(ref theCluster, i,
Request.Params[location + 1], Request.Params[location + 2],
Request.Params[location + 3], Request.Params[location + 4], Request.Params[location + 5],
Request.Params[location + 6]);
clusters.Add(theCluster);
}
Common.GetClustersBoundary(clusters, ref clustersBoundary);
//translate the graphics, so the data are always show on the left-top corner
graphics.TranslateTransform((float)(-1) * clustersBoundary.X, (float)(-1) * clustersBoundary.Y);
float scaleRatio = Common.GetScaleRatio(clustersBoundary);
if (scaleRatio != 1.0) {
graphics.ScaleTransform(scaleRatio, scaleRatio, MatrixOrder.Append);
}
//Generate all points
Common.GenerateAllPoints(ref points, clusters, NoiseDensity, clustersBoundary, Convert.ToInt32(clusterSeed));
// Create a table containing the training points System.Data.DataTable tbl = new DataTable();
// Add columns to the table tbl.Columns.Add("X", typeof(int));
tbl.Columns.Add("Y", typeof(int));
// Populate the table from the points object[] dataRow = new object[2];
for (i = 0; i < points.Count; i++) {
dataRow[0] = points[i].X;
dataRow[1] = points[i].Y;
tbl.Rows.Add(dataRow);
}
//Create the table containing data points used to color clusters
System.Data.DataTable tblColor = new DataTable();
tblColor.Columns.Add("X", typeof(int));
tblColor.Columns.Add("Y", typeof(int));
for (float x1 = (float)clustersBoundary.X; x1 <
(float)(clustersBoundary.X + clustersBoundary.Width);
x1 += factor)
for (float y1 = (float)clustersBoundary.Y; y1 <
(float)(clustersBoundary.Y + clustersBoundary.Height);
y1 += factor) {
dataRow[0] = x1;
dataRow[1] = y1;
tblColor.Rows.Add(dataRow);
}
Pen pen = null;
int clustersFound = 0;
//Traing clustering model now AdomdConnection conn = null;
bool HasDMError = false;
try {
// Connect
conn = new AdomdConnection();
// Get the connectionStrings.
ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings;
if (connectionStrings[DMConnectionString] != null) {
conn.ConnectionString =
connectionStrings[DMConnectionString].ConnectionString;
} else {
conn.ConnectionString = string.Format("Data Source=localhost");
}
conn.Open();
string modelName = "A" + conn.SessionID;
StringBuilder modelNameBuffer = new StringBuilder(modelName);
modelNameBuffer.Replace('-', '_');
modelName = modelNameBuffer.ToString();
using (AdomdCommand cmd = new AdomdCommand()) {
cmd.Connection = conn;
cmd.CommandText = "CREATE SESSION MINING MODEL " + modelName +
" ( K LONG KEY, " +
" X LONG CONTINUOUS, " + " Y LONG CONTINUOUS" +
") USING Microsoft_Clustering(CLUSTER_COUNT=" + targetClusterNum +
", CLUSTERING_METHOD=" + clusteringAlg + ", CLUSTER_SEED=" + clusterSeed +
", MINIMUM_SUPPORT=" + minSupport +
", MODELLING_CARDINALITY=" + modelingCard + ", SAMPLE_SIZE=" + sampleSize + ",
STOPPING_TOLERANCE=" + stopTolerance + ")";
cmd.ExecuteNonQuery();
// Train Model
cmd.CommandText = "INSERT INTO " + modelName + "(X, Y)
@inputRowset";
cmd.Parameters.Add(new AdomdParameter("inputRowset", tbl));
cmd.ExecuteNonQuery();
//Get the cluster number
cmd.CommandText = "Select [CHILDREN_CARDINALITY] from
" + modelName
+ ".Content where Node_Type=1";
AdomdDataReader rdr = cmd.ExecuteReader();
if (rdr.Read()) {
clustersFound = rdr.GetInt32(0);
}
rdr.Close();
int x, y;
System.Collections.Hashtable h = new System.Collections.Hashtable();
for (i = 0; i < clustersFound; i++) {
h.Add("Cluster " + (i+1).ToString(), i % MAXCLUSTER);
}
if ((clusterShading == 0) || (clusterShading == 1)) {
cmd.CommandText = "SELECT T.x, T.y, PredictHistogram( Cluster() ), PredictCaseLikelihood() from " +
modelName + " NATURAL PREDICTION JOIN @inputRowset AS T";
cmd.Parameters.Add(new AdomdParameter("inputRowset", tblColor));
rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess);
Common.GetColorMatrix(colors, ref rgbMatrix);
int n = 0;
while (rdr.Read()) {
n++;
x = rdr.GetInt32(0);
y = rdr.GetInt32(1);
double[] hist = new double[clustersFound];
int nIndex = 0;
for (nIndex = 0; nIndex < clustersFound;
nIndex++)
{
hist[nIndex] = 0.0;
}
AdomdDataReader nRdr = rdr.GetDataReader(2);
while (nRdr.Read()) {
string c = nRdr.GetString(0);
nIndex = (int)h[c];
hist[nIndex] = nRdr.GetDouble(2);
}
nRdr.Close();
double dLikelihood = rdr.GetDouble(3);
Brush b = null;
if (clusterShading == 0) {
b = new
SolidBrush(Common.GetColorWithLikelihood(hist, dLikelihood, rgbMatrix, clustersFound));
} else {
b = new SolidBrush(Common.GetColor(hist, rgbMatrix, clustersFound));
}
graphics.FillRectangle(b, x, y, factor, factor);
b.Dispose();
} } else {
//Get the clusters of the data points
cmd.CommandText = "SELECT T.X, T.Y, Cluster() FROM
" + modelName +
" NATURAL PREDICTION JOIN @inputRowset AS T ORDER BY Cluster()";
cmd.Parameters.Add(new AdomdParameter("inputRowset", tblColor));
rdr = cmd.ExecuteReader();
// Color clusters SolidBrush theBrush = null;
while (rdr.Read()) {
// read one prediction result, draw the point x = rdr.GetInt32(0);
y = rdr.GetInt32(1);
String clusterName = rdr.GetString(2);
theBrush = new SolidBrush(colors[(int)h[clusterName]]);
graphics.FillRectangle(theBrush, x, y, factor, factor);
theBrush.Dispose();
}
rdr.Close();
} }
conn.Close();
}
catch (System.Exception ex) {
HasDMError = true;
lblClusteringErrorMessage.Text = ex.Message;
lblClusteringErrorMessage.ForeColor = System.Drawing.Color.Red;
}
if (!HasDMError) {
//draw the ellipses if (drawEllipses) {
Common.DrawEllipses(clusters, graphics, false);
}
//Darw the legends
Common.DrawLegends(colors, clustersFound, clustersBoundary, graphics);
}
else {
Common.RenderDMError(graphics, lblClusteringErrorMessage.Text);
}
// Save the image to the OutputStream
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
// clean up...
if (pen != null) {
pen.Dispose();
}
graphics.Dispose();
objBitmap.Dispose();
}
catch (System.Exception ex) {
lblClusteringErrorMessage.Text = ex.Message;
lblClusteringErrorMessage.ForeColor = System.Drawing.Color.Red;
} } }